

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

# 使用 SageMaker AI 分散式資料平行化程式庫執行分散式訓練
<a name="data-parallel"></a>

SageMaker AI 分散式資料平行處理 (SMDDP) 程式庫透過提供針對 AWS 基礎設施最佳化的集體通訊操作實作，以近線性擴展效率擴展深度學習模型上的 SageMaker 訓練功能。

在龐大的訓練資料集上訓練大型機器學習 (ML) 模型 (例如大型語言模型 (LLM) 和擴散模型) 時，ML 從業者會使用加速器叢集和分散式訓練技術來減少訓練時間，或解決無法容納每個 GPU 記憶體之模型的記憶體限制。ML 從業人員通常從單一執行個體上的多個加速器開始，然後隨著工作負載需求增加擴展到執行個體叢集。隨著叢集規模的增加，多個節點之間的通訊開銷也會增加，導致整體運算效能下降。

為了解決此類開銷和記憶體問題，SMDDP 程式庫提供下列功能。
+ SMDDP 程式庫會最佳化 AWS 網路基礎設施和 Amazon SageMaker AI ML 執行個體拓撲的訓練任務。
+ SMDDP 程式庫透過針對 AWS 基礎設施最佳化的 `AllReduce`和 `AllGather` 集體通訊操作的實作，改善節點之間的通訊。

若要進一步了解 SMDDP 程式庫產品的詳細資訊，請繼續前往[SageMaker AI 分散式資料平行化程式庫簡介](data-parallel-intro.md)。

如需使用 SageMaker AI 提供的模型平行化策略來進行訓練的詳細資訊，另請參閱[(存檔) SageMaker 模型平行化程式庫 v1.x](model-parallel.md)。

**Topics**
+ [SageMaker AI 分散式資料平行化程式庫簡介](data-parallel-intro.md)
+ [支援的架構 AWS 區域和執行個體類型](distributed-data-parallel-support.md)
+ [使用 SageMaker AI 分散式資料平行化程式庫進行分散式訓練](data-parallel-modify-sdp.md)
+ [Amazon SageMaker AI 資料平行程式庫範例](distributed-data-parallel-v2-examples.md)
+ [Amazon SageMaker AI 分散式資料平行程式庫的組態提示。](data-parallel-config.md)
+ [Amazon SageMaker AI 分散式資料平行化程式庫常見問答集](data-parallel-faq.md)
+ [針對 Amazon SageMaker AI 分散式訓練進行故障診斷](distributed-troubleshooting-data-parallel.md)
+ [SageMaker AI 資料平行化程式庫版本備註](data-parallel-release-notes.md)

# SageMaker AI 分散式資料平行化程式庫簡介
<a name="data-parallel-intro"></a>

SageMaker AI 分散式資料平行化 (SMDDP) 程式庫是一種集體通訊程式庫，可改善分散式資料平行訓練的運算效能。SMDDP 程式庫透過提供下列項目來解決關鍵集體通訊操作的通訊額外負荷。

1. 程式庫提供`AllReduce`針對 最佳化的 AWS。 `AllReduce` 是一種金鑰操作，用於在分散式資料訓練期間，在每次訓練反覆運算結束時跨 GPUs 同步漸層。

1. 程式庫提供針對 `AllGather`最佳化 AWS。 `AllGather` 是碎片資料平行訓練中使用的另一個關鍵操作，這是一種記憶體效率的資料平行處理技術，由熱門程式庫提供，例如 SageMaker AI 模型平行處理 (SMP) 程式庫、DeepSpeed 零冗餘最佳化工具 (ZeRO) 和 PyTorch 完全碎片資料平行處理 (FSDP)。

1. 程式庫會透過充分利用 AWS 網路基礎設施和 Amazon EC2 執行個體拓撲來執行最佳化node-to-node通訊。

SMDDP 程式庫可以透過近線性擴展效率，在擴展訓練叢集時提供效能提升，進而提高訓練速度。

**注意**  
SageMaker AI 分散式訓練程式庫可透過 SageMaker Training 平台中 PyTorch 和 Hugging Face 的 AWS 深度學習容器取得。若要使用這些程式庫，您必須透過適用於 Python 的 SDK (Boto3) 或 AWS Command Line Interface使用 SageMaker Python SDK 或 SageMaker API。整個文件中，指示和範例著重於如何將分散式訓練程式庫與SageMaker Python SDK 搭配使用。

## 針對 AWS 運算資源和網路基礎設施最佳化的 SMDDP 集體通訊操作
<a name="data-parallel-collective-operations"></a>

SMDDP 程式庫提供針對 AWS 運算資源`AllReduce`和網路基礎設施最佳化的 和 `AllGather`集體操作實作。

### SMDDP `AllReduce` 集體操作
<a name="data-parallel-allreduce"></a>

SMDDP 程式庫可實現 `AllReduce` 操作與向後傳遞的最佳重疊，大幅提高 GPU 利用率。它透過最佳化 CPU 和 GPU 之間的核心操作，實現了近線性的擴展效率和更快的訓練速度。程式庫在 GPU 運算梯度時平行執行 `AllReduce`，而不會佔用額外的 GPU 週期，進而使程式庫能夠實現更快的訓練。
+  *利用 CPU*：程式庫使用 CPU 至 `AllReduce` 梯度，從 GPU 卸載此任務。
+ *改善 GPU 使用率*：叢集的 GPU 專注於運算漸層，改善整個訓練的使用率。

以下是 SMDDP `AllReduce` 操作的高階工作流程。

1. 程式庫指派 GPU 排名 (工作者)。

1. 在每次反覆運算時，程式庫會將每個全域批次除以工作者總數 (世界大小)，並將小批次 (批次碎片) 指派給工作者。
   + 全域批次的大小為 `(number of nodes in a cluster) * (number of GPUs per node) * (per batch shard)`。
   + 批次碎片 (小批次) 是每個 GPU (工作者) 每次反覆運算的已指派資料集子集。

1. 程式庫會在每個工作者上啟動訓練指令碼。

1. 程式庫在每次迭代結束時，會管理來自工作者的模型權重和漸層的副本。

1. 程式庫會同步處理工作者中的模型權重和漸層，以彙總單一訓練的模型。

下列架構圖顯示程式庫如何為 3 個節點的叢集設定資料平行處理的範例。

 

