分布式训练与效率
一个 7B 模型光是"能训起来"就需要大约 112 GB 的显存,单卡 80 GB 装不下。这一章讲清楚三件事:显存都花在哪里,各种并行方式各自切的是什么、付出什么通信代价,以及怎么用 MFU 判断一次训练跑得好不好。面试里这部分几乎都是"白板估算题",能现场算出数字的人会明显加分。
建议顺序:§1 显存 → §2 通信原语(后面所有并行的"货币")→ §3 数据并行/ZeRO(最常考)→ §4 TP → §5 PP → §6 其他并行与整体布局 → §7 省显存技巧 → §8 MFU → §10 场景题和 §11 练习(一定要自己动笔算)。
和其他模块的关系:参数量与 6ND 的推导在 模块 04;bf16/fp16 的位布局和 GradScaler 在 模块 01 §8;KV cache、推理时的 TP 和带宽瓶颈在 模块 08;FlashAttention 的算法细节在 模块 04 §8。本章对研究岗来说是"☆ 应该会":面试官通常不要求你写 NCCL 代码,但会要求你对数字有感觉。
\(\Psi\) 或 \(N\):参数量;\(N_d\)(或直接写"DP 大小"):数据并行组的 GPU 数;\(t\):tensor parallel 大小;\(p\):pipeline stage 数;\(m\):每个 step 的 micro-batch 数;\(s\):序列长度;\(b\):micro-batch 大小(每个 micro-batch 的序列数);\(h\) 或 \(d\):hidden size;\(a\):attention head 数;\(L\):层数。显存单位 GB 按 \(10^9\) 字节算(面试里足够精确)。硬件数字(NVLink、InfiniBand、峰值 FLOPs)都是近似值,用来做数量级估算。
§1 · MEMORY ANATOMY显存都花在哪里
所有并行方案的出发点都是"一张卡装不下"或"一张卡太慢"。所以第一步是把训练时的显存拆开:哪些和参数量成正比(model states),哪些和 batch×序列长度成正比(activations),哪些是杂项(临时 buffer、通信 buffer、碎片)。这一节是后面所有估算题的基础。
训练显存的四大块
训练显存 = model states(参数 + 梯度 + 优化器状态,和参数量成正比)+ activations(为反向传播保存的中间结果,和 batch×seq×hidden×层数成正比)+ 临时 buffer + 碎片。
Training memory = model states (params, grads, optimizer states — proportional to parameter count) + activations saved for backward (proportional to batch × sequence × hidden × layers) + temporary buffers + fragmentation.
把一张 GPU 上的显存想成四个桶:
| 桶 | 内容 | 和什么成正比 | 典型对策 |
|---|---|---|---|
| Parameters | 模型权重(bf16 一份用于计算;混合精度下还有一份 fp32 master copy,通常算进优化器状态) | \(\Psi\) | ZeRO-3/FSDP、TP、PP 切分 |
| Gradients | 每个参数一个梯度 | \(\Psi\) | ZeRO-2/3 切分 |
| Optimizer states | Adam 的一阶矩 \(m\)、二阶矩 \(v\)(fp32),加上 fp32 master weights | \(\Psi\),而且系数最大 | ZeRO-1 切分、CPU offload、8-bit 优化器 |
| Activations | 前向时为反向保存的张量:每个 Linear 的输入、softmax 输出、GeLU 输入、LayerNorm 输入、dropout mask…… | \(s\cdot b\cdot h\cdot L\)(标准 attention 还有 \(a\cdot s^2\cdot b\cdot L\) 项) | activation checkpointing、Sequence/Context Parallel、FlashAttention、减小 micro-batch |
| 其他 | 通信 buffer(DDP bucket、FSDP all-gather 后的完整层参数)、cuBLAS workspace、logits(\(s\times V\) 可能很大)、CUDA context(约几百 MB)、allocator 碎片 | 杂 | chunked loss、expandable_segments、减少碎片 |
还有一个容易忽略的"大户":logits。词表 \(V=128{,}256\)(LLaMA-3 的词表大小)、序列 32k 时,单条序列的 fp32 logits 是 \(32768\times128256\times4 \approx 16.8\) GB,比很多层的 activation 还大。所以长序列训练常用 chunked / fused cross-entropy,不一次性 materialize 全部 logits。
I usually split training memory into model states and activations. Model states are the parameters, gradients and optimizer states, and they scale only with the parameter count. Activations are whatever the forward pass saves for backward, and they scale with batch size, sequence length, hidden size and depth. That split tells me which tool to reach for: sharding like ZeRO or FSDP for model states, and checkpointing or sequence parallelism for activations. I also keep an eye on the logits, since a large vocabulary at long context can take several gigabytes by itself.
- Why does PyTorch sometimes OOM even when "allocated" memory is well below capacity?
思路
碎片(fragmentation)。PyTorch 的 caching allocator 把显存切成块缓存起来;变长序列导致不同大小的张量反复申请释放,空闲块可能很多但都不够大。看torch.cuda.memory_summary()里 reserved 和 allocated 的差值。对策:PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True、固定 shape(padding 到桶长度)、减少临时大张量。 - What else besides params/grads/optimizer/activations shows up in nvidia-smi?
思路
CUDA context(每个进程几百 MB)、NCCL 通信 buffer、cuBLAS/cuDNN workspace、caching allocator 已保留但未使用的块。所以估算时要留 10–20% 余量。
混合精度 Adam:每个参数 16 字节
bf16 参数 2 B + bf16 梯度 2 B + fp32 master 参数 4 B + fp32 Adam m 4 B + fp32 Adam v 4 B = 16 B/参数,所以 7B 模型光 model states 就要 112 GB。
Mixed-precision Adam costs 16 bytes per parameter: 2 for bf16 weights, 2 for bf16 grads, and 12 for the fp32 master weights plus Adam's two moments — so a 7B model needs about 112 GB before any activations.
推导。混合精度训练的约定(来自 Micikevicius et al. 2017, Mixed Precision Training,ZeRO 论文沿用同样的记账):
- 前向和反向用低精度(fp16/bf16)的权重计算:2 字节/参数。
- 反向得到低精度梯度:2 字节/参数。
- 为了让很小的更新量 \(\eta\cdot\Delta\) 不在低精度下被舍入掉,保留一份 fp32 master weights:4 字节。
- Adam 的一阶矩 \(m\) 和二阶矩 \(v\),都用 fp32:4 + 4 = 8 字节。
ZeRO 论文把优化器部分记为 \(K\cdot\Psi\),Adam 时 \(K=12\),总共 \((2+2+K)\Psi = 16\Psi\)。
| 模型 | bf16 权重(推理) | 训练 model states (16Ψ) |
|---|---|---|
| 1.3B | 2.6 GB | 20.8 GB |
| 7B | 14 GB | 112 GB |
| 13B | 26 GB | 208 GB |
| 70B | 140 GB | 1120 GB |
| 405B | 810 GB | 6480 GB |
变体(面试时主动说出来会加分):
- 有些实现把梯度累加在 fp32 里(梯度累积时更稳),那就是 2+4+12 = 18 B/参数。
- 纯 bf16 训练(不保留 fp32 master,配合 stochastic rounding 或 Kahan summation)可以降到 2+2+4+4 = 12 甚至更少,但有精度风险。
- SGD with momentum:K = 4(master)+ 4(momentum)= 8,总 12 B。不带 master 的纯 fp32 Adam:4+4+4+4 = 16 B(巧合地也是 16)。
- 8-bit Adam(bitsandbytes)把 m、v 量化到 1 字节,K 从 12 降到约 6。
为什么 fp32 master weights 是必要的
bf16 只有 8 位有效数字位(7 位尾数 + 隐含 1),相对精度约 \(2^{-8}\approx 0.4\%\)。如果权重 \(w\approx 1\)、单步更新 \(\eta\cdot\Delta \approx 10^{-5}\),那么 \(w+\eta\Delta\) 在 bf16 下直接舍入回 \(w\),更新被吃掉了。几千步累积下来,模型几乎不动。fp32 有 24 位有效数字,相对精度约 \(6\times10^{-8}\),能把这些小更新累积起来。流程是:fp32 master 更新 → 拷一份 cast 成 bf16 → 下一步前向用 bf16。
fp16 还有另一个问题:指数位只有 5 位,小梯度会下溢成 0,所以需要 loss scaling(GradScaler)。bf16 指数位和 fp32 一样是 8 位,动态范围够,所以一般不需要 loss scaling,但 master weights 仍然需要。详见 模块 01 §8。
model.parameters() 本身仍是 fp32(PyTorch AMP 下参数就是 master weights,此时是 4(fp32 参数)+4(fp32 梯度)+8(m,v)= 16 B,外加 autocast 时临时的 bf16 权重拷贝)。The standard accounting is sixteen bytes per parameter for mixed-precision Adam. You have two bytes each for the bf16 weights and gradients, and then twelve bytes of fp32 state: a master copy of the weights, plus Adam's first and second moments. The master copy matters because tiny updates would just round away in bf16. So a 7B model needs about 112 gigabytes for model states alone, which is why you can't train it on a single 80-gigabyte GPU without sharding or offloading.
- How much memory do you need to fine-tune a 7B model with LoRA instead?
思路
冻结的基座只需 bf16 权重 14 GB(不需要梯度和优化器状态);LoRA 参数通常只占 0.1–1%,按 16 B/参数算也就几百 MB。再加 activations(注意:即使基座冻结,反向仍要穿过基座计算对 LoRA 参数的梯度,所以 activations 不能省)。QLoRA 把基座量化到 4-bit,约 3.5 GB。 - Where does the 16-bytes number break down?
思路
fp32 梯度累积(18 B);不同优化器(Adafactor 分解二阶矩,几乎不占;Muon 只有 momentum);FP8 训练仍然保留高精度 master weights 和优化器状态,所以 model states 基本不变,省的主要是计算和部分激活。
Activation 显存:每层 \(sbh(34 + 5as/h)\)
按 Korthikanti et al. 的记账(fp16/bf16、标准 attention、带 dropout),一个 Transformer 层的 activation 是 \(34\,sbh + 5\,as^2b\) 字节:第一项随序列线性增长,第二项(attention 分数矩阵)随序列平方增长。
Per layer, activations take about 34·s·b·h bytes plus 5·a·s²·b bytes for the attention matrices; the first term is linear in sequence length, the second quadratic.
来源:Korthikanti et al. 2022, Reducing Activation Recomputation in Large Transformer Models(NVIDIA,Megatron 的 sequence parallelism 和 selective recomputation 就出自这篇)。假设 activations 用 2 字节,dropout mask 用 1 字节。逐项数一个标准 GPT 层(attention + MLP,4h 中间维度):
| 位置 | 保存的张量 | 字节 |
|---|---|---|
| Attention | QKV 投影的输入 \(X\) | \(2sbh\) |
| \(QK^\top\) 需要的 Q、K | \(4sbh\) | |
| softmax 输出(\(a\) 个 \(s\times s\) 矩阵) | \(2as^2b\) | |
| attention dropout mask | \(as^2b\) | |
| dropout 后的分数(乘 V 用)+ V | \(2as^2b + 2sbh\) | |
| 输出投影的输入 + 输出 dropout mask | \(2sbh + sbh\) | |
| 小计 | \(11sbh + 5as^2b\) | |
| MLP | 第一个 Linear 的输入 | \(2sbh\) |
| GeLU 的输入(4h 宽) | \(8sbh\) | |
| 第二个 Linear 的输入(4h 宽) | \(8sbh\) | |
| dropout mask | \(sbh\) | |
| 小计 | \(19sbh\) | |
| LayerNorm ×2 | 各自的输入 | \(4sbh\) |
| 每层合计 | \(34sbh + 5as^2b = sbh\left(34+\dfrac{5as}{h}\right)\) | |
论文里的几个变体(都是每层、字节):
| 配置 | 每层 activation |
|---|---|
| 无并行 | \(sbh(34 + 5as/h)\) |
| Tensor parallel(大小 \(t\)) | \(sbh(10 + 24/t + 5as/(ht))\) |
| TP + Sequence parallel | \(sbh(34/t + 5as/(ht))\) |
| TP + selective recompute | \(sbh(10 + 24/t)\) |
| TP + SP + selective recompute | \(sbh \cdot 34/t\) |
| Full recompute(只存每层输入) | \(2sbh\)(SP 下再除以 \(t\)) |
TP 下的 "10" 来自没被 TP 切开的部分:两个 LayerNorm 的输入(4sbh)、attention 和 MLP 输出的 dropout mask(2sbh)、QKV 和 MLP 第一层的输入 X(2sbh + 2sbh,因为这两个 Linear 的输入在每个 TP rank 上都是完整复制的)。Sequence parallel 把这 10 也沿序列维切开,所以变成 34/t。
算一个数字感:LLaMA-2-7B 尺寸(\(h=4096,\ a=32,\ L=32\)),\(s=4096,\ b=1\):
- \(34sbh = 34\times4096\times4096 \approx 0.57\) GB;\(5as^2b = 5\times32\times4096^2 \approx 2.68\) GB。每层约 3.26 GB,32 层约 104 GB。比 model states 还大!
- 如果 attention 分数不存(selective recompute 或 FlashAttention),每层只剩约 0.57 GB,32 层约 18 GB。
- \(s=32\text{k}\) 时,平方项每层约 172 GB,完全不可能——这就是长上下文训练必须用 FlashAttention 的原因。
现代 LLM 和这个公式的差异:(1) 大多数 LLM 预训练不用 dropout,去掉 mask 项;(2) FlashAttention 只额外保存每行的 logsumexp(\(O(asb)\)),平方项消失;(3) SwiGLU MLP 有三个矩阵、中间维 \(\approx 8h/3\),MLP 项的系数会变;(4) GQA 让 K、V 更小。所以面试时说"用 Korthikanti 的公式作为数量级,现代配置大约是每层 \(\approx 30\text{–}40\,sbh\) 字节"就足够了。
A useful reference is the Megatron accounting from Korthikanti and colleagues: each transformer layer stores about 34·s·b·h bytes of activations, plus 5·a·s²·b bytes for the attention scores and softmax. The quadratic term starts to dominate once the sequence is longer than roughly seven times the head dimension, so at 4k context it's actually the largest piece. FlashAttention removes that term because it never materializes the score matrix. After that, you're left with something linear in sequence length, which sequence parallelism or checkpointing can cut further.
- If you double the sequence length and halve the micro-batch, what happens to activation memory?
思路
线性项 \(34sbh\) 不变(\(s\cdot b\) 不变);平方项 \(5as^2b\) 翻倍(\(s^2 b\) 翻倍)。用 FlashAttention 时基本不变。tokens per micro-batch 相同,但 attention FLOPs 会翻倍。 - Why is activation memory not divided by the data-parallel degree?
思路
DP 是每个 rank 处理不同的样本,每个 rank 都有自己完整的 activation(对应自己的 micro-batch)。只有沿 \(s\)、\(h\) 或层维度切分的并行(SP/CP/TP/PP)才减少每卡 activation。ZeRO 也不切 activation(ZeRO-R 的 partitioned activation checkpointing 是例外,用在 MP 场景)。
估算流程:一张白板就能算的显存预算
先算 model states(16Ψ ÷ 切分份数),再算 activations(每层 × 层数 × 同时在飞的 micro-batch 数 ÷ 序列/张量切分),加上临时 buffer 和 10–20% 余量,和单卡显存比较。
Budget memory as model states divided by the sharding factor, plus per-layer activations times layers times in-flight micro-batches divided by sequence or tensor sharding, plus buffers and a safety margin.
面试里的标准步骤(建议背下来,按顺序说):
- Model states:\(16\Psi\)。如果 ZeRO-3/FSDP 切在 \(N_d\) 张卡上,变成 \(16\Psi/N_d\);TP×PP 切在 \(t\cdot p\) 张卡上,每卡是 \(16\Psi/(tp)\);两者叠加时再除以 ZeRO 的份数。
- Activations:每层 \(\approx sbh(34 + 5as/h)\)(FlashAttention 时去掉平方项);乘以本卡上的层数 \(L/p\);乘以同时在飞的 micro-batch 数(PP 下最多约 \(p\));TP+SP 时除以 \(t\);CP 时 \(s\) 换成 \(s/\text{cp}\);checkpointing 时换成每层 \(2sbh\) 加一层的完整工作集。
- 临时项:ZeRO-3 时 all-gather 出来的完整层参数(每层 \(2\Psi/L\) 字节,prefetch 时 ×2);logits \(s\cdot b\cdot V\cdot\)(2 或 4)字节;通信 bucket。
- 余量:留 10–20% 给碎片和 CUDA context。
本章 §9 的计算器代码和 §10/§11 的场景题都按这个流程做。
这个流程的计算器(已运行)
# Memory / pipeline / MFU calculators (pure Python)
GB = 1e9
def zero_mem_per_gpu(n_params, n_gpus, stage, k_opt=12):
"""Mixed-precision Adam: 2 B bf16 params + 2 B bf16 grads + k_opt (=12: fp32 master+m+v) per param.
stage 0 = plain DDP, 1 = shard opt states, 2 = + grads, 3 = + params. Returns bytes (model states only)."""
p, g, o = 2 * n_params, 2 * n_params, k_opt * n_params
if stage >= 1: o /= n_gpus
if stage >= 2: g /= n_gpus
if stage >= 3: p /= n_gpus
return p + g + o
def act_mem_per_layer(s, b, h, a, t=1, sp=False, selective=False):
"""Korthikanti et al. 2022, bytes per transformer layer (fp16/bf16 activations)."""
attn = 0 if selective else 5 * a * s / (h * t)
if sp:
return s * b * h * (34 / t + attn)
return s * b * h * (10 + 24 / t + attn)
def bubble_fraction(p, m, v=1):
"""fraction of time idle in GPipe/1F1B; interleaved with v chunks per device."""
return (p - 1) / (v * m + p - 1)
def mfu(n_params, tokens_per_sec, n_gpus, peak_flops, n_layers=None, seq=None, d=None):
flops_per_token = 6 * n_params
if n_layers: # optional attention term 12*L*s*d (PaLM-style, no causal halving)
flops_per_token += 12 * n_layers * seq * d
return flops_per_token * tokens_per_sec / (n_gpus * peak_flops)
if __name__ == "__main__":
N = 7e9
print("7B DDP model states:", zero_mem_per_gpu(N, 1, 0) / GB, "GB")
assert abs(zero_mem_per_gpu(N, 1, 0) / GB - 112) < 1e-9
for st in range(4):
print(f"7B, 64 GPUs, ZeRO-{st}: {zero_mem_per_gpu(N, 64, st)/GB:.2f} GB")
# 13B on 32 GPUs ZeRO-3
z3 = zero_mem_per_gpu(13e9, 32, 3) / GB
print(f"13B ZeRO-3 on 32 GPUs: {z3:.2f} GB"); assert abs(z3 - 6.5) < 1e-9
# 70B on 64 GPUs ZeRO-3
print(f"70B ZeRO-3 on 64 GPUs: {zero_mem_per_gpu(70e9, 64, 3)/GB:.2f} GB")
# Activation memory: LLaMA-2-7B like layer, s=4096,b=1,h=4096,a=32
s, b, h, a, L = 4096, 1, 4096, 32, 32
full = act_mem_per_layer(s, b, h, a)
sel = act_mem_per_layer(s, b, h, a, selective=True)
print(f"act/layer no-par: {full/GB:.3f} GB ; x{L} layers = {full*L/GB:.1f} GB")
print(f"act/layer selective: {sel/GB:.3f} GB ; x{L} = {sel*L/GB:.1f} GB")
print(f"act/layer t=8 sp selective: {act_mem_per_layer(s,b,h,a,t=8,sp=True,selective=True)/GB:.4f} GB")
s2 = 32768
print(f"s=32k act/layer no-par: {act_mem_per_layer(s2,1,h,a)/GB:.2f} GB; x32 = {act_mem_per_layer(s2,1,h,a)*32/GB:.0f} GB")
print(f"s=32k selective x32: {act_mem_per_layer(s2,1,h,a,selective=True)*32/GB:.1f} GB")
# full checkpointing: store only layer input 2sbh per layer
print(f"s=32k full ckpt inputs x32: {2*s2*h*32/GB:.1f} GB")
for p, m in [(4, 4), (4, 16), (8, 32), (16, 64)]:
print(f"bubble p={p} m={m}: {bubble_fraction(p,m):.3f}")
print(f"interleaved p=8 m=32 v=4: {bubble_fraction(8,32,4):.4f}")
assert abs(bubble_fraction(4, 4) - 3/7) < 1e-12
# MFU worked examples (H100 bf16 dense peak ~989 TFLOPs, A100 ~312 TFLOPs)
r = mfu(7e9, 8 * 3500, 8, 989e12)
print(f"MFU 7B, 3500 tok/s/GPU on H100: {r:.3f}")
r2 = mfu(70e9, 400, 1, 312e12)
print(f"MFU 70B, 400 tok/s/GPU on A100: {r2:.3f}")
# Llama-3 405B check: 400 TFLOPs/GPU / 989 = ?
print("Llama3 400/989 =", 400/989)
print("calc OK")
运行输出(节选):7B DDP model states 112.0 GB;7B 在 64 卡上 ZeRO-0/1/2/3 分别是 112.00 / 29.31 / 15.53 / 1.75 GB;13B ZeRO-3 在 32 卡上 6.50 GB;LLaMA-2-7B 尺寸、\(s=4096\) 每层 activation 3.255 GB(selective 0.570 GB);\(s=32\text{k}\) 时 full checkpointing 只存每层输入,32 层共 8.6 GB;bubble \(p=4,m=4\) 为 0.429。
When I estimate memory, I go in a fixed order. First, model states: sixteen bytes per parameter, divided by however many ways they're sharded. Next, activations: per-layer cost times the layers on this GPU, times the number of micro-batches in flight, divided by any sequence or tensor sharding. Then I add temporaries like gathered parameters or logits. Finally I keep ten to twenty percent headroom, because fragmentation and the CUDA context take a real share.
§2 · COLLECTIVES通信原语
所有并行方式最后都落到几种集合通信(collective)上。把它们的语义和代价记住,后面每种并行的通信量都可以直接"组合"出来:DDP = all-reduce;ZeRO = reduce-scatter + all-gather;TP = all-reduce(或 SP 下的 RS + AG);PP = 点对点 send/recv;EP = all-to-all;Ulysses = all-to-all;Ring Attention = 环形点对点。
六种集合通信
broadcast(一发全)、reduce(全归约到一)、all-reduce(全归约后人人有)、reduce-scatter(归约后每人拿一片)、all-gather(每人一片拼成完整的人人有)、all-to-all(每人把第 j 片发给第 j 人,相当于转置)。
Broadcast sends one rank's data to all; reduce sums to one rank; all-reduce sums and gives everyone the result; reduce-scatter sums and gives each rank one shard; all-gather concatenates shards onto every rank; all-to-all is a distributed transpose.
设 \(N\) 个 rank,每个 rank 上有一个向量 \(x_r\),把它切成 \(N\) 片:\(x_r = [x_r^{(0)}, \dots, x_r^{(N-1)}]\)。
| 原语 | 之前 | 之后(rank \(r\) 上) | 每卡发送量(带宽最优算法) | 在哪里用 |
|---|---|---|---|---|
| Broadcast | rank 0 有 \(x\) | \(x\) | \(\approx S\) | DDP 初始化同步权重 |
| Reduce | 各有 \(x_r\) | rank 0 得到 \(\sum_r x_r\) | \(\approx S\) | 汇总 metric |
| All-reduce | 各有 \(x_r\) | \(\sum_r x_r\) | \(2\frac{N-1}{N}S\) | DDP 梯度、TP 的部分和 |
| Reduce-scatter | 各有 \(x_r\) | \(\sum_{r'} x_{r'}^{(r)}\)(只有第 \(r\) 片) | \(\frac{N-1}{N}S\) | ZeRO-2/3、FSDP 梯度;SP |
| All-gather | 各有一片 \(y^{(r)}\) | \([y^{(0)},\dots,y^{(N-1)}]\) | \(\frac{N-1}{N}S\) | ZeRO-3/FSDP 取参数;SP;CP 取 KV |
| All-to-all | 各有 \(x_r\) | \([x_0^{(r)}, x_1^{(r)},\dots]\) | \(\frac{N-1}{N}S\) | MoE expert parallel、Ulysses |
(\(S\) 是每个 rank 上完整数据的字节数;all-gather 时 \(S\) 指拼好后的大小。)
最重要的恒等式:
$$\text{all-reduce} = \text{reduce-scatter} + \text{all-gather}$$先 reduce-scatter:每个 rank 拿到第 \(r\) 片的总和;再 all-gather:把各片的总和拼起来发给所有人。两步各 \(\frac{N-1}{N}S\),合计 \(2\frac{N-1}{N}S\)。这就是 ZeRO 能"免费"切分优化器状态的关键:DDP 本来就要做 all-reduce,ZeRO 只是把它拆成两半,在中间插入"只更新自己那一片参数"这一步。
点对点(send/recv):pipeline parallel 在相邻 stage 间传 activation(前向)和 activation 的梯度(反向)。每个 micro-batch 每次 \(2sbh\) 字节,量小,对带宽要求低,所以 PP 适合跨节点。
用 torch.distributed 验证 all-reduce = RS + AG(参考代码,需 torch)
# all-reduce == reduce-scatter + all-gather, checked with real torch.distributed collectives on CPU (gloo).
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def worker(rank, world_size):
os.environ["MASTER_ADDR"] = "127.0.0.1"
os.environ["MASTER_PORT"] = "29512"
dist.init_process_group("gloo", rank=rank, world_size=world_size)
x = torch.arange(8, dtype=torch.float32) + 10 * rank # each rank holds a different vector
ar = x.clone()
dist.all_reduce(ar, op=dist.ReduceOp.SUM) # every rank gets the sum
# reduce-scatter (via all_to_all + local sum, since gloo lacks reduce_scatter_tensor)
chunks = list(x.clone().chunk(world_size))
recv = [torch.empty_like(c) for c in chunks]
dist.all_to_all(recv, chunks) # recv[j] = rank j's chunk number `rank`
my_shard = torch.stack(recv).sum(0) # = sum over ranks of chunk `rank`
gathered = [torch.empty_like(my_shard) for _ in range(world_size)]
dist.all_gather(gathered, my_shard) # all-gather the reduced shards
assert torch.equal(torch.cat(gathered), ar)
dist.destroy_process_group()
if __name__ == "__main__":
mp.spawn(worker, args=(2,), nprocs=2, join=True)
print("collectives OK")
说明:这段在 CPU 上用 gloo 后端起 2 个进程。本环境没有 torch,未实际运行;同样的逻辑已用 numpy 的 ring all-reduce 模拟验证(见 §9)。文件保存在 torch_tests/02_collectives_gloo.py。
The key collectives are all-reduce, reduce-scatter, all-gather and all-to-all. All-reduce leaves the full sum on every rank. Reduce-scatter leaves each rank with one summed shard, and all-gather puts the shards back together everywhere. All-reduce is exactly a reduce-scatter followed by an all-gather, and that identity is the whole trick behind ZeRO. All-to-all is a distributed transpose, which is why mixture-of-experts dispatch and Ulysses-style sequence parallelism use it.
- Which collective does each parallelism strategy use?
思路
DDP:梯度 all-reduce。ZeRO-1/2:梯度 reduce-scatter + 参数 all-gather。ZeRO-3/FSDP:前向 all-gather 参数、反向再 all-gather 参数、梯度 reduce-scatter。TP:每个 attention/MLP 块前向一次 all-reduce(SP 下换成 AG + RS)。PP:相邻 stage send/recv。EP:dispatch 和 combine 两次 all-to-all。CP:ring attention 用环形 send/recv 传 KV,或用 all-gather KV(LLaMA-3);Ulysses 用 all-to-all。
Ring all-reduce 与 \(2(N-1)/N\) 的推导
把数据切成 N 片,沿环做 N−1 步 reduce-scatter,再做 N−1 步 all-gather;每步每卡只发 S/N,总共每卡发送 \(2(N-1)S/N\),几乎和 N 无关,是带宽最优的。
Ring all-reduce does N−1 reduce-scatter steps and N−1 all-gather steps, each sending S/N per GPU, so each GPU sends 2(N−1)/N·S in total — essentially independent of N and bandwidth-optimal.
设定:\(N\) 张卡排成环,卡 \(r\) 只给卡 \(r+1\) 发,只从卡 \(r-1\) 收。每张卡有大小为 \(S\) 字节的向量,切成 \(N\) 片,每片 \(S/N\)。
阶段 1:reduce-scatter(\(N-1\) 步)。第 \(k\) 步(\(k=0,\dots,N-2\)),卡 \(r\) 把它的第 \((r-k)\bmod N\) 片发给卡 \(r+1\),卡 \(r+1\) 把收到的片加到自己对应的片上。每一片沿着环走一圈少一站,每过一站累加一个 rank 的贡献,走了 \(N-1\) 站之后就累加了全部 \(N\) 个 rank。结束时卡 \(r\) 拥有第 \((r+1)\bmod N\) 片的完整总和。
阶段 2:all-gather(\(N-1\) 步)。每张卡把自己拥有的"完整片"沿环传下去,接收方直接覆盖(不再求和)。\(N-1\) 步后每张卡拥有全部 \(N\) 片的总和。
通信量:每步每卡发 \(S/N\),共 \(2(N-1)\) 步:
$$\text{bytes sent per GPU} = 2(N-1)\cdot\frac{S}{N} = 2\frac{N-1}{N}S \;\xrightarrow{N\to\infty}\; 2S$$时间模型(α-β 模型):每次发送有固定延迟 \(\alpha\),每字节耗时 \(1/B\)(\(B\) 为每卡链路带宽):
$$T_{\text{ring}} \approx 2(N-1)\,\alpha + 2\frac{N-1}{N}\cdot\frac{S}{B}$$为什么是带宽最优:每个 rank 的数据都必须到达其他所有人,每个 rank 也必须收到其他人对每一片的贡献。下界论证:每张卡至少要收到 \(\frac{N-1}{N}S\) 字节来完成它那片的归约,再收到 \(\frac{N-1}{N}S\) 字节拿到其他片的结果,所以 \(2\frac{N-1}{N}S\) 是下界,ring 恰好达到。
nccl-tests 里的 "busbw":nccl-tests 报两个数,algbw = \(S/T\),busbw = algbw × \(2(N-1)/N\)(all-reduce 的情况)。busbw 衡量的是"链路实际跑了多少带宽",可以直接和硬件链路带宽比较。面试里提到这个说明你真的跑过 benchmark。
numpy 模拟:N 个 worker 的 ring all-reduce == 求和(已运行)
import numpy as np
def ring_all_reduce(xs):
"""xs: list of N equal-length 1-D arrays (one per worker). Returns list of results and bytes sent per worker."""
N = len(xs)
bufs = [np.array_split(x.astype(np.float64).copy(), N) for x in xs] # bufs[r][c]
sent = [0] * N
# Phase 1: reduce-scatter. step k: worker r sends chunk (r - k) % N to r+1
for k in range(N - 1):
msgs = []
for r in range(N):
c = (r - k) % N
msgs.append((r, (r + 1) % N, c, bufs[r][c].copy()))
for src, dst, c, data in msgs: # all sends happen "simultaneously"
bufs[dst][c] += data
sent[src] += data.nbytes
# now worker r owns the fully reduced chunk (r + 1) % N
# Phase 2: all-gather. step k: worker r sends chunk (r + 1 - k) % N to r+1
for k in range(N - 1):
msgs = []
for r in range(N):
c = (r + 1 - k) % N
msgs.append((r, (r + 1) % N, c, bufs[r][c].copy()))
for src, dst, c, data in msgs:
bufs[dst][c] = data
sent[src] += data.nbytes
return [np.concatenate(b) for b in bufs], sent
rng = np.random.default_rng(0)
for N in [2, 3, 4, 8]:
D = 1000 * N
xs = [rng.standard_normal(D) for _ in range(N)]
out, sent = ring_all_reduce(xs)
ref = np.sum(xs, axis=0)
for o in out:
assert np.allclose(o, ref)
size = xs[0].astype(np.float64).nbytes
print(f"N={N}: bytes sent per worker = {sent[0]}, theory 2(N-1)/N*size = {2*(N-1)/N*size:.0f}")
assert all(s == 2 * (N - 1) * size // N for s in sent)
print("ring all-reduce OK")
输出:N=2/3/4/8 时,每卡发送字节数都恰好等于 \(2(N-1)/N\cdot S\)(例如 N=8、S=64 KB 时为 112000 字节),且所有 worker 结果都等于 np.sum。
In a ring all-reduce, you split the buffer into N chunks and pass them around the ring. During the first N minus one steps you add as you go, which is the reduce-scatter. After that, each GPU owns one fully reduced chunk, and in the next N minus one steps you just forward those chunks, which is the all-gather. Each step sends S over N bytes, so each GPU sends two times N-minus-one over N times S in total. That's essentially 2S no matter how many GPUs you have, and it matches the lower bound. The catch is the latency term, which grows linearly with N, so for small messages NCCL switches to tree algorithms.
- How long does it take to all-reduce 14 GB of gradients on 8 GPUs with NVLink, versus 64 GPUs over InfiniBand?
思路
8 卡、单向约 450 GB/s:\(2\cdot\frac78\cdot14/450\approx 54\) ms。64 卡、瓶颈链路为 IB 约 50 GB/s/GPU:\(2\cdot\frac{63}{64}\cdot14/50 \approx 0.55\) s。实际 NCCL 会用分层算法(节点内先 reduce-scatter,跨节点再 all-reduce,节点内 all-gather),跨节点只传 \(1/8\) 的数据,所以会比这个更快;这个数量级对比本身就是答案的要点。 - What's the difference between ring and tree all-reduce?
思路
ring:带宽最优,延迟 \(O(N\alpha)\)。tree(NCCL 用 double binary tree):延迟 \(O(\log N\cdot\alpha)\),带宽项也接近最优。大消息、卡少用 ring;小消息或超大规模用 tree。NCCL 根据消息大小和拓扑自动选择。
带宽 vs 延迟;NVLink vs InfiniBand;拓扑决定并行布局
节点内 NVLink 每卡约数百 GB/s,跨节点 InfiniBand 每卡约几十 GB/s,差约一个数量级;所以通信最频繁、在关键路径上的并行(TP)放节点内,通信少或可重叠的(PP、DP)放跨节点。
Intra-node NVLink gives each GPU hundreds of GB/s while inter-node InfiniBand gives tens, roughly a 10× gap, so the chattiest, latency-critical parallelism (tensor parallel) stays inside a node and pipeline and data parallelism span nodes.
近似硬件数字(用于数量级估算,具体以厂商文档为准):
| 链路 | 每 GPU 带宽(近似) | 备注 |
|---|---|---|
| NVLink 3 (A100) | 600 GB/s 双向合计(约 300 GB/s 单向) | 节点内 8 卡通过 NVSwitch 全互联 |
| NVLink 4 (H100 SXM) | 900 GB/s 双向合计(约 450 GB/s 单向) | 同上 |
| InfiniBand NDR | 400 Gb/s ≈ 50 GB/s 单向(每卡一张 NIC 的典型配置) | 跨节点 |
| PCIe Gen5 x16 | 约 64 GB/s 单向 | CPU↔GPU,offload 的瓶颈 |
| HBM3 (H100) | 约 3.35 TB/s | 显存带宽,对比用 |
α-β 模型:一次消息耗时 \(T = \alpha + S/B\)。\(\alpha\)(启动延迟)是微秒级。消息越小,延迟占比越大,所以 DDP 要把梯度攒成 bucket 再发,而不是每个参数单独发。
拓扑 → 布局的原则:
- TP:每层 4 次 all-reduce(前向 2、反向 2),每次 \(\sim 2sbh\) 字节,在关键路径上,难以重叠 → 必须 NVLink,\(t\le 8\)(一个节点的卡数)。
- CP/SP:通信也频繁,优先节点内或紧邻 TP。
- PP:只在 stage 边界传 activation,量小 → 可跨节点。
- DP/FSDP:每 step 一次大规模梯度同步,但可以和反向重叠 → 最外层。
- EP:all-to-all,量较大且在关键路径上 → 尽量节点内或限制跨节点数。
LLaMA-3 405B 的论文明确写了这个顺序:并行维度从内到外是 [TP, CP, PP, DP],最内层需要最高带宽和最低延迟,最外层的 DP(FSDP)能容忍较高延迟(The Llama 3 Herd of Models, §3.3.2)。
The gap that drives every layout decision is intra-node versus inter-node bandwidth. NVLink gives each GPU a few hundred gigabytes per second, while InfiniBand gives a few tens, so there's about an order of magnitude between them. Tensor parallelism does several all-reduces per layer right on the critical path, so I keep it within a node, usually at degree eight or less. Pipeline parallelism only sends activations at stage boundaries, and data parallelism can overlap its gradient sync with backward, so both of those can cross nodes. Llama 3 used exactly that order, with TP innermost, then context parallel, then pipeline, then data parallel.
通信与计算重叠
通信只要不在关键路径上就是"免费"的:DDP 在反向过程中边算边 all-reduce 已就绪的梯度 bucket,FSDP 提前 prefetch 下一层参数,PP 异步发送,TP 的通信最难隐藏。
Communication is free when it's off the critical path: DDP all-reduces finished gradient buckets during backward, FSDP prefetches the next layer's parameters, and tensor-parallel communication is the hardest to hide.
判断一种通信能否被隐藏,问两个问题:(1) 有没有和它不相关的计算可以同时做?(2) 这个计算的时长是否 ≥ 通信时长?
- DDP:反向是从最后一层往前算。最后几层的梯度算完后,在前面几层的反向还在算时就可以 all-reduce → 天然可重叠。只有最后一个 bucket(第一层)的通信暴露在外。
- FSDP/ZeRO-3:计算第 \(i\) 层时 prefetch 第 \(i+1\) 层参数(前向)或第 \(i-1\) 层参数(反向);reduce-scatter 第 \(i\) 层梯度和第 \(i-1\) 层反向计算重叠。
- TP:all-reduce 的结果是下一个操作的输入(数据依赖),朴素实现无法重叠。进阶做法:把 GEMM 切成块和通信流水化("async TP"/collective matmul),但工程复杂。
- PP:send/recv 和其他 micro-batch 的计算重叠。
- EP:DeepSeek-V3 的 DualPipe 把一个 micro-batch 的 all-to-all 和另一个 micro-batch 的计算交错排布,用来隐藏跨节点 all-to-all(DeepSeek-V3 Technical Report)。
重叠的代价:通信 kernel 和计算 kernel 抢 SM 和显存带宽,所以"重叠"也不是完全免费;NCCL 会占用一部分 SM。
Whether communication costs you anything depends on whether there's independent compute to hide it behind. DDP overlaps naturally, because the last layers' gradients are ready while the earlier layers are still running backward. FSDP prefetches the next layer's parameters while the current layer computes. Tensor parallelism is the hard case, because the all-reduce output feeds straight into the next operation, which is one more reason to keep it on NVLink.
§3 · DATA PARALLELISM数据并行、ZeRO 与 FSDP
数据并行是最简单也最常用的并行:每张卡有完整模型,处理不同数据,同步梯度。它的问题是每张卡都存一份完整的 16Ψ。ZeRO/FSDP 的思想是"数据并行的计算方式 + 模型状态的切分存储",在几乎不增加通信的前提下把 model states 摊到所有卡上。这一节是本章最高频的考点。
DDP:复制模型、切分数据、all-reduce 梯度
每张卡一份完整模型,处理 global batch 的一部分,反向时把梯度分桶(bucket)all-reduce 求平均,并和反向计算重叠;结果和单卡在完整 batch 上训练数学上等价。
DDP replicates the model, gives each GPU a slice of the batch, and averages gradients with bucketed all-reduces overlapped with backward; the result is mathematically equivalent to single-GPU training on the full batch.
流程(PyTorch DistributedDataParallel,见 Li et al. 2020, PyTorch Distributed):
- 构造时从 rank 0 broadcast 参数和 buffer,保证所有副本初始相同。
- 每个 rank 用
DistributedSampler取不同的数据分片,独立前向。 - 反向时,每个参数的梯度算完会触发 autograd hook;参数按(大致逆序的)顺序分进若干 bucket(默认约 25 MB),一个 bucket 里所有梯度都就绪就立即发起异步 all-reduce。
- all-reduce 求和后除以 world size 得到平均梯度;每个 rank 独立做完全相同的 optimizer step,副本保持一致。
为什么等价:损失是样本平均,\(\nabla \frac{1}{B}\sum_{i=1}^{B}\ell_i = \frac{1}{N}\sum_{r=1}^{N}\Big(\frac{1}{B/N}\sum_{i\in r}\nabla\ell_i\Big)\),即各 rank 本地平均梯度的平均。(前提:各 rank 的样本数相同,且没有 BatchNorm 这类跨样本的统计量——BN 需要 SyncBatchNorm。)
为什么要 bucket:(1) 每次通信有固定延迟 \(\alpha\),几百个小张量逐个通信太慢;(2) 一次把全部梯度攒齐再通信又无法重叠。bucket 是两者的折中。
通信量:每 step 一次梯度 all-reduce,每卡约 \(2\cdot 2\Psi = 4\Psi\) 字节(bf16 梯度)。用 ZeRO 论文的记法,DDP 的通信量是 \(2\Psi\)(以"参数个数"为单位:RS 和 AG 各 \(\Psi\))。
显存:每卡完整的 16Ψ + 自己的 activation。所以 DDP 只适合模型 states 装得下单卡的情况(约 ≤ 4B 参数在 80 GB 卡上,还要留 activation)。
DDP 最小例子(参考代码,需 torch)
# DDP minimal example. Runs on CPU with 2 processes (gloo backend) so it can be tested without GPUs.
# On a GPU node you would launch with: torchrun --nproc_per_node=8 train.py and use backend="nccl".
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
def worker(rank, world_size):
os.environ["MASTER_ADDR"] = "127.0.0.1"
os.environ["MASTER_PORT"] = "29511"
dist.init_process_group("gloo", rank=rank, world_size=world_size)
torch.manual_seed(0) # same init on every rank (DDP also broadcasts rank 0's weights)
model = torch.nn.Sequential(torch.nn.Linear(8, 16), torch.nn.ReLU(), torch.nn.Linear(16, 1))
ddp = DDP(model) # registers autograd hooks -> bucketed all-reduce of grads
opt = torch.optim.SGD(ddp.parameters(), lr=0.1)
g = torch.Generator().manual_seed(123)
X = torch.randn(8, 8, generator=g); y = torch.randn(8, 1, generator=g)
Xr, yr = X.chunk(world_size)[rank], y.chunk(world_size)[rank] # each rank: its shard of the batch
loss = torch.nn.functional.mse_loss(ddp(Xr), yr)
opt.zero_grad(); loss.backward(); opt.step() # backward() already averaged grads across ranks
# reference: single-process model on the full batch must give identical weights
torch.manual_seed(0)
ref = torch.nn.Sequential(torch.nn.Linear(8, 16), torch.nn.ReLU(), torch.nn.Linear(16, 1))
ropt = torch.optim.SGD(ref.parameters(), lr=0.1)
rl = torch.nn.functional.mse_loss(ref(X), y)
ropt.zero_grad(); rl.backward(); ropt.step()
for p, q in zip(model.parameters(), ref.parameters()):
assert torch.allclose(p, q, atol=1e-6), "DDP != single-process full batch"
dist.destroy_process_group()
if __name__ == "__main__":
mp.spawn(worker, args=(2,), nprocs=2, join=True)
print("DDP OK")
这段在 CPU 上用 gloo 起 2 个进程,并断言 DDP 一步后的权重 == 单进程在完整 batch 上一步后的权重。本环境没有 torch,未运行(保存为 torch_tests/01_ddp_gloo.py);"各 rank 平均梯度的平均 == 全 batch 梯度"这件事在 §9 的 ZeRO 模拟里用 numpy 验证过。GPU 上用 torchrun --nproc_per_node=8 train.py 启动,后端换成 nccl,并用 LOCAL_RANK 环境变量选择设备。
DistributedSampler 调用 set_epoch(epoch),每个 epoch 的 shuffle 都一样。(2) 部分参数在某些 step 没参与前向(比如 MoE 某些专家、条件分支)→ DDP 一直等它的梯度而卡住,需要 find_unused_parameters=True(有开销)。(3) 在 rank 0 上做 eval 或保存 checkpoint 时,其他 rank 跑去做下一个 collective,导致死锁或超时。(4) loss 用 sum 而非 mean 时,等价性要重新推导。In DDP every GPU holds a full replica and processes its own slice of the batch. During backward, gradients are grouped into buckets of about 25 megabytes, and each bucket gets all-reduced as soon as it's ready, so communication overlaps with the rest of backward. After the all-reduce every rank has the same averaged gradient and takes the same optimizer step, so the replicas stay identical. Mathematically that's the same as training on the full batch on one GPU. The limitation is that every GPU still holds all sixteen bytes per parameter.
- Why was DataParallel (DP) replaced by DistributedDataParallel?
思路
老的nn.DataParallel是单进程多线程:每步把模型从 GPU 0 复制到其他卡、输出收集到 GPU 0,GPU 0 负载不均,还受 GIL 限制。DDP 每卡一个进程,没有 GIL 问题,用 all-reduce 而非集中收集,也支持多机。 - Does increasing the number of DP ranks change the optimization?
梯度累积与有效 batch size
有效 batch = 每卡 micro-batch × 梯度累积步数 × DP 大小;梯度累积用时间换显存,activation 只和 micro-batch 有关,而且 DDP 下应该只在最后一个累积步才同步梯度(no_sync)。
Global batch = micro-batch × accumulation steps × data-parallel size; accumulation trades time for memory since activations depend only on the micro-batch, and under DDP you should skip the all-reduce until the last micro-step.
例:目标 4M tokens/step(\(2^{22}\)),\(s=4096\) → 1024 条序列;64 个 DP rank → 每 rank 16 条;显存只放得下 \(b=2\) → 累积 8 步。
实现要点:
- 每个 micro-step 的 loss 除以 \(k\)(或者累积完再把梯度除以 \(k\)),这样累积后的梯度才是平均值。
- 如果是变长序列、按 token 平均 loss,正确做法是除以整个 global batch 的有效 token 总数,而不是每个 micro-batch 各自平均再平均(否则短序列的 token 权重被放大)。这是一个常见 bug。
- DDP 下前 \(k-1\) 个 micro-step 放在
with model.no_sync():里,避免每个 micro-step 都 all-reduce(通信量变成 \(k\) 倍)。FSDP 也有类似的设置,但 ZeRO-2/3 下不同步就要保存完整(未切分)梯度,有显存代价。 - 梯度裁剪、optimizer step、scheduler step、zero_grad 都在累积完成后各做一次。
optimizer.step()。(3) 变长序列下"平均的平均"导致 token 加权错误(这在 2024 年被社区广泛讨论过,许多框架的梯度累积实现都修过这个 bug)。The effective batch size is micro-batch times accumulation steps times the data-parallel degree. Gradient accumulation lets you hit a large global batch without the activation memory, because activations only depend on the micro-batch. Under DDP you wrap all but the last micro-step in no_sync so you all-reduce only once. A subtle bug is normalizing the loss per micro-batch when sequences have different lengths. The right thing is to divide by the total number of loss tokens in the whole global batch.
ZeRO-1 / 2 / 3:切优化器状态、梯度、参数
ZeRO 在数据并行组内把 model states 切成 \(N_d\) 份,每卡只负责 1/N_d:Stage 1 切优化器状态(4Ψ+12Ψ/N_d),Stage 2 再切梯度(2Ψ+14Ψ/N_d),Stage 3 再切参数(16Ψ/N_d);Stage 1/2 通信量和 DDP 相同,Stage 3 约为 1.5 倍。
ZeRO shards model states across data-parallel ranks: stage 1 shards optimizer states, stage 2 also gradients, stage 3 also parameters; stages 1 and 2 cost the same communication as DDP, stage 3 about 1.5×.
来源:Rajbhandari et al. 2019, ZeRO: Memory Optimizations Toward Training Trillion Parameter Models。核心观察:DDP 里每个 rank 存了完全相同的优化器状态、梯度和参数,是巨大的冗余。
每卡显存(Adam,K=12,混合精度):
| Stage | 切分什么 | 每卡 model states | 7B, \(N_d=64\) | 通信量(参数个数为单位) |
|---|---|---|---|---|
| DDP (0) | 无 | \((2+2+K)\Psi = 16\Psi\) | 112 GB | \(2\Psi\)(all-reduce) |
| ZeRO-1 (\(P_{os}\)) | 优化器状态 | \(4\Psi + \frac{K\Psi}{N_d}\) | 29.3 GB | \(2\Psi\)(RS 梯度 + AG 参数) |
| ZeRO-2 (\(P_{os+g}\)) | + 梯度 | \(2\Psi + \frac{(2+K)\Psi}{N_d}\) | 15.5 GB | \(2\Psi\) |
| ZeRO-3 (\(P_{os+g+p}\)) | + 参数 | \(\frac{(2+2+K)\Psi}{N_d}\) | 1.75 GB | \(3\Psi\)(≈1.5×) |
(7B 那一列来自 §9 计算器的输出。注意这只是 model states,activation 另算。)
ZeRO-1/2 的一步怎么做:
- 前向、反向和 DDP 一样(每卡有完整 bf16 参数)。
- 梯度做 reduce-scatter(而不是 all-reduce):rank \(r\) 只拿到自己负责的那 \(1/N_d\) 片的平均梯度。ZeRO-2 下其余梯度可以立即释放(所以梯度也只存 1/N_d);ZeRO-1 下通常仍保留完整梯度 buffer。
- rank \(r\) 用自己那片的 fp32 master、m、v 做 Adam 更新,得到新的参数片。
- 参数做 all-gather,每卡重新得到完整的 bf16 参数。
RS(\(\Psi\))+ AG(\(\Psi\))= \(2\Psi\),和 DDP 的 all-reduce 一模一样。这就是 ZeRO-1/2"免费"的原因:all-reduce 本来就是 RS + AG,ZeRO 只是在中间插了一个"只更新自己那片"的步骤。
ZeRO-3 为什么是 1.5×:参数也切开了,每卡平时只存 1/N_d。
- 前向:每层计算前 all-gather 该层参数,用完释放 → 共 \(\Psi\)。
- 反向:每层再 all-gather 一次参数(前向后已经释放了)→ \(\Psi\)。
- 梯度 reduce-scatter → \(\Psi\)。
合计 \(3\Psi\),是 DDP 的 1.5 倍。(如果前向后不释放参数——FSDP 的 reshard_after_forward=False,相当于 ZeRO-2 式的行为——就省掉反向那次 all-gather,回到 \(2\Psi\),代价是参数在前向到反向之间完整驻留。LLaMA-3 就是这样做的:前向后不 reshard 参数,避免反向时的额外 all-gather。)
ZeRO 的其他部分:ZeRO-R 处理残余显存(activation 分区、固定大小 buffer、碎片整理);ZeRO-Offload 把优化器状态和更新放到 CPU;ZeRO-Infinity 进一步 offload 到 NVMe;ZeRO++ 用量化通信和分层切分减少跨节点通信。
numpy 验证:ZeRO 式分片 Adam == 不分片 Adam(已运行)
import numpy as np
def adam_step(p, g, m, v, t, lr=1e-2, b1=0.9, b2=0.95, eps=1e-8, wd=0.1):
m = b1 * m + (1 - b1) * g
v = b2 * v + (1 - b2) * g * g
mh, vh = m / (1 - b1**t), v / (1 - b2**t)
p = p - lr * (mh / (np.sqrt(vh) + eps) + wd * p)
return p, m, v
rng = np.random.default_rng(0)
N, D, steps = 4, 32, 5
p_ref = rng.standard_normal(D); m_ref = np.zeros(D); v_ref = np.zeros(D)
# ZeRO-2 style: every worker has full params, but only its 1/N slice of m, v (and reduced grads)
p_w = [p_ref.copy() for _ in range(N)]
sl = np.array_split(np.arange(D), N)
m_sh = [np.zeros(len(s)) for s in sl]; v_sh = [np.zeros(len(s)) for s in sl]
for t in range(1, steps + 1):
local_g = [rng.standard_normal(D) for _ in range(N)] # each worker's micro-batch grad
g_avg = np.mean(local_g, axis=0)
p_ref, m_ref, v_ref = adam_step(p_ref, g_avg, m_ref, v_ref, t)
# reduce-scatter: worker r receives the average of slice r only
g_shard = [np.mean([lg[sl[r]] for lg in local_g], axis=0) for r in range(N)]
new_slices = []
for r in range(N):
pr, m_sh[r], v_sh[r] = adam_step(p_w[r][sl[r]], g_shard[r], m_sh[r], v_sh[r], t)
new_slices.append(pr)
full = np.concatenate(new_slices) # all-gather updated params
p_w = [full.copy() for _ in range(N)]
for r in range(N):
assert np.allclose(p_w[r], p_ref)
print("ZeRO sharded Adam == unsharded Adam OK")
输出 ZeRO sharded Adam == unsharded Adam OK:4 个 worker 每个只存 1/4 的 m、v,用 reduce-scatter 得到自己那片的平均梯度,更新后 all-gather,5 步后的参数和不分片版本完全一致。原因是 Adam 和 weight decay 都是逐元素操作。注意:梯度裁剪需要全局梯度范数,分片后要先在各片上算平方和,再 all-reduce 一个标量;Shampoo/Muon 这类按矩阵操作的优化器不能简单按元素切分,需要按整块参数分配。
ZeRO removes the redundancy in data parallelism by sharding model states across the data-parallel group. Stage one shards the optimizer states, stage two also shards gradients, and stage three also shards the parameters themselves. The nice part is that stages one and two cost no extra communication. An all-reduce is just a reduce-scatter plus an all-gather, so you reduce-scatter the gradients, update your own shard, and all-gather the new parameters. Stage three has to gather each layer's parameters again in backward, so it's about 1.5 times the DDP traffic, but memory drops to 16 Ψ over N.
- When would you pick ZeRO-2 over ZeRO-3?
思路
如果 bf16 参数(2Ψ)完整放得下(例如 7B 只要 14 GB),ZeRO-2 已经把大头(梯度和 12Ψ 的优化器状态)切掉了,通信更少,也没有每层 all-gather 的延迟和 prefetch 调度问题。模型大到 2Ψ 都放不下(如 70B 需要 140 GB)才必须 ZeRO-3,或者和 TP/PP 组合。 - Why does ZeRO-3 get slow on many nodes with small per-GPU batch?
思路
每层 all-gather 的数据量固定(该层参数大小),和 batch 无关;计算量却和本卡 batch 成正比。batch 小时计算不足以掩盖通信,每层都要等 all-gather。而且跨节点带宽低。对策:增大 micro-batch、HSDP(节点内切分、跨节点复制)、和 TP 组合减少参数通信、ZeRO++ 的量化通信。 - How do you compute the global gradient norm for clipping under ZeRO?
思路
每个 rank 对自己的梯度片算平方和,all-reduce(求和)这个标量,开根号得到全局范数,然后各自用同一个缩放因子裁剪自己那片。有 TP/PP 时要在对应的组内也求和,并注意不要重复计算被复制的参数(如 TP 中复制的 LayerNorm 参数)。
FSDP:PyTorch 版的 ZeRO-3
FSDP 按"wrap 单元"(通常是一个 Transformer block)把参数展平切分;前向/反向前 all-gather 这个单元的参数,用完 reshard,梯度 reduce-scatter;wrap 的粒度决定峰值显存和通信重叠的效果。
FSDP shards each wrapped unit, typically one transformer block; it all-gathers a unit's parameters just before use, frees them afterward, and reduce-scatters its gradients, so the wrapping granularity sets peak memory and overlap.
来源:Zhao et al. 2023, PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel。
- Wrapping(auto-wrap policy):每个 Transformer block 是一个 FSDP 单元。粒度太粗(整个模型一个单元)→ all-gather 时整个模型同时完整驻留,等于没切;粒度太细 → 通信次数多、消息小、延迟主导。按 block 切是常见的平衡点。
- 前向:all-gather 单元 \(i\) 参数 → 计算 → 释放(reshard);同时 prefetch 单元 \(i+1\)。
- 反向:再次 all-gather 单元 \(i\) 参数 → 计算梯度 → reduce-scatter 梯度 → 释放。
- 峰值显存 ≈ 分片后的 model states + 完整参数中正在用的 1–2 个单元 + activations。
- Mixed precision 策略:参数分片以 fp32 存储,all-gather 时转成 bf16 计算;梯度 reduce-scatter 用 fp32 或 bf16(LLaMA-3 用 fp32 做梯度 reduce-scatter)。
- FSDP2(
torch.distributed.fsdp.fully_shard):按参数切分,用 DTensor 表示,更好地和 TP 组合(2D 并行),是 PyTorch 目前推荐的接口。
HSDP(Hybrid Sharded Data Parallel):在节点内(或一组卡内)做 FSDP 切分,跨组做复制(DDP 式 all-reduce)。好处:频繁的参数 all-gather 只走 NVLink;跨节点只做一次梯度 all-reduce。代价:每卡显存是 \(16\Psi/(\text{组大小})\) 而不是 \(16\Psi/N_d\)。这是"显存换通信"的典型折中,DeepSpeed 里对应 ZeRO++ 的 hierarchical partitioning(hpZ)。
FSDP2 参考代码(需 torch,未运行)
# FSDP2 (fully_shard) reference snippet. Intended for GPUs (nccl). This test tries CPU+gloo; if the
# installed torch version does not support FSDP2 on CPU it prints SKIP and exits 0.
import os, sys
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
class Block(torch.nn.Module):
def __init__(self, d):
super().__init__()
self.ff = torch.nn.Sequential(torch.nn.Linear(d, 4 * d), torch.nn.GELU(), torch.nn.Linear(4 * d, d))
def forward(self, x):
return x + self.ff(x)
def worker(rank, world_size):
os.environ["MASTER_ADDR"] = "127.0.0.1"
os.environ["MASTER_PORT"] = "29513"
dist.init_process_group("gloo", rank=rank, world_size=world_size)
from torch.distributed.fsdp import fully_shard # public since PyTorch 2.6
from torch.distributed.device_mesh import init_device_mesh
mesh = init_device_mesh("cpu", (world_size,))
torch.manual_seed(0)
model = torch.nn.Sequential(*[Block(16) for _ in range(4)])
for blk in model: # shard each block: its params are all-gathered just-in-time
fully_shard(blk, mesh=mesh, reshard_after_forward=True)
fully_shard(model, mesh=mesh) # root wrap for remaining params
opt = torch.optim.AdamW(model.parameters(), lr=1e-3) # optimizer only sees local shards (DTensor)
x = torch.randn(4, 16)
loss = model(x).pow(2).mean()
loss.backward() # grads are reduce-scattered to shards
opt.step(); opt.zero_grad()
dist.destroy_process_group()
if __name__ == "__main__":
try:
mp.spawn(worker, args=(2,), nprocs=2, join=True)
print("FSDP2 OK")
except Exception as e: # environment without CPU FSDP2 support
print("SKIP:", type(e).__name__, e)
sys.exit(0)
这是参考代码,本环境没有 torch,未运行。它尝试在 CPU + gloo 上跑 FSDP2;如果当前 torch 版本不支持就打印 SKIP 并以 0 退出。在 GPU 上应使用 init_device_mesh("cuda", ...) 和 nccl,还可以传 mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)。API 细节以你使用的 PyTorch 版本文档为准。
state_dict() 得到的是分片,需要用 distributed checkpoint(DCP)或者先 gather 成完整的 state dict(大模型会在 rank 0 上 OOM)。(3) 在 wrap 之前创建 optimizer:optimizer 拿到的是旧参数对象。FSDP is PyTorch's take on ZeRO stage three. You wrap each transformer block as a unit. Before a unit runs, FSDP all-gathers its parameter shards, then frees them right afterward, and prefetches the next unit to overlap communication. In backward it gathers again, computes gradients, and reduce-scatters them. Wrapping granularity is the key knob: too coarse and you lose the memory savings, too fine and you're latency-bound. On multi-node clusters I'd often use hybrid sharding, which shards within a node and replicates across nodes, so the frequent all-gathers stay on NVLink.
Offload 与 ZeRO-Infinity
把优化器状态(以及更新计算)放到 CPU 内存(ZeRO-Offload)或 NVMe(ZeRO-Infinity),用 PCIe 带宽和 CPU 算力换 GPU 显存;适合卡少、只要求"能训"的场景,吞吐通常明显下降。
Offloading moves optimizer states and the update step to CPU memory or NVMe, trading PCIe bandwidth and CPU compute for GPU memory; it's great for training big models on few GPUs but usually costs throughput.
ZeRO-Offload(Ren et al. 2021)的设计:GPU 上保留 bf16 参数,做前向和反向;梯度传到 CPU(每步 \(2\Psi\) 字节过 PCIe);CPU 上用优化过的 Adam 更新 fp32 master 和 m、v;新的 bf16 参数传回 GPU。每卡 GPU 显存从 \(16\Psi\) 降到约 \(4\Psi\)(ZeRO-2 + offload 时更低)。
瓶颈估算:7B 模型的 bf16 梯度 14 GB,PCIe Gen4 约 25 GB/s 实际 → 单程约 0.5 s;如果每步计算只有 1 s,offload 就会占很大比例。所以 offload 适合每步计算时间长(大 batch)的情况。ZeRO-Infinity(Rajbhandari et al. 2021)进一步用 NVMe,能在有限 GPU 上放下万亿参数模型。
Offloading puts the optimizer states, and usually the Adam update itself, on the CPU, so the GPU only keeps bf16 weights and does forward and backward. That cuts GPU memory a lot, but now every step pushes the gradients and parameters over PCIe, which is far slower than HBM or NVLink. I'd use it when I have very few GPUs and just need the model to fit, like fine-tuning a big model on a single node, not for large-scale pretraining where throughput matters.
§4 · TENSOR PARALLELISM张量并行
当一层的参数或计算本身太大时,就把每个矩阵乘切到多张卡上。Megatron-LM 的设计非常巧妙:MLP 和 attention 各只需要前向一次 all-reduce。这一节要能在白板上画出切分方式并说明"为什么第一个矩阵按列切、第二个按行切"。
Megatron MLP:先列切,后行切,前向只需一次 all-reduce
MLP \(Y=\text{GeLU}(XA)B\):A 按列切(每卡得到中间激活的一部分列,GeLU 逐元素可以本地做),B 按行切(每卡得到输出的部分和),最后一次 all-reduce 求和;反向对称地在输入处一次 all-reduce。
For the MLP, split the first weight by columns so each GPU applies GeLU to its own slice of the hidden units, then split the second weight by rows so each GPU produces a partial sum, and one all-reduce finishes the forward pass.
来源:Shoeybi et al. 2019, Megatron-LM。设 \(X\in\mathbb{R}^{n\times h}\),\(A\in\mathbb{R}^{h\times 4h}\),\(B\in\mathbb{R}^{4h\times h}\),TP 大小为 \(t\)。
第一步:A 按列切(column parallel)。\(A=[A_1, A_2, \dots, A_t]\),每个 \(A_i\in\mathbb{R}^{h\times 4h/t}\)。每卡都有完整的 \(X\),算
$$Y_i = \text{GeLU}(XA_i) \in \mathbb{R}^{n\times 4h/t}$$因为 \([XA_1,\dots,XA_t] = XA\),而 GeLU 逐元素作用,所以 \([Y_1,\dots,Y_t]=\text{GeLU}(XA)\)。不需要任何通信。
为什么不按行切 A?如果 \(A\) 按行切、\(X\) 按列切,每卡得到的是部分和 \(X_iA_i\),而 \(\text{GeLU}(X_1A_1+X_2A_2)\ne\text{GeLU}(X_1A_1)+\text{GeLU}(X_2A_2)\),GeLU 前必须先 all-reduce,多一次同步。
第二步:B 按行切(row parallel)。\(B=\begin{bmatrix}B_1\\ \vdots\\ B_t\end{bmatrix}\),每个 \(B_i\in\mathbb{R}^{4h/t\times h}\)。卡 \(i\) 正好有 \(Y_i\),算
$$Z_i = Y_iB_i\in\mathbb{R}^{n\times h},\qquad Z=\sum_{i=1}^{t} Z_i = [Y_1,\dots,Y_t]\begin{bmatrix}B_1\\ \vdots\\ B_t\end{bmatrix}=YB$$一次 all-reduce 得到 \(Z\)(然后每卡做同样的 dropout/残差加法)。
Megatron 的 \(f\) 和 \(g\) 算子:论文把这对通信写成两个共轭算子:\(f\) 在 MLP 入口,前向是恒等(identity),反向是 all-reduce(因为 \(X\) 被所有卡使用,\(\partial L/\partial X\) 要把各卡的贡献加起来);\(g\) 在出口,前向 all-reduce,反向恒等。所以每个 MLP 前向 1 次、反向 1 次 all-reduce。
通信量:每次 all-reduce 的数据是 \(n\times h\) 的激活(\(n=s\cdot b\)),即 \(2sbh\) 字节(bf16)。每层(attention + MLP)前向 2 次、反向 2 次,共 4 次 all-reduce。
显存:MLP 的参数和中间激活(4h 宽的部分)都被切成 1/t。但 \(X\)(MLP 的输入)、LayerNorm、dropout 在每卡上都是完整复制的——这就是 §1 表格里 TP 下的 "10sbh" 项,也是 sequence parallelism 要解决的问题。
numpy 验证:2/4 分片的 column→row 并行 MLP == 不分片 MLP(已运行)
import numpy as np
def gelu(x):
return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3)))
def mlp(X, A, B):
return gelu(X @ A) @ B # X:(n,h) A:(h,4h) B:(4h,h)
def tp_mlp(X, A, B, t):
# column-parallel A: split output columns; row-parallel B: split input rows
A_shards = np.split(A, t, axis=1) # each (h, 4h/t)
B_shards = np.split(B, t, axis=0) # each (4h/t, h)
partials = []
for i in range(t): # each "GPU" i, no communication inside
Yi = gelu(X @ A_shards[i]) # GeLU is elementwise -> OK on a column shard
partials.append(Yi @ B_shards[i]) # partial sum (n, h)
return sum(partials) # the single all-reduce in forward
rng = np.random.default_rng(0)
n, h = 6, 8
X = rng.standard_normal((n, h))
A = rng.standard_normal((h, 4 * h)) / np.sqrt(h)
B = rng.standard_normal((4 * h, h)) / np.sqrt(4 * h)
ref = mlp(X, A, B)
for t in [1, 2, 4]:
assert np.allclose(tp_mlp(X, A, B, t), ref)
# Why NOT split A by rows: GeLU(X1 A1 + X2 A2) != GeLU(X1 A1) + GeLU(X2 A2)
A_r = np.split(A, 2, axis=0); X_c = np.split(X, 2, axis=1)
wrong = gelu(X_c[0] @ A_r[0]) + gelu(X_c[1] @ A_r[1])
assert not np.allclose(wrong, gelu(X @ A))
print("TP MLP OK: column->row parallel == unsharded; row-split before GeLU is wrong")
输出:TP MLP OK: column->row parallel == unsharded; row-split before GeLU is wrong。t=1/2/4 都和不分片结果一致,并且验证了"GeLU 之前按行切"会得到错误结果。
In Megatron's MLP, the first weight matrix is split by columns. Each GPU has the full input and computes its own slice of the hidden units, and since GeLU is elementwise it can be applied locally with no communication. The second matrix is split by rows, so each GPU multiplies its slice and gets a partial sum of the output. One all-reduce adds those up. Backward is symmetric, with one all-reduce on the input gradient. Splitting the first matrix by rows would be wrong, because you'd have to sum before the nonlinearity, which adds an extra sync.
- How do you handle the embedding and the LM head under TP?
思路
按词表维度切分(vocab parallel):每卡存 \(V/t\) 行。Embedding 查表时,不在本卡范围内的 token 得 0,再 all-reduce。LM head 的输出 logits 按词表切开,cross-entropy 要做"并行版本":各卡算本地 max 和 sum-exp,all-reduce 得到全局的 logsumexp,再取目标 token 的 logit(只有一张卡有),避免 all-gather 完整的 \(s\times V\) logits。 - What's the TP communication volume per layer for a 70B-scale model?
思路
\(h=8192\)、\(s=4096\)、\(b=1\):每次 all-reduce \(2sbh = 2\times4096\times8192 \approx 67\) MB。每层前向 2 次 + 反向 2 次 = 4 次,每次 ring all-reduce 每卡发送约 \(2\cdot\frac{t-1}{t}\cdot 67\) MB。80 层乘下来每步每卡几十 GB,所以必须 NVLink。
Attention 的张量并行:按头切分
Q、K、V 投影按列切(每卡分到 a/t 个头,各头的 attention 完全独立地本地计算),输出投影按行切,前向一次 all-reduce;要求头数(以及 GQA 的 KV 头数)能被 t 整除或做复制。
Attention is split by heads: the QKV projections are column-parallel so each GPU owns a/t heads and computes them locally, the output projection is row-parallel, and one all-reduce finishes the block.
多头 attention 天然可并行:各头之间没有交互,只在输出投影 \(W_O\) 处混合。
- \(W_Q, W_K, W_V\in\mathbb{R}^{h\times h}\) 按列切成 \(t\) 份,每份对应 \(a/t\) 个头(列切必须对齐头的边界)。
- 每卡对自己的 \(a/t\) 个头做完整的 softmax attention(包括 causal mask、FlashAttention),无通信。
- \(W_O\) 按行切,每卡得到输出的部分和,一次 all-reduce。
GQA 的情况:若 KV 头数 \(n_{kv}\ge t\) 且能整除,就按 KV 组切;若 \(n_{kv}<t\)(例如 8 个 KV 头、TP=16),则需要在多张卡上复制同一组 KV 头。这也是 TP 通常不超过 8 的原因之一(LLaMA-2-70B 有 8 个 KV 头)。
每层 TP 通信汇总:attention 1 次 + MLP 1 次(前向),反向各 1 次,共 4 次 all-reduce,每次 \(2sbh\) 字节。和 \(h^2\) 成正比的计算量相比,通信量和 \(h\) 成正比——所以模型越宽,TP 的通信占比越小,效率越高。
TP 的扩展极限:\(t\) 变大时,每卡的矩阵乘变"瘦"(\(h\times h/t\)),GPU 利用率下降;all-reduce 的数据量不随 \(t\) 减少(每卡总是 \(\sim 2sbh\)),而计算按 \(1/t\) 减少,通信占比上升。跨节点做 TP 时带宽下降约 10 倍,通常得不偿失。
Attention parallelizes naturally across heads. You split the Q, K and V projections by columns along head boundaries, so each GPU computes attention for its own subset of heads with no communication. Then the output projection is row-parallel, followed by one all-reduce. With grouped-query attention you need the number of KV heads to divide evenly, or else you replicate KV heads across ranks. Per layer that's two all-reduces in forward and two in backward, each the size of the activations, which is why TP stays inside a node.
Megatron Sequence Parallelism:把 TP 剩下的激活也切开
在 TP 区域之外(LayerNorm、dropout、残差),按序列维度切分激活;把 TP 的 all-reduce 拆成 reduce-scatter + all-gather,通信量不变,activation 显存从 \(sbh(10+24/t)\) 降到 \(34sbh/t\)。
Megatron sequence parallelism shards the activations outside the tensor-parallel regions, such as LayerNorm and dropout, along the sequence dimension; it turns each all-reduce into a reduce-scatter plus an all-gather, so communication stays the same while activation memory becomes fully divided by t.
来源:Korthikanti et al. 2022。问题:纯 TP 下 LayerNorm、dropout 和残差处的激活在每张 TP 卡上完整复制,这部分(10sbh)不随 \(t\) 减少。
做法:这些操作是逐 token 独立的,所以可以沿序列维度切开:每卡只处理 \(s/t\) 个 token 的 LayerNorm/dropout。
- 进入 TP 区域(column-parallel Linear)前,需要完整序列 → all-gather(沿序列维度)。
- 离开 TP 区域(row-parallel Linear 后)本来要 all-reduce 部分和;现在改成 reduce-scatter:既求和,又顺便按序列切开,直接得到下一个 SP 区域需要的分片。
因为 all-reduce = reduce-scatter + all-gather,通信总量和纯 TP 一样,却省掉了冗余的 activation。这也是"all-reduce = RS + AG"这个恒等式的第二个经典应用(第一个是 ZeRO)。
Selective activation recomputation(同一篇论文):attention 里 \(QK^\top\)、softmax、dropout、乘 V 这一段占 activation 很大(\(5as^2b\)),但 FLOPs 相对少。只对这一段重计算,其余照常保存 → activation 降到 \(34sbh/t\),而重计算开销很小。论文报告:对 22B 模型的一层,full recompute 让前向+反向时间增加 39%,SP + selective recompute 只增加 4%。(FlashAttention 本身就在反向时重算 attention,所以用了 FlashAttention 后 selective recompute 基本是"自动"的。)
Megatron's sequence parallelism fixes a leftover inefficiency in tensor parallelism. LayerNorm, dropout and the residual adds are replicated on every TP rank, but they're independent per token, so you can shard them along the sequence. You then replace each all-reduce with a reduce-scatter on the way out of the TP region and an all-gather on the way in. The communication volume is identical, but activation memory is now fully divided by the TP degree. It's the same identity ZeRO uses: all-reduce equals reduce-scatter plus all-gather.
§5 · PIPELINE PARALLELISM流水线并行
把模型按层切成 \(p\) 段(stage),每段放在一组卡上,activation 在 stage 之间传递。通信量小,适合跨节点;代价是"气泡"(bubble):流水线填充和排空时有卡在空等。核心考点:bubble 公式的推导、1F1B 为什么省显存、interleaved 和 zero-bubble 的思路。
GPipe 与 bubble 公式 \((p-1)/(m+p-1)\)
把 batch 切成 m 个 micro-batch 流过 p 个 stage;填充和排空各浪费 p−1 个时间槽,bubble 占比 = \((p-1)/(m+p-1)\),所以要 \(m \gg p\)(经验上 \(m\ge 4p\))。
Split the batch into m micro-batches flowing through p stages; filling and draining the pipeline wastes p−1 slots, so the bubble fraction is (p−1)/(m+p−1) and you want m much larger than p.
朴素流水线(不切 micro-batch):同一时刻只有一个 stage 在工作,利用率只有 \(1/p\)。
GPipe:把一个 mini-batch 切成 \(m\) 个 micro-batch。所有 micro-batch 先依次做完前向(F),再依次做反向(B),最后同步更新。
推导 bubble:设每个 micro-batch 在一个 stage 上的前向时间为 \(t_f\),反向为 \(t_b\)。
- 前向阶段:最后一个 stage 要等 \(p-1\) 个 \(t_f\) 才能开始第一个 micro-batch;最后一个 micro-batch 在第一个 stage 开始于 \((m-1)t_f\),到最后一个 stage 完成于 \((m-1+p)t_f\)。所以前向阶段总时长 \((m+p-1)t_f\),其中每个 stage 有效工作 \(m\,t_f\)。
- 反向阶段对称:\((m+p-1)t_b\),有效 \(m\,t_b\)。
(Megatron 论文用的是另一种表述:bubble 时间与有效时间之比 \(=\frac{p-1}{m}\)。两者一致:\(\frac{p-1}{m+p-1} = \frac{(p-1)/m}{1+(p-1)/m}\)。面试时说清楚你用的是哪种定义。)
| p | m | bubble 占比 |
|---|---|---|
| 4 | 4 | 3/7 ≈ 42.9% |
| 4 | 16 | 3/19 ≈ 15.8% |
| 8 | 8 | 7/15 ≈ 46.7% |
| 8 | 32 | 7/39 ≈ 17.9% |
| 8 | 64 | 7/71 ≈ 9.9% |
GPipe 的显存问题:所有 \(m\) 个 micro-batch 的前向都做完才开始反向,所以每个 stage 要同时保存 \(m\) 份 activation。\(m\) 越大 bubble 越小,但显存越大——GPipe 用 activation checkpointing 缓解。
In GPipe you split the batch into m micro-batches and stream them through p stages. The last stage has to wait p minus one slots before it gets any work, and symmetrically the first stage sits idle while the pipeline drains. So total time is m plus p minus one slots, of which m are useful, and the bubble fraction is p minus one over m plus p minus one. To make it small you want many more micro-batches than stages, say four times as many. The catch with GPipe is memory, because every stage holds activations for all m micro-batches before backward starts.
- Why not just make m huge?
思路
\(m\cdot b\cdot N_{\text{DP}}=B_{\text{global}}\),global batch 受优化(critical batch size)限制;\(b\) 太小会降低 GEMM 效率;GPipe 下显存随 \(m\) 增长(1F1B 解决了这一点)。 - What does pipeline parallelism communicate, and how much?
思路
每个 micro-batch 在 stage 边界前向传 activation \(s\cdot b\cdot h\cdot 2\) 字节,反向传等大的梯度。比 TP 每层 4 次 all-reduce 少得多,而且是点对点,所以 PP 适合跨节点。
1F1B:同样的 bubble,显存从 m 份降到 p 份
1F1B(PipeDream-Flush 式)调度:每个 stage 做完少量 warmup 前向后,交替执行一次前向、一次反向,尽早释放 activation;bubble 和 GPipe 相同,但每个 stage 同时在飞的 micro-batch 最多 p 个,而不是 m 个。
The 1F1B schedule alternates one forward and one backward after a short warm-up, so each stage holds at most p micro-batches of activations instead of m, with the same bubble as GPipe.
来源:PipeDream(Harlap et al. 2018)提出 1F1B 思路;带同步 flush 的版本(PipeDream-Flush)被 Megatron 采用(Narayanan et al. 2021)。
调度(stage \(s\),从 0 开始编号):
- Warmup:做 \(p-s-1\) 个前向(最后一个 stage 不需要 warmup)。
- 稳态:交替"一个前向、一个反向"。
- Cooldown:把剩下的反向做完。
为什么显存少:一个 micro-batch 的 activation 从它的前向开始保存,到它的反向结束才释放。GPipe 中 stage 0 要做完全部 \(m\) 个前向才开始第一个反向,峰值 \(m\) 份;1F1B 中 stage 0 最多领先 \(p\) 个 micro-batch,之后每做一个前向就做一个反向,峰值 \(p\) 份(stage \(s\) 是 \(p-s\) 份)。
为什么 bubble 不变:流水线的填充和排空阶段仍然各需要 \(p-1\) 个槽位,所以总时间仍是 \((m+p-1)(t_f+t_b)\)。1F1B 只改善了显存,没改善 bubble。
本章 §9 有一个事件驱动模拟:\(p=8, m=32\) 时 GPipe 和 1F1B 的 bubble 都是 0.1795(= 7/39),stage 0 的峰值在飞 micro-batch 数分别是 32 和 8。
One-forward-one-backward keeps GPipe's bubble but fixes its memory problem. After a short warm-up, each stage alternates one forward and one backward, so a micro-batch's activations get freed soon after they're created. The first stage only ever runs about p micro-batches ahead, so it holds p sets of activations instead of m. The fill and drain phases are unchanged, though, so the bubble is still p minus one over m plus p minus one.
Interleaved 1F1B 与 Zero Bubble
Interleaved:每张卡放 v 个不连续的小 stage(虚拟 stage),bubble 降为 \(\frac{p-1}{vm+p-1}\),代价是 v 倍的 PP 通信;Zero Bubble:把反向拆成"对输入求梯度 B"和"对权重求梯度 W",W 没有跨 stage 依赖,可以用来填满气泡。
Interleaving puts v non-contiguous chunks on each GPU and cuts the bubble roughly by v at v times the pipeline communication; zero-bubble scheduling splits backward into input-gradient and weight-gradient parts and uses the dependency-free weight gradients to fill the bubbles.
Interleaved 1F1B(Narayanan et al. 2021):例如 32 层、4 张卡,不是每卡连续 8 层,而是每卡 2 段各 4 层(卡 0:第 0–3 层和第 16–19 层)。每个"虚拟 stage"的耗时变成 \(1/v\),填充/排空的时间也缩短到 \(1/v\):
$$\text{bubble}=\frac{p-1}{v\,m+p-1}\qquad\Big(\text{或者以比值表示 }\frac{1}{v}\cdot\frac{p-1}{m}\Big)$$代价:每个 micro-batch 跨卡传递的次数增加 \(v\) 倍;要求 \(m\) 是 \(p\) 的整数倍(Megatron 的实现要求)。LLaMA-3 进一步把"每 stage 连续执行多少个 micro-batch"做成可调参数,也报告了 bubble 比 \((PP-1)/(V\cdot M)\)。
Zero Bubble Pipeline Parallelism(Qi et al. 2023):反向传播其实包含两部分:
- B:\(\partial L/\partial x\)(对输入的梯度),上一个 stage 在等它,在关键路径上。
- W:\(\partial L/\partial W\)(对权重的梯度),只有本 stage 的 optimizer step 需要,没有跨 stage 依赖。
先做 B 让上游尽早开始,把 W 推迟到原本空闲的气泡里做。论文还用"更新后验证"替代 optimizer step 前的全局同步。论文报告:在类似显存限制下吞吐比 1F1B 高最多 23%,放宽显存时最多 31%;其 ZB-V 调度在 F/B/W 耗时相等的假设下能做到零气泡,峰值 activation 显存和 1F1B 相同。
DualPipe(DeepSeek-V3):双向流水线,micro-batch 同时从两端进入,并把前向和反向的计算与 MoE all-to-all 通信交错排布,以隐藏跨节点 EP 通信。DeepSeek-V3 报告使用 16 路 PP、64 路 EP(跨 8 个节点)和 ZeRO-1 DP,没有使用 TP。
Interleaving gives each GPU several smaller, non-contiguous chunks of layers. Each virtual stage is shorter, so the fill and drain time shrinks by the number of chunks, at the price of more point-to-point communication. Zero-bubble scheduling goes further by splitting backward into two parts: the input gradient, which the previous stage is waiting on, and the weight gradient, which nothing downstream needs. You run the input gradient first and use the weight-gradient work to fill what used to be idle bubbles.
§6 · CP / EP / ND LAYOUT其他并行与整体布局
长上下文需要切序列(context parallel);MoE 需要切专家(expert parallel)。真实的大规模训练把 DP、TP、PP、CP、EP 组合成多维网格。面试的开放题通常是"给你 N 张卡训 X 模型,怎么切",这一节给出思考框架和一个有数字的例子。
Context Parallel:Ring Attention 与 DeepSpeed-Ulysses
把整个序列(包括 attention)切到 cp 张卡上:Ring Attention 让 KV 块沿环流动、每卡用 online softmax 累积;Ulysses 用 all-to-all 把"按序列切"转成"按头切",每卡对部分头做完整 attention,再 all-to-all 回来。
Context parallelism shards the whole sequence: Ring Attention passes KV blocks around a ring and accumulates with online softmax, while Ulysses uses all-to-all to switch from sequence sharding to head sharding, runs full attention on a subset of heads, and switches back.
难点:MLP、LayerNorm 都是逐 token 的,按序列切没问题;但 attention 需要每个 query 看到所有(之前的)key/value。
Ring Attention(Liu, Zaharia, Abbeel 2023):每卡持有 \(s/\text{cp}\) 个 token 的 Q、K、V。进行 cp 轮:每轮用本地 Q 和当前持有的 KV 块算部分 attention,用 online softmax(和 FlashAttention 同样的 running max / running sum 技巧)累积结果,同时把 KV 块传给下一张卡。只要计算一个块的时间 ≥ 传一个 KV 块的时间,通信就能完全隐藏。因果 mask 下各卡负载不均(后面的块要看更多 KV),常用"zigzag"切分(每卡拿一前一后两块)来平衡。
DeepSpeed-Ulysses(Jacobs et al. 2023):attention 前做一次 all-to-all,把 \([s/\text{cp}, a]\) 的分布变成 \([s, a/\text{cp}]\)(每卡有完整序列、部分头),本地跑标准(Flash)attention,再 all-to-all 回去。论文指出,序列长度和设备数同比例增加时,每卡通信量保持不变。限制:cp 不能超过头数(GQA 时受 KV 头数限制)。
All-gather KV(LLaMA-3 的做法):LLaMA-3 405B 的 CP 是基于 all-gather 的:先 all-gather K、V,再对本地 Q 块计算 attention。理由是能灵活支持 document mask 等各种 mask,而且因为 GQA,K、V 比 Q 小很多,暴露的 all-gather 开销小。其 128k 序列阶段用 CP=16。
| Ring Attention | Ulysses | All-gather KV | |
|---|---|---|---|
| 通信 | 环形 P2P 传 KV,可与计算重叠 | 2 次 all-to-all(前后各一次)+ 反向对应 | all-gather KV |
| 并行度上限 | 不受头数限制 | ≤ 头数 / KV 头数 | 受 KV 总显存限制 |
| 适合 | 超长序列、跨节点 | 节点内、高带宽 | GQA 模型、复杂 mask |
Context parallelism shards the full sequence across GPUs, including attention. Ring Attention keeps the queries local and rotates key-value blocks around a ring, accumulating with the same online-softmax trick FlashAttention uses, so the transfer of the next block hides behind the current block's compute. Ulysses takes a different route: an all-to-all switches from sequence sharding to head sharding, each GPU runs ordinary attention on its heads over the whole sequence, and a second all-to-all switches back. Ulysses is simple and fast within a node, but its degree is capped by the number of heads.
Expert Parallel:MoE 的 all-to-all
不同专家放在不同卡上;每层 MoE 先 all-to-all 把 token 发到对应专家所在的卡(dispatch),专家计算后再 all-to-all 发回(combine);通信量和 top-k 成正比,在关键路径上,负载不均会导致等待。
Expert parallelism places different experts on different GPUs; each MoE layer does an all-to-all to dispatch tokens to their experts and another to combine the results, with traffic proportional to top-k and sitting on the critical path.
- 每层通信:每个 token 的 hidden 向量被发给 \(k\) 个专家:dispatch 约 \(k\cdot s b\cdot h\cdot 2\) 字节,combine 同样大小;反向再来两次。例:每卡 8192 token、\(h=7168\)、top-8、bf16 → 每次 dispatch 约 0.94 GB。
- 负载均衡:某个专家过热,它所在的卡成为瓶颈,所有卡等它。对策:负载均衡辅助损失、capacity factor(超出容量的 token 丢弃或溢出)、DeepSeek-V3 的无辅助损失 bias 调节(见 模块 04 §7)。
- 限制跨节点:DeepSeek-V3 限制每个 token 最多发往有限个节点(node-limited routing),以控制跨节点 all-to-all 的量。
- 和其他并行组合:attention 部分通常用 DP(或 TP),MoE 部分用 EP;EP 组常与 DP 组重叠(专家参数不复制,非专家参数复制)。
With expert parallelism, each GPU hosts a subset of experts. After routing, an all-to-all sends each token's hidden state to the GPUs holding its top-k experts, the experts run, and a second all-to-all brings the outputs back. The traffic scales with k and with hidden size, and it sits on the critical path, so you try to keep it within a node or limit how many nodes each token can reach. Load balance matters a lot, because the slowest expert sets the pace for the whole layer.
3D/4D/5D 并行:怎么选布局
总卡数 = TP × CP × PP × DP(MoE 再加 EP);从内到外按通信强度排:TP(节点内,≤8)→ CP → PP(跨节点,让 model states 放得下)→ DP/FSDP(最外层,扩吞吐);先满足显存,再最小化 bubble 和暴露通信。
Total GPUs = TP × CP × PP × DP, plus EP for MoE; order them from most to least communication-intensive, with TP inside a node, then CP, then PP across nodes to fit memory, then DP or FSDP outermost for throughput.
决策顺序(面试时按这个说):
- 能不能只用 FSDP/ZeRO?中小模型(≲ 10–30B)在几十到几百张卡上,FSDP(或 HSDP)往往就够了,最简单,MFU 也高。
- 单层或单卡 activation 太大 / ZeRO-3 通信太多?加 TP(节点内,2/4/8),配合 SP。
- TP=8 之后 model states 仍放不下,或者 ZeRO-3 跨节点 all-gather 太慢?加 PP(跨节点),保证 \(m \gg p\)。
- 序列很长(≥ 32k–128k)?加 CP。
- MoE?加 EP(与 DP 组重叠)。
- 剩下的卡全部给 DP(可以叠加 ZeRO-1 切优化器状态)。
LLaMA-3 405B 的实际配置(Llama 3 论文 Table 4):
| GPUs | TP | CP | PP | DP | 序列长度 | tokens/batch | TFLOPs/GPU | BF16 MFU |
|---|---|---|---|---|---|---|---|---|
| 8,192 | 8 | 1 | 16 | 64 | 8,192 | 16M | 430 | 43% |
| 16,384 | 8 | 1 | 16 | 128 | 8,192 | 16M | 400 | 41% |
| 16,384 | 8 | 16 | 16 | 8 | 131,072 | 16M | 380 | 38% |
注意:tokens/batch 固定为 16M,卡数翻倍后每个 DP rank 的 batch 减半,pipeline 的 micro-batch 变少,bubble 变大,MFU 从 43% 降到 41%。长上下文阶段 CP=16 吃掉了大部分 DP 维度。
Worked example:70B 稠密模型,1024 张 80 GB H100,\(s=4096\)(近似推理)
- 模型:\(L=80,\ h=8192,\ a=64\),GQA 8 个 KV 头。model states \(16\times70\text{B}=1120\) GB。
- TP=8(节点内,KV 头数 8 正好整除)。PP=4(每 stage 20 层)。DP = 1024/32 = 32,DP 上叠加 ZeRO-1。
- 每卡 bf16 参数 + 梯度:\(4\times70\text{B}/(8\times4) = 8.75\) GB;fp32 优化器状态(ZeRO-1 再除以 32):\(12\times 70\text{B}/(32\times32)\approx 0.82\) GB。
- activation:TP+SP+selective,每层 \(34sbh/t = 34\times4096\times8192/8 \approx 143\) MB;每 stage 20 层;1F1B 下 stage 0 最多 4 个在飞 → \(\approx 11.4\) GB。
- 合计约 21 GB + logits/buffer,远小于 80 GB → 可以增大 micro-batch 或减小 PP(例如 PP=2 让 bubble 更小),甚至考虑 FSDP + TP 不用 PP。
- batch:4M tokens/step = 1024 条序列;每个 DP rank 32 条;micro-batch=1 → \(m=32\),bubble \(=3/35\approx 8.6\%\)。
(这些数字由 §9 的 layout70b.py 计算。真实系统还要考虑 logits、通信 buffer、负载均衡,这里的目的是展示推理过程。)
I'd pick the layout by communication intensity. Tensor parallel goes innermost, within a node and at most eight. Context parallel comes next if sequences are long. Pipeline parallel spans nodes when model states still don't fit. Data parallel, usually with ZeRO-1 or FSDP, takes everything that's left. The order of questions is: does it fit, then is the bubble small, meaning enough micro-batches per pipeline, then is communication hidden. Llama 3 405B is a good reference: TP 8, PP 16, and the rest data parallel, at around 40 percent MFU on sixteen thousand H100s.
- Why did Llama 3's MFU drop when they doubled the GPU count at fixed batch size?
思路
tokens/batch 固定 16M,DP 从 64 变 128,每个 DP rank 的序列数从 32 减到 16 → 每个 pipeline 的 micro-batch 数减半 → bubble 增大;同时 DP 通信涉及更多节点。这说明 batch size(受优化限制)是扩展的硬约束。 - DeepSeek-V3 used no tensor parallelism. Why might that be a good choice?
思路
MoE 模型每 token 激活参数少(V3 激活约 37B),通过 PP 16 + EP 64 + ZeRO-1 DP 已经能放下;TP 每层都要 all-reduce,开销大。省掉 TP 把节点内带宽留给 EP 的 all-to-all,再配合 DualPipe 隐藏通信。论文明确说显存优化使他们无需使用代价高昂的 TP。
§7 · MEMORY TRICKS省显存技巧
并行是"用更多卡分摊";这一节的技巧是"在同样的卡上用更少显存",通常用计算或精度换显存。
Activation checkpointing(重计算)
前向时只保存部分张量(例如每层的输入),反向时重新前向计算出需要的中间结果;full checkpointing 约多一次前向(约 +33% 计算),把 activation 从每层 \(\sim34sbh\) 降到 \(2sbh\);selective 只重算便宜但占显存的部分(attention 分数)。
Activation checkpointing saves only some tensors, such as each layer's input, and recomputes the rest during backward; full checkpointing costs roughly one extra forward pass, about 33% more compute, while selective checkpointing recomputes only the cheap but memory-hungry parts.
为什么是约 33%:前向 FLOPs ≈ \(2N\) 每 token,反向 ≈ \(4N\)(对输入和对权重各一次矩阵乘),总 \(6N\)。full recompute 多一次前向 \(2N\),总 \(8N\),增加 \(2/6 \approx 33\%\)。(这也是 HFU 和 MFU 不同的来源之一:HFU 把重计算的 FLOPs 算进去,MFU 不算。)
显存:每层只存输入 \(2sbh\) 字节;反向到某层时,重新前向这一层,峰值额外需要这一层完整的 activation(\(\sim 34sbh\))。所以总量 ≈ \(L\cdot 2sbh + 34sbh\)。
经典的 \(\sqrt{L}\) 方案:(Chen et al. 2016, Training Deep Nets with Sublinear Memory Cost)每 \(\sqrt{L}\) 层存一个 checkpoint,显存 \(O(\sqrt{L})\),计算多一次前向。实践中 LLM 一般按 Transformer block 粒度做 checkpointing。
Selective recomputation(Korthikanti et al.):只重算 attention 中的 \(QK^\top\)/softmax/dropout/\(\times V\)(显存 \(5as^2b\) 大但 FLOPs 相对小)。FlashAttention 本身在反向时重算 attention,所以用了 FlashAttention 后这部分自然实现了。
什么时候用:先尝试不重计算;放不下时先 selective(或者只对部分层做 full checkpoint),最后才全部层 full checkpoint。有时"减小 micro-batch + 不重算"比"大 micro-batch + full 重算"更快,要实测。
PyTorch checkpoint 用法(需 torch,未运行)
# Activation checkpointing: same loss and gradients, fewer saved activations. Runs on CPU.
import torch
from torch.utils.checkpoint import checkpoint
class Block(torch.nn.Module):
def __init__(self, d):
super().__init__()
self.norm = torch.nn.LayerNorm(d)
self.ff = torch.nn.Sequential(torch.nn.Linear(d, 4 * d), torch.nn.GELU(), torch.nn.Linear(4 * d, d))
def forward(self, x):
return x + self.ff(self.norm(x))
class Net(torch.nn.Module):
def __init__(self, d=32, n=4, ckpt=False):
super().__init__()
self.blocks = torch.nn.ModuleList([Block(d) for _ in range(n)])
self.ckpt = ckpt
def forward(self, x):
for blk in self.blocks:
if self.ckpt and self.training:
# only the block input is saved; the block's internals are recomputed in backward
x = checkpoint(blk, x, use_reentrant=False)
else:
x = blk(x)
return x
torch.manual_seed(0)
a = Net(ckpt=False)
b = Net(ckpt=True); b.load_state_dict(a.state_dict())
x = torch.randn(8, 16, 32)
la = a(x).pow(2).mean(); la.backward()
lb = b(x).pow(2).mean(); lb.backward()
assert torch.allclose(la, lb)
for p, q in zip(a.parameters(), b.parameters()):
assert torch.allclose(p.grad, q.grad, atol=1e-6)
print("checkpoint OK")
断言 checkpoint 版本和普通版本的 loss 和所有梯度一致。本环境没有 torch,未运行(保存为 torch_tests/04_checkpoint.py)。注意:带 dropout 的块做重计算时,PyTorch 默认会保存并恢复 RNG 状态,以保证重算时 dropout mask 相同(preserve_rng_state=True)。
Activation checkpointing trades compute for memory. In the forward pass you keep only each block's input and drop the internals, then recompute them during backward. Full checkpointing adds roughly one extra forward pass. Forward is about a third of training FLOPs, so that's about thirty-three percent more compute, and in exchange activations shrink from tens of s·b·h bytes per layer to two. Selective recomputation is the smarter version: you recompute only the attention scores, which are huge in memory but cheap to compute. FlashAttention effectively does that for you already.
混合精度与 FP8
bf16 计算 + fp32 master/优化器是默认配置;FP8(E4M3 / E5M2)进一步把矩阵乘做成 8 位以提升吞吐,需要细粒度缩放因子和高精度累加,主要省计算时间和部分激活,不省 model states。
bf16 compute with fp32 master weights and optimizer is the default; FP8 GEMMs with E4M3 or E5M2 raise throughput further but need fine-grained scaling and high-precision accumulation, and they save compute rather than model-state memory.
- bf16 vs fp16:bf16 有 8 位指数(和 fp32 动态范围相同)、7 位尾数;fp16 有 5 位指数、10 位尾数。bf16 基本不需要 loss scaling,是 LLM 训练的默认选择。
- FP8 格式(Micikevicius et al. 2022, FP8 Formats for Deep Learning):E4M3(4 位指数、3 位尾数,范围较小、精度较高,常用于前向的权重和激活)和 E5M2(范围更大,常用于梯度)。H100 的 FP8 Tensor Core 峰值约是 bf16 的 2 倍。
- 缩放:FP8 动态范围窄,需要缩放因子。per-tensor 缩放容易被离群值破坏;DeepSeek-V3 用细粒度缩放:激活按 1×128 的 tile、权重按 128×128 的 block 分别缩放,并且每累加 128 个元素就把部分和提升到 FP32 做累加。
- FP8 不省什么:master weights 和优化器状态仍是高精度,所以 16 B/参数的 model states 基本不变;省的是 GEMM 时间和部分激活显存/通信。
The default recipe is bf16 compute with fp32 master weights and optimizer states, and bf16's wide exponent means you usually don't need loss scaling. FP8 goes a step further by running the big matmuls in eight bits, roughly doubling peak throughput on H100. The difficulty is the narrow dynamic range, so you need fine-grained scaling, such as per-tile or per-block scales like DeepSeek-V3 used, and you accumulate in higher precision. It speeds up compute, but it doesn't shrink the optimizer state, which stays in high precision.
Fused kernels、FlashAttention 与其他技巧
FlashAttention 去掉 \(O(s^2)\) 的 attention 激活;fused kernel(融合 LayerNorm、SwiGLU、RoPE、cross-entropy)减少中间张量和显存读写;chunked/fused CE 避免 materialize 完整 logits;8-bit 优化器、offload 进一步压缩 model states。
FlashAttention removes the quadratic attention activations; fused kernels for norms, activations, RoPE and cross-entropy cut intermediate tensors and memory traffic; chunked cross-entropy avoids materializing full logits.
- FlashAttention:分块(tiling)+ online softmax,把 \(QK^\top\) 留在 SRAM 里,不写回 HBM;反向重算。activation 从 \(O(as^2b)\) 降到 \(O(sbh)\)(只多存每行的 logsumexp)。FLOPs 不变甚至略增,但因为 IO 少所以更快。细节见 模块 04 §8。
- Kernel fusion:逐元素操作(bias + GeLU、残差 + LayerNorm、SwiGLU 的 silu(a)·b)融合成一个 kernel,减少 HBM 读写和中间张量;
torch.compile能自动做一部分。 - Fused / chunked cross-entropy:大词表下 logits(\(s\times V\))及其梯度很大;分块计算 loss 和梯度,或者把 LM head 的矩阵乘和 CE 融合,避免一次性存下全部 logits。
- 8-bit 优化器 / Adafactor:压缩或分解优化器状态。
- CPU offload:见 §3。
Beyond parallelism, the big memory wins come from kernels. FlashAttention removes the quadratic attention activations by keeping the score tiles in on-chip SRAM and recomputing them in backward. Fusing elementwise ops like the residual add and norm, or SwiGLU, cuts both intermediate tensors and memory bandwidth. And with large vocabularies, a chunked or fused cross-entropy avoids ever materializing the full logits tensor, which can take several gigabytes at long context.
§8 · EFFICIENCY METRICS效率指标:MFU 与可靠性
"你的训练跑得好不好"的标准答案是 MFU。它把吞吐(tokens/s)换算成"实际有用 FLOPs 占硬件峰值的比例",可以跨模型、跨硬件比较。面试常让你现场算 MFU,或者给你一个低 MFU 让你排查。
MFU vs HFU
MFU = 观测吞吐(tokens/s)× 每 token 模型所需 FLOPs(≈ 6N,可加 attention 项)÷(GPU 数 × 单卡峰值 FLOPs);HFU 把重计算等额外执行的 FLOPs 也算进去,所以 HFU ≥ MFU。
MFU is observed tokens per second times the model FLOPs per token, about 6N plus an attention term, divided by the aggregate peak FLOPs; HFU also counts recomputation, so HFU is at least MFU.
定义来自 PaLM (Chowdhery et al. 2022) §4.1:MFU 是观测吞吐与"峰值 FLOPs 下理论最大吞吐"之比,理论值只计前向+反向所需的运算,不计重计算。HFU 计入设备实际执行的所有 FLOPs(包括重计算),PaLM 认为它依赖实现、不够一致。
$$\text{MFU}=\frac{\text{tokens/s}\times F_{\text{token}}}{N_{\text{GPU}}\times \text{peak FLOPs}},\qquad F_{\text{token}}\approx 6N + 12\,L\,d\,s$$- \(6N\):前向 \(2N\) + 反向 \(4N\)(推导见 模块 04 §5)。这里 \(N\) 通常指不含 embedding 查表的参数(LM head 矩阵乘要算)。
- \(12Lds\):attention 的 \(QK^\top\) 和 \(\times V\)(与参数无关)。PaLM 附录用 \(6N + 12LHQT\)(\(H\cdot Q = d\),\(T\) 为序列长度)。因果 mask 下实际只需一半,有些代码库会除以 2;报告时要说明口径。
- HFU 在 full recompute 时的分子用 \(8N\)(多一次前向)。
Worked example:7B 模型,H100(bf16 稠密峰值约 989 TFLOPs),每卡 10,000 tokens/s,\(s=4096,\ L=32,\ d=4096\):
- 只算 6N:\(6\times7\times10^9\times10^4 / 989\times10^{12} \approx 42.5\%\)。
- attention 项:\(12\times32\times4096\times4096 \approx 6.4\times10^9\) FLOPs/token,约为 6N 的 15%;加上后 MFU ≈ 49%。
可见 attention 项在长序列时不可忽略,两种口径下的 MFU 可以差好几个百分点。
参考数字(谨慎引用):
- PaLM 540B(6144 TPU v4):MFU 46.2%(含 attention),HFU 57.8%;同表中 GPT-3 为 21.3%,Gopher 32.5%,MT-NLG 30.2%(PaLM Table 3 的估算)。
- Megatron-LM 2021:1T 参数模型在 3072 张 A100 上达到 502 PFLOP/s,每卡为理论峰值的 52%(Narayanan et al. 2021)。
- Korthikanti et al.:530B 模型在 2240 张 A100 上 MFU 54.2%,对比 full recompute 时 42.1%。
- LLaMA-3 405B:16K H100 上 BF16 MFU 38–43%(见 §6 表)。
经验:大规模稠密模型训练 MFU 在 35–55% 算正常;低于 30% 值得排查;MoE 由于 all-to-all 和较小的专家 GEMM,MFU 通常更低。
MFU, or model FLOPs utilization, is the useful model FLOPs you actually achieve divided by the hardware peak. You take tokens per second, multiply by about 6N FLOPs per token, plus an attention term at long context, and divide by the number of GPUs times peak FLOPs. Hardware FLOPs utilization also counts recomputation, so it's always higher and a bit flattering. For large dense training, somewhere around forty to fifty percent is good. PaLM reported about 46 percent and Llama 3 about 38 to 43 percent on H100s.
- How long would it take to train a 7B model on 2T tokens with 1024 H100s at 40% MFU?
思路
总 FLOPs \(=6ND = 6\times7\times10^9\times2\times10^{12}=8.4\times10^{22}\)。有效算力 \(1024\times989\times10^{12}\times0.4\approx4.05\times10^{17}\) FLOP/s。时间 \(\approx2.07\times10^5\) s ≈ 2.4 天。
MFU 低的排查清单
先 profile 看时间花在哪:数据加载、暴露的通信、pipeline bubble、小 GEMM / kernel launch 开销、重计算、stragglers;按"最大块先解决"的顺序处理。
Profile first and find where the time goes: data loading, exposed communication, pipeline bubbles, small GEMMs or launch overhead, recomputation, or stragglers; then fix the biggest bucket first.
- 数据加载:GPU 是否在等数据?看 step 之间的空隙;增加 dataloader worker、预取、预先 tokenize。
- 暴露的通信:用 PyTorch profiler / Nsight 看 NCCL kernel 是否和计算重叠。TP 跨节点?FSDP 的 all-gather 没有 prefetch?DP bucket 太小?
- Pipeline bubble:\(m/p\) 太小?stage 不均衡(最后一个 stage 有大词表 LM head)?
- GEMM 效率:micro-batch 太小或 TP 太大导致矩阵很"瘦";维度不是 64/128 的倍数;大量逐元素 kernel 没融合,kernel launch 开销显著(可用
torch.compile、CUDA graphs)。 - 重计算:full checkpointing 吃掉约 25% 的时间;能否改成 selective,或者用 TP/SP/CP 腾出显存后关掉。
- Stragglers:某张卡或某个节点慢(降频、过热、网络链路差、MoE 负载不均),所有卡在同步点等它。逐 rank 记录 step 时间找出离群者。
- 其他:频繁的
.item()/CPU 同步、日志、checkpoint 保存阻塞训练、垃圾回收停顿。
If MFU is twenty percent, I wouldn't guess. I'd take a profiler trace of a few steps and break down where the time goes. The usual suspects are the data loader starving the GPU, communication that isn't overlapped, like tensor parallel across nodes or FSDP without prefetch, pipeline bubbles from too few micro-batches, and matmuls that are too small because the micro-batch or TP degree is off. Then there's recomputation overhead and stragglers. I'd fix the biggest bucket first and re-measure.
Stragglers、checkpoint 与容错
大规模训练中硬件故障是常态(LLaMA-3 54 天里有 419 次非计划中断,约 78% 归因于硬件问题);需要频繁、快速(异步、分片)的 checkpoint,自动检测和替换坏节点,以及快速重启。
At scale, failures are routine — Llama 3 saw 419 unexpected interruptions in 54 days — so you need frequent, fast, sharded asynchronous checkpoints and automated detection, replacement and restart.
- LLaMA-3 报告:54 天的快照期间共 466 次中断,其中 47 次计划内、419 次非计划;非计划中断中约 78% 归因于已确认或疑似的硬件问题,GPU 问题占 58.7%(Llama 3 论文 §3.3)。
- Checkpoint 间隔:Young 的近似公式 \(T_{\text{opt}}\approx\sqrt{2\,C\cdot \text{MTBF}}\)(\(C\) 为保存一次 checkpoint 的时间)。例:\(C=5\) 分钟、MTBF=3 小时 → 约 42 分钟。
- 快速 checkpoint:每个 rank 只保存自己的分片(distributed checkpoint);先异步拷到 CPU 内存再后台写盘,训练不阻塞。
- Stragglers:同步训练里最慢的卡决定速度;监控每 rank 的 step 时间,剔除慢节点。
- 静默数据损坏(SDC):硬件算错却不报错,表现为 loss 异常;可以用确定性重放、跨副本校验来检测。
At the scale of thousands of GPUs, failures are routine rather than exceptional. Llama 3 reported over four hundred unexpected interruptions in about two months, mostly hardware. So you checkpoint often and asynchronously, with each rank writing its own shard. You detect and swap out bad nodes automatically, and you watch per-rank step times, because in synchronous training a single straggler slows everyone down.
§9 · CODE代码:用 numpy 模拟分布式
面试里很少要求写真正的 NCCL 代码,但"用单进程模拟 N 个 worker"是理解和验证各种并行的好方法,也可能作为 ML coding 题出现。下面所有 numpy / 纯 Python 代码都已实际运行通过;torch 代码是参考,本环境没有 torch,未运行,已明确标出。
四个已运行的模拟
ring all-reduce == 求和且每卡发送 \(2(N-1)S/N\);column→row 并行 MLP == 不分片 MLP;ZeRO 分片 Adam == 不分片 Adam;事件驱动的 GPipe/1F1B 模拟验证 bubble 公式和峰值显存。
Four verified simulations: ring all-reduce equals the sum with 2(N−1)/N·S traffic per GPU, the column-then-row parallel MLP matches the unsharded one, ZeRO-sharded Adam matches plain Adam, and an event simulation confirms the bubble formula and 1F1B's memory advantage.
1. Ring all-reduce:代码在 §2 Ring all-reduce 的折叠框里。2. Tensor parallel MLP:在 §4。3. ZeRO 分片 Adam:在 §3。4. 显存/bubble/MFU 计算器:在 §1。下面是 pipeline 调度模拟和 70B 布局计算。
Pipeline 调度模拟:GPipe vs 1F1B(已运行)
# Event simulation of GPipe and 1F1B: forward of 1 micro-batch on 1 stage = 1 unit, backward = 2 units.
def simulate(p, m, schedule):
# per-stage ordered list of ops
ops = []
for s in range(p):
if schedule == "gpipe":
seq = [("F", i) for i in range(m)] + [("B", i) for i in reversed(range(m))]
else: # 1F1B: warmup p-s-1 forwards, then alternate, then cooldown backwards
w = min(p - s - 1, m)
seq = [("F", i) for i in range(w)]
f, b = w, 0
while b < m:
if f < m:
seq.append(("F", f)); f += 1
seq.append(("B", b)); b += 1
ops.append(seq)
done = {}; t_stage = [0] * p; idx = [0] * p
inflight_max = [0] * p
progress = True
while progress:
progress = False
for s in range(p):
while idx[s] < len(ops[s]):
kind, i = ops[s][idx[s]]
dep = (("F", i, s - 1) if s > 0 else None) if kind == "F" else (("B", i, s + 1) if s < p - 1 else ("F", i, s))
if dep is not None and dep not in done:
break
start = max(t_stage[s], done[dep] if dep else 0)
dur = 1 if kind == "F" else 2
t_stage[s] = start + dur; done[(kind, i, s)] = t_stage[s]; idx[s] += 1; progress = True
nf = sum(1 for (k, j, ss) in done if ss == s and k == "F"); nb = sum(1 for (k, j, ss) in done if ss == s and k == "B")
inflight_max[s] = max(inflight_max[s], nf - nb)
assert all(idx[s] == len(ops[s]) for s in range(p))
T = max(t_stage); busy = 3 * m
return 1 - busy / T, inflight_max[0]
for p, m in [(4, 4), (4, 8), (8, 32)]:
bg, memg = simulate(p, m, "gpipe"); b1, mem1 = simulate(p, m, "1f1b")
th = (p - 1) / (m + p - 1)
print(f"p={p} m={m}: bubble gpipe={bg:.4f} 1f1b={b1:.4f} theory={th:.4f} | peak in-flight acts stage0: gpipe={memg} 1f1b={mem1}")
assert abs(bg - th) < 1e-9 and abs(b1 - th) < 1e-9
assert memg == m and mem1 == min(p, m)
print("pipeline sim OK")
输出:
p=4 m=4: bubble gpipe=0.4286 1f1b=0.4286 theory=0.4286 | peak in-flight acts stage0: gpipe=4 1f1b=4
p=4 m=8: bubble gpipe=0.2727 1f1b=0.2727 theory=0.2727 | peak in-flight acts stage0: gpipe=8 1f1b=4
p=8 m=32: bubble gpipe=0.1795 1f1b=0.1795 theory=0.1795 | peak in-flight acts stage0: gpipe=32 1f1b=8
pipeline sim OK
结论:两种调度的 bubble 都精确等于 \((p-1)/(m+p-1)\)(前向 1 单位、反向 2 单位的假设下),但 stage 0 的峰值在飞 micro-batch 数是 \(m\) 对 \(\min(p, m)\)。
70B / 1024 GPU 布局计算(已运行)
GB=1e9
N=70e9; L=80; h=8192; a=64; s=4096
TP,PP,DP=8,4,32
assert TP*PP*DP==1024
pg = 4*N/(TP*PP) # bf16 params + grads, sharded by TP*PP only
opt = 12*N/(TP*PP*DP) # ZeRO-1 over DP
act_layer = s*1*h*34/TP # TP+SP+selective, b=1
layers_per_stage = L//PP
inflight = PP # 1F1B stage 0
act = act_layer*layers_per_stage*inflight
print(f"params+grads {pg/GB:.2f} GB, opt {opt/GB:.2f} GB, act/layer {act_layer/1e6:.1f} MB, acts {act/GB:.2f} GB, total {(pg+opt+act)/GB:.1f} GB")
gb_tokens=4*2**20; seqs=gb_tokens//s; per_dp=seqs//DP
print("seqs",seqs,"per DP rank",per_dp,"bubble",(PP-1)/(per_dp+PP-1))
# 13B ZeRO-3 32 GPUs: layer all-gather temp
print("13B layer params bf16 GB (40 layers):", 13e9/40*2/GB)
# 70B on 64 GPUs FSDP + full ckpt
print("70B full ckpt inputs 80 layers s=4096:", 2*s*h*80/GB, "one layer full act (no flash, b=1):", s*h*(34+5*a*s/h)/GB, "with flash approx 34sbh:", 34*s*h/GB)
# OOM at 32k attention scores term
s2=32768; print("5as^2 per layer at 32k (a=32):", 5*32*s2*s2/GB)
# Young
import math; print("Young interval min (C=5min, MTBF=3h):", math.sqrt(2*5*180))
关键输出:params+grads 8.75 GB, opt 0.82 GB, act/layer 142.6 MB, acts 11.41 GB, total 21.0 GB;seqs 1024 per DP rank 32 bubble 0.0857;13B 每层 bf16 参数 0.65 GB;Young 公式 checkpoint 间隔约 42 分钟。
A good way to make sure I really understand a parallelism scheme is to simulate it in a single process with numpy. I keep N arrays as the workers, implement the sends as copies, and assert that the sharded result matches the unsharded one. For ring all-reduce I also count the bytes each worker sends and check it equals two times N-minus-one over N times the buffer size.
torchrun / DDP / FSDP 参考代码(未运行)
真实代码的骨架:torchrun 设置 RANK/WORLD_SIZE/LOCAL_RANK 环境变量 → init_process_group("nccl") → 包装模型(DDP 或 fully_shard)→ DistributedSampler → 正常训练循环 → destroy_process_group()。
The real skeleton is: torchrun sets the rank environment variables, you init the NCCL process group, wrap the model with DDP or fully_shard, use a DistributedSampler, run the normal loop, and destroy the group at the end.
DDP、collectives、FSDP2、checkpoint 的完整参考代码分别在 §3 DDP、§2、§3 FSDP、§7 的折叠框里,都保存为带断言的独立测试文件。下面是 GPU 节点上的典型骨架(参考,未运行):
# launch: torchrun --nnodes=2 --nproc_per_node=8 --rdzv_endpoint=$HOST:29500 train.py
import os, torch, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
dist.init_process_group("nccl") # reads RANK / WORLD_SIZE / MASTER_ADDR from env
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
model = build_model().cuda()
model = DDP(model, device_ids=[local_rank])
sampler = DistributedSampler(dataset, shuffle=True)
loader = DataLoader(dataset, batch_size=micro_bs, sampler=sampler)
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.1)
for epoch in range(epochs):
sampler.set_epoch(epoch) # different shuffle each epoch
for step, (x, y) in enumerate(loader):
x, y = x.cuda(non_blocking=True), y.cuda(non_blocking=True)
last = (step + 1) % accum == 0
ctx = model.no_sync() if not last else torch.enable_grad()
with ctx, torch.autocast("cuda", dtype=torch.bfloat16):
loss = model(x, y) / accum
loss.backward()
if last:
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step(); opt.zero_grad(set_to_none=True)
if dist.get_rank() == 0:
torch.save(model.module.state_dict(), "ckpt.pt")
dist.barrier()
dist.destroy_process_group()
build_model、dataset、micro_bs、epochs、accum 是占位符。
state_dict()),都会导致死锁或 NCCL 超时。The skeleton is always the same. torchrun launches one process per GPU and sets the rank environment variables. Each process initializes the NCCL group, pins its device, and wraps the model in DDP or FSDP. It uses a DistributedSampler so ranks see different data. The one rule you can't break is that every rank must issue the same collectives in the same order, otherwise you hang.
§10 · SCENARIOS面试场景题
每题先自己估算(写下数字),再看参考思路。答题模板:澄清假设 → 算 model states → 算 activations → 选并行方案 → 检查通信和 bubble → 说出风险。
12 道场景题
所有场景题都是同一个套路:16Ψ ÷ 切分份数 + activation ÷ 序列/张量切分 ≤ 显存 × 0.8,再看通信放在哪层网络、bubble 和 MFU 是否合理。
Every scenario follows one recipe: model states over the sharding factor plus activations over sequence or tensor sharding must fit in about 80% of memory; then check where communication lands and whether bubble and MFU are reasonable.
- You have 64 × 80 GB GPUs (8 nodes). How would you pretrain a 70B dense model at 4k context?
思路
model states:\(16\times70=1120\) GB,64 卡平均 17.5 GB/卡 → 必须把参数也切开(ZeRO-3/FSDP,或 TP×PP)。
方案 A:FSDP(ZeRO-3)+ activation checkpointing。每卡 model states 17.5 GB;ZeRO-3 时每层 bf16 参数 \(70\text{B}/80\times2\approx1.75\) GB,prefetch 时两层约 3.5 GB;activation(FlashAttention、full checkpoint,\(b=1\)):每层输入 \(2sbh=67\) MB × 80 ≈ 5.4 GB,加一层的工作集约 1.1 GB;logits(vocab 32k、fp32)约 0.5 GB。合计约 28 GB,能放下,可以把 micro-batch 提到 2–4。问题:每层 all-gather 1.75 GB 跨节点(IB),计算量小时通信可能暴露 → 用 HSDP 不行(节点内 8 卡 1120/8=140 GB 放不下)。
方案 B:TP=8(节点内)+ FSDP/ZeRO-1 跨 8 个节点。TP 后每卡参数 70B/8;跨节点 DP=8 再用 ZeRO-3:每卡 \(1120/64=17.5\) GB,但跨节点 all-gather 的数据量只有 1/8;或用 PP=2–4 + ZeRO-1。activation 用 TP+SP 除以 8,可以不做 full checkpoint。
答题要点:指出 1120 GB 这个数;给出至少一个可行方案并算出每卡显存;指出跨节点通信是瓶颈,所以 TP 放节点内;提到 global batch 和吞吐(64 卡训 70B 很慢:\(6\times70\text{B}\times1\text{T tokens}\) / (64 × 989T × 0.4) ≈ 1.7 × 10⁷ s ≈ 190 天/每 1T token——这个数字本身说明 64 卡更适合做 fine-tuning 或继续训练)。
- Training a 7B model with FSDP on 8 GPUs works at 4k context but OOMs at 32k. What do you do?
思路
诊断:model states \(112/8=14\) GB 不变,问题在 activation。\(s\) 从 4k 到 32k,线性项 ×8,平方项 ×64。
- 先确认用了 FlashAttention(否则平方项每层约 172 GB,没有任何希望)。
- FlashAttention 下 activation ≈ \(34sbh\times L = 34\times32768\times4096\times32\approx146\) GB(\(b=1\))→ 开 full activation checkpointing:每层只存 \(2sbh\),32 层约 8.6 GB + 一层工作集约 4.6 GB ≈ 13 GB。
- logits:\(32768\times V\times4\) 字节,V=32k 时约 4.2 GB、V=128k 时约 16.8 GB → 用 chunked/fused cross-entropy。
- 还不够或太慢:加 context parallel(Ring Attention/Ulysses,CP=2–8 在节点内),把 \(s\) 切开。
- 减少碎片:
expandable_segments:True。
- Someone set up tensor parallelism of 16 across two nodes and throughput is terrible. Why?
思路
TP 每层前向 2 次、反向 2 次 all-reduce,每次 \(2sbh\) 字节,在关键路径上无法重叠;跨节点 IB 带宽约为 NVLink 的 1/10,延迟也高。而且 TP=16 让每卡矩阵乘更"瘦",GEMM 效率下降;GQA 的 KV 头数(如 8)不能被 16 整除,需复制。修复:TP=8 限制在节点内,跨节点用 PP 或 DP/FSDP。用数字说:70B、\(s=4096\),每层每次 all-reduce 约 67 MB,每 micro-batch 每卡要发送约 38 GB 的 TP 流量;NVLink 约 0.08 s,IB 约 0.75 s。 - Your job reports 20% MFU on a 30B dense model. Walk me through debugging.
思路
先确认 MFU 计算口径(峰值用的是否是 bf16 稠密 989 TFLOPs;tokens 是否去掉 padding)。然后 profile:(1) step 间 GPU 空闲 → 数据加载;(2) NCCL kernel 和计算不重叠 → FSDP prefetch、bucket 大小、TP 是否跨节点;(3) bubble → 检查 \(m/p\);(4) GEMM 太小 → 增大 micro-batch、减小 TP;(5) full checkpointing → 改 selective;(6) 某些 rank 慢 → straggler;(7) Python 开销 / 频繁同步 →torch.compile、减少.item()。见 §8 排查清单。 - How much memory per GPU for a 13B model with ZeRO-3 on 32 GPUs?
思路
model states:\(16\times13/32=6.5\) GB。ZeRO-3 临时:每层 bf16 参数(40 层)约 0.65 GB,prefetch 两层约 1.3 GB。activation(\(h=5120,\ L=40,\ s=4096,\ b=4\),FlashAttention,无重计算):\(34sbh\times L\approx114\) GB → 放不下;full checkpoint 后约 9.6 GB。所以答案:model states 6.5 GB,再加 activation,取决于 \(s\)、\(b\) 和是否重计算;在 \(b=4\) 时需要 checkpointing,总量约 18 GB 加上 logits 和余量。
要点:ZeRO-3 把 model states 切得很小,但不碰 activation,activation 往往成为新的瓶颈。
- Can you fine-tune a 7B model on a single 80 GB GPU? What are your options?
思路
全参数 + 标准 Adam:112 GB 放不下。选项:(1) LoRA:基座 bf16 14 GB + 少量 LoRA 状态 + activation(开 checkpointing)→ 可以;(2) QLoRA:基座 4-bit ≈ 3.5 GB;(3) 全参数 + 8-bit Adam(K≈6,约 70 GB 但 activation 空间紧张);(4) 全参数 + ZeRO-Offload(优化器在 CPU,GPU 约 28 GB + activation,但慢);(5) 无 master weights 的纯 bf16 训练(风险大)。 - You're scaling from 8K to 16K GPUs at a fixed 16M-token batch. What happens and what do you change?
思路
每个 DP rank 的 batch 减半 → pipeline 的 micro-batch 数减半 → bubble 变大;DP all-reduce/reduce-scatter 涉及更多节点,延迟上升。LLaMA-3 在这种情况下 MFU 从 43% 降到 41%。对策:用 interleaved schedule(增大 \(v\))、减小 PP 换更多 TP/CP、优化通信重叠;或者如果优化允许,增大 global batch(受 critical batch size 限制)。 - Your MoE model trains much slower than a dense model with the same active parameters. Why?
思路
(1) 每层两次 all-to-all(dispatch/combine)+ 反向两次,在关键路径上,跨节点时尤其慢;(2) 负载不均:热门专家所在的卡成为 straggler;(3) 每个专家分到的 token 少,GEMM 小、效率低;(4) 总参数量大,model states 和 checkpoint 更大。对策:EP 限制在节点内或 node-limited routing、负载均衡(aux loss 或 bias)、grouped GEMM、通信与计算重叠(DualPipe 类调度)。 - You need to train at 128k context. What changes in your parallelism setup?
思路
activation 线性项 ×32(相对 4k),FlashAttention 必须;attention FLOPs(\(12Lds\)/token)占比大幅上升,MFU 口径要包含它。加 context parallel(LLaMA-3 用 CP=16,基于 all-gather KV,利用 GQA 让 KV 小);保持 global batch 的 token 数不变时,序列数变少,DP 维度被 CP 占用。数据侧:document mask 要和 CP 兼容;负载均衡(因果 mask 下用 zigzag 切分)。 - Training throughput drops by half every few hours and recovers after a restart. What could it be?
思路
可能:某张卡过热降频或 ECC 错误(straggler);网络链路降级;显存碎片随时间增加,导致 allocator 频繁cudaFree/重新分配;内存泄漏(日志里累积了张量、Python 对象);数据加载器 worker 退化;checkpoint 保存阻塞。排查:逐 rank step 时间、nvidia-smi时钟和温度、memory_summary、NCCL 调试日志。 - DDP training hangs at the end of the first epoch. What would you check?
思路
各 rank 的 batch 数不同(数据集不能整除,drop_last未设)→ 一个 rank 多进行一次 all-reduce 等待其他人;只在 rank 0 上执行的 eval/保存代码里有 collective;有未使用的参数导致梯度 hook 永远不触发。设置NCCL_DEBUG=INFO、TORCH_DISTRIBUTED_DEBUG=DETAIL,并设置超时来定位。 - Should you use ZeRO-3 or tensor parallelism for a 13B model on 2 nodes of 8 GPUs?
思路
13B 的 model states 208 GB,16 卡 ZeRO-3 → 13 GB/卡,能放下。ZeRO-3 简单、和模型代码解耦、在中等规模下 MFU 往往不错;缺点是每层参数 all-gather 跨节点。HSDP(节点内 8 卡切分 → 26 GB/卡,跨节点复制)把频繁通信留在 NVLink,可能更快。TP 适合 activation 很大(长序列)或单层很大的情况;13B、4k 上下文一般不需要。结论:先 FSDP/HSDP,profile 后再决定是否加 TP=2–4。
For any of these questions I follow the same recipe out loud. First I state assumptions, like bf16 with Adam and 4k context. Then I compute model states at sixteen bytes per parameter and divide by the sharding factor. Next come activations per layer and how sequence or tensor sharding cuts them. Then I check where the communication lands, inside a node or across nodes, and whether the pipeline has enough micro-batches. I finish with risks and what I'd measure first.
§11 · EXERCISES练习
全部是数值题,参考答案中的数字都由 Python 计算过(见 scratch 中的 exercises.py、calc.py)。一定要先用纸笔算。
一个 1.3B 模型用混合精度 Adam 训练,model states 多大?用 ZeRO-2 在 8 卡上,每卡 model states 多大?
提示
参考答案
7B 模型在 8 卡上,分别用 ZeRO-1、ZeRO-2、ZeRO-3,每卡 model states 是多少?
提示
参考答案
8 张卡的 NVLink(单向每卡约 450 GB/s)上 all-reduce 14 GB 梯度(7B 的 bf16 梯度),理想 ring 时间是多少?如果是 64 张卡、瓶颈链路约 50 GB/s 呢?(忽略延迟项)
提示
参考答案
p=8 个 stage,m=8 个 micro-batch 时 bubble 占比是多少?m=64 呢?m=64 且 interleaved v=2 呢?
提示
参考答案
用 Korthikanti 公式计算 \(s=2048,\ b=1,\ h=4096,\ a=32\) 时每层 activation(无并行),以及 attention 平方项占多少。
提示
参考答案
用 1024 张 H100(bf16 峰值 989 TFLOPs),MFU 40%,在 2T tokens 上训练 7B 模型要多久?
提示
参考答案
7B 模型(\(L=32,\ d=4096\)),\(s=4096\),每张 H100 每秒处理 10,000 tokens。分别只用 6N 以及加上 attention 项 \(12Lds\) 计算 MFU。
提示
参考答案
70B 模型(\(h=8192\)),TP=8,\(s=4096,\ b=1\)。每次 TP all-reduce 的数据多大?每层前向+反向共几次?80 层每个 micro-batch 每卡发送多少字节?在 450 GB/s 上大约多少时间?
提示
参考答案
8 张 80 GB 卡用 ZeRO-3,只看 model states(不留 activation 空间),最大能训多大的模型?
提示
参考答案
目标 global batch 为 4M tokens(\(2^{22}\)),\(s=4096\),64 个 DP rank,显存只放得下 micro-batch=2。需要累积几步?
提示
参考答案
LLaMA-3 风格的词表 \(V=128{,}256\),序列长 32k、\(b=1\),完整 logits 用 fp32 存需要多少显存?bf16 呢?
提示
参考答案
MoE 层:每卡 8192 个 token,\(h=7168\),top-8 路由,bf16。每次 dispatch all-to-all 每卡要发出多少数据(上界,假设所有专家都在其他卡上)?每层前向+反向共几次 all-to-all?
提示
参考答案
Checkpoint 一次需要 5 分钟,集群平均每 3 小时发生一次故障。按 Young 公式,最优 checkpoint 间隔约为多少?
提示
参考答案
证明 ZeRO-1/2 每 step 的通信量和 DDP 相同,而 ZeRO-3 是 1.5 倍(以每卡发送的参数个数为单位)。
提示
参考答案
§ · CHEAT SHEET一页速查
面试前一晚看这一页。
| 主题 | 必须记住 |
|---|---|
| Model states | 混合精度 Adam:2 (bf16 W) + 2 (bf16 g) + 12 (fp32 master, m, v) = 16 B/参数;7B → 112 GB;70B → 1120 GB |
| Activation / 层 | \(sbh(34 + 5as/h)\) 字节(Korthikanti);FlashAttention 去掉平方项;full ckpt 只存 \(2sbh\);TP+SP+selective:\(34sbh/t\) |
| Ring all-reduce | 每卡发送 \(2\frac{N-1}{N}S\);时间 \(2(N-1)\alpha + 2\frac{N-1}{N}S/B\);all-reduce = reduce-scatter + all-gather |
| ZeRO | Z1: \(4\Psi + 12\Psi/N\);Z2: \(2\Psi + 14\Psi/N\);Z3: \(16\Psi/N\)。通信:Z1/Z2 = DDP (\(2\Psi\));Z3 = 1.5× (\(3\Psi\)) |
| TP (Megatron) | MLP:A 列切 → GeLU 本地 → B 行切 → 1 次 all-reduce;attention 按头切;每层 4 次 all-reduce(前向 2、反向 2),每次 \(2sbh\);节点内,≤ 8 |
| SP (Megatron) | all-reduce → RS + AG,切 LayerNorm/dropout 的激活,通信不变 |
| PP | bubble \(=\frac{p-1}{m+p-1}\)(interleaved:\(\frac{p-1}{vm+p-1}\));1F1B 峰值 activation \(p\) 份(GPipe \(m\) 份);zero bubble:拆分 B / W |
| CP | Ring Attention(KV 环形传递 + online softmax);Ulysses(all-to-all,≤ 头数);LLaMA-3:all-gather KV |
| EP | 每层 2 次 all-to-all(dispatch/combine),量 \(\propto k\cdot sbh\) |
| 布局顺序 | 内 → 外:TP → CP → PP → DP(LLaMA-3:[TP, CP, PP, DP]) |
| Checkpointing | full:约 +33% 计算(\(8N\) vs \(6N\));selective:只重算 attention 分数 |
| MFU | \(\frac{\text{tokens/s}\times(6N + 12Lds)}{N_{\text{GPU}}\times\text{peak}}\);HFU 含重计算;大规模稠密 35–55% 正常;PaLM 46.2%,LLaMA-3 405B 38–43% |
| 硬件(近似) | H100 bf16 稠密约 989 TFLOPs;NVLink4 约 450 GB/s 单向;IB NDR 约 50 GB/s;HBM3 约 3.35 TB/s |
| 训练时间 | \(T = 6ND / (N_{\text{GPU}}\cdot\text{peak}\cdot\text{MFU})\) |
| 有效 batch | micro × accum × DP;DDP 下用 no_sync;变长序列按 global token 数归一化 |
高频面试题清单
| 问题 | 答案位置 |
|---|---|
| How much GPU memory does it take to train a 7B model? Why 16 bytes per parameter? | 16 字节、四大块 |
| What dominates memory at long context, and how do you reduce it? | Activation 显存、checkpointing、CP |
| Explain ring all-reduce and its cost. | Ring all-reduce |
| Difference between all-reduce, reduce-scatter, all-gather, all-to-all? | 六种集合通信 |
| How does DDP work? Why buckets? | DDP |
| Explain ZeRO stages 1/2/3 — memory and communication. | ZeRO |
| FSDP vs DDP? What's HSDP? | FSDP |
| How does Megatron tensor parallelism split the MLP? Why column then row? | TP MLP |
| How is attention split under TP? | TP attention |
| What is sequence parallelism (Megatron) vs context parallelism? | SP、CP |
| Derive the pipeline bubble. How do 1F1B and interleaving help? | GPipe、1F1B、Interleaved |
| ZeRO-3 vs tensor parallelism — when to use which? | ZeRO、布局 |
| How would you lay out 3D/4D parallelism for a 70B model on N GPUs? | 布局、场景题 1 |
| Why keep TP within a node? | 硬件拓扑 |
| What's the cost of activation checkpointing? | Checkpointing |
| Define MFU. What's a good number? MFU vs HFU? | MFU |
| MFU is 20% — how do you debug? | 排查清单 |
| How does gradient accumulation interact with DDP and loss normalization? | 梯度累积 |
| How does expert parallelism communicate? Why is MoE training slower? | EP |
| What does FP8 training save and not save? | FP8 |
| How long would it take to train model X on Y GPUs? | MFU、练习 11.6 |
§ · RECALL自测卡片
先自己说出答案(最好用英文出声),再点开对照并打分。