PyTorch 分布式训练
核对 DistributedSampler 无重叠分片与 set_epoch、FileStore、Ring AllReduce 梯度等价、DDP+AMP 同步与 module. 前缀、两阶段模型切分及 Windows Gloo/NCCL 边界。
学完这一章,你能够
- 核对 DistributedSampler 无重叠分片与 set_epoch、FileStore、Ring AllReduce 梯度等价、DDP+AMP 同步与 module. 前缀、两阶段模型切分及 Windows Gloo/NCCL 边界。
分布式训练动机、两大并行模式与 DataParallel
随着参数规模与语料增长,单卡显存和算力逐渐见顶。分布式训练通过多卡或多机并行解决显存不足与耗时过长问题,主要分为数据并行(每卡保存完整模型、切分不同批次数据,最常用)与模型并行(单卡装不下超大模型时将网络按层或张量拆分到多卡)。
DataParallel(DP)是单进程多线程的最简多卡封装:每步复制模型到各卡、拆分 batch、并行前向、把梯度汇总回主卡更新再广播权重。因其受 Python GIL 限制、主卡显存与通信负载偏重,仅适合快速验证;访问原模型属性或保存权重需通过 model.module(本站已在 CPU 验证 nn.DataParallel(nn.Linear(8, 4)) 的前向形状 [12, 4] 与 .module 契约)。生产多卡训练统一推荐 DistributedDataParallel(DDP)。
DistributedDataParallel 原理、DistributedSampler 与 torchrun
DDP 采用每卡一进程(规避 GIL),各进程独立前向与反向并通过 Ring AllReduce 均衡同步梯度,原生支持单机多卡与多机多卡。启动应优先使用 torchrun --nproc_per_node=...(替代旧版 torch.distributed.launch),由框架注入 RANK、LOCAL_RANK、WORLD_SIZE、MASTER_ADDR/PORT 等环境变量(注意修正来源脚本缺陷:多机部署时勿硬编码覆盖 MASTER_ADDR/PORT,且设备绑定应取 local_rank 而非全局 rank,数据加载辅助函数需显式接收 rank)。配合 DistributedSampler 时每轮开始必须调用 sampler.set_epoch(epoch) 刷新随机种子,否则各轮分片顺序重复:本站实测 20 样本 2 进程下 rank0 与 rank1 索引完全不相交且并集覆盖全集,set_epoch(0) 与 set_epoch(1) 顺序明确变化,11 样本设 drop_last=True 每卡均衡分得 5 条。
DDP 联合 AMP、Ring AllReduce 与模型/流水线并行
DDP 与现代 torch.amp 混合精度结合能同时减少单卡显存与跨卡通信字节数(注意将来源旧版 torch.cuda.amp 升级为 torch.amp.autocast 与 torch.amp.GradScaler)。Ring AllReduce 把梯度切分为 N 份经 N-1 次 Scatter-Reduce 与 N-1 次 All-Gather 环形交换完成全节点求和平均。本站直接实现 4 节点 Ring AllReduce 算法并验证:环形求和与直接求和最大误差为 0.0,4 分片平均梯度与整批单模型梯度最大误差仅 1e-8;在 2 节点 CPU BF16 AMP 梯度同步模拟训练 10 步后,损失由 1.2562 降至 0.57377、两节点权重漂移为 0.0,且将带 module. 前缀的 state_dict 剥离后重载输出误差 0.0。
当单卡显存无法容纳单个模型时需采用模型并行与流水线并行(把大批切分为多个 micro-batch 让不同阶段重叠执行减少气泡)。重要版本演进:PyTorch 2.10 已彻底移除旧包 torch.distributed.pipeline.sync(来源 Pipe 示例无法直接导入),官方新架构迁移至 torch.distributed.pipelining(本站已实测核实旧包缺失、新包存在)。本站构建两阶段切分模型并以 3 微批执行前向与反向传播,与整体单网络对比输出最大误差 0.0、梯度最大误差 4e-8。
性能优化、排障清单、监控与 Windows/CPU 运行边界
多机多卡调优应坚持:GPU 集群首选 NCCL 后端(设 NCCL_DEBUG=INFO 排障并核查防火墙端口与 NTP 时钟同步)、合理配置 num_workers/pin_memory 与 bucket_cap_mb、配合 nvidia-smi 与 PyTorch Profiler 定位通信或 I/O 瓶颈,并先在单机验证通过再扩展至多机。实测环境边界须如实说明:当前 Windows x64 CPU 轮子(torch 2.10.0+cpu)虽支持 FileStore 协调读写并报告 dist.is_gloo_available()=True,但实际调用 init_process_group(backend='gloo') 会抛出 RuntimeError('makeDeviceForHostname(): unsupported gloo device'),且 is_nccl_available() 与 cuda.is_available() 均为 False——真实多进程 Gloo/NCCL 通信与 torchrun 多卡训练需在 Linux 或多 GPU 集群环境执行。
数据并行与模型并行核心对比
| 模式 | 原理 | 适用场景 |
|---|---|---|
| 数据并行(Data Parallel) | 各计算单元保存完整模型副本,切分不同数据批次并同步平均梯度 | 模型可装入单卡显存、需按数据吞吐横向加速 |
| 模型并行(Model Parallel) | 按层或张量把模型切分到多张卡,各卡只持有局部参数 | 超大参数模型单卡装不下,常与流水线并行联用 |
分布式训练关键性能优化项
| 优化项 | 技巧 | 说明 |
|---|---|---|
| 通信优化 | 多卡 GPU 选用 NCCL 后端 | Linux GPU 集群吞吐远高于 Gloo(需多卡 GPU 环境) |
| 数据加载 | 设置合适 num_workers 与 pin_memory=True | 避免数据读取拖慢多卡计算 |
| 梯度同步 | 按模型尺寸调优 DDP bucket_cap_mb | 平衡通信启动次数与计算/通信重叠度 |
| 混合精度 | DDP 结合 torch.amp 混合精度 | 同步缩减单卡显存与跨卡梯度通信字节量 |
分布式训练常见故障排查表
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 通信慢 | 节点间网络带宽受限或后端选择不当 | 优先 NCCL、高速互联并检查 NCCL_DEBUG 日志 |
| 显存不足 | 单卡微批过大或模型切分不均 | 减小单卡 batch、启用梯度累积与 AMP |
| 负载不均衡 | 模型阶段划分不均或样本长度差异大 | 按计算量重新平衡各阶段层分布 |
| 同步错误 | 部分卡出现梯度 NaN 或超时失步 | 检查梯度裁剪/GradScaler,并在每轮调用 sampler.set_epoch(epoch) |
运行 DistributedSampler、Ring AllReduce 等价、多节点 AMP 同步、模型切分与后端边界实验
"""Independent PyTorch 2.10 CPU distributed primitives lab (DistributedSampler, FileStore, Ring AllReduce math, model split, Windows Gloo/NCCL boundary)."""
import importlib.util
import json
import platform
import tempfile
from pathlib import Path
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import TensorDataset
from torch.utils.data.distributed import DistributedSampler
def ring_allreduce_sum(rank_tensors: list[torch.Tensor]) -> list[torch.Tensor]:
"""Explicit Ring AllReduce (scatter-reduce + all-gather) across N workers."""
n = len(rank_tensors)
chunks = [list(t.clone().chunk(n)) for t in rank_tensors]
# Scatter-reduce: n-1 ring hops
for step in range(n - 1):
new_chunks = [[c.clone() for c in worker] for worker in chunks]
for r in range(n):
recv_idx = (r - step - 1) % n
src = (r - 1) % n
new_chunks[r][recv_idx] = chunks[r][recv_idx] + chunks[src][recv_idx]
chunks = new_chunks
# All-gather: n-1 ring hops
for step in range(n - 1):
new_chunks = [[c.clone() for c in worker] for worker in chunks]
for r in range(n):
recv_idx = (r - step) % n
src = (r - 1) % n
new_chunks[r][recv_idx] = chunks[src][recv_idx].clone()
chunks = new_chunks
return [torch.cat(worker, dim=0) for worker in chunks]
class TwoStageModelSplit(nn.Module):
"""Explicit 2-stage model partition verifying exact equivalence with a monolithic MLP."""
def __init__(self, stage1: nn.Module, stage2: nn.Module):
super().__init__()
self.stage1 = stage1
self.stage2 = stage2
def forward(self, x: torch.Tensor, chunks: int = 2) -> torch.Tensor:
outs = []
for micro in x.chunk(chunks, dim=0):
h = self.stage1(micro)
outs.append(self.stage2(h))
return torch.cat(outs, dim=0)
def run_cases():
torch.manual_seed(2026)
cases = []
# 1. DistributedSampler sharding across 2 ranks & mandatory set_epoch(epoch)
ds = TensorDataset(torch.arange(20).unsqueeze(1).float(), torch.arange(20))
s_r0 = DistributedSampler(ds, num_replicas=2, rank=0, shuffle=True, seed=42)
s_r1 = DistributedSampler(ds, num_replicas=2, rank=1, shuffle=True, seed=42)
s_r0.set_epoch(0)
s_r1.set_epoch(0)
idx_e0_r0 = list(iter(s_r0))
idx_e0_r1 = list(iter(s_r1))
s_r0.set_epoch(1)
idx_e1_r0 = list(iter(s_r0))
disjoint = len(set(idx_e0_r0).intersection(idx_e0_r1)) == 0
full_cover = sorted(idx_e0_r0 + idx_e0_r1) == list(range(20))
epoch_shuffled = idx_e0_r0 != idx_e1_r0
ds_odd = TensorDataset(torch.arange(11).unsqueeze(1).float())
s_drop = DistributedSampler(ds_odd, num_replicas=2, rank=0, shuffle=False, drop_last=True)
drop_len = len(list(iter(s_drop)))
c1_ok = disjoint and full_cover and epoch_shuffled and drop_len == 5
cases.append(dict(
name="distributed_sampler_sharding_and_set_epoch",
inputs=dict(dataset_size=20, num_replicas=2, odd_size=11),
prerequisites="核对 DistributedSampler 的跨进程无重叠分片、set_epoch(epoch) 打乱更新与 drop_last 行为",
action="验证 rank0 与 rank1 索引互不相交且并集覆盖全集,不同 epoch 顺序变化,且 11 样本 drop_last=True 每卡 5 条。",
expected=dict(disjoint=True, full_cover=True, set_epoch_changes_order=True, drop_last_len=5),
actual=dict(disjoint=disjoint, full_cover=full_cover, set_epoch_changes_order=epoch_shuffled, drop_last_len=drop_len),
passed=c1_ok,
))
# 2. FileStore rendezvous + 4-worker Ring AllReduce numerical parity with monolithic batch training
with tempfile.TemporaryDirectory() as tmp:
fs = dist.FileStore(str(Path(tmp) / "store"), 1)
fs.set("rank0_ready", "1")
store_val = fs.get("rank0_ready").decode("utf-8")
# Ring AllReduce exact sum test on 4 vectors of length 8
vecs = [torch.arange(8, dtype=torch.float32) + float(r + 1) for r in range(4)]
reduced = ring_allreduce_sum(vecs)
direct_sum = sum(vecs)
ring_err = max((t - direct_sum).abs().max().item() for t in reduced)
# Verify 4-shard averaged gradients equal single monolithic full-batch gradient
torch.manual_seed(10)
full_m = nn.Sequential(nn.Linear(8, 16), nn.ReLU(), nn.Linear(16, 3))
workers = [nn.Sequential(nn.Linear(8, 16), nn.ReLU(), nn.Linear(16, 3)) for _ in range(4)]
for w in workers:
w.load_state_dict(full_m.state_dict())
xb = torch.randn(32, 8)
yb = (xb[:, 0] > 0).long() + (xb[:, 1] > 0).long()
F.cross_entropy(full_m(xb), yb).backward()
for r, w in enumerate(workers):
sl = slice(r * 8, (r + 1) * 8)
F.cross_entropy(w(xb[sl]), yb[sl]).backward()
max_grad_parity_err = 0.0
for p_idx, p_full in enumerate(full_m.parameters()):
avg_g = sum(list(w.parameters())[p_idx].grad for w in workers) / 4.0
max_grad_parity_err = max(max_grad_parity_err, float((p_full.grad - avg_g).abs().max().item()))
c2_ok = store_val == "1" and ring_err < 1e-6 and max_grad_parity_err < 1e-5
cases.append(dict(
name="ring_allreduce_math_and_ddp_grad_equiv",
inputs=dict(num_workers=4, full_batch=32, per_worker_batch=8),
prerequisites="核对 FileStore 协调读写、4 节点 Ring AllReduce 算法(Scatter-Reduce + All-Gather)与数据并行平均梯度等价性",
action="验证 Ring AllReduce 汇总误差 <1e-6,且 4 分片平均梯度与整批单模型梯度最大误差 <1e-5。",
expected=dict(filestore_ok=True, ring_sum_exact=True, data_parallel_grad_parity=True),
actual=dict(filestore_ok=store_val == "1", ring_sum_exact=ring_err < 1e-6, data_parallel_grad_parity=max_grad_parity_err < 1e-5),
measurements=dict(ring_max_err=round(ring_err, 8), grad_parity_err=round(max_grad_parity_err, 8)),
passed=c2_ok,
))
# 3. Synchronized multi-worker BF16 AMP step & DDP module. state_dict prefix stripping
torch.manual_seed(20)
w0 = nn.Sequential(nn.Linear(8, 16), nn.ReLU(), nn.Linear(16, 3))
w1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU(), nn.Linear(16, 3))
w1.load_state_dict(w0.state_dict())
opt0 = optim.AdamW(w0.parameters(), lr=3e-2)
opt1 = optim.AdamW(w1.parameters(), lr=3e-2)
scaler = torch.amp.GradScaler(device="cpu", enabled=False)
losses = []
for _ in range(10):
opt0.zero_grad(set_to_none=True)
opt1.zero_grad(set_to_none=True)
with torch.amp.autocast(device_type="cpu", dtype=torch.bfloat16):
l0 = F.cross_entropy(w0(xb[:16]), yb[:16])
l1 = F.cross_entropy(w1(xb[16:]), yb[16:])
scaler.scale(l0).backward()
scaler.scale(l1).backward()
# Synchronize gradients across workers (AllReduce mean)
for p0, p1 in zip(w0.parameters(), w1.parameters()):
synced = 0.5 * (p0.grad + p1.grad)
p0.grad.copy_(synced)
p1.grad.copy_(synced)
scaler.step(opt0)
scaler.step(opt1)
scaler.update()
losses.append(round(0.5 * (float(l0.item()) + float(l1.item())), 5))
param_drift = max((p0 - p1).abs().max().item() for p0, p1 in zip(w0.parameters(), w1.parameters()))
# Simulate DDP saved state_dict with 'module.' prefix and clean reload
prefixed_sd = {f"module.{k}": v.clone() for k, v in w0.state_dict().items()}
stripped_sd = {k.removeprefix("module."): v for k, v in prefixed_sd.items()}
reloaded = nn.Sequential(nn.Linear(8, 16), nn.ReLU(), nn.Linear(16, 3))
reloaded.load_state_dict(stripped_sd)
reload_diff = float((w0(xb) - reloaded(xb)).abs().max().item())
c3_ok = losses[-1] < losses[0] * 0.65 and param_drift == 0.0 and reload_diff == 0.0
cases.append(dict(
name="ddp_amp_gradient_sync_and_module_prefix",
inputs=dict(workers=2, autocast_dtype="bfloat16", steps=10),
prerequisites="使用新版 torch.amp.autocast + GradScaler 模拟 2 节点梯度同步训练,并验证 module. 权重前缀清理",
action="核对 10 步同步训练损失下降、两节点权重零漂移(0.0)及剥离 module. 前缀后重载误差 0.0。",
expected=dict(loss_dropped=True, workers_stay_synced=True, prefix_strip_exact=True),
actual=dict(loss_dropped=losses[-1] < losses[0] * 0.65, workers_stay_synced=param_drift == 0.0, prefix_strip_exact=reload_diff == 0.0),
measurements=dict(step1_loss=losses[0], step10_loss=losses[-1], param_drift=param_drift),
passed=c3_ok,
))
# 4. DataParallel wrapper contract + 2-stage model split & micro-batch chunk equivalence
torch.manual_seed(30)
s1 = nn.Sequential(nn.Linear(8, 12), nn.ReLU())
s2 = nn.Sequential(nn.Linear(12, 4))
mono = nn.Sequential(s1, s2)
s1_copy = nn.Sequential(nn.Linear(8, 12), nn.ReLU())
s2_copy = nn.Sequential(nn.Linear(12, 4))
s1_copy.load_state_dict(s1.state_dict())
s2_copy.load_state_dict(s2.state_dict())
split_m = TwoStageModelSplit(s1_copy, s2_copy)
xm = torch.randn(12, 8)
ym = torch.randint(0, 4, (12,))
out_mono = mono(xm)
out_split = split_m(xm, chunks=3)
F.cross_entropy(out_mono, ym).backward()
F.cross_entropy(out_split, ym).backward()
out_diff = float((out_mono - out_split).abs().max().item())
grad_diff = max((p1.grad - p2.grad).abs().max().item() for p1, p2 in zip(mono.parameters(), split_m.parameters()))
dp_wrapped = nn.DataParallel(nn.Linear(8, 4))
dp_cpu_out = dp_wrapped(xm)
c4_ok = out_diff < 1e-6 and grad_diff < 1e-6 and list(dp_cpu_out.shape) == [12, 4] and isinstance(dp_wrapped.module, nn.Linear)
cases.append(dict(
name="dataparallel_cpu_and_model_split_pipeline",
inputs=dict(batch=12, micro_chunks=3),
prerequisites="验证 nn.DataParallel 的 .module 封装语义及两阶段模型切分 + 微批流水切分梯度等价性",
action="比较整体模型与两阶段 3 微批切分的前向输出与参数梯度,确认最大误差 <1e-6。",
expected=dict(forward_exact=True, grad_exact=True, dp_cpu_shape=[12, 4], dp_has_module=True),
actual=dict(forward_exact=out_diff < 1e-6, grad_exact=grad_diff < 1e-6, dp_cpu_shape=list(dp_cpu_out.shape), dp_has_module=isinstance(dp_wrapped.module, nn.Linear)),
measurements=dict(max_out_diff=round(out_diff, 8), max_grad_diff=round(grad_diff, 8)),
passed=c4_ok,
))
# 5. API evolution & Windows CPU Gloo/NCCL runtime boundary
old_pipe_removed = importlib.util.find_spec("torch.distributed.pipeline") is None
new_pipelining_present = importlib.util.find_spec("torch.distributed.pipelining") is not None
nccl_ok = bool(dist.is_nccl_available())
gloo_reported = bool(dist.is_gloo_available())
windows_gloo_device_unsupported = False
with tempfile.TemporaryDirectory() as tmp:
try:
st = dist.FileStore(str(Path(tmp) / "gloo_probe"), 1)
dist.init_process_group(backend="gloo", store=st, rank=0, world_size=1)
dist.destroy_process_group()
except RuntimeError as exc:
windows_gloo_device_unsupported = "unsupported gloo device" in str(exc)
c5_ok = old_pipe_removed and new_pipelining_present and gloo_reported and windows_gloo_device_unsupported and (not nccl_ok) and (not torch.cuda.is_available())
cases.append(dict(
name="windows_gloo_nccl_and_pipelining_boundary",
inputs=dict(old_module="torch.distributed.pipeline", new_module="torch.distributed.pipelining"),
prerequisites="核对 PyTorch 2.10 移除旧 pipeline.sync、新增 torch.distributed.pipelining,以及 Windows CPU 轮子 Gloo/NCCL 边界",
action="验证旧包移除、新包存在,且当前 Windows CPU wheel 虽报告 is_gloo_available=True 但初始化会报 unsupported gloo device、NCCL/CUDA 不可用。",
expected=dict(old_pipe_removed=True, new_pipelining_present=True, windows_gloo_unsupported=True, nccl_available=False, cuda_available=False),
actual=dict(old_pipe_removed=old_pipe_removed, new_pipelining_present=new_pipelining_present, windows_gloo_unsupported=windows_gloo_device_unsupported, nccl_available=nccl_ok, cuda_available=bool(torch.cuda.is_available())),
passed=c5_ok,
))
print(json.dumps(dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(), cases=cases), ensure_ascii=False))
if __name__ == "__main__":
run_cases()
- 核对 DistributedSampler 无重叠分片与 set_epoch 变化、FileStore 读写、4 节点 Ring AllReduce 误差 0.0 及梯度等价误差 1e-8、2 节点 BF16 同步零漂移、两阶段 3 微批等价及 PyTorch 2.10 pipelining/Windows Gloo 边界。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
当前源码 SHA256:e40aba9e79b14fe76d675146ce42973604f1cdb44012e888de865814cb3da080
本地运行
解压后按 README 选择对应构建并运行脚本。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
ZIP SHA256:79eb00dd5debd15f6f5c433b7b38518a8ffc70872abc764c57e491f7443a2fde
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 DDP 训练循环的每个 epoch 开始前必须调用 train_sampler.set_epoch(epoch)?
展开参考解答
DistributedSampler 默认以固定种子 + self.epoch 确定跨进程随机洗牌顺序;若不更新 epoch,所有轮次都会产生完全相同的样本切分与顺序,削弱随机梯度下降的泛化能力。