

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 搭配 AWS Neuron 使用 DLAMI
<a name="tutorial-inferentia-using"></a>

 使用 AWS Neuron SDK 的典型工作流程是在編譯伺服器上編譯先前訓練的機器學習模型。之後，將成品分發至 Inf1 執行個體以執行。 AWS 深度學習 AMIs (DLAMI) 預先安裝了您在使用 Inferentia 的 Inf1 執行個體中編譯和執行推論所需的一切。

 下列各節說明如何搭配 Inferentia 使用 DLAMI。

**Topics**
+ [使用 TensorFlow-Neuron 和 AWS Neuron 編譯器](tutorial-inferentia-tf-neuron.md)
+ [使用 AWS Neuron TensorFlow 服務](tutorial-inferentia-tf-neuron-serving.md)
+ [使用 MXNet-Neuron 和 AWS Neuron 編譯器](tutorial-inferentia-mxnet-neuron.md)
+ [使用 MXNet-Neuron 模型服務](tutorial-inferentia-mxnet-neuron-serving.md)
+ [使用 PyTorch-Neuron 和 AWS Neuron 編譯器](tutorial-inferentia-pytorch-neuron.md)

# 使用 TensorFlow-Neuron 和 AWS Neuron 編譯器
<a name="tutorial-inferentia-tf-neuron"></a>

 本教學課程說明如何使用 AWS Neuron 編譯器編譯 Keras ResNet-50 模型，並以 SavedModel 格式將其匯出為儲存的模型。此格式是典型的 TensorFlow 模型可互換格式。您也會學習如何使用範例輸入在 Inf1 執行個體上執行推論。  

 如需 Neuron SDK 的詳細資訊，請參閱 [AWS Neuron SDK 文件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/tensorflow-neuron/index.html)。

