

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

# 在训练脚本中使用 SMDDP 库 PyTorch
<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)、PyTorch 完全分片数据并行](https://pytorch.org/docs/stable/notes/ddp.html)[性 (FSDP) 和威震](https://pytorch.org/docs/stable/fsdp.html)天-。[DeepSpeed](https://github.com/microsoft/DeepSpeed)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`后端目前不支持使用 API 创建子流程组。`torch.distributed.new_group()`您也不能同时使用 `smddp` 后端和其他进程组后端，如 `NCCL` 和 `Gloo`。

## 对于我们的 DeepSpeed 威震天-DeepSpeed
<a name="data-parallel-enable-for-deepspeed"></a>

进程组初始化如下。

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

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

**注意**  
要将 SMDDP `AllGather` 与 [使用 Python SageMaker SDK 使用 SMDDP 启动分布式训练作业](data-parallel-use-api.md) 中基于 `mpirun` 的启动器（`smdistributed` 和 `pytorchddp`）配合使用，还需要在训练脚本中设置以下环境变量。  

```
export SMDATAPARALLEL_OPTIMIZE_SDP=true
```

有关编写 PyTorch FSDP 训练脚本的一般指导，请参阅文档中的[使用完全分片数据并行 (FSDP) 进行高级模型训练](https://pytorch.org/tutorials/intermediate/FSDP_adavnced_tutorial.html)。 PyTorch

有关编写 PyTorch DDP 训练脚本的一般指导，请参阅 PyTorch 文档中的[分布式并行数据入门](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html)。

调整完训练脚本后，继续到 [使用 Python SageMaker SDK 使用 SMDDP 启动分布式训练作业](data-parallel-use-api.md)。