Lecture 6 · Parallelism II: Tensor, Sequence, Pipeline and N-D Parallelism

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 06。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

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 from code/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:

  1. 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.
  2. 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.
  3. Shard what TP replicates. Explain sequence parallelism, why it costs no extra communication, and what saving the shard instead of the gathered input buys.
  4. 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.
  5. Compose and place. Factor NGPUs=NdpNtpNpp(NcpNep)N_{\text{GPUs}} = N_{dp} N_{tp} N_{pp} (N_{cp} N_{ep}), 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

SectionIdeaCode in code/lecture06/
§2.1–2.4column/row-parallel layers, the Megatron block, f and gtensor_parallel.py, 01_tp_layers.py
§2.5–2.6what TP costs on H100s, training and decode03_tp_cost_model.py
§3sequence parallelism and re-gatheringtensor_parallel.py, 02_sequence_parallel.py
§4.1–4.7pipeline schedules, bubbles, memory, balancepipeline.py, 04_pipeline_schedules.py
§4.8a real 4-stage pipeline05_real_pipeline.py
§5–6topology, composition, layout searchlayout.py, 06_layout_search.py

0.4 Notation

As in Lecture 5 (pp ranks in a group, α\alpha, β\beta, BtokB_{\text{tok}}, DD, FF). New today:

SymbolMeaning
tt (or NtpN_{tp})tensor-parallel group size
pp (or NppN_{pp})pipeline stages (devices in the pipeline)
mmmicro-batches per optimizer step per pipeline
vvmodel chunks per device in an interleaved pipeline (“virtual stages”)
tF,tB,tWt_F, t_B, t_Wtime of one micro-batch’s forward / backward (activation gradient) / weight gradient on one stage
s,b,d,as, b, d, asequence length, micro-batch size, model width, attention heads (Korthikanti’s notation)
Wq,Wk,Wv,WoW_q, W_k, W_v, W_oattention projections; Wgate,Wup,WdownW_{\text{gate}}, W_{\text{up}}, W_{\text{down}}: SwiGLU MLP

1. What FSDP leaves on the table

Lecture 5 ended with two things that FSDP never shards:

  1. 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.
  2. Activations. Every rank computes and stores full-width activations for its own tokens: norm inputs, attention scores, the Btok×FB_{\text{tok}} \times F 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 BtokB_{\text{tok}} 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, Y=XWY = XW with X∈RBtok×DX \in \mathbb{R}^{B_{\text{tok}} \times D}, W∈RD×FW \in \mathbb{R}^{D \times F}, Y∈RBtok×FY \in \mathbb{R}^{B_{\text{tok}} \times F}, and a TP group of size tt:

  • Column-parallel (列并行): shard the output features, W=[W0∣W1∣… ]W = [W_0 \mid W_1 \mid \dots] with F/tF/t columns each. With XX replicated, rank rr computes Yr=XWrY_r = X W_r, its slice of the output, with no communication. YY comes out sharded, and you only AllGather it if the next op needs the full tensor.
  • Row-parallel (行并行): shard the input features, W=[W0;W1;… ]W = [W_0; W_1; \dots] with D/tD/t rows each. With XX already sharded the same way, rank rr computes a partial sum (部分和) Y~(r)=XrWr\tilde Y^{(r)} = X_r W_r of the full output, and an AllReduce gives Y=∑rY~(r)Y = \sum_r \tilde Y^{(r)}.

(In PyTorch’s nn.Linear the weight is stored as (F,D)(F, D), 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 tt partial sums are rounded differently from one long sum.

2.2 The Megatron pairing: synchronize where the tensor is small

A Transformer MLP expands D→F≈4DD \to F \approx 4D (SwiGLU: 83D\frac{8}{3}D, with two up-matrices), then contracts F→DF \to D. Megatron combines the two kinds of split:

  • expand (column-parallel): the large Btok×FB_{\text{tok}} \times F activation stays sharded, F/tF/t per rank, and the elementwise nonlinearity runs locally on each shard;
  • contract (row-parallel): the reduction happens on the small Btok×DB_{\text{tok}} \times D 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 (按头切分). Wq,Wk,WvW_q, W_k, W_v are column-parallel, so each rank gets N/tN/t query heads with their K/V heads, and attention for those heads is entirely local. WoW_o is row-parallel, so the reduction lands on the Btok×DB_{\text{tok}} \times D residual stream. With GQA, rank rr owns query heads [rN/t,(r+1)N/t)[rN/t, (r+1)N/t) and KV heads [rNKV/t,(r+1)NKV/t)[rN_{KV}/t, (r+1)N_{KV}/t), exactly the KV heads its query heads read. That requires NKVN_{KV} to be divisible by tt. 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 Btok×DB_{\text{tok}} \times D tensor, which is why every TP reduction in a block lands on a DD-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):