**Topics**
+ [先決條件](#tutorial-inferentia-tf-neuron-prerequisites)
+ [啟動 Conda 環境](#tutorial-inferentia-tf-neuron-activate)
+ [Resnet50 編譯](#tutorial-inferentia-tf-neuron-compilation)
+ [ResNet50 推論](#tutorial-inferentia-tf-neuron-inference)

## 先決條件
<a name="tutorial-inferentia-tf-neuron-prerequisites"></a>

 在使用本教學課程之前，您應該已完成 [使用 AWS Neuron 啟動 DLAMI 執行個體](tutorial-inferentia-launching.md) 中的設置步驟。您也應該熟悉深度學習和使用 DLAMI。

## 啟動 Conda 環境
<a name="tutorial-inferentia-tf-neuron-activate"></a>

 使用以下命令啟用 TensorFlow-Neuron conda 環境：

```
source activate aws_neuron_tensorflow_p36
```

 若要結束目前的 conda 環境，請執行下列命令：

```
source deactivate
```

## Resnet50 編譯
<a name="tutorial-inferentia-tf-neuron-compilation"></a>

建立一個叫做 **tensorflow\$1compile\$1resnet50.py** 的 Python 指令碼，具有以下內容。這個 Python 指令碼會編譯 Keras ResNet50 模型，並將其匯出為儲存的模型。

```
import os
import time
import shutil
import tensorflow as tf
import tensorflow.neuron as tfn
import tensorflow.compat.v1.keras as keras
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet50 import preprocess_input

# Create a workspace
WORKSPACE = './ws_resnet50'
os.makedirs(WORKSPACE, exist_ok=True)

# Prepare export directory (old one removed)
model_dir = os.path.join(WORKSPACE, 'resnet50')
compiled_model_dir = os.path.join(WORKSPACE, 'resnet50_neuron')
shutil.rmtree(model_dir, ignore_errors=True)
shutil.rmtree(compiled_model_dir, ignore_errors=True)

# Instantiate Keras ResNet50 model
keras.backend.set_learning_phase(0)
model = ResNet50(weights='imagenet')

# Export SavedModel
tf.saved_model.simple_save(
 session            = keras.backend.get_session(),
 export_dir         = model_dir,
 inputs             = {'input': model.inputs[0]},
 outputs            = {'output': model.outputs[0]})

# Compile using Neuron
tfn.saved_model.compile(model_dir, compiled_model_dir)

# Prepare SavedModel for uploading to Inf1 instance
shutil.make_archive(compiled_model_dir, 'zip', WORKSPACE, 'resnet50_neuron')
```

 使用下列命令編譯模型：

```
python tensorflow_compile_resnet50.py
```

編譯程序需要幾分鐘的時間。完成時，您的輸出應如以下所示：

```
...
INFO:tensorflow:fusing subgraph neuron_op_d6f098c01c780733 with neuron-cc
INFO:tensorflow:Number of operations in TensorFlow session: 4638
INFO:tensorflow:Number of operations after tf.neuron optimizations: 556
INFO:tensorflow:Number of operations placed on Neuron runtime: 554
INFO:tensorflow:Successfully converted ./ws_resnet50/resnet50 to ./ws_resnet50/resnet50_neuron
...
```

 ​ 

 編譯之後，儲存的模型會在 **ws\$1resnet50/resnet50\$1neuron.zip** 被壓縮。使用下列命令將模型解壓縮，並下載推論範例影像：

```
unzip ws_resnet50/resnet50_neuron.zip -d .
curl -O https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg
```

## ResNet50 推論
<a name="tutorial-inferentia-tf-neuron-inference"></a>

建立一個叫做 **tensorflow\$1infer\$1resnet50.py** 的 Python 指令碼，具有以下內容。此指令碼使用先前編譯的推論模型，針對下載的模型執行推論。

```
import os
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications import resnet50

# Create input from image
img_sgl = image.load_img('kitten_small.jpg', target_size=(224, 224))
img_arr = image.img_to_array(img_sgl)
img_arr2 = np.expand_dims(img_arr, axis=0)
img_arr3 = resnet50.preprocess_input(img_arr2)
# Load model
COMPILED_MODEL_DIR = './ws_resnet50/resnet50_neuron/'
predictor_inferentia = tf.contrib.predictor.from_saved_model(COMPILED_MODEL_DIR)
# Run inference
model_feed_dict={'input': img_arr3}
infa_rslts = predictor_inferentia(model_feed_dict);
# Display results
print(resnet50.decode_predictions(infa_rslts["output"], top=5)[0])
```

 使用下列命令在模型上執行推論：

```
python tensorflow_infer_resnet50.py
```

 您的輸出看起來應如以下所示：

```
...
[('n02123045', 'tabby', 0.6918919), ('n02127052', 'lynx', 0.12770271), ('n02123159', 'tiger_cat', 0.08277027), ('n02124075', 'Egyptian_cat', 0.06418919), ('n02128757', 'snow_leopard', 0.009290541)]
```

**後續步驟**  
[使用 AWS Neuron TensorFlow 服務](tutorial-inferentia-tf-neuron-serving.md)

# 使用 AWS Neuron TensorFlow 服務
<a name="tutorial-inferentia-tf-neuron-serving"></a>

本教學課程示範如何在匯出儲存的模型以搭配 TensorFlow Serving 使用之前，建構圖形並新增 AWS Neuron 編譯步驟。TensorFlow 服務是一個服務系統，允許您跨網路擴展推斷。Neuron TensorFlow Serving 使用相同的 API 做為一般 TensorFlow Serving。唯一的差別是，必須為 AWS Inferentia 編譯儲存的模型，且進入點是名為 的不同二進位 `tensorflow_model_server_neuron`。二進位檔位於 `/usr/local/bin/tensorflow_model_server_neuron` ，並預先安裝在 DLAMI 中。

 如需 Neuron SDK 的詳細資訊，請參閱 [AWS Neuron SDK 文件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/tensorflow-neuron/index.html)。

**Topics**
+ [先決條件](#tutorial-inferentia-tf-neuron--serving-prerequisites)
+ [啟動 Conda 環境](#tutorial-inferentia-tf-neuron-serving-activate)
+ [編譯和匯出儲存的模型](#tutorial-inferentia-tf-neuron-serving-compile)
+ [為儲存的模型提供服務](#tutorial-inferentia-tf-neuron-serving-serving)
+ [向模型伺服器產生推論請求](#tutorial-inferentia-tf-neuron-serving-inference)

## 先決條件
<a name="tutorial-inferentia-tf-neuron--serving-prerequisites"></a>

在使用本教學課程之前，您應該已完成 [使用 AWS Neuron 啟動 DLAMI 執行個體](tutorial-inferentia-launching.md) 中的設置步驟。您也應該熟悉深度學習和使用 DLAMI。

## 啟動 Conda 環境
<a name="tutorial-inferentia-tf-neuron-serving-activate"></a>

 使用以下命令啟用 TensorFlow-Neuron conda 環境：

```
source activate aws_neuron_tensorflow_p36
```

 如果您需要退出目前的 conda 環境，請執行：

```
source deactivate
```

## 編譯和匯出儲存的模型
<a name="tutorial-inferentia-tf-neuron-serving-compile"></a>

使用下列內容建立名為 `tensorflow-model-server-compile.py` 的 Python 指令碼。 此指令碼建構圖形並使用 Neuron 編譯圖形。然後將編譯後的圖形匯出為儲存的模型。  

```
import tensorflow as tf
import tensorflow.neuron
import os

tf.keras.backend.set_learning_phase(0)
model = tf.keras.applications.ResNet50(weights='imagenet')
sess = tf.keras.backend.get_session()
inputs = {'input': model.inputs[0]}
outputs = {'output': model.outputs[0]}

# save the model using tf.saved_model.simple_save
modeldir = "./resnet50/1"
tf.saved_model.simple_save(sess, modeldir, inputs, outputs)

# compile the model for Inferentia
neuron_modeldir = os.path.join(os.path.expanduser('~'), 'resnet50_inf1', '1')
tf.neuron.saved_model.compile(modeldir, neuron_modeldir, batch_size=1)
```

 使用下列命令編譯模型：

```
python tensorflow-model-server-compile.py
```

 您的輸出看起來應如以下所示：

```
...
INFO:tensorflow:fusing subgraph neuron_op_d6f098c01c780733 with neuron-cc
INFO:tensorflow:Number of operations in TensorFlow session: 4638
INFO:tensorflow:Number of operations after tf.neuron optimizations: 556
INFO:tensorflow:Number of operations placed on Neuron runtime: 554
INFO:tensorflow:Successfully converted ./resnet50/1 to /home/ubuntu/resnet50_inf1/1
```

## 為儲存的模型提供服務
<a name="tutorial-inferentia-tf-neuron-serving-serving"></a>

一旦模型已編譯過，您可以使用以下命令，以 tensorflow\$1model\$1server\$1neuron 二進位檔案為儲存的模型提供服務：

```
tensorflow_model_server_neuron --model_name=resnet50_inf1 \
    --model_base_path=$HOME/resnet50_inf1/ --port=8500 &
```

 您的輸出看起來應該如下所示。編譯的模型 由伺服器在 Inferentia 裝置的 DRAM 中暫存，以準備推論。

```
...
2019-11-22 01:20:32.075856: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:311] SavedModel load for tags { serve }; Status: success. Took 40764 microseconds.
2019-11-22 01:20:32.075888: I tensorflow_serving/servables/tensorflow/saved_model_warmup.cc:105] No warmup data file found at /home/ubuntu/resnet50_inf1/1/assets.extra/tf_serving_warmup_requests
2019-11-22 01:20:32.075950: I tensorflow_serving/core/loader_harness.cc:87] Successfully loaded servable version {name: resnet50_inf1 version: 1}
2019-11-22 01:20:32.077859: I tensorflow_serving/model_servers/server.cc:353] Running gRPC ModelServer at 0.0.0.0:8500 ...
```

## 向模型伺服器產生推論請求
<a name="tutorial-inferentia-tf-neuron-serving-inference"></a>

建立一個叫做 `tensorflow-model-server-infer.py` 的 Python 指令碼，具有以下內容。此指令碼透過 gRPC (為一服務框架) 執行推斷。

```
import numpy as np
import grpc
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
from tensorflow.keras.applications.resnet50 import decode_predictions

if __name__ == '__main__':
    channel = grpc.insecure_channel('localhost:8500')
    stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)
    img_file = tf.keras.utils.get_file(
        "./kitten_small.jpg",
        "https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg")
    img = image.load_img(img_file, target_size=(224, 224))
    img_array = preprocess_input(image.img_to_array(img)[None, ...])
    request = predict_pb2.PredictRequest()
    request.model_spec.name = 'resnet50_inf1'
    request.inputs['input'].CopyFrom(
        tf.contrib.util.make_tensor_proto(img_array, shape=img_array.shape))
    result = stub.Predict(request)
    prediction = tf.make_ndarray(result.outputs['output'])
    print(decode_predictions(prediction))
```

 使用 gRPC，以下列命令在模型上執行推論：

```
python tensorflow-model-server-infer.py
```

 您的輸出看起來應如以下所示：

```
[[('n02123045', 'tabby', 0.6918919), ('n02127052', 'lynx', 0.12770271), ('n02123159', 'tiger_cat', 0.08277027), ('n02124075', 'Egyptian_cat', 0.06418919), ('n02128757', 'snow_leopard', 0.009290541)]]
```

# 使用 MXNet-Neuron 和 AWS Neuron 編譯器
<a name="tutorial-inferentia-mxnet-neuron"></a>

MXNet-Neuron 編譯 API 提供一種方法來編譯模型圖表，您可以在 AWS Inferentia 裝置上執行。

 在此範例中，您可以使用 API 來編譯 ResNet-50 模型，並使用它來執行推論。

 如需 Neuron SDK 的詳細資訊，請參閱 [AWS Neuron SDK 文件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/mxnet-neuron/index.html)。

**Topics**
+ [先決條件](#tutorial-inferentia-mxnet-neuron-prerequisites)
+ [啟動 Conda 環境](#tutorial-inferentia-mxnet-neuron-activate)
+ [Resnet50 編譯](#tutorial-inferentia-mxnet-neuron-compilation)
+ [ResNet50 推論](#tutorial-inferentia-mxnet-neuron-inference)

## 先決條件
<a name="tutorial-inferentia-mxnet-neuron-prerequisites"></a>

 在使用本教學課程之前，您應該已完成 [使用 AWS Neuron 啟動 DLAMI 執行個體](tutorial-inferentia-launching.md) 中的設置步驟。您也應該熟悉深度學習和使用 DLAMI。

## 啟動 Conda 環境
<a name="tutorial-inferentia-mxnet-neuron-activate"></a>

 使用以下命令啟動 MXNet-Neuron conda 環境：

```
source activate aws_neuron_mxnet_p36
```

若要退出目前的 conda 環境，請執行：

```
source deactivate
```

## Resnet50 編譯
<a name="tutorial-inferentia-mxnet-neuron-compilation"></a>

建立一個叫做 **mxnet\$1compile\$1resnet50.py** 的 Python 指令碼，具有以下內容。此指令碼使用 MXNet-Neuron 編譯 Python API 來編譯一個 ResNet-50 模型。

```
import mxnet as mx
import numpy as np

print("downloading...")
path='http://data.mxnet.io/models/imagenet/'
mx.test_utils.download(path+'resnet/50-layers/resnet-50-0000.params')
mx.test_utils.download(path+'resnet/50-layers/resnet-50-symbol.json')
print("download finished.")

sym, args, aux = mx.model.load_checkpoint('resnet-50', 0)

print("compile for inferentia using neuron... this will take a few minutes...")
inputs = { "data" : mx.nd.ones([1,3,224,224], name='data', dtype='float32') }

sym, args, aux = mx.contrib.neuron.compile(sym, args, aux, inputs)

print("save compiled model...")
mx.model.save_checkpoint("compiled_resnet50", 0, sym, args, aux)
```

 使用下列命令編譯模型：

```
python mxnet_compile_resnet50.py
```

 編譯需要幾分鐘的時間。編譯完成 時，下列檔案將位於您目前的目錄中：

```
resnet-50-0000.params
resnet-50-symbol.json
compiled_resnet50-0000.params
compiled_resnet50-symbol.json
```

## ResNet50 推論
<a name="tutorial-inferentia-mxnet-neuron-inference"></a>

建立一個叫做 **mxnet\$1infer\$1resnet50.py** 的 Python 指令碼，具有以下內容。此指令碼會下載範例影像，並使用它來執行具有已編譯模型的推論。

```
import mxnet as mx
import numpy as np

path='http://data.mxnet.io/models/imagenet/'
mx.test_utils.download(path+'synset.txt')

fname = mx.test_utils.download('https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg')
img = mx.image.imread(fname)

# convert into format (batch, RGB, width, height)
img = mx.image.imresize(img, 224, 224) 
# resize
img = img.transpose((2, 0, 1)) 
# Channel first
img = img.expand_dims(axis=0) 
# batchify
img = img.astype(dtype='float32')

sym, args, aux = mx.model.load_checkpoint('compiled_resnet50', 0)
softmax = mx.nd.random_normal(shape=(1,))
args['softmax_label'] = softmax
args['data'] = img
# Inferentia context
ctx = mx.neuron()

exe = sym.bind(ctx=ctx, args=args, aux_states=aux, grad_req='null')
with open('synset.txt', 'r') as f:
    labels = [l.rstrip() for l in f]

exe.forward(data=img)
prob = exe.outputs[0].asnumpy()
# print the top-5
prob = np.squeeze(prob)
a = np.argsort(prob)[::-1] 
for i in a[0:5]:
    print('probability=%f, class=%s' %(prob[i], labels[i]))
```

 使用以下命令，以編譯模型執行推斷：

```
python mxnet_infer_resnet50.py
```

 您的輸出看起來應如以下所示：

```
probability=0.642454, class=n02123045 tabby, tabby cat
probability=0.189407, class=n02123159 tiger cat
probability=0.100798, class=n02124075 Egyptian cat
probability=0.030649, class=n02127052 lynx, catamount
probability=0.016278, class=n02129604 tiger, Panthera tigris
```

**後續步驟**  
[使用 MXNet-Neuron 模型服務](tutorial-inferentia-mxnet-neuron-serving.md)

# 使用 MXNet-Neuron 模型服務
<a name="tutorial-inferentia-mxnet-neuron-serving"></a>

在本教學課程中，您將學習如何使用預先培訓的 MXNet 模型來執行多模型伺服器 (MMS) 的即時影像分類。MMS 是一種靈活且易於使用的工具，可提供使用任何機器學習或深度學習架構培訓的深度學習模型。本教學課程包含使用 AWS Neuron 的編譯步驟，以及使用 MXNet 的 MMS 實作。

 如需 Neuron 開發套件的詳細資訊，請參閱 [AWS Neuron 開發套件文件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/mxnet-neuron/index.html)。

**Topics**
+ [先決條件](#tutorial-inferentia-mxnet-neuron-serving-prerequisites)
+ [啟動 Conda 環境](#tutorial-inferentia-mxnet-neuron-serving-activate)
+ [下載範例程式碼](#tutorial-inferentia-mxnet-neuron-serving-download)
+ [編譯模型](#tutorial-inferentia-mxnet-neuron-serving-compile)
+ [執行推論](#tutorial-inferentia-mxnet-neuron-serving-inference)

## 先決條件
<a name="tutorial-inferentia-mxnet-neuron-serving-prerequisites"></a>

 在使用本教學課程之前，您應該已完成 [使用 AWS Neuron 啟動 DLAMI 執行個體](tutorial-inferentia-launching.md) 中的設置步驟。您也應該熟悉深度學習和使用 DLAMI。

## 啟動 Conda 環境
<a name="tutorial-inferentia-mxnet-neuron-serving-activate"></a>

 使用以下命令啟動 MXNet-Neuron conda 環境：

```
source activate aws_neuron_mxnet_p36
```

 若要退出目前的 conda 環境，請執行：

```
source deactivate
```

## 下載範例程式碼
<a name="tutorial-inferentia-mxnet-neuron-serving-download"></a>

 若要執行此範例，請使用下列命令下載範例程式碼：

```
git clone https://github.com/awslabs/multi-model-server
cd multi-model-server/examples/mxnet_vision
```

## 編譯模型
<a name="tutorial-inferentia-mxnet-neuron-serving-compile"></a>

建立一個叫做 `multi-model-server-compile.py` 的 Python 指令碼，具有以下內容。此指令碼會將 ResNet50 模型編譯至 Inferentia 裝置目標。

```
import mxnet as mx
from mxnet.contrib import neuron
import numpy as np

path='http://data.mxnet.io/models/imagenet/'
mx.test_utils.download(path+'resnet/50-layers/resnet-50-0000.params')
mx.test_utils.download(path+'resnet/50-layers/resnet-50-symbol.json')
mx.test_utils.download(path+'synset.txt')

nn_name = "resnet-50"

#Load a model
sym, args, auxs = mx.model.load_checkpoint(nn_name, 0)

#Define compilation parameters#  - input shape and dtype
inputs = {'data' : mx.nd.zeros([1,3,224,224], dtype='float32') }

# compile graph to inferentia target
csym, cargs, cauxs = neuron.compile(sym, args, auxs, inputs)

# save compiled model
mx.model.save_checkpoint(nn_name + "_compiled", 0, csym, cargs, cauxs)
```

 若要編譯模型，請使用下列命令：

```
python multi-model-server-compile.py
```

 您的輸出看起來應如以下所示：

```
...
[21:18:40] src/nnvm/legacy_json_util.cc:209: Loading symbol saved by previous version v0.8.0. Attempting to upgrade...
[21:18:40] src/nnvm/legacy_json_util.cc:217: Symbol successfully upgraded!
[21:19:00] src/operator/subgraph/build_subgraph.cc:698: start to execute partition graph.
[21:19:00] src/nnvm/legacy_json_util.cc:209: Loading symbol saved by previous version v0.8.0. Attempting to upgrade...
[21:19:00] src/nnvm/legacy_json_util.cc:217: Symbol successfully upgraded!
```

 建立一個叫做 `signature.json` 的檔案，具有以下內容，以設定輸入名稱和形狀：

```
{
  "inputs": [
    {
      "data_name": "data",
      "data_shape": [
        1,
        3,
        224,
        224
      ]
    }
  ]
}
```

您可以使用下列命令來下載 `synset.txt` 檔案。這個檔案是 ImageNet 預測類別的名稱清單。

```
curl -O https://s3.amazonaws.com/model-server/model_archive_1.0/examples/squeezenet_v1.1/synset.txt
```

按照 `model_server_template` 資料夾中的範本建立自訂服務類別。使用下列命令將範本複製到目前的工作目錄：

```
cp -r ../model_service_template/* .
```

 編輯 `mxnet_model_service.py` 模組，將 `mx.cpu()` 內容取代為 `mx.neuron()` 內容，如下所示。您還需要將 `model_input` 所使用、不必要的資料副本註釋掉，因為 MXNet-Neuron 不支援 NDArray 和 Gluon API。

```
...
self.mxnet_ctx = mx.neuron() if gpu_id is None else mx.gpu(gpu_id)
...
#model_input = [item.as_in_context(self.mxnet_ctx) for item in model_input]
```

 使用下列指令，以模型歸檔程式封裝模型：

```
cd ~/multi-model-server/examples
model-archiver --force --model-name resnet-50_compiled --model-path mxnet_vision --handler mxnet_vision_service:handle
```

## 執行推論
<a name="tutorial-inferentia-mxnet-neuron-serving-inference"></a>

啟動多模型伺服器，並使用下列命令載入使用 RESTful API 的模型。請確認 **neuron-rtd** 是以預設設定執行。

```
cd ~/multi-model-server/
multi-model-server --start --model-store examples > /dev/null # Pipe to log file if you want to keep a log of MMS
curl -v -X POST "http://localhost:8081/models?initial_workers=1&max_workers=4&synchronous=true&url=resnet-50_compiled.mar"
sleep 10 # allow sufficient time to load model
```

 以下列命令使用範例影像執行推論：

```
curl -O https://raw.githubusercontent.com/awslabs/multi-model-server/master/docs/images/kitten_small.jpg
curl -X POST http://127.0.0.1:8080/predictions/resnet-50_compiled -T kitten_small.jpg
```

 您的輸出看起來應如以下所示：

```
[
  {
    "probability": 0.6388034820556641,
    "class": "n02123045 tabby, tabby cat"
  },
  {
    "probability": 0.16900072991847992,
    "class": "n02123159 tiger cat"
  },
  {
    "probability": 0.12221276015043259,
    "class": "n02124075 Egyptian cat"
  },
  {
    "probability": 0.028706775978207588,
    "class": "n02127052 lynx, catamount"
  },
  {
    "probability": 0.01915954425930977,
    "class": "n02129604 tiger, Panthera tigris"
  }
]
```

 若要在測試之後進行清理，請透過 RESTful API 發出 delete 命令，並使用以下命令停止模型伺服器：

```
curl -X DELETE http://127.0.0.1:8081/models/resnet-50_compiled

multi-model-server --stop
```

 您應該會看到下列輸出：

```
{
  "status": "Model \"resnet-50_compiled\" unregistered"
}
Model server stopped.
Found 1 models and 1 NCGs.
Unloading 10001 (MODEL_STATUS_STARTED) :: success
Destroying NCG 1 :: success
```

# 使用 PyTorch-Neuron 和 AWS Neuron 編譯器
<a name="tutorial-inferentia-pytorch-neuron"></a>

PyTorch-Neuron 編譯 API 提供一種方法來編譯模型圖表，您可以在 AWS Inferentia 裝置上執行。

經過訓練的模型必須編譯至 Inferentia 目標，才能部署到 Inf1 執行個體上。下列教學課程編譯了 torchvision ResNet50 模型，並將其匯出為儲存的 TorchScript 模組。接著，即可使用此模型執行推論。

為了方便起見，本教學課程使用 Inf1 執行個體進行編譯和推論。實際上，您可以使用 c5 執行個體系列等其他執行個體類型來編譯模型。接著，您必須將已編譯的模型部署到 Inf1 推論伺服器。如需詳細資訊，請參閱 [AWS Neuron PyTorch SDK 文件](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-frameworks/pytorch-neuron/index.html)。

**Topics**
+ [先決條件](#tutorial-inferentia-pytorch-neuron-prerequisites)
+ [啟動 Conda 環境](#tutorial-inferentia-pytorch-neuron-activate)
+ [Resnet50 編譯](#tutorial-inferentia-pytorch-neuron-compilation)
+ [ResNet50 推論](#tutorial-inferentia-pytorch-neuron-inference)

## 先決條件
<a name="tutorial-inferentia-pytorch-neuron-prerequisites"></a>

在使用本教學課程之前，您應該已完成 [使用 AWS Neuron 啟動 DLAMI 執行個體](tutorial-inferentia-launching.md) 中的設置步驟。您也應該熟悉深度學習和使用 DLAMI。

## 啟動 Conda 環境
<a name="tutorial-inferentia-pytorch-neuron-activate"></a>

使用以下命令啟動 PyTorch-Neuron conda 環境：

```
source activate aws_neuron_pytorch_p36
```

若要退出目前的 conda 環境，請執行：

```
source deactivate
```

## Resnet50 編譯
<a name="tutorial-inferentia-pytorch-neuron-compilation"></a>

建立一個叫做 **pytorch\$1trace\$1resnet50.py** 的 Python 指令碼，具有以下內容。此指令碼使用 PyTorch-Neuron 編譯 Python API 來編譯一個 ResNet-50 模型。

**注意**  
在編譯 torchvision 模型時，您應該注意的 torchvision 版本與 torch 套件之間存在相依性。這些相依性規則可以透過 pip 管理。Torchvision==0.6.1 符合 torch==1.5.1 版本，而 torchvision=0.8.2 符合 torch==1.7.1 版本。

```
import torch
import numpy as np
import os
import torch_neuron
from torchvision import models

image = torch.zeros([1, 3, 224, 224], dtype=torch.float32)

## Load a pretrained ResNet50 model
model = models.resnet50(pretrained=True)

## Tell the model we are using it for evaluation (not training)
model.eval()
model_neuron = torch.neuron.trace(model, example_inputs=[image])

## Export to saved model
model_neuron.save("resnet50_neuron.pt")
```

執行編譯指令碼。

```
python pytorch_trace_resnet50.py
```

編譯需要幾分鐘的時間。 編譯完成後，編譯的模型會儲存為本機目錄中`resnet50_neuron.pt`的 。

## ResNet50 推論
<a name="tutorial-inferentia-pytorch-neuron-inference"></a>

建立一個叫做 **pytorch\$1infer\$1resnet50.py** 的 Python 指令碼，具有以下內容。此指令碼會下載範例影像，並使用它來執行具有已編譯模型的推論。

```
import os
import time
import torch
import torch_neuron
import json
import numpy as np

from urllib import request

from torchvision import models, transforms, datasets

## Create an image directory containing a small kitten
os.makedirs("./torch_neuron_test/images", exist_ok=True)
request.urlretrieve("https://raw.githubusercontent.com/awslabs/mxnet-model-server/master/docs/images/kitten_small.jpg",
                    "./torch_neuron_test/images/kitten_small.jpg")


## Fetch labels to output the top classifications
request.urlretrieve("https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json","imagenet_class_index.json")
idx2label = []

with open("imagenet_class_index.json", "r") as read_file:
    class_idx = json.load(read_file)
    idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))]

## Import a sample image and normalize it into a tensor
normalize = transforms.Normalize(
    mean=[0.485, 0.456, 0.406],
    std=[0.229, 0.224, 0.225])

eval_dataset = datasets.ImageFolder(
    os.path.dirname("./torch_neuron_test/"),
    transforms.Compose([
    transforms.Resize([224, 224]),
    transforms.ToTensor(),
    normalize,
    ])
)

image, _ = eval_dataset[0]
image = torch.tensor(image.numpy()[np.newaxis, ...])

## Load model
model_neuron = torch.jit.load( 'resnet50_neuron.pt' )

## Predict
results = model_neuron( image )

# Get the top 5 results
top5_idx = results[0].sort()[1][-5:]

# Lookup and print the top 5 labels
top5_labels = [idx2label[idx] for idx in top5_idx]

print("Top 5 labels:\n {}".format(top5_labels) )
```

使用以下命令，以編譯模型執行推斷：

```
python pytorch_infer_resnet50.py
```

您的輸出看起來應如以下所示：

```
Top 5 labels:
 ['tiger', 'lynx', 'tiger_cat', 'Egyptian_cat', 'tabby']
```