Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 5 (Sep 14 and 16, 2026), slides
lecture5.pdf(107 slides), Parallelism Strategies: Scaling Transformers Across Many GPUs, Nodes, and Clusters. This lecture covers the slides’ foundations, the collectives, data parallelism, expert parallelism and ZeRO/FSDP. Tensor and pipeline parallelism and the multi-dimensional recipes are in Lecture 6. Spring 2026 taught the material as Lecture 4. Recommended readings (course schedule): Hugging Face, The Ultra-Scale Playbook; M. Shoeybi et al., Megatron-LM (2019); S. Rajbhandari et al., ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (2019); the interactive Pipeline-parallelism schedule visualizer. Other sources: S. Li et al., PyTorch Distributed: Experiences on Accelerating Data Parallel Training (VLDB 2020), for DDP’s buckets and overlap; Y. Zhao et al., PyTorch FSDP (VLDB 2023); R. Thakur, R. Rabenseifner, W. Gropp, Optimization of Collective Communication Operations in MPICH (2005), for ring, tree and halving-doubling; P. Patarasuk and X. Yuan, Bandwidth optimal all-reduce algorithms (2009); the NCCL documentation andnccl-testsperformance notes, for bus bandwidth; DeepSeek-AI, DeepSeek-V3 Technical Report (2024), for node-limited routing and its parallel layout; the DeepEP repository. Every number labelled measured comes fromcode/lecture05/on the author’s laptop; computed / model numbers come from the same code’s formulas. Code:code/lecture05/:collectives.py(α–β model + exact ring/tree simulators),dist_utils.py(realtorch.distributedprocesses),ddp_zero.py(DDP and ZeRO-1/2/3 from scratch),expert_parallel.py, and seven demos. Reading time: ~2.5 hours for the prose; ~30 minutes for the demos.
0. How to read this lecture
0.1 Learning goals
From the slides, for the part of the material in this lecture. After it you should be able to:
- Name the seam. Say what each strategy (DP, EP, FSDP/ZeRO; TP and PP next lecture) cuts, what each GPU then holds, and what it buys: capacity, throughput or latency.
- Predict the communication. Name the collective each strategy introduces, its volume, and whether its cost is dominated by startup (α) or by bandwidth (β).
- Do the memory accounting. Say what fills GPU memory in training (weights, gradients, optimizer state, activations) and in serving (weights, KV cache), and which strategy relieves which part.
- Reason about overlap. Say when gradient or parameter communication hides behind compute, and diagnose it when it does not.
- Separate training from serving. A choice that is good for training throughput can be bad for decode latency.
0.2 Prerequisites and scope
- Prerequisites: Lectures 1–3 for accounting: 16 B/param of training state, FLOPs per token, the roofline, MFU. Lecture 4 for MoE: routing, top-, the routed payload , load balance. The TinyTransformer of Lecture 1, which the code trains.
- Scope: the foundations (three objectives, where to cut), the collectives and their cost model, data parallelism, expert parallelism, and sharded state (ZeRO/FSDP/HSDP). Everything is implemented and measured across real processes on one laptop, and modelled for H100 clusters.
- Not in scope today: tensor, sequence and pipeline parallelism, interconnect topology in depth, and composing the axes into a mesh (Lecture 6). Context parallelism and the kernels behind it (Lecture 7). How a framework packages all of this (Lecture 8).
0.3 Section → code map
| Section | Idea | Code in code/lecture05/ |
|---|---|---|
| §2 | where to cut; what each GPU holds | 01_where_to_cut.py |
| §3.1–3.6 | collectives, ring vs tree vs hierarchy, the α–β model | collectives.py, 02_collectives_by_hand.py |
| §3.7 | real collectives between processes, measured | dist_utils.py, 03_real_collectives.py |
| §4 | DDP: buckets, overlap, accumulation, exactness | ddp_zero.py, 04_ddp_from_scratch.py, 07_dp_scaling_model.py (Parts A–B) |
| §5 | expert parallelism: AllToAll, stragglers, topology | expert_parallel.py, 06_expert_parallel.py |
| §6 | ZeRO-1/2/3, FSDP, HSDP | ddp_zero.py, 05_zero_from_scratch.py, 07_dp_scaling_model.py (Part C) |
0.4 Notation
As in Lectures 1–4: (model width), (layers or sequence length, from context), (tokens per step on one GPU), (experts per token), (routed experts), (achieved FLOP/s). New today:
| Symbol | Meaning |
|---|---|
| (or , ) | number of ranks in a group: processes, one per GPU |
| bytes in one collective (the full tensor a rank contributes or receives) | |
| startup time of one message (seconds) | |
| seconds per byte on the bottleneck link (one direction per GPU) | |
| number of parameters being synchronized | |
| bytes per parameter of weights, gradients, optimizer state | |
| gradient-accumulation micro-steps per optimizer step | |
| utilization of an EP group, mean load / max load |
1. Roofline thinking, extended to many GPUs
1.1 A third term
Lectures 2–3 bounded a step by its slowest resource, . Once a model runs on more than one GPU, a third resource appears: the interconnect (互联) between GPUs.
Every parallelism strategy (并行策略) shifts pressure among these three terms. It splits compute and memory across GPUs, and in return introduces communication. The question the slides repeat for every strategy: which term is on the critical path, and what did your strategy do to it? “Max” is the optimistic case, when communication overlaps perfectly with compute. When it does not overlap, the terms add, and much of this lecture is about telling the two cases apart.
1.2 What parallelism buys: three objectives
The slides name three things you might want from more GPUs:
- Capacity (容量): “does it fit?” Shard state across devices to avoid running out of memory.
- Throughput (吞吐量): tokens per second. Keep many GPUs busy (high MFU) and reduce step time.
- Latency (延迟): one request finishes fast. Minimize synchronization on the critical path.
The slides call this the big mental model: capacity is a memory problem, throughput is a utilization problem, latency is a critical-path communication problem. It is rough, but it tells you where to look first. An out-of-memory error is a capacity failure, and no amount of network bandwidth fixes it. Low MFU on 1,000 GPUs is a utilization failure. A slow decode step is a latency failure, usually a collective that cannot be hidden.
1.3 Training and serving weight them differently
| Training | Serving | |
|---|---|---|
| unit of work | optimizer step: forward + backward + gradient sync + update | request: prefill the prompt (batch-friendly), then decode one token at a time (sequential) |
| optimizes | throughput, cost per token, scaling efficiency | latency (TTFT, TPOT), then aggregate throughput |
| memory pressure | weights + gradients + optimizer state + saved activations (grow with and depth) | weights + KV cache (grows with batch and cached length); no optimizer state |
Both use the same strategies with the same names, but a trick that is good for training throughput can be actively risky for serving latency. The rest of the lecture keeps the two columns apart.
2. Where can you cut a Transformer?
2.1 Six seams
A parallelism strategy is a choice of seam (切分维度). Where you cut determines what each GPU stores and who must talk to whom. A decoder-only Transformer can be cut in six places:
| Seam | Strategy | Each GPU holds | Buys | Price |
|---|---|---|---|---|
| the batch, between sequences | DP (data parallel, 数据并行) | the full model + 1/N of the batch | throughput | average the gradients every step |
| each FFN, into experts | EP (expert parallel, 专家并行; needs MoE) | a few experts of every layer + everything else | parameter capacity | tokens travel to their experts and back; unlucky routing makes stragglers |
| every stored tensor | FSDP / ZeRO (sharded state, 分片状态) | 1/N of every parameter, gradient, optimizer state + 1/N of the batch | capacity for training state | weights reassembled layer by layer |
| inside each layer | TP (tensor parallel, Lecture 6) | 1/N of every weight matrix | capacity + latency | partial results exchanged inside every layer |
| the depth, between blocks | PP (pipeline parallel, Lecture 6) | a contiguous slab of layers | capacity across slow links | keep stages fed; per-request latency gets worse |
| the sequence | CP (context parallel, Lecture 7) | 1/N of the tokens of a sequence | long-context activations / KV | attention needs remote K/V |
Two facts about this table organize the next two lectures. First, DP is the only cut that leaves the model whole, and the only one whose main product is throughput; the other cuts buy capacity of some kind, and TP alone also buys latency. Second, every cut pays in communication: the rest of the lecture is about making those patterns precise.
Note that FSDP’s computation is exactly DP’s: the batch is split the same way. Only the storage is cut. The cut runs through the tensors, not through the network.
2.2 What fills the memory (demo 01)
The capacity question needs numbers. For training with mixed-precision AdamW, the ZeRO paper’s accounting is 16 bytes per parameter: bf16 weights (2) + bf16 gradients (2) + fp32 master weights, Adam and (4 + 4 + 4 = 12, the paper’s “K = 12”). Demo 01 applies it to three models on 80 GB H100s, of which ~72 GB is usable. All numbers are computed.
| Model (params) | DDP | ZeRO-1 | ZeRO-2 | ZeRO-3 / FSDP |
|---|---|---|---|---|
| Llama-3-8B (8.03 B), N = 64 | 128 GB ✗ | 33.6 GB ✓ | 17.8 GB ✓ | 2.01 GB ✓ |
| Llama-3-70B (70.6 B), N = 64 | 1.13 TB ✗ | 295 GB ✗ | 157 GB ✗ | 17.6 GB ✓ |
| DeepSeek-V3 (671 B), N = 512 | 10.7 TB ✗ | 2.70 TB ✗ | 1.36 TB ✗ | 21.0 GB ✓ |
Three lessons:
- DDP buys no capacity. Llama-3-8B needs 128 GB per GPU under DDP whether you have 8 GPUs or 512. Even an 8B model does not fit on one H100 for full training with Adam.
- The optimizer state is the biggest piece (12 of 16 B), so ZeRO-1 does most of the work for mid-sized models. But ZeRO-1/2 still replicate the bf16 weights, 141 GB for 70B, so only ZeRO-3 (or the model-parallel cuts of Lecture 6) fits it.
- Activations are not training state. For Llama-3-8B at 8,192 tokens, the activations of one sequence take 36.5 GB, even when attention is recomputed (“selective” recomputation; 380 GB keeping everything). Next to that, a 2 GB ZeRO-3 state on 64 GPUs is small. Sharding the state does nothing for activations. Full recomputation (2.15 GB, one layer input kept per layer) or sharding the sequence and the layer width (TP/SP/CP) does.
For serving, the same demo shows the other column: one Llama-3-70B replica with 32 requests of 8k tokens needs 141 GB of weights + 85.9 GB of KV cache = 227 GB, so at least 4 GPUs. Serving “data parallelism” means replicas (副本): it multiplies throughput, and never makes one copy smaller.
3. Collectives and their cost
3.1 Ranks and collectives
A distributed job is separate processes, one per GPU, called ranks (秩 / 进程编号). They share nothing but messages. Most of the communication in this lecture uses collectives (集合通信): operations that a whole group of ranks executes together, each contributing a tensor and receiving a result. The programming model is SPMD (single program, multiple data): every rank runs the same script on its own shard of data.
One rule makes collectives work, and breaking it makes them hang: every rank must call the same collectives, with the same sizes, in the same order. A collective cannot complete until all participants have joined. A rank that skips one, or calls them in a different order, leaves the others waiting forever: a hang (卡住 / 死锁), the most common distributed bug. It shows up again in DDP’s bucket order (§4.3).
3.2 The primitives
Each strategy is recognizable by the collective it adds:
| Primitive | What every rank ends with | First needed by |
|---|---|---|
| AllReduce (全规约) | the sum (or mean) of everyone’s tensors, the full tensor | DP: average gradients |
| ReduceScatter (规约-分散) | one shard () of the sum | ZeRO/FSDP: “my shard of the gradient” |
| AllGather (全收集) | the concatenation of everyone’s shards, the full tensor | FSDP: reassemble weights; TP |
| AllToAll (全交换) | chunk of every rank’s tensor (a distributed transpose) | EP: MoE dispatch and combine |
| SendRecv (点对点收发) | point-to-point: one rank’s tensor appears on another | PP: stage boundaries |
| Broadcast, Gather, Scatter | rooted versions: one rank sends to all, or all to one | initialization, checkpoints |
A key identity: AllReduce = AllGather(ReduceScatter(x)). The reduced result is first left sharded, one shard per rank; then the shards are copied everywhere. Many libraries implement AllReduce exactly this way. It matters because some consumers, such as a sharded optimizer, only need their shard. They can stop after the ReduceScatter and never materialize the full tensor (§6).
3.3 The α–β model
The slides’ first-order lens for any message:
- α, startup (启动开销): a fixed cost per message, covering kernel launch, driver overhead, routing setup and synchronization. The slides’ figures: NVLink/NVSwitch ≲ 1 µs; InfiniBand ~2–5 µs; RoCE Ethernet ~5–20 µs.
- β, inverse bandwidth: time per byte on the bottleneck link. An H100’s NVLink 4 is quoted as 900 GB/s, but that is the bidirectional total. A ring step sends and receives at the same time, so the number that limits it is the one-way 450 GB/s: β ≈ 2.2 ps/B. The slide derives 1.1 ps/B from the 900 GB/s figure; this lecture uses the one-way number throughout. An InfiniBand NDR 400 Gb/s NIC gives 50 GB/s per GPU, so β = 20 ps/B.
The crossover size (临界消息大小) separates two regimes. Below it a message is latency-bound (延迟受限): the fix is fewer messages, by batching or fusing them. Above it a message is bandwidth-bound (带宽受限): the fix is fewer bytes, by compressing or sharding them. With the numbers above, one NVLink message is latency-bound below 450 kB and one InfiniBand message below 150 kB.
A collective is a sequence of steps. In each step every rank sends one message in parallel, so
The primitive only says what each rank must end with. The algorithm the library picks decides the step count and the bytes, and therefore the cost.
3.4 The ring AllReduce, step by step (demo 02)
The ring arranges the ranks in a circle and cuts each tensor into chunks. Demo 02 runs it on 4 ranks with symbolic values, so each cell shows whose contributions it already contains (B:0+2+3 means chunk B summed over ranks 0, 2 and 3). The rule: in step , rank sends its partial sum of chunk to rank , which adds its own contribution. After the third and last reduce-scatter step:
chunk A chunk B chunk C chunk D
rank 0 A:0+1+2+3 B:0+2+3 C:0+3 D:0
rank 1 A:1 B:0+1+2+3 C:0+1+3 D:0+1
rank 2 A:1+2 B:2 C:0+1+2+3 D:0+1+2
rank 3 A:1+2+3 B:2+3 C:3 D:0+1+2+3
After steps, rank owns the complete chunk : that is a ReduceScatter. Three more steps forward each complete chunk around the ring, with copies only and no additions: that is an AllGather. Every rank now holds A:0+1+2+3 B:0+1+2+3 C:0+1+2+3 D:0+1+2+3.
Counting gives the slide’s formula. There are steps, and in each a rank sends one chunk of bytes:
Two consequences:
- Bandwidth-optimal. For large each rank sends bytes, no matter how many ranks there are. Demo 02 counts 1.97 at . No AllReduce algorithm can do better. Every rank’s data must reach every other rank, so each rank must send at least bytes in the reduce half and receive as much in the gather half. This is why NCCL uses rings for large tensors and why DDP’s cost barely grows with the GPU count.
- Startup grows with . It pays α times: 126 sequential steps at . Bigger groups hurt latency.
3.5 Tree, halving-doubling, hierarchy: when each wins
A binary tree (树形算法) reduces pairwise toward a root in rounds, then broadcasts back down, for steps. In its textbook form each step moves the whole tensor. Demo 02 counts 12 steps at , but the busiest rank sends . Recursive halving-doubling (递归减半/倍增, Rabenseifner) gets the best of both, steps and the ring’s bandwidth term, for power-of-two . NCCL’s real trees pipeline the tensor in pieces, which recovers most of the bandwidth.
Demo 02’s model numbers for AllReduce on 8 GPUs over NVLink and on 64 GPUs over InfiniBand:
| message | 8 GPUs NVLink: ring | tree | 64 GPUs IB: ring | tree | halving-doubling |
|---|---|---|---|---|---|
| 1 KiB | 14.0 µs | 6.01 µs | 378 µs | 36.2 µs | 36.0 µs |
| 1 MiB | 18.1 µs | 20.0 µs | 419 µs | 288 µs | 77.3 µs |
| 16 MiB | 79.2 µs | 230 µs | 1.04 ms | 4.06 ms | 697 µs |
| 1 GiB | 4.19 ms | 14.3 ms | 42.7 ms | 258 ms | 42.3 ms |
The slide’s rule, “large tensors: bandwidth decides, ring wins; small tensors (decode!): the step count decides, tree wins”, becomes quantitative. On 8 NVLink GPUs the ring beats the unpipelined tree above ~847 kB, and on 64 GPUs over InfiniBand above ~1.7 MB. One subtlety the demo exposes: a ring AllReduce stays latency-dominated far above the single-message crossover. The α term equals the β term at , which is 3.6 MB on 8 NVLink GPUs, not 450 kB. A 16 KiB message, the size of one decode token’s hidden state at , takes 14.1 µs on the ring, 99.5% of it startup. Remember that number for tensor parallelism in decode (Lecture 6).
Hierarchy. A cluster is not flat: 8 GPUs per node share NVLink, and nodes talk over the slower network. A hierarchical AllReduce (分层全规约) does a ReduceScatter inside each node (NVLink), then an AllReduce of each shard across nodes (each GPU on its own NIC, a rail (轨道)), then an AllGather inside the node. For 64 GPUs in 8 nodes, demo 02 compares it with one flat ring in which every step waits for the slowest hop:
| message | flat ring | hierarchical | speed-up |
|---|---|---|---|
| 1 MB | 419 µs | 64.7 µs | 6.5× |
| 16 GB (Llama-3-8B’s bf16 gradients) | 630 ms | 132 ms | 4.8× |
The network carries of the bytes per GPU, and only 14 slow-link startups happen instead of 126. NCCL’s parallel per-NIC rings recover the bandwidth part of this gap, but not the startups. The principle to keep: put the most frequent and largest traffic on the fastest links.
3.6 Floating point: same bits everywhere, not the sequential sum
The ring has a numerical side that matters for checking correctness (§4.6). Demo 02 runs it on random floats of mixed magnitude:
| ranks | all ranks bit-identical? | elements ≠ sequential sum | max relative difference |
|---|---|---|---|
| 2 | yes | 0 of 4,096 | 0 |
| 3 | yes | 562 | 2.5e-15 |
| 4 | yes | 1,029 | 1.9e-13 |
| 8 | yes | 1,711 | 4.2e-14 |
Every rank gets the same bits, because the all-gather half only copies. That is what keeps DP replicas identical. But with the result differs from adding the ranks in order, because floating-point addition is commutative but not associative (满足交换律但不满足结合律). exactly, but and can differ in the last bit, and the ring sums each chunk in a different rotated order. With two ranks there is only one possible sum, so the difference is exactly zero.
3.7 Real collectives between processes (demo 03)
dist_utils.run starts real processes joined by torch.distributed with the gloo backend. It is the CPU counterpart of NCCL, with the same calls and the same rank bookkeeping, over loopback TCP. Demo 03 times every primitive from 32 B to 16 MiB with 2, 4 and 8 ranks, using the best of N repetitions, each the time of the slowest rank. The measured shapes:
| 2 ranks | 4 ranks | 8 ranks | |
|---|---|---|---|
| smallest AllReduce (latency floor) | 150 µs | 488 µs | 1.03 ms |
| fitted AllReduce startup | 107 µs | 447 µs | 1.49 ms |
| AllReduce bus bandwidth at 16 MiB | 6.72 GB/s | 3.54 GB/s | 1.67 GB/s |
Bus bandwidth (总线带宽) is NCCL’s convention, for an AllReduce. It is the rate each rank’s link would have to run at if the library used a ring, and it can be compared directly with a link’s spec. Running a test like this (nccl-tests on a real cluster) is the first thing to do on a new node: if bus bandwidth is far below spec, no parallelism strategy will save you.
What survives, and what does not:
- The shape holds. Every collective has a flat latency floor up to tens of KiB, then grows linearly with the payload. The absolute numbers are far from NVLink’s: a 2-rank AllReduce starts up in ~107 µs, vs ~2 µs for a 2-GPU NVLink ring, and its bus bandwidth is ~70× lower (6.7 vs 450 GB/s), because every byte goes through the operating system’s TCP stack.
- Startup grows faster than (13.9× from 2 to 8 ranks instead of 7×), and bus bandwidth falls with . On a real fabric each GPU has its own link. Here all ranks share one CPU and one memory system, so more ranks means more competition.
- AllReduce = ReduceScatter + AllGather holds for the result, not for this library’s cost. gloo’s ReduceScatter takes 1.05–1.31× as long as its AllReduce at 16 MiB, where a ring ReduceScatter would take about half. So AR/(RS + AG) is 0.50–0.62 instead of ~1. We measured this; we did not trace gloo’s internals. NCCL implements ReduceScatter as the cheap half of the ring. The lesson is the slide’s: the primitive says what; the algorithm decides how much it costs, so measure the library you actually run on.
4. Data parallelism
4.1 The idea and why it needs communication
Suppose the model fits on one GPU and training is simply too slow. With GPUs the obvious plan is data parallelism (数据并行):
- keep a full copy of the model on every rank, a replica (副本);
- split each global batch into shards, one per rank;
- run forward and backward locally: no rank needs another rank’s tokens.
The replicas see different data, so they compute different gradients. If each applied its own, they would drift apart and we would no longer be training one model. The gradients must be averaged across ranks before the update, with one AllReduce per step. The average of the shard gradients is exactly the gradient of the mean loss over the whole global batch, so DP is plain large-batch SGD, just computed in pieces. DDP (DistributedDataParallel) is PyTorch’s implementation, and the baseline every other strategy is compared to.
What limits DDP:
- Memory: every GPU stores the full , and optimizer state (+ activations), so no capacity is gained (§2.2).
- Communication: per optimizer step, e.g. 16.1 GB of bf16 gradients for Llama-3-8B. That is once per step, not per layer, which is why DDP scales well when it fits.
4.2 Building DDP by hand (ddp_zero.py)
ddp_worker is about 60 lines, and every step is visible:
- Initial broadcast. Each rank deliberately initializes its model with a different seed, then all ranks Broadcast rank 0’s weights. Real DDP does the same in its constructor, so the replicas start identical whatever each process did before.
- Hooks. A hook on every parameter fires when its gradient is final (
register_post_accumulate_grad_hook). - Buckets. Gradients are grouped into buckets (梯度桶) in reverse parameter order, because backward produces the last layers’ gradients first. When all of a bucket’s parameters have fired, the bucket is ready.
- AllReduce. Each bucket is flattened and AllReduced, asynchronously if overlap is on. After backward, everything is waited for, divided by and written back into
.grad. - Update. An elementwise AdamW (
FlatAdam) updates a flat parameter buffer that the model’s parameters are views of, so there is no extra copy.
4.3 Buckets: amortize α, but start early
Most models have many parameter tensors: 39 in the TinyTransformer, hundreds in a real model. AllReducing each one as it arrives pays α for each. Packing them into buckets trades two things, as the slides put it: large enough to amortize α, small enough to start early and overlap. Demo 04 counts, with 4 ranks:
| bucket size | AllReduce calls per step | bytes sent per rank |
|---|---|---|
| 4 KiB | 39 (one per tensor: a tensor larger than the bucket gets its own) | 1.16 MB |
| 64 KiB | 16 | 1.16 MB |
| 1 MiB or 25 MiB | 1 | 1.16 MB |
Buckets change the number of calls, never the bytes: always , with parameters. For Llama-3-8B on 64 H100s over InfiniBand, the model gives:
| bucket | calls per step | time in startups | time in bandwidth |
|---|---|---|---|
| 1 MiB | 15,317 | 5.79 s | 632 ms |
25 MiB (PyTorch’s default bucket_cap_mb) | 613 | 232 ms | 632 ms |
| 100 MiB | 154 | 58.2 ms | 632 ms |
| 1 GiB | 15 | 5.67 ms | 632 ms |
Two implementation details that matter in practice. Buckets must be launched in index order even if a later one fills first: every rank must issue the same collectives in the same order (§3.1). And a parameter that receives no gradient in some step would leave its bucket waiting forever. PyTorch’s find_unused_parameters exists for models with such branches.
4.4 Overlap: when communication is “free”
Gradients appear layer by layer during backward, so the reduction of early buckets can run while later layers are still computing. The slides’ overlap view:
If , communication is mostly hidden and scaling is near-linear. If , the job becomes communication-bound (通信受限) and scaling efficiency collapses. In practice there is also a tail: the last bucket holds the first layers and the embedding, whose gradients arrive last, so its reduction can never hide.
Measured (demo 04, 4 ranks, the 1.16 M-parameter TIMING model):
| configuration | step time | exposed communication |
|---|---|---|
| no communication (lower bound) | 11.6 ms | — |
| 256 KiB buckets, after backward / overlapped | 28.5 / 21.1 ms | 16.4 / 8.17 ms |
| 1 MiB buckets, after backward / overlapped | 21.3 / 16.1 ms | 9.23 / 4.06 ms |
| one 16 MiB bucket, after backward / “overlapped” | 17.0 / 18.2 ms | 5.65 / 6.46 ms |
Overlap works: with five 1 MiB buckets, exposed communication drops from 9.2 ms to 4.1 ms. One bucket cannot overlap at all, since it is full only when backward ends. 26 small buckets pay the startup tax: each extra call costs ~0.46 ms here. On this machine the two effects nearly cancel. The best overlapped setting beats the best non-overlapped one by only 0.9 ms, because a call’s startup here (~0.46 ms) is ~75× that of a 4-GPU NVLink ring (6 steps × 1 µs).
Modelled for a real cluster (demo 07, Llama-3-8B, 64 H100s, 8,192 tokens per GPU, 50% MFU): backward takes 497 ms. A flat-ring AllReduce of the 16.1 GB of gradients takes 633 ms, longer than backward, so even the best bucketing (1 GiB here) exposes 190 ms. The step is then 80% compute, and 1 MiB buckets drop it to 11%. A hierarchical AllReduce brings communication to 141 ms. With 25–100 MiB buckets only ~14 ms stays exposed, and the step is 98% compute; reducing after backward would expose all 133 ms. Bucketing is a trade-off in both directions. Tiny buckets drown in startups, and huge ones start late and grow the tail (17.5 ms exposed at 1 GiB vs 14.0 ms at 100 MiB).
4.5 Gradient accumulation
To grow the effective batch without more replicas, accumulate (梯度累积) gradients locally over micro-steps and synchronize once. Communication frequency drops by , and so does optimizer-step frequency. In DDP the first micro-steps skip the hooks (no_sync), and the loss of each is scaled by so the sum is the mean. Demo 04 checks it: identical bits to the reference for , the same 16 AllReduce calls per optimizer step, and bytes sent per training token 3.02 kB → 1.51 kB → 754 B. Accumulation is the lever when the network is the bottleneck. It interacts with pipeline parallelism, which already runs micro-batches (Lecture 6).
4.6 Is it the same training? Bit for bit, and when not
DP is supposed to be “the same math, computed in pieces”. Demo 04 checks this strictly after 20 AdamW steps on the TinyTransformer:
| ranks | dtype | replicas bit-identical? | equal to the reference, bit for bit? | max relative weight difference |
|---|---|---|---|---|
| 2 | fp32 | yes | yes | 0 |
| 4 | fp32 | yes | no | 2.9e-6 |
| 4 | fp64 | yes | no | 2.3e-15 |
The reference is one process that computes each rank’s shard gradient in turn (same shapes), sums them and divides by . With 2 ranks there is only one sum, so DDP is bit-for-bit (逐位一致) identical. With 4 ranks the ring adds in a different order (§3.6), and the results agree only to rounding: ~1e-6 in fp32, ~1e-15 in fp64, the signature of reordered additions rather than a bug. What is always exact: all replicas hold identical bits, because every collective ends with copies. Even the “obvious” reference is a choice: one gradient of the whole global batch, mathematically the same mean, differs from the shard-summed reference by 9.2e-6.
This is the practical meaning of the slide’s “verification” advice. When you change a parallel layout, compare against a reference that does the same arithmetic in the same order if you want bits. Otherwise decide a tolerance from the dtype and the reduction order, and expect fp64 to shrink the difference by ~9 orders of magnitude if the code is right.
4.7 Scaling, and DP’s failure modes
Weak scaling keeps tokens per GPU fixed and adds GPUs. Demo 07 models it for Llama-3-8B with 25 MiB buckets:
| GPUs | flat ring: step / efficiency | hierarchical: step / efficiency |
|---|---|---|
| 8 (one node, NVLink) | 770 ms / 99.1% | 770 ms / 99.1% |
| 64 | 1.15 s / 65.0% | 761 ms / 97.9% |
| 1,024 | 4.71 s / 15.9% | 919 ms / 82.7% |
With a flat ring, startups per bucket grow with . The hierarchy keeps the frequent, large traffic inside nodes. The slides’ table of what to look for in a profile:
| Symptom | Likely cause | Fix / lever |
|---|---|---|
| AllReduce dominates the step | communication not overlapped; too many buckets; slow fabric | tune bucket size; overlap; hierarchical AllReduce; fewer ranks per DP group |
| OOM with DDP | optimizer state + gradients too big | ZeRO/FSDP (§6); offload; lower precision |
| FSDP slow despite fitting | per-layer AllGather on the critical path | larger wrap units; prefetch; overlap; less aggressive sharding (§6.5) |
4.8 Serving-time “DP” is replicas
At inference, “data parallel” usually means several independent replicas, each possibly sharded by EP/TP/PP internally. Replicas raise aggregate throughput and cut tail latency through less queueing, and they need no per-layer synchronization with each other. On a fixed GPU pool there is a trade-off. More replicas mean smaller groups per replica, fewer per-layer collectives and a better TPOT. But each replica then has less memory for KV cache, so a lower maximum context unless the KV is sharded. The slides add a serving-specific point: route requests KV-cache-aware, to the replica that already holds a matching prefix, not by load alone (Lecture 22).
5. Expert parallelism
5.1 Why EP exists
MoE (Lecture 4) raises total parameters without raising per-token compute. But it forces a new distributed pattern. In a dense FFN every token touches all FFN weights in one big GEMM. In an MoE layer each token touches only experts, and nothing requires those experts to live on the same GPU. Expert parallelism (专家并行) places different experts on different ranks, so each GPU holds a few experts of every layer, plus a copy of everything that is not an expert.
What EP shards: the expert FFN weights, with their gradients and optimizer state. In DeepSeek-V3 that is 654 B of 671 B parameters, 97.4% (demo 01). What it does not shard: attention, embeddings, norms, routers and shared experts. That is the remaining 17.1 B parameters, still 274 GB per GPU at 16 B each. So even EP = 256 alone needs 315 GB per GPU. Adding FSDP over the same GPUs shards the rest too, giving 41.9 GB. The NeMo AutoModel slides (Lecture 8) describe exactly this: FSDP and EP share the same axis of the device mesh. And EP buys no speed per token: each token still does about the same FLOPs. EP adds parameters, not per-token speed.
5.2 Router → dispatch → experts → combine
A typical MoE layer under EP runs four steps on every rank (expert_parallel.ep_forward):
- Route: the router, replicated on every rank, picks the top- experts of each local token. Expert lives on rank .
- Dispatch (分发): sort the (token, expert) assignments by destination rank, exchange the row counts (a tiny AllToAll of integers), then send each assignment’s activation row to its expert’s rank. This is an AllToAll with uneven splits, because every rank sends a different number of rows to every other rank.
- Experts: each rank runs its own experts on the rows it received, often as one grouped GEMM (Lecture 7).
- Combine (合并): the inverse AllToAll returns every result to the token’s home rank, which adds into the output.
AllToAll is a distributed transpose (分布式转置): rank cuts its tensor into chunks and sends chunk to rank , receiving one chunk from everyone. The volume model from the slides, per MoE layer:
It costs more than the formula suggests. AllToAll is many-to-many, so more participants means more contention. It is harder to overlap than one big AllReduce. And it is extremely sensitive to topology.
Measured (demo 06). Four ranks, 8 experts, top-2, 256 tokens. EP’s output is bit-identical to a single process that routes each rank’s tokens separately, in both fp32 and fp64. It also agrees to 6e-8 with the plain layer applied to all 256 tokens at once, in fp32 (and exactly in fp64). The one difference is instructive: the router’s matmul runs on 64 rows per rank instead of 256, and this machine’s fp32 BLAS rounds a 64-row product differently from the same rows inside a 256-row product. Same operations on the same shapes give the same bits, a useful rule when you validate a parallel implementation. Each rank keeps 12.5 K of the layer’s 49.4 K parameters. The two AllToAlls carry 30.7–34.9 kB per rank vs = 32.8 kB: dispatch sends rows, but combine returns the rows each rank received, which depends on routing.
5.3 Load balance: the slowest expert sets the step time
Dispatch must finish before the experts run, and combine must finish before the next layer. So the busiest rank is everyone’s barrier: it sends and receives more data and runs bigger expert GEMMs. The slides’ utilization proxy:
Demo 06 measures it, biasing the router’s selection toward rank 0’s two experts (gates still use the unbiased scores, so the layer stays valid). The setup is 4,096 tokens, , 8 experts, top-2, 4 ranks:
| router skew | rows received per rank | utilization | expert compute, busiest / idlest rank | step time | dropped at capacity 1.25 |
|---|---|---|---|---|---|
| 0 | 2045 1962 2154 2031 | 95.1% | 3.01 / 2.61 ms | 6.10 ms | 0 |
| 0.05 | 3329 1542 1735 1586 | 61.5% | 3.67 / 2.29 ms | 6.66 ms | 769 (9.4%) |
| 0.15 | 6171 665 779 577 | 33.2% | 5.55 / 1.18 ms | 8.71 ms | 3,611 (44.1%) |
| 0.5 | 8191 0 1 0 | 25.0% | 6.74 ms / 21 µs | 10.0 ms | 5,631 (68.7%) |
Even an unbiased random router leaves the busiest rank 5% above the mean. At skew 0.5, three ranks idle while rank 0 works, and the step takes 1.6× longer, all of it spent waiting in the combine AllToAll. A capacity factor (容量因子) bounds the worst case: each expert processes at most tokens per step and drops (or reroutes) the rest. That turns a straggler into lost tokens, a quality risk, which is why balancing is both a router-training issue (Lecture 4’s aux loss and bias controller) and a systems issue. MoE throughput is set by the worst-case per-expert load, not the average.
5.4 Topology: keep EP inside the node
Demo 06 prices DeepSeek-V3’s AllToAll (, top-8 of 256 experts, bf16) with the α–β model:
| phase | tokens per GPU | dispatch bytes per GPU | EP8 in one node (NVLink) | EP64 over 8 nodes (IB) | expert FLOPs at peak |
|---|---|---|---|---|---|
| training micro-batch | 4,096 | 470 MB | 1.84 ms | 18.9 ms | 2.92 ms |
| decode, batch 64 | 64 | 7.34 MB | 42.5 µs | 667 µs | — |
| decode, batch 1 | 1 | 115 kB | 14.4 µs | 383 µs | — |
(Dispatch + combine per MoE layer. Decode experts are bound by reading weights, not FLOPs, so no compute column.)
In training, cross-node EP is communication-bound by a wide margin: 18.9 ms of AllToAll against 2.92 ms of expert math. It can be made viable, but only with effort. DeepSeek-V3 trains with 64-way EP across 8 nodes, using three main tools:
- Node-limited routing (节点受限路由): each token goes to experts on at most 4 nodes.
- De-duplication (去重): a token crosses the network once per destination node, then NVLink fans it out to the GPUs that need it. This is the DeepEP pattern the AutoModel slides draw. Under uniform routing a token’s 8 experts sit on 4.63 of the 7 other nodes on average, vs 7.00 remote experts, so de-duplication alone cuts cross-node bytes by 34%.
- Overlap: computation of one micro-batch overlaps the AllToAll of another, in DeepSeek’s DualPipe schedule.
In decode, the payload is tiny but the startups are not. Cross-node EP adds 383 µs per MoE layer, 22.2 ms to every token’s TPOT over DeepSeek-V3’s 58 MoE layers, vs 838 µs inside a node. Nothing can hide it, because the next token needs this one. That is the slide’s “cross-node EP is often catastrophic for TPOT”.
The slides’ sizing rules follow:
- Pick so the AllToAll stays on the fastest links you have.
- Assign experts evenly, per rank.
- Profile: tokens per expert and per rank, time in dispatch and combine, expert GEMM efficiency (are expert batches big enough?), and overlap.
Scale to more GPUs with DP/PP rather than a huge , unless your fabric can handle it. In serving: keep EP local; if that is impossible, reduce the EP size and add replicas.
6. Sharding the training state: ZeRO and FSDP
6.1 Where DDP breaks
DDP stores the full state on each GPU:
If that exceeds the GPU’s memory, DDP cannot run even with infinite network bandwidth: a capacity failure. The ZeRO observation (Zero Redundancy Optimizer, 零冗余优化器): in DDP the dominant tensors are replicated times, which is pure redundancy. Shard them, and reconstruct each only when needed.
6.2 Three stages
| Stage | Shards | Per-GPU state (mixed precision) | New communication |
|---|---|---|---|
| DDP | nothing | AllReduce gradients (once per step) | |
| ZeRO-1 | optimizer state (, fp32 master) | ReduceScatter gradients + AllGather updated weights (= one AllReduce’s volume) | |
| ZeRO-2 | + gradients | the same, but gradients reduce-scattered and freed during backward | |
| ZeRO-3 / FSDP | + parameters | AllGather weights in forward and backward, per layer; ReduceScatter gradients |
Replicated per GPU becomes sharded , but only for the tensors you shard. The communication column hides the most important consequence: FSDP moves some communication from once per step to many times per step, one AllGather per layer in forward and again in backward. In training that is fine if it overlaps. In serving latency it is risky.
Why ZeRO-1 and ZeRO-2 cost no extra communication: after the gradient ReduceScatter, rank holds the averaged gradient of its shard. It updates that shard with its own slice of the optimizer state, which is elementwise, so the shard is all it needs. It then AllGathers the updated weights so every rank has the full model for the next forward pass. ReduceScatter + AllGather is exactly an AllReduce’s volume (§3.2). The difference between stages 1 and 2 is only memory: stage 2 reduce-scatters each bucket during backward and frees the full gradient immediately, so the full gradient never exists at once.
6.3 The FSDP / ZeRO-3 loop, implemented
ddp_zero.zero_worker cuts the model into units (包装单元, FSDP’s “wrapping units”): the embedding, each Transformer block, and the final norm + LM head. Each unit’s parameters live as one flat vector, zero-padded to a multiple of , and rank stores only shard . Then, as in the slide’s loop:
- Forward: for each unit, AllGather its shards into the full vector, run the unit, free the full vector. Keep only the unit’s input.
- Backward: for each unit in reverse, AllGather again, recompute the unit’s forward from its saved input, backpropagate through it, ReduceScatter its gradient (keep the averaged shard), free.
- Optimizer: update the local shard with the local optimizer-state shard.
Real FSDP keeps the activations and re-gathers parameters from hooks before each unit’s backward. Our version recomputes instead, which is ZeRO-3 plus unit-level activation checkpointing. It keeps the code free of autograd tricks. The communication pattern is exactly FSDP’s; the extra forward compute is not.
Measured (demo 05). First, same training: all four strategies (DDP, ZeRO-1, -2, -3) reproduce single-process training bit for bit with 2 ranks. With 4 ranks every rank agrees with its peers, and ZeRO differs from DDP by at most 3.5e-7, again only reduction order. Sharding Adam is free because Adam is elementwise.
Memory, measured by summing the distinct tensor storages each rank holds at the optimizer step (fp32 toy model, 4 B per element, , ):
| measured | formula | fraction of DDP | transient buffers | |
|---|---|---|---|---|
| DDP | 3.09 MB | 1.00 | full gradients until the step | |
| ZeRO-1 | 2.12 MB | 0.69 | full gradients until the step | |
| ZeRO-2 | 1.35 MB | 0.44 | peak 185 kB of full gradients | |
| ZeRO-3 | 772 kB | 0.25 | one gathered unit (185 kB) + its gradients |
Measured equals formula to the byte, after one correction recorded in the code README: the first version kept the owned weight shard as a separate copy rather than a view into the resident weights. ZeRO-2’s saving is real only because gradients are reduce-scattered unit by unit during backward; at most one block’s gradients are alive at once. ZeRO-3’s transient memory is set by the largest unit, which is why wrapping granularity matters.
Communication per step, counted by Comm:
| collectives | sent per rank | × DDP | |
|---|---|---|---|
| DDP | AllReduce ×1 | 1.16 MB | 1.00 |
| ZeRO-1, ZeRO-2 | AllGather ×6, ReduceScatter ×6 | 1.16 MB | 1.00 |
| ZeRO-3 | AllGather ×12, ReduceScatter ×6 | 1.74 MB | 1.50 |
ZeRO-3’s 1.5× is the AllGather in backward: instead of . On this laptop the step times are DDP 15.9 ms, ZeRO-1 21.7 ms, ZeRO-2 28.1 ms, ZeRO-3 37.7 ms (measured, 4 ranks). Every call pays a ~0.5 ms startup, nothing is overlapped, and our ZeRO-3 also recomputes. The memory is what ZeRO buys; the time is what it costs, and how much depends entirely on overlap.
6.4 When does FSDP’s AllGather hide? A knee, like the roofline’s
With prefetching, the AllGather of unit runs during unit ‘s compute. It is hidden when ; otherwise the slide’s visible time is , clipped at 0. Write both sides for a unit of parameters in bf16 and tokens per GPU:
cancels: the size of the unit does not decide overlap. Tokens per GPU and the link do. The AllGather hides when
a knee exactly like the roofline’s. Here it is in tokens per GPU instead of FLOPs per byte, because each gathered weight byte is used once per token. Demo 07, with of the H100’s BF16 peak:
| sharding group | tokens per GPU needed to hide the AllGather |
|---|---|
| inside one node, NVLink (p = 8) | ~962 |
| across 8 nodes, InfiniBand (p = 64) | ~9,740 |
Backward has the same ratio: twice the compute, an AllGather plus a ReduceScatter. So sharding across InfiniBand needs ~10k tokens per GPU per step to overlap, and inside a node ~1k suffices.
Unit size still matters at the edges. For Llama-3-70B over 64 GPUs on InfiniBand at 8,192 tokens per GPU, below the knee, every unit size leaves 16–19% of its AllGather visible, as the formula says. But a per-matrix unit spends 3.8% of each AllGather in startups (the α tax of too many collectives). A 16-layer unit keeps 54.8 GB of weights gathered at once, current plus prefetched, a memory spike. One Transformer block, the usual choice, sits between: 0.6% startups and 3.4 GB resident. The slides’ three knobs, in order:
- Sharding strategy: gradients + optimizer only (ZeRO-2-like), or parameters too (ZeRO-3-like).
- Prefetching and overlap: if the AllGather for layer is not overlapped, it becomes visible and can dominate.
- Wrapping granularity: too small and you get too many collectives and bad overlap; too big and you get memory spikes and less concurrency.
6.5 HSDP: shard inside the node, replicate across nodes
The knee above suggests the multi-node shape. HSDP (hybrid sharded data parallel, 混合分片数据并行) applies sharding hierarchically. Inside a node, FSDP shards over NVLink, where the frequent per-layer AllGathers are cheap and hide at ~1k tokens per GPU. Across nodes, the node-groups are plain replicas. They only AllReduce gradient shards once per step, a -sized, overlappable, cold collective. The hottest communication stays local. The price is capacity: each GPU holds of the state instead of . For Llama-3-70B that is 141 GB per GPU, which does not fit, so 70B needs FSDP over more GPUs, or TP/PP inside the node (Lecture 6).
The slides’ decision rubric:
- If the model fits with its optimizer state, start with DDP: simplest, often fastest.
- If optimizer, gradient or parameter state is the bottleneck, move to FSDP / ZeRO.
- If you are multi-node, consider HSDP (hierarchical groups).
- Pitfall: assuming FSDP is good for serving latency because it is good for training. Often false: a per-layer AllGather on the decode path cannot be hidden.
6.6 What FSDP does not shard
Two things stay full-size on every rank, and they motivate the next lecture:
- Weights at compute time. Each layer is gathered back to full size for its GEMM, so a layer that does not fit on one GPU still cannot run.
- Activations. Every rank computes and stores full-width activations for its tokens, and adding FSDP ranks does not shrink them (demo 01: 36.5 GB per 8k-token sequence for Llama-3-8B).
Tensor parallelism removes both limits at once by sharding the weight matrices, the compute and the resulting activations. It is the subject of Lecture 6, together with pipelines and how all the axes compose.
7. Putting today’s three strategies together
A procedure for a training run, using only today’s tools:
- Fit first. Add up weights, gradients, optimizer state and activations (§2.2). If the state does not fit, choose ZeRO-1 → 2 → 3 until it does. If activations do not fit, recompute (or wait for TP/SP/CP).
- Then throughput. Make large enough for efficient GEMMs and for FSDP to sit above its knee (§6.4). Size the buckets so startups are amortized but overlap starts early (§4.3). Use hierarchical collectives across nodes.
- Map to topology. The hottest collectives go on the fastest links: EP AllToAll inside the node; FSDP sharding inside the node where it fits (HSDP); DP gradient AllReduce across nodes.
- Validate. Profile overlap and exposed communication, router imbalance and token drops. Check that a layout change reproduces the reference within the tolerance its dtype and reduction order predict (§4.6).
DeepSeek-V3 is a concrete point in this space. Its report describes 64-way EP spanning 8 nodes, 16-way pipeline parallelism, and ZeRO-1 data parallelism, with node-limited routing, de-duplicated dispatch and computation–communication overlap. Those are today’s tools plus the pipelines of Lecture 6.
8. Summary
- A third roofline term. when communication overlaps, a sum when it does not. Parallelism trades compute and memory for communication.
- Six seams. Batch (DP), experts (EP), stored state (FSDP/ZeRO), layer width (TP), depth (PP), sequence (CP). DP alone keeps the model whole and buys throughput. DDP buys no capacity: 128 GB per GPU for Llama-3-8B at any .
- Collectives and α–β. . The ring AllReduce sends per rank, which is bandwidth-optimal, but in steps, so it is latency-bound below (3.6 MB on 8 NVLink GPUs). Trees and halving-doubling win small messages; hierarchy wins across nodes (4.8–6.5× here).
- DDP. One gradient AllReduce per step, in reverse-order buckets launched in a fixed order, overlapped with backward. It is exact: bit for bit with 2 ranks, rounding-level with more. Overlap is worth most when . For Llama-3-8B on 64 GPUs that requires a hierarchical AllReduce (14 ms exposed instead of ≥190 ms).
- EP. Two AllToAlls of each per MoE layer. The busiest rank sets the step (1.6× slower at 25% utilization, measured). Cross-node EP is communication-bound in training (18.9 vs 2.92 ms per layer for DeepSeek-V3) and adds ~22 ms to every decode token. Keep it in the node, de-duplicate, limit nodes per token.
- ZeRO/FSDP. Shard the optimizer state, then the gradients, then the parameters: . Measured state equals the formulas. ZeRO-1/2 cost no extra communication; ZeRO-3 costs 1.5×, per layer. Its AllGather hides only above tokens per GPU: ~1k on NVLink, ~10k on InfiniBand, whatever the unit size. Hence HSDP.
- Training ≠ serving. Overlap is natural in training (backward is a pipeline) and impossible on the decode path (each token waits for the last). Collectives on the decode path must be removed or localized.
9. Common pitfalls
- Adding GPUs to fix an OOM. DDP replicates everything; only sharding (or model parallelism) adds capacity.
- Using NVLink’s bidirectional 900 GB/s in ring math. A ring step sends and receives at once; the one-way 450 GB/s is the limit.
- Judging a collective by the single-message crossover. A ring AllReduce on ranks is latency-bound up to times .
- Tiny buckets, or one giant bucket. The first drowns in startups, the second cannot overlap.
- Calling collectives in rank-dependent order. For example, launching DDP buckets in the order they happened to fill. Every rank must issue the same sequence, or the job hangs.
- Expecting bit-identical results across layouts. Different reduction orders, and even different matrix shapes, change the last bits. Compare against a shape- and order-matched reference, or set a dtype-appropriate tolerance.
- Balancing experts on average. The maximum load sets the step; a capacity factor turns overload into dropped tokens.
- Cross-node EP or FSDP on the decode path. α-dominated collectives that nothing can hide.
- Expecting FSDP to shrink activations. It does not; recomputation, TP/SP and CP do.
10. Exercises
- Ring cost. Estimate a ring AllReduce of 2 GB of bf16 gradients on 8 GPUs over NVLink (α = 1 µs, 450 GB/s one way) and on 64 GPUs over InfiniBand (α = 3 µs, 50 GB/s). Which term dominates?
Answer
8 GPUs: 7.8 ms. 64 GPUs: 79 ms. Both are bandwidth-dominated: the payload is far above (3.6 MB and 9.6 MB).
- The latency-bound region. Show that the ring AllReduce’s α and β terms are equal at . What is that size for 64 GPUs over InfiniBand, and why is it larger than the single-message crossover?
Answer
. For : MB. It is times the single-message crossover (150 kB) because the ring splits the tensor into chunks: each of its messages carries only bytes, so each message stays small until is times larger.
- ZeRO memory. A 30 B-parameter model is trained with mixed-precision AdamW on 32 GPUs. Compute the per-GPU training state under DDP, ZeRO-1, ZeRO-2 and ZeRO-3, and say which fit in 72 GB.
Answer
DDP GB. ZeRO-1 GB. ZeRO-2 GB. ZeRO-3 GB. Only ZeRO-3 fits; ZeRO-2 misses by a hair, and activations still need room.
- ZeRO-3’s traffic. Why does ZeRO-3 send 1.5× what DDP sends, while ZeRO-1 and ZeRO-2 send exactly the same? Count in units of .
Answer
DDP: one AllReduce = ReduceScatter + AllGather = 2 units. ZeRO-1/2: ReduceScatter of gradients (1) + AllGather of updated weights (1) = 2 units. ZeRO-3: AllGather of weights in forward (1) + again in backward (1) + ReduceScatter of gradients (1) = 3 units, i.e. 1.5×. ZeRO-3 does not need the post-update AllGather, because weights stay sharded until the next forward gathers them.
- The FSDP knee. An H100 sustains 400 TFLOP/s in your training job, and you shard across nodes with 50 GB/s per GPU. How many tokens per GPU per step do you need for FSDP’s AllGathers to hide? What if you switch to HSDP with 8-GPU NVLink groups?
Answer
Across nodes ( large): tokens. HSDP inside the node (, 450 GB/s): tokens. The unit size does not enter either answer.
- EP straggler. An EP group of 8 ranks processes 16,384 assignments per layer. The busiest rank receives 3,500 of them. What is the utilization, and by how much would a perfectly balanced router speed up the expert phase?
Answer
Mean ; . If expert time scales with rows, the expert phase takes the balanced time, so balancing would make it 1.71× faster (less in practice, since bigger GEMMs are more efficient per row: demo 06’s busiest rank did 4× the rows in 2.2× the time).
- EP in decode. A model has 40 MoE layers and serves with EP across nodes. Each AllToAll over 64 ranks pays in startups. How much does EP add to TPOT, and what does keeping EP within an 8-GPU NVLink node (α = 1 µs) give?
Answer
Two AllToAlls per layer: ms per token (plus small bandwidth terms). Inside a node: ms. A 27× difference, on the critical path of every token.
- Bit for bit. Your DDP run on 8 GPUs differs from a single-GPU reference by 3e-6 relative after 100 steps, in fp32. Is it a bug? Describe two checks.
Answer
Not necessarily: a ring sums 8 gradients in rotated orders, and float addition is not associative, so ~1e-6 drift in fp32 is expected. Check 1: run both in fp64. If the code is right the difference falls to ~1e-15; a bug stays large. Check 2: run with 2 ranks against a reference that computes the two shard gradients with the same shapes and adds them (a + b is exact either way); it must match bit for bit. Also confirm that all 8 replicas are bit-identical to each other. If they are not, a collective is missing or misordered.
11. The related assignment (concepts only)
Spring 2026’s Assignment 1 was parallelism. Fall 2026’s A1 is performance engineering (Lectures 2–3), and parallelism comes back in A2 (pre-training) and the project. The concepts these exercises test:
- Account before you measure. Bytes per collective and per step, and state bytes per GPU, are your predictions. A profile then confirms them or tells you which assumption failed.
- Name the primitive. It tells you the payload, whether the cost is α- or β-dominated, and how sensitive it is to topology.
- Prove correctness against the right reference. As in §4.6: same shapes and reduction order for bits, a dtype-derived tolerance otherwise, and replica agreement always.
- Explain overlap with a timeline. “Why didn’t this communication hide?” has a concrete answer: bucket order, the last bucket, a missing prefetch, or .
No assignment solutions are given here; the demo code is independent of the course’s starter code.
12. Research directions
- Smarter overlap for FSDP and EP. Below the knee, communication is visible by arithmetic. Can scheduling (DualPipe-style micro-batch interleaving), compression or partial gathers move the knee, and what does each cost in memory and complexity?
- Topology-aware MoE. Node-limited routing and de-duplication trade routing freedom for bytes. How much quality does each constraint cost, and can routers learn topology-friendly assignments?
- Deterministic distributed training. Exactly reproducible reductions (fixed-order trees, compensated sums) cost some speed. When does reproducibility pay for itself in debugging and evaluation?
- Low-precision communication. BF16 or FP8 gradients and AllToAll payloads halve or quarter the bytes. The AutoModel case study (Lecture 8) reports a 1% step gain from BF16 gradient reduction. When does it hurt convergence?
- Collectives that adapt to message size. Decode-time and training-time collectives live in opposite regimes. Runtime algorithm selection, NCCL’s tuner plugins, and in-switch reduction (NVLink SHARP) are active areas.
13. Further reading
- Hugging Face, The Ultra-Scale Playbook: Training LLMs on GPU Clusters (2025): DP, ZeRO, TP, PP, CP and EP, with measurements.
- S. Rajbhandari, J. Rasley, O. Ruwase, Y. He, ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (SC 2020, arXiv:1910.02054).
- S. Li et al., PyTorch Distributed: Experiences on Accelerating Data Parallel Training (VLDB 2020, arXiv:2006.15704): buckets, overlap,
no_sync. - Y. Zhao et al., PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel (VLDB 2023, arXiv:2304.11277).
- R. Thakur, R. Rabenseifner, W. Gropp, Optimization of Collective Communication Operations in MPICH (IJHPCA 2005); P. Patarasuk, X. Yuan, Bandwidth Optimal All-reduce Algorithms for Clusters of Workstations (JPDC 2009).
- NVIDIA, NCCL documentation and the
nccl-testsperformance notes: algorithm and bus bandwidth. - DeepSeek-AI, DeepSeek-V3 Technical Report (arXiv:2412.19437): node-limited routing, DualPipe, the EP64/PP16/ZeRO-1 layout; the DeepEP repository for dispatch and combine kernels.
- M. Shoeybi et al., Megatron-LM (arXiv:1909.08053): tensor parallelism, the topic of Lecture 6.
14. Next lecture
Lecture 6 · Parallelism II: Tensor, Sequence, Pipeline and N-D Parallelism. FSDP left two things full-size on every GPU: weights at compute time and activations. Tensor parallelism shards inside every layer, with Megatron’s column- and row-parallel linear layers. It places the unavoidable synchronization where the tensor is small, and pays for it with collectives inside every layer, so it needs NVLink. Sequence parallelism trims what TP leaves replicated. Pipeline parallelism cuts the depth and pays in bubbles: GPipe, 1F1B, interleaved and zero-bubble schedules. Then we compose all the axes into a mesh, map it onto a cluster, and search for a layout for a 70B model.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| parallelism strategy / seam | 并行策略 / 切分维度 |
| capacity / throughput / latency | 容量 / 吞吐量 / 延迟 |
| interconnect / NVLink / NVSwitch / InfiniBand / RoCE | 互联 / 节点内高速互联 / NVLink 交换芯片 / 无限带宽网络 / 以太网 RDMA |
| scale-up vs scale-out | 纵向扩展(节点内) vs 横向扩展(节点间) |
| rank / process group / world size | 秩(进程编号) / 进程组 / 进程总数 |
| SPMD (single program, multiple data) | 单程序多数据 |
| collective communication | 集合通信 |
| AllReduce / ReduceScatter / AllGather | 全规约 / 规约-分散 / 全收集 |
| AllToAll / Broadcast / Gather / Scatter / SendRecv | 全交换 / 广播 / 收集 / 分散 / 点对点收发 |
| α–β model / startup cost / inverse bandwidth | α–β 模型 / 启动开销 / 带宽倒数 |
| latency-bound / bandwidth-bound / crossover | 延迟受限 / 带宽受限 / 临界点 |
| ring / tree / recursive halving-doubling | 环形 / 树形 / 递归减半-倍增 |
| bandwidth-optimal | 带宽最优 |
| hierarchical AllReduce / rail | 分层全规约 / 轨道(同编号网卡平面) |
| bus bandwidth | 总线带宽 |
| hang / deadlock | 卡住 / 死锁 |
| data parallelism (DP) / DDP / replica | 数据并行 / 分布式数据并行 / 副本 |
| gradient bucket / hook / overlap | 梯度桶 / 钩子 / 通信计算重叠 |
| exposed communication / critical path | 暴露的通信时间 / 关键路径 |
| gradient accumulation / micro-batch / no_sync | 梯度累积 / 微批次 / 不同步 |
| communication-bound | 通信受限 |
| weak scaling / scaling efficiency | 弱扩展 / 扩展效率 |
| bit-for-bit reproducibility | 逐位可复现 |
| commutative / associative | 交换律 / 结合律 |
| expert parallelism (EP) / dispatch / combine | 专家并行 / 分发 / 合并 |
| distributed transpose / uneven split | 分布式转置 / 非均匀切分 |
| utilization / straggler / capacity factor / token dropping | 利用率 / 掉队者 / 容量因子 / 丢弃 token |
| node-limited routing / de-duplication | 节点受限路由 / 去重 |
| ZeRO (Zero Redundancy Optimizer) stage 1/2/3 | 零冗余优化器 1/2/3 阶段 |
| FSDP / HSDP | 全分片数据并行 / 混合分片数据并行 |
| optimizer state / master weights | 优化器状态 / 主权重(fp32 副本) |
| shard / flat parameter / wrapping unit | 分片 / 扁平参数 / 包装单元 |
| prefetch / reshard / gather on demand | 预取 / 重新分片 / 按需收集 |
| activation recomputation (checkpointing) | 激活重计算 |
| tensor / sequence / pipeline / context parallelism | 张量 / 序列 / 流水线 / 上下文并行 |