数据并行的核心思想是:
流程示意:
输入数据
↓ split
GPU0: model(data0) → loss0
GPU1: model(data1) → loss1
...
↓ 梯度 AllReduce
↓ 更新参数DataParallel(DP)model = nn.DataParallel(model)特点:
缺点:
DistributedDataParallel(DDP,强烈推荐)from torch.nn.parallel import DistributedDataParallel as DDP特点:
| 维度 | DP | DDP |
|---|---|---|
| 通信方式 | 主卡汇总 | AllReduce |
| 扩展性 | 差 | 好 |
| 多机 | ❌ | ✅ |
| 官方推荐 | ❌ | ✅ |
torch.distributedDataLoader(DistributedSampler)配合好DDP 被广泛用于:
数据并行 不是万能的,以下情况需谨慎或补充方案:
此时应改用:
✅ 数据并行(DDP)是首选
✅ 单机多卡、多机多卡都推荐 DDP
✅ 模型放得下就优先 DDP| 场景 | 推荐 |
|---|---|
| 单机多卡 | DDP |
| 多机多卡 | DDP + NCCL |
| 超大模型 | FSDP / ZeRO |
| 大模型 + 长序列 | 数据并行 + 模型并行 |
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
dist.init_process_group("nccl")
model = model.to(local_rank)
model = DDP(model, device_ids=[local_rank])
# DataLoader
sampler = DistributedSampler(dataset)
loader = DataLoader(dataset, sampler=sampler)✅ 数据并行非常适合 PyTorch 分布式训练,尤其是DistributedDataParallel(DDP)。
只要你不是“模型单卡装不下”,DDP 基本就是最优解。
如果你愿意,我可以:
直接告诉我你的训练场景即可。