

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

# 带有自定义训练算法的容器
<a name="your-algorithms-training-algo"></a>

本节介绍了 Amazon SageMaker AI 如何与运行您的自定义训练算法的 Docker 容器进行交互。使用此信息编写代码并为训练算法创建 Docker 镜像。

**Topics**
+ [Amazon SageMaker AI 如何运行你的训练图像](your-algorithms-training-algo-dockerfile.md)
+ [Amazon SageMaker AI 如何提供培训信息](your-algorithms-training-algo-running-container.md)
+ [使用 EFA 运行训练](your-algorithms-training-efa.md)
+ [Amazon A SageMaker I 如何发出算法成功和失败的信号](your-algorithms-training-signal-success-failure.md)
+ [Amazon SageMaker AI 如何处理训练输出](your-algorithms-training-algo-output.md)

# Amazon SageMaker AI 如何运行你的训练图像
<a name="your-algorithms-training-algo-dockerfile"></a>

您可以使用自定义入口点脚本来自动配置基础设施，以便在生产环境中进行训练。如果您将入口点脚本传递到 Docker 容器中，也可以将其作为独立脚本运行，而无需重新构建映像。 SageMaker AI 使用 Docker 容器入口点脚本处理你的训练图像。

本节将介绍如何无需训练工具包来使用自定义入口点。如果您想使用自定义入口点，但不熟悉如何手动配置 Docker 容器，我们建议您改用[SageMaker 培训](https://github.com/aws/sagemaker-training-toolkit)工具包库。有关如何使用训练工具包的更多信息，请参阅 [调整自己的训练容器](adapt-training-container.md)。

默认情况下， SageMaker AI 会在您的容器`train`内查找一个名为的脚本。您也可以使用 API 的`ContainerArguments`和`ContainerEntrypoint`参数手动提供自己的自定义入口点。[AlgorithmSpecification](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AlgorithmSpecification.html)

您可以采用以下两个选项来手动配置 Docker 容器以运行您的映像。
+ 使用 [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)API 和包含入口点指令的 Docker 容器。
+ 使用 `CreateTrainingJob` API，然后从 Docker 容器外部传递您的训练脚本。

如果您从 Docker 容器外部传递您的训练脚本，则在更新脚本时无需重新构建 Docker 容器。您也可以使用多个不同的脚本在同一个容器中运行。

您的入口点脚本应包含映像的训练代码。如果您在[估算器](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html)中使用可选的 `source_dir` 参数，则它应引用相对 Amazon S3 路径，指向包含入口点脚本的文件夹。您可以使用 `source_dir` 参数引用多个文件。如果您不使用 `source_dir`，可以使用 `entry_point` 参数指定入口点。有关包含估算器的自定义入口点脚本的示例，请参阅使用 AI [脚本模式自带 SageMaker 模型](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-script-mode/sagemaker-script-mode.html)。

SageMaker AI 模型训练支持高性能 S3 Express One Zone 目录存储桶作为文件模式、快速文件模式和管道模式的数据输入位置。您还可以使用 S3 Express One Zone 目录存储桶来存储训练输出。要使用 S3 Express One Zone，请提供 S3 Express One Zone 目录存储桶的 URI，而不是 Amazon S3 通用存储桶的 URI。您只能使用 Amazon S3 托管密钥 (SSE-S3) 通过服务器端加密对目录存储桶中的 A SageMaker I 输出数据进行加密。目前不支持使用 AWS KMS 密钥进行服务器端加密 (SSE-KMS)，以将 SageMaker AI 输出数据存储在目录存储桶中。有关更多信息，请参阅 [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html)。

## 使用 Docker 容器内部捆绑的入口点脚本运行训练作业
<a name="your-algorithms-training-algo-dockerfile-api-ep-in"></a>

SageMaker AI 可以运行捆绑在 Docker 容器中的入口点脚本。
+ 默认情况下，Amazon SageMaker AI 运行以下容器。

  ```
  docker run image train
  ```
+ SageMaker AI 通过在图像名称后指定`train`参数来覆盖容器中的任何默认 [CMD](https://docs.docker.com/engine/reference/builder/#cmd) 语句。在您的 Docker 容器中，使用 `ENTRYPOINT` 指令的 `exec` 形式：

  ```
  ENTRYPOINT ["executable", "param1", "param2", ...]
  ```

  以下示例显示如何指定名为 `k-means-algorithm.py` 的 Python 入口点指令。

  ```
  ENTRYPOINT ["python", "k-means-algorithm.py"]
  ```

  `exec` 形式的 `ENTRYPOINT` 指令直接启动可执行文件，而不是 `/bin/sh` 的子级。这使它能够接收类似`SIGTERM`和`SIGKILL`来自的信号 SageMaker APIs。使用时，以下条件适用 SageMaker APIs。
  + [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)API 具有停止条件，可指示 SageMaker AI 在特定时间后停止模型训练。
  + 下面显示了 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_StopTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_StopTrainingJob.html) API。此 API 发出与 `docker stop`（具有 2 分钟超时）等效的命令，以便正常停止指定容器：

    ```
    docker stop -t 120
    ```

    该命令尝试通过发送 `SIGTERM` 信号来停止正在运行的容器。在 2 分钟的超时时间后，API 会发送 `SIGKILL`，然后强行停止容器。如果容器正常处理了 `SIGTERM` 并在收到信号后的 120 秒内退出，则不会发送 `SIGKILL`。

  如果您想在 SageMaker AI 停止训练后访问中间模型工件，请添加代码来处理在处理程序中保存工件`SIGTERM`的问题。
+ 如果您计划使用 GPU 设备进行模型训练，请确保您的容器与 `nvidia-docker` 兼容。容器上仅包含 CUDA 工具包；不要将 NVIDIA 驱动程序与映像捆绑。有关 `nvidia-docker` 的更多信息，请参阅 [NVIDIA/nvidia-docker](https://github.com/NVIDIA/nvidia-docker)。
+ 你不能在 SageMaker AI 容器中使用`tini`初始化器作为入口点脚本，因为它会被和参数所`train`混淆。`serve`
+ `/opt/ml`并且所有子目录均由 SageMaker 训练保留。在您构建算法的 Docker 映像时，请确保不要在此目录中放置算法所需的任何数据。因为如果这样做，则在训练期间数据可能不再可见。

要将 shell 或 Python 脚本捆绑在 Docker 映像中，或者要在 Amazon S3 存储桶中提供脚本或使用 AWS Command Line Interface (CLI)，请继续阅读以下部分。

### 在 Docker 容器内部捆绑您的 Shell 脚本
<a name="your-algorithms-training-algo-dockerfile-script-sh"></a>

 如果您要在 Docker 映像内部捆绑自定义 Shell 脚本，请使用以下步骤。

1. 将 Shell 脚本从工作目录复制到 Docker 容器内部。以下代码片段将自定义入口点脚本 `custom_entrypoint.sh` 从当前工作目录，复制到位于 `mydir` 中的 Docker 容器。以下示例假定基本 Docker 映像已安装 Python。

   ```
   FROM <base-docker-image>:<tag>
   
   # Copy custom entrypoint from current dir to /mydir on container
   COPY ./custom_entrypoint.sh /mydir/
   ```

1. 按照《Amazon ECR 用户指南》**中[推送 Docker 映像](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)的说明，构建 Docker 容器并将其推送到 Amazon Elastic Container Registry ([Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html))。

1. 通过运行以下 AWS CLI 命令启动训练作业。

   ```
   aws --region <your-region> sagemaker create-training-job \
   --training-job-name <your-training-job-name> \
   --role-arn <your-execution-role-arn> \
   --algorithm-specification '{ \ 
       "TrainingInputMode": "File", \
       "TrainingImage": "<your-ecr-image>", \
       "ContainerEntrypoint": ["/bin/sh"], \
       "ContainerArguments": ["/mydir/custom_entrypoint.sh"]}' \
   --output-data-config '{"S3OutputPath": "s3://custom-entrypoint-output-bucket/"}' \
   --resource-config '{"VolumeSizeInGB":10,"InstanceCount":1,"InstanceType":"ml.m5.2xlarge"}' \
   --stopping-condition '{"MaxRuntimeInSeconds": 180}'
   ```

### 在 Docker 容器内部捆绑您的 Python 脚本
<a name="your-algorithms-training-algo-dockerfile-script-py"></a>

要在 Docker 映像内部捆绑自定义 Python 脚本，请使用以下步骤。

1. 将 Python 脚本从工作目录复制到 Docker 容器内部。以下代码片段将自定义入口点脚本 `custom_entrypoint.py` 从当前工作目录，复制到位于 `mydir` 中的 Docker 容器。

   ```
   FROM <base-docker-image>:<tag>
   # Copy custom entrypoint from current dir to /mydir on container
   COPY ./custom_entrypoint.py /mydir/
   ```

1. 通过运行以下 AWS CLI 命令启动训练作业。

   ```
   --algorithm-specification '{ \ 
       "TrainingInputMode": "File", \
       "TrainingImage": "<your-ecr-image>", \
       "ContainerEntrypoint": ["python"], \
       "ContainerArguments": ["/mydir/custom_entrypoint.py"]}' \
   ```

## 使用在 Docker 容器外部的入口点脚本运行训练作业
<a name="your-algorithms-training-algo-dockerfile-api-pass-ep"></a>

您可以使用自己的 Docker 容器进行训练，并将入口点脚本从 Docker 容器的外部传入。在容器之外构建入口点脚本有一些好处。如果您更新入口点脚本，则无需重新构建 Docker 容器。您也可以使用多个不同的脚本在同一个容器中运行。

使用 [AlgorithmSpecification](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AlgorithmSpecification.html)API 的`ContainerEntrypoint`和`ContainerArguments`参数指定训练脚本的位置。这些入口点和参数的行为方式与 Docker 入口点和参数相同。这些参数中的值会覆盖提供作为 Docker 容器一部分的对应 `ENTRYPOINT` 或 `CMD`。

当您将自定义入口点脚本传递给 Docker 训练容器时，您提供的输入决定了容器的行为。
+ 例如，如果您仅提供`ContainerEntrypoint`，则使用 CreateTrainingJob API 的请求语法如下所示。

  ```
  {
      "AlgorithmSpecification": {
          "ContainerEntrypoint": ["string"],   
          ...     
          }       
  }
  ```

  然后， SageMaker 训练后端按如下方式运行您的自定义入口点。

  ```
  docker run --entrypoint <ContainerEntrypoint> image
  ```
**注意**  
如果`ContainerEntrypoint`提供，则 SageMaker 训练后端使用给定的入口点运行图像并覆盖图像`ENTRYPOINT`中的默认值。
+ 如果您仅提供`ContainerArguments`，则 SageMaker AI 会假定 Docker 容器包含入口点脚本。使用 `CreateTrainingJob` API 的请求语法如下所示。

  ```
  {
      "AlgorithmSpecification": {
          "ContainerArguments": ["arg1", "arg2"],
          ...
      }
  }
  ```

   SageMaker 训练后端按如下方式运行您的自定义入口点。

  ```
  docker run image <ContainerArguments>
  ```
+ 如果您同时提供 `ContainerEntrypoint` 和 `ContainerArguments`，则使用 `CreateTrainingJob` API 的请求语法如下所示。

  ```
  {
      "AlgorithmSpecification": {
          "ContainerEntrypoint": ["string"],
          "ContainerArguments": ["arg1", "arg2"],
          ...
      }
  }
  ```

   SageMaker 训练后端按如下方式运行您的自定义入口点。

  ```
  docker run --entrypoint <ContainerEntrypoint> image <ContainerArguments>
  ```

您可以在 `CreateTrainingJob` API 中使用任何支持的 `InputDataConfig` 源，提供入口点脚本来运行您的训练映像。

### 在 Amazon S3 存储桶中提供您的入口点脚本
<a name="your-algorithms-training-algo-dockerfile-script-s3"></a>

 要使用 S3 存储桶提供自定义入口点脚本，请使用 [DataSource](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataSource.html#sagemaker-Type-DataSource-S3DataSource)API 的`S3DataSource`参数指定脚本的位置。如果使用 `S3DataSource` 参数，则需要以下信息。
+ [InputMode](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Channel.html#sagemaker-Type-Channel-InputMode)必须是该类型`File`。
+ S [3 DataDistributionType](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataSource.html#sagemaker-Type-DataSource-S3DataSource) 必须是`FullyReplicated`。

以下示例在 S3 存储桶的路径中放置了一个名为 custom\$1entrypoint.sh 的脚本：`s3://<bucket-name>/<bucket prefix>/custom_entrypoint.sh`。

```
#!/bin/bash
echo "Running custom_entrypoint.sh"
echo "Hello you have provided the following arguments: " "$@"
```

接下来，您必须设置输入数据通道的配置以运行训练作业。要执行此操作，可以 AWS CLI 直接使用，也可以使用 JSON 文件。

#### 使用 AWS CLI JSON 文件配置输入数据通道
<a name="your-algorithms-training-algo-dockerfile-script-s3-json"></a>

要使用 JSON 文件配置输入数据通道，请 AWS CLI 按以下代码结构所示使用。确保以下所有字段都使用 [CreateTrainingJob](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html#API_CreateTrainingJob_RequestSyntax)API 中定义的请求语法。

```
// run-my-training-job.json
{
 "[AlgorithmSpecification](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html#sagemaker-CreateTrainingJob-request-AlgorithmSpecification)": { 
        "ContainerEntrypoint": ["/bin/sh"],
        "ContainerArguments": ["/opt/ml/input/data/<your_channel_name>/custom_entrypoint.sh"],
         ...
   },
  "[InputDataConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html#sagemaker-CreateTrainingJob-request-InputDataConfig)": [ 
    { 
        "[ChannelName](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Channel.html#sagemaker-Type-Channel-ChannelName)": "<your_channel_name>",
        "[DataSource](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Channel.html#sagemaker-Type-Channel-DataSource)": { 
            "[S3DataSource](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataSource.html#sagemaker-Type-DataSource-S3DataSource)": { 
                "[S3DataDistributionType](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_S3DataSource.html#sagemaker-Type-S3DataSource-S3DataDistributionType)": "FullyReplicated",
                "[S3DataType](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_S3DataSource.html#sagemaker-Type-S3DataSource-S3DataType)": "S3Prefix",
                "[S3Uri](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_S3DataSource.html#sagemaker-Type-S3DataSource-S3Uri)": "s3://<bucket-name>/<bucket_prefix>"
            }
        },
        "[InputMode](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Channel.html#sagemaker-Type-Channel-InputMode)": "File",
    },
    ...]
}
```

接下来，运行 AWS CLI 命令从 JSON 文件启动训练作业，如下所示。

```
aws sagemaker create-training-job --cli-input-json file://run-my-training-job.json
```

#### AWS CLI 直接使用配置输入数据通道
<a name="your-algorithms-training-algo-dockerfile-script-s3-directly"></a>

要在没有 JSON 文件的情况下配置输入数据通道，请使用以下 AWS CLI 代码结构。

```
aws --region <your-region> sagemaker create-training-job \
--training-job-name <your-training-job-name> \
--role-arn <your-execution-role-arn> \
--algorithm-specification '{ \
    "TrainingInputMode": "File", \
    "TrainingImage": "<your-ecr-image>", \
    "ContainerEntrypoint": ["/bin/sh"], \
    "ContainerArguments": ["/opt/ml/input/data/<your_channel_name>/custom_entrypoint.sh"]}' \
--input-data-config '[{ \
    "ChannelName":"<your_channel_name>", \
    "DataSource":{ \
        "S3DataSource":{ \
            "S3DataType":"S3Prefix", \
            "S3Uri":"s3://<bucket-name>/<bucket_prefix>", \
            "S3DataDistributionType":"FullyReplicated"}}}]' \
--output-data-config '{"S3OutputPath": "s3://custom-entrypoint-output-bucket/"}' \
--resource-config '{"VolumeSizeInGB":10,"InstanceCount":1,"InstanceType":"ml.m5.2xlarge"}' \
--stopping-condition '{"MaxRuntimeInSeconds": 180}'
```

# Amazon SageMaker AI 如何提供培训信息
<a name="your-algorithms-training-algo-running-container"></a>

本节介绍了 SageMaker AI 如何将训练信息（例如训练数据、超参数和其他配置信息）提供给 Docker 容器。

当您向 A SageMaker I 发送启动模型训练的[https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html)请求时，您可以指定包含训练算法的 Docker 镜像的亚马逊弹性容器注册表 (Amazon ECR) Container Registry 路径。您还可以指定存储训练数据的亚马逊简单存储服务 (Amazon S3) 位置以及特定于算法的参数。 SageMaker AI 将这些信息提供给 Docker 容器，以便您的训练算法可以使用这些信息。本节介绍我们如何向您的 Docker 容器提供此信息。有关创建训练作业的信息，请参阅`CreateTrainingJob`。有关 SageMaker AI 容器组织信息的方式的更多信息，请参阅[SageMaker 训练和推理工具包](amazon-sagemaker-toolkits.md)。

**Topics**
+ [超参数](#your-algorithms-training-algo-running-container-hyperparameters)
+ [环境变量](#your-algorithms-training-algo-running-container-environment-variables)
+ [输入数据配置](#your-algorithms-training-algo-running-container-inputdataconfig)
+ [训练数据](#your-algorithms-training-algo-running-container-trainingdata)
+ [分布式训练配置](#your-algorithms-training-algo-running-container-dist-training)

## 超参数
<a name="your-algorithms-training-algo-running-container-hyperparameters"></a>

 SageMaker AI 使`CreateTrainingJob`请求中的超参数在文件的 Docker 容器中`/opt/ml/input/config/hyperparameters.json`可用。

以下是中用于在`CreateTrainingJob`操作中`hyperparameters.json`指定`num_round`和超参数的`eta`超参数配置示例。[XGBoost](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html)

```
{
    "num_round": "128",
    "eta": "0.001"
}
```

有关可用于 SageMaker AI 内置 XGBoost 算法的超参数的完整列表，请参阅[XGBoost超](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost_hyperparameters.html)参数。

您可以调整的超参数取决于所训练的算法。有关可用于 AI 内置算法的超参数列表，请在使用 A [ma SageMaker zon SageMaker AI 内置算法或预](https://docs.aws.amazon.com/sagemaker/latest/dg/algos.html)训练模型中的算法链接下的**超参数**中找到这些超参数。

## 环境变量
<a name="your-algorithms-training-algo-running-container-environment-variables"></a>

SageMaker AI 在您的容器中设置以下环境变量：
+ TRAINING\$1JOB\$1NAME – 在 `CreateTrainingJob` 请求中指定 `TrainingJobName` 参数。
+ TRAINING\$1JOB\$1ARN – 作为 `CreateTrainingJob` 响应中的 `TrainingJobArn` 返回的训练作业的 Amazon 资源名称 (ARN)。
+ 在 `CreateTrainingJob` 请求的 [Environment](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html#sagemaker-CreateTrainingJob-request-Environment) 参数中指定的所有环境变量。

## 输入数据配置
<a name="your-algorithms-training-algo-running-container-inputdataconfig"></a>

SageMaker AI 使`CreateTrainingJob`请求中`InputDataConfig`参数中的数据通道信息在 Docker 容器的`/opt/ml/input/config/inputdataconfig.json`文件中可用。

例如，假设您在请求中指定了三个数据通道（`train``evaluation`、和`validation`）。 SageMaker AI 提供了以下 JSON：

```
{
  "train" : {"ContentType":  "trainingContentType",
             "TrainingInputMode": "File",
             "S3DistributionType": "FullyReplicated",
             "RecordWrapperType": "None"},
  "evaluation" : {"ContentType":  "evalContentType",
                  "TrainingInputMode": "File",
                  "S3DistributionType": "FullyReplicated",
                  "RecordWrapperType": "None"},
  "validation" : {"TrainingInputMode": "File",
                  "S3DistributionType": "FullyReplicated",
                  "RecordWrapperType": "None"}
}
```

**注意**  
SageMaker AI 仅向容器提供有关每个数据通道的相关信息（例如频道名称和内容类型），如前面的示例所示。 `S3DistributionType`将设置为`FullyReplicated`将 EFS 或 FSx Lustre 指定为输入数据源。

## 训练数据
<a name="your-algorithms-training-algo-running-container-trainingdata"></a>

[https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) 请求中 `AlgorithmSpecification` 的参数 `TrainingInputMode` 指定了如何向容器提供训练数据集。有以下输入模式可用。
+ **`File` 模式**

  如果您使用`File`模式作为`TrainingInputMode`值， SageMaker AI 会在您的容器中设置以下参数。
  + 您的 `TrainingInputMode` 参数将写入到 `inputdataconfig.json` 中作为“File”。
  + 您的数据通道目录写入到 `/opt/ml/input/data/channel_name` 中。

  如果您使用`File`模式， SageMaker AI 会为每个频道创建一个目录。例如，如果你有三个名为、和`training``validation``testing`、的频道， SageMaker AI 会在你的 Docker 容器中创建以下三个目录：
  + `/opt/ml/input/data/training`
  + `/opt/ml/input/data/validation`
  + `/opt/ml/input/data/testing`

  `File` 还支持以下数据来源：
  + Amazon Simple Storage Service (Amazon S3)
  + Amazon Elastic File System (Amazon EFS)
  + 亚马逊 f FSx or Lustre
**注意**  
使用 Amazon EFS 和 Amazon 等文件系统数据源的渠道 FSx必须使用`File`模式。在这种情况下，通道中提供的目录路径挂载在 `/opt/ml/input/data/channel_name`。
+ **`FastFile` 模式**

  如果你使用`FastFile`模式作为你的`TrainingInputNodeParameter`， SageMaker AI 会在你的容器中设置以下参数。
  + 与 `File` 模式类似，在 `FastFile` 模式下，您的 `TrainingInputMode` 参数将写入到 `inputdataconfig.json` 中作为“File”。
  + 您的数据通道目录写入到 `/opt/ml/input/data/channel_name` 中。

  `FastFile` 模式支持以下数据来源：
  + Amazon S3

  如果您使用 `FastFile` 模式，则以只读权限挂载通道目录。

  过去，`File` 模式优先于 `FastFile` 模式。为了确保向后兼容性，只要在 `inputdataconfig.json.` 中将 `TrainingInputMode` 参数设置为 `File`，则支持 `File` 模式的算法也可以无缝地与 `FastFile` 模式配合使用。
**注意**  
使用 `FastFile` 模式的通道必须使用`S3DataType`“S3Prefix”。  
`FastFile` 模式显示了文件夹视图，使用正斜杠 (`/`) 作为将 Amazon S3 对象分组到文件夹中的分隔符。`S3Uri` 前缀不能对应于部分文件夹名称。例如，如果 Amazon S3 数据集包含 `s3://amzn-s3-demo-bucket/train-01/data.csv`，则 `s3://amzn-s3-demo-bucket/train` 或 `s3://amzn-s3-demo-bucket/train-01` 均不允许使用 `S3Uri` 前缀。  
建议使用结尾正斜杠来定义与文件夹对应的通道。例如，`train-01` 文件夹的 `s3://amzn-s3-demo-bucket/train-01/` 通道。如果没有结尾处的正斜杠，则如果存在其他文件夹 `s3://amzn-s3-demo-bucket/train-011/` 或文件 `s3://amzn-s3-demo-bucket/train-01.txt/`，就无法确定该通道。
+ **`Pipe` 模式**
  + `TrainingInputMode` 参数写入到 `inputdataconfig.json`：“Pipe”
  + Docker 容器中的数据通道目录：`/opt/ml/input/data/channel_name_epoch_number`
  + 支持的数据来源：Amazon S3

  您需要为每个通道从单独的管道中读取。例如，如果您有三个通道（分别名为 `training`、`validation` 和 `testing`），则需要从以下管道读取：
  + `/opt/ml/input/data/training_0, /opt/ml/input/data/training_1, ...`
  + `/opt/ml/input/data/validation_0, /opt/ml/input/data/validation_1, ...`
  + `/opt/ml/input/data/testing_0, /opt/ml/input/data/testing_1, ...`

  按顺序读取管道。例如，如果您有一个名为 `training` 的通道，请按以下顺序读取管道：

  1. `/opt/ml/input/data/training_0`在读取模式下打开并将其读入 end-of-file (EOF)，或者，如果您完成了第一个纪元，请尽早关闭管道文件。

  1. 关闭第一个管道文件后，请查找 `/opt/ml/input/data/training_1` 并读取它，直到您完成第二个纪元，以此类推。

  如果给定纪元的文件尚不存在，您的代码可能需要重试，直到创建该管道。各个通道类型没有顺序限制。例如，对于 `training` 通道，您可以读取多个纪元，并仅在准备好后才开始读取 `validation` 通道。或者，如果算法要求，您可以同时读取它们。

  有关展示自带容器时如何使用管道模式的 Jupyter 笔记本示例，请参阅将自己的管道模式[算法引入 Amazon AI](https://github.com/aws/amazon-sagemaker-examples/blob/main/advanced_functionality/pipe_bring_your_own/pipe_bring_your_own.ipynb)。 SageMaker 

  

SageMaker AI 模型训练支持高性能 S3 Express One Zone 目录存储桶作为文件模式、快速文件模式和管道模式的数据输入位置。要使用 S3 Express One Zone，请输入 S3 Express One Zone 目录存储桶的位置，而不是 Amazon S3 通用存储桶的位置。为具有所需访问控制和权限策略的 IAM 角色提供 ARN。有关详细信息，请参阅[AmazonSageMakerFullAccesspolicy](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonSageMakerFullAccess.html)。您只能使用 Amazon S3 托管密钥 (SSE-S3) 通过服务器端加密对目录存储桶中的 A SageMaker I 输出数据进行加密。目前不支持使用 AWS KMS 密钥进行服务器端加密 (SSE-KMS)，以将 SageMaker AI 输出数据存储在目录存储桶中。有关更多信息，请参阅 [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html)。

## 分布式训练配置
<a name="your-algorithms-training-algo-running-container-dist-training"></a>

如果您使用多个容器执行分布式训练， SageMaker AI 会在`/opt/ml/input/config/resourceconfig.json`文件中提供有关所有容器的信息。

为了启用容器间通信，此 JSON 文件包含所有容器的信息。 SageMaker AI 使该文件可用于模式算法`File`和`Pipe`模式算法。该文件提供以下信息：
+ `current_host` – 容器网络中的当前容器的名称。例如 `algo-1`。您可以随时更改主机值。不要使用此变量的特定值编写代码。
+ `hosts` – 容器网络中的所有容器的名称列表，按字典顺序排列。例如，`["algo-1", "algo-2", "algo-3"]` 用于三节点集群。容器可以使用这些名称来查找容器网络上的其他容器。您可以随时更改主机值。不要使用这些变量的特定值编写代码。
+ `network_interface_name` – 对您的容器公开的网络接口的名称。例如，运行消息传递接口 (MPI) 的容器可以使用该信息设置网络接口名称。
+ 请勿使用 `/etc/hostname` 或 `/etc/hosts` 中的信息，因为可能不准确。
+ 算法容器可能无法立即获得主机名信息。我们建议当节点在集群中可用时，在主机名解析操作上添加重试策略。

下面是三节点集群的节点 1 上的示例文件：

```
{
    "current_host": "algo-1",
    "hosts": ["algo-1","algo-2","algo-3"],
    "network_interface_name":"eth1"
}
```

# 使用 EFA 运行训练
<a name="your-algorithms-training-efa"></a>

 SageMaker AI 提供与 [EFA](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) 设备的集成，以加速高性能计算 (HPC) 和机器学习应用程序。通过这种集成，您可在运行分布式训练作业时利用 EFA 设备。您可以将 EFA 集成添加到您引入 SageMaker AI 的现有 Docker 容器中。以下信息概述了如何配置自己的容器，以便为分布式训练作业使用 EFA 设备。

## 先决条件
<a name="your-algorithms-training-efa-prereq"></a>

 您的容器必须满足[SageMaker 训练容器规范](https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo-dockerfile.html)。  

## 安装 EFA 和所需的软件包
<a name="your-algorithms-training-efa-install"></a>

您的容器必须下载并安装 [EFA 软件](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html)。这使您的容器能够识别 EFA 设备，并提供兼容版本的 Libfabric 和 Open MPI。

容器内必须安装和管理 MPI 和 NCCL 等任意工具，才能在启用 EFA 的训练作业中使用。有关所有可用 EFA 版本的列表，请参阅[使用校验和验证 EFA 安装程序](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-verify.html)。以下示例说明如何修改启用 EFA 的容器的 Dockerfile，以便安装 EFA、MPI、OFI、NCCL 和 NCCL-TEST。

**注意**  
在容器上 PyTorch 与 EFA 一起使用时，容器的 NCCL 版本应与安装的 NCCL 版本相匹配。 PyTorch 要验证 PyTorch NCCL 版本，请使用以下命令：  

```
torch.cuda.nccl.version()
```

```
ARG OPEN_MPI_PATH=/opt/amazon/openmpi/
ENV NCCL_VERSION=2.7.8
ENV EFA_VERSION=1.30.0
ENV BRANCH_OFI=1.1.1

#################################################
## EFA and MPI SETUP
RUN cd $HOME \
  && curl -O https://s3-us-west-2.amazonaws.com/aws-efa-installer/aws-efa-installer-${EFA_VERSION}.tar.gz \
  && tar -xf aws-efa-installer-${EFA_VERSION}.tar.gz \
  && cd aws-efa-installer \
  && ./efa_installer.sh -y --skip-kmod -g \

ENV PATH="$OPEN_MPI_PATH/bin:$PATH"
ENV LD_LIBRARY_PATH="$OPEN_MPI_PATH/lib/:$LD_LIBRARY_PATH"

#################################################
## NCCL, OFI, NCCL-TEST SETUP
RUN cd $HOME \
  && git clone https://github.com/NVIDIA/nccl.git -b v${NCCL_VERSION}-1 \
  && cd nccl \
  && make -j64 src.build BUILDDIR=/usr/local

RUN apt-get update && apt-get install -y autoconf
RUN cd $HOME \
  && git clone https://github.com/aws/aws-ofi-nccl.git -b v${BRANCH_OFI} \
  && cd aws-ofi-nccl \
  && ./autogen.sh \
  && ./configure --with-libfabric=/opt/amazon/efa \
       --with-mpi=/opt/amazon/openmpi \
       --with-cuda=/usr/local/cuda \
       --with-nccl=/usr/local --prefix=/usr/local \
  && make && make install
  
RUN cd $HOME \
  && git clone https://github.com/NVIDIA/nccl-tests \
  && cd nccl-tests \
  && make MPI=1 MPI_HOME=/opt/amazon/openmpi CUDA_HOME=/usr/local/cuda NCCL_HOME=/usr/local
```

## 创建容器时的注意事项
<a name="your-algorithms-training-efa-considerations"></a>

EFA 设备作为 `/dev/infiniband/uverbs0` 挂载到容器中，位于容器可访问的设备列表下。在 P4d 实例上，容器可以访问 4 个 EFA 设备。在容器能够访问的设备列表中可以找到 EFA 设备，如下所示：
+  `/dev/infiniband/uverbs0` 
+  `/dev/infiniband/uverbs1` 
+  `/dev/infiniband/uverbs2` 
+  `/dev/infiniband/uverbs3` 

 要从向每个容器实例提供的 `resourceconfig.json` 文件中获取主机名、对等连接主机名和网络接口（对于 MPI）等信息，请参阅[分布式训练配置](https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo-running-container.html#your-algorithms-training-algo-running-container-dist-training)。您的容器通过默认的弹性网络接口 (ENI) 处理对等连接之间的常规 TCP 流量，同时通过 EFA 设备处理 OFI（内核旁路）流量。

## 验证是否已识别您的 EFA 设备
<a name="your-algorithms-training-efa-verify"></a>

  要验证是否已识别 EFA 设备，请在容器内运行以下命令。

```
/opt/amazon/efa/bin/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
```

## 使用 EFA 运行训练作业
<a name="your-algorithms-training-efa-run"></a>

 创建支持 EFA 的容器后，您可以像处理任何其他 Docker 镜像一样使用 SageMaker AI 估算器使用 EFA 运行训练作业。有关注册容器并将其用于训练的更多信息，请参阅[调整您自己的训练容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html#byoc-training-step5)。

# Amazon A SageMaker I 如何发出算法成功和失败的信号
<a name="your-algorithms-training-signal-success-failure"></a>

一种指示是否成功使用其进程退出代码的训练算法。

成功训练执行在退出时的退出代码为 0，而不成功训练执行在退出时的退出代码为非零。在 `DescribeTrainingJob` 返回的 `TrainingJobStatus` 中，这些代码被转换为 `Completed` 和 `Failed`。此退出代码是标准惯例，对于所有语言均可轻松实施。例如，在 Python 中，您可以使用 `sys.exit(1)` 发出失败并退出信号，而仅运行至主例程结束将导致 Python 使用代码 0 退出。

如果失败，该算法可将关于失败的描述写入到失败文件。有关详细信息，请参阅下一节。

# Amazon SageMaker AI 如何处理训练输出
<a name="your-algorithms-training-algo-output"></a>

由于您的算法在容器中运行，它会生成包含训练作业状态以及模型和输出构件的输出。您的算法应将此信息写入到以下文件中，这些文件位于容器的 `/output` 目录。Amazon SageMaker AI 按如下方式处理此目录中包含的信息：
+ `/opt/ml/model`— 您的算法应将所有最终模型工件写入此目录。 SageMaker AI 将这些数据作为压缩的 tar 格式的单个对象复制到您在`CreateTrainingJob`请求中指定的 S3 位置。如果单个训练作业中有多个容器写入此目录，则应确保`file/directory`名称没有冲突。 SageMaker AI 将结果聚合到 TAR 文件中，并在训练作业结束时上传到 S3。
+ `/opt/ml/output/data`— 您的算法应将要存储的最终模型以外的工件写入此目录。 SageMaker AI 将这些数据作为压缩的 tar 格式的单个对象复制到您在`CreateTrainingJob`请求中指定的 S3 位置。如果单个训练作业中有多个容器写入此目录，则应确保`file/directory`名称没有冲突。 SageMaker AI 将结果聚合到 TAR 文件中，并在训练作业结束时上传到 S3。
+ `/opt/ml/output/failure` – 如果训练失败，当所有算法输出（例如日志记录）完成后，您的算法应将关于失败的描述写入到此文件。作为`DescribeTrainingJob`响应， SageMaker AI 将此文件中的前 1024 个字符返回为`FailureReason`。

您可以指定 S3 通用存储桶或 S3 目录存储桶来存储训练输出。目录存储桶仅使用 Amazon S3 Express One Zone 存储类，该类专为需要稳定的毫秒级延迟的工作负载或注重性能的应用程序而设计。选择最适合您的应用程序和性能要求的桶类型。有关 S3 目录存储桶的更多信息，请参阅[《Amazon Simple Storage Service 用户指南》](https://docs.aws.amazon.com/AmazonS3/latest/userguide/directory-buckets-overview.html)中的*目录存储桶*。

**注意**  
您只能使用 SageMaker Amazon S3 托管密钥 (SSE-S3) 通过服务器端加密来加密 S3 目录存储桶中的 AI 输出数据。目前不支持使用 AWS KMS 密钥进行服务器端加密 (SSE-KMS)，以将 SageMaker AI 输出数据存储在目录存储桶中。