

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

# 開始使用 Amazon SageMaker AI 分散式訓練
<a name="distributed-training-get-started"></a>

以下頁面提供在 Amazon SageMaker AI 中開始分散式訓練所需的步驟資訊。如果您已經熟悉分散式訓練，請選擇下列其中一個符合您偏好策略或架構的選項以開始使用。如果您想要了解一般的分散式訓練，請參閱[分散式訓練概念](distributed-training.md#distributed-training-basic-concepts)。

SageMaker AI 分散式訓練資料庫已針對 SageMaker AI 訓練環境進行最佳化，可協助調整您的分散式訓練任務以符合 SageMaker AI，並提高訓練速度與輸送量。這些資料庫提供資料平行和模型平行訓練策略。它們結合了軟體與硬體技術來改善 GPU 間和節點間的通訊，並透過內建選項擴展 SageMaker AI 的訓練功能，這些選項只需對訓練指令碼進行最少的程式碼變更。 

## 開始之前
<a name="distributed-training-before-getting-started"></a>

SageMaker 訓練支援單一執行個體和多個執行個體的分散式訓練，因此您可以大規模執行任何規模的訓練。我們建議您在 SageMaker Python SDK 使用架構估算器類別，例如 [PyTorch](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html#pytorch-estimator) 以及 [TensorFlow](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.html#tensorflow-estimator)，這是具有各種分散式訓練選項的訓練工作啟動器。當您建立估算器物件時，物件會設定分散式訓練基礎設施、在後端執行 `CreateTrainingJob` API、尋找目前工作階段執行所在的區域，以及提取預先建置的 AWS 深度學習容器，其中包含深度學習架構、分散式訓練架構和 [EFA](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) 驅動程式等多種程式庫。如果想要將 FSx 檔案系統掛載至訓練執行個體，則需要將 VPC 子網路及安全群組 ID 傳遞給估算器。在 SageMaker AI 執行分散式訓練任務之前，請閱讀以下有關基本基礎結構設定的一般指南。

### 可用性區域與網路後擋板
<a name="availability-zones"></a>

使用多個執行個體 (也稱為*節點*) 時，請務必了解連接執行個體的網路、它們如何讀取訓練資料，以及它們如何在彼此之間共用資訊。例如，當您執行分散式資料平行訓練工作時，許多因素 (例如用於執行 `AllReduce` 作業的運算叢集節點之間的通訊) 以及 Amazon Simple Storage Service 或 Amazon FSx for Lustre 中的節點及資料儲存之間的資料傳輸，都扮演著至關重要的角色，以達到最佳化運算資源和更快的訓練速度。若要降低通訊開銷，請確定您在相同的 和可用區域中設定執行個體、VPC 子網路 AWS 區域 和資料儲存。

### 具有更快網路及高輸送量儲存的 GPU 執行個體
<a name="optimized-GPU"></a>

您可以在技術上使用任何執行個體進行分散式訓練。對於需要執行多節點分散式訓練任務以訓練大型模型，例如大型語言模型 (LLM) 及擴散模型 (需要更快的節點間交換)，我們建議 [SageMaker AI 支援啟用 EFA 的 GPU 執行個體](https://aws.amazon.com/about-aws/whats-new/2021/05/amazon-sagemaker-supports-elastic-fabric-adapter-distributed-training/)。特別是，為了在 SageMaker AI 中達成效能最高的分散式訓練任務，我們建議使用配備 [NVIDIA A100 GPU 的 P4d 與 P4de 執行個體](https://aws.amazon.com/ec2/instance-types/p4/)。這些還配備了高輸送量、低延遲的本機執行個體儲存以及更快速的節點內部網路。對於資料儲存，我們建議使用 [Amazon FSx for Lustre](https://docs.aws.amazon.com/fsx/latest/LustreGuide/what-is.html) 提供高輸送量來存放訓練資料集及模型檢查點。

**使用 SageMaker AI 分散式資料平行化 (SMDDP) 程式庫**

SMDDP 程式庫透過針對 AWS 網路基礎設施`AllReduce`和 Amazon SageMaker AI ML 執行個體拓撲最佳化的 和 `AllGather` 集體通訊操作實作，改善節點之間的通訊。您可以使用 [SMDDP 程式庫做為 PyTorch 型分散式訓練套件的後端](https://docs.aws.amazon.com/sagemaker/latest/dg/data-parallel-modify-sdp-pt.html)：[PyTorch 分散式資料平行處理 (DDP)](https://pytorch.org/docs/stable/notes/ddp.html)、[PyTorch 全碎片資料平行處理 (FSDP)](https://pytorch.org/docs/stable/fsdp.html)、[DeepSpeed](https://github.com/microsoft/DeepSpeed) 和 [Megatron-DeepSpeed](https://github.com/microsoft/Megatron-DeepSpeed)。下列程式碼範例示範如何設定 `PyTorch` 估算器，以在兩個 `ml.p4d.24xlarge` 執行個體上啟動分散式訓練任務。

```
from sagemaker.pytorch import PyTorch

estimator = PyTorch(
    ...,
    instance_count=2,
    instance_type="ml.p4d.24xlarge",
    # Activate distributed training with SMDDP
    distribution={ "pytorchddp": { "enabled": True } }  # mpirun, activates SMDDP AllReduce OR AllGather
    # distribution={ "torch_distributed": { "enabled": True } }  # torchrun, activates SMDDP AllGather
    # distribution={ "smdistributed": { "dataparallel": { "enabled": True } } }  # mpirun, activates SMDDP AllReduce OR AllGather
)
```

若要了解如何準備訓練指令碼，並在 SageMaker AI 上啟動分散式資料平行訓練任務，請參閱 [使用 SageMaker AI 分散式資料平行化程式庫執行分散式訓練](data-parallel.md)。

**使用 SageMaker AI 模型平行化程式庫 (SMP)**

SageMaker AI 提供 SMP 程式庫並支援各種分散式訓練技術，例如分割資料平行化、管線、張量平行化、最佳化器狀態分割等。若要進一步了解 SMP 程式庫提供的功能，請參閱[SageMaker 模型平行化程式庫的核心功能](model-parallel-core-features.md)。

若要使用 SageMaker AI 的模型平行化程式庫，請設定 SageMaker AI 架構估算器的 `distribution` 參數。支援的架構估算器是 [PyTorch](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html#pytorch-estimator) 和 [TensorFlow](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.html#tensorflow-estimator)。下列程式碼範例示範如何透過在兩個 `ml.p4d.24xlarge` 執行個體使用模型平行程式庫，建立用於分散式訓練的架構估算器。

```
from sagemaker.framework import Framework

distribution={
    "smdistributed": {
        "modelparallel": {
            "enabled":True,
            "parameters": {
                ...   # enter parameter key-value pairs here
            }
        },
    },
    "mpi": {
        "enabled" : True,
        ...           # enter parameter key-value pairs here
    }
}

estimator = Framework(
    ...,
    instance_count=2,
    instance_type="ml.p4d.24xlarge",
    distribution=distribution
)
```

若要了解如何調整訓練指令碼、在 `estimator` 類別設定發布參數，以及啟動分散式訓練任務，請參閱 [SageMaker AI 模型平行化程式庫](model-parallel.md) (另請參閱 *SageMaker Python SDK 文件*中的[分散式訓練 API](https://sagemaker.readthedocs.io/en/stable/api/training/distributed.html#the-sagemaker-distributed-model-parallel-library))。

**使用開放原始碼分散式訓練架構**

SageMaker AI 也支援下列選項在後端操作 `mpirun` 及 `torchrun`。
+ 若要將 SageMaker AI 中的 [PyTorch DistributedDataParallel (DDP)](https://pytorch.org/docs/master/generated/torch.nn.parallel.DistributedDataParallel.html) 與後 `mpirun` 端結合使用，請新增 `distribution={"pytorchddp": {"enabled": True}}` 至您的 PyTorch 估算器。如需更多資訊，另請參閲*SageMaker Python SDK 文件*的 [PyTorch 分散式訓練](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#distributed-pytorch-training)及 [SageMaker AI PyTorch 估算器](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html#pytorch-estimator)的 `distribution` 參數。
**注意**  
此選項適用於 PyTorch 1.12.0 及更新版本。

  ```
  from sagemaker.pytorch import PyTorch
  
  estimator = PyTorch(
      ...,
      instance_count=2,
      instance_type="ml.p4d.24xlarge",
      distribution={"pytorchddp": {"enabled": True}}  # runs mpirun in the backend
  )
  ```
+ SageMaker AI 支援 [PyTorch `torchrun` 啟動器](https://pytorch.org/docs/stable/elastic/run.html)，針對以 GPU 為基礎的 Amazon EC2 執行個體 (例如 P3 和 P4) 以及由 [AWS Trainium 裝置](https://aws.amazon.com/machine-learning/trainium/)支援的 Trn1 進行分散式訓練。

  若要在 SageMaker AI 使用 [PyTorch DistributedDataParallel (DDP)](https://pytorch.org/docs/master/generated/torch.nn.parallel.DistributedDataParallel.html) 及 `torchrun` 後端，請將 `distribution={"torch_distributed": {"enabled": True}}` 新增至 PyTorch 估算器。
**注意**  
此選項適用於 PyTorch 1.13.0 及更新版本。

  下列程式碼片段會示範如何建立 SageMaker AI PyTorch 估算器，以使用 `torch_distributed` 分散選項在兩個 `ml.p4d.24xlarge` 執行個體執行分散式訓練的範例。

  ```
  from sagemaker.pytorch import PyTorch
  
  estimator = PyTorch(
      ...,
      instance_count=2,
      instance_type="ml.p4d.24xlarge",
      distribution={"torch_distributed": {"enabled": True}}   # runs torchrun in the backend
  )
  ```

  如需更多資訊，請參閱 *SageMaker Python SDK 文件*中的[分散式 PyTorch 訓練](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#distributed-pytorch-training)及 [SageMaker AI PyTorch 估算器](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html#pytorch-estimator) 的 `distribution` 引數。

  **Trn1 分散式訓練的注意事項**

  一個 Trn1 執行個體最多由 16 個 Trainium 裝置組成，每個 Trainium 裝置由兩個 [NeuronCore](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/arch/neuron-hardware/neuroncores-arch.html#neuroncores-v2-arch) 組成。如需 AWS Trainium 裝置的規格，請參閱 *AWS Neuron 文件*中的 [Trainium 架構](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/arch/neuron-hardware/trn1-arch.html#id2)。

  要在 Trainium 支援的執行個體進行訓練，您只需在 SageMaker AI PyTorch 估算器類別的 `instance_type` 引數的字串指定 Trn1 執行個體程式碼 `ml.trn1.*`。若要尋找可用的 Trn1 執行個體類型，請參閱 *AWS Neuron 文件*中的 [AWS Trn1 架構](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/arch/neuron-hardware/trn1-arch.html#aws-trn1-arch)。
**注意**  
Amazon EC2 Trn1 執行個體上的 SageMaker Training 目前僅適用於從 1.11.0 版開始的 PyTorch Neuron AWS 深度學習容器中的 PyTorch 架構。若要尋找支援 PyTorch Neuron 版本的完整清單，請參閱 *AWS Deep Learning Containers GitHub 儲存庫*的 [Neuron Containers](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#neuron-containers)。

  當您使用 SageMaker Python SDK 在 Trn1 執行個體上啟動訓練任務時，SageMaker AI 會自動從 AWS 深度學習容器提供的 [Neuron 容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#neuron-containers)取得並執行正確的容器。Neuron Containers 已預先封裝訓練環境設定和相依性，以便訓練工作更輕鬆適應 SageMaker 訓練平台與 Amazon EC2 Trn1 執行個體。
**注意**  
若要使用 SageMaker AI 在 Trn1 執行個體執行 PyTorch 訓練任務，您應該修改訓練指令碼以使用 `xla` 後端初始化程序群組，並使用 [Pytorch/XLA](https://pytorch.org/xla/release/1.12/index.html)。為了支援 XLA 採用程序， AWS Neuron SDK 提供 PyTorch Neuron，使用 XLA 將 PyTorch 操作轉換為 Trainium 指示。若要了解如何修改訓練指令碼，請參閱 *AWS Neuron 文件*中的 [PyTorch Neuron 訓練開發人員指南 (`torch-neuronx`)](https://awsdocs-neuron.readthedocs-hosted.com/en/latest/frameworks/torch/torch-neuronx/programming-guide/training/pytorch-neuron-programming-guide.html)。

  如需更多資訊，請參閱 *SageMaker Python SDK 文件*中的[在 Trn1 執行個體使用 PyTorch Neuron 進行分散式訓練](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#id24)及 [SageMaker AI PyTorch 估算器](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html#pytorch-estimator)的 `distribution` 引數。
+ 若要在 SageMaker AI 使用 MPI，請將 `distribution={"mpi": {"enabled": True}}` 新增至您的估算器。MPI 發布選項適用於下列架構：MXNet、PyTorch 及 TensorFlow。
+ 若要在 SageMaker AI 使用參數伺服器，請將 `distribution={"parameter_server": {"enabled": True}}` 新增至您的估算器。參數伺服器選項適用於下列架構：MXNet、PyTorch 及 TensorFlow。
**提示**  
如需有關針對每個架構使用 MPI 和參數伺服器選項的更多相關資訊，請使用下列連結至 *SageMaker Python SDK 文件*。  
[MXNet 分散式訓練](https://sagemaker.readthedocs.io/en/stable/frameworks/mxnet/using_mxnet.html#distributed-training)與 [SageMaker AI MXNet 估算器](https://sagemaker.readthedocs.io/en/stable/frameworks/mxnet/sagemaker.mxnet.html#mxnet-estimator)的 `distribution` 引數
[PyTorch 分散式訓練](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#distributed-pytorch-training)與 [SageMaker AI PyTorch 估算器](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html#pytorch-estimator)的 `distribution` 引數
[TensorFlow 分散式訓練](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html#distributed-training)與 [SageMaker AI TensorFlow 估算器](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.html#tensorflow-estimator)的 `distribution` 引數。