

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# DLAMI を使用した AWS Inferentia チップ
<a name="tutorial-inferentia"></a>

AWS Inferentia は、 によって設計されたカスタム機械学習チップ AWS で、高性能な推論予測に使用できます。このチップを使用するには、Amazon Elastic Compute Cloud インスタンスをセットアップし、 AWS Neuron Software Development Kit (SDK) を使用して Inferentia チップを呼び出します。お客様に最高の Inferentia エクスペリエンスを提供するために、Neuron が AWS Deep Learning AMIs (DLAMI) に組み込まれています。

以下のトピックでは、Inferentia と DLAMI の使用を開始する方法について説明します。

**Topics**
+ [AWS Neuron を使用した DLAMI インスタンスの起動](tutorial-inferentia-launching.md)
+ [AWS Neuron での DLAMI の使用](tutorial-inferentia-using.md)

# AWS Neuron を使用した DLAMI インスタンスの起動
<a name="tutorial-inferentia-launching"></a>

 最新の DLAMI は Inferentia AWS で使用できるようになり、 AWS Neuron API パッケージが付属しています。DLAMI インスタンスを起動するには、[DLAMI の起動と設定](https://docs.aws.amazon.com/dlami/latest/devguide/launch-config.html)を参照してください。DLAMI を作成したら、以下のステップを使用して、 AWS Inferentia チップと AWS Neuron リソースがアクティブであることを確認します。

**Topics**
+ [インスタンスの確認](#tutorial-inferentia-launching-verify)
+ [AWS Inferentia デバイスの識別](#tutorial-inferentia-launching-identify)
+ [リソースの使用状況の表示](#tutorial-inferentia-launching-resource-usage)
+ [Neuron Monitor (neuron-monitor) の使用](#tutorial-inferentia-launching-neuron-monitor)
+ [Neuron ソフトウェアのアップグレード](#tutorial-inferentia-launching-upgrade)

## インスタンスの確認
<a name="tutorial-inferentia-launching-verify"></a>

 インスタンスを使用する前に、インスタンスが正しくセットアップされ、Neuron で設定されていることを確認します。

## AWS Inferentia デバイスの識別
<a name="tutorial-inferentia-launching-identify"></a>

 インスタンス上の Inferentia デバイスの数を確認するには、次のコマンドを使用します。

```
neuron-ls
```

 インスタンスに Inferentia デバイスがアタッチされている場合、出力は次のようになります。

```
+--------+--------+--------+-----------+--------------+
| NEURON | NEURON | NEURON | CONNECTED |     PCI      |
| DEVICE | CORES  | MEMORY |  DEVICES  |     BDF      |
+--------+--------+--------+-----------+--------------+
| 0      | 4      | 8 GB   | 1         | 0000:00:1c.0 |
| 1      | 4      | 8 GB   | 2, 0      | 0000:00:1d.0 |
| 2      | 4      | 8 GB   | 3, 1      | 0000:00:1e.0 |
| 3      | 4      | 8 GB   | 2         | 0000:00:1f.0 |
+--------+--------+--------+-----------+--------------+
```

 示されている出力は Inf1.6xLarge インスタンスから取得されたものであり、次の列が含まれています。
+ NEURON DEVICE: NeuronDevice に割り当てられた論理 ID。この ID は、異なる NeuronDevice を使用するように複数のランタイムを設定する場合に使用されます。
+ NEURON CORES: NeuronDevice に存在する NeuronCore の数。
+ NEURON MEMORY: NeuronDevice 内の DRAM メモリの量。
+ CONNECTED DEVICES: NeuronDevice に接続されている他の NeuronDevice。
+ PCI BDF: NeuronDevice の PCI バスデバイス機能 (BDF) ID。

## リソースの使用状況の表示
<a name="tutorial-inferentia-launching-resource-usage"></a>

 `neuron-top` コマンドを使用して、NeuronCore と vCPU の使用率、メモリ使用率、ロードされたモデル、Neuron アプリケーションに関する有用な情報を表示します。引数を指定せずに `neuron-top` を起動すると、NeuronCore を使用するすべての機械学習アプリケーションのデータが表示されます。

```
neuron-top
```

 アプリケーションが 4 つの NeuronCore を使用している場合、出力は以下の画像のようになります。

![\[neuron-top コマンドの出力。4 つの NeuronCore のうちの 1 つの情報が強調表示されています。\]](http://docs.aws.amazon.com/ja_jp/dlami/latest/devguide/images/neuron-top-output.png)


Neuron ベースの推論アプリケーションを監視および最適化するためのリソースの詳細については、[Neuron Tools](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-tools/index.html) を参照してください。

## Neuron Monitor (neuron-monitor) の使用
<a name="tutorial-inferentia-launching-neuron-monitor"></a>

Neuron Monitor は、システムで実行されている Neuron ランタイムからメトリクスを収集し、収集したデータを JSON 形式で標準出力にストリーミングします。これらのメトリクスは、設定ファイルを指定して設定するメトリクスグループに編成されます。Neuron Monitor の詳細については、[Neuron Monitor User Guide](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-tools/neuron-monitor-user-guide.html) を参照してください。

## Neuron ソフトウェアのアップグレード
<a name="tutorial-inferentia-launching-upgrade"></a>

DLAMI 内で Neuron SDK ソフトウェアを更新する方法については、 AWS 「 Neuron [セットアップガイド](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-intro/neuron-install-guide.html)」を参照してください。

**次のステップ**  
[AWS Neuron での DLAMI の使用](tutorial-inferentia-using.md)

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

 AWS Neuron SDK の一般的なワークフローは、以前にトレーニングされた機械学習モデルをコンパイルサーバーでコンパイルすることです。その後、実行のためにアーティファクトを Inf1 インスタンスに配布します。 AWS Deep Learning AMIs (DLAMI) には、Inferentia を使用する Inf1 インスタンスで推論をコンパイルして実行するために必要なものがすべてプリインストールされています。

 以下のセクションでは、Inferentia とともに DLAMI を使用する方法について説明します。

**Topics**
+ [TensorFlow-Neuron と AWS Neuron Compiler の使用](tutorial-inferentia-tf-neuron.md)
+ [AWS Neuron TensorFlow Serving の使用](tutorial-inferentia-tf-neuron-serving.md)
+ [MXNet-Neuron と AWS Neuron Compiler の使用](tutorial-inferentia-mxnet-neuron.md)
+ [MXNet-Neuron モデルサービングの使用](tutorial-inferentia-mxnet-neuron-serving.md)
+ [PyTorch-Neuron と AWS Neuron Compiler の使用](tutorial-inferentia-pytorch-neuron.md)

# TensorFlow-Neuron と AWS Neuron Compiler の使用
<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 Serving の使用](tutorial-inferentia-tf-neuron-serving.md)

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

このチュートリアルでは、TensorFlow Serving で使用する保存済みモデルをエクスポートする前に、グラフを作成し、 AWS Neuron コンパイルステップを追加する方法を示します。TensorFlow Serving は、ネットワーク全体で推論をスケールアップすることを可能にする提供システムです。Neuron TensorFlow Serving は通常の TensorFlow Serving と同じ API を使用します。唯一の違いは、保存されたモデルを Inferentia AWS 用にコンパイルする必要があり、エントリポイントは という名前の別のバイナリであることです `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>

以下の内容が含まれた Python スクリプト `tensorflow-model-server-compile.py` を作成します。このスクリプトは、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 Compiler の使用
<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 は、Machine Learning や深層学習フレームワークを使用してトレーニングされた深層学習モデルを提供するための、柔軟で使いやすいツールです。このチュートリアルには、 AWS Neuron を使用したコンパイルステップと、MXNet を使用した MMS の実装が含まれています。

 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>

 このチュートリアルを使用する前に、[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()` コンテキストに置き換えます。MXNet-Neuron は NDArray および Gluon API をサポートしていないため、`model_input` の不要なデータコピーをコメントアウトする必要があります。

```
...
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 と AWS Neuron Compiler の使用
<a name="tutorial-inferentia-pytorch-neuron"></a>

PyTorch-Neuron コンパイル API は、 AWS Inferentia デバイスで実行できるモデルグラフをコンパイルする方法を提供します。

トレーニング済みモデルは、Inf1 インスタンスにデプロイする前に、Inferentia ターゲットにコンパイルする必要があります。以下のチュートリアルでは、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 と torch パッケージのバージョン間には、torchvision モデルのコンパイル時に注意すべき依存関係があります。これらの依存関係ルールは、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']
```