

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 将 DLAMI 与神经元一起使用 AWS
<a name="tutorial-inferentia-using"></a>

 Ne AWS uron SDK 的典型工作流程是在编译服务器上编译之前训练过的机器学习模型。之后，将构件分发给 Inf1 实例以供执行。 AWS Deep Learning AMIs (DLAMI) 预装了在使用 Inferentia 的 Inf1 实例中编译和运行推理所需的一切。

 以下部分说明如何将 DLAMI 与 Inferentia 结合使用。

**Topics**
+ [使用 TensorFlow-Neuron 和 Neuron 编译器 AWS](tutorial-inferentia-tf-neuron.md)
+ [使用 AWS 神经元服务 TensorFlow](tutorial-inferentia-tf-neuron-serving.md)
+ [使用 MXNet-Neuron 和 Neuron 编译器 AWS](tutorial-inferentia-mxnet-neuron.md)
+ [使用 MXNet神经元模型服务](tutorial-inferentia-mxnet-neuron-serving.md)
+ [使用 PyTorch-Neuron 和 Neuron 编译器 AWS](tutorial-inferentia-pytorch-neuron.md)

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

 本教程演示如何使用 Ne AWS uron 编译器编译 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>

 使用本教程之前，您应已完成 [启动带有神经元的 DLAMI 实例 AWS](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 ResNet 50 模型并将其导出为已保存的模型。

```
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 神经元服务 TensorFlow](tutorial-inferentia-tf-neuron-serving.md)

# 使用 AWS 神经元服务 TensorFlow
<a name="tutorial-inferentia-tf-neuron-serving"></a>

本教程展示了在导出保存的模型以用 AWS 于 Serving 之前，如何构造图形并添加 Neuron 编译步骤 TensorFlow 。 TensorFlow Serving 是一种服务系统，允许您在网络上扩大推理规模。Neuron S TensorFlow erving 使用与普通 TensorFlow 服务相同的 API。唯一的区别是，必须为 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>

使用本教程之前，您应已完成 [启动带有神经元的 DLAMI 实例 AWS](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 和 Neuron 编译器 AWS
<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>

 使用本教程之前，您应已完成 [启动带有神经元的 DLAMI 实例 AWS](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神经元模型服务](tutorial-inferentia-mxnet-neuron-serving.md)

# 使用 MXNet神经元模型服务
<a name="tutorial-inferentia-mxnet-neuron-serving"></a>

在本教程中，您将学习使用预训练的 MXNet 模型通过多模型服务器 (MMS) 执行实时图像分类。MMS 是一种灵活的 easy-to-use工具，用于提供使用任何机器学习或深度学习框架训练的深度学习模型。本教程包括使用 AWS Neuron 的编译步骤和使用 MMS 的实现。 MXNet

 有关 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-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>

 使用本教程之前，您应已完成 [启动带有神经元的 DLAMI 实例 AWS](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 脚本，其中包含以下内容。此脚本将 ResNet 50 模型编译为 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。 APIs

```
...
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 发出删除命令并使用以下命令停止模型服务器：

```
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 和 Neuron 编译器 AWS
<a name="tutorial-inferentia-pytorch-neuron"></a>

 PyTorch-Neuron 编译 API 提供了一种编译模型图的方法，您可以在 AWS Inferentia 设备上运行该模型。

经过训练的模型必须先编译为 Inferentia 目标，才能部署在 Inf1 实例上。以下教程编译 torchvision ResNet 50 模型并将其导出为已保存的模块。 TorchScript 此模型随后将用于运行推理。

为方便起见，本教程使用 Inf1 实例进行编译和推理。在实际操作中，您也可以使用其他实例类型来编译模型，例如 c5 实例系列。然后，您必须将已编译的模型部署到 Inf1 推理服务器中。有关更多信息，请参阅 Ne [AWS uron 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>

使用本教程之前，您应已完成 [启动带有神经元的 DLAMI 实例 AWS](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']
```