![\[SMDDP AllReduce 和資料平行化架構圖\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/distributed/data-parallel/sdp-architecture.png)


### SMDDP `AllGather` 集體操作
<a name="data-parallel-allgather"></a>

`AllGather` 是一種集體操作，其中每個工作者都從輸入緩衝區開始，然後將所有其他工作者的輸入緩衝區串連或*收集*到輸出緩衝區。

**注意**  
SMDDP `AllGather`集體操作可在適用於 PyTorch v2.0.1 和更新版本的 `smdistributed-dataparallel>=2.0.1`和 AWS 深度學習容器 (DLC) 中使用。

`AllGather` 大量用於分散式訓練技術，例如碎片資料平行化，其中每個個別工作者都有一部分的模型或碎片層。工作者會在向前和向後傳遞之前呼叫 `AllGather`，以重建碎片圖層。所有參數都*收集*完畢後，向前和向後通過會繼續。在向後傳遞期間，每個工作者也會呼叫 `ReduceScatter` 來收集 (減少) 梯度，並將它們分解 (散射) 為梯度碎片，以更新對應的碎片層。如需這些集體操作在碎片資料平行化中的角色詳細資訊，請參閱 [SMP 程式庫在碎片資料平行化上的實作](https://docs.aws.amazon.com/sagemaker/latest/dg/model-parallel-extended-features-pytorch-sharded-data-parallelism.html)、DeepSpeed 文件中的 [ZeRO](https://deepspeed.readthedocs.io/en/latest/zero3.html#)，以及有關 [PyTorch 全碎片資料平行化](https://engineering.fb.com/2021/07/15/open-source/fsdp/)的部落格。

由於每次迭代運算都會呼叫 AllGather 等集體操作，因此它們是 GPU 通訊額外負荷的主要因素。這些集體操作的更快速運算會直接轉換為較短的訓練時間，而不會對收斂造成副作用。為了達成此目的，SMDDP 程式庫提供針對 [P4d 執行個體](https://aws.amazon.com/ec2/instance-types/p4/)最佳化的 `AllGather` 功能。

SMDDP `AllGather` 使用以下技術來改善 P4d 執行個體的運算效能。

1. 它透過具有網格拓撲的 [Elastic Fabric Adapter (EFA)](https://aws.amazon.com/hpc/efa/) 網路，在執行個體 (節點間) 之間傳輸資料。EFA 是 AWS 低延遲和高輸送量的網路解決方案。節點間網路通訊的網格拓撲更符合 EFA 和 AWS 網路基礎設施的特性。相較於涉及多個封包跳轉的 NCCL 環形或樹狀拓撲，SMDDP 可避免從多個跳轉累積延遲，因為它只需要一個跳轉。SMDDP 實作網路速率控制演算法，在網格拓撲中平衡工作負載與每個通訊對等，並實現更高的全球網路輸送量。

1. 它採用以 [NVIDIA GPUDirect RDMA 技術 (GDRCopy) 為基礎的低延遲 GPU 記憶體複製程式庫](https://github.com/NVIDIA/gdrcopy)，來協調本機 NVLink 和 EFA 網路流量。GDRCopy 是由 NVIDIA 提供的低延遲 GPU 記憶體複製程式庫，可在 CPU 程序與 GPU CUDA 核心之間提供低延遲通訊。使用此技術，SMDDP 程式庫能夠將節點內和節點間資料移動管道化。

1. 它減少了 GPU 串流多處理器的使用，以提高執行模型核心的運算能力。P4d 和 P4de 執行個體配備 NVIDIA A100 GPU，每個 GPU 具有 108 個串流多處理器。雖然 NCCL 最多需要 24 個串流多處理器來執行集體操作，但 SMDDP 會使用少於 9 個串流多處理器。模型運算核心會挑選儲存的串流多處理器，以加快運算速度。

# 支援的架構 AWS 區域和執行個體類型
<a name="distributed-data-parallel-support"></a>

使用 SageMaker AI 分散式資料平行處理 (SMDDP) 程式庫之前，請檢查支援的 ML 架構和執行個體類型，以及 AWS 您的帳戶和 中是否有足夠的配額 AWS 區域。

## 支援的架構
<a name="distributed-data-parallel-supported-frameworks"></a>

下表顯示 SageMaker AI 和 SMDDP 支援的深度學習架構及其版本。SMDDP 程式庫可在 [SageMaker AI 架構容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only)中使用、整合在 [SageMaker 模型平行化 (SMP) 程式庫 v2 發佈的 Docker 容器](distributed-model-parallel-support-v2.md#distributed-model-parallel-supported-frameworks-v2)中，也可下載為二進位檔案。

**注意**  
若要檢查 SMDDP 程式庫的最新更新和版本備註，請參閱[SageMaker AI 資料平行化程式庫版本備註](data-parallel-release-notes.md)。

**Topics**
+ [PyTorch](#distributed-data-parallel-supported-frameworks-pytorch)
+ [PyTorch Lightning](#distributed-data-parallel-supported-frameworks-lightning)
+ [Hugging Face 轉換器](#distributed-data-parallel-supported-frameworks-transformers)
+ [TensorFlow (已棄用)](#distributed-data-parallel-supported-frameworks-tensorflow)

### PyTorch
<a name="distributed-data-parallel-supported-frameworks-pytorch"></a>


| PyTorch 版本 | SMDDP 程式庫版本 | 預先安裝 SMDDP 的 SageMaker AI 架構容器映像檔 | 預先安裝 SMDDP 的 SMP Docker 映像檔 | 二進位檔案的網址\$1\$1 | 
| --- | --- | --- | --- | --- | 
| v2.3.1 | smdistributed-dataparallel==v2.5.0 | 不適用 | 658645717510.dkr.ecr.<us-west-2>.amazonaws.com/smdistributed-modelparallel:2.4.1-gpu-py311-cu121 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.4.1/cu121/2024-10-09/smdistributed\$1dataparallel-2.5.0-cp311-cp311-linux\$1x86\$164.whl | 
| v2.3.0 | smdistributed-dataparallel==v2.3.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.3.0-gpu-py311-cu121-ubuntu20.04-sagemaker | 目前無法使用 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.3.0/cu121/2024-05-23/smdistributed\$1dataparallel-2.3.0-cp311-cp311-linux\$1x86\$164.whl | 
| v2.2.0 | smdistributed-dataparallel==v2.2.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.2.0-gpu-py310-cu121-ubuntu20.04-sagemaker | 658645717510.dkr.ecr.<region>.amazonaws.com/smdistributed-modelparallel:2.2.0-gpu-py310-cu121 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.2.0/cu121/2024-03-04/smdistributed\$1dataparallel-2.2.0-cp310-cp310-linux\$1x86\$164.whl | 
| 2.1.0 版 | smdistributed-dataparallel==v2.1.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.1.0-gpu-py310-cu121-ubuntu20.04-sagemaker | 658645717510.dkr.ecr.<region>.amazonaws.com/smdistributed-modelparallel:2.1.2-gpu-py310-cu121 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.1.0/cu121/2024-02-04/smdistributed\$1dataparallel-2.1.0-cp310-cp310-linux\$1x86\$164.whl | 
| v2.0.1 | smdistributed-dataparallel==v2.0.1 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.0.1-gpu-py310-cu118-ubuntu20.04-sagemaker | 不適用 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.0.1/cu118/2023-12-07/smdistributed\$1dataparallel-2.0.2-cp310-cp310-linux\$1x86\$164.whl | 
| v2.0.0 | smdistributed-dataparallel==v1.8.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.0.0-gpu-py310-cu118-ubuntu20.04-sagemaker | 不適用 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.0.0/cu118/2023-03-20/smdistributed\$1dataparallel-1.8.0-cp310-cp310-linux\$1x86\$164.whl | 
| V1.13.1 | smdistributed-dataparallel==v1.7.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.13.1-gpu-py39-cu117-ubuntu20.04-sagemaker | 不適用 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/1.13.1/cu117/2023-01-09/smdistributed\$1dataparallel-1.7.0-cp39-cp39-linux\$1x86\$164.whl | 
| v1.12.1 | smdistributed-dataparallel==v1.6.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.12.1-gpu-py38-cu113-ubuntu20.04-sagemaker | 不適用 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/1.12.1/cu113/2022-12-05/smdistributed\$1dataparallel-1.6.0-cp38-cp38-linux\$1x86\$164.whl | 
| v1.12.0 | smdistributed-dataparallel==v1.5.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.12.0-gpu-py38-cu113-ubuntu20.04-sagemaker | 不適用 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/1.12.0/cu113/2022-07-01/smdistributed\$1dataparallel-1.5.0-cp38-cp38-linux\$1x86\$164.whl | 
| v1.11.0 | smdistributed-dataparallel==v1.4.1 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.11.0-gpu-py38-cu113-ubuntu20.04-sagemaker | 不適用 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/1.11.0/cu113/2022-04-14/smdistributed\$1dataparallel-1.4.1-cp38-cp38-linux\$1x86\$164.whl | 

\$1\$1 二進位檔案的 URL 用於在自訂容器中安裝 SMDDP 程式庫。如需詳細資訊，請參閱[使用 SageMaker AI 分散式資料平行程式庫建立您自己的 Docker 容器](data-parallel-bring-your-own-container.md)。

**注意**  
SMDDP 程式庫可在 AWS 區域 [SageMaker AI Framework Containers](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only) 和 [SMP Docker 映像](distributed-model-parallel-support-v2.md)正在使用的 中使用。

**注意**  
SMDDP 程式庫 v1.4.0 和更新版本可做為 PyTorch 分散式 (torch.distributed) 資料平行化 (torch.parallel.DistributedDataParallel) 的後端。根據這項變更，下列適用於 PyTorch 分散式套件的[小型分散式 API](https://sagemaker.readthedocs.io/en/stable/api/training/sdp_versions/latest/smd_data_parallel_pytorch.html#pytorch-api) 已停用。  
`smdistributed.dataparallel.torch.distributed` 已棄用。請改用 [torch.distributed](https://pytorch.org/docs/stable/distributed.html) 套件。
`smdistributed.dataparallel.torch.parallel.DistributedDataParallel` 已棄用。請改用 [torch.nn.parallel.DistributedDataParallel](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) API。
如果您需要使用舊版本程式庫 (v1.3.0 或更新版本)，請參閱 *SageMaker AI Python SDK 文件*中的[封存 SageMaker AI 分散式資料平行化文件](https://sagemaker.readthedocs.io/en/stable/api/training/sdp_versions/latest.html#documentation-archive)。

### PyTorch Lightning
<a name="distributed-data-parallel-supported-frameworks-lightning"></a>

SMDDP 程式庫可用於以下適用於 PyTorch 的 SageMaker AI 架構容器和 SMP Docker 容器中的 PyTorch Lightning。

**PyTorch Lightning v2**


| PyTorch Lightning 版本 | PyTorch 版本 | SMDDP 程式庫版本 | 預先安裝 SMDDP 的 SageMaker AI 架構容器映像檔 | 預先安裝 SMDDP 的 SMP Docker 映像檔 | 二進位檔案的網址\$1\$1 | 
| --- | --- | --- | --- | --- | --- | 
| 2.2.5 | 2.3.0 | smdistributed-dataparallel==v2.3.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.3.0-gpu-py311-cu121-ubuntu20.04-sagemaker | 目前無法使用 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.3.0/cu121/2024-05-23/smdistributed\$1dataparallel-2.3.0-cp311-cp311-linux\$1x86\$164.whl | 
| 2.2.0 | 2.2.0 | smdistributed-dataparallel==v2.2.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.2.0-gpu-py310-cu121-ubuntu20.04-sagemaker | 658645717510.dkr.ecr.<region>.amazonaws.com/smdistributed-modelparallel:2.2.0-gpu-py310-cu121 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.2.0/cu121/2024-03-04/smdistributed\$1dataparallel-2.2.0-cp310-cp310-linux\$1x86\$164.whl | 
| 2.1.2 | 2.1.0 | smdistributed-dataparallel==v2.1.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.1.0-gpu-py310-cu121-ubuntu20.04-sagemaker | 658645717510.dkr.ecr.<region>.amazonaws.com/smdistributed-modelparallel:2.1.2-gpu-py310-cu121 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.1.0/cu121/2024-02-04/smdistributed\$1dataparallel-2.1.0-cp310-cp310-linux\$1x86\$164.whl | 
| 2.1.0 | 2.0.1 | smdistributed-dataparallel==v2.0.1 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.0.1-gpu-py310-cu118-ubuntu20.04-sagemaker | 不適用 | https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.0.1/cu118/2023-12-07/smdistributed\$1dataparallel-2.0.2-cp310-cp310-linux\$1x86\$164.whl | 

**PyTorch Lightning v1**


| PyTorch Lightning 版本 | PyTorch 版本 | SMDDP 程式庫版本 | 預先安裝 SMDDP 的 SageMaker AI 架構容器映像檔 | 二進位檔案 URL \$1\$1 | 
| --- | --- | --- | --- | --- | 
|  1.7.2 1.7.0 1.6.4 1.6.3 1.5.10  | 1.12.0 | smdistributed-dataparallel==v1.5.0 | 763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:1.12.0-gpu-py38-cu113-ubuntu20.04-sagemaker | https://smdataparallel.s3.amazonaws.com/binary/pytorch/1.12.0/cu113/2022-07-01/smdistributed\$1dataparallel-1.5.0-cp38-cp38-linux\$1x86\$164.whl | 

\$1\$1 二進位檔案的 URL 用於在自訂容器中安裝 SMDDP 程式庫。如需詳細資訊，請參閱[使用 SageMaker AI 分散式資料平行程式庫建立您自己的 Docker 容器](data-parallel-bring-your-own-container.md)。

**注意**  
PyTorch Lightning 及公用程式程式庫 (例如 Lightning Bolts) 未預先安裝於 PyTorch DLC。在[步驟 2](https://docs.aws.amazon.com/sagemaker/latest/dg/data-parallel-use-api.html#data-parallel-framework-estimator) 建構 SageMaker AI PyTorch 估算器並提交訓練任務請求時，您必須提供 `requirements.txt`，以在 SageMaker AI PyTorch 訓練容器中安裝 `pytorch-lightning` 與 `lightning-bolts`。  

```
# requirements.txt
pytorch-lightning
lightning-bolts
```
如需指定來源目錄以放置 `requirements.txt` 檔案和訓練指令碼以及工作提交的更多相關資訊，請參閱 *Amazon SageMaker AI Python SDK 文件*中的[使用第三方程式庫](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#id12)。

### Hugging Face 轉換器
<a name="distributed-data-parallel-supported-frameworks-transformers"></a>

適用於 Hugging Face 的 AWS 深度學習容器使用適用於 PyTorch 和 TensorFlow 的 SageMaker 訓練容器作為其基礎映像。若要查詢 Hugging Face 轉換器程式庫版本及配對的 PyTorch 和 TensorFlow 版本，請參閱最新的 [Hugging Face 容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#huggingface-training-containers)和[先前的 Hugging Face 容器版本](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#prior-hugging-face-container-versions)。

### TensorFlow (已棄用)
<a name="distributed-data-parallel-supported-frameworks-tensorflow"></a>

**重要**  
SMDDP 程式庫已停止對 TensorFlow 的支援，且不再於 v2.11.0 之後的 TensorFlow DLC 中提供。下表列出已安裝 SMDDP 程式庫的舊版 TensorFlow DLC。


| TensorFlow 版本 | SMDDP 程式庫版本 | 
| --- | --- | 
| 2.9.1、2.10.1、2.11.0 |  smdistributed-dataparallel==v1.4.1  | 
| 2.8.3 |  smdistributed-dataparallel==v1.3.0  | 

## AWS 區域
<a name="distributed-data-parallel-availablity-zone"></a>

SMDDP 程式庫可在 SageMaker AI 的 AWS 區域 深度學習容器和 [SMP Docker 映像](distributed-model-parallel-support-v2.md)正在使用的所有 中使用。 [AWS SageMaker ](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only) 

## 支援的執行個體類型
<a name="distributed-data-parallel-supported-instance-types"></a>

SMDDP 程式庫需要下列其中一種執行個體類型。


| 執行個體類型 | 
| --- | 
| ml.p3dn.24xlarge\$1 | 
| ml.p4d.24xlarge | 
| ml.p4de.24xlarge | 

**提示**  
若要在已啟用 EFA 的執行個體類型上正確執行分散式訓練，您應該透過設定 VPC 的安全群組來啟用執行個體之間的流量，以允許進出安全群組本身的所有傳入和傳出流量。若要了解如何設定安全群組規則，請參閱《Amazon EC2 使用者指南》**中的[步驟 1：準備啟用 EFA 的安全群組](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html#efa-start-security)。

**重要**  
\$1 SMDDP 程式庫已停止支援在 P3 執行個體上最佳化其集體通訊操作。雖然您仍然可以在 `ml.p3dn.24xlarge` 執行個體上利用 SMDDP 最佳化的 `AllReduce` 集體，但將不再提供進一步的開發支援來增強此執行個體類型的效能。請注意，SMDDP 最佳化的 `AllGather` 集體僅適用於 P4 執行個體。

如需執行個體類型的空間，請參閱 [Amazon EC2 執行個體類型頁面](https://aws.amazon.com/ec2/instance-types/)中的**加速運算**區段。有關執行個體定價資訊，請參閱 [Amazon SageMaker 定價](https://aws.amazon.com/sagemaker/pricing/)。

如果您遇到類似下列內容的錯誤訊息，請按照[請求 SageMaker AI 資源服務配額增加](https://docs.aws.amazon.com/sagemaker/latest/dg/regions-quotas.html#service-limit-increase-request-procedure)的指示進行操作。

```
ResourceLimitExceeded: An error occurred (ResourceLimitExceeded) when calling
the CreateTrainingJob operation: The account-level service limit 'ml.p3dn.24xlarge
for training job usage' is 0 Instances, with current utilization of 0 Instances
and a request delta of 1 Instances.
Please contact AWS support to request an increase for this limit.
```

# 使用 SageMaker AI 分散式資料平行化程式庫進行分散式訓練
<a name="data-parallel-modify-sdp"></a>

SageMaker AI 分散式資料平行化 (SMDDP) 程式庫旨在簡化使用，並提供與 PyTorch 的無縫整合。

在 SageMaker AI 使用 SMDDP 程式庫訓練深度學習模型時，您可以專注於撰寫訓練指令碼和模型訓練。

若要開始使用，請匯入 SMDDP 程式庫，以使用其針對 AWS最佳化的集體操作。下列主題會根據您要最佳化的集體操作，提供如何新增至訓練指令碼的指示。

**Topics**
+ [調整訓練指令碼以使用 SMDDP 集體操作](data-parallel-modify-sdp-select-framework.md)
+ [使用 SageMaker Python SDK 透過 SMDDP 啟動分散式訓練任務](data-parallel-use-api.md)

# 調整訓練指令碼以使用 SMDDP 集體操作
<a name="data-parallel-modify-sdp-select-framework"></a>

本節提供的訓練指令碼範例經過簡化，並僅強調在訓練指令碼中啟用 SageMaker AI 分散式資料平行化 (SMDDP) 程式庫所需的變更。如需示範如何使用 SMDDP 程式庫執行分散式訓練作業的端對端 Jupyter 筆記本範例，請參閱 [Amazon SageMaker AI 資料平行程式庫範例](distributed-data-parallel-v2-examples.md)。

**Topics**
+ [在 PyTorch 訓練指令碼中使用 SMDDP 程式庫](data-parallel-modify-sdp-pt.md)
+ [在 PyTorch Lightning 訓練指令碼中使用 SMDDP 程式庫](data-parallel-modify-sdp-pt-lightning.md)
+ [在 TensorFlow 訓練指令碼中使用 SMDDP 程式庫 (已棄用)](data-parallel-modify-sdp-tf2.md)

# 在 PyTorch 訓練指令碼中使用 SMDDP 程式庫
<a name="data-parallel-modify-sdp-pt"></a>

從 SageMaker AI 分散式資料平行化 (SMDDP) 程式庫 v1.4.0 開始，您可以使用程式庫做為 [PyTorch 分散式套件](https://pytorch.org/tutorials/beginner/dist_overview.html)的後端選項。若要使用 SMDDP `AllReduce` 和 `AllGather` 集體操作，您只需在訓練指令碼開頭匯入 SMDDP 程式庫，並在程序群組初始化期間將 SMDDP 設定為 PyTorch 分散式模組的後端。只需一行後端規範，您就可以保持所有原生 PyTorch 分散式模組和整個訓練指令碼不變。下列程式碼片段示範如何使用 SMDDP 程式庫做為 PyTorch 型分散式訓練套件的後端：[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 DDP 或 FSDP
<a name="data-parallel-enable-for-ptddp-ptfsdp"></a>

初始化程序群組，如下所示。

```
import torch.distributed as dist
import smdistributed.dataparallel.torch.torch_smddp

dist.init_process_group(backend="smddp")
```

**注意**  
(僅適用於 PyTorch DDP 任務) `smddp` 後端目前不支援使用 `torch.distributed.new_group()` API 建立子程序群組。您也無法與其他程序群組後端 (例如 `NCCL` 和 `Gloo`) 同時使用 `smddp` 後端。

## 對於 DeepSpeed 或 Megatron-DeepSpeed
<a name="data-parallel-enable-for-deepspeed"></a>

初始化程序群組，如下所示。

```
import deepspeed
import smdistributed.dataparallel.torch.torch_smddp

deepspeed.init_distributed(dist_backend="smddp")
```

**注意**  
若要在 [使用 SageMaker Python SDK 透過 SMDDP 啟動分散式訓練任務](data-parallel-use-api.md) 中使用 SMDDP `AllGather` 搭配 `mpirun` 型啟動器 (`smdistributed` 和 `pytorchddp`)，您也需要在訓練指令碼中設定下列環境變數。  

```
export SMDATAPARALLEL_OPTIMIZE_SDP=true
```

如需撰寫 PyTorch FSDP 訓練指令碼的一般指引，請參閱 PyTorch 文件中的[使用全碎片資料平行化 (FSDP) 的進階模型訓練](https://pytorch.org/tutorials/intermediate/FSDP_adavnced_tutorial.html)。

如需撰寫 PyTorch DDP 訓練指令碼的一般指引，請參閱 PyTorch 文件中的[分散式資料平行化入門](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html)。

完成訓練指令碼的調整後，請繼續前往[使用 SageMaker Python SDK 透過 SMDDP 啟動分散式訓練任務](data-parallel-use-api.md)。

# 在 PyTorch Lightning 訓練指令碼中使用 SMDDP 程式庫
<a name="data-parallel-modify-sdp-pt-lightning"></a>

如果您想使用 [PyTorch Lightning](https://pytorch-lightning.readthedocs.io/en/latest/starter/introduction.html) 訓練指令碼，並在 SageMaker AI 執行分散式資料平行化訓練任務，您只需對訓練指令碼進行最少的修改即可執行訓練任務。必要的變更包如下：匯入 `smdistributed.dataparallel` 程式庫的 PyTorch 模組、設定 PyTorch Lightning 的環境變數以接受 SageMaker AI 訓練工具組預設的 SageMaker AI 環境變數，以及將程序群組後端設定為 `"smddp"` 以啟動 SMDDP 程式庫。若要進一步了解，請逐步執行以程式碼範例分解步驟的下列指示。

**注意**  
SageMaker AI 資料平行化程式庫 v1.5.0 及更新版本提供 PyTorch Lightning 支援。

## PyTorch Lightning == v2.1.0 和 PyTorch == 2.0.1
<a name="smddp-pt-201-lightning-210"></a>

1. 匯入 `pytorch_lightning` 程式庫和 `smdistributed.dataparallel.torch` 模組。

   ```
   import lightning as pl
   import smdistributed.dataparallel.torch.torch_smddp
   ```

1. 執行個體化 [LightningEnvironment](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.plugins.environments.LightningEnvironment.html)。

   ```
   from lightning.fabric.plugins.environments.lightning import LightningEnvironment
   
   env = LightningEnvironment()
   env.world_size = lambda: int(os.environ["WORLD_SIZE"])
   env.global_rank = lambda: int(os.environ["RANK"])
   ```

1. **對於 PyTorch DDP** – 建立 [DDPStrategy](https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.strategies.DDPStrategy.html) 類別的物件並將 `process_group_backend` 設為 `"smddp"`、將 `accelerator` 設為 `"gpu"`，然後將其傳遞給 [Trainer](https://pytorch-lightning.readthedocs.io/en/stable/common/trainer.html) 類別。

   ```
   import lightning as pl
   from lightning.pytorch.strategies import DDPStrategy
   
   ddp = DDPStrategy(
       cluster_environment=env, 
       process_group_backend="smddp", 
       accelerator="gpu"
   )
   
   trainer = pl.Trainer(
       max_epochs=200, 
       strategy=ddp, 
       devices=num_gpus, 
       num_nodes=num_nodes
   )
   ```

   **對於 PyTorch FSDP** – 建立 [FSDPStrategy](https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.strategies.FSDPStrategy.html) 類別的物件 (搭配自行選擇的[包裝政策](https://pytorch.org/docs/stable/fsdp.html)) 並將 `process_group_backend` 設為 `"smddp"`、將 `accelerator` 設為 `"gpu"`，然後將其傳遞給 [Trainer](https://pytorch-lightning.readthedocs.io/en/stable/common/trainer.html) 類別。

   ```
   import lightning as pl
   from lightning.pytorch.strategies import FSDPStrategy
   
   from functools import partial
   from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy
   
   policy = partial(
       size_based_auto_wrap_policy, 
       min_num_params=10000
   )
   
   fsdp = FSDPStrategy(
       auto_wrap_policy=policy,
       process_group_backend="smddp", 
       cluster_environment=env
   )
   
   trainer = pl.Trainer(
       max_epochs=200, 
       strategy=fsdp, 
       devices=num_gpus, 
       num_nodes=num_nodes
   )
   ```

完成訓練指令碼的調整後，請繼續前往[使用 SageMaker Python SDK 透過 SMDDP 啟動分散式訓練任務](data-parallel-use-api.md)。

**注意**  
在 [使用 SageMaker Python SDK 透過 SMDDP 啟動分散式訓練任務](data-parallel-use-api.md) 中建構 SageMaker AI PyTorch 估算器並提交訓練任務請求時，您必須提供 `requirements.txt` 以在 SageMaker AI PyTorch 訓練容器中安裝 `pytorch-lightning` 與 `lightning-bolts`。  

```
# requirements.txt
pytorch-lightning
lightning-bolts
```
如需指定來源目錄以放置 `requirements.txt` 檔案和訓練指令碼以及工作提交的更多相關資訊，請參閱 *Amazon SageMaker AI Python SDK 文件*中的[使用第三方程式庫](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#id12)。

# 在 TensorFlow 訓練指令碼中使用 SMDDP 程式庫 (已棄用)
<a name="data-parallel-modify-sdp-tf2"></a>

**重要**  
SMDDP 程式庫已停止對 TensorFlow 的支援，且不再於 v2.11.0 之後的 TensorFlow DLC 中提供。若要尋找已安裝 SMDDP 程式庫的舊版 TensorFlow DLC，請參閱[支援的架構](distributed-data-parallel-support.md#distributed-data-parallel-supported-frameworks)。

下列步驟說明如何修改 TensorFlow 訓練指令碼，利用 SageMaker AI 的分散式資料平行化資料庫。  

程式庫 API 的設計旨在近似 Horovod API。請參閱 [SageMaker AI 分散式資料平行化 TensorFlow API 文件](https://sagemaker.readthedocs.io/en/stable/api/training/smd_data_parallel.html#api-documentation)，了解程式庫為 TensorFlow 提供之每個 API 的其他詳細資訊。

**注意**  
SageMaker AI 分散式資料平行化可配合包含 `tf` 核心模組的 TensorFlow 訓練指令碼 (`tf.keras` 模組除外) 調整。SageMaker AI 分散式資料平行化不支援包含 Keras 實作的 TensorFlow。

**注意**  
SageMaker AI 分散式資料平行化程式庫支援開箱即用的自動混合精確度 (AMP)。除了對訓練指令碼進行架構層級修改之外，無需執行任何額外操作即可啟用 AMP。如果梯度是 FP16，SageMaker AI 資料平行化程式庫會以 FP16 執行其 `AllReduce` 操作。有關將 AMP API 實施到訓練腳本的詳細資訊，請參閱以下資源：  
[架構 - ](https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/index.html#tensorflow)*NVIDIA 深度學習效能文件中的 TensorFlow*
*NVIDIA 開發人員文件*中[適用於深度學習的自動混合精確度](https://developer.nvidia.com/automatic-mixed-precision)
*TensorFlow 文件*中的 [TensorFlow 混合精確度 API](https://www.tensorflow.org/guide/mixed_precision)

1. 匯入程式庫的 TensorFlow 用戶端並將其初始化。

   ```
   import smdistributed.dataparallel.tensorflow as sdp 
   sdp.init()
   ```

1. 使用 `local_rank` 將每個 GPU 固定到單一 `smdistributed.dataparallel` 程序-這是指特定節點內程序的相對等級。`sdp.tensorflow.local_rank()` API 為您提供裝置的本地排名。領導節點是等級 0，工作者節點是等級 1、2、3，依此類推。這在下列程式碼區塊中調用為 `sdp.local_rank()`。`set_memory_growth` 與分散式 SageMaker AI 沒有直接相關，但必須針對使用 TensorFlow 的分散式訓練進行設定。

   ```
   gpus = tf.config.experimental.list_physical_devices('GPU')
   for gpu in gpus:
       tf.config.experimental.set_memory_growth(gpu, True)
   if gpus:
       tf.config.experimental.set_visible_devices(gpus[sdp.local_rank()], 'GPU')
   ```

1. 按工作者數量調整學習速率。`sdp.tensorflow.size()` API 提供叢集中的工作者數量。這在下列程式碼區塊中調用為 `sdp.size()`。

   ```
   learning_rate = learning_rate * sdp.size()
   ```

1. 使用程式庫的 `DistributedGradientTape`，在訓練期間最佳化 `AllReduce` 操作。這包含 `tf.GradientTape`。  

   ```
   with tf.GradientTape() as tape:
         output = model(input)
         loss_value = loss(label, output)
       
   # SageMaker AI data parallel: Wrap tf.GradientTape with the library's DistributedGradientTape
   tape = sdp.DistributedGradientTape(tape)
   ```

1. 廣播從領導節點 (排名 0) 到所有工作者節點 (排名 1 到 n) 的初始模型變數。為了確保所有工作者排名初始化一致，必須這麼做。初始化模型和最佳化工具變數後，請使用 `sdp.tensorflow.broadcast_variables` API。這在下面的程式碼塊中調用為 `sdp.broadcast_variables()`。

   ```
   sdp.broadcast_variables(model.variables, root_rank=0)
   sdp.broadcast_variables(opt.variables(), root_rank=0)
   ```

1. 最後，修改指令碼，僅在領導節點保存檢查點。領導節點有同步化的模型。這也可避免工作者節點覆寫檢查點，以及可能損壞檢查點。

   ```
   if sdp.rank() == 0:
       checkpoint.save(checkpoint_dir)
   ```

以下是 TensorFlow 訓練指令碼範例，適用於使用程式庫進行分散式訓練。

```
import tensorflow as tf

# SageMaker AI data parallel: Import the library TF API
import smdistributed.dataparallel.tensorflow as sdp

# SageMaker AI data parallel: Initialize the library
sdp.init()

gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    tf.config.experimental.set_memory_growth(gpu, True)
if gpus:
    # SageMaker AI data parallel: Pin GPUs to a single library process
    tf.config.experimental.set_visible_devices(gpus[sdp.local_rank()], 'GPU')

# Prepare Dataset
dataset = tf.data.Dataset.from_tensor_slices(...)

# Define Model
mnist_model = tf.keras.Sequential(...)
loss = tf.losses.SparseCategoricalCrossentropy()

# SageMaker AI data parallel: Scale Learning Rate
# LR for 8 node run : 0.000125
# LR for single node run : 0.001
opt = tf.optimizers.Adam(0.000125 * sdp.size())

@tf.function
def training_step(images, labels, first_batch):
    with tf.GradientTape() as tape:
        probs = mnist_model(images, training=True)
        loss_value = loss(labels, probs)

    # SageMaker AI data parallel: Wrap tf.GradientTape with the library's DistributedGradientTape
    tape = sdp.DistributedGradientTape(tape)

    grads = tape.gradient(loss_value, mnist_model.trainable_variables)
    opt.apply_gradients(zip(grads, mnist_model.trainable_variables))

    if first_batch:
       # SageMaker AI data parallel: Broadcast model and optimizer variables
       sdp.broadcast_variables(mnist_model.variables, root_rank=0)
       sdp.broadcast_variables(opt.variables(), root_rank=0)

    return loss_value

...

# SageMaker AI data parallel: Save checkpoints only from master node.
if sdp.rank() == 0:
    checkpoint.save(checkpoint_dir)
```

完成訓練指令碼的調整後，請繼續前往 [使用 SageMaker Python SDK 透過 SMDDP 啟動分散式訓練任務](data-parallel-use-api.md)。

# 使用 SageMaker Python SDK 透過 SMDDP 啟動分散式訓練任務
<a name="data-parallel-use-api"></a>

若要使用來自 [調整訓練指令碼以使用 SMDDP 集體操作](data-parallel-modify-sdp-select-framework.md) 的改編指令碼執行分散式訓練任務，請使用 SageMaker Python SDK 的架構或一般估算器，方法是將準備好的訓練指令碼指定為進入點指令碼和分散式訓練組態。

此頁面說明如何以兩種方式使用 [SageMaker AI Python SDK](https://sagemaker.readthedocs.io/en/stable/api/training/index.html)。
+ 如果您想要在 SageMaker AI 中快速採用分散式訓練任務，請設定 SageMaker AI [PyTorch](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html#sagemaker.pytorch.estimator.PyTorch) 或 [TensorFlow](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.html#tensorflow-estimator) 架構估算器類別。架構估算器會挑選您的訓練指令碼，並自動比對[預先建置的 PyTorch 或 TensorFlow 深度學習容器 (DLC](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only)) 的正確映像 URI，且根據指定給 `framework_version` 參數的值來執行。
+ 如果您想要擴充其中一個預先建置的容器，或建立自訂容器以使用 SageMaker AI 建立自己的機器學習 (ML) 環境，請使用 SageMaker AI 一般 `Estimator` 類別，並指定託管在 Amazon Elastic Container Registry (Amazon ECR) 中的自訂 Docker 容器的映像 URI。

您的訓練資料集應存放在 Amazon S3 或 [Amazon FSx for Lustre](https://docs.aws.amazon.com/fsx/latest/LustreGuide/what-is.html)，位於您啟動訓練任務 AWS 區域 的 中。如果您使用 Jupyter 筆記本，您應該有一個 SageMaker 筆記本執行個體或 SageMaker Studio Classic 應用程式在同樣的 AWS 區域中執行。有關儲存訓練資料的詳細資訊，請參閱 [SageMaker Python SDK 資料輸入](https://sagemaker.readthedocs.io/en/stable/overview.html#use-file-systems-as-training-input) 文件。

**提示**  
建議您使用 Amazon FSx for Lustre，而不是 Amazon S3 來改進訓練效能。Amazon FSx 具有比 Amazon S3 更高的輸送量和更低的延遲。

**提示**  
若要在已啟用 EFA 的執行個體類型上正確執行分散式訓練，您應該透過設定 VPC 的安全群組來啟用執行個體之間的流量，以允許進出安全群組本身的所有傳入和傳出流量。若要了解如何設定安全群組規則，請參閱《Amazon EC2 使用者指南》**中的[步驟 1：準備啟用 EFA 的安全群組](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-start.html#efa-start-security)。

選擇下列其中一個主題，以取得如何執行訓練指令碼分散式訓練任務的指示。啟動訓練任務後，您可以使用 [Amazon SageMaker Debugger](train-debugger.md) 或 Amazon CloudWatch 監控系統使用率和模型效能。

當您按照下列主題中的指示進一步了解技術詳細資訊時，我們也建議您嘗試開始使用[Amazon SageMaker AI 資料平行程式庫範例](distributed-data-parallel-v2-examples.md)。

**Topics**
+ [在 SageMaker Python SDK 中使用 PyTorch 架構估算器](data-parallel-framework-estimator.md)
+ [使用 SageMaker AI 一般估算器來擴充預先建置的 DLC 容器](data-parallel-use-python-skd-api.md)
+ [使用 SageMaker AI 分散式資料平行程式庫建立您自己的 Docker 容器](data-parallel-bring-your-own-container.md)

# 在 SageMaker Python SDK 中使用 PyTorch 架構估算器
<a name="data-parallel-framework-estimator"></a>

您可以將 `distribution` 引數新增至 SageMaker AI 架構估算器 [https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html#sagemaker.pytorch.estimator.PyTorch](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/sagemaker.pytorch.html#sagemaker.pytorch.estimator.PyTorch) 或 [https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.html#tensorflow-estimator](https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/sagemaker.tensorflow.html#tensorflow-estimator)，以啟動分散式訓練。如需詳細資訊，請從下列選項中選擇 SageMaker AI 分散式資料平行化 (SMDDP) 程式庫支援的其中一個架構。

------
#### [ PyTorch ]

下列啟動器選項可用於啟動 PyTorch 分散式訓練。
+ `pytorchddp` – 此選項會執行 `mpirun` 並設定在 SageMaker AI 上執行 PyTorch 分散式訓練所需的環境變數。若要使用此選項，請將下列字典傳遞至 `distribution` 參數。

  ```
  { "pytorchddp": { "enabled": True } }
  ```
+ `torch_distributed` – 此選項會執行 `torchrun` 並設定在 SageMaker AI 上執行 PyTorch 分散式訓練所需的環境變數。若要使用此選項，請將下列字典傳遞至 `distribution` 參數。

  ```
  { "torch_distributed": { "enabled": True } }
  ```
+ `smdistributed` – 此選項也會執行 `mpirun`，但使用 `smddprun` 設定在 SageMaker AI 上執行 PyTorch 分散式訓練所需的環境變數。

  ```
  { "smdistributed": { "dataparallel": { "enabled": True } } }
  ```

如果您選擇將 NCCL `AllGather` 取代為 SMDDP `AllGather`，您可以使用全部三個選項。選擇一個符合您使用案例的選項。

如果您選擇將 NCCL `AllReduce` 取代為 SMDDP `AllReduce`，您應該選擇其中一個 `mpirun` 型選項：`smdistributed` 或 `pytorchddp`。您也可以新增其他 MPI 選項，如下所示。

```
{ 
    "pytorchddp": {
        "enabled": True, 
        "custom_mpi_options": "-verbose -x NCCL_DEBUG=VERSION"
    }
}
```

```
{ 
    "smdistributed": { 
        "dataparallel": {
            "enabled": True, 
            "custom_mpi_options": "-verbose -x NCCL_DEBUG=VERSION"
        }
    }
}
```

下列程式碼範例顯示具有分散式訓練選項的 PyTorch 估算器的基本結構。

```
from sagemaker.pytorch import PyTorch

pt_estimator = PyTorch(
    base_job_name="training_job_name_prefix",
    source_dir="subdirectory-to-your-code",
    entry_point="adapted-training-script.py",
    role="SageMakerRole",
    py_version="py310",
    framework_version="2.0.1",

    # For running a multi-node distributed training job, specify a value greater than 1
    # Example: 2,3,4,..8
    instance_count=2,

    # Instance types supported by the SageMaker AI data parallel library: 
    # ml.p4d.24xlarge, ml.p4de.24xlarge
    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
)

pt_estimator.fit("s3://bucket/path/to/training/data")
```

**注意**  
PyTorch Lightning 及其公用程式庫 (例如 Lightning Bolts) 未預先安裝在 SageMaker AI PyTorch DLC 中。建立下列 `requirements.txt` 檔案並儲存在存放訓練指令碼的來源目錄中。  

```
# requirements.txt
pytorch-lightning
lightning-bolts
```
例如，tree-structured 目錄看起來應該如下所示。  

```
├── pytorch_training_launcher_jupyter_notebook.ipynb
└── sub-folder-for-your-code
    ├──  adapted-training-script.py
    └──  requirements.txt
```
如需指定來源目錄以放置 `requirements.txt` 檔案和訓練指令碼以及工作提交的更多相關資訊，請參閱 *Amazon SageMaker AI Python SDK 文件*中的[使用第三方程式庫](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#id12)。

**啟用 SMDDP 集合操作和使用正確分散式訓練啟動器選項的考量**
+ SMDDP `AllReduce` 和 SMDDP `AllGather` 目前不可相互相容。
+ 使用 `smdistributed` 或 `pytorchddp` (`mpirun` 型啟動器) 時，預設會啟用 SMDDP `AllReduce`，並使用 NCCL `AllGather`。
+ 使用 `torch_distributed` 啟動器時，預設會啟用 SMDDP `AllGather`，且 `AllReduce` 會回復為 NCCL。
+ 使用 `mpirun` 型啟動器搭配額外的環境變數集時，SMDDP `AllGather` 也會啟用，如下所示。

  ```
  export SMDATAPARALLEL_OPTIMIZE_SDP=true
  ```

------
#### [ TensorFlow ]

**重要**  
SMDDP 程式庫已停止對 TensorFlow 的支援，且不再於 v2.11.0 之後的 TensorFlow DLC 中提供。若要尋找已安裝 SMDDP 程式庫的舊版 TensorFlow DLCs，請參閱[TensorFlow (已棄用)](distributed-data-parallel-support.md#distributed-data-parallel-supported-frameworks-tensorflow)。

```
from sagemaker.tensorflow import TensorFlow

tf_estimator = TensorFlow(
    base_job_name = "training_job_name_prefix",
    entry_point="adapted-training-script.py",
    role="SageMakerRole",
    framework_version="2.11.0",
    py_version="py38",

    # For running a multi-node distributed training job, specify a value greater than 1
    # Example: 2,3,4,..8
    instance_count=2,

    # Instance types supported by the SageMaker AI data parallel library: 
    # ml.p4d.24xlarge, ml.p3dn.24xlarge, and ml.p3.16xlarge
    instance_type="ml.p3.16xlarge",

    # Training using the SageMaker AI data parallel distributed training strategy
    distribution={ "smdistributed": { "dataparallel": { "enabled": True } } }
)

tf_estimator.fit("s3://bucket/path/to/training/data")
```

------

# 使用 SageMaker AI 一般估算器來擴充預先建置的 DLC 容器
<a name="data-parallel-use-python-skd-api"></a>

您可以自訂 SageMaker AI 預先建置的容器，或加以擴充，以處理 SageMaker AI Docker 映像檔不支援的演算法或模型的任何其他功能需求。有關如何擴展預構建容器的範例，請參閱[擴展預構建的容器](https://docs.aws.amazon.com/sagemaker/latest/dg/prebuilt-containers-extend.html)。

若要擴充預先建置的容器或調整您自己的容器以使用程式庫，您必須使用 [支援的架構](distributed-data-parallel-support.md#distributed-data-parallel-supported-frameworks) 中列出的其中一個映像。

**注意**  
從 TensorFlow 2.4.1 和 PyTorch 1.8.1 開始，SageMaker AI 架構 DLC 支援 EFA 型執行個體類型。建議您使用包含 TensorFlow 2.4.1 或較新版本的 DLC 映像，以及 PyTorch 1.8.1 或較新版本。

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

```
# SageMaker AI PyTorch image
FROM 763104351884.dkr.ecr.<aws-region>.amazonaws.com/pytorch-training:<image-tag>

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

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

# /opt/ml and all subdirectories are utilized by SageMaker AI, use the /code subdirectory to store your user code.
COPY train.py /opt/ml/code/train.py

# Defines cifar10.py as script entrypoint
ENV SAGEMAKER_PROGRAM train.py
```

您可以使用 [SageMaker AI 訓練工具組](https://github.com/aws/sagemaker-training-toolkit)和 SageMaker AI 分散式資料平行程式庫的二進位檔案，進一步自訂您自己的 Docker 容器，以便與 SageMaker AI 搭配使用。如需進一步了解，請參閱下一節中的指示。

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

若要建置自己的 Docker 容器以進行訓練並使用 SageMaker AI 資料平行程式庫，您必須在 Docerfile 中包含 SageMaker AI 分散式平行程式庫的正確相依性和二進位檔案。本節提供有關如何使用資料平行程式庫在 SageMaker AI 中針對分散式訓練建立具有最小相依性集的完整 Dockerfile 之指示。

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

**若要使用 SageMaker 訓練工具組和資料平行程式庫建立 Dockerfile**

1. 從 [NVIDIA CUDA](https://hub.docker.com/r/nvidia/cuda) 的 Docker 映像開始。使用包含 CUDA 執行期和開發工具 (標題和程式庫) 的 cuDNN 開發人員版本，從 [PyTorch 原始程式碼](https://github.com/pytorch/pytorch#from-source)進行建置。

   ```
   FROM nvidia/cuda:11.3.1-cudnn8-devel-ubuntu20.04
   ```
**提示**  
官方 AWS 深度學習容器 (DLC) 映像是從 [NVIDIA CUDA 基礎映像](https://hub.docker.com/r/nvidia/cuda)建置而成。如想使用預先建置的 DLC 映像做為參考，同時遵循其餘指示，請參閱[適用於 PyTorch Dockerfiles 的AWS 深度學習容器](https://github.com/aws/deep-learning-containers/tree/master/pytorch)。

1. 新增下列引數以指定 PyTorch 和其他套件的版本。此外，請指出到 SageMaker AI 資料平行程式庫的 Amazon S3 儲存貯體路徑，以及其他軟體以使用 AWS 資源 (例如 Amazon S3 外掛程式)。

   若要使用下列程式碼範例中提供的版本以外的第三方程式庫版本，建議您查看適用於 [ PyTorch 的 AWS Deep Learning Container 官方 Dockerfiles](https://github.com/aws/deep-learning-containers/tree/master/pytorch/training/docker)，以尋找經過測試、相容且適合您的應用程式的版本。

   若要尋找 `SMDATAPARALLEL_BINARY` 引數的 URL，請參閱[支援的架構](distributed-data-parallel-support.md#distributed-data-parallel-supported-frameworks)中的查詢資料表。

   ```
   ARG PYTORCH_VERSION=1.10.2
   ARG PYTHON_SHORT_VERSION=3.8
   ARG EFA_VERSION=1.14.1
   ARG SMDATAPARALLEL_BINARY=https://smdataparallel.s3.amazonaws.com/binary/pytorch/${PYTORCH_VERSION}/cu113/2022-02-18/smdistributed_dataparallel-1.4.0-cp38-cp38-linux_x86_64.whl
   ARG PT_S3_WHL_GPU=https://aws-s3-plugin.s3.us-west-2.amazonaws.com/binaries/0.0.1/1c3e69e/awsio-0.0.1-cp38-cp38-manylinux1_x86_64.whl
   ARG CONDA_PREFIX="/opt/conda"
   ARG BRANCH_OFI=1.1.3-aws
   ```

1. 設定下列環境變數，以妥善建置 SageMaker 訓練元件，並執行資料平行程式庫。您可以在後續步驟中將這些變數用於元件。

   ```
   # Set ENV variables required to build PyTorch
   ENV TORCH_CUDA_ARCH_LIST="7.0+PTX 8.0"
   ENV TORCH_NVCC_FLAGS="-Xfatbin -compress-all"
   ENV NCCL_VERSION=2.10.3
   
   # Add OpenMPI to the path.
   ENV PATH /opt/amazon/openmpi/bin:$PATH
   
   # Add Conda to path
   ENV PATH $CONDA_PREFIX/bin:$PATH
   
   # Set this enviroment variable for SageMaker AI to launch SMDDP correctly.
   ENV SAGEMAKER_TRAINING_MODULE=sagemaker_pytorch_container.training:main
   
   # Add enviroment variable for processes to be able to call fork()
   ENV RDMAV_FORK_SAFE=1
   
   # Indicate the container type
   ENV DLC_CONTAINER_TYPE=training
   
   # Add EFA and SMDDP to LD library path
   ENV LD_LIBRARY_PATH="/opt/conda/lib/python${PYTHON_SHORT_VERSION}/site-packages/smdistributed/dataparallel/lib:$LD_LIBRARY_PATH"
   ENV LD_LIBRARY_PATH=/opt/amazon/efa/lib/:$LD_LIBRARY_PATH
   ```

1. 在後續步驟中安裝或更新 `curl`、`wget` 和 `git`，以下載並建置套件。

   ```
   RUN --mount=type=cache,id=apt-final,target=/var/cache/apt \
       apt-get update && apt-get install -y  --no-install-recommends \
           curl \
           wget \
           git \
       && rm -rf /var/lib/apt/lists/*
   ```

1. 為 Amazon EC2 網路通訊安裝 [Elastic Fabric Adapter (EFA)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) 軟體。

   ```
   RUN DEBIAN_FRONTEND=noninteractive apt-get update
   RUN mkdir /tmp/efa \
       && cd /tmp/efa \
       && curl --silent -O https://efa-installer.amazonaws.com/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 \
       && rm -rf /tmp/efa
   ```

1. 安裝 [Conda](https://docs.conda.io/en/latest/) 以處理套件管理。

   ```
   RUN curl -fsSL -v -o ~/miniconda.sh -O  https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh  && \
       chmod +x ~/miniconda.sh && \
       ~/miniconda.sh -b -p $CONDA_PREFIX && \
       rm ~/miniconda.sh && \
       $CONDA_PREFIX/bin/conda install -y python=${PYTHON_SHORT_VERSION} conda-build pyyaml numpy ipython && \
       $CONDA_PREFIX/bin/conda clean -ya
   ```

1. 獲取、建置和安裝 PyTorch 及其相依項。我們[從原始程式碼建置 PyTorch](https://github.com/pytorch/pytorch#from-source)，因為我們需要控制 NCCL 版本，以確保與 [AWS OFI NCCL 外掛程式](https://github.com/aws/aws-ofi-nccl)的相容性。

   1. 按照 [PyTorch 官方 Dockerfile](https://github.com/pytorch/pytorch/blob/master/Dockerfile) 中的步驟，安裝建置相依項並設定 [ccache](https://ccache.dev/) 以加速重新編譯。

      ```
      RUN DEBIAN_FRONTEND=noninteractive \
          apt-get install -y --no-install-recommends \
              build-essential \
              ca-certificates \
              ccache \
              cmake \
              git \
              libjpeg-dev \
              libpng-dev \
          && rm -rf /var/lib/apt/lists/*
        
      # Setup ccache
      RUN /usr/sbin/update-ccache-symlinks
      RUN mkdir /opt/ccache && ccache --set-config=cache_dir=/opt/ccache
      ```

   1. 安裝 [PyTorch 常見的和 Linux 的相依項](https://github.com/pytorch/pytorch#install-dependencies)。

      ```
      # Common dependencies for PyTorch
      RUN conda install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses
      
      # Linux specific dependency for PyTorch
      RUN conda install -c pytorch magma-cuda113
      ```

   1. 複製 [PyTorch GitHub 儲存器](https://github.com/pytorch/pytorch)。

      ```
      RUN --mount=type=cache,target=/opt/ccache \
          cd / \
          && git clone --recursive https://github.com/pytorch/pytorch -b v${PYTORCH_VERSION}
      ```

   1. 安裝並建置特定的 [NCCL](https://developer.nvidia.com/nccl) 版本。若要這麼做，請將 PyTorch 的預設 NCCL 資料夾 (`/pytorch/third_party/nccl`) 中的內容取代為 NVIDIA 儲存庫中的特定 NCCL 版本。NCCL 版本已在本指南的步驟 3 中設定。

      ```
      RUN cd /pytorch/third_party/nccl \
          && rm -rf nccl \
          && git clone https://github.com/NVIDIA/nccl.git -b v${NCCL_VERSION}-1 \
          && cd nccl \
          && make -j64 src.build CUDA_HOME=/usr/local/cuda NVCC_GENCODE="-gencode=arch=compute_70,code=sm_70 -gencode=arch=compute_80,code=sm_80" \
          && make pkg.txz.build \
          && tar -xvf build/pkg/txz/nccl_*.txz -C $CONDA_PREFIX --strip-components=1
      ```

   1. 建置和安裝 PyTorch。此程序通常需稍微超過 1 小時才能完成。它是使用上一個步驟中所下載的 NCCL 版本。

      ```
      RUN cd /pytorch \
          && CMAKE_PREFIX_PATH="$(dirname $(which conda))/../" \
          python setup.py install \
          && rm -rf /pytorch
      ```

1. 建置並安裝 [AWS OFI NCCL 外掛程式](https://github.com/aws/aws-ofi-nccl)。這會啟用 SageMaker AI 資料平行程式庫的 [libfabric](https://github.com/ofiwg/libfabric) 支援。

   ```
   RUN DEBIAN_FRONTEND=noninteractive apt-get update \
       && apt-get install -y --no-install-recommends \
           autoconf \
           automake \
           libtool
   RUN mkdir /tmp/efa-ofi-nccl \
       && cd /tmp/efa-ofi-nccl \
       && 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=$CONDA_PREFIX \
       && make \
       && make install \
       && rm -rf /tmp/efa-ofi-nccl
   ```

1. 建置並安裝 [TorchVision](https://github.com/pytorch/vision.git)。

   ```
   RUN pip install --no-cache-dir -U \
       packaging \
       mpi4py==3.0.3
   RUN cd /tmp \
       && git clone https://github.com/pytorch/vision.git -b v0.9.1 \
       && cd vision \
       && BUILD_VERSION="0.9.1+cu111" python setup.py install \
       && cd /tmp \
       && rm -rf vision
   ```

1. 安裝及設定 OpenSSH。MPI 需要 OpenSSH 才能在容器之間進行通訊。允許 OpenSSH 不必要求確認就會與容器通話。

   ```
   RUN apt-get update \
       && apt-get install -y  --allow-downgrades --allow-change-held-packages --no-install-recommends \
       && apt-get install -y --no-install-recommends openssh-client openssh-server \
       && mkdir -p /var/run/sshd \
       && cat /etc/ssh/ssh_config | grep -v StrictHostKeyChecking > /etc/ssh/ssh_config.new \
       && echo "    StrictHostKeyChecking no" >> /etc/ssh/ssh_config.new \
       && mv /etc/ssh/ssh_config.new /etc/ssh/ssh_config \
       && rm -rf /var/lib/apt/lists/*
   
   # Configure OpenSSH so that nodes can communicate with each other
   RUN mkdir -p /var/run/sshd && \
    sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
   RUN rm -rf /root/.ssh/ && \
    mkdir -p /root/.ssh/ && \
    ssh-keygen -q -t rsa -N '' -f /root/.ssh/id_rsa && \
    cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys \
    && printf "Host *\n StrictHostKeyChecking no\n" >> /root/.ssh/config
   ```

1. 安裝 PT S3 外掛程式，以有效率地存取 Amazon S3 中的資料集。

   ```
   RUN pip install --no-cache-dir -U ${PT_S3_WHL_GPU}
   RUN mkdir -p /etc/pki/tls/certs && cp /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt
   ```

1. 安裝 [libboost](https://www.boost.org/) 程式庫。此套件需要用來連接 SageMaker AI 資料平行程式庫的非同步 IO 功能。

   ```
   WORKDIR /
   RUN wget https://sourceforge.net/projects/boost/files/boost/1.73.0/boost_1_73_0.tar.gz/download -O boost_1_73_0.tar.gz \
       && tar -xzf boost_1_73_0.tar.gz \
       && cd boost_1_73_0 \
       && ./bootstrap.sh \
       && ./b2 threading=multi --prefix=${CONDA_PREFIX} -j 64 cxxflags=-fPIC cflags=-fPIC install || true \
       && cd .. \
       && rm -rf boost_1_73_0.tar.gz \
       && rm -rf boost_1_73_0 \
       && cd ${CONDA_PREFIX}/include/boost
   ```

1. 安裝下列 SageMaker AI 工具以進行 PyTorch 訓練。

   ```
   WORKDIR /root
   RUN pip install --no-cache-dir -U \
       smclarify \
       "sagemaker>=2,<3" \
       sagemaker-experiments==0.* \
       sagemaker-pytorch-training
   ```

1. 最後，安裝 SageMaker AI 資料平行二進位檔案及其餘的相依項。

   ```
   RUN --mount=type=cache,id=apt-final,target=/var/cache/apt \
     apt-get update && apt-get install -y  --no-install-recommends \
     jq \
     libhwloc-dev \
     libnuma1 \
     libnuma-dev \
     libssl1.1 \
     libtool \
     hwloc \
     && rm -rf /var/lib/apt/lists/*
   
   RUN SMDATAPARALLEL_PT=1 pip install --no-cache-dir ${SMDATAPARALLEL_BINARY}
   ```

1. 建立完 Dockerfile 後，請參閱[調整您自己的訓練容器](https://docs.aws.amazon.com/sagemaker/latest/dg/adapt-training-container.html)，以了解如何建置 Docker 容器、在 Amazon ECR 中託管，以及使用 SageMaker Python SDK 執行訓練任務。

以下範例程式碼顯示了一個完整的 Dockerfile 於合併所有先前的程式碼區塊的情況。

```
# This file creates a docker image with minimum dependencies to run SageMaker AI data parallel training
FROM nvidia/cuda:11.3.1-cudnn8-devel-ubuntu20.04

# Set appropiate versions and location for components
ARG PYTORCH_VERSION=1.10.2
ARG PYTHON_SHORT_VERSION=3.8
ARG EFA_VERSION=1.14.1
ARG SMDATAPARALLEL_BINARY=https://smdataparallel.s3.amazonaws.com/binary/pytorch/${PYTORCH_VERSION}/cu113/2022-02-18/smdistributed_dataparallel-1.4.0-cp38-cp38-linux_x86_64.whl
ARG PT_S3_WHL_GPU=https://aws-s3-plugin.s3.us-west-2.amazonaws.com/binaries/0.0.1/1c3e69e/awsio-0.0.1-cp38-cp38-manylinux1_x86_64.whl
ARG CONDA_PREFIX="/opt/conda"
ARG BRANCH_OFI=1.1.3-aws

# Set ENV variables required to build PyTorch
ENV TORCH_CUDA_ARCH_LIST="3.7 5.0 7.0+PTX 8.0"
ENV TORCH_NVCC_FLAGS="-Xfatbin -compress-all"
ENV NCCL_VERSION=2.10.3

# Add OpenMPI to the path.
ENV PATH /opt/amazon/openmpi/bin:$PATH

# Add Conda to path
ENV PATH $CONDA_PREFIX/bin:$PATH

# Set this enviroment variable for SageMaker AI to launch SMDDP correctly.
ENV SAGEMAKER_TRAINING_MODULE=sagemaker_pytorch_container.training:main

# Add enviroment variable for processes to be able to call fork()
ENV RDMAV_FORK_SAFE=1

# Indicate the container type
ENV DLC_CONTAINER_TYPE=training

# Add EFA and SMDDP to LD library path
ENV LD_LIBRARY_PATH="/opt/conda/lib/python${PYTHON_SHORT_VERSION}/site-packages/smdistributed/dataparallel/lib:$LD_LIBRARY_PATH"
ENV LD_LIBRARY_PATH=/opt/amazon/efa/lib/:$LD_LIBRARY_PATH

# Install basic dependencies to download and build other dependencies
RUN --mount=type=cache,id=apt-final,target=/var/cache/apt \
  apt-get update && apt-get install -y  --no-install-recommends \
  curl \
  wget \
  git \
  && rm -rf /var/lib/apt/lists/*

# Install EFA.
# This is required for SMDDP backend communication
RUN DEBIAN_FRONTEND=noninteractive apt-get update
RUN mkdir /tmp/efa \
    && cd /tmp/efa \
    && curl --silent -O https://efa-installer.amazonaws.com/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 \
    && rm -rf /tmp/efa

# Install Conda
RUN curl -fsSL -v -o ~/miniconda.sh -O  https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh  && \
    chmod +x ~/miniconda.sh && \
    ~/miniconda.sh -b -p $CONDA_PREFIX && \
    rm ~/miniconda.sh && \
    $CONDA_PREFIX/bin/conda install -y python=${PYTHON_SHORT_VERSION} conda-build pyyaml numpy ipython && \
    $CONDA_PREFIX/bin/conda clean -ya

# Install PyTorch.
# Start with dependencies listed in official PyTorch dockerfile
# https://github.com/pytorch/pytorch/blob/master/Dockerfile
RUN DEBIAN_FRONTEND=noninteractive \
    apt-get install -y --no-install-recommends \
        build-essential \
        ca-certificates \
        ccache \
        cmake \
        git \
        libjpeg-dev \
        libpng-dev && \
    rm -rf /var/lib/apt/lists/*

# Setup ccache
RUN /usr/sbin/update-ccache-symlinks
RUN mkdir /opt/ccache && ccache --set-config=cache_dir=/opt/ccache

# Common dependencies for PyTorch
RUN conda install astunparse numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses

# Linux specific dependency for PyTorch
RUN conda install -c pytorch magma-cuda113

# Clone PyTorch
RUN --mount=type=cache,target=/opt/ccache \
    cd / \
    && git clone --recursive https://github.com/pytorch/pytorch -b v${PYTORCH_VERSION}
# Note that we need to use the same NCCL version for PyTorch and OFI plugin.
# To enforce that, install NCCL from source before building PT and OFI plugin.

# Install NCCL.
# Required for building OFI plugin (OFI requires NCCL's header files and library)
RUN cd /pytorch/third_party/nccl \
    && rm -rf nccl \
    && git clone https://github.com/NVIDIA/nccl.git -b v${NCCL_VERSION}-1 \
    && cd nccl \
    && make -j64 src.build CUDA_HOME=/usr/local/cuda NVCC_GENCODE="-gencode=arch=compute_70,code=sm_70 -gencode=arch=compute_80,code=sm_80" \
    && make pkg.txz.build \
    && tar -xvf build/pkg/txz/nccl_*.txz -C $CONDA_PREFIX --strip-components=1

# Build and install PyTorch.
RUN cd /pytorch \
    && CMAKE_PREFIX_PATH="$(dirname $(which conda))/../" \
    python setup.py install \
    && rm -rf /pytorch

RUN ccache -C

# Build and install OFI plugin. \
# It is required to use libfabric.
RUN DEBIAN_FRONTEND=noninteractive apt-get update \
    && apt-get install -y --no-install-recommends \
        autoconf \
        automake \
        libtool
RUN mkdir /tmp/efa-ofi-nccl \
    && cd /tmp/efa-ofi-nccl \
    && 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=$CONDA_PREFIX \
    && make \
    && make install \
    && rm -rf /tmp/efa-ofi-nccl

# Build and install Torchvision
RUN pip install --no-cache-dir -U \
    packaging \
    mpi4py==3.0.3
RUN cd /tmp \
    && git clone https://github.com/pytorch/vision.git -b v0.9.1 \
    && cd vision \
    && BUILD_VERSION="0.9.1+cu111" python setup.py install \
    && cd /tmp \
    && rm -rf vision

# Install OpenSSH.
# Required for MPI to communicate between containers, allow OpenSSH to talk to containers without asking for confirmation
RUN apt-get update \
    && apt-get install -y  --allow-downgrades --allow-change-held-packages --no-install-recommends \
    && apt-get install -y --no-install-recommends openssh-client openssh-server \
    && mkdir -p /var/run/sshd \
    && cat /etc/ssh/ssh_config | grep -v StrictHostKeyChecking > /etc/ssh/ssh_config.new \
    && echo "    StrictHostKeyChecking no" >> /etc/ssh/ssh_config.new \
    && mv /etc/ssh/ssh_config.new /etc/ssh/ssh_config \
    && rm -rf /var/lib/apt/lists/*
# Configure OpenSSH so that nodes can communicate with each other
RUN mkdir -p /var/run/sshd && \
    sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
RUN rm -rf /root/.ssh/ && \
    mkdir -p /root/.ssh/ && \
    ssh-keygen -q -t rsa -N '' -f /root/.ssh/id_rsa && \
    cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys \
    && printf "Host *\n StrictHostKeyChecking no\n" >> /root/.ssh/config

# Install PT S3 plugin.
# Required to efficiently access datasets in Amazon S3
RUN pip install --no-cache-dir -U ${PT_S3_WHL_GPU}
RUN mkdir -p /etc/pki/tls/certs && cp /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt

# Install libboost from source.
# This package is needed for smdataparallel functionality (for networking asynchronous IO).
WORKDIR /
RUN wget https://sourceforge.net/projects/boost/files/boost/1.73.0/boost_1_73_0.tar.gz/download -O boost_1_73_0.tar.gz \
    && tar -xzf boost_1_73_0.tar.gz \
    && cd boost_1_73_0 \
    && ./bootstrap.sh \
    && ./b2 threading=multi --prefix=${CONDA_PREFIX} -j 64 cxxflags=-fPIC cflags=-fPIC install || true \
    && cd .. \
    && rm -rf boost_1_73_0.tar.gz \
    && rm -rf boost_1_73_0 \
    && cd ${CONDA_PREFIX}/include/boost

# Install SageMaker AI PyTorch training.
WORKDIR /root
RUN pip install --no-cache-dir -U \
    smclarify \
    "sagemaker>=2,<3" \
    sagemaker-experiments==0.* \
    sagemaker-pytorch-training

# Install SageMaker AI data parallel binary (SMDDP)
# Start with dependencies
RUN --mount=type=cache,id=apt-final,target=/var/cache/apt \
    apt-get update && apt-get install -y  --no-install-recommends \
        jq \
        libhwloc-dev \
        libnuma1 \
        libnuma-dev \
        libssl1.1 \
        libtool \
        hwloc \
    && rm -rf /var/lib/apt/lists/*

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

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

**提示**  
如果您想要延伸自訂 Dockerfile 以納入 SageMaker AI 模型平行程式庫，請參閱[使用 SageMaker 分散式模型平行程式庫建立您自己的 Docker 容器](model-parallel-sm-sdk.md#model-parallel-bring-your-own-container)。

# Amazon SageMaker AI 資料平行程式庫範例
<a name="distributed-data-parallel-v2-examples"></a>

此頁面提供 Jupyter 筆記本，其中提供實作 SageMaker AI 分散式資料平行化 (SMDDP) 程式庫以在 SageMaker AI 上執行分散式訓練任務的範例。

## 部落格與案例研究
<a name="distributed-data-parallel-v2-examples-blog"></a>

下列部落格討論有關使用 SMDDP 程式庫的案例研究。

**SMDDP v2 部落格**
+ [使用 Amazon SageMaker AI 資料平行程式庫進行更快速的訓練](https://aws.amazon.com/blogs/machine-learning/enable-faster-training-with-amazon-sagemaker-data-parallel-library/)，*AWS 機器學習部落格* (2023 年 12 月 5 日)

**SMDDP v1 部落格**
+ [我如何在 SageMaker AI 上訓練 Stable Diffusion 10TB](https://medium.com/@emilywebber/how-i-trained-10tb-for-stable-diffusion-on-sagemaker-39dcea49ce32)，*Medium* (2022 年 11 月 29 日)
+ [與 Amazon Search 在 Amazon SageMaker 訓練中執行 PyTorch Learning 和原生 PyTorch DDP](https://aws.amazon.com/blogs/machine-learning/run-pytorch-lightning-and-native-pytorch-ddp-on-amazon-sagemaker-training-featuring-amazon-search/)，*AWS 機器學習部落格* (2022 年 8 月 18 日)
+ [AWS 使用 PyTorch 和 SageMaker AI 分散式資料平行程式庫在 上訓練 YOLOv5](https://medium.com/@sitecao/training-yolov5-on-aws-with-pytorch-and-sagemaker-distributed-data-parallel-library-a196ab01409b)，*中* (2022 年 5 月 6 日）
+ [使用 PyTorch 和 SageMaker AI 分散式資料平行程式庫，加速 SageMaker AI 上的 EfficientNet 模型訓練](https://medium.com/@dangmz/speed-up-efficientnet-model-training-on-amazon-sagemaker-with-pytorch-and-sagemaker-distributed-dae4b048c01a)，*Medium* (2022 年 3 月 21 日)
+ [AWS 使用 SageMaker AI 分散式資料平行程式庫加速 上的 EfficientNet 訓練](https://towardsdatascience.com/speed-up-efficientnet-training-on-aws-by-up-to-30-with-sagemaker-distributed-data-parallel-library-2dbf6d1e18e8)，*面向資料科學* (2022 年 1 月 12 日）
+ [現代汽車使用 Amazon SageMaker AI 縮短自動駕駛模型的 ML 模型訓練時間](https://aws.amazon.com/blogs/machine-learning/hyundai-reduces-training-time-for-autonomous-driving-models-using-amazon-sagemaker/)，*AWS 機器學習部落格* (2021 年 6 月 25 日)
+ [分散式訓練：使用 Transformers 和 Amazon SageMaker AI 訓練 BART/T5 進行摘要](https://huggingface.co/blog/sagemaker-distributed-training-seq2seq)，*Hugging Face 網站* (2021 年 4 月 8 日)

## 範例筆記本
<a name="distributed-data-parallel-v2-examples-pytorch"></a>

範例筆記本在 [SageMaker AI 範例 GitHub 儲存庫](https://github.com/aws/amazon-sagemaker-examples/tree/master/training/distributed_training/)中提供。若要下載範例，請執行下列命令來複製儲存庫並前往 `training/distributed_training/pytorch/data_parallel`。

**注意**  
在下列 SageMaker AI ML IDEs 中複製並執行範例筆記本。  
[SageMaker AI JupyterLab](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated-jl.html) (可在 2023 年 12 月之後建立的 [Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated.html) 中使用)
[SageMaker AI 程式碼編輯器](https://docs.aws.amazon.com/sagemaker/latest/dg/code-editor.html) (可在 2023 年 12 月之後建立的 [Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated.html) 中使用)
[Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html) (作為在 2023 年 12 月之後建立的 [Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated.html) 中的應用程式提供)
[SageMaker 筆記本執行個體](https://docs.aws.amazon.com/sagemaker/latest/dg/nbi.html)

```
git clone https://github.com/aws/amazon-sagemaker-examples.git
cd amazon-sagemaker-examples/training/distributed_training/pytorch/data_parallel
```

**SMDDP v2 範例**
+ [使用 SageMaker AI 分散式資料平行程式庫 (SMDDP) 和 DeepSpeed 訓練 Llama 2](https://github.com/aws/amazon-sagemaker-examples/blob/main/training/distributed_training/pytorch/data_parallel/deepspeed/llama2/smddp_deepspeed_example.ipynb)
+ [使用 SageMaker AI 分散式資料平行程式庫 (SMDDP) 和 PyTorch 完全碎片資料平行化 (FSDP) 來訓練 Falcon](https://github.com/aws/amazon-sagemaker-examples/blob/main/training/distributed_training/pytorch/data_parallel/fully_sharded_data_parallel/falcon/smddp_fsdp_example.ipynb)

**SMDDP v1 範例**
+ [使用 PyTorch 的 CNN 與 SageMaker AI 資料平行化程式庫](https://github.com/aws/amazon-sagemaker-examples/blob/main/training/distributed_training/pytorch/data_parallel/mnist/pytorch_smdataparallel_mnist_demo.ipynb)
+ [使用 PyTorch 的 BERT 與 SageMaker AI 資料平行化程式庫](https://github.com/aws/amazon-sagemaker-examples/blob/main/training/distributed_training/pytorch/data_parallel/bert/pytorch_smdataparallel_bert_demo.ipynb)
+ [使用 TensorFlow 2.3.1 的 CNN 與 SageMaker AI 資料平行程式庫](https://sagemaker-examples.readthedocs.io/en/latest/training/distributed_training/tensorflow/data_parallel/mnist/tensorflow2_smdataparallel_mnist_demo.html)
+ [使用 TensorFlow 2.3.1 的 BERT 與 SageMaker AI 資料平行化程式庫](https://sagemaker-examples.readthedocs.io/en/latest/training/distributed_training/tensorflow/data_parallel/bert/tensorflow2_smdataparallel_bert_demo.html)
+ [在 SageMaker AI 上 PyTorch 中的 HuggingFace 分散式資料平行訓練：分散式問題回答](https://github.com/huggingface/notebooks/blob/master/sagemaker/03_distributed_training_data_parallelism/sagemaker-notebook.ipynb)
+ [在 SageMaker AI 上 PyTorch 中的 HuggingFace 分散式資料平行訓練：分散式文字摘要](https://github.com/huggingface/notebooks/blob/master/sagemaker/08_distributed_summarization_bart_t5/sagemaker-notebook.ipynb)
+ [在 SageMaker AI 上 TensorFlow 中 HuggingFace 分散式資料平行訓練](https://github.com/huggingface/notebooks/blob/master/sagemaker/07_tensorflow_distributed_training_data_parallelism/sagemaker-notebook.ipynb)

# Amazon SageMaker AI 分散式資料平行程式庫的組態提示。
<a name="data-parallel-config"></a>

使用 SageMaker AI 分散式資料平行 (SMDDP) 程式庫之前，請先檢閱下列提示。此清單包含適用於跨架構的提示。

**Topics**
+ [資料預先處理](#data-parallel-config-dataprep)
+ [單一節點與多個節點](#data-parallel-config-multi-node)
+ [使用偵錯工具偵錯擴展效率](#data-parallel-config-debug)
+ [批次大小](#data-parallel-config-batch-size)
+ [自訂 MPI 選項](#data-parallel-config-mpi-custom)
+ [使用 Amazon FSx 並設定最佳儲存和輸送容量](#data-parallel-config-fxs)

## 資料預先處理
<a name="data-parallel-config-dataprep"></a>

如果您在訓練期間使用利用 CPU 的外部程式庫預先處理資料，則可能會遇到 CPU 瓶頸，因為 SageMaker AI 分散式資料平行使用 CPU 進行 `AllReduce` 操作。您可以將預先處理步驟移至使用 GPU 的程式庫，或在訓練前完成所有預先處理，以改善訓練時間。

## 單一節點與多個節點
<a name="data-parallel-config-multi-node"></a>

我們建議您搭配多個節點使用此程式庫。此程式庫可搭配單一主機、多裝置設定 (例如，具有多個 GPU 的單一機器學習 (ML) 運算執行個體) 搭配使用；不過，當您使用兩個或多個節點時，程式庫的 `AllReduce` 操作可大幅提升效能。此外，在單一主機上，NVLink 已經有助於提升節點內部 `AllReduce` 效率。

## 使用偵錯工具偵錯擴展效率
<a name="data-parallel-config-debug"></a>

您可以使用 Amazon SageMaker Debugger，在訓練期間監控並視覺化 CPU 和 GPU 使用率以及其他感興趣的指標。您可以使用偵錯工具[內建規則](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-built-in-rules.html)，以監控運算效能問題，例如 `CPUBottleneck`、`LoadBalancing` 和 `LowGPUUtilization`。當您定義 Amazon SageMaker Python SDK 估算器，您可以使用[偵錯工具組態](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-configuration-for-debugging.html)來指定這些規則。如果您使用 AWS CLI 和 適用於 Python (Boto3) 的 AWS SDK 在 SageMaker AI 上進行訓練，您可以啟用偵錯工具，如[使用 Amazon SageMaker API 設定 SageMaker Debugger Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/debugger-createtrainingjob-api.html)所示。

若要查看 SageMaker 訓練任務中使用偵錯工具的範例，您可以參考 [SageMaker 筆記本範例 GitHub 儲存庫](https://github.com/aws/amazon-sagemaker-examples/tree/master/sagemaker-debugger)中的其中一個筆記本範例。要瞭解有關除錯器的詳細資訊，請參閱 [Amazon SageMaker Debugger](https://docs.aws.amazon.com/sagemaker/latest/dg/train-debugger.html)。

## 批次大小
<a name="data-parallel-config-batch-size"></a>

在分散式訓練中，隨著新增更多節點，批次大小應按比例增加。若要在訓練任務中新增更多節點並增加全域批次大小時，同時提高收斂速度，請提升學習速率。

實現此目標的一個方法是使用逐步學習速率暖機，其中隨著訓練任務的進展，學習速率會從小到大的值逐步提升。此逐步提升可避免突然增加學習速率，提供在訓練開始時運作狀態良好的收斂。例如，您可以使用*線性擴展規則*，其中每當最低批次大小乘以 k 時，學習速率也會乘以 k。要瞭解更多關於這種技術的資訊，請參閱研究論文[準確的大型微型批量 SGD：在 1 小時內訓練 ImageNet](https://arxiv.org/pdf/1706.02677.pdf), 第 2 和第 3 節。

## 自訂 MPI 選項
<a name="data-parallel-config-mpi-custom"></a>

SageMaker AI 分散式資料平行程式庫採用訊息傳遞介面 (MPI)，這是管理高效能叢集中節點之間通訊的常用標準，並使用 NVIDIA 的 NCCL 程式庫進行 GPU 層級通訊。當您將資料平行程式庫與 TensorFlow 或 Pytorch `Estimator` 搭配使用時，個別容器會設定 MPI 環境，並執行 `mpirun` 指令以啟動叢集節點上的任務。

您可以使用 `Estimator` 中的 `custom_mpi_options` 參數來設定自訂 MPI 作業。在此欄位中傳遞的任何 `mpirun` 旗標都會新增至 `mpirun` 命令，並由 SageMaker AI 執行以進行訓練。例如，您可以使用下列項目來定義 `Estimator` 的 `distribution` 參數，以便在程式開始時使用 [https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/env.html#nccl-debug](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/env.html#nccl-debug) 變數列印 NCCL 版本：

```
distribution = {'smdistributed':{'dataparallel':{'enabled': True, "custom_mpi_options": "-verbose -x NCCL_DEBUG=VERSION"}}}
```

## 使用 Amazon FSx 並設定最佳儲存和輸送容量
<a name="data-parallel-config-fxs"></a>

在具有分散式資料平行處理的多個節點上訓練模型時，強烈建議您使用 [FSx for Lustre](https://docs.aws.amazon.com/fsx/latest/LustreGuide/what-is.html)。Amazon FSx 是可擴展且高效能的儲存服務，支援具有更快輸送量的共用檔案儲存。使用 Amazon FSx 進行大規模儲存，您可以在運算節點之間實現更快的資料載入速度。

通常，透過分散式資料平行處理，您會預期總訓練輸送量幾乎隨著 GPU 數量線性擴展。但是，如果您使用非最佳化的 Amazon FSx 儲存，則訓練效能可能會因為 Amazon FSx 輸送量較低而降低。

例如，如果您使用具有最低 1.2 TiB 儲存容量[的 Amazon FSx 檔案系統的 **SCRACCH\$12** 部署類型](https://docs.aws.amazon.com/fsx/latest/LustreGuide/performance.html#fsx-aggregate-perf)，則 I/O 輸送容量為每秒 240 MB。Amazon FSx 儲存的運作方式，可讓您指派實體儲存裝置，指派的裝置越多，您獲得的輸送量就越大。SRATCH\$12 類型的最小儲存增加量為 1.2 TiB，對應的輸送量增益為 240 MB/秒。

假設您有一個模型，可以在超過 100 GB 資料集的 4 節點叢集上進行訓練。使用針對叢集最佳化的特定批次大小，假設模型可以在大約 30 秒內完成一個週期。在這種情況下，所需的最低 I/O 速度約為每秒 3 Gb (100 GB/30 秒)。這顯然是比 240 MB/秒 更高的較高輸送量要求。使用有限的 Amazon FSx 容量，將分散式訓練任務擴展到更大的叢集，可能會加重 I/O 瓶頸的問題；模型訓練輸送量可能會隨著快取的建置而改善，但 Amazon FSx 輸送量仍然存在瓶頸。

為了減輕此類 I/O 瓶頸問題，您應該增加 Amazon FSx 儲存大小，以獲得更高的輸送容量。通常，為了找到最佳的 I/O 輸送量，您可以嘗試使用不同的 Amazon FSx 輸送容量，指派等於或稍低於預估的輸送量，直到您發現其足以解決 I/O 瓶頸問題為止。在上述範例中，具有每秒 2.4 GB 輸送量和 67 GB RAM 快取的 Amazon FSx 儲存就已足夠。如果該檔案系統具有最佳輸送量，則模型訓練輸送量應立即達到最大值，或在快取已建置的第一個週期之後達到最大值。

要瞭解有關如何增加 Amazon FSX 儲存和部署類型的更多資訊，請參閱 *Amazon FSx for Lustre 文件*：
+  [如何增加儲存容量](https://docs.aws.amazon.com/fsx/latest/LustreGuide/managing-storage-capacity.html#increase-storage-capacity) 
+  [彙總檔案系統效能](https://docs.aws.amazon.com/fsx/latest/LustreGuide/performance.html#fsx-aggregate-perf) 

# Amazon SageMaker AI 分散式資料平行化程式庫常見問答集
<a name="data-parallel-faq"></a>

使用下列項目來尋找有關 SMDDP 程式庫常見問題的答案。

**問：使用程式庫時，如何管理 `allreduce` 支援 CPU 執行個體？ 我是否必須建立異質 CPU-GPU 叢集，或 SageMaker AI 服務是否會為使用 SMDDP 程式庫的任務建立額外的 C5？**

SMDDP 程式庫僅支援 GPU 執行個體，更具體地說，是具有 NVIDIA A100 GPU 和 EFA 的 P4d 和 P4de 執行個體。不會啟動其他 C5 或 CPU 執行個體；如果您的 SageMaker AI 訓練任務是 8個節點 P4d 叢集，則僅會使用 8 個 `ml.p4d.24xlarge` 執行個體。不會佈建其他執行個體。

**問：我有一個需要 5 天的訓練任務，在具有一組超參數 H1 (學習速率、批次大小、最佳化工具等) 的單一 `ml.p3.24xlarge` 執行個體上執行。使用 SageMaker AI 的資料平行處理程式庫和五倍大的叢集，是否足以達到大約五倍的加速？ 還是我在啟動 SMDDP 程式庫後重新檢視其訓練超參數？**

程式庫會變更總體批次大小。新的總體批次大小會隨著使用的訓練執行個體數量線性擴展。因此，必須變更超參數 (例如學習速率) 才能確保整合。

**問：SMDDP 程式庫是否支援 Spot？**

是。您可以使用受管 Spot 訓練。您可以在 SageMaker 訓練任務中指定檢查點檔案的路徑。如同[在 TensorFlow 訓練指令碼中使用 SMDDP 程式庫 (已棄用)](data-parallel-modify-sdp-tf2.md)和[在 PyTorch 訓練指令碼中使用 SMDDP 程式庫](data-parallel-modify-sdp-pt.md)的最後一個步驟中所述，您可以在其訓練指令碼中儲存並還原檢查點。

**問：SMDDP 程式庫是否在單一主機、多裝置設定中相關？**

該程式庫可用於單一主機多裝置訓練，但程式庫僅在多主機訓練中提供效能改進。

**問：應該將訓練資料集儲存在哪裡？**

訓練資料集可儲存在 Amazon S3 儲存貯體或 Amazon FSx 磁碟機。請參閱[訓練工作的各種支援輸入檔案系統文件](https://sagemaker.readthedocs.io/en/stable/api/utility/inputs.html#sagemaker.inputs.FileSystemInput)。

**問：使用 SMDDP 程式庫時，是否必須在 FSx for Lustre 中提供訓練資料？ 是否可以使用 Amazon EFS 和 Amazon S3 嗎？**

我們通常建議您使用 Amazon FSx，因為其延遲較低且輸送量較高。如果您願意，您可以使用 Amazon EFS 或 Amazon S3。

**問：程式庫是否可與 CPU 節點搭配使用？** 

否。若要尋找 SMDDP 程式庫支援的執行個體類型，請參閱 [支援的執行個體類型](distributed-data-parallel-support.md#distributed-data-parallel-supported-instance-types)。

**問：SMDDP 程式庫目前在啟動時支援哪些架構和架構版本？** 

SMDDP 程式庫目前支援 PyTorch 1.6.0 版或更新版本，以及 TensorFlow 2.3.0 版或更新版本。不支援 TensorFlow 1.x。有關 AWS 深度學習容器中封裝的 SMDDP 程式庫版本，請參閱[深度學習容器版本備註](https://docs.aws.amazon.com/deep-learning-containers/latest/devguide/dlc-release-notes.html)。

**問：程式庫是否支援 AMP？**

是，SMDDP 程式庫支援開箱即用的自動混合精確度 (AMP)。除了對訓練指令碼進行架構級修改之外，不需要額外的動作即可使用 AMP。如果梯度是 FP16，SageMaker AI 資料平行化程式庫會以 FP16 執行其 `AllReduce` 操作。有關將 AMP API 實施到訓練腳本的詳細資訊，請參閱以下資源：
+ [架構 - ](https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/index.html#pytorch)*NVIDIA 深度學習效能文件中的 PyTorch*
+ [架構 - ](https://docs.nvidia.com/deeplearning/performance/mixed-precision-training/index.html#tensorflow)*NVIDIA 深度學習效能文件中的 TensorFlow*
+ *NVIDIA 開發人員文件*中[適用於深度學習的自動混合精確度](https://developer.nvidia.com/automatic-mixed-precision)
+ [在 *PyTorch 部落格*介紹原生 PyTorch 自動混合精度，以加快 NVIDIA GPU 的訓練速度](https://pytorch.org/blog/accelerating-training-on-nvidia-gpus-with-pytorch-automatic-mixed-precision/)
+ *TensorFlow 文件*中的 [TensorFlow 混合精確度 API](https://www.tensorflow.org/guide/mixed_precision)

**問：如何識別分散式訓練任務是否因 I/O 瓶頸而減慢速度？**

對於較大的叢集，訓練任務需要更多的 I/O 輸送量，因此訓練輸送量可能需要更長的時間 (更多週期) 才能提升到最大的效能。這表示 I/O 存在瓶頸，並且隨著節點擴展 (較高輸送量需求和更複雜的網路拓撲)，更難以建立快取。有關在雲手錶上監控亞馬遜 FSX 吞吐量的更多資訊，請參閱[監控 FSx for Lustre](https://docs.aws.amazon.com/fsx/latest/LustreGuide/monitoring_overview.html)在*FSx for Lustre 用戶指南*。

**問：執行具有資料平行處理的分散式訓練任務時，如何解決 I/O 瓶頸？**

如果您使用的是 Amazon S3，我們強烈建議您使用 Amazon FSx 做為資料管道。如果您已經在使用 Amazon FSx，但仍有 I/O 瓶頸問題，您可能已經設定 Amazon FSx 檔案系統為低 I/O 輸送量和小儲存容量。有關如何估計和選擇正確的 I/O 吞吐量容量大小的詳細資訊，請參閱[使用 Amazon FSx 並設定最佳儲存和輸送容量](data-parallel-config.md#data-parallel-config-fxs)。

**問：(適用於程式庫 1.4.0 版或更新版本) 如何解決初始化程序群組時的 `Invalid backend` 錯誤。**

如果在呼叫 `init_process_group` 時遇到錯誤訊息 `ValueError: Invalid backend: 'smddp'`，這是由於 SMDDP 程式庫 1.4.0 版及更新版本中的突破性變更。您必須匯入程式庫的 PyTorch 用戶端 (`smdistributed.dataparallel.torch.torch_smddp`)，該用戶端會註冊 `smddp` 為 PyTorch 後端。如需詳細資訊，請參閱 [在 PyTorch 訓練指令碼中使用 SMDDP 程式庫](data-parallel-modify-sdp-pt.md)。

**問：(適用於 SMDDP 程式庫 1.4.0 版或更新版本)，我想呼叫 [https://pytorch.org/docs/stable/distributed.html](https://pytorch.org/docs/stable/distributed.html) 介面的集合基本元素。`smddp` 後端支援哪些基本元素？**

在 v1.4.0 中，SMDDP 程式庫支援 `torch.distributed` 介面的 `all_reduce`、`broadcast`、`reduce`、`all_gather` 和 `barrier`。

**問：(適用於 SMDDP 程式庫 1.4.0 版或更新版本) 這個新的 API 是否可與其他自訂 DDP 類別或程式庫 (如 Apex DDP) 搭配使用？**

SMDDP 程式庫會與使用 `torch.distribtued` 模組的其他第三方分散式資料平行程式庫和架構實作一起測試。只要 SMDDP 程式庫支援自訂 DDP 類別所使用的集合操作，就可以將 SMDDP 程式庫搭配自訂 DDP 類別一起使用。有關支援集合的清單，請參閱上述問題。如果您有這些使用案例並需要進一步的支援，請透過[AWS 支援中心](https://console.aws.amazon.com/support/)或 [Amazon SageMaker AI 的 AWS 開發人員論壇](https://forums.aws.amazon.com/forum.jspa?forumID=285)與 SageMaker AI 團隊聯絡。

**問：SMDDP 程式庫是否支援自攜容器 (BYOC) 選項？ 如果有，我該如何透過編寫自訂 Dockerfile 來安裝程式褲，並執行分散式訓練任務？**

如果您想要將 SMDDP 程式庫及其最小相依性整合到您自己的 Docker 容器，BYOC 是正確方法。您可以使用程式庫的二進位檔案建置自己的容器。建議的程序是使用程式庫及其相依性編寫自訂 Dockerfile、建置 Docker 容器、在 Amazon ECR 中託管，然後使用 ECR 映像 URI 啟動使用 SageMaker AI 一般估算器類別的訓練任務。如需有關如何使用 SMDDP 程式庫，在 SageMaker AI 中為分散式訓練準備自訂 Dockerfile 的更多指示，請參閱[使用 SageMaker AI 分散式資料平行程式庫建立您自己的 Docker 容器](data-parallel-bring-your-own-container.md)。

# 針對 Amazon SageMaker AI 分散式訓練進行故障診斷
<a name="distributed-troubleshooting-data-parallel"></a>

如果在使用程式庫時執行訓練任務遇到問題，請使用下列清單嘗試進行故障診斷。如果您需要進一步的支援，請透過 [AWS 支援中心](https://console.aws.amazon.com/support/)或[Amazon Amazon SageMaker AI 的AWS 開發人員論壇](https://forums.aws.amazon.com/forum.jspa?forumID=285)與 SageMaker AI 團隊聯絡。

**Topics**
+ [將 SageMaker AI 分散式資料平行與 Amazon SageMaker Debugger 和檢查點搭配使用](#distributed-ts-data-parallel-debugger)
+ [連接至模型參數機碼的未預期字首](#distributed-ts-data-parallel-pytorch-prefix)
+ [初始化期間的 SageMaker AI 分散式訓練任務停滯](#distributed-ts-data-parallel-efa-sg)
+ [SageMaker AI 分散式訓練任務在訓練結束時停滯](#distributed-ts-data-parallel-stall-at-the-end)
+ [觀察由於 Amazon FSx 輸送量瓶頸而造成的擴展效率降低](#distributed-ts-data-parallel-fxs-bottleneck)
+ [使用 PyTorch 的 SageMaker AI 分散式訓練任務傳回棄用警告](#distributed-ts-data-parallel-deprecation-warnings)

## 將 SageMaker AI 分散式資料平行與 Amazon SageMaker Debugger 和檢查點搭配使用
<a name="distributed-ts-data-parallel-debugger"></a>

若要使用 SageMaker AI 分散式資料平行來監控系統瓶頸、分析架構作業和偵錯模型輸出張量以進行訓練任務，請使用 Amazon SageMaker Debugger。

但是，當您使用 SageMaker Debugger、SageMaker AI 分散式資料平行以及 SageMaker AI 檢查點時，您可能會看到類似下列範例的錯誤。

```
SMDebug Does Not Currently Support Distributed Training Jobs With Checkpointing Enabled
```

這是由於偵錯工具和檢查點之間發生內部錯誤，當您啟用 SageMaker AI 分散式資料平行化時，就會發生此錯誤。
+ 如果您啟用所有這三個功能，SageMaker Python SDK 會自動透過傳遞 `debugger_hook_config=False` 關閉偵錯工具，這等同於下列架構 `estimator` 範例。

  ```
  bucket=sagemaker.Session().default_bucket()
  base_job_name="sagemaker-checkpoint-test"
  checkpoint_in_bucket="checkpoints"
  
  # The S3 URI to store the checkpoints
  checkpoint_s3_bucket="s3://{}/{}/{}".format(bucket, base_job_name, checkpoint_in_bucket)
  
  estimator = TensorFlow(
      ...
  
      distribution={"smdistributed": {"dataparallel": { "enabled": True }}},
      checkpoint_s3_uri=checkpoint_s3_bucket,
      checkpoint_local_path="/opt/ml/checkpoints",
      debugger_hook_config=False
  )
  ```
+ 如果您想要繼續使用 SageMaker AI 分散式資料平行化和 SageMaker Debugger，解決方法是手動新增檢查點函式至訓練指令碼，而不是從估算器指定 `checkpoint_s3_uri` 和 `checkpoint_local_path` 參數。有關在訓練腳本中設置手動檢查點的詳細資訊，請參閱[儲存檢查點](distributed-troubleshooting-model-parallel.md#distributed-ts-model-parallel-checkpoints)。

## 連接至模型參數機碼的未預期字首
<a name="distributed-ts-data-parallel-pytorch-prefix"></a>

對於 PyTorch 分散式訓練任務，未預期的字首 (例如 `model`) 可能會連接至 `state_dict` 機碼 (模型參數)。當 PyTorch 訓練任務儲存模型成品時，SageMaker AI 資料平行化程式庫不會直接變更或加上任何模型參數名稱。PyTorch 的分散式訓練會變更 `state_dict` 中的名稱，以便透過網路，欲加上字首。如果您在使用 SageMaker AI 資料平行化程式庫和 PyTorch 訓練的檢查點時，因為參數名稱不同而遇到任何模型失敗問題，請調整下列範例程式碼，在訓練指令碼中載入檢查點的步驟中移除自首。

```
state_dict = {k.partition('model.')[2]:state_dict[k] for k in state_dict.keys()}
```

這會將每個 `state_dict` 機碼視為字串值，在 `'model.'` 第一次出現的時候分隔字串，並取得分割字串的第三個清單項目 (含索引 2)。

有關字首問題的詳細資訊，請參閱[如果由多 GPU 訓練，則在保存模型中為參數名稱新增字首？](https://discuss.pytorch.org/t/prefix-parameter-names-in-saved-model-if-trained-by-multi-gpu/494)在*PyTorch 討論論壇*。

有關用於保存和加載模型的 PyTorch 方法的詳細資訊，請參閱[跨設備保存和加載模型](https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-across-devices)，在*PyTorch 文件*。

## 初始化期間的 SageMaker AI 分散式訓練任務停滯
<a name="distributed-ts-data-parallel-efa-sg"></a>

如果您的 SageMaker AI 分散式資料平行化訓練任務在使用啟用 EFA 的執行個體初始化期間停滯，這可能是由於用於訓練任務的 VPC 子網路的安全群組設定錯誤造成的。EFA 需要適當的安全群組組態，才能啟用節點之間的流量。

**若要設定安全群組的傳入和傳出規則**

1. 登入 AWS 管理主控台 ，並在 [https://console.aws.amazon.com/vpc/](https://console.aws.amazon.com/vpc/)：// 開啟 Amazon VPC 主控台。

1. 在左導覽窗格中，選擇**安全群組**。

1. 選取與您用於訓練的 VPC 子網路綁定的安全群組。

1. 在**詳細資訊**區段中，複製**安全群組 ID**。

1. 在**傳入規則**索引標籤上，選擇**編輯傳入規則**。

1. 在 **編輯傳入規則** 頁面上，執行下列動作：

   1. 選擇**新增規則**。

   1. 針對**類型**，選擇**所有流量**。

   1. 在**來源**中，選擇**自訂**，將安全群組 ID 貼到搜尋方塊中，然後選取彈出的安全群組。

1. 選擇**儲存規則**，以完成設定安全群組的傳入規則。

1. 在**傳出規則**標籤上，選擇**編輯傳出規則**。

1. 重複步驟 6 和 7，以新增與傳出規則相同的規則。

完成上述步驟，以使用傳入和傳出規則設定安全群組後，請重新執行訓練任務，並驗證停止問題是否已解決。

有關為 VPC 和 EFA 配置安全組的詳細資訊，請參閱[您的 VPC 的安全組](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html)和[彈性織物適配器](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html)。

## SageMaker AI 分散式訓練任務在訓練結束時停滯
<a name="distributed-ts-data-parallel-stall-at-the-end"></a>

訓練結束時停止問題的根本原因之一，就是不同排名的每個週期處理的批次數量不相符。所有工作者 (GPU) 都會在向後傳遞中同步其本機漸層，以確保在批次迭代結束時具有相同的模型副本。如果在最後的訓練週期期間，批次大小不平均地指派給不同工作者群組，則訓練任務會停止。例如，當一組工作者 (群組 A) 完成處理所有批次並結束訓練迴路時，另一個工作者群組 (群組 B) 會開始處理另一個批次，但仍需要來自群組 A 的通訊以同步漸層。這會導致群組 B 等待已完成訓練、且沒有任何漸層可同步的群組 A。

因此，設定訓練資料集時，每個工作者都必須取得相同數量的資料範例，這樣每個工作者才能在訓練時處理相同數量的批次。確保每個排名取得相同數量的批次，以避免此停止問題。

## 觀察由於 Amazon FSx 輸送量瓶頸而造成的擴展效率降低
<a name="distributed-ts-data-parallel-fxs-bottleneck"></a>

擴展效率降低的一個潛在原因是 FSx 輸送量限制。如果您在切換至較大的訓練叢集時發現擴展效率突然下降，請嘗試使用較高輸送量限制的較大 FSx for Lustre 檔案系統。如需詳細資訊，請參閱 *Amazon FSx for Lustre 使用者指南*中的[彙總檔案系統效能](https://docs.aws.amazon.com/fsx/latest/LustreGuide/performance.html#fsx-aggregate-perf)和[管理儲存和輸送容量](https://docs.aws.amazon.com/fsx/latest/LustreGuide/managing-storage-capacity.html)。

## 使用 PyTorch 的 SageMaker AI 分散式訓練任務傳回棄用警告
<a name="distributed-ts-data-parallel-deprecation-warnings"></a>

自 1.4.0 版，SageMaker AI 分散式資料平行化程式庫以 PyTorch 分散式的後端運作。由於在 PyTorch 中使用程式庫的突破性變更，您可能會遇到警告訊息，指出 PyTorch 分散式套件的 `smdistributed` API 已棄用。警告訊息應類似以下內容：

```
smdistributed.dataparallel.torch.dist is deprecated in the SageMaker AI distributed data parallel library v1.4.0+.
Please use torch.distributed and specify 'smddp' as a backend when initializing process group as follows:
torch.distributed.init_process_group(backend='smddp')
For more information, see the library's API documentation at
https://docs.aws.amazon.com/sagemaker/latest/dg/data-parallel-modify-sdp-pt.html
```

在 1.4.0 版及更新版本中，程式庫只需要在訓練指令碼一開始匯入程式庫一次，並在 PyTorch 分散式初始化期間將其設定為後端即可。利用僅一行的後端規格，您不需要變更 PyTorch 訓練指令碼，即可直接使用 PyTorch 分散式模組。請參閱[在 PyTorch 訓練指令碼中使用 SMDDP 程式庫](data-parallel-modify-sdp-pt.md)，以了解突破性變更以及搭配 PyTorch 使用程式庫的新方法。

# SageMaker AI 資料平行化程式庫版本備註
<a name="data-parallel-release-notes"></a>

請參閱下列版本備註，以追蹤 SageMaker AI 分散式資料平行化 (SMDDP) 程式庫的最新更新。

## SageMaker AI 分散式資料平行化程式庫 v2.5.0
<a name="data-parallel-release-notes-20241017"></a>

*日期：2024 年 10 月 17 日*

**新功能**
+ 新增對 PyTorch v2.4.1 與 CUDA v12.1 的支援。

**整合到由 SageMaker AI 模型平行化 (SMP) 程式庫發佈的 Docker 容器**

此版本的 SMDDP 程式庫會遷移至 [SageMaker 模型平行化程式庫 v2.6.0](model-parallel-release-notes.md#model-parallel-release-notes-20241017)。

```
658645717510.dkr.ecr.<us-west-2>.amazonaws.com/smdistributed-modelparallel:2.4.1-gpu-py311-cu121
```

如需可使用 SMP Docker 映像檔的區域，請參閱 [AWS 區域](distributed-model-parallel-support-v2.md#distributed-model-parallel-availablity-zone-v2)。

**此版本的二進位檔案**

您可以使用下列 URL 下載或安裝程式庫。

```
https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.4.1/cu121/2024-10-09/smdistributed_dataparallel-2.5.0-cp311-cp311-linux_x86_64.whl
```

## SageMaker AI 分散式資料平行化程式庫 v2.3.0
<a name="data-parallel-release-notes-20240611"></a>

*日期：2024 年 6 月 11 日*

**新功能**
+ 新增對 PyTorch v2.3.0 搭配 CUDA v12.1 和 Python v3.11 的支援。
+ 新增支援 PyTorch Lightning v2.2.5。這已整合至 PyTorch v2.3.0 的 SageMaker AI 架構容器中。
+ 在匯入期間新增執行個體類型驗證，以防止在不支援的執行個體類型上載入 SMDDP 程式庫。如需與 SMDDP 程式庫相容的執行個體類型清單，請參閱 [支援的架構 AWS 區域和執行個體類型](distributed-data-parallel-support.md)。

**整合到 SageMaker AI 架構容器**

此版本的 SMDDP 程式庫會遷移至下列 [SageMaker AI 架構容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only)。
+ PyTorch v2.3.0

  ```
  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.3.0-gpu-py311-cu121-ubuntu20.04-sagemaker
  ```

如需 SMDDP 程式庫和預先建置容器的完整版本清單，請參閱 [支援的架構 AWS 區域和執行個體類型](distributed-data-parallel-support.md)。

**此版本的二進位檔案**

您可以使用下列 URL 下載或安裝程式庫。

```
https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.3.0/cu121/2024-05-23/smdistributed_dataparallel-2.3.0-cp311-cp311-linux_x86_64.whl
```

**其他變更**
+ SMDDP 程式庫 v2.2.0 已整合到 PyTorch v2.2.0 的 SageMaker AI 架構容器中。

## SageMaker AI 分散式資料平行化程式庫 v2.2.0
<a name="data-parallel-release-notes-20240304"></a>

*日期：2024 年 3 月 4 日*

**新功能**
+ 新增對 PyTorch v2.2.0 與 CUDA v12.1 的支援。

**整合到由 SageMaker AI 模型平行化 (SMP) 程式庫發佈的 Docker 容器**

此版本的 SMDDP 程式庫會遷移至 [SageMaker 模型平行化程式庫 v2.2.0](model-parallel-release-notes.md#model-parallel-release-notes-20240307)。

```
658645717510.dkr.ecr.<region>.amazonaws.com/smdistributed-modelparallel:2.2.0-gpu-py310-cu121
```

如需可使用 SMP Docker 映像檔的區域，請參閱 [AWS 區域](distributed-model-parallel-support-v2.md#distributed-model-parallel-availablity-zone-v2)。

**此版本的二進位檔案**

您可以使用下列 URL 下載或安裝程式庫。

```
https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.2.0/cu121/2024-03-04/smdistributed_dataparallel-2.2.0-cp310-cp310-linux_x86_64.whl
```

## SageMaker AI 分散式資料平行化程式庫 v2.1.0
<a name="data-parallel-release-notes-20240301"></a>

*日期：2024 年 3 月 1 日*

**新功能**
+ 新增對 PyTorch v2.1.0 與 CUDA v12.1 的支援。

**錯誤修正**
+ 修正[SMDDP v2.0.1](#data-parallel-release-notes-20231207) 中的 CPU 記憶體流失問題。

**整合到 SageMaker AI 架構容器**

此版本的 SMDDP 程式庫已通過基準測試，並遷移至下列 [SageMaker AI 架構容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only)。
+ PyTorch v2.1.0

  ```
  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.1.0-gpu-py310-cu121-ubuntu20.04-sagemaker
  ```

**整合到由 SageMaker AI 模型平行化 (SMP) 程式庫發佈的 Docker 容器**

此版本的 SMDDP 程式庫會遷移至 [SageMaker 模型平行化程式庫 v2.1.0](model-parallel-release-notes.md#model-parallel-release-notes-20240206)。

```
658645717510.dkr.ecr.<region>.amazonaws.com/smdistributed-modelparallel:2.1.2-gpu-py310-cu121
```

如需可使用 SMP Docker 映像檔的區域，請參閱 [AWS 區域](distributed-model-parallel-support-v2.md#distributed-model-parallel-availablity-zone-v2)。

**此版本的二進位檔案**

您可以使用下列 URL 下載或安裝程式庫。

```
https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.1.0/cu121/2024-02-04/smdistributed_dataparallel-2.1.0-cp310-cp310-linux_x86_64.whl
```

## SageMaker AI 分散式資料平行化程式庫 v2.0.1
<a name="data-parallel-release-notes-20231207"></a>

*日期：2023 年 12 月 7 日*

**新功能**
+ 新增了針對 AWS 運算資源和網路基礎設施最佳化的`AllGather`集合操作的 SMDDP 實作。如需詳細資訊，請參閱 [SMDDP `AllGather` 集體操作](data-parallel-intro.md#data-parallel-allgather)。
+ SMDDP `AllGather` 集體操作與 PyTorch FSDP 和 DeepSpeed 相容。如需詳細資訊，請參閱 [在 PyTorch 訓練指令碼中使用 SMDDP 程式庫](data-parallel-modify-sdp-pt.md)。
+ 新增支援 PyTorch v2.0.1

**已知問題**
+ 在 DDP 模式下使用 SMDDP `AllReduce` 進行訓練時，由於 CPU 記憶體逐漸增加，導致 CPU 記憶體洩漏問題。

**整合到 SageMaker AI 架構容器**

此版本的 SMDDP 程式庫已通過基準測試，並遷移至下列 [SageMaker AI 架構容器](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sagemaker-framework-containers-sm-support-only)。
+ PyTorch v2.0.1

  ```
  763104351884.dkr.ecr.<region>.amazonaws.com/pytorch-training:2.0.1-gpu-py310-cu118-ubuntu20.04-sagemaker
  ```

**此版本的二進位檔案**

您可以使用下列 URL 下載或安裝程式庫。

```
https://smdataparallel.s3.amazonaws.com/binary/pytorch/2.0.1/cu118/2023-12-07/smdistributed_dataparallel-2.0.2-cp310-cp310-linux_x86_64.whl
```

**其他變更**
+ 從此版本開始，本《Amazon SageMaker AI 開發人員指南》**已完整提供 SMDDP 程式庫的完整文件。為了支援《Amazon SageMaker AI 開發人員指南》**中有關 SMDDP v2 的完整開發人員指南，*SageMaker AI Python SDK 文件*中有關 [SMDDP v1.x 的附加參考](https://sagemaker.readthedocs.io/en/stable/api/training/smd_data_parallel.html)文件不再受支援。如果您仍然需要 SMP v1.x 文件，請參閱 [SageMaker Python SDK v2.212.0 文件](https://sagemaker.readthedocs.io/en/v2.212.0/api/training/distributed.html#the-sagemaker-distributed-data-parallel-library)中的下列文件快照。