

# 在 Amazon ECS 任务定义中指定 GPU 数
<a name="ecs-gpu-specifying"></a>

要在容器实例和 Docker GPU 运行时上使用 GPU，请确保在任务定义中指定容器所需的 GPU 数量。由于已放置支持 GPU 的容器，Amazon ECS 容器代理会将所需数量的物理 GPU 固定到相应的容器中。为某个任务中的所有容器预留的 GPU 的数量不能超过该任务在其上启动的容器实例的可用 GPU 的数量。有关更多信息，请参阅 [使用控制台创建 Amazon ECS 任务定义](create-task-definition.md)。

**重要**  
如果任务定义中未指定 GPU 要求，则任务将使用原定设置 Docker 运行时。

下面显示了任务定义中的 GPU 要求的 JSON 格式：

```
{
  "containerDefinitions": [
     {
        ...
        "resourceRequirements" : [
            {
               "type" : "GPU", 
               "value" : "2"
            }
        ],
     },
...
}
```

以下示例演示了指定 GPU 要求的 Docker 容器的语法。此容器使用两个 GPU，运行 `nvidia-smi` 实用程序，然后退出。

```
{
  "containerDefinitions": [
    {
      "memory": 80,
      "essential": true,
      "name": "gpu",
      "image": "nvidia/cuda:11.0.3-base",
      "resourceRequirements": [
         {
           "type":"GPU",
           "value": "2"
         }
      ],
      "command": [
        "sh",
        "-c",
        "nvidia-smi"
      ],
      "cpu": 100
    }
  ],
  "family": "example-ecs-gpu"
}
```

以下示例任务定义展示了一个打印可用 GPU 数量的 TensorFlow 容器。该任务在 Amazon ECS 托管实例上运行，需要一个 GPU，并使用 `g4dn.xlarge` 实例。

```
{
  "family": "tensorflow-gpu",
  "networkMode": "awsvpc",
  "executionRoleArn": "arn:aws:iam::account-id:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "name": "tensorflow",
      "image": "tensorflow/tensorflow:latest-gpu",
      "essential": true,
      "command": [
        "python",
        "-c",
        "import tensorflow as tf; print('Num GPUs Available: ', len(tf.config.list_physical_devices('GPU')))"
      ],
      "resourceRequirements": [
        {
          "type": "GPU",
          "value": "1"
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/tensorflow-gpu",
          "awslogs-region": "region",
          "awslogs-stream-prefix": "ecs"
        }
      }
    }
  ],
  "requiresCompatibilities": [
    "MANAGED_INSTANCES"
  ],
  "cpu": "4096",
  "memory": "8192",
}
```