Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 5, continued (Sep 16, 2026), slides
lecture5.pdf(107 slides). This lecture covers the tensor-parallelism and pipeline-parallelism sections, “Putting it together: 3D → 6D + recipes”, the mapping of the mesh onto the cluster, and the backup slides on TP’s backward pass, SwiGLU and attention sharding, pipeline imbalance, interleaving and SP/CP terminology. Spring 2026 taught it within Lecture 4. Recommended readings (course schedule): M. Shoeybi et al., Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism (2019); Hugging Face, The Ultra-Scale Playbook; the interactive Pipeline-parallelism schedule visualizer; S. Rajbhandari et al., ZeRO (2019). Other sources: D. Narayanan et al., Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM (SC 2021), for the PTD-P composition and interleaved 1F1B; V. Korthikanti et al., Reducing Activation Recomputation in Large Transformer Models (2022), for sequence parallelism and selective recomputation; Y. Huang et al., GPipe (2019); D. Narayanan et al., PipeDream (2019), the origin of 1F1B; P. Qi et al., Zero Bubble Pipeline Parallelism (ICLR 2024); L. Zheng et al., Alpa (OSDI 2022), for automated layout search. Every number labelled measured comes fromcode/lecture06/on the author’s laptop; computed / model / simulated numbers come from the same code. Code:code/lecture06/:tensor_parallel.py(TP and SP as explicit autograd operators),pipeline.py(schedule simulator),layout.py(layout cost model and search), and six demos. Reading time: ~2.5 hours for the prose; ~25 minutes for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Shard a layer. Write out column- and row-parallel linear layers. Explain why Megatron pairs them as it does, and place every TP collective in a Transformer block, forward and backward.
- Price TP. Estimate TP’s per-layer communication against compute in training, and against TPOT in decode. Say why TP lives inside one NVLink node.
- Shard what TP replicates. Explain sequence parallelism, why it costs no extra communication, and what saving the shard instead of the gathered input buys.
- Schedule a pipeline. Derive the GPipe/1F1B bubble. Explain why 1F1B is a memory win and not a bubble win. Say what interleaving and zero-bubble schedules trade, and why stage balance comes first.
- Compose and place. Factor , map each axis to the right links, and search for a layout: fit first, then throughput, then latency.
0.2 Prerequisites and scope
- Prerequisites: Lecture 5: collectives, the α–β model, DDP, ZeRO/FSDP and the overlap rule. Lecture 1’s activation-memory formula (Korthikanti et al.). Lecture 3’s tiles and waves.
- Scope: tensor, sequence and pipeline parallelism; interconnect hotness and placement; composing the axes; choosing a layout. Everything is checked against dense single-process computation across real processes, simulated where a laptop cannot run it, and priced on H100s.
- Not in scope today: context parallelism and the attention kernels behind it (Lecture 7); how a framework packages these plans, AutoModel’s AutoPipeline (Lecture 8); MoE layouts beyond Lecture 5’s EP.
0.3 Section → code map
| Section | Idea | Code in code/lecture06/ |
|---|---|---|
| §2.1–2.4 | column/row-parallel layers, the Megatron block, f and g | tensor_parallel.py, 01_tp_layers.py |
| §2.5–2.6 | what TP costs on H100s, training and decode | 03_tp_cost_model.py |
| §3 | sequence parallelism and re-gathering | tensor_parallel.py, 02_sequence_parallel.py |
| §4.1–4.7 | pipeline schedules, bubbles, memory, balance | pipeline.py, 04_pipeline_schedules.py |
| §4.8 | a real 4-stage pipeline | 05_real_pipeline.py |
| §5–6 | topology, composition, layout search | layout.py, 06_layout_search.py |
0.4 Notation
As in Lecture 5 ( ranks in a group, , , , , ). New today:
| Symbol | Meaning |
|---|---|
| (or ) | tensor-parallel group size |
| (or ) | pipeline stages (devices in the pipeline) |
| micro-batches per optimizer step per pipeline | |
| model chunks per device in an interleaved pipeline (“virtual stages”) | |
| time of one micro-batch’s forward / backward (activation gradient) / weight gradient on one stage | |
| sequence length, micro-batch size, model width, attention heads (Korthikanti’s notation) | |
| attention projections; : SwiGLU MLP |
1. What FSDP leaves on the table
Lecture 5 ended with two things that FSDP never shards:
- Weights at compute time. Each layer is gathered back to full size for its GEMM, so a layer whose weights do not fit on one GPU still cannot run. For decode, a per-layer AllGather on the critical path is the slow way to read weights.
- Activations. Every rank computes and stores full-width activations for its own tokens: norm inputs, attention scores, the MLP intermediates. For Llama-3-8B at 8k tokens that was 36.5 GB per sequence even with attention recomputed (Lecture 5, demo 01). More FSDP ranks do not shrink it.
The slides add a third reason, from the throughput side: you cannot always afford tiny micro-batches. Shrinking to make activations fit makes every GEMM less efficient. Tensor parallelism (张量并行) removes all three limits at once. It shards the weight matrices, the compute and the resulting activations, and pays with communication inside every layer. Pipeline parallelism (流水线并行) cuts the depth instead, paying with idle time and a serial dependency between stages. These are the two model-parallel cuts of the six seams (Lecture 5 §2).
2. Tensor parallelism
2.1 Two ways to split one linear layer
Zoom into one linear layer, with , , , and a TP group of size :
- Column-parallel (列并行): shard the output features, with columns each. With replicated, rank computes , its slice of the output, with no communication. comes out sharded, and you only AllGather it if the next op needs the full tensor.
- Row-parallel (行并行): shard the input features, with rows each. With already sharded the same way, rank computes a partial sum (部分和) of the full output, and an AllReduce gives .
(In PyTorch’s nn.Linear the weight is stored as , so “column-parallel” slices its rows; tensor_parallel.shard_rows and shard_cols follow that layout.)
What TP really chooses is which activation is sharded and which is replicated at each layer boundary, and therefore which collective you pay for. Demo 01 checks both on 2 and 4 ranks. A column-parallel rank’s output slice equals the dense slice exactly: the same dot products, just fewer of them. The row-parallel result after the AllReduce differs by 9.5e-6 in fp32 and 1.8e-14 in fp64, because partial sums are rounded differently from one long sum.
2.2 The Megatron pairing: synchronize where the tensor is small
A Transformer MLP expands (SwiGLU: , with two up-matrices), then contracts . Megatron combines the two kinds of split:
- expand (column-parallel): the large activation stays sharded, per rank, and the elementwise nonlinearity runs locally on each shard;
- contract (row-parallel): the reduction happens on the small output.
The slide’s principle: keep the biggest activations sharded; put the unavoidable synchronization on the smallest boundary tensor. The same works for attention by head partitioning (按头切分). are column-parallel, so each rank gets query heads with their K/V heads, and attention for those heads is entirely local. is row-parallel, so the reduction lands on the residual stream. With GQA, rank owns query heads and KV heads , exactly the KV heads its query heads read. That requires to be divisible by . Llama-3-70B has 8 KV heads, so TP beyond 8 would have to replicate K and V. MQA, with one KV head, must replicate it on every rank.
The residual boundary (残差边界) is the replication point. Norms, residual adds and the next layer’s input want the full tensor, which is why every TP reduction in a block lands on a -sized tensor.
2.3 Where the collectives sit: f, g and their conjugates
Each column/row pair needs exactly one collective per direction. Megatron places them with two tiny autograd operators (tensor_parallel.copy_to_tp and reduce_from_tp):
| Operator | Forward | Backward | Sits |
|---|---|---|---|
| f | identity (input already replicated) | AllReduce (each rank’s input gradient is partial) | before and before |
| g | AllReduce (sum the partial outputs) | identity (the output gradient is already full on every rank) | after and after |
This is the backup slide’s conjugate pair (共轭对偶): whatever the forward does at a boundary, the backward does the opposite there. Per Transformer block that makes 2 AllReduces in forward and 2 in backward, all on tensors. Training therefore pays twice the per-layer TP volume of a forward-only inference pass.
Measured (demo 01). A TP block, built by slicing the weights of the Lecture 1 dense block, matches it on 4 ranks. The outputs agree to 2.4e-7 (fp32) and 6.7e-16 (fp64), and the input gradient and every weight gradient’s slice agree too (2.2e-18 in fp64). The block issues exactly 2 AllReduces in forward and 4 in total, each 16.4 kB, the size of one activation. Each rank keeps 11.5 K sharded parameters plus 128 replicated norm weights, 0.252 of the block. Unlike FSDP, the weights stay sharded at compute time.
2.4 What TP buys on one machine (demo 01, measured)
TP is the only cut that also buys latency: GPUs cooperate on every matmul, so one layer finishes sooner. On CPU processes that talk over loopback, the measured strong scaling of one block’s forward + backward (, 512 tokens) is honest about the obstacles:
| TP ranks | TP block | its 1/t of the compute alone | its 4 AllReduces alone |
|---|---|---|---|
| 1 | 10.5 ms | 10.3 ms | — |
| 2 | 9.59 ms | 7.29 ms | 2.01 ms |
| 4 | 15.2 ms | 6.18 ms | 3.75 ms |
Three things eat the ideal -fold speed-up:
- Each rank’s 1/t share of the GEMMs speeds up only 1.4–1.7×: smaller matrices run less efficiently, and the ranks share one memory system.
- The 4 AllReduces cost 3.75 ms at 4 ranks.
- The two together explain 9.9 ms of the 15.2 ms. The remaining ~5 ms is most likely synchronization, since four times per block every rank waits for the slowest. We did not profile it further.
On H100s the same split runs over NVLink at ~1 µs per step, which is what makes TP worthwhile there (§2.5). The general lesson holds on any hardware: TP’s collectives sit between the GEMMs of every layer, on the critical path.
2.5 What TP costs on H100s (demo 03)
Training. For Llama-3-70B with 8,192-token micro-batches, each AllReduce carries bytes = 134 MB. Per layer, with compute at 50% of the BF16 peak:
| TP size | link | compute per GPU | 4 AllReduces | comm / compute |
|---|---|---|---|---|
| 2 | NVLink | 45.8 ms | 1.20 ms | 0.03 |
| 4 | NVLink | 22.9 ms | 1.81 ms | 0.08 |
| 8 | NVLink | 11.5 ms | 2.14 ms | 0.19 |
| 16 | 2 nodes, InfiniBand | 5.73 ms | 20.5 ms | 3.58 |
Inside a node, TP’s communication is a modest tax, partly overlappable. Engines overlap TP collectives with neighbouring GEMMs (“async TP”). Across nodes it is 3.6× the compute. Training with large makes TP collectives bandwidth-bound, so the link’s bandwidth decides.
Decode. One token per request makes each AllReduce tiny: 16 KiB for one request at . That is deep in the latency-bound regime (Lecture 5 §3.5), and there are 160 of them per token (2 per layer × 80 layers). TPOT = HBM read time of weights + KV, plus the AllReduces:
| TP size | 1 request: TPOT | of which AllReduces | 32 requests: TPOT |
|---|---|---|---|
| 1 | does not fit (142 GB) | — | does not fit |
| 2 | 21.6 ms | 0.33 ms | does not fit (92 GB) |
| 4 | 11.6 ms | 0.97 ms | 15.0 ms |
| 8 | 7.57 ms | 2.25 ms | 9.43 ms |
| 16 (2 nodes) | 17.2 ms | 14.5 ms | 21.8 ms |
Inside the node, more TP splits the weight reads and improves TPOT. Leaving the node, 160 cross-node AllReduces per token cost more than all the HBM reads saved. The slide’s rule: use the smallest that fits your weights per shard while meeting latency/throughput goals. Serving pushes toward the node size; training at scale keeps it at or below the node size.
Skinny GEMMs. Larger TP also makes each GPU’s GEMMs thinner. Llama-3-70B’s MLP up-projection on one GPU at TP = 8 is :
- In training ( = 8,192) it has 1,792 output tiles of 128 × 128, 14 waves on 132 SMs, which keeps the SMs 97% busy.
- In decode with 32 requests it has 28 tiles for 132 SMs, so 21% of the SMs are busy, and only 25% of each tile is real work.
Decode tolerates this because it is bandwidth-bound anyway; real decode kernels use split-K or GEMV paths. Compute-bound training with small micro-batches does not: the slide’s “MFU drops as grows”.
2.6 TP failure modes, and 2D TP
The slides’ table, condensed:
| Symptom | Likely cause | Lever |
|---|---|---|
| TPOT grows with | α-dominated collectives on the decode path | keep TP in the node; reduce ; add replicas |
| low throughput despite TP | micro-batches too small, skinny GEMMs | raise (DP, accumulation); reduce PP bubbles |
| cross-node TP is terrible | per-layer collectives on slow links; topology-unaware rank mapping | TP inside the node, PP across nodes (§5) |
| OOM in activations with TP | replicated tensors / AllGathers | SP (§3), CP (Lecture 7), checkpointing |
| collectives don’t overlap compute | collectives on the critical path, no async | async TP, fuse/reorder communication, tune NCCL |
| sawtooth utilization / hangs | imbalance across TP ranks; collective order mismatch; flaky fabric | balance work; validate collective order; health checks |
Classic TP is one-dimensional: each matrix is sharded along one axis. 2D TP shards along two axes of a process grid, with SUMMA-like communication. It gives smaller per-rank memory for very large matrices and better scaling past one node, at the price of more complex and latency-sensitive communication. It appears in very large training jobs with strong fabrics, not in latency-sensitive serving.
3. Sequence parallelism
3.1 What TP still replicates
Between the two TP regions of a block, everything is replicated on all ranks: the residual stream, both norms and their saved inputs, dropout masks (in models that use dropout), and the full input that each column-parallel GEMM saves for its weight gradient. Korthikanti et al. count it for a GPT-style layer in 16-bit precision:
The term does not shrink with . With the attention scores recomputed (selective recomputation, or FlashAttention, Lecture 7), the formula becomes , and the replicated 10 dominates once .
3.2 Shard the sequence where TP replicates
Norms, residual adds and dropout are token-wise: each position is processed independently. So between the TP regions the activations can be sharded along the sequence instead, each rank holding positions. Sequence parallelism (SP, 序列并行, Megatron-SP) replaces Megatron’s two operators:
- f → AllGather along the sequence (backward: ReduceScatter). Gather the full sequence just before the column-parallel GEMMs.
- g → ReduceScatter along the sequence (backward: AllGather). Reduce the partial outputs and keep only my positions.
An AllGather plus a ReduceScatter moves exactly the bytes of one AllReduce (Lecture 5 §3.2), so SP costs no extra communication. It only shards what TP replicated. One new detail: each rank now sees only its tokens, so the replicated norm weights receive partial gradients, which must be AllReduced across the TP group (SPBlock.sync_norm_grads).
3.3 Save the shard, gather again in backward
Plain autograd defeats part of SP. The column-parallel GEMM after the AllGather saves its gathered full-sequence input for the weight gradient, which is a replicated tensor again. Megatron instead saves the sequence shard and AllGathers it a second time in backward, where the extra AllGather can overlap with the input-gradient GEMM. tensor_parallel.gathered_linear implements exactly this: a custom autograd function that fuses (or ) into one GEMM over the gathered input, and saves only the shard and the parameters.
3.4 Measured (demo 02)
All three variants compute the dense block: to ~1e-15 in fp64 for every rank’s tokens, the input gradient, and the AllReduced norm gradients. Per block, forward + backward, at 4 ranks:
| Variant | collectives | sent per rank | saved activations per rank (measured) | fraction of dense |
|---|---|---|---|---|
| dense (1 rank) | — | — | 957 kB | 1.00 |
| TP | AllReduce ×4 | 197 kB | 392 kB | 0.41 |
| TP + SP | AllGather ×4, ReduceScatter ×4 (+ norm-gradient AllReduce) | 197 kB | 293 kB | 0.31 |
| TP + SP, re-gather | AllGather ×6, ReduceScatter ×4 (+ norm AllReduce) | 247 kB | 244 kB | 0.25 |
The activation bytes are measured with autograd’s saved-tensor hooks: every non-parameter tensor saved for backward is counted once per storage. TP alone already shards the big per-head and per-neuron tensors. Plain SP shards the norms and the residual stream, but still keeps the gathered GEMM inputs. Only re-gathering reaches exactly , for 2 extra AllGathers. That is the general shape of activation-memory engineering: memory bought with communication or recomputation.
For Llama-3-70B (one 8k-token sequence per micro-batch, bf16, Korthikanti’s formulas), per layer:
| TP size | TP only | TP + SP | TP + selective recompute | TP + SP + selective |
|---|---|---|---|---|
| 1 | 23.8 GB | 23.8 GB | 2.28 GB | 2.28 GB |
| 8 | 3.56 GB | 2.97 GB | 872 MB | 285 MB |
Without recomputation, the attention scores dominate. Once they are recomputed, SP removes the replicated term: 872 MB → 285 MB, 3.1×. Even then, all 80 layers come to 22.8 GB per GPU at . That is why pipelines, which hold fewer layers per GPU, and context parallelism (Lecture 7), which shards the sequence for attention too, follow.
Terminology. In Megatron’s language, SP shards only selected activations within the TP group, to make TP cheaper. Context parallelism (CP) shards inputs and all activations along the sequence, attention included, which needs remote K/V. That is the subject of Lecture 7.
4. Pipeline parallelism
4.1 Cut the depth
Pipeline parallelism splits the model’s depth into ordered stages (阶段), contiguous slabs of layers, one per device. Two facts:
- It shards parameters and optimizer state per device ∼ . Each device holds only its stage’s layers.
- It introduces a schedule of micro-batches (微批次), and SendRecv transfers at the stage boundaries. These are plain point-to-point copies, not collectives.
Only the activations at one block boundary cross each cut, neighbour to neighbour: bytes per micro-batch forward, and the same again for its gradient backward. That makes PP the one cut that is comfortable over slow links between nodes. Its price is time. A stage idles unless it is kept fed, and a single request must traverse the stages in order, so its latency gets worse.
PP is attractive when the model is too deep to fit even with TP and sharded optimizer state, and when you want more GPUs without making TP groups huge. The slides’ checklist runs in order: fit → cut → balance → fill.
4.2 GPipe and the bubble
Pipelining only helps with several items in flight, so the batch is split into micro-batches. In GPipe (Huang et al. 2019) every stage runs all forwards, then all backwards. With equal stages, the last stage cannot start until forward slots have passed, and the first stage finishes backward slots after the last. The step therefore takes slots of , of which each device is busy for :
The bubble (气泡) is idle time during fill and drain. Demo 04 simulates it (4 stages, 8 micro-batches, , ; ’.’ = idle):
GPipe stage 0 |FFFFFFFF.........BBBBBBBBBBBBBBBB|
stage 1 |.FFFFFFFF......BBBBBBBBBBBBBBBB..|
stage 2 |..FFFFFFFF...BBBBBBBBBBBBBBBB....|
stage 3 |...FFFFFFFFBBBBBBBBBBBBBBBB......| 33 units, bubble 27.3% = 3/11
More micro-batches fill the pipeline: gives 46.7% at and 9.9% at . But at a fixed global batch, larger means smaller micro-batches and worse GEMM efficiency. In GPipe, every in-flight micro-batch’s activations must also be kept until its backward: all of them.
4.3 1F1B: the same bubble, bounded memory
1F1B (one forward, one backward; PipeDream-flush, Narayanan et al.) changes the order, not the work. Stage runs warm-up forwards, then strictly alternates one forward and one backward, then drains the remaining backwards:
1F1B stage 0 |FFFF......BBFBBFBBFBBFBB.BB.BB.BB|
stage 1 |.FFF....BBFBBFBBFBBFBBFBB.BB.BB..|
stage 2 |..FF..BBFBBFBBFBBFBBFBBFBB.BB....|
stage 3 |...FBBFBBFBBFBBFBBFBBFBBFBB......| 33 units, bubble 27.3%
Same 33 units, same bubble for equal stage times. The win is memory: stage never holds more than micro-batches in flight (4, 3, 2, 1 here) instead of . Demo 04’s simulator checks exactly. An important consequence: stage 0 holds micro-batches of its layers, which is layers’ worth of activations for one micro-batch, whatever is. PP does not reduce the first stage’s activation memory below one micro-batch of the whole model. It bounds it there.
4.4 Interleaving: more, thinner stages
In interleaved 1F1B (Narayanan et al. 2021) each device holds non-contiguous chunks: device holds virtual stages . Fill and drain then proceed in slots times shorter:
The simulator, using Megatron’s ordering and warm-up count , reproduces this exactly: 15.8% for , , , vs 27.3% for 1F1B. The price is times as many SendRecvs, and more in-flight chunks: 5.5 stage-micro-batches on the first device instead of 4. It also requires to be divisible by . Interleaving pays most at very large scale, where bubbles are costly.
4.5 Zero-bubble: split the backward
A backward pass does two things: the activation gradient (B), , which the previous stage is waiting for, and the weight gradient (W), , which nobody waits for. Zero-bubble schedules (Qi et al. 2024) run B on the critical path and use W to fill the idle slots. With , the paper’s ZB-H1 schedule reduces 1F1B’s bubble to , a third, at 1F1B’s peak memory, through a hand-designed order. Demo 04 implements two greedy approximations:
| Schedule (, ) | step | bubble | memory |
|---|---|---|---|
| 1F1B | 33 units | 27.3% | ≤ 4 micro-batches in flight on stage 0 |
| zero-bubble, memory-capped (≤ 4 in flight on every stage) | 29 units | 17.2% | 1F1B’s peak |
| zero-bubble, W deferred freely | 27 units | 11.1% = | up to 8 W ops pending, each keeping its inputs and output gradients |
The greedy version reaches the paper’s bubble only by letting work, and its memory, pile up. The paper’s contribution is the order that avoids this. Zero-bubble schedules rely on careful balance and add debugging complexity. Like interleaving, they matter most at very large scale.
4.6 Memory in gigabytes (demo 04)
For Llama-3-70B with (10 layers per stage), TP = 8 + SP, selective recomputation and micro-batches of 8k tokens, one stage’s activations are 2.85 GB per micro-batch. The training state is 17.6 GB per GPU (16 B/param over GPUs):
| Schedule | in flight on the first stage | activations | + state | fits 72 GB? |
|---|---|---|---|---|
| GPipe | 32 | 91.3 GB | 109 GB | no |
| 1F1B | 8 | 22.8 GB | 40.5 GB | yes |
| interleaved, | 11.5 | 32.8 GB | 50.4 GB | yes |
This is why production pipelines use 1F1B or its descendants, never plain GPipe at large .
4.7 Balance and communication
The bubble formula assumes equal stages. Real pipelines have stragglers: the first stage holds the embedding, the last the final norm, the LM head and the loss. In steady state the pipeline runs at the pace of its slowest stage, . Demo 04 makes the last stage 1.5× slower (, ). That adds only 12.5% of the total work, yet the step grows from 57 to 81 units (+42%). Spreading the same work evenly gives 64. Balance first, then bubbles: when utilization is low, check the bubble ( too small), then imbalance (uneven ), then boundary communication. Cut at Transformer-block boundaries, where one tensor crosses. Never cut inside an MLP, where , or inside attention, where several tensors would have to cross.
The boundary transfer itself is cheap. For Llama-3-70B at TP = 8 one micro-batch’s boundary tensor is 16.8 MB per TP rank, which takes 339 µs over InfiniBand, against 38.2 ms of forward compute per stage. Adding it to the simulation moves the 1F1B bubble from 17.9% to 18.4%. PP communication is smaller than DP’s gradient sync, but it happens per micro-batch and is serialization-critical: a request cannot skip a stage.
4.8 A real pipeline (demo 05)
Four processes each own two blocks of an 8-layer TinyTransformer: stage 0 also has the embedding, stage 3 the head and the loss. They execute GPipe or 1F1B in exactly schedule_order’s op order. Activations go forward with posted sends (isend) and blocking receives tagged by micro-batch; gradients come back the same way. Three results:
- Same math. After one step of 8 micro-batches, both schedules’ gradients are bit-identical to one process accumulating the same micro-batches in order. Each stage runs the same ops on the same shapes and accumulates micro-batches in the same order. Pipelining changes when work happens, not what is computed.
- Bubble, measured. GPipe 29.7 ms (bubble 38.6%), 1F1B 26.4 ms (34.0%). Simulating each schedule with the measured per-op times predicts 30.9% and 30.3%; the equal-stage formula gives 27.3%. The last stage is slower (it runs the LM head), and every op waits for a message through the OS, so the measured bubbles sit above both. With = 4, 8, 16, the measured 1F1B bubble falls 47.3% → 34.0% → 23.6%, tracking the formula’s 42.9% → 27.3% → 15.8%.
- Memory, measured from the tensors autograd saves. 1F1B’s peak activations relative to GPipe’s are 0.50, 0.38, 0.25 and 0.12 on stages 0–3. That is exactly = 4/8, 3/8, 2/8, 1/8.
4.9 PP in inference, and failure modes
For serving, PP helps fit very large models, but it puts stage-to-stage serialization on every request’s critical path, which raises TPOT. The slides’ rule: use PP in serving when you must for capacity, and compensate with replicas and batching. Failure modes:
| Symptom | Likely cause | Lever |
|---|---|---|
| low utilization despite many GPUs | bubbles (too few micro-batches) | increase ; 1F1B; interleave; zero-bubble |
| OOM with PP | too many in-flight activations | 1F1B; checkpointing; reduce or |
| stage imbalance | uneven layer assignment; expensive first/last layers | rebalance layers; profile; move expensive layers |
| high serving latency | stage serialization | reduce ; use TP or quantization; add replicas |
5. Topology: put the hottest traffic on the fastest links
An H100 cluster is two-level. Inside a node, 8 GPUs share NVLink/NVSwitch: ~1 µs, 450 GB/s per GPU each way. Between nodes, each GPU has its own ~50 GB/s NIC on a rail of the network, at ~3 µs. The slides classify each axis by how often it talks:
| Hotness | Traffic | Placement |
|---|---|---|
| hot: every layer | TP collectives, EP AllToAll (and CP exchanges, Lecture 7); latency-critical, especially in decode | inside the node, NVLink |
| warm: every micro-batch | PP boundary SendRecv; serial for a request | across nodes when depth or capacity needs it |
| cold: every step | DP gradient sync (overlappable); checkpoint I/O; weight loading | across nodes; prefer hierarchical collectives (HSDP) |
The one-line principle: frequent collectives on local links; infrequent ones can span nodes. Keep the hottest collectives inside the smallest domain that still fits the model. Concretely, the global rank order puts TP fastest-varying, so 8 consecutive ranks form one TP group on one node, then PP, then DP (demo 06 Part D). A topology-unaware rank mapping, for example TP groups split across two nodes, turns NVLink-speed collectives into network-speed ones with no change to the code.
6. Composing the axes
6.1 3D, then N-D
The classic training recipe is 3D parallelism (三维并行), Megatron’s PTD-P:
- TP inside a node: wide layers, weight capacity.
- PP across nodes if needed: extreme depth, without huge TP groups.
- DP across replicas: throughput, with communication once per step, overlapped.
It works because it matches the hotness of the communication to the topology: TP is hottest, DP coldest. Beyond 3D, the slides’ mesh shorthand is . ZeRO/FSDP is usually a policy inside DP, deciding what is replicated and what is sharded, rather than a new axis. EP may share an axis with DP or FSDP (Lecture 5 §5.1). Offloading is a sixth knob when HBM capacity is the limit. The order of operations: pick parallelism to satisfy fit first, then tune for throughput, then validate latency (if serving).
6.2 Choosing a layout (demo 06)
layout.py is the back-of-envelope you would do before launching. It covers:
- Memory: ZeRO-1 or ZeRO-3 state, plus 1F1B activations with SP and selective or full recomputation.
- Compute: at 50% of peak.
- Communication: the 1F1B bubble, TP collectives on NVLink, the PP boundary SendRecv, and DP/FSDP exposure on InfiniBand with per-phase overlap.
It searches every TP ∈ {1, 2, 4, 8} × PP ∈ {1, …, 20} × DP layout, with micro-batch sizes 1, 2 and 4, ZeRO-1 or -3, and selective or full recomputation. The target is Llama-3-70B with 8k-token sequences.
Fit first. Of 228 layouts for 64 GPUs, 102 are out of memory and 16 cannot split the batch into whole micro-batches. On 512 GPUs, 124 of 240 fit. All 32 layouts with TP = 1 that fit use full recomputation: without splitting every layer, 8k-token activations only fit if almost none are kept.
Then throughput. The best layouts on 512 GPUs (4.2 M-token global batch):
| layout | memory/GPU | step | MFU | where the time goes |
|---|---|---|---|---|
| TP8 PP1 DP64, micro-batch 2, FSDP, selective | 47.8 GB | 8.69 s | 40.3% | compute 7.33 s, TP 1.35 s |
| TP8 PP1 DP64, micro-batch 1, ZeRO-1 | 59.7 GB | 8.79 s | 39.9% | + 84 ms exposed DP |
| TP8 PP8 DP8, ZeRO-1 | 29.4 GB | 9.67 s | 36.2% | + bubble 952 ms ( = 64) |
| TP8 PP1 DP64, full recompute | 3.55 GB | — | 28.8% | an extra forward |
Six layouts land within 10% of the best. The model is a screen, not an answer: everything in that band is a tie until measured. Sensitivity shows the answer depends on the cluster and the batch, not only on the model:
- With a 2× slower network the best layout becomes TP8 DP64 with ZeRO-1 (37.0%): less sharding across nodes.
- With a 2× faster network it becomes TP4 DP128 with FSDP (44.3%): less TP, more sharding.
- A 4× smaller global batch leaves the PP-free best layout untouched, but it hurts every pipelined layout. TP8 PP8 DP8 drops from 36.2% to 27.9% MFU as its micro-batches fall from 64 to 16.
Automated orchestration. Searching this space by hand does not scale to MoE meshes, heterogeneous clusters or new models. Systems such as Alpa (Zheng et al. 2022) search inter- and intra-operator parallelism automatically, and frameworks expose layouts as configuration (Lecture 8’s AutoModel builds pipelines from Hugging Face models with AutoPipeline). The cost model they optimize is this lecture’s arithmetic.
6.3 Practical recipes
Training (from the slides):
- Capacity: shard so that weights + gradients + optimizer state + activations fit (FSDP/TP/PP/CP).
- Throughput: make large enough for efficient GEMMs and for FSDP to sit above its knee. Avoid tiny micro-batches.
- Topology: put the hottest collectives (TP/EP/CP) on fast fabrics, and push DP/PP outward.
- Validate: profile overlap, PP stage balance and EP router imbalance.
- Iterate: adjust mesh sizes and granularity (wrap units, pipeline chunks, bucket sizes).
Serving:
- Fit weights + KV (TP/PP/CP, quantization, selective offload).
- Meet SLOs by minimizing critical-path collectives for TPOT.
- Separate prefill from decode: different batching and parallel groups (TTFT vs TPOT).
- Scale throughput with replicas and good load balancing.
- Watch tail latency: no cross-node TP/EP on the decode path.
Before launching any run, write down (the slides’ final checklist):
- the objective (throughput vs TTFT/TPOT SLOs);
- the memory budget (state + activations, or weights + KV);
- the mesh factorization and its mapping to the topology;
- the collective inventory: which primitives occur per layer, per micro-batch, per step;
- the overlap plan: which communication is hidden behind which compute;
- the risk list: PP bubbles, EP imbalance, α-dominated decode collectives.
Then a profiler trace can be read against the plan.
7. Summary
- TP splits every layer. The column-parallel expand keeps the activation sharded, and the row-parallel contract reduces the small output. Megatron’s f/g give 2 AllReduces forward + 2 backward per block. Measured: the TP block equals the dense block to rounding.
- TP’s cost is per layer and on the critical path. On NVLink at TP = 8 a Llama-3-70B layer pays 0.19× its compute; across nodes 3.6×. In decode, TP = 8 gives the best TPOT (7.6 ms), and TP = 16 across nodes makes it 17.2 ms. Keep TP inside the node and make it as small as fit and latency allow.
- SP shards along the sequence what TP replicates, with the same communication volume. Saving the shard and re-gathering in backward reaches exactly 1/t of the activations (measured: 0.25 at 4 ranks) for two extra AllGathers.
- PP cuts the depth with point-to-point traffic. Bubble = for GPipe and 1F1B; 1F1B bounds memory at micro-batches (measured: of GPipe). Interleaving gives . Zero-bubble splits B from W to fill idle slots. The slowest stage sets the pace.
- Placement follows hotness: TP (every layer) in the node; PP (every micro-batch) and DP (every step) across nodes.
- Layouts are chosen fit-first. Many land within ~10% of each other, and the winner moves with network speed and batch size. Model, then measure.
8. Common pitfalls
- Assuming TP buys throughput. It buys capacity and per-layer latency; its collectives sit on the critical path of every layer.
- Splitting TP across nodes, or mapping ranks so that a TP group straddles two nodes.
- Choosing TP larger than the KV-head count under GQA (or any TP under MQA) without planning to replicate K/V.
- Expecting SP to shrink activations by without re-gathering. Autograd keeps the gathered GEMM inputs unless you save the shard.
- Forgetting to AllReduce norm gradients under SP. Each rank saw only its tokens.
- Reading 1F1B as a bubble reduction. It is a memory reduction. Bubbles shrink with , interleaving or zero-bubble schedules.
- Tuning bubbles before balance. One slow stage costs more than the bubble.
- Using GPipe with large . Activations grow with .
- Trusting a layout model’s ranking at the 5% level. Measure the top candidates.
9. Exercises
- TP volume. A block with processes a micro-batch of 4 × 2048 tokens in bf16 with TP = 4. How many bytes does each TP AllReduce carry, and how many bytes does each rank send per block in training (ring)?
Answer
Each AllReduce carries = 67.1 MB. Training has 4 per block (2 forward, 2 backward); each ring AllReduce sends = 100.7 MB per rank, so 403 MB per rank per block. SP would send the same.
- Why column then row? What would go wrong if the MLP’s up-projection were row-parallel and the down-projection column-parallel?
Answer
Row-parallel up-projection needs its input sharded along (a scatter of the replicated input) and produces partial outputs. The nonlinearity cannot be applied to partial sums, so you would have to AllReduce the large -wide tensor before SiLU, about 2.7–4× more bytes than reducing the -wide output. Then the column-parallel down-projection would produce a sharded -wide output that needs an AllGather for the residual. More collectives, on bigger tensors.
- Decode TP. A 30 B model (60 GB in bf16, 60 layers, ) is served at batch 1 on H100s. Estimate TPOT for TP = 2, 4, 8 using HBM reads only plus 2 ring AllReduces per layer (NVLink α = 1 µs). Ignore KV.
Answer
Weights per GPU are 30, 15 and 7.5 GB, giving 8.96, 4.48 and 2.24 ms of HBM reads at 3.35 TB/s. AllReduces: = 0.24, 0.72 and 1.68 ms (the 12 KiB payload is negligible). TPOT ≈ 9.2, 5.2 and 3.9 ms. TP = 8 still wins, but the collectives are now 43% of its TPOT. A smaller model or a slower link would move the optimum down.
- SP’s saving. Using Korthikanti’s formula with selective recomputation, compare one layer of a model with at , under TP = 8 with and without SP.
Answer
M. TP alone: = 436 MB. TP + SP: = 143 MB. SP saves 3.1×, with no extra communication volume.
- Bubble. With stages, how many micro-batches do you need for a 1F1B bubble below 10%? What does interleaving with give at that ?
Answer
, so . With at : . Equivalently, interleaving reaches 10% with about a quarter of the micro-batches: gives .
- 1F1B memory. Why does the first stage of a 1F1B pipeline hold the activations of the whole model’s depth for one micro-batch, whatever is? What does that imply for using PP to fit activations?
Answer
Stage 0 holds up to micro-batches in flight, each with layers of activations: layers’ worth. Adding stages does not shrink stage 0’s activation memory; it only shrinks its parameter memory. To cut activations, shrink the micro-batch, recompute, or shard them (TP + SP, CP). (Interleaving even raises stage 0’s in-flight count slightly.)
- Imbalance. A 4-stage pipeline has stage times 1.0, 1.0, 1.0, 1.4 (the last holds the LM head) and runs micro-batches. Estimate the step time relative to perfect balance. What could you move?
Answer
Steady state runs at the slowest stage: about slot-units, vs if the same total work (4.4) were spread evenly: ~27% slower. Move one Transformer layer from the last stage to the first, or give the LM head its own stage (some frameworks do), or use uneven layer counts per stage.
- Placement. You have 4 nodes × 8 GPUs and a layout TP = 4, PP = 2, DP = 4. Propose a rank order. Which collectives cross nodes?
Answer
Order ranks with TP fastest, then PP, then DP: rank = tp + 4·pp + 8·dp. Each TP group of 4 is then inside a node, and so is each PP pair (ranks 0–3 → 4–7 is the stage boundary, also inside node 0): one DP replica per node. Only DP’s gradient sync crosses nodes, the coldest traffic. An alternative order that put the PP stages on different nodes would also be fine, since PP traffic is warm. Splitting a TP group across nodes would not.
10. The related assignment (concepts only)
Spring 2026’s Assignment 1 covered parallelism. Fall 2026’s A1 is performance engineering, and these ideas return in A2 (pre-training on an 8×H100 node) and in the project. The concepts to be able to explain, without code:
- for each linear layer in a block, whether it is column- or row-parallel, and which collective appears where in forward and backward;
- how many bytes a TP or SP block moves per micro-batch, and when that is bandwidth- vs latency-bound;
- how a pipeline schedule’s bubble and memory follow from its op order;
- how to check a parallel implementation: equality with the dense computation within a dtype-appropriate tolerance, bit-for-bit when shapes and accumulation orders match (demo 05);
- how to justify a layout from a written-down memory budget and a collective inventory.
No assignment solutions are given here; the demo code is independent of the course’s starter code.
11. Research directions
- Overlapping TP communication with compute. Async TP, decomposing GEMMs into chunks that overlap with collective pieces, and fusing communication into kernels all aim to hide the per-layer AllReduce. How much of demo 03’s 0.19 ratio can be hidden, and at what kernel complexity?
- Memory-optimal zero-bubble schedules. The gap between our greedy schedules and ZB-H1 is a scheduling problem. Schedules that adapt to measured, unequal stage times (with the LM head, MoE or vision encoders) are open.
- Activation memory as a first-class objective. Choose recomputation per operator, offloading and SP re-gathering together, for a given memory budget and step time.
- Layout search with measured costs. Calibrate
layout.py-style models with a few short profiles, then search; quantify how often the modelled top-5 contains the measured best. - Topology beyond two levels. NVL72-class domains, multi-rail networks and heterogeneous clusters change the hotness-to-link mapping. What layouts become possible when the “node” holds 72 GPUs?
12. Further reading
- M. Shoeybi et al., Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism (arXiv:1909.08053): column/row parallel layers, f and g.
- D. Narayanan et al., Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM (SC 2021, arXiv:2104.04473): PTD-P composition, interleaved 1F1B, placement.
- V. Korthikanti et al., Reducing Activation Recomputation in Large Transformer Models (arXiv:2205.05198): sequence parallelism, selective recomputation, the activation formulas.
- Y. Huang et al., GPipe (NeurIPS 2019); D. Narayanan et al., PipeDream (SOSP 2019).
- P. Qi, X. Wan, G. Huang, M. Lin, Zero Bubble Pipeline Parallelism (ICLR 2024, arXiv:2401.10241).
- Hugging Face, The Ultra-Scale Playbook; the Pipeline-parallelism schedule visualizer (interactive).
- L. Zheng et al., Alpa: Automating Inter- and Intra-Operator Parallelism for Distributed Deep Learning (OSDI 2022).
13. Next lecture
Lecture 7 · Attention and MoE Kernels: FlashAttention, Context Parallelism, SonicMoE. Attention’s scores were the term that dominated today’s activation formula until recomputed. FlashAttention removes them from HBM with online softmax and tiling. On top of FlashAttention’s blockwise kernels we build the sequence dimension’s parallelism, deferred today: context parallelism with ring attention, Ulysses AllToAll, and causal load balancing. Then MoE at the kernel level: saved activations vs temporary buffers, grouped GEMMs overlapped with IO, and SonicMoE’s token rounding.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| tensor parallelism (TP) | 张量并行 |
| column-parallel / row-parallel linear | 列并行 / 行并行线性层 |
| partial sum / replicated / sharded | 部分和 / 复制 / 分片 |
| head partitioning | 按注意力头切分 |
| residual boundary / replication point | 残差边界 / 复制点 |
| Megatron f / g operator | Megatron 的 f / g 算子 |
| conjugate collective (forward vs backward) | 共轭通信(前向与反向互为对偶) |
| async TP / communication–computation overlap | 异步张量并行 / 通信计算重叠 |
| 2D tensor parallelism / SUMMA | 二维张量并行 / SUMMA 矩阵乘算法 |
| skinny GEMM / wave quantization | 瘦长矩阵乘 / 波次量化 |
| sequence parallelism (SP) | 序列并行 |
| token-wise operation | 逐 token 运算 |
| selective / full activation recomputation | 选择性 / 完全激活重计算 |
| re-gathering (save the shard, gather again) | 反向时重新收集 |
| saved tensors / saved-tensor hooks | 为反向保存的张量 / 保存张量钩子 |
| context parallelism (CP) | 上下文并行 |
| pipeline parallelism (PP) / stage | 流水线并行 / 阶段 |
| micro-batch / in-flight micro-batches | 微批次 / 在途微批次 |
| pipeline bubble / fill / drain | 流水线气泡 / 填充 / 排空 |
| GPipe / 1F1B / PipeDream-flush | GPipe / 一前一后 / PipeDream-flush |
| warm-up / steady state / cool-down | 预热 / 稳态 / 收尾 |
| interleaved schedule / virtual stage / model chunk | 交错调度 / 虚拟阶段 / 模型块 |
| zero-bubble / activation gradient (B) / weight gradient (W) | 零气泡 / 激活梯度 / 权重梯度 |
| stage imbalance / straggler stage | 阶段不均衡 / 最慢阶段 |
| point-to-point (SendRecv) | 点对点通信 |
| NVLink domain / scale-up vs scale-out | NVLink 域 / 纵向 vs 横向扩展 |
| hot / warm / cold traffic | 热 / 温 / 冷流量 |
| rank mapping / topology-aware placement | 秩映射 / 拓扑感知放置 |
| 3D parallelism (PTD-P) / N-D mesh | 三维并行 / 多维设备网格 |
| layout search / automated parallelization | 布局搜索 / 自动并行化 |
| fit first, then throughput, then latency | 先放得下,再求吞吐,最后验证延迟 |