7种并行、3D并行、ZeRO、通信原语、DeepSpeed、Megatron-LM、FSDP对比
大模型训练需要巨大的计算和显存资源。以70B参数模型为例,仅模型参数(fp16)就需要140GB显存,加上梯度和优化器状态,单卡(80GB A100)完全无法容纳。分布式训练是训练大模型的唯一可行方案。
| 模型规模 | 参数显存(fp16) | 训练显存(Adam混合精度) | 单卡可行? | 最小GPU数 |
|---|---|---|---|---|
| 7B | 14GB | ~112GB | ✗ | 2-4 |
| 13B | 26GB | ~208GB | ✗ | 4-8 |
| 70B | 140GB | ~1120GB | ✗ | 16-32 |
| 175B | 350GB | ~2800GB | ✗ | 64-128 |
| 540B | 1080GB | ~8640GB | ✗ | 128-256 |
| 策略 | 缩写 | 切分维度 | 通信类型 | 主要用途 |
|---|---|---|---|---|
| 数据并行 | DP | 数据batch | AllReduce梯度 | 扩展batch size |
| 分片数据并行 | SDP/FSDP | 参数+梯度+优化器 | AllGather+ReduceScatter | 减少显存占用 |
| 张量并行 | TP | 层内参数 | AllReduce(每层) | 减少单层显存 |
| 流水线并行 | PP | 层间分配 | P2P(相邻stage) | 扩展模型深度 |
| 序列并行 | SP | 序列维度 | AllGather+ReduceScatter | 长序列训练 |
| 专家并行 | EP | 专家分配 | All-to-All | MoE模型训练 |
| 上下文并行 | CP | 上下文窗口 | Ring Attention | 超长上下文 |
数据并行是最简单的并行策略:每张卡持有完整模型副本,处理不同数据batch,前向后通过AllReduce同步梯度。
import torch
import torch.distributed as dist
class DataParallel:
"""经典数据并行实现"""
def __init__(self, model, world_size):
self.model = model.cuda()
self.world_size = world_size
self.optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
def step(self, batch):
# 1. 前向传播 (各卡独立)
loss = self.model(batch)
# 2. 反向传播 (各卡独立)
loss.backward()
# 3. 梯度AllReduce同步
for param in self.model.parameters():
if param.grad is not None:
dist.all_reduce(param.grad, op=dist.ReduceOp.SUM)
param.grad /= self.world_size
# 4. 优化器更新
self.optimizer.step()
self.optimizer.zero_grad()
return loss.item()
AllReduce是数据并行的核心通信操作,实现所有GPU上的梯度求和。最常用的实现是Ring AllReduce,通信量为2(N-1)·S/N(S是梯度大小,N是GPU数),带宽利用率接近最优。
# AllReduce通信量分析
def allreduce_comm_cost(param_size_bytes, n_gpus):
"""Ring AllReduce通信量"""
# Phase 1 (Reduce-Scatter): (N-1) * S/N
# Phase 2 (All-Gather): (N-1) * S/N
# 总量: 2*(N-1)*S/N
total = 2 * (n_gpus - 1) * param_size_bytes / n_gpus
return total
# 70B模型梯度同步通信量
N_params = 70e9
grad_size = N_params * 4 # fp32梯度
for n in [8, 32, 64, 128]:
comm = allreduce_comm_cost(grad_size, n)
print(f"{n:4d} GPUs: {comm/1e9:.1f}GB通信/step, "
f"每GPU: {comm/n/1e9:.1f}GB")
ZeRO(Zero Redundancy Optimizer)通过分片模型状态来消除数据并行中的冗余。三个阶段逐步增加分片程度:
| 阶段 | 分片对象 | 显存(per GPU) | 通信量 | vs DP |
|---|---|---|---|---|
| ZeRO-1 | 优化器状态 | 2N + 2N + 4N/K | = DP | 显存↓ 通信= |
| ZeRO-2 | 优化器+梯度 | 2N + 2N/K + 4N/K | ≈ DP | 显存↓↓ 通信≈ |
| ZeRO-3 | 优化器+梯度+参数 | (2N+2N+4N)/K | > DP | 显存↓↓↓ 通信↑ |
其中N是参数量,K是GPU数。ZeRO-3等价于FSDP(Fully Sharded Data Parallel)。
# ZeRO显存分析
def zero_memory(N_params, K_gpus, stage=3, precision="mixed"):
"""计算ZeRO各阶段的显存占用"""
if precision == "mixed":
param_mem = 2 * N_params # fp16参数
grad_mem = 2 * N_params # fp16梯度
opt_mem = 4 * N_params # fp32 Adam状态 (m + v)
else:
param_mem = 4 * N_params
grad_mem = 4 * N_params
opt_mem = 8 * N_params
if stage == 0: # 标准DP
total = param_mem + grad_mem + opt_mem
elif stage == 1: # ZeRO-1: 分片优化器
total = param_mem + grad_mem + opt_mem / K_gpus
elif stage == 2: # ZeRO-2: 分片优化器+梯度
total = param_mem + grad_mem / K_gpus + opt_mem / K_gpus
elif stage == 3: # ZeRO-3: 全分片
total = (param_mem + grad_mem + opt_mem) / K_gpus
return total / (1024**3) # GB
# 70B模型在不同ZeRO阶段和GPU数下的显存
N = 70e9
print(f"{'GPU数':>6} {'标准DP':>10} {'ZeRO-1':>10} {'ZeRO-2':>10} {'ZeRO-3':>10}")
for K in [8, 16, 32, 64]:
dp = zero_memory(N, K, 0)
z1 = zero_memory(N, K, 1)
z2 = zero_memory(N, K, 2)
z3 = zero_memory(N, K, 3)
print(f"{K:>6} {dp:>9.1f}G {z1:>9.1f}G {z2:>9.1f}G {z3:>9.1f}G")
import torch
import torch.distributed as dist
import torch.nn.functional as F
class FSDPParameter:
"""ZeRO-3/FSDP参数分片"""
def __init__(self, param, rank, world_size):
self.rank = rank
self.world_size = world_size
self.full_size = param.numel()
self.shard_size = self.full_size // world_size
# 分片参数: 每个rank只持有1/world_size的参数
self.shard = param.data.chunk(world_size)[rank].clone()
# 临时全参数缓冲 (前向时gather)
self._full_param = None
def gather(self):
"""前向前: AllGather收集完整参数"""
gathered = [torch.zeros_like(self.shard) for _ in range(self.world_size)]
dist.all_gather(gathered, self.shard)
self._full_param = torch.cat(gathered)
return self._full_param
def scatter_grad(self, grad):
"""反向后: ReduceScatter梯度分片"""
grad_shards = grad.chunk(self.world_size)
reduced = torch.zeros_like(self.shard)
dist.reduce_scatter([reduced], [grad_shards[self.rank]], op=dist.ReduceOp.SUM)
return reduced
class FSDPModel(torch.nn.Module):
"""FSDP模型包装器"""
def __init__(self, model, rank, world_size):
super().__init__()
self.model = model
self.rank = rank
self.world_size = world_size
# 分片所有参数
self.fsdp_params = {}
for name, param in model.named_parameters():
self.fsdp_params[name] = FSDPParameter(param, rank, world_size)
def forward(self, x):
# 前向前gather所有参数
for name, fsdp_p in self.fsdp_params.items():
full = fsdp_p.gather()
# 替换模型参数为完整版本
setattr(self.model, name, full.view_as(
dict(self.model.named_parameters())[name]))
# 正常前向
out = self.model(x)
return out
张量并行将模型每一层的参数矩阵按行或列切分到不同GPU上。对于线性层Y = XW,列切分将W按列分成[W1, W2],各GPU计算Yi = XWi,然后AllReduce合并。
class ColumnParallelLinear(nn.Module):
"""列并行线性层: W按列切分"""
def __init__(self, in_features, out_features, rank, world_size):
super().__init__()
self.rank = rank
self.world_size = world_size
assert out_features % world_size == 0
self.out_per_partition = out_features // world_size
# 每个rank只持有1/world_size的列
self.weight = nn.Parameter(torch.randn(
self.out_per_partition, in_features) / (in_features ** 0.5))
self.bias = nn.Parameter(torch.zeros(self.out_per_partition))
def forward(self, x):
# 各rank独立计算: Y_i = X @ W_i^T + b_i
out = F.linear(x, self.weight, self.bias)
return out # 不需要AllReduce (后续操作会处理)
class RowParallelLinear(nn.Module):
"""行并行线性层: W按行切分, 输入也按列切分"""
def __init__(self, in_features, out_features, rank, world_size):
super().__init__()
self.rank = rank
self.world_size = world_size
assert in_features % world_size == 0
self.in_per_partition = in_features // world_size
self.weight = nn.Parameter(torch.randn(
out_features, self.in_per_partition) / (in_features ** 0.5))
self.bias = nn.Parameter(torch.zeros(out_features))
def forward(self, x):
# 各rank独立计算部分结果
out_partial = F.linear(x, self.weight) # 无bias
# AllReduce求和
dist.all_reduce(out_partial, op=dist.ReduceOp.SUM)
out = out_partial + self.bias # bias只加一次
return out
class TPMLP(nn.Module):
"""张量并行MLP: ColumnParallel → GELU → RowParallel"""
def __init__(self, d_model, d_ff, rank, world_size):
super().__init__()
self.fc1 = ColumnParallelLinear(d_model, d_ff, rank, world_size)
self.fc2 = RowParallelLinear(d_ff, d_model, rank, world_size)
def forward(self, x):
h = F.gelu(self.fc1(x)) # 各rank独立
out = self.fc2(h) # AllReduce合并
return out
每个TP层需要一次AllReduce,通信量为2(TP-1)·B·S·d/TP(B=batch, S=seq_len, d=d_model)。TP通常在机内使用(NVLink高带宽),跨机通信开销过大。
流水线并行将模型的不同层分配到不同GPU上,数据像流水线一样依次通过各stage。主要问题是"气泡":当stage 1计算时,stage 2空闲,造成资源浪费。
# PP气泡分析
def pipeline_bubble(n_stages, n_microbatches):
"""计算流水线气泡比例"""
# 气泡 = (P-1) 个micro-batch的时间
# 总时间 = (M + P - 1) 个micro-batch的时间
bubble = (n_stages - 1) / (n_microbatches + n_stages - 1)
efficiency = 1 - bubble
return bubble, efficiency
print(f"{'Stages':>7} {'MicroB':>7} {'气泡%':>8} {'效率%':>8}")
for P in [4, 8, 16]:
for M in [8, 32, 128]:
b, e = pipeline_bubble(P, M)
print(f"{P:>7} {M:>7} {b*100:>7.1f}% {e*100:>7.1f}%")
print()
1F1B(One Forward One Backward)调度策略通过交错前向和反向传播,减少显存占用和气泡。每个stage在填满流水线后,交替执行一个前向和一个反向。
def schedule_1f1b(n_stages, n_microbatches):
"""生成1F1B调度计划"""
schedule = []
for stage in range(n_stages):
stage_ops = []
# Warmup: 前向填充流水线
warmup = n_stages - stage - 1
for i in range(warmup):
stage_ops.append(("F", i))
# Steady state: 1F1B交替
fwd_idx = warmup
bwd_idx = 0
for _ in range(n_microbatches - warmup):
stage_ops.append(("F", fwd_idx))
stage_ops.append(("B", bwd_idx))
fwd_idx += 1
bwd_idx += 1
# Cooldown: 剩余反向
while bwd_idx < n_microbatches:
stage_ops.append(("B", bwd_idx))
bwd_idx += 1
schedule.append(stage_ops)
return schedule
# 生成4 stage, 8 microbatch的1F1B调度
sched = schedule_1f1b(4, 8)
for i, ops in enumerate(sched):
op_str = " ".join(f"{op}{idx}" for op, idx in ops)
print(f"Stage {i}: {op_str}")
3D并行同时使用张量并行(TP)、流水线并行(PP)和数据并行(DP),将GPU集群组织为3D网格。通常TP在机内(NVLink),PP和DP跨机。
import torch
import torch.distributed as dist
class ParallelConfig:
"""3D并行配置"""
def __init__(self, tp_size, pp_size, dp_size):
self.tp_size = tp_size # 张量并行度
self.pp_size = pp_size # 流水线并行度
self.dp_size = dp_size # 数据并行度
self.world_size = tp_size * pp_size * dp_size
# 计算各维度rank
self.rank = dist.get_rank()
self.dp_rank = self.rank // (tp_size * pp_size)
remainder = self.rank % (tp_size * pp_size)
self.pp_rank = remainder // tp_size
self.tp_rank = remainder % tp_size
def build_3d_parallel(model_fn, config, n_layers):
"""构建3D并行模型"""
# 1. 流水线切分: 每个PP stage负责一部分层
layers_per_stage = n_layers // config.pp_size
my_layers = range(
config.pp_rank * layers_per_stage,
(config.pp_rank + 1) * layers_per_stage
)
# 2. 张量并行: 层内参数按TP切分
model = model_fn(
tp_rank=config.tp_rank, tp_size=config.tp_size,
layer_indices=my_layers
)
# 3. 数据并行: ZeRO分片优化器状态
if config.dp_size > 1:
model = FSDPModel(model, config.dp_rank, config.dp_size)
return model
# 示例: 64 GPU, TP=8, PP=4, DP=2
config = ParallelConfig(tp_size=8, pp_size=4, dp_size=2)
print(f"总GPU数: {config.world_size}")
print(f"TP(机内): {config.tp_size} (NVLink)")
print(f"PP(跨机): {config.pp_size}")
print(f"DP(跨机): {config.dp_size}")
import torch
import torch.distributed as dist
# AllReduce: 所有GPU上的tensor求和后广播到所有GPU
def demo_allreduce():
tensor = torch.tensor([dist.get_rank()], device="cuda")
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
# 每个GPU上tensor = 0+1+2+...+(N-1)
return tensor
# AllGather: 收集所有GPU上的tensor到完整列表
def demo_allgather():
local = torch.tensor([dist.get_rank()], device="cuda")
gathered = [torch.zeros(1, device="cuda") for _ in range(dist.get_world_size())]
dist.all_gather(gathered, local)
# gathered = [0, 1, 2, ..., N-1]
return gathered
# ReduceScatter: 求和后按分片scatter到各GPU
def demo_reduce_scatter():
world_size = dist.get_world_size()
local = torch.tensor([dist.get_rank()] * world_size, device="cuda")
output = torch.zeros(1, device="cuda")
dist.reduce_scatter(output, [local], op=dist.ReduceOp.SUM)
# output = sum of all ranks' corresponding shard
return output
# All-to-All (用于MoE专家并行)
def demo_alltoall():
world_size = dist.get_world_size()
# 每个GPU发送不同数据到不同目标GPU
send_tensors = [torch.ones(4, device="cuda") * (dist.get_rank() * world_size + i)
for i in range(world_size)]
recv_tensors = [torch.zeros(4, device="cuda") for _ in range(world_size)]
dist.all_to_all(recv_tensors, send_tensors)
return recv_tensors
| 原语 | 语义 | 通信量 | 用途 |
|---|---|---|---|
| AllReduce | Σ后广播 | 2(N-1)S/N | DP梯度同步, TP层输出 |
| AllGather | 收集完整 | (N-1)S/N | FSDP参数收集 |
| ReduceScatter | Σ后分片 | (N-1)S/N | FSDP梯度分片 |
| All-to-All | 全交换 | S | MoE专家路由 |
| Send/Recv | 点对点 | S | PP stage间传递 |
| Broadcast | 一对全 | S | 参数初始化同步 |
{
"train_batch_size": 1024,
"train_micro_batch_size_per_gpu": 4,
"gradient_accumulation_steps": 8,
"zero_optimization": {
"stage": 3,
"offload_optimizer": {
"device": "cpu",
"pin_memory": true
},
"offload_param": {
"device": "cpu",
"pin_memory": true
},
"overlap_comm": true,
"contiguous_gradients": true,
"sub_group_size": 1000000000,
"reduce_bucket_size": 50000000,
"stage3_prefetch_bucket_size": 45000000,
"stage3_param_persistence_threshold": 100000
},
"fp16": {
"enabled": true,
"loss_scale": 0,
"loss_scale_window": 1000,
"hysteresis": 2,
"min_loss_scale": 1
},
"optimizer": {
"type": "AdamW",
"params": {
"lr": 0.0003,
"betas": [0.9, 0.95],
"eps": 1e-8,
"weight_decay": 0.1
}
},
"scheduler": {
"type": "WarmupLR",
"params": {
"warmup_min_lr": 0,
"warmup_max_lr": 0.0003,
"warmup_num_steps": 2000
}
},
"activation_checkpointing": {
"partition_activations": true,
"cpu_checkpointing": true,
"contiguous_memory_optimization": true
}
}
GPUS_PER_NODE=8
NNODES=4
NNODES_PER_TEAM=2
TP=4 # 张量并行度
PP=2 # 流水线并行度
DP=4 # 数据并行度
DISTRIBUTED_ARGS="--nproc_per_node $GPUS_PER_NODE --nnodes $NNODES"
torchrun pretrain_gpt.py \
--tensor-model-parallel-size $TP \
--pipeline-model-parallel-size $PP \
--num-layers 80 \
--hidden-size 8192 \
--num-attention-heads 64 \
--seq-length 4096 \
--micro-batch-size 2 \
--global-batch-size 256 \
--lr 0.00015 \
--train-iters 100000 \
--bf16 \
--use-flash-attn \
--overlap-grad-reduce \
--overlap-param-gather \
--sequence-parallel \
$DISTRIBUTED_ARGS
| 特性 | PyTorch FSDP | DeepSpeed ZeRO |
|---|---|---|
| ZeRO阶段 | ZeRO-3 | ZeRO-1/2/3 |
| CPU offload | 支持(有限) | 支持(成熟) |
| NVMe offload | 不支持 | 支持 |
| 混合精度 | bf16/fp16 | bf16/fp16 |
| 梯度累积 | 手动 | 内置 |
| 激活检查点 | 手动 | 内置 |
| TP支持 | 不支持 | 通过Megatron |
| PP支持 | 不支持 | 通过Megatron |
| MoE支持 | 不支持 | 支持 |
| 易用性 | PyTorch原生 | 需配置文件 |
import torch
from torch.cuda.amp import autocast, GradScaler
class MixedPrecisionTrainer:
"""混合精度训练 + 梯度累积"""
def __init__(self, model, optimizer, grad_accum_steps=8):
self.model = model
self.optimizer = optimizer
self.grad_accum = grad_accum_steps
self.scaler = GradScaler()
self.step_count = 0
def train_step(self, batch):
# 混合精度前向
with autocast(dtype=torch.bfloat16):
loss = self.model(batch)
loss = loss / self.grad_accum # 缩放损失
# 反向传播 (梯度累积)
self.scaler.scale(loss).backward()
self.step_count += 1
# 累积足够步数后更新
if self.step_count % self.grad_accum == 0:
self.scaler.step(self.optimizer)
self.scaler.update()
self.optimizer.zero_grad()
return loss.item() * self.grad_accum
通信重叠是分布式训练的关键优化:在反向传播过程中,一旦某层梯度计算完成就立即开始AllReduce,与后续层的反向传播重叠执行。
class OverlapCommunication:
"""梯度通信与计算重叠"""
def __init__(self, model):
self.model = model
self.grad_handles = []
# 注册反向hook: 每层梯度就绪即启动AllReduce
for param in model.parameters():
param.register_hook(self._make_grad_hook(param))
def _make_grad_hook(self, param):
def hook(grad):
# 异步启动AllReduce (不阻塞反向传播)
handle = dist.all_reduce(grad, op=dist.ReduceOp.SUM, async_op=True)
self.grad_handles.append(handle)
return grad / dist.get_world_size()
return hook
def wait_all(self):
"""等待所有异步通信完成"""
for handle in self.grad_handles:
handle.wait()
self.grad_handles.clear()
MoE的专家并行使用All-to-All通信,将token路由到对应专家所在GPU。通信量为O(B·S·d),与batch和序列长度成正比。
# EP通信量分析
def ep_comm_cost(batch_size, seq_len, d_model, n_experts, top_k, dtype_bytes=2):
"""专家并行All-to-All通信量"""
# 每个token发送到top_k个专家
# 通信量 ≈ 2 * B * S * d * dtype (发送+接收)
comm = 2 * batch_size * seq_len * d_model * dtype_bytes
return comm / (1024**3) # GB
# 不同配置下的EP通信量
print(f"{'Batch':>6} {'SeqLen':>8} {'d_model':>8} {'EP通信(GB)':>12}")
for B, S, d in [(32, 4096, 4096), (64, 8192, 8192), (128, 16384, 12288)]:
comm = ep_comm_cost(B, S, d, n_experts=64, top_k=8)
print(f"{B:>6} {S:>8} {d:>8} {comm:>11.2f}")
| 模型 | GPU数 | TP | PP | DP | ZeRO | 说明 |
|---|---|---|---|---|---|---|
| 7B | 8 | 1 | 1 | 8 | ZeRO-2 | 单机8卡 |
| 13B | 8 | 2 | 1 | 4 | ZeRO-1 | 单机TP=2 |
| 70B | 64 | 8 | 4 | 2 | ZeRO-1 | 8机×8卡 |
| 175B | 256 | 8 | 8 | 4 | ZeRO-1 | 32机×8卡 |
| 540B | 512 | 8 | 16 | 4 | ZeRO-1 | 64机×8卡 |
| MoE 671B | 256 | 8 | 4 | 8 | ZeRO-1 | +EP=64 |
# 分布式训练监控指标
def training_metrics(model, optimizer, step_time, data_loader):
"""关键训练指标"""
metrics = {}
# MFU (Model FLOPs Utilization)
total_flops = 6 * sum(p.numel() for p in model.parameters()) * data_loader.tokens_per_step
actual_flops = total_flops / step_time
gpu_peak_flops = 312e12 * torch.cuda.device_count() # A100 bf16
metrics["MFU"] = actual_flops / gpu_peak_flops
# 显存使用
metrics["gpu_mem_gb"] = torch.cuda.max_memory_allocated() / (1024**3)
# 通信占比
metrics["comm_time_ratio"] = get_comm_time() / step_time
# 梯度范数
metrics["grad_norm"] = compute_grad_norm(model)
return metrics
# 理想MFU参考
print("理想MFU参考:")
print(" 纯DP: 45-55%")
print(" TP+DP: 40-50%")
print(" 3D并行: 35-45%")
print(" +ZeRO-3: 30-40%")
print(" +CPU offload: 20-30%")
序列并行将序列维度切分到多个GPU上,用于减少长序列训练时的激活显存。Megatron-LM的SP将attention和MLP的输入按序列切分,配合TP使用。
class SequenceParallelAttention(nn.Module):
"""序列并行注意力: 输入按序列维度切分"""
def __init__(self, d_model, n_heads, sp_rank, sp_size):
super().__init__()
self.sp_rank = sp_rank
self.sp_size = sp_size
self.d_model = d_model
self.n_heads = n_heads
self.d_head = d_model // n_heads
self.qkv = nn.Linear(d_model, 3 * d_model)
self.proj = nn.Linear(d_model, d_model)
def forward(self, x_local):
"""x_local: [B, S/SP, d] - 本地序列分片"""
B, S_local, d = x_local.shape
# 1. 计算QKV (各SP rank独立)
qkv = self.qkv(x_local) # [B, S/SP, 3d]
q, k, v = qkv.chunk(3, dim=-1)
# 2. AllGather K, V到完整序列 (通信)
k_full = [None] * self.sp_size
v_full = [None] * self.sp_size
dist.all_gather(k_full, k.contiguous())
dist.all_gather(v_full, v.contiguous())
k_full = torch.cat(k_full, dim=1) # [B, S, d]
v_full = torch.cat(v_full, dim=1)
# 3. 本地Q × 全局K, V
attn = F.scaled_dot_product_attention(q, k_full, v_full)
# 4. 输出投影 (本地)
out = self.proj(attn)
# 5. ReduceScatter输出 (通信)
out_shard = torch.zeros_like(out)
dist.reduce_scatter([out_shard], [out], op=dist.ReduceOp.SUM)
return out_shard
上下文并行用于超长上下文训练(如128K-1M tokens),采用Ring Attention将上下文窗口分片到多个GPU,通过环形通信避免显存爆炸。
class RingAttention(nn.Module):
"""Ring Attention: 上下文并行"""
def __init__(self, d_model, n_heads, cp_rank, cp_size):
self.cp_rank = cp_rank
self.cp_size = cp_size
self.d_head = d_model // n_heads
def forward(self, q_local, k_local, v_local):
"""环形传递KV, 本地计算Q×K×V"""
# q_local: [B, S/CP, d] - 本地Q分片
# k_local, v_local: 本地KV分片
output = torch.zeros_like(q_local)
k_curr, v_curr = k_local.clone(), v_local.clone()
for step in range(self.cp_size):
# 计算本地Q与当前KV的attention
attn = F.scaled_dot_product_attention(
q_local, k_curr, v_curr, is_causal=(step == 0))
output += attn
# 环形传递KV到下一个rank
next_rank = (self.cp_rank + 1) % self.cp_size
prev_rank = (self.cp_rank - 1) % self.cp_size
# 异步发送当前KV, 接收前一个rank的KV
reqs = []
k_recv = torch.zeros_like(k_curr)
v_recv = torch.zeros_like(v_curr)
reqs.append(dist.isend(k_curr, next_rank))
reqs.append(dist.isend(v_curr, next_rank))
reqs.append(dist.irecv(k_recv, prev_rank))
reqs.append(dist.irecv(v_recv, prev_rank))
for r in reqs: r.wait()
k_curr, v_curr = k_recv, v_recv
return output
专家并行的核心通信是All-to-All:前向前将token发送到对应专家所在GPU,计算后再将结果发送回来。两次All-to-All是EP的主要通信开销。
class ExpertParallel:
"""专家并行实现"""
def __init__(self, experts, n_experts, ep_rank, ep_size):
self.ep_rank = ep_rank
self.ep_size = ep_size
self.n_experts = n_experts
# 每个GPU持有 n_experts/ep_size 个专家
self.local_experts = experts[ep_rank::ep_size]
def forward(self, x, routing_weights, assignments):
"""x: [B*S, d], assignments: [B*S, top_k] 专家索引"""
B, d = x.shape
top_k = assignments.shape[1]
# 1. 按目标专家重组token (All-to-All dispatch)
# 每个token发送到其路由专家所在的GPU
dispatch_buffer = torch.zeros(B * top_k, d, device=x.device)
for k in range(top_k):
for e in range(self.n_experts):
mask = (assignments[:, k] == e)
if mask.any():
dispatch_buffer[mask.nonzero().squeeze() + k * B] = x[mask]
# All-to-All: 发送到目标GPU
recv_buffer = torch.zeros_like(dispatch_buffer)
dist.all_to_all_single(recv_buffer, dispatch_buffer)
# 2. 本地专家计算
expert_outputs = torch.zeros_like(recv_buffer)
for i, expert in enumerate(self.local_experts):
expert_outputs[i::len(self.local_experts)] = expert(
recv_buffer[i::len(self.local_experts)])
# 3. All-to-All: 结果送回原GPU (combine)
result = torch.zeros_like(expert_outputs)
dist.all_to_all_single(result, expert_outputs)
# 4. 加权求和
output = torch.zeros(B, d, device=x.device)
for k in range(top_k):
output += routing_weights[:, k].unsqueeze(-1) * result[k*B:(k+1)*B]
return output
大规模MoE通常同时使用EP和TP:EP将专家分配到不同GPU,TP在每个专家内部做张量并行。DeepSeek-V3使用EP=64, TP=8的组合。
def choose_parallel_strategy(n_params, n_gpus, gpu_mem_gb=80, seq_len=4096):
"""自动选择并行策略"""
param_mem = n_params * 2 / (1024**3) # fp16 GB
train_mem = param_mem * 8 # 粗略估计
config = {"TP": 1, "PP": 1, "DP": n_gpus, "ZeRO": 0}
# 小模型: 纯DP + ZeRO
if train_mem < gpu_mem_gb * n_gpus * 0.5:
config["ZeRO"] = 2
# 中等模型: TP + DP + ZeRO
elif param_mem < gpu_mem_gb * 4:
config["TP"] = 2
config["DP"] = n_gpus // 2
config["ZeRO"] = 1
# 大模型: 3D并行
else:
config["TP"] = 8 # 机内TP
config["PP"] = max(1, n_gpus // 64)
config["DP"] = n_gpus // (config["TP"] * config["PP"])
config["ZeRO"] = 1
# 长序列: 加SP
if seq_len > 8192:
config["SP"] = config["TP"]
return config
# 示例
for n, g in [(7e9, 8), (70e9, 64), (175e9, 256)]:
c = choose_parallel_strategy(n, g)
print(f"{n/1e9:.0f}B / {g} GPUs: {c}")
| 问题 | 症状 | 解决方案 |
|---|---|---|
| OOM | CUDA out of memory | 增大ZeRO stage, 减小micro-batch, 激活检查点 |
| 通信瓶颈 | MFU低, 通信占比高 | 增大DP, 减小TP, 通信重叠 |
| 负载不均 | 各GPU利用率差异大 | 调整PP切分, MoE负载均衡 |
| 梯度爆炸 | loss=NaN | 梯度裁剪, 减小lr, bf16替代fp16 |
| 训练发散 | loss震荡不收敛 | 减小lr, 增加warmup, 检查数据 |
| PP气泡大 | 效率低于预期 | 增大micro-batch数, Interleaved PP |
大规模训练经常遇到硬件故障,需要完善的checkpoint机制。除了模型参数和优化器状态,还需保存:训练步数、LR scheduler状态、RNG状态、数据加载位置。
def save_checkpoint(model, optimizer, scheduler, step, path):
"""保存完整训练状态"""
ckpt = {
"model_state": model.state_dict(),
"optimizer_state": optimizer.state_dict(),
"scheduler_state": scheduler.state_dict(),
"step": step,
"rng_state": torch.get_rng_state(),
"cuda_rng_state": torch.cuda.get_rng_state_all(),
"numpy_rng_state": np.random.get_state(),
}
# 分布式: 只rank 0保存
if dist.get_rank() == 0:
torch.save(ckpt, path)
dist.barrier()
def load_checkpoint(model, optimizer, scheduler, path):
"""恢复训练状态"""
ckpt = torch.load(path)
model.load_state_dict(ckpt["model_state"])
optimizer.load_state_dict(ckpt["optimizer_state"])
scheduler.load_state_dict(ckpt["scheduler_state"])
torch.set_rng_state(ckpt["rng_state"])
torch.cuda.set_rng_state_all(ckpt["cuda_rng_state"])
np.random.set_state(ckpt["numpy_rng_state"])
return ckpt["step"]
弹性训练允许在节点故障时自动移除故障节点并继续训练,而不需要从头重启。这需要动态调整world_size、重新分配数据分片和同步优化器状态。
class ElasticTrainer:
"""弹性训练管理器"""
def __init__(self, model, optimizer, min_nodes=4, max_nodes=8):
self.model = model
self.optimizer = optimizer
self.min_nodes = min_nodes
self.max_nodes = max_nodes
self.current_world_size = dist.get_world_size()
def handle_node_failure(self, failed_ranks):
"""处理节点故障"""
# 1. 重新初始化进程组 (排除故障节点)
remaining = set(range(self.current_world_size)) - set(failed_ranks)
if len(remaining) < self.min_nodes:
raise RuntimeError("节点数低于最小要求")
# 2. 重新分配数据分片
self.current_world_size = len(remaining)
# 3. 从最近checkpoint恢复
step = load_checkpoint(self.model, self.optimizer, ...)
# 4. 重新初始化通信
dist.init_process_group(backend="nccl",
world_size=self.current_world_size)
return step
| 指标 | 频率 | 告警阈值 | 说明 |
|---|---|---|---|
| loss | 每步 | NaN或突增10x | 训练健康度 |
| grad_norm | 每步 | >10或NaN | 梯度稳定性 |
| MFU | 每100步 | <30% | GPU利用率 |
| GPU显存 | 每100步 | >95% | OOM风险 |
| 通信占比 | 每100步 | >50% | 通信瓶颈 |
| step时间 | 每步 | 偏差>20% | 性能退化 |
| 层次 | 带宽 | 延迟 | 适用并行 |
|---|---|---|---|
| NVLink (机内) | 600 GB/s | ~1μs | TP, ZeRO-3 |
| IB (机间) | 100-200 GB/s | ~5μs | PP, DP |
| 跨交换机 | 50-100 GB/s | ~10μs | DP |
| 跨Pod | 25-50 GB/s | ~20μs | DP (尽量避免) |
分布式训练的并行策略应与物理网络拓扑匹配:通信量最大的并行维度放在带宽最高的网络层次(机内NVLink),通信量最小的放在跨机网络。
# 拓扑感知的并行分配
def topology_aware_placement(tp, pp, dp, gpus_per_node=8):
"""将并行维度映射到网络层次"""
# TP: 通信最频繁 → 机内NVLink
assert tp <= gpus_per_node, "TP应≤机内GPU数"
# PP: 通信量中等 → 相邻机间IB
# DP: 通信量与TP相当但可重叠 → 跨机IB
nodes_needed = pp * dp
print(f"配置: {nodes_needed}机 × {gpus_per_node}卡 = {nodes_needed*gpus_per_node}GPU")
print(f" TP={tp} (机内NVLink)")
print(f" PP={pp} (机间IB, 相邻)")
print(f" DP={dp} (机间IB, AllReduce)")
return nodes_needed * gpus_per_node
topology_aware_placement(tp=8, pp=4, dp=2)