OperatorForwardBackwardSits
fidentity (input already replicated)AllReduce (each rank’s input gradient is partial)before WqkvW_{qkv} and before Wgate,WupW_{\text{gate}}, W_{\text{up}}
gAllReduce (sum the partial outputs)identity (the output gradient is already full on every rank)after WoW_o and after WdownW_{\text{down}}

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 Btok×DB_{\text{tok}} \times D 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 B×s×DB \times s \times D 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: tt 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 (d=512d = 512, 512 tokens) is honest about the obstacles:

TP ranksTP blockits 1/t of the compute aloneits 4 AllReduces alone
110.5 ms10.3 ms—
29.59 ms7.29 ms2.01 ms
415.2 ms6.18 ms3.75 ms

Three things eat the ideal tt-fold speed-up:

  1. 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.
  2. The 4 AllReduces cost 3.75 ms at 4 ranks.
  3. 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 BtokD⋅2B_{\text{tok}} D \cdot 2 bytes = 134 MB. Per layer, with compute at 50% of the BF16 peak:

TP sizelinkcompute per GPU4 AllReducescomm / compute
2NVLink45.8 ms1.20 ms0.03
4NVLink22.9 ms1.81 ms0.08
8NVLink11.5 ms2.14 ms0.19
162 nodes, InfiniBand5.73 ms20.5 ms3.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 BtokB_{\text{tok}} 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 D=8192D = 8192. 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 size1 request: TPOTof which AllReduces32 requests: TPOT
1does not fit (142 GB)—does not fit
221.6 ms0.33 msdoes not fit (92 GB)
411.6 ms0.97 ms15.0 ms
87.57 ms2.25 ms9.43 ms
16 (2 nodes)17.2 ms14.5 ms21.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 NtpN_{tp} that fits your weights per shard while meeting latency/throughput goals. Serving pushes NtpN_{tp} 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 (Btok×8192)⋅(8192×3584)(B_{\text{tok}} \times 8192) \cdot (8192 \times 3584):

  • In training (BtokB_{\text{tok}} = 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 NtpN_{tp} grows”.

2.6 TP failure modes, and 2D TP

The slides’ table, condensed:

SymptomLikely causeLever
TPOT grows with NtpN_{tp}α-dominated collectives on the decode pathkeep TP in the node; reduce NtpN_{tp}; add replicas
low throughput despite TPmicro-batches too small, skinny GEMMsraise BtokB_{\text{tok}} (DP, accumulation); reduce PP bubbles
cross-node TP is terribleper-layer collectives on slow links; topology-unaware rank mappingTP inside the node, PP across nodes (§5)
OOM in activations with TPreplicated tensors / AllGathersSP (§3), CP (Lecture 7), checkpointing
collectives don’t overlap computecollectives on the critical path, no asyncasync TP, fuse/reorder communication, tune NCCL
sawtooth utilization / hangsimbalance across TP ranks; collective order mismatch; flaky fabricbalance 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 tt ranks: the residual stream, both norms and their saved inputs, dropout masks (in models that use dropout), and the full Btok×DB_{\text{tok}} \times D 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:

activations per layer=s b d(10+24t+5 a sd t)\text{activations per layer} = s\,b\,d\left(10 + \frac{24}{t} + \frac{5\,a\,s}{d\,t}\right)

The 10 sbd10\,sbd term does not shrink with tt. With the attention scores recomputed (selective recomputation, or FlashAttention, Lecture 7), the formula becomes sbd(10+24/t)sbd(10 + 24/t), and the replicated 10 dominates once t≥4t \ge 4.

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 s/ts/t 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 Btok×DB_{\text{tok}} \times D 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 Wq,Wk,WvW_q, W_k, W_v (or Wgate,WupW_{\text{gate}}, W_{\text{up}}) 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:

Variantcollectivessent per ranksaved activations per rank (measured)fraction of dense
dense (1 rank)——957 kB1.00
TPAllReduce ×4197 kB392 kB0.41
TP + SPAllGather ×4, ReduceScatter ×4 (+ norm-gradient AllReduce)197 kB293 kB0.31
TP + SP, re-gatherAllGather ×6, ReduceScatter ×4 (+ norm AllReduce)247 kB244 kB0.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 1/t1/t, 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 sizeTP onlyTP + SPTP + selective recomputeTP + SP + selective
123.8 GB23.8 GB2.28 GB2.28 GB
83.56 GB2.97 GB872 MB285 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 t=8t = 8. 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 pp ordered stages (阶段), contiguous slabs of layers, one per device. Two facts:

  • It shards parameters and optimizer state per device ∼ 1/p1/p. 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: Btok,μ⋅D⋅bB_{\text{tok},\mu} \cdot D \cdot b 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 mm micro-batches. In GPipe (Huang et al. 2019) every stage runs all mm forwards, then all mm backwards. With equal stages, the last stage cannot start until p−1p - 1 forward slots have passed, and the first stage finishes p−1p - 1 backward slots after the last. The step therefore takes (m+p−1)(m + p - 1) slots of (tF+tB)(t_F + t_B), of which each device is busy for mm:

bubble fraction  =  p−1m+p−1.\text{bubble fraction} \;=\; \frac{p - 1}{m + p - 1}.

The bubble (气泡) is idle time during fill and drain. Demo 04 simulates it (4 stages, 8 micro-batches, tF=1t_F = 1, tB=2t_B = 2; ’.’ = 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: p=8p = 8 gives 46.7% at m=8m = 8 and 9.9% at m=64m = 64. But at a fixed global batch, larger mm 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 mm 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 dd runs p−d−1p - d - 1 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 dd never holds more than p−dp - d micro-batches in flight (4, 3, 2, 1 here) instead of mm. Demo 04’s simulator checks p−dp - d exactly. An important consequence: stage 0 holds pp micro-batches of its L/pL/p layers, which is LL layers’ worth of activations for one micro-batch, whatever pp 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 vv non-contiguous chunks: device dd holds virtual stages d,d+p,d+2p,…d, d + p, d + 2p, \dots. Fill and drain then proceed in slots vv times shorter:

bubble  ≈  p−1v m+p−1.\text{bubble} \;\approx\; \frac{p - 1}{v\,m + p - 1}.

The simulator, using Megatron’s ordering and warm-up count 2(p−d−1)+(v−1)p2(p - d - 1) + (v - 1)p, reproduces this exactly: 15.8% for p=4p = 4, m=8m = 8, v=2v = 2, vs 27.3% for 1F1B. The price is vv times as many SendRecvs, and more in-flight chunks: 5.5 stage-micro-batches on the first device instead of 4. It also requires mm to be divisible by pp. 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), ∂L/∂X\partial L/\partial X, which the previous stage is waiting for, and the weight gradient (W), ∂L/∂W\partial L/\partial 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 tF=tB=tWt_F = t_B = t_W, the paper’s ZB-H1 schedule reduces 1F1B’s bubble (p−1)(tF+tB+tW)(p-1)(t_F + t_B + t_W) to (p−1)(tF+tB−tW)(p-1)(t_F + t_B - t_W), a third, at 1F1B’s peak memory, through a hand-designed order. Demo 04 implements two greedy approximations:

Schedule (p=4p = 4, m=8m = 8)stepbubblememory
1F1B33 units27.3%≤ 4 micro-batches in flight on stage 0
zero-bubble, memory-capped (≤ 4 in flight on every stage)29 units17.2%1F1B’s peak
zero-bubble, W deferred freely27 units11.1% = (p−1)(tF+tB−tW)(p-1)(t_F+t_B-t_W)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 p=8p = 8 (10 layers per stage), TP = 8 + SP, selective recomputation and m=32m = 32 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 8×88 \times 8 GPUs):

