PyTorch 分布式训练主流方案:
| 方案 | 推荐度 | 说明 |
|---|---|---|
| DistributedDataParallel (DDP) | ✅✅✅ 官方推荐 | 高性能、稳定 |
| DataParallel (DP) | ❌ | 单进程、性能差 |
| FSDP | ✅ | 超大模型(LLM) |
| DeepSpeed | ✅ | 超大规模训练 |
nvidia-smi确认 CUDA 版本:
nvcc --version建议:
推荐使用 conda
conda create -n torch_ddp python=3.10 -y
conda activate torch_ddp安装 PyTorch(示例 CUDA 11.8):
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118验证:
import torch
print(torch.cuda.device_count())
print(torch.cuda.is_available())✅ PyTorch 默认使用 NCCL 做 GPU 通信
一般 pip install torch 已包含,但服务器环境需确认:
apt install libnccl2 libnccl-dev验证:
import torch
print(torch.distributed.is_nccl_available())DDP 依赖以下环境变量:
| 变量 | 作用 |
|---|---|
| MASTER_ADDR | 主节点 IP |
| MASTER_PORT | 通信端口 |
| WORLD_SIZE | 总 GPU 数 |
| RANK | 当前进程编号 |
使用 torchrun
torchrun \
--nproc_per_node=4 \
train.pyimport os
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
def setup():
dist.init_process_group(backend="nccl")
def cleanup():
dist.destroy_process_group()
def main():
setup()
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
model = nn.Linear(10, 1).cuda(local_rank)
model = DDP(model, device_ids=[local_rank])
dataset = torch.randn(100, 10)
sampler = DistributedSampler(dataset)
loader = DataLoader(dataset, batch_size=8, sampler=sampler)
for x in loader:
x = x.cuda(local_rank)
loss = model(x).mean()
loss.backward()
cleanup()
if __name__ == "__main__":
main()torchrun \
--nproc_per_node=4 \
--nnodes=2 \
--node_rank=0 \
--master_addr=192.168.1.10 \
--master_port=29500 \
train.pytorchrun \
--nproc_per_node=4 \
--nnodes=2 \
--node_rank=1 \
--master_addr=192.168.1.10 \
--master_port=29500 \
train.py⚠️ 多机必须:
❌ 错误:
DataLoader(dataset, shuffle=True)✅ 正确:
sampler = DistributedSampler(dataset)
DataLoader(dataset, batch_size=..., sampler=sampler)每个 epoch 前:
sampler.set_epoch(epoch)DistributedSampler✅ 原因:
解决:
export NCCL_DEBUG=INFO
export NCCL_SOCKET_IFNAME=eth0✅ 检查:
ping MASTER_ADDR
telnet MASTER_ADDR MASTER_PORTPyTorch 2.x
CUDA 11.8 / 12.1
NCCL 2.18+
Ubuntu 22.04
torchrun + DDP| 场景 | 方案 |
|---|---|
| 大模型 | FSDP / DeepSpeed |
| 混合精度 | torch.cuda.amp |
| 梯度累积 | 手动 step |
| 断点恢复 | save/load rank0 |
你可以直接告诉我:
1️⃣ 单机还是多机?
2️⃣ 显卡数量 & 型号?
3️⃣ 是否用 Docker / Slurm?
4️⃣ 训练 CV / NLP / LLM?
我可以给你 完全可运行的模板代码 + 启动脚本。