

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

# 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\_trace\_resnet50.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\_infer\_resnet50.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']
```