Schedulein flight on the first stageactivations+ statefits 72 GB?
GPipe3291.3 GB109 GBno
1F1B822.8 GB40.5 GByes
interleaved, v=2v = 211.532.8 GB50.4 GByes

This is why production pipelines use 1F1B or its descendants, never plain GPipe at large mm.

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, tclock≈max⁡itit_{\text{clock}} \approx \max_i t_i. Demo 04 makes the last stage 1.5× slower (p=4p = 4, m=16m = 16). 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 (mm too small), then imbalance (uneven tit_i), then boundary communication. Cut at Transformer-block boundaries, where one Btok,μ×DB_{\text{tok},\mu} \times D tensor crosses. Never cut inside an MLP, where F≈4DF \approx 4D, 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 mm = 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 (p−d)/m(p - d)/m = 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:

SymptomLikely causeLever
low utilization despite many GPUsbubbles (too few micro-batches)increase mm; 1F1B; interleave; zero-bubble
OOM with PPtoo many in-flight activations1F1B; checkpointing; reduce mm or BμB_\mu
stage imbalanceuneven layer assignment; expensive first/last layersrebalance layers; profile; move expensive layers
high serving latencystage serializationreduce NppN_{pp}; use TP or quantization; add replicas

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:

HotnessTrafficPlacement
hot: every layerTP collectives, EP AllToAll (and CP exchanges, Lecture 7); latency-critical, especially in decodeinside the node, NVLink
warm: every micro-batchPP boundary SendRecv; serial for a requestacross nodes when depth or capacity needs it
cold: every stepDP gradient sync (overlappable); checkpoint I/O; weight loadingacross 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:

