

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

# 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
```