

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 具有自訂訓練演算法的容器
<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 SageMaker AI 指出演算法成功和失敗的方式](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` 的指令碼。您也可以使用 [AlgorithmSpecification](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_AlgorithmSpecification.html) API 的 `ContainerArguments` 和 `ContainerEntrypoint` 參數，手動提供您的自訂進入點。

您可以使用以下兩個選項來手動配置 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` 參數指定進入點。如需包含估算器的自訂進入點指令碼範例，請參閱 [以 SageMaker AI 指令碼模式帶入自有模型](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 一般用途儲存貯體。您只能使用 Amazon S3 受管金鑰 (SSE-S3) 在伺服器端加密的目錄儲存貯體中加密 SageMaker AI 輸出資料。目前不支援使用 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"]
  ```

  `ENTRYPOINT` 指示的 `exec` 格式直啟動可執行檔，而非 `/bin/sh` 的子項。如此一來即可接收訊號，例如來自 SageMaker API 的 `SIGTERM` 與 `SIGKILL`。使用 SageMaker API 時，適用下列條件。
  + [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)。
+ 不可將 `tini` 初始設定式作為 SageMaker AI 容器的進入點指令碼，因為 `train` 和 `serve` 引數會混淆該設定式。
+ SageMaker 訓練會保留 `/opt/ml` 與所有子目錄。建立演算法的 Docker 映像檔時，請確定您沒有在此目錄中放置演算法所需的任何資料。因為如果您這樣做，在訓練期間可能會看不見這些資料。

若要在 Docker 映像中綁定 shell 或 Python 指令碼，或在 Amazon S3 儲存貯體中提供指令碼，或使用 AWS Command Line Interface (CLI)，請繼續下一節。

### 將您的 Shell 程式碼與 Docker 容器綁定
<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}'
   ```

### 將您的 Python 腳本與 Docker 容器綁定
<a name="your-algorithms-training-algo-dockerfile-script-py"></a>

請使用以下步驟將自訂的 Python 程式碼與 Docker 映像檔綁定。

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` 類型。
+ [S3DataDistributionType](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataSource.html#sagemaker-Type-DataSource-S3DataSource) 必須是 `FullyReplicated`。

下列範例會將名為 custom\$1entrypoint.sh 的指令碼放置在 S3 儲存貯體 `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 容器可以使用訓練資訊，如訓練資料、超參數和其他組態資訊等等。

當您將 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html) 請求傳送至 SageMaker AI 來啟動模型訓練時，您需要指定包含訓練演算法之 Docker 映像的 Amazon Elastic Container Registry (Amazon ECR) 路徑。您亦需指定 Amazon Simple Storage Service (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` 請求中的超參數可以在 `/opt/ml/input/config/hyperparameters.json` 檔案的 Docker 容器使用。

以下是 `hyperparameters.json` 中的超參數組態範例，用來指定在 `CreateTrainingJob` 作業中 [XGBoost](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html) 的 `num_round` 和 `eta` 超參數。

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

如需可用於 SageMaker AI 內建 XGBoost 演算法的超參數完整清單，請參閱 [XGBoost 超參數](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost_hyperparameters.html)。

您可以調整的超參數，依您正在訓練的演算法而定。如需可用於 SageMaker AI 內建演算法的超參數清單，可以在[使用 Amazon 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 – 訓練工作的 Amazon Resource Name (ARN)，會被傳回，以做為 `CreateTrainingJob` 回應中的 `TrainingJobArn`。
+ `CreateTrainingJob` 請求中[環境](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 僅會將各個資料通道的相關資訊 (例如通道名稱、內容類型) 提供給容器。若您指定 EFS 或 FSxLustre 作為輸入資料來源，`S3DistributionType` 將設為 `FullyReplicated`。

## 訓練資料
<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`。
  + 您的資料通道目錄被寫入 `/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)
  + Amazon FSx for Lustre
**注意**  
使用檔案系統資料來源 (例如 Amazon EFS 和 Amazon FSx) 的通道必須使用 `File` 模式。在這種情況下，通道中提供的目錄路徑掛載於 `/opt/ml/input/data/channel_name`。
+ **`FastFile` 模式**

  如果您使用 `FastFile` 模式作為您的 `TrainingInputNodeParameter`，SageMaker AI 會在您的容器中設定下列參數。
  + 與 `File` 模式類似，在 `FastFile` 模式下，您的 `TrainingInputMode` 參數以 “檔案” 形式被寫入 `inputdataconfig.json`。
  + 您的資料通道目錄被寫入 `/opt/ml/input/data/channel_name`。

  `FastFile` 模式支援下列資料來源。
  + Amazon S3

  如果您使用 `FastFile` 模式，通道目錄會以唯讀權限掛載。

  過去 `File` 模式一向早於 `FastFile` 模式。為了確保向下相容性，只要將 `TrainingInputMode` 參數設定為 `inputdataconfig.json.` 內的 `File`，支援 `File` 模式的演算法也可以順暢地使用 `FastFile` 模式。
**注意**  
使用 `FastFile` 模式的通道必須使用 “S3Prefix” 的 `S3DataType`。  
`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`：“管道”
  + 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`，並閱讀至檔案結尾 (EOF)，或者您已完成第一個 epoch，則請盡快關閉管道檔案。

  1. 關閉第一個管道檔案之後，請尋找 `/opt/ml/input/data/training_1` 並讀取它，直到完成第二個 epoch，以此類推。

  若指定 epoch 的檔案尚不存在，則您可能需要重試執行程式碼，直到該管道建立為止。通道類型之間並沒有順序限制。例如，您可以讀取 `training` 通道的多個 epoch，但只有在準備好的時候才開始讀取 `validation` 通道。或者，若演算法有需求，您亦可同時讀取這兩個管道。

  如需 Jupyter 筆記本的範例，示範如何在自有的容器使用管道模式，請參閱 [Bring your own pipe-mode algorithm to Amazon SageMaker AI](https://github.com/aws/amazon-sagemaker-examples/blob/main/advanced_functionality/pipe_bring_your_own/pipe_bring_your_own.ipynb)。

  

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) 在伺服器端加密的目錄儲存貯體中加密 SageMaker AI 輸出資料。目前不支援使用 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 檔案包含所有容器的資訊，讓您可以啟用容器間的通訊。且 `File` 與 `Pipe` 模式演算法皆可透過 SageMaker AI 使用此檔案。該檔案提供下列資訊：
+ `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。

**注意**  
在容器上透過 EFA 使用 PyTorch 時，容器的 NCCL 版本應與 PyTorch 安裝的 NCCL 版本相符。若要確認 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 的容器後，您可以使用 SageMaker AI 估算器透過 EFA 執行訓練任務，方法與處理任何其他 Docker 映像的方式相同。如需註冊容器並將其用於訓練的詳細資訊，請參閱[調整您自有的訓練容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html#byoc-training-step5)。

# Amazon SageMaker AI 指出演算法成功和失敗的方式
<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)。

**注意**  
您只能使用 Amazon S3 受管金鑰 (SSE-S3) 在伺服器端加密的 S3 目錄儲存貯體中加密 SageMaker AI 輸出資料。目前不支援使用 AWS KMS 金鑰 (SSE-KMS) 進行伺服器端加密，以將 SageMaker AI 輸出資料儲存在目錄儲存貯體中。