NGPUs=Ndp⋅Ntp⋅NppN_{\text{GPUs}} = N_{dp} \cdot N_{tp} \cdot N_{pp}

  • 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 N≈NdpNtpNppNcpNepN \approx N_{dp} N_{tp} N_{pp} N_{cp} N_{ep}. 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):

layoutmemory/GPUstepMFUwhere the time goes
TP8 PP1 DP64, micro-batch 2, FSDP, selective47.8 GB8.69 s40.3%compute 7.33 s, TP 1.35 s
TP8 PP1 DP64, micro-batch 1, ZeRO-159.7 GB8.79 s39.9%+ 84 ms exposed DP
TP8 PP8 DP8, ZeRO-129.4 GB9.67 s36.2%+ bubble 952 ms (mm = 64)
TP8 PP1 DP64, full recompute3.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):

  1. Capacity: shard so that weights + gradients + optimizer state + activations fit (FSDP/TP/PP/CP).
  2. Throughput: make BtokB_{\text{tok}} large enough for efficient GEMMs and for FSDP to sit above its knee. Avoid tiny micro-batches.
  3. Topology: put the hottest collectives (TP/EP/CP) on fast fabrics, and push DP/PP outward.
  4. Validate: profile overlap, PP stage balance and EP router imbalance.
  5. Iterate: adjust mesh sizes and granularity (wrap units, pipeline chunks, bucket sizes).

Serving:

  1. Fit weights + KV (TP/PP/CP, quantization, selective offload).
  2. Meet SLOs by minimizing critical-path collectives for TPOT.
  3. Separate prefill from decode: different batching and parallel groups (TTFT vs TPOT).
  4. Scale throughput with replicas and good load balancing.
  5. Watch tail latency: no cross-node TP/EP on the decode path.

Before launching any run, write down (the slides’ final checklist):

  1. the objective (throughput vs TTFT/TPOT SLOs);
  2. the memory budget (state + activations, or weights + KV);
  3. the mesh factorization and its mapping to the topology;
  4. the collective inventory: which primitives occur per layer, per micro-batch, per step;
  5. the overlap plan: which communication is hidden behind which compute;
  6. the risk list: PP bubbles, EP imbalance, α-dominated decode collectives.

Then a profiler trace can be read against the plan.


