

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

# 步驟 2：使用 SageMaker Python SDK 啟動訓練任務
<a name="model-parallel-sm-sdk"></a>

SageMaker Python SDK 支援使用機器學習 (ML) 架構 (例如 TensorFlow 和 PyTorch) 模型進行受管訓練。若要使用其中一個架構啟動訓練任務，您可以定義 SageMaker [ TensorFlow 估算器](https://sagemaker.readthedocs.io/en/v2.199.0/frameworks/tensorflow/sagemaker.tensorflow.html#tensorflow-estimator)、SageMaker [PyTorch 估算器](https://sagemaker.readthedocs.io/en/v2.199.0/frameworks/pytorch/sagemaker.pytorch.html#pytorch-estimator)或 SageMaker 一般[估計器](https://sagemaker.readthedocs.io/en/v2.199.0/api/training/estimators.html#sagemaker.estimator.Estimator)，以使用修改過的訓練指令碼和模型平行組態。

**Topics**
+ [使用 SageMaker TensorFlow 和 PyTorch 估算器](#model-parallel-using-sagemaker-pysdk)
+ [擴充包含 SageMaker 分散式模型平行程式庫的預先建置 Docker 容器](#model-parallel-customize-container)
+ [使用 SageMaker 分散式模型平行程式庫建立您自己的 Docker 容器](#model-parallel-bring-your-own-container)

## 使用 SageMaker TensorFlow 和 PyTorch 估算器
<a name="model-parallel-using-sagemaker-pysdk"></a>

TensorFlow 和 PyTorch 估算器類別包含 `distribution` 參數，方便您用來指定使用分散式訓練架構的組態參數。SageMaker 模型平行程式庫的內部會使用 MPI 來處理混合資料和模型平行，因此您必須將 MPI 選項與程式庫搭配使用。

下列 TensorFlow 或 PyTorch 估算器範本會示範，如何設定 `distribution` 參數，藉此將 SageMaker 模型平行程式庫與 MPI 搭配使用。

------
#### [ Using the SageMaker TensorFlow estimator ]

```
import sagemaker
from sagemaker.tensorflow import TensorFlow

smp_options = {
    "enabled":True,              # Required
    "parameters": {
        "partitions": 2,         # Required
        "microbatches": 4,
        "placement_strategy": "spread",
        "pipeline": "interleaved",
        "optimize": "speed",
        "horovod": True,         # Use this for hybrid model and data parallelism
    }
}

mpi_options = {
    "enabled" : True,            # Required
    "processes_per_host" : 8,    # Required
    # "custom_mpi_options" : "--mca btl_vader_single_copy_mechanism none"
}

smd_mp_estimator = TensorFlow(
    entry_point="{{your_training_script.py}}", # Specify your train script
    source_dir="{{location_to_your_script}}",
    role=sagemaker.get_execution_role(),
    instance_count=1,
    instance_type='{{ml.p3.16xlarge}}',
    framework_version='{{2.6.3}}',
    py_version='{{py38}}',
    distribution={
        "smdistributed": {"modelparallel": smp_options},
        "mpi": mpi_options
    },
    base_job_name="{{SMD-MP-demo}}",
)

smd_mp_estimator.fit('{{s3://my_bucket/my_training_data/}}')
```

------
#### [ Using the SageMaker PyTorch estimator ]

```
import sagemaker
from sagemaker.pytorch import PyTorch

smp_options = {
    "enabled":True,
    "parameters": {                        # Required
        "pipeline_parallel_degree": 2,     # Required
        "microbatches": 4,
        "placement_strategy": "spread",
        "pipeline": "interleaved",
        "optimize": "speed",
        "ddp": True,
    }
}

mpi_options = {
    "enabled" : True,                      # Required
    "processes_per_host" : 8,              # Required
    # "custom_mpi_options" : "--mca btl_vader_single_copy_mechanism none"
}

smd_mp_estimator = PyTorch(
    entry_point="{{your_training_script.py}}", # Specify your train script
    source_dir="{{location_to_your_script}}",
    role=sagemaker.get_execution_role(),
    instance_count=1,
    instance_type='{{ml.p3.16xlarge}}',
    framework_version='{{1.13.1}}',
    py_version='{{py38}}',
    distribution={
        "smdistributed": {"modelparallel": smp_options},
        "mpi": mpi_options
    },
    base_job_name="{{SMD-MP-demo}}",
)

smd_mp_estimator.fit('{{s3://my_bucket/my_training_data/}}')
```

------

若要啟用程式庫，您需要透過 SageMaker 估算器建構函式的 `distribution` 引數，將組態字典傳遞至 `"smdistributed"` 和 `"mpi"` 金鑰。

**SageMaker 模型平行的組態參數**
+ 若為 `"smdistributed"` 金鑰，利用 `"modelparallel"` 金鑰來傳遞字典及下列內部字典。
**注意**  
系統不支援在單一訓練任務中使用 `"modelparallel"` 和 `"dataparallel"`。
  + `"enabled"` - 必要。若要啟用模型平行，請設定 `"enabled": True`。
  + `"parameters"` - 必要。為 SageMaker 模型平行指定一組參數。
    + 如需常用參數的完整清單，請參閱 *SageMaker Python SDK 文件中*的[針對 `smdistributed` 的參數](https://sagemaker.readthedocs.io/en/v2.199.0/api/training/smd_model_parallel_general.html#smdistributed-parameters)。

      對於 TensorFlow，請參閱 [TensorFlow 特定的參數](https://sagemaker.readthedocs.io/en/v2.199.0/api/training/smd_model_parallel_general.html#tensorflow-specific-parameters)。

      對於 PyTorch，請參閱 [PyTorch 特定的參數](https://sagemaker.readthedocs.io/en/v2.199.0/api/training/smd_model_parallel_general.html#pytorch-specific-parameters)。
    + `"pipeline_parallel_degree"` (或 `smdistributed-modelparallel<v1.6.0` 的 `"partitions"`) — 必要。在[針對 `smdistributed` 的參數](https://sagemaker.readthedocs.io/en/v2.199.0/api/training/smd_model_parallel_general.html#smdistributed-parameters)中，需要此參數才能指定要分割成多少個模型分割區。
**重要**  
參數名稱有重大變更。此 `"pipeline_parallel_degree"` 參數會取代自 `smdistributed-modelparallel` v1.6.0 以來的 `"partitions"`。如需詳細資訊，請參閱 SageMaker 模型平行組態的[一般參數](https://sagemaker.readthedocs.io/en/v2.199.0/api/training/smd_model_parallel_general.html#common-parameters)和 *SageMaker Python SDK 文件*中 [SageMaker 分散式模型平行發行說明](https://sagemaker.readthedocs.io/en/v2.199.0/api/training/smd_model_parallel_release_notes/smd_model_parallel_change_log.html)。
+ 若為 `"mpi"` 金鑰，請傳遞包含以下內容的字典：
  + `"enabled"` - 必要。設定 `True` 以透過 MPI 啟動分散式訓練任務。
  + `"processes_per_host"` - 必要。指定應在每台主機上啟動 MPI 的處理數目。在 SageMaker AI 中，主機是單一的 Amazon EC2 ML 執行個體。SageMaker Python SDK 在不同模型和資料平行之間，會維持程序與 GPU 之間的一對一映射。這表示 SageMaker AI 會在單一獨立的 GPU 上安排每個程序時間，而且 GPU 不包含超過一個處理程序。如果您使用的是 PyTorch，則必須透過 `torch.cuda.set_device(smp.local_rank())` 將每個程序限制為自身的裝置。如需詳細資訊，請參閱 [使用 PyTorch 自動化分割](model-parallel-customize-training-script-pt.md#model-parallel-customize-training-script-pt-16)。
**重要**  
 `process_per_host` *不得*超過每個執行個體的 GPU 數目，且通常會等於每個執行個體的 GPU 數目。
  + `"custom_mpi_options"` (選用) — 使用此金鑰以傳遞您可能需要的任何自訂 MPI 選項。如果您未傳遞任何 MPI 自訂選項至金鑰，MPI 選項預設會設為下列標記。

    ```
    --mca btl_vader_single_copy_mechanism none
    ```
**注意**  
您不需要將此預設標記明確指定給金鑰。如果您明確指定，您的分散式模型平行訓練任務可能會失敗，並出現下列錯誤：  

    ```
    The following MCA parameter has been listed multiple times on the command line: 
    MCA param: btl_vader_single_copy_mechanism MCA parameters can only be listed once 
    on a command line to ensure there is no ambiguity as to its value. 
    Please correct the situation and try again.
    ```
**提示**  
如果您使用支援 EFA 的執行個體類型 (例如 `ml.p4d.24xlarge` 和 `ml.p3dn.24xlarge` ) 啟動訓練任務，請使用下列標記來獲得最佳效能：  

    ```
    -x FI_EFA_USE_DEVICE_RDMA=1 -x FI_PROVIDER=efa -x RDMAV_FORK_SAFE=1
    ```

若要使用估算器和 SageMaker 模型平行設定的訓練指令碼啟動訓練任務，請執行 `estimator.fit()` 函式。

使用下列資源，進一步了解如何在 SageMaker Python SDK 中使用模型平行處理功能：
+ [搭配 SageMaker Python SDK 使用 TensorFlow](https://sagemaker.readthedocs.io/en/v2.199.0/frameworks/tensorflow/using_tf.html)
+ [搭配 SageMaker Python SDK 使用 PyTorch](https://sagemaker.readthedocs.io/en/v2.199.0/frameworks/pytorch/using_pytorch.html)
+ 如果您是新使用者，建議您使用 SageMaker 筆記本執行個體。若要查看如何使用 SageMaker 筆記本執行個體啟動訓練任務的範例，請參閱[Amazon SageMaker AI 模型平行化程式庫 v2 範例](distributed-model-parallel-v2-examples.md)。
+ 您也可以透過您的機器使用 AWS CLI，來提交分散式訓練任務。若要在機器 AWS CLI 上設定 ，請參閱[設定您的 AWS 登入資料和開發區域](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html)。

## 擴充包含 SageMaker 分散式模型平行程式庫的預先建置 Docker 容器
<a name="model-parallel-customize-container"></a>

若要擴充預先建置的容器並使用 SageMaker 的模型平行處理程式庫，您必須使用其中一個可用的 AWS PyTorch 或 TensorFlow 深度學習容器 (DLC) 映像。SageMaker 模型平行程式庫隨附於 TensorFlow (2.3.0 及更新版本) 和具有 CUDA (`cuxyz`) 的 PyTorch (1.6.0 及更新版本) DLC 映像。如需 DLC 映像的完整清單，請參閱 *AWS 深度學習容器 GitHub 儲存庫*中的[可用深度學習容器映像](https://github.com/aws/deep-learning-containers/blob/master/available_images.md)。

**提示**  
建議您使用包含 TensorFlow 或 PyTorch 最新版本的映像，來存取最新版本的 SageMaker 模型平行程式庫。

例如，您的 Dockerfile 應包含類似下列的 `FROM` 陳述式：

```
# Use the SageMaker DLC image URI for TensorFlow or PyTorch
FROM {{aws-dlc-account-id}}.dkr.ecr.{{aws-region}}.amazonaws.com/{{framework}}-training:{{{framework-version-tag}}}

# Add your dependencies here
RUN {{...}}

ENV PATH="/opt/ml/code:{{${PATH}}}"

# this environment variable is used by the SageMaker AI container to determine our user code directory.
ENV SAGEMAKER_SUBMIT_DIRECTORY /opt/ml/code
```

此外，當您定義 PyTorch 或 TensorFlow 估算器時，您必須為您的訓練指令碼指定該 `entry_point` 項目。這應與 Dockerfile 中 `ENV SAGEMAKER_SUBMIT_DIRECTORY` 識別的路徑相同。

**提示**  
您必須將此 Docker 容器推送到 Amazon Elastic Container Registry (Amazon ECR)，並使用映像 URI (`image_uri`) 來定義 SageMaker 估算器以進行訓練。如需詳細資訊，請參閱[延伸預先建置的容器](prebuilt-containers-extend.md)。

完成託管 Docker 容器並擷取容器的映象 URI 之後，請依照下列步驟建立 SageMaker `PyTorch` 估算器物件。此範例假設您已定義 `smp_options` 和 `mpi_options`。

```
smd_mp_estimator = Estimator(
    entry_point="{{your_training_script.py}}",
    role=sagemaker.get_execution_role(),
    instance_type='{{ml.p3.16xlarge}}',
    sagemaker_session=sagemaker_session,
    image_uri='{{your_aws_account_id}}.dkr.ecr.{{region}}.amazonaws.com/{{name}}:{{tag}}'
    instance_count={{1}},
    distribution={
        "smdistributed": smp_options,
        "mpi": mpi_options
    },
    base_job_name="{{SMD-MP-demo}}",
)

smd_mp_estimator.fit('s3://my_bucket/my_training_data/')
```

## 使用 SageMaker 分散式模型平行程式庫建立您自己的 Docker 容器
<a name="model-parallel-bring-your-own-container"></a>

若要建立自己的 Docker 容器以進行訓練並使用 SageMaker 模型平行程式庫，您必須在 Docerfile 中納入 SageMaker 分散式平行程式庫正確的相依性和二進位檔案。本節提供您必須包含的最少程式碼區塊組合，才能在您自己的 Docker 容器中妥善準備 SageMaker 訓練環境和模型平行程式庫。

**注意**  
此自訂 Docker 選項將 SageMaker 模型平行程式庫做為二進位程式庫，僅適用於 PyTorch。

**使用 SageMaker 訓練工具組和模型平行程式庫建立 Dockerfile**

1. 從其中一個 [NVIDIA CUDA 基礎映像](https://hub.docker.com/r/nvidia/cuda)開始著手。

   ```
   FROM {{<cuda-cudnn-base-image>}}
   ```
**提示**  
官方 AWS 深度學習容器 (DLC) 映像是從 [NVIDIA CUDA 基礎映像](https://hub.docker.com/r/nvidia/cuda)建置而成。我們建議您查看[適用於 PyTorch 的 AWS 深度學習容器官方 Dockerfiles](https://github.com/aws/deep-learning-containers/tree/master/pytorch/training/docker)，以尋找您需要安裝的程式庫版本，以及如何設定它們。官方版 Dockerfiles 經過 SageMaker 和深度學習容器服務團隊完整的基準測試和管理。在提供的連結中，選擇您使用的 PyTorch 版本、選擇 CUDA (`cuxyz`) 資料夾，然後選擇以 `.gpu` 或 `.sagemaker.gpu` 結尾結尾的 Dockerfile。

1. 若要設定分散式訓練環境，您需要安裝適用於通訊和網路裝置的軟體，例如 [Elastic Fabric Adapter (EFA)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html)、[NVIDIA 集合通訊程式庫 (NCCL)](https://developer.nvidia.com/nccl) 和 [Open MPI](https://www.open-mpi.org/)。視您選擇的 PyTorch 和 CUDA 版本而定，您必須安裝相容的程式庫版本。
**重要**  
由於 SageMaker 模型平行程式庫需要在後續步驟中使用 SageMaker 資料平行程式庫，因此我們強烈建議您遵循[使用 SageMaker AI 分散式資料平行程式庫建立您自己的 Docker 容器](data-parallel-bring-your-own-container.md)的指示，為分散式訓練妥善設定 SageMaker 訓練環境。

   如需有關使用 NCCL 和 Open MPI 設定 EFA 的詳細資訊，請參閱[開始使用 EFA 和 MPI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html) 以及[開始使用 EFA 和 NCCL](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start-nccl.html)。

1. 新增下列引數，以指定適用於 PyTorch 的 SageMaker 分散式訓練套件的 URL。SageMaker 模型平行程式庫需要 SageMaker 資料平行程式庫，才能使用跨節點遠端直接記憶體存取 (RDMA)。

   ```
   ARG SMD_MODEL_PARALLEL_URL=https://sagemaker-distributed-model-parallel.s3.us-west-2.amazonaws.com/pytorch-1.10.0/build-artifacts/2022-02-21-19-26/smdistributed_modelparallel-1.7.0-cp38-cp38-linux_x86_64.whl
   ARG SMDATAPARALLEL_BINARY=https://smdataparallel.s3.amazonaws.com/binary/pytorch/1.10.2/cu113/2022-02-18/smdistributed_dataparallel-1.4.0-cp38-cp38-linux_x86_64.whl
   ```

1. 安裝 SageMaker 模型平行程式庫所需的相依性。

   1. 安裝 [METIS](http://glaros.dtc.umn.edu/gkhome/metis/metis/overview) 程式庫。

      ```
      ARG METIS=metis-{{5.1.0}}
      
      RUN rm /etc/apt/sources.list.d/* \
        && wget -nv http://glaros.dtc.umn.edu/gkhome/fetch/sw/metis/${METIS}.tar.gz \
        && gunzip -f ${METIS}.tar.gz \
        && tar -xvf ${METIS}.tar \
        && cd ${METIS} \
        && apt-get update \
        && make config shared=1 \
        && make install \
        && cd .. \
        && rm -rf ${METIS}.tar* \
        && rm -rf ${METIS} \
        && rm -rf /var/lib/apt/lists/* \
        && apt-get clean
      ```

   1. 安裝 [RAPIDS 記憶體管理員程式庫](https://github.com/rapidsai/rmm#rmm-rapids-memory-manager)。系統須使用 [CMake](https://cmake.org/) 3.14 或更高版本。

      ```
      ARG RMM_VERSION={{0.15.0}}
      
      RUN  wget -nv https://github.com/rapidsai/rmm/archive/v${RMM_VERSION}.tar.gz \
        && tar -xvf v${RMM_VERSION}.tar.gz \
        && cd rmm-${RMM_VERSION} \
        && INSTALL_PREFIX=/usr/local ./build.sh librmm \
        && cd .. \
        && rm -rf v${RMM_VERSION}.tar* \
        && rm -rf rmm-${RMM_VERSION}
      ```

1. 安裝 SageMaker 模型平行程式庫。

   ```
   RUN pip install --no-cache-dir -U ${SMD_MODEL_PARALLEL_URL}
   ```

1. 安裝 SageMaker 資料平行程式庫。

   ```
   RUN SMDATAPARALLEL_PT=1 pip install --no-cache-dir ${SMDATAPARALLEL_BINARY}
   ```

1. 安裝 [sagemaker-training 工具組](https://github.com/aws/sagemaker-training-toolkit)。此工具組包含建立與 SageMaker 訓練平台和 SageMaker Python SDK 相容的容器所需的常見功能。

   ```
   RUN pip install sagemaker-training
   ```

1. 完成建立 Dockerfile 之後，請參閱[調整您自己的訓練容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html)，了解如何建置 Docker 容器並將其託管在 Amazon ECR 中。

**提示**  
如需有關在 SageMaker AI 中建立自訂 Dockerfile 以進行訓練的詳細資訊，請參閱[使用您自己的訓練演算法](https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html)。