

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

# 使用 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)