7. Summary

  1. TP splits every layer. The column-parallel expand keeps the Btok×FB_{\text{tok}} \times F activation sharded, and the row-parallel contract reduces the small Btok×DB_{\text{tok}} \times D output. Megatron’s f/g give 2 AllReduces forward + 2 backward per block. Measured: the TP block equals the dense block to rounding.
  2. 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.
  3. 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.
  4. PP cuts the depth with point-to-point traffic. Bubble = (p−1)/(m+p−1)(p-1)/(m+p-1) for GPipe and 1F1B; 1F1B bounds memory at p−dp - d micro-batches (measured: (p−d)/m(p-d)/m of GPipe). Interleaving gives (p−1)/(vm+p−1)(p-1)/(vm+p-1). Zero-bubble splits B from W to fill idle slots. The slowest stage sets the pace.
  5. Placement follows hotness: TP (every layer) in the node; PP (every micro-batch) and DP (every step) across nodes.
  6. 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 1/t1/t 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 mm, interleaving or zero-bubble schedules.
  • Tuning bubbles before balance. One slow stage costs more than the bubble.
  • Using GPipe with large mm. Activations grow with mm.
  • Trusting a layout model’s ranking at the 5% level. Measure the top candidates.

9. Exercises

  1. TP volume. A block with D=4096D = 4096 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 BtokDb=8192⋅4096⋅2B_{\text{tok}} D b = 8192 \cdot 4096 \cdot 2 = 67.1 MB. Training has 4 per block (2 forward, 2 backward); each ring AllReduce sends 2t−1tn=1.5×67.12\frac{t-1}{t}n = 1.5 \times 67.1 = 100.7 MB per rank, so 403 MB per rank per block. SP would send the same.

  1. 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 DD (a scatter of the replicated input) and produces partial Btok×FB_{\text{tok}} \times F outputs. The nonlinearity cannot be applied to partial sums, so you would have to AllReduce the large FF-wide tensor before SiLU, about 2.7–4× more bytes than reducing the DD-wide output. Then the column-parallel down-projection would produce a sharded DD-wide output that needs an AllGather for the residual. More collectives, on bigger tensors.

  1. Decode TP. A 30 B model (60 GB in bf16, 60 layers, D=6144D = 6144) 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: 120×2(t−1) μs120 \times 2(t-1)\,\mu s = 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.

  1. SP’s saving. Using Korthikanti’s formula with selective recomputation, compare one layer of a model with d=8192d = 8192 at s=4096s = 4096, b=1b = 1 under TP = 8 with and without SP.
Answer

sbd=4096⋅8192=33.6sbd = 4096 \cdot 8192 = 33.6 M. TP alone: sbd(10+24/8)=13 sbdsbd(10 + 24/8) = 13\,sbd = 436 MB. TP + SP: 34/8 sbd=4.25 sbd34/8\,sbd = 4.25\,sbd = 143 MB. SP saves 3.1×, with no extra communication volume.

  1. Bubble. With p=16p = 16 stages, how many micro-batches do you need for a 1F1B bubble below 10%? What does interleaving with v=4v = 4 give at that mm?
Answer

(p−1)/(m+p−1)<0.1  ⟺  m>9(p−1)=135(p-1)/(m+p-1) < 0.1 \iff m > 9(p-1) = 135, so m≥136m \ge 136. With v=4v = 4 at m=136m = 136: 15/(544+15)=2.7%15/(544 + 15) = 2.7\%. Equivalently, interleaving reaches 10% with about a quarter of the micro-batches: m=34m = 34 gives 15/151=9.9%15/151 = 9.9\%.

  1. 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 pp is? What does that imply for using PP to fit activations?
Answer

Stage 0 holds up to pp micro-batches in flight, each with L/pL/p layers of activations: p⋅L/p=Lp \cdot L/p = L 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.)

  1. Imbalance. A 4-stage pipeline has stage times 1.0, 1.0, 1.0, 1.4 (the last holds the LM head) and runs m=32m = 32 micro-batches. Estimate the step time relative to perfect balance. What could you move?
Answer

Steady state runs at the slowest stage: about (m+p−1)×1.4=35×1.4=49(m + p - 1) \times 1.4 = 35 \times 1.4 = 49 slot-units, vs 35×1.1=38.535 \times 1.1 = 38.5 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.

  1. 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.

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 L×LL \times L 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 operatorMegatron 的 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-flushGPipe / 一前一后 / 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-outNVLink 域 / 纵向 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先放得下,再求吞吐,最后验证延迟
← 返回课程目录