

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

# 教程
<a name="tutorials"></a>

以下是有关如何使用带 Conda 的深度学习 AMI 的软件的教程。

**Topics**
+ [激活框架](activating.md)
+ [使用 Elastic Fabric Adapter 进行分布式训练](tutorial-efa.md)
+ [GPU 监控和优化](tutorial-gpu.md)
+ [带有 DLAMI 的 AWS 推理芯片](tutorial-inferentia.md)
+ [ARM64 DLAMI](tutorial-arm64.md)
+ [推理](tutorial-inference.md)
+ [模型处理](model-serving.md)

# 激活框架
<a name="activating"></a>

以下是在带 Conda 的深度学习 AMI 上安装的深度学习框架。单击某个框架即可了解如何将其激活。

**Topics**
+ [PyTorch](tutorial-pytorch.md)
+ [TensorFlow 2](tutorial-tensorflow-2.md)

# PyTorch
<a name="tutorial-pytorch"></a>

## 正在激活 PyTorch
<a name="tutorial-pytorch-overview"></a>

当框架的稳定 Conda 程序包发布时，它会在 DLAMI 上进行测试并预安装。如果您希望运行最新的、未经测试的每日构建版本，您可以手动[Install PyTorch 的夜间构建（实验版）](#tutorial-pytorch-install)。

要激活当前安装的框架，请按照这些有关带 Conda 的深度学习 AMI 的说明进行操作。

对于使用 PyTorch CUDA 和 MKL-DNN 的 Python 3，请运行以下命令：

```
$ source activate pytorch_p310
```

启动 iPython 终端。

```
(pytorch_p310)$ ipython
```

运行一个快速 PyTorch 程序。

```
import torch
x = torch.rand(5, 3)
print(x)
print(x.size())
y = torch.rand(5, 3)
print(torch.add(x, y))
```

您应该会看到系统输出初始随机数组，然后输出大小，然后添加另一个随机数组。

## Install PyTorch 的夜间构建（实验版）
<a name="tutorial-pytorch-install"></a>

**如何 PyTorch 从夜间版本中安装**

您可以使用 Conda 将最新 PyTorch 版本安装到深度学习 AMI 上的任一或两个 PyTorch Conda 环境中。

1. 
   + （Python 3 的选项）-激活 Python 3 PyTorch 环境：

     ```
     $ source activate pytorch_p310
     ```

1. 其余步骤假定您使用的是 `pytorch_p310` 环境。移除当前安装的 PyTorch：

   ```
   (pytorch_p310)$ pip uninstall torch
   ```

1. 
   + （GPU 实例的选项）-使用 CUDA.0 安装最新的夜间版本： PyTorch 

     ```
     (pytorch_p310)$ pip install torch_nightly -f https://download.pytorch.org/whl/nightly/cu100/torch_nightly.html
     ```
   + （CPU 实例的选项）-为不 GPUs带以下选项的 PyTorch 实例安装最新的夜间版本：

     ```
     (pytorch_p310)$ pip install torch_nightly -f https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html
     ```

1. 要验证您是否已成功安装最新的夜间版本，请启动 IPython 终端并检查的版本。 PyTorch

   ```
   (pytorch_p310)$ ipython
   ```

   ```
   import torch
   print (torch.__version__)
   ```

   输出应类似于以下内容：`1.0.0.dev20180922`

1. 要验证 PyTorch 夜间版本是否与 MNIST 示例配合使用，您可以从 PyTorch的示例存储库中运行测试脚本：

   ```
   (pytorch_p310)$ cd ~
   (pytorch_p310)$ git clone https://github.com/pytorch/examples.git pytorch_examples
   (pytorch_p310)$ cd pytorch_examples/mnist
   (pytorch_p310)$ python main.py || exit 1
   ```

## 更多教程
<a name="tutorial-pytorch-more"></a>

有关更多教程和示例，请参阅该框架的官方[PyTorch 文档](http://pytorch.org/docs/master/)、文档和[PyTorch](http://pytorch.org)网站。

# TensorFlow 2
<a name="tutorial-tensorflow-2"></a>

本教程介绍如何在运行带有 Conda 的深度学习 AMI（Conda 上的 DLAMI）的实例上激活 TensorFlow 2 并运行 2 程序。 TensorFlow 

当框架的稳定 Conda 程序包发布时，它会在 DLAMI 上进行测试并预安装。

## 正在激活 TensorFlow 2
<a name="tutorial-tensorflow-2-overview"></a>

**和 Cond TensorFlow a 一起在 DLAMI 上跑步**

1. 要激活 TensorFlow 2，请使用 Conda 打开 DLAMI 的亚马逊弹性计算云 (Amazon EC2) 实例。

1. 对于使用 TensorFlow CUDA 10.1 和 MKL-DNN 的 Python 3 上的 2 和 Keras 2，请运行以下命令：

   ```
   $ source activate tensorflow2_p310
   ```

1. 启动 iPython 终端：

   ```
   (tensorflow2_p310)$ ipython
   ```

1. 运行 TensorFlow 2 程序以验证它是否正常运行：

   ```
   import tensorflow as tf
   hello = tf.constant('Hello, TensorFlow!')
   tf.print(hello)
   ```

   `Hello, TensorFlow!` 应显示在您的屏幕上。

## 更多教程
<a name="tutorial-tensorflow-2-more"></a>

有关更多教程和示例，请参阅 [TensorFlow Python API](https://www.tensorflow.org/api_docs/python/) 的 TensorFlow 文档或[TensorFlow](https://www.tensorflow.org)访问网站。

# 使用 Elastic Fabric Adapter 进行分布式训练
<a name="tutorial-efa"></a>

[Elastic Fabric Adapter](https://aws.amazon.com/hpc/efa/) (EFA) 是一种网络设备，可以将其附加到您的 DLAMI 实例以加快高性能计算 (HPC) 应用程序的速度。借助 AWS 云提供的可扩展性、灵活性和弹性，EFA 使您能够实现本地 HPC 集群的应用程序性能。

以下主题将向您展示如何开始结合使用 EFA 与 DLAMI。

**注意**  
从这个[基础 GPU DLAMI 列表](appendix-ami-release-notes.md#appendix-ami-release-notes-base)中选择您的 DLAMI

**Topics**
+ [使用 EFA 启动 AWS Deep Learning AMIs 实例](tutorial-efa-launching.md)
+ [在 DLAMI 上使用 EFA](tutorial-efa-using.md)

# 使用 EFA 启动 AWS Deep Learning AMIs 实例
<a name="tutorial-efa-launching"></a>

最新基础 DLAMI 可随时与 EFA 结合使用，并随附所需的驱动程序、内核模块、libfabric、openmpi 和适用于 GPU 实例的 [NCCL OFI 插件](https://github.com/aws/aws-ofi-nccl/tree/aws)。

您可以在[发布说明](appendix-ami-release-notes.md#appendix-ami-release-notes-base)中找到基础 DLAMI 的支持 CUDA 版本。

注意：
+ 在 EFA 上使用 `mpirun` 运行 NCCL 应用程序时，必须将 EFA 支持的安装的完整路径指定为：

  ```
  /opt/amazon/openmpi/bin/mpirun <command>  
  ```
+ 要使您的应用程序能够使用 EFA，请将 `FI_PROVIDER="efa"` 添加到 `mpirun` 命令，如[在 DLAMI 上使用 EFA](tutorial-efa-using.md)中所示。

**Topics**
+ [准备 EFA 启用的安全组](#tutorial-efa-security-group)
+ [启动实例](#tutorial-efa-launch)
+ [验证 EFA 附件](#tutorial-efa-verify-attachment)

## 准备 EFA 启用的安全组
<a name="tutorial-efa-security-group"></a>

EFA 需要一个安全组来支持进出安全组本身的所有入站和出站流量。有关更多信息，请参阅 [EFA 文档](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html#efa-start-security)。

1. 打开位于 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/) 的 Amazon EC2 控制台。

1. 在导航窗格中，选择**安全组**，然后选择**创建安全组**。

1. 在**创建安全组**窗口中，执行以下操作：
   + 对于**安全组名称**，请输入一个描述性的安全组名称，例如 `EFA-enabled security group`。
   + （可选）对于**描述**，请输入安全组的简要描述。
   + 对于 **VPC**，请选择要在其中启动启用了 EFA 的实例的 VPC。
   + 选择**创建**。

1. 选择您创建的安全组，然后在**描述** 选项卡上复制**组 ID**。

1. 在**入站**和**出站**选项卡上，执行以下操作：
   + 选择**编辑**。
   + 对于**类型**，请选择**所有流量**。
   + 对于 **Source**，选择 **Custom**。
   + 将您复制的安全组 ID 粘贴到该字段中。
   + 选择**保存**。

1. 启用入站流量，请参考[授权您 Linux 实例的入站流量](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html)。如果跳过此步骤，您将无法与您的 DLAMI 实例进行通信。

## 启动实例
<a name="tutorial-efa-launch"></a>

目前 AWS Deep Learning AMIs ，以下实例类型和操作系统支持上的 EFA：
+  P3dn：Amazon Linux 2、Ubuntu 20.04
+  P4d、P4de：Amazon Linux 2、Amazon Linux 2023、Ubuntu 20.04、Ubuntu 22.04
+  P5、P5e、P5en：Amazon Linux 2、Amazon Linux 2023、Ubuntu 20.04、Ubuntu 22.04

下节介绍如何启动启用了 EFA 的 DLAMI 实例。有关启动 EFA 启用的 DLAMI 实例的更多信息，请参阅[在集群置放群组中启动 EFA 启用的实例](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html#efa-start-instances)。

1. 打开位于 [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/) 的 Amazon EC2 控制台。

1. 选择**启动实例**。

1. 在**选择 AMI** 页面上，选择在 [DLAMI Release Notes Page](https://docs.aws.amazon.com/dlami/latest/devguide/appendix-ami-release-notes) 上找到的受支持的 DLAMI。

1. 在**选择实例类型**页面上，选择以下支持的实例类型之一，然后选择**下一步：配置实例详细信息**。有关受支持的实例的列表，请参阅此链接：[开始使用 EFA 和 MPI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html)。

1. 在**配置实例详细信息**页面中，执行以下操作：
   + 对于**实例的数量**，请输入要启动的启用了 EFA 的实例数量。
   + 对于**网络** 和**子网**，请选择要在其中启动实例的 VPC 和子网。
   + [可选] 对于**置放群组**，请选择**将实例添加到置放群组**。为获得最佳性能，请在置放群组中启动实例。
   + [可选] 对于**置放群组名称**，请选择**添加到新的置放群组**，输入置放群组的描述性名称，然后对于**置放群组策略**选择**集群**。
   + 请务必在此页面上启用**“Elastic Fabric Adapter”**。如果禁用此选项，请将子网更改为支持所选实例类型的子网。
   + 在**网络接口**部分中，为设备 **eth0** 选择**新网络接口**。您可以选择指定一个主 IPv4 地址和一个或多个辅助 IPv4 地址。如果您要在具有关联 IPv6 CIDR 块的子网中启动实例，则可以选择指定一个主 IPv6 地址和一个或多个辅助 IPv6 地址。
   + 选择**下一步：添加存储**。

1. 在**添加存储**页面上，除了 AMI 指定的卷（如根设备卷）以外，还要指定要附加到实例的卷，然后选择**下一步：添加标签**。

1. 在**添加标签**页面上，为实例指定标签（例如，便于用户识别的名称），然后选择**下一步：配置安全组**。

1. 在**配置安全组**页面上，对于**分配安全组**选择**选择一个现有的安全组**，然后选择先前创建的安全组**。**

1. 选择**审核并启动**。

1. 在**核查实例启动**页面上，检查这些设置，然后选择**启动**以选择一个密钥对并启动您的实例。

## 验证 EFA 附件
<a name="tutorial-efa-verify-attachment"></a>

### 通过控制台
<a name="tutorial-efa-verify-attachment-console"></a>

启动实例后，请在 AWS 控制台中查看实例详细信息。为此，请在 EC2 控制台中选择实例，然后查看页面下部窗格中的 Description (描述) 选项卡。找到参数“Network Interfaces: eth0”，然后单击 eth0，这将弹出一个弹出窗口。确保已启用“Elastic Fabric Adapter”。

如果未启用 EFA，您可以通过以下任一方式解决此问题：
+ 终止 EC2 实例并使用相同步骤启动新实例。确保已附加 EFA。
+ 将 EFA 附加到现有实例。

  1. 在 EC2 控制台中，转到“网络接口”。

  1. 单击“创建虚拟网络接口”。

  1. 选择您的实例所在的相同子网。

  1. 确保启用“Elastic Fabric Adapter”并点击“创建”。

  1. 返回“EC2 实例”选项卡并选择您的实例。

  1. 转到“操作：实例状态”并在附加 EFA 之前停止实例。

  1. 从 “操作”中，选择“网络连接：连接网络接口”。

  1. 选择您刚刚创建的界面，然后点击“附加”。

  1. 重新启动您的实例。

### 通过实例
<a name="tutorial-efa-verify-attachment-instance"></a>

以下测试脚本已存在于 DLAMI 中。运行它以确保内核模块正确加载。

```
$ fi_info -p efa
```

您的输出应类似于以下内容。

```
provider: efa
    fabric: EFA-fe80::e5:56ff:fe34:56a8
    domain: efa_0-rdm
    version: 2.0
    type: FI_EP_RDM
    protocol: FI_PROTO_EFA
provider: efa
    fabric: EFA-fe80::e5:56ff:fe34:56a8
    domain: efa_0-dgrm
    version: 2.0
    type: FI_EP_DGRAM
    protocol: FI_PROTO_EFA
provider: efa;ofi_rxd
    fabric: EFA-fe80::e5:56ff:fe34:56a8
    domain: efa_0-dgrm
    version: 1.0
    type: FI_EP_RDM
    protocol: FI_PROTO_RXD
```

### 验证安全组配置
<a name="tutorial-efa-verify-attachment-security"></a>

以下测试脚本已存在于 DLAMI 中。运行它以确保您创建的安全组配置正确。

```
$ cd /opt/amazon/efa/test/ 
$ ./efa_test.sh
```

您的输出应类似于以下内容。

```
Starting server...
Starting client...
bytes   #sent   #ack     total       time     MB/sec    usec/xfer   Mxfers/sec
64      10      =10      1.2k        0.02s      0.06    1123.55       0.00
256     10      =10      5k          0.00s     17.66      14.50       0.07
1k      10      =10      20k         0.00s     67.81      15.10       0.07
4k      10      =10      80k         0.00s    237.45      17.25       0.06
64k     10      =10      1.2m        0.00s    921.10      71.15       0.01
1m      10      =10      20m         0.01s   2122.41     494.05       0.00
```

如果它停止响应或未完成，请确保您的安全组具有正确的 inbound/outbound 规则。

# 在 DLAMI 上使用 EFA
<a name="tutorial-efa-using"></a>

以下部分描述如何在 AWS Deep Learning AMIs上使用 EFA 来运行多节点应用程序。

## 使用 EFA 来运行多节点应用程序
<a name="tutorial-efa-using-multi-node"></a>

要跨节点集群运行应用程序，需要以下配置

**Topics**
+ [启用无密码 SSH](#tutorial-efa-using-multi-node-ssh)
+ [创建主机文件](#tutorial-efa-using-multi-node-hosts)
+ [NCCL 测试](#tutorial-efa-using-2node)

### 启用无密码 SSH
<a name="tutorial-efa-using-multi-node-ssh"></a>

选择集群中的一个节点作为领导节点。其余节点称为成员节点。

1. 在领导节点上，生成 RSA 密钥对。

   ```
   ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
   ```

1. 更改领导节点上私有密钥的权限。

   ```
   chmod 600 ~/.ssh/id_rsa
   ```

1. 复制公有密钥 `~/.ssh/id_rsa.pub` 并将其附加到集群中成员节点的 `~/.ssh/authorized_keys` 之后。

1. 现在，您应该能够使用私有 ip 从领导节点直接登录到成员节点。

   ```
   ssh <member private ip>
   ```

1. 通过将以下内容添加到领导节点上的 \$1/.ssh/config 文件中，禁用 strictHostKey检查并在领导节点上启用代理转发：

   ```
   Host *
       ForwardAgent yes
   Host *
       StrictHostKeyChecking no
   ```

1. 在 Amazon Linux 2 实例上，在领导节点上运行以下命令，为配置文件提供正确的权限：

   ```
   chmod 600 ~/.ssh/config
   ```

### 创建主机文件
<a name="tutorial-efa-using-multi-node-hosts"></a>

在领导节点上，创建主机文件以标识集群中的节点。主机文件必须针对集群中的每个节点都有一个条目。创建文件 \$1/hosts 并使用私有 IP 添加每个节点，如下所示：

```
localhost slots=8
<private ip of node 1> slots=8
<private ip of node 2> slots=8
```

### NCCL 测试
<a name="tutorial-efa-using-2node"></a>

**注意**  
这些测试是使用 EFA 版本 1.38.0 和 OFI NCCL Plugin 1.13.2 运行的。

 下面列出了由 Nvidia 提供的 NCCL 测试子集，用于测试多个计算节点的功能和性能 

 **支持的实例：P3dn、P4、P5、P5e、P5en** 

#### 性能测试
<a name="tutorial-efa-using-multinode"></a>

##### P4d.24xlarge 上的多节点 NCCL 性能测试
<a name="tutorial-efa-using-multi-node-performance"></a>

要使用 EFA 来检查 NCCL 性能，请运行官方 [NCCL-Tests 存储库](https://github.com/NVIDIA/nccl-tests.git)中提供的标准 NCCL 性能测试。DLAMI 附带了这个已经为 CUDA XX.X 构建的测试。您也可以使用 EFA 运行自己的脚本。

构建您自己的脚本时，请参阅以下指南：
+ 当使用 EFA 来运行 NCCL 应用程序时，按照示例所示使用到 mpirun 的完整路径。
+ 根据集群 GPUs 中的实例数量更改参数 np 和 N。
+ 添加 NCCL\$1DEBUG=INFO 标志，并确保日志将 EFA 用法指示为“所选提供程序是 EFA”。
+  设置要解析的训练日志位置以进行验证 

  ```
  TRAINING_LOG="testEFA_$(date +"%N").log"
  ```

在任何成员节点上使用 `watch nvidia-smi` 命令来监视 GPU 使用情况。以下 `watch nvidia-smi` 命令适用于通用 CUDA xx.x 版本，并且依赖于您的实例的操作系统。通过替换脚本中的 CUDA 版本，您可以在您的 Amazon EC2 实例中运行适用于任何可用 CUDA 版本的命令。
+ Amazon Linux 2、Amazon Linux 2023：

  ```
   $ /opt/amazon/openmpi/bin/mpirun -n 16 -N 8 \
  -x NCCL_DEBUG=INFO --mca pml ^cm \
  -x LD_LIBRARY_PATH=/usr/local/cuda-xx.x/efa/lib:/usr/local/cuda-xx.x/lib:/usr/local/cuda-xx.x/lib64:/usr/local/cuda-xx.x:/opt/amazon/efa/lib64:/opt/amazon/openmpi/lib64:$LD_LIBRARY_PATH \
  --hostfile hosts --mca btl tcp,self --mca btl_tcp_if_exclude lo,docker0 --bind-to none \
  /usr/local/cuda-xx.x/efa/test-cuda-xx.x/all_reduce_perf -b 8 -e 1G -f 2 -g 1 -c 1 -n 100 | tee ${TRAINING_LOG}
  ```
+ Ubuntu 20.04，Ubuntu 20.04：

  ```
  $ /opt/amazon/openmpi/bin/mpirun -n 16 -N 8 \
  -x NCCL_DEBUG=INFO --mca pml ^cm \
  -x LD_LIBRARY_PATH=/usr/local/cuda-xx.x/efa/lib:/usr/local/cuda-xx.x/lib:/usr/local/cuda-xx.x/lib64:/usr/local/cuda-xx.x:/opt/amazon/efa/lib:/opt/amazon/openmpi/lib:$LD_LIBRARY_PATH \
  --hostfile hosts --mca btl tcp,self --mca btl_tcp_if_exclude lo,docker0 --bind-to none \
  /usr/local/cuda-xx.x/efa/test-cuda-xx.x/all_reduce_perf -b 8 -e 1G -f 2 -g 1 -c 1 -n 100 | tee ${TRAINING_LOG}
  ```

您的输出应与以下内容类似：

```
# nThread 1 nGpus 1 minBytes 8 maxBytes 1073741824 step: 2(factor) warmup iters: 5 iters: 100 agg iters: 1 validation: 1 graph: 0
#
# Using devices
#  Rank  0 Group  0 Pid  33378 on ip-172-31-42-25 device  0 [0x10] NVIDIA A100-SXM4-40GB
#  Rank  1 Group  0 Pid  33379 on ip-172-31-42-25 device  1 [0x10] NVIDIA A100-SXM4-40GB
#  Rank  2 Group  0 Pid  33380 on ip-172-31-42-25 device  2 [0x20] NVIDIA A100-SXM4-40GB
#  Rank  3 Group  0 Pid  33381 on ip-172-31-42-25 device  3 [0x20] NVIDIA A100-SXM4-40GB
#  Rank  4 Group  0 Pid  33382 on ip-172-31-42-25 device  4 [0x90] NVIDIA A100-SXM4-40GB
#  Rank  5 Group  0 Pid  33383 on ip-172-31-42-25 device  5 [0x90] NVIDIA A100-SXM4-40GB
#  Rank  6 Group  0 Pid  33384 on ip-172-31-42-25 device  6 [0xa0] NVIDIA A100-SXM4-40GB
#  Rank  7 Group  0 Pid  33385 on ip-172-31-42-25 device  7 [0xa0] NVIDIA A100-SXM4-40GB
#  Rank  8 Group  0 Pid  30378 on ip-172-31-43-8 device  0 [0x10] NVIDIA A100-SXM4-40GB
#  Rank  9 Group  0 Pid  30379 on ip-172-31-43-8 device  1 [0x10] NVIDIA A100-SXM4-40GB
#  Rank 10 Group  0 Pid  30380 on ip-172-31-43-8 device  2 [0x20] NVIDIA A100-SXM4-40GB
#  Rank 11 Group  0 Pid  30381 on ip-172-31-43-8 device  3 [0x20] NVIDIA A100-SXM4-40GB
#  Rank 12 Group  0 Pid  30382 on ip-172-31-43-8 device  4 [0x90] NVIDIA A100-SXM4-40GB
#  Rank 13 Group  0 Pid  30383 on ip-172-31-43-8 device  5 [0x90] NVIDIA A100-SXM4-40GB
#  Rank 14 Group  0 Pid  30384 on ip-172-31-43-8 device  6 [0xa0] NVIDIA A100-SXM4-40GB
#  Rank 15 Group  0 Pid  30385 on ip-172-31-43-8 device  7 [0xa0] NVIDIA A100-SXM4-40GB
ip-172-31-42-25:33385:33385 [7] NCCL INFO cudaDriverVersion 12060
ip-172-31-43-8:30383:30383 [5] NCCL INFO Bootstrap : Using ens32:172.31.43.8
ip-172-31-43-8:30383:30383 [5] NCCL INFO NCCL version 2.23.4+cuda12.5
...
ip-172-31-42-25:33384:33451 [6] NCCL INFO NET/OFI Initializing aws-ofi-nccl 1.13.2-aws
ip-172-31-42-25:33384:33451 [6] NCCL INFO NET/OFI Using Libfabric version 1.22
ip-172-31-42-25:33384:33451 [6] NCCL INFO NET/OFI Using CUDA driver version 12060 with runtime 12050
ip-172-31-42-25:33384:33451 [6] NCCL INFO NET/OFI Configuring AWS-specific options
ip-172-31-42-25:33384:33451 [6] NCCL INFO NET/OFI Setting provider_filter to efa
ip-172-31-42-25:33384:33451 [6] NCCL INFO NET/OFI Setting FI_EFA_FORK_SAFE environment variable to 1
ip-172-31-42-25:33384:33451 [6] NCCL INFO NET/OFI Setting NCCL_NVLSTREE_MAX_CHUNKSIZE to 512KiB
ip-172-31-42-25:33384:33451 [6] NCCL INFO NET/OFI Setting NCCL_NVLS_CHUNKSIZE to 512KiB
ip-172-31-42-25:33384:33451 [6] NCCL INFO NET/OFI Running on p4d.24xlarge platform, Setting NCCL_TOPO_FILE environment variable to /opt/amazon/ofi-nccl/share/aws-ofi-nccl/xml/p4d-24xl-topo.xml
...
-----------------------------some output truncated-----------------------------------
#                                                              out-of-place                       in-place          
#       size         count      type   redop    root     time   algbw   busbw #wrong     time   algbw   busbw #wrong
#        (B)    (elements)                               (us)  (GB/s)  (GB/s)            (us)  (GB/s)  (GB/s)       
           8             2     float     sum      -1    180.3    0.00    0.00      0    179.3    0.00    0.00      0
          16             4     float     sum      -1    178.1    0.00    0.00      0    177.6    0.00    0.00      0
          32             8     float     sum      -1    178.5    0.00    0.00      0    177.9    0.00    0.00      0
          64            16     float     sum      -1    178.8    0.00    0.00      0    178.7    0.00    0.00      0
         128            32     float     sum      -1    178.2    0.00    0.00      0    177.8    0.00    0.00      0
         256            64     float     sum      -1    178.6    0.00    0.00      0    178.8    0.00    0.00      0
         512           128     float     sum      -1    177.2    0.00    0.01      0    177.1    0.00    0.01      0
        1024           256     float     sum      -1    179.2    0.01    0.01      0    179.3    0.01    0.01      0
        2048           512     float     sum      -1    181.3    0.01    0.02      0    181.2    0.01    0.02      0
        4096          1024     float     sum      -1    184.2    0.02    0.04      0    183.9    0.02    0.04      0
        8192          2048     float     sum      -1    191.2    0.04    0.08      0    190.6    0.04    0.08      0
       16384          4096     float     sum      -1    202.5    0.08    0.15      0    202.3    0.08    0.15      0
       32768          8192     float     sum      -1    233.0    0.14    0.26      0    232.1    0.14    0.26      0
       65536         16384     float     sum      -1    238.6    0.27    0.51      0    235.1    0.28    0.52      0
      131072         32768     float     sum      -1    237.2    0.55    1.04      0    236.8    0.55    1.04      0
      262144         65536     float     sum      -1    248.3    1.06    1.98      0    247.0    1.06    1.99      0
      524288        131072     float     sum      -1    309.2    1.70    3.18      0    307.7    1.70    3.20      0
     1048576        262144     float     sum      -1    408.7    2.57    4.81      0    404.3    2.59    4.86      0
     2097152        524288     float     sum      -1    613.5    3.42    6.41      0    607.9    3.45    6.47      0
     4194304       1048576     float     sum      -1    924.5    4.54    8.51      0    914.8    4.58    8.60      0
     8388608       2097152     float     sum      -1   1059.5    7.92   14.85      0   1054.3    7.96   14.92      0
    16777216       4194304     float     sum      -1   1269.9   13.21   24.77      0   1272.0   13.19   24.73      0
    33554432       8388608     float     sum      -1   1642.7   20.43   38.30      0   1636.7   20.50   38.44      0
    67108864      16777216     float     sum      -1   2446.7   27.43   51.43      0   2445.8   27.44   51.45      0
   134217728      33554432     float     sum      -1   4143.6   32.39   60.73      0   4142.4   32.40   60.75      0
   268435456      67108864     float     sum      -1   7351.9   36.51   68.46      0   7346.7   36.54   68.51      0
   536870912     134217728     float     sum      -1    13717   39.14   73.39      0    13703   39.18   73.46      0
  1073741824     268435456     float     sum      -1    26416   40.65   76.21      0    26420   40.64   76.20      0
...
# Out of bounds values : 0 OK
# Avg bus bandwidth    : 15.5514
```

#### 验证测试
<a name="tutorial-efa-validation"></a>

要验证 EFA 测试返回的结果有效，请使用以下测试进行确认：
+ 使用 EC2 实例元数据获取实例类型：

  ```
  TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
  INSTANCE_TYPE=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/instance-type)
  ```
+ 运行[性能测试](#tutorial-efa-using-multinode) 
+  设置以下参数 

  ```
  CUDA_VERSION
  CUDA_RUNTIME_VERSION
  NCCL_VERSION
  ```
+  验证结果，如下所示：

  ```
  RETURN_VAL=`echo $?`
  if [ ${RETURN_VAL} -eq 0 ]; then
  
      # [0] NCCL INFO NET/OFI Initializing aws-ofi-nccl 1.13.2-aws
      # [0] NCCL INFO NET/OFI Using CUDA driver version 12060 with runtime 12010
  
      # cudaDriverVersion 12060  --> This is max supported cuda version by nvidia driver
      # NCCL version 2.23.4+cuda12.5 --> This is NCCL version compiled with cuda version
  
      # Validation of logs
      grep "NET/OFI Configuring AWS-specific options" ${TRAINING_LOG} || { echo "AWS-specific options text not found"; exit 1; } 
      grep "busbw" ${TRAINING_LOG} || { echo "busbw text not found"; exit 1; } 
      grep "Avg bus bandwidth " ${TRAINING_LOG} || { echo "Avg bus bandwidth text not found"; exit 1; } 
      grep "NCCL version $NCCL_VERSION" ${TRAINING_LOG} || { echo "Text not found: NCCL version $NCCL_VERSION"; exit 1; }
      if [[ ${INSTANCE_TYPE} == "p4d.24xlarge" ]]; then
          grep "NET/Libfabric/0/GDRDMA" ${TRAINING_LOG} || { echo "Text not found: NET/Libfabric/0/GDRDMA"; exit 1; }  
          grep "NET/OFI Selected Provider is efa (found 4 nics)" ${TRAINING_LOG} || { echo "Selected Provider is efa text not found"; exit 1; }   
      elif [[ ${INSTANCE_TYPE} == "p4de.24xlarge" ]]; then
          grep "NET/Libfabric/0/GDRDMA" ${TRAINING_LOG} || { echo "Avg bus bandwidth text not found"; exit 1; }
          grep "NET/OFI Selected Provider is efa (found 4 nics)" ${TRAINING_LOG} || { echo "Avg bus bandwidth text not found"; exit 1; }
      elif [[ ${INSTANCE_TYPE} == "p5.48xlarge" ]]; then
          grep "NET/Libfabric/0/GDRDMA" ${TRAINING_LOG} || { echo "Avg bus bandwidth text not found"; exit 1; }
          grep "NET/OFI Selected Provider is efa (found 32 nics)" ${TRAINING_LOG} || { echo "Avg bus bandwidth text not found"; exit 1; } 
      elif [[ ${INSTANCE_TYPE} == "p5e.48xlarge" ]]; then
          grep "NET/Libfabric/0/GDRDMA" ${TRAINING_LOG} || { echo "Avg bus bandwidth text not found"; exit 1; }
          grep "NET/OFI Selected Provider is efa (found 32 nics)" ${TRAINING_LOG} || { echo "Avg bus bandwidth text not found"; exit 1; }
      elif [[ ${INSTANCE_TYPE} == "p5en.48xlarge" ]]; then
          grep "NET/Libfabric/0/GDRDMA" ${TRAINING_LOG} || { echo "Avg bus bandwidth text not found"; exit 1; }
          grep "NET/OFI Selected Provider is efa (found 16 nics)" ${TRAINING_LOG} || { echo "Avg bus bandwidth text not found"; exit 1; }
      elif [[ ${INSTANCE_TYPE} == "p3dn.24xlarge" ]]; then
          grep "NET/OFI Selected Provider is efa (found 4 nics)" ${TRAINING_LOG} || { echo "Selected Provider is efa text not found"; exit 1; }  
      fi
      echo "***************************** check_efa_nccl_all_reduce passed for cuda version ${CUDA_VERSION} *****************************"
  else
      echo "***************************** check_efa_nccl_all_reduce failed for cuda version ${CUDA_VERSION} *****************************"
  fi
  ```
+ 要访问基准数据，可以解析多节点 all\$1reduce 测试的表输出的最后一行：

  ```
  benchmark=$(sudo cat ${TRAINING_LOG} | grep '1073741824' | tail -n1 | awk -F " " '{{print $12}}' | sed 's/ //' | sed  's/  5e-07//')
  if [[ -z "${benchmark}" ]]; then
    echo "benchmark variable is empty"
    exit 1
  fi
  
  echo "Benchmark throughput: ${benchmark}"
  ```

# GPU 监控和优化
<a name="tutorial-gpu"></a>

以下部分将指导您完成 GPU 优化和监控选项。本部分的组织方式如同一个典型工作流程一样，其中包含监控监督预处理和训练。
+ [监控](tutorial-gpu-monitoring.md)
  + [GPUs 使用监视器 CloudWatch](tutorial-gpu-monitoring-gpumon.md)
+ [优化](tutorial-gpu-opt.md)
  + [预处理](tutorial-gpu-opt-preprocessing.md)
  + [训练](tutorial-gpu-opt-training.md)

# 监控
<a name="tutorial-gpu-monitoring"></a>

您的 DLAMI 已预安装多个 GPU 监控工具。本指南还将介绍可用于下载和安装的工具。
+ [GPUs 使用监视器 CloudWatch](tutorial-gpu-monitoring-gpumon.md)-预装的实用程序，可向 Amazon CloudWatch 报告 GPU 使用情况统计信息。
+ [nvidia-smi CLI](https://developer.nvidia.com/nvidia-system-management-interface) — 一个监控总体 GPU 计算和内存利用率的实用工具。它已预先安装在你的 AWS Deep Learning AMIs (DLAMI) 上。
+ [NVML C 库](https://developer.nvidia.com/nvidia-management-library-nvml) - 一个基于 C 的 API，可直接访问 GPU 监控和管理功能。此项已在后台由 nvidia-smi CLI 所使用且已预安装在您的 DLAMI 上。它还具有 Python 和 Perl 绑定以方便采用这些请求进行开发。你的 DLAMI 上预装的 gpumon.py 实用程序使用的是来自的 pynvml 包。[nvidia-ml-py](https://pypi.org/project/nvidia-ml-py/)
+ [NVIDIA DCGM](https://developer.nvidia.com/data-center-gpu-manager-dcgm) - 一个集群管理工具。请访问开发人员页面，了解如何安装和配置此工具。

**提示**  
请查看 NVIDIA 的开发人员博客，了解有关使用已安装在您的 DLAMI 上的 CUDA 工具的最新信息。  
[使用 Nsight IDE 和 nvprof 监控 TensorCore 利用率](https://devblogs.nvidia.com/using-nsight-compute-nvprof-mixed-precision-deep-learning-models/)。

# GPUs 使用监视器 CloudWatch
<a name="tutorial-gpu-monitoring-gpumon"></a>

当您将 DLAMI 与 GPU 结合使用时，您可能会发现，您要寻找在训练或推理期间跟踪其使用率的方式。这对于优化您的数据管道以及调整深度学习网络非常有用。

有两种方法可以配置 GPU 指标 CloudWatch：
+ [使用 AWS CloudWatch 代理配置指标（推荐）](#tutorial-gpu-monitoring-gpumon-cloudwatch-agent-guide)
+ [使用预安装 `gpumon.py` 脚本来配置指标](#tutorial-gpu-monitoring-gpumon-script)

## 使用 AWS CloudWatch 代理配置指标（推荐）
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-guide"></a>

将您的 DLAMI 与[ CloudWatch 统一](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html)代理集成，以配置 GPU 指标并监控 Amazon EC2 加速实例中 GPU 协进程的利用率。

使用 DLAMI 来配置 [GPU 指标](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-NVIDIA-GPU.html)的方式有四种：
+ [配置最低 GPU 指标](#tutorial-gpu-monitoring-gpumon-cloudwatch-agent-minimal)
+ [配置部分 GPU 指标](#tutorial-gpu-monitoring-gpumon-cloudwatch-agent-partial)
+ [配置所有可用 GPU 指标](#tutorial-gpu-monitoring-gpumon-cloudwatch-agent-all)
+ [配置自定义 GPU 指标](#tutorial-gpu-monitoring-gpumon-cloudwatch-agent-custom)

有关更新和安全补丁的信息，请参阅 [为代理安装安全补 AWS CloudWatch 丁](#tutorial-gpu-monitoring-gpumon-cloudwatch-agent-security)

### 先决条件
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-prerequisites"></a>

首先，您必须配置 Amazon EC2 实例 IAM 权限，以允许您的实例将指标推送到 CloudWatch。有关详细步骤，请参阅[创建用于 CloudWatch 代理的 IAM 角色和用户](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-iam-roles-for-cloudwatch-agent.html)。

### 配置最低 GPU 指标
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-minimal"></a>

使用 `dlami-cloudwatch-agent@minimal` `systemd` 服务来配置最低 GPU 指标。此服务配置以下指标：
+ `utilization_gpu`
+ `utilization_memory`

您可以在以下位置找到适用于最低预先配置 GPU 指标的 `systemd` 服务：

```
/opt/aws/amazon-cloudwatch-agent/etc/dlami-amazon-cloudwatch-agent-minimal.json
```

使用以下命令启用并启动 `systemd` 服务：

```
sudo systemctl enable dlami-cloudwatch-agent@minimal
sudo systemctl start dlami-cloudwatch-agent@minimal
```

### 配置部分 GPU 指标
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-partial"></a>

使用 `dlami-cloudwatch-agent@partial` `systemd` 服务来配置部分 GPU 指标。此服务配置以下指标：
+ `utilization_gpu`
+ `utilization_memory`
+ `memory_total`
+ `memory_used`
+ `memory_free`

您可以在以下位置找到适用于部分预先配置 GPU 指标的 `systemd` 服务：

```
/opt/aws/amazon-cloudwatch-agent/etc/dlami-amazon-cloudwatch-agent-partial.json
```

使用以下命令启用并启动 `systemd` 服务：

```
sudo systemctl enable dlami-cloudwatch-agent@partial
sudo systemctl start dlami-cloudwatch-agent@partial
```

### 配置所有可用 GPU 指标
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-all"></a>

使用 `dlami-cloudwatch-agent@all` `systemd` 服务来配置所有可用 GPU 指标。此服务配置以下指标：
+ `utilization_gpu`
+ `utilization_memory`
+ `memory_total`
+ `memory_used`
+ `memory_free`
+ `temperature_gpu`
+ `power_draw`
+ `fan_speed`
+ `pcie_link_gen_current`
+ `pcie_link_width_current`
+ `encoder_stats_session_count`
+ `encoder_stats_average_fps`
+ `encoder_stats_average_latency`
+ `clocks_current_graphics`
+ `clocks_current_sm`
+ `clocks_current_memory`
+ `clocks_current_video`

您可以在以下位置找到适用于所有可用预先配置 GPU 指标的 `systemd` 服务：

```
/opt/aws/amazon-cloudwatch-agent/etc/dlami-amazon-cloudwatch-agent-all.json
```

使用以下命令启用并启动 `systemd` 服务：

```
sudo systemctl enable dlami-cloudwatch-agent@all
sudo systemctl start dlami-cloudwatch-agent@all
```

### 配置自定义 GPU 指标
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-custom"></a>

如果预配置的指标不符合您的要求，则可以创建自定义 CloudWatch 代理配置文件。

#### 创建自定义配置文件
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-custom-create"></a>

要创建自定义配置文件，请参阅[手动创建或编辑 CloudWatch 代理配置文件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html)中的详细步骤。

在此示例中，假设架构定义位于 `/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json`。

#### 使用您的自定义文件来配置指标
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-custom-configure"></a>

运行以下命令根据您的自定义文件配置 CloudWatch 代理：

```
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
-a fetch-config -m ec2 -s -c \
file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
```

### 为代理安装安全补 AWS CloudWatch 丁
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-security"></a>

新发布 DLAMIs 的服务器配置了最新的可用 AWS CloudWatch 代理安全补丁。请参阅以下部分，根据您选择的操作系统，使用最新安全补丁来更新您当前的DLAMI。

#### Amazon Linux 2
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-security-al2"></a>

`yum`用于获取亚马逊 Linux 2 DLAMI 的最新 AWS CloudWatch 代理安全补丁。

```
 sudo yum update
```

#### Ubuntu
<a name="tutorial-gpu-monitoring-gpumon-cloudwatch-agent-security-ubuntu"></a>

要使用Ubuntu获取DLAMI的最新 AWS CloudWatch 安全补丁，必须 AWS CloudWatch 使用Amazon S3下载链接重新安装代理。

```
wget https://s3.region.amazonaws.com/amazoncloudwatch-agent-region/ubuntu/arm64/latest/amazon-cloudwatch-agent.deb
```

有关使用 Amazon S3 下载链接安装 AWS CloudWatch 代理的更多信息，请参阅在[服务器上安装和运行 CloudWatch 代](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/install-CloudWatch-Agent-commandline-fleet.html)理。

## 使用预安装 `gpumon.py` 脚本来配置指标
<a name="tutorial-gpu-monitoring-gpumon-script"></a>

一个名为 gpumon.py 的实用工具已预安装在您的 DLAMI 上。它集成 CloudWatch 并支持监控每个 GPU 的使用情况：GPU 内存、GPU 温度和 GPU 功率。该脚本会定期将监控的数据发送到 CloudWatch。您可以通过更改脚本中的一些设置来配置要发送到 CloudWatch 的数据的粒度级别。但是，在启动脚本之前，您需要进行设置 CloudWatch 才能接收指标。

**如何使用设置和运行 GPU 监控 CloudWatch**

1. 创建 IAM 用户，或修改现有用户以制定向其发布指标的策略 CloudWatch。如果创建新用户，请记下凭证，因为您将在下一步中需要这些凭证。

   要搜索的 IAM 策略是 “cloudwatch:PutMetricData”。要添加的策略如下所示：

------
#### [ JSON ]

****  

   ```
   {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
           {
               "Action": [
                   "cloudwatch:PutMetricData"
                ],
                "Effect": "Allow",
                "Resource": "*"
           }
      ]
   }
   ```

------
**提示**  
有关创建 IAM 用户和为添加策略的更多信息 CloudWatch，请参阅[ CloudWatch 文档](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-iam-roles-for-cloudwatch-agent.html)。

1. 在您的 DLAMI 上，运行 [AWS 配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html#cli-quick-configuration)并指定 IAM 用户凭证。

   ```
   $ aws configure
   ```

1. 您可能需要先对 gpumon 实用工具进行一些修改，然后再运行该工具。您可以在以下代码块中定义的位置中找到 gpumon 实用工具和 README。有关 `gpumon.py` 脚本的更多信息，请参阅[脚本的 Amazon S3 位置](https://s3.amazonaws.com/aws-bigdata-blog/artifacts/GPUMonitoring/gpumon.py)。

   ```
   Folder: ~/tools/GPUCloudWatchMonitor
   Files: 	~/tools/GPUCloudWatchMonitor/gpumon.py
         	~/tools/GPUCloudWatchMonitor/README
   ```

   选项：
   + 如果您的实例不在 us-east-1 中，请在 gpumon.py 中更改区域。
   + 更改其他参数，例如 CloudWatch`namespace`或报告周期`store_reso`。

1. 目前，该脚本仅支持 Python 3。激活您的首选框架的 Python 3 环境或激活 DLAMI 一般 Python 3 环境。

   ```
   $ source activate python3
   ```

1. 在后台中运行 gpumon 实用工具。

   ```
   (python3)$ python gpumon.py &
   ```

1. 打开您的浏览器前往 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/)，然后选择指标。它将有一个命名空间 “DeepLearningTrain”。
**提示**  
您可以修改 gpumon.py 来更改该命名空间。您也可以通过调整 `store_reso` 来修改报告间隔。

以下是一个示例 CloudWatch 图表，报告了 gpumon.py 在监视 p2.8xlarge 实例上的训练作业的情况。

![\[GPU 监控已开启 CloudWatch\]](http://docs.aws.amazon.com/zh_cn/dlami/latest/devguide/images/gpumon.png)


您可能对有关 GPU 监控和优化的以下其他主题感兴趣：
+ [监控](tutorial-gpu-monitoring.md)
  + [GPUs 使用监视器 CloudWatch](#tutorial-gpu-monitoring-gpumon)
+ [优化](tutorial-gpu-opt.md)
  + [预处理](tutorial-gpu-opt-preprocessing.md)
  + [训练](tutorial-gpu-opt-training.md)

# 优化
<a name="tutorial-gpu-opt"></a>

要充分利用您的数据 GPUs，您可以优化数据管道并调整深度学习网络。如以下图表所述，神经网络的简单或基本实施对 GPU 的使用可能会不一致且不充分。当您优化预处理和数据加载时，您可以从您的 CPU 到 GPU 减少瓶颈。您可以通过使用混合化（该框架支持时）、调整批大小并同步调用来调整神经网络本身。您也可以在大多数框架中使用多精度（float16 或 int8）训练，从而可以显著提高吞吐量。

以下图表显示应用不同优化时的累积性能提升。您的结果将取决于要处理的数据和要优化的网络。

![\[的性能增强 GPUs\]](http://docs.aws.amazon.com/zh_cn/dlami/latest/devguide/images/performance-enhancements.png)


以下指南介绍将使用您的 DLAMI 并帮助您提升 GPU 性能的选项。

**Topics**
+ [预处理](tutorial-gpu-opt-preprocessing.md)
+ [训练](tutorial-gpu-opt-training.md)

# 预处理
<a name="tutorial-gpu-opt-preprocessing"></a>

通过转换或扩增的数据预处理通常可以是一个绑定 CPU 的流程，而且这可以是您的整体管道中的瓶颈。框架具有用于图像处理的内置运算符，但 DALI（数据扩增库）通过框架的内置选项展示了改进的性能。
+ NVIDIA 数据扩增库 (DALI)：DALI 将数据扩增卸载到 GPU。该项未预安装在 DLAMI 上，但您可以通过安装它或在您的 DLAMI 或其他 Amazon Elastic Compute Cloud 实例上加载支持的框架容器来访问它。有关详细信息，请参阅 NVIDIA 网站上的 [DALI 项目页面](https://docs.nvidia.com/deeplearning/sdk/dali-install-guide/index.html)。有关示例用例和下载代码示例，请参阅[ SageMaker 预处理训练](https://github.com/aws-samples/sagemaker-cv-preprocessing-training-performance)性能示例。
+ nvJPEG：一个面向 C 编程人员的 GPU 加速型 JPEG 解码器库。它支持解码单个图像或批处理以及深度学习中常见的后续转换操作。nvJPEG 具有内置 DALI，或者您可以从 [NVIDIA 网站的 nvjpeg 页面](https://developer.nvidia.com/nvjpeg)下载并单独使用它。

您可能对有关 GPU 监控和优化的以下其他主题感兴趣：
+ [监控](tutorial-gpu-monitoring.md)
  + [GPUs 使用监视器 CloudWatch](tutorial-gpu-monitoring-gpumon.md)
+ [优化](tutorial-gpu-opt.md)
  + [预处理](#tutorial-gpu-opt-preprocessing)
  + [训练](tutorial-gpu-opt-training.md)

# 训练
<a name="tutorial-gpu-opt-training"></a>

利用混合精度训练，您可以使用相同的内存量部署更大的网络，或者减少内存使用量（与您的单精度或双精度网络相比），并且您将看到计算性能增加。您还将受益于更小且更快的数据传输，这在多节点分布式训练中是一个重要因素。要利用混合精度训练，您需要调整数据转换和损失比例。以下是介绍如何针对支持混合精度的框架执行此操作的指南。
+ [NVIDIA 深度学习 SDK](https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/) ——NVIDIA 网站上描述了 MXNet PyTorch、和的混合精度实现的文档。 TensorFlow

**提示**  
请务必针对您选择的框架检查网站，并且搜索“混合精度”或“fp16”，了解最新的优化方法。下面是可能对您有帮助的一些混合精度指南：  
[混合精度训练 TensorFlow （视频）](https://devblogs.nvidia.com/mixed-precision-resnet-50-tensor-cores/)-在 NVIDIA 博客网站上。
[使用 float16 进行混合精度训练，其中包含网站 MXNet](https://mxnet.apache.org/api/faq/float16)上的常见问题解答文章。 MXNet 
[NVIDIA Apex：一款用于轻松进行混合精度训练的工具 PyTorch](https://devblogs.nvidia.com/apex-pytorch-easy-mixed-precision-training/) ——NVIDIA 网站上的一篇博客文章。

您可能对有关 GPU 监控和优化的以下其他主题感兴趣：
+ [监控](tutorial-gpu-monitoring.md)
  + [GPUs 使用监视器 CloudWatch](tutorial-gpu-monitoring-gpumon.md)
+ [优化](tutorial-gpu-opt.md)
  + [预处理](tutorial-gpu-opt-preprocessing.md)
  + [训练](#tutorial-gpu-opt-training)

# 带有 DLAMI 的 AWS 推理芯片
<a name="tutorial-inferentia"></a>

AWS Inferentia 是一款由其设计的自定义机器学习芯片 AWS ，可用于高性能的推理预测。 要使用该芯片，请设置亚马逊弹性计算云实例，然后使用 Ne AWS uron 软件开发套件 (SDK) 调用 Inferentia 芯片。为了向客户提供最佳 Inferentia 体验，Neuron 已内置在 AWS Deep Learning AMIs (DLAMI) 中。

以下主题将向您展示如何开始将 Inferentia 与 DLAMI 结合使用。

**Topics**
+ [启动带有神经元的 DLAMI 实例 AWS](tutorial-inferentia-launching.md)
+ [将 DLAMI 与神经元一起使用 AWS](tutorial-inferentia-using.md)

# 启动带有神经元的 DLAMI 实例 AWS
<a name="tutorial-inferentia-launching"></a>

 最新的 DLAMI 已准备好 AWS 与 Inferentia 一起使用，并附带 Neuron API 包。 AWS 要启动 DLAMI 实例，请参阅[启动和配置 DLAMI](https://docs.aws.amazon.com/dlami/latest/devguide/launch-config.html)。获得 DLAMI 后，请使用此处的步骤确保 AWS 您的推理芯片 AWS 和 Neuron 资源处于活动状态。

**Topics**
+ [验证您的实例](#tutorial-inferentia-launching-verify)
+ [识别 AWS 推理设备](#tutorial-inferentia-launching-identify)
+ [查看资源使用量](#tutorial-inferentia-launching-resource-usage)
+ [使用 Neuron Monitor（Neuron 监视器）](#tutorial-inferentia-launching-neuron-monitor)
+ [升级 Neuron 软件](#tutorial-inferentia-launching-upgrade)

## 验证您的实例
<a name="tutorial-inferentia-launching-verify"></a>

 在使用您的实例之前，验证该实例是否已针对 Neuron 进行正确的设置和配置。

## 识别 AWS 推理设备
<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 实例，包括以下各列：
+ 神经元设备：分配给的逻辑 ID。 NeuronDevice此 ID 用于将多个运行时配置为使用不同的 NeuronDevices运行时。
+ NEURON CORE： NeuronCores 存在于 NEURON CORES 中的 NeuronDevice数量。
+ 神经元内存：中的 DRAM 内存量。 NeuronDevice
+ 连接的设备：其他 NeuronDevices 连接到 NeuronDevice。
+ PCI BDF：的 PCI 总线设备功能 (BDF) ID。 NeuronDevice

## 查看资源使用量
<a name="tutorial-inferentia-launching-resource-usage"></a>

 使用命令查看有关 NeuronCore vCPU 利用率、内存使用率、已加载模型和 Neuron 应用程序的有用信息。`neuron-top`不`neuron-top`带参数启动将显示所有使用的机器学习应用程序的数据 NeuronCores。

```
neuron-top
```

 当应用程序使用四时 NeuronCores，输出应类似于下图：

![\[neuron-top命令的输出，其中一个命令的信息 NeuronCores 突出显示。\]](http://docs.aws.amazon.com/zh_cn/dlami/latest/devguide/images/neuron-top-output.png)


有关用于监控和优化基于 Neuron 的推理应用程序的资源的更多信息，请参阅 [Neuron 工具](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-guide/neuron-tools/index.html)。

## 使用 Neuron Monitor（Neuron 监视器）
<a name="tutorial-inferentia-launching-neuron-monitor"></a>

Neuron Monitor 从系统上运行的 Neuron 运行时系统收集指标，并将收集的数据以 JSON 格式流式传输到 stdout。这些指标按指标组进行组织，您可以通过提供配置文件进行配置。有关 Neuron Monitor 的更多信息，请参阅 [Neuron Monitor 用户指南](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 《神经元设置指南》。](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-intro/neuron-install-guide.html)

**下一个步骤**  
[将 DLAMI 与神经元一起使用 AWS](tutorial-inferentia-using.md)

# 将 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']
```

# ARM64 DLAMI
<a name="tutorial-arm64"></a>

AWS ARM64 GPU 旨在 DLAMIs 为深度学习工作负载提供高性能和成本效益。具体而言，g5G 实例类型采用基于 ARM64 的 G [AWS raviton2 处理器，该处理器](https://aws.amazon.com/ec2/graviton/)是从头开始构建的， AWS 并针对客户在云中运行工作负载的方式进行了优化。 AWS ARM64 GPU DLAMIs 预先配置了 Docker、NVIDIA Docker、NVIDIA Driver、CUDA、cuDNN、NCCL 以及流行的机器学习框架，例如和。 TensorFlow PyTorch

借助 G5g 实例类型，您可以利用 Graviton2 的价格和性能优势来部署基于 GPU 加速的深度学习模型，与基于 x86 的带有 GPU 加速的实例相比，成本大幅降低。

## 选择一个 ARM64 DLAMI
<a name="tutorial-arm64-select-dlami"></a>

使用您选择的 D ARM64 LAMI 启动 [g5G 实例](https://aws.amazon.com/ec2/instance-types/g5g/)。

有关启动 DLAMI 的 step-by-step说明，[请参阅启动和配置](https://docs.aws.amazon.com/dlami/latest/devguide/launch-config.html) DLAMI。

有关最新版本的列表 ARM64 DLAMIs，请参阅 [DLAMI 发行说明](https://docs.aws.amazon.com/dlami/latest/devguide/appendix-ami-release-notes.html)。

## 开始使用
<a name="tutorial-arm64-get-started"></a>

以下主题向您展示了如何开始使用 ARM64 DLAMI。

**Topics**
+ [选择一个 ARM64 DLAMI](#tutorial-arm64-select-dlami)
+ [开始使用](#tutorial-arm64-get-started)
+ [使用 ARM64 GPU PyTorch DLAMI](tutorial-arm64-pytorch.md)

# 使用 ARM64 GPU PyTorch DLAMI
<a name="tutorial-arm64-pytorch"></a>

已准备好在基 AWS Deep Learning AMIs 于 Arm64 处理器的情况下使用 GPUs，并针对以下方面进行了优化。 PyTorch ARM64 GPU PyTorch DLAMI 包括一个预先配置了、和的 Python 环境 [TorchVision](https://pytorch.org/vision/stable/index.html)，用于深度学习训练[TorchServe](https://pytorch.org/serve/)和推理[PyTorch](https://aws.amazon.com/pytorch)用例。

**Topics**
+ [验证 PyTorch Python 环境](#tutorial-arm64-pytorch-environment)
+ [使用运行训练示例 PyTorch](#tutorial-arm64-pytorch-training)
+ [使用运行推理示例 PyTorch](#tutorial-arm64-pytorch-inference)

## 验证 PyTorch Python 环境
<a name="tutorial-arm64-pytorch-environment"></a>

使用以下命令来连接您的 G5g 实例并激活基础 Conda 环境：

```
source activate base
```

您的命令提示符应表明您正在基本 Conda 环境中工作，该环境包含 PyTorch TorchVision、和其他库。

```
(base) $
```

验证 PyTorch 环境的默认刀具路径：

```
(base) $ which python
(base) $ which pip
(base) $ which conda
(base) $ which mamba
>>> import torch, torchvision
>>> torch.__version__
>>> torchvision.__version__
>>> v = torch.autograd.Variable(torch.randn(10, 3, 224, 224))
>>> v = torch.autograd.Variable(torch.randn(10, 3, 224, 224)).cuda()
>>> assert isinstance(v, torch.Tensor)
```

## 使用运行训练示例 PyTorch
<a name="tutorial-arm64-pytorch-training"></a>

运行示例 MNIST 训练作业：

```
git clone https://github.com/pytorch/examples.git
cd examples/mnist
python main.py
```

您的输出应类似于以下内容：

```
...
Train Epoch: 14 [56320/60000 (94%)]    Loss: 0.021424
Train Epoch: 14 [56960/60000 (95%)]    Loss: 0.023695
Train Epoch: 14 [57600/60000 (96%)]    Loss: 0.001973
Train Epoch: 14 [58240/60000 (97%)]    Loss: 0.007121
Train Epoch: 14 [58880/60000 (98%)]    Loss: 0.003717
Train Epoch: 14 [59520/60000 (99%)]    Loss: 0.001729
Test set: Average loss: 0.0275, Accuracy: 9916/10000 (99%)
```

## 使用运行推理示例 PyTorch
<a name="tutorial-arm64-pytorch-inference"></a>

使用以下命令下载预训练的 densenet161 模型并使用以下命令运行推理： TorchServe

```
# Set up TorchServe
cd $HOME
git clone https://github.com/pytorch/serve.git
mkdir -p serve/model_store
cd serve

# Download a pre-trained densenet161 model
wget https://download.pytorch.org/models/densenet161-8d451a50.pth >/dev/null

# Save the model using torch-model-archiver
torch-model-archiver --model-name densenet161 \
    --version 1.0 \
    --model-file examples/image_classifier/densenet_161/model.py \
    --serialized-file densenet161-8d451a50.pth \
    --handler image_classifier \
    --extra-files examples/image_classifier/index_to_name.json  \
    --export-path model_store 

# Start the model server
torchserve --start --no-config-snapshots \
    --model-store model_store \
    --models densenet161=densenet161.mar &> torchserve.log

# Wait for the model server to start
sleep 30

# Run a prediction request
curl http://127.0.0.1:8080/predictions/densenet161 -T examples/image_classifier/kitten.jpg
```

您的输出应类似于以下内容：

```
{
  "tiger_cat": 0.4693363308906555,
  "tabby": 0.4633873701095581,
  "Egyptian_cat": 0.06456123292446136,
  "lynx": 0.0012828150065615773,
  "plastic_bag": 0.00023322898778133094
}
```

使用以下命令来注销 densenet161 模型并停止服务器：

```
curl -X DELETE http://localhost:8081/models/densenet161/1.0
torchserve --stop
```

您的输出应类似于以下内容：

```
{
  "status": "Model \"densenet161\" unregistered"
}
TorchServe has stopped.
```

# 推理
<a name="tutorial-inference"></a>

此部分提供了有关如何使用 DLAMI 的框架和工具来运行推理的教程。

## 推理工具
<a name="tutorial-inference-tools"></a>
+ [TensorFlow 上菜](tutorial-tfserving.md)

# 模型处理
<a name="model-serving"></a>

以下是已在带 Conda 的深度学习 AMI 上安装的模型处理选项。单击其中一个选项可了解如何使用该选项。

**Topics**
+ [TensorFlow 上菜](tutorial-tfserving.md)
+ [TorchServe](tutorial-torchserve.md)

# TensorFlow 上菜
<a name="tutorial-tfserving"></a>

TensorFlow S@@ [er](https://www.tensorflow.org/tfx/guide/serving) ving 是一款适用于机器学习模型的灵活、高性能的服务系统。

`tensorflow-serving-api` 预先安装了单一框架 DLAMI。要使用 tensorflow 服务，请先激活环境。 TensorFlow 

```
$ source /opt/tensorflow/bin/activate
```

然后，使用您的首选文本编辑器创建具有以下内容的脚本。将它命名为 `test_train_mnist.py`。此脚本引自[TensorFlow 教程，该教程](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/quickstart/beginner.ipynb)将训练和评估对图像进行分类的神经网络机器学习模型。

```
import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
```

现在，运行将服务器位置和端口以及哈士奇照片的文件名作为参数传递的脚本。

```
$ /opt/tensorflow/bin/python3 test_train_mnist.py
```

 请耐心等待，因为此脚本可能需要一段时间才能提供输出。在训练完成后，您应该看到以下内容：

```
I0000 00:00:1739482012.389276    4284 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.
1875/1875 [==============================] - 24s 2ms/step - loss: 0.2973 - accuracy: 0.9134 
Epoch 2/5
1875/1875 [==============================] - 3s 2ms/step - loss: 0.1422 - accuracy: 0.9582
Epoch 3/5
1875/1875 [==============================] - 3s 1ms/step - loss: 0.1076 - accuracy: 0.9687
Epoch 4/5
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0872 - accuracy: 0.9731
Epoch 5/5
1875/1875 [==============================] - 3s 1ms/step - loss: 0.0731 - accuracy: 0.9771
313/313 [==============================] - 0s 1ms/step - loss: 0.0749 - accuracy: 0.9780
```

## 更多功能和示例
<a name="tutorial-tfserving-project"></a>

如果您有兴趣了解有关 TensorFlow 服务的更多信息，请[TensorFlow 访问网站](https://www.tensorflow.org/serving/)。

# TorchServe
<a name="tutorial-torchserve"></a>

TorchServe 是一款灵活的工具，用于提供已从中导出的深度学习模型 PyTorch。 TorchServe 预装了带有 Conda 的深度学习 AMI。

有关使用的更多信息 TorchServe，[请参阅 PyTorch文档模型服务器](https://github.com/pytorch/serve/blob/master/docs/README.md)。

 **主题** 

## 在上提供图像分类模型 TorchServe
<a name="tutorial-torchserve-serving"></a>

本教程介绍如何使用提供图像分类模型 TorchServe。它使用提供的 DenseNet -161 模型。 PyTorch 服务器运行后，它会监听预测请求。在这种情况下，如果您上传图像（一张小猫的图像），服务器会返回在其上训练该模型的类中匹配的前 5 个类的预测。

**在上提供图像分类模型示例 TorchServe**

1. 使用带 Conda 的深度学习 AMI（v34 或更高版本）来连接到 Amazon Elastic Compute Cloud (Amazon EC2) 实例。

1. 激活 `pytorch_p310` 环境。

   ```
   source activate pytorch_p310
   ```

1. 克隆 TorchServe 存储库，然后创建一个目录来存储您的模型。  

   ```
   git clone https://github.com/pytorch/serve.git
   mkdir model_store
   ```

1. 使用模型存档程序来存档模型。该`extra-files`参数使用`TorchServe`存储库中的文件，因此如有必要，请更新路径。 有关模型存档器的更多信息，请参阅 [Torch 模型存档器](https://github.com/pytorch/serve/blob/master/model-archiver/README.md)。 TorchServe

   ```
   wget https://download.pytorch.org/models/densenet161-8d451a50.pth
   torch-model-archiver --model-name densenet161 --version 1.0 --model-file ./serve/examples/image_classifier/densenet_161/model.py --serialized-file densenet161-8d451a50.pth --export-path model_store --extra-files ./serve/examples/image_classifier/index_to_name.json --handler image_classifier
   ```

1. 运行 TorchServe 以启动终端节点。添加 `> /dev/null` 会使日志输出静音。

   ```
   torchserve --start --ncs --model-store model_store --models densenet161.mar > /dev/null
   ```

1. 下载小猫的图像并将其发送到 TorchServe预测端点：

   ```
   curl -O https://s3.amazonaws.com/model-server/inputs/kitten.jpg
   curl http://127.0.0.1:8080/predictions/densenet161 -T kitten.jpg
   ```

   该预测终端节点将返回一个 JSON 格式的预测（类似于下面的前 5 个预测），其中，图像具有 47% 的可能性为埃及猫，然后有 46% 的可能性为虎斑猫。

   ```
   {
    "tiger_cat": 0.46933576464653015,
    "tabby": 0.463387668132782,
    "Egyptian_cat": 0.0645613968372345,
    "lynx": 0.0012828196631744504,
    "plastic_bag": 0.00023323058849200606
   }
   ```

1. 当您完成测试时，停止服务器：

   ```
   torchserve --stop
   ```

 **其他示例** 

TorchServe 提供了各种各样的示例，您可以在 DLAMI 实例上运行这些示例。您可以在[ TorchServe项目存储库示例页面上](https://github.com/pytorch/serve/tree/master/examples)查看它们。

 **更多信息** 

 有关更多 TorchServe 文档，包括如何 TorchServe使用 Docker 进行设置和最新 TorchServe 功能，请参阅[上的 TorchServe GitHub项目页面](https://github.com/pytorch/serve)。