Lecture 20 · Parallelism and Distributed Training

Advanced Natural Language Processing · Lecture 20。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 20 (03/31), “Parallelism and Scaling”, Sean Welleck; slides anlp-s2026-20-scaling-parallelism.pdf (content based on The Ultra-Scale Playbook); course code 20_parallelism/ (basic_comm.py, dist_sgd.py). Reading: N. Tazi et al., The Ultra-Scale Playbook: Training LLMs on GPU Clusters (Hugging Face, 2025). Sources: the public slides and code, the Playbook, and the papers cited in each section. Numbers quoted from papers are attributed to them. Every number labelled “measured” comes from code/lecture20/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14). Large-model numbers labelled “computed” come from formulas in budget.py, not from GPUs. Code: code/lecture20/ — five demos, each under 10 seconds. Reading time: ~90 minutes for the prose; ~15 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Compute the memory of a training step (weights, gradients, optimizer states, activations) and its compute (6ND), and explain MFU.
  2. Explain activation recomputation and gradient accumulation, what each trades, and how to normalize an accumulated loss correctly.
  3. Define the collective operations (all-reduce, reduce-scatter, all-gather, …) and explain why the ring all-reduce is bandwidth-optimal.
  4. Describe data parallelism, overlap and bucketing, and the global-batch arithmetic gbs=mbs×grad_acc×dp\text{gbs} = \text{mbs} \times \text{grad\_acc} \times \text{dp}.
  5. Explain ZeRO stages 1–3 (and FSDP): what each shards, what it saves, what it costs in communication.
  6. Derive tensor parallelism (column- then row-parallel) and pipeline parallelism (bubbles, AFAB vs 1F1B), and say when each is used.
  7. Choose a parallel configuration in three steps: fit in memory, reach the global batch, maximize throughput.

0.2 Prerequisites and scope

  • Prerequisites:
    • Lecture 5: the Transformer block, attention heads, the FFN.
    • Lecture 7: C≈6NDC \approx 6ND.
    • Lecture 19: number formats and bytes per parameter.
  • Scope: the slides’ outline, following the Ultra-Scale Playbook: training on one GPU (compute, memory, recomputation, accumulation), then data parallelism, communication primitives, tensor and pipeline parallelism, ZeRO, and choosing strategies.
  • Not in scope:
    • Context (sequence) parallelism and ring attention: Lecture 22.
    • Expert parallelism: Lecture 21.
    • Kernel-level optimization, fault tolerance, and cluster networking hardware beyond a bandwidth number.

0.3 Section → code map

SectionIdeaDemo in code/lecture20/
§2compute, memory, activations, recomputation, accumulation01_memory_compute.py (+ budget.py)
§3collectives, ring all-reduce, costs, real processes02_collectives.py (+ collectives.py)
§4data parallelism, overlap, batch arithmetic03_data_parallel_zero.py Parts A–D (+ parallel_sim.py)
§5ZeRO03_data_parallel_zero.py Part E
§6–7tensor and pipeline parallelism04_tensor_pipeline.py
§8choosing a strategy05_choosing_strategy.py

0.4 Notation

SymbolMeaning
NN (or Ψ\Psi)number of parameters
DDnumber of training tokens (per step or in total)
L,h,aL, h, alayers, hidden size, attention heads
ss, bbsequence length, (micro-)batch size in sequences
mbs, grad_acc, gbsmicro-batch size, gradient-accumulation steps, global batch size
dp, tp, ppnumber of data-, tensor- and pipeline-parallel ranks
ppnumber of ranks in a collective
α,β\alpha, \betalatency per message, bandwidth (bytes per second)

1. Why one GPU is not enough

Lecture 7’s scaling laws said: bigger models, trained on more data, reach lower loss. The slides’ framing: take advantage of many devices to

  • train larger models than fit on one GPU, and
  • process more tokens per second.

Three concerns run through the whole lecture:

  1. Memory usage: a training step must fit in each device’s memory.
  2. Compute efficiency: the hardware should spend most of its time computing.
  3. Communication overhead: moving data between devices leaves GPUs idle, so minimize it or hide it behind computation.

Every technique below moves some of the burden between these three. Before splitting anything, we need to know what one training step costs on one GPU.


2. Training on one GPU

2.1 Compute: FLOPs, FLOPS and MFU

A forward pass multiplies every weight once per token: one multiply and one add, 2 FLOPs per parameter per token. The backward pass computes two gradients per weight matrix, w.r.t. its input and w.r.t. itself, so 4 FLOPs. In total:

FLOPs per step≈6×N×tokens.\text{FLOPs per step} \approx 6 \times N \times \text{tokens}.

NN counts the parameters that take part in matrix products; the embedding lookup is free. Attention adds QK⊤QK^\top and AVAV, which have no parameters: 12 L s h12\,L\,s\,h FLOPs per token for forward plus backward.

Measured (demo 01 Part D): PyTorch’s FLOP counter on Lecture 5’s Transformer gives exactly 6ND+12LshD6ND + 12LshD (ratio 1.000000 for three batch shapes). The rule is exact for matrix products, and the counter skips elementwise operations.

FLOPS (FLOPs per second) measure hardware. An H100 peaks at about 989 TFLOPS for dense bf16. Model FLOPs utilization is the share of that peak a training run achieves:

MFU=6ND/timenumber of GPUs×peak FLOPS.\text{MFU} = \frac{6 N D / \text{time}}{\text{number of GPUs} \times \text{peak FLOPS}}.

The losses come from communication, memory bandwidth (elementwise operations move bytes without computing) and idle time. For scale: Llama 3 405B (Dubey et al., 2024) was trained on 15.6T tokens, 6×406B×15.6T=3.8×10256 \times 406\text{B} \times 15.6\text{T} = 3.8 \times 10^{25} FLOPs. At 400 TFLOPS per GPU (MFU 40%, close to the paper’s reported 38–43%) on 16,384 H100s, that is about 67 days (computed).

2.2 Memory: where the bytes go

A training step holds four kinds of tensors. The slides’ rough budget for mixed-precision training with Adam:

peak memory=2N⏟bf16 model+4N⏟fp32 model+4N⏟fp32 grads+8N⏟Adam m,v+activations.\text{peak memory} = \underbrace{2N}_{\text{bf16 model}} + \underbrace{4N}_{\text{fp32 model}} + \underbrace{4N}_{\text{fp32 grads}} + \underbrace{8N}_{\text{Adam } m, v} + \text{activations}.

That is 18 bytes per parameter:

  • The bf16 copy runs the forward and backward passes.
  • The fp32 “master” copy receives the updates. Lecture 19, §2.4 showed why: in bf16, small updates are rounded away.
  • Adam keeps two fp32 moments per parameter.

ZeRO (Rajbhandari et al., 2020) counts 16 bytes, with fp16 gradients. Demo 01 computes it for Llama 3:

modelparametersFFN sharemodel states (GB)H100s (80 GB) just to hold them
Llama 3 8B8.03B70%1451.8
Llama 3 70B70.55B80%1,27015.9
Llama 3 405B405.85B81%7,30591.3

Even the 8B model cannot be trained on one 80 GB GPU this way, before a single activation is stored. Inference needs only the bf16 weights (16 GB for 8B); training needs 9× more.

2.3 Activations, and why batch size is a memory question

The backward pass needs the forward pass’s intermediate results: the inputs of every matrix product, norm and nonlinearity. These activations grow with the batch. For a GPT-style block in 16-bit, Korthikanti et al. (2022) count, per layer (the slides’ formula):

mact=L⋅s⋅b⋅h⋅(34+5 a sh) bytes.m_{\text{act}} = L \cdot s \cdot b \cdot h \cdot \left(34 + \frac{5\, a\, s}{h}\right) \text{ bytes}.

It has two parts:

  • 34 sbh34\,sbh: inputs of the linear layers, norms, activation functions, dropout masks. Linear in sequence length.
  • 5 as2b5\,a s^2 b: the s×ss \times s attention scores, softmax output and dropout mask of every head. Quadratic in sequence length.

Computed for Llama 3 8B, one sequence:

sequence lengthactivationswithout the s2s^2 termfull recomputation
2,04830.6 GB9.1 GB0.5 GB
4,096104.2 GB18.3 GB1.1 GB
8,192380.1 GB36.5 GB2.1 GB

At long sequences the attention matrices dominate everything. FlashAttention (Lecture 22) never stores them, which removes the s2s^2 term.

Measured (demo 01 Part C) on Lecture 5’s model, counting the tensors autograd saves (with saved_tensors_hooks):

  • twice the batch → ×1.99 activation memory: linear;
  • 32 → 64 tokens → ×2.16, and 128 → 256 → ×2.51: faster than linear, the s2s^2 term growing.

The batch size, in tokens b⋅sb \cdot s, is therefore a memory decision as well as an optimization one. Small batches adjust parameters quickly but noisily, and large ones accurately with fewer steps. LLM pretraining typically uses 4–60 million tokens per batch (slides). That is far more than any GPU’s activations can hold at once, which is where the next two techniques come in.

2.4 Activation recomputation

Recomputation (gradient checkpointing; Chen et al., 2016) keeps only some activations (“checkpoints”) during the forward pass. It recomputes the rest during backward, trading compute for memory.

  • Full: keep each layer’s input only (2sbh2sbh bytes per layer) and recompute the whole layer in backward. The cost is about one extra forward pass, ×4/3 compute, since forward is a third of forward + backward.
  • Selective (Korthikanti et al., 2022): recompute only the attention scores. They are large (s2s^2) but cheap to recompute. This removes the quadratic term for a few percent of compute.

Measured: checkpointing every block cuts saved activations by 91–94% at the cost of ×1.26 FLOPs. That is a little under 4/3: PyTorch’s non-reentrant checkpointing stops recomputing a block as soon as backward has what it needs, and each block’s last matrix product is never re-run.

2.5 Gradient accumulation

To reach a global batch larger than memory allows, split it into micro-batches. Run forward and backward on each, add up the gradients, and update once:

gbs=mbs×grad_acc.\text{gbs} = \text{mbs} \times \text{grad\_acc}.

Memory stays that of one micro-batch; the cost is time, since micro-batches run one after another.

The subtle part is normalization. The batch loss is a mean over tokens. If micro-batches hold different numbers of tokens (variable-length sentences, padding), averaging each micro-batch’s own mean is not the batch mean. The correct recipe: each micro-batch contributes (its token-loss sum) / (tokens in the whole batch).

Measured (demo 01 Part E; 32 sentences in 4 micro-batches of 101, 72, 64 and 96 tokens):

how each micro-batch’s loss is scaledrelative gradient error vs one big batch
token-loss sum / tokens in the whole batch3.7e-07 (float rounding)
its own mean loss / 48.7e-02

The shortcut is off by 9%. The same mistake was found in widely used fine-tuning libraries in 2024. Data parallelism (§4) has the same issue.

2.6 Recap: one GPU

  • Compute is 6ND6ND; MFU measures how much of the peak we use.
  • Memory = model states (18 bytes per parameter) + activations (linear in batch, quadratic in sequence length).
  • Recomputation saves activation memory for extra compute; accumulation reaches large batches for extra time.
  • The savings buy a larger batch or a larger model, until one GPU is no longer enough.

3. Communication: the collective operations

3.1 The primitives

Distributed training needs a few standard patterns of communication among pp processes (ranks). The slides’ “communication ops”; demo 02 shows each on 4 ranks, where rank rr starts with [1,2,3,4]+10r[1, 2, 3, 4] + 10r:

operationresultused by
broadcastroot’s tensor → everyoneinitial weights
reducesum of all → root—
all-reducesum of all → everyone ([64 68 72 76] on every rank)data parallelism, TP
gathereveryone’s → root—
all-gathereveryone’s → everyone (concatenated)ZeRO-3, sequence parallelism
scatterroot’s chunk ii → rank ii—
reduce-scattersum of everyone’s chunk ii → rank ii (64, 68, 72, 76)ZeRO-2/3
all-to-allrank jj‘s chunk ii → rank iiexpert parallelism (Lecture 21)

Plus point-to-point send/receive, used between pipeline stages. The course’s basic_comm.py sends a tensor from rank 0 to rank 1 with non-blocking isend/irecv.

Measured (demo 02 Part B): the same operations with torch.distributed on 4 real processes (gloo backend) give the simulation’s results for all eight. Reduce and gather are compared on the root, the only rank whose result is defined: gloo leaves partial sums in the other ranks’ buffers. On GPU clusters the same calls use the NCCL backend over NVLink and InfiniBand.

3.2 The ring all-reduce

The naive all-reduce sends everything to one rank, which sums and sends back. That rank’s link then carries 2(p−1)2(p-1) copies of the tensor, a bottleneck that grows with pp. The ring algorithm arranges ranks in a circle, cuts each tensor into pp chunks, and runs two phases:

  1. Reduce-scatter (p−1p - 1 steps). Each rank sends one chunk’s running sum to its neighbour, which adds its own copy. Afterwards each rank holds the full sum of one chunk.
  2. All-gather (p−1p - 1 steps). The completed chunks travel around the ring once.

Demo 02 traces it on 4 ranks. In step 1, rank 0 sends chunk 0 to rank 1, rank 1 sends chunk 1 to rank 2, and so on. After 6 steps every rank holds the sum.

Each rank sends 2(p−1)/p2(p-1)/p times the tensor’s size: 1.5× for 4 ranks, and never more than 2× however many ranks there are. Note that all-reduce = reduce-scatter + all-gather. ZeRO (§5) exploits exactly this split.

3.3 What communication costs

Sending mm bytes costs α+m/β\alpha + m/\beta: a latency per message plus size over bandwidth. For an all-reduce of nn bytes:

Tring=2(p−1)(α+np β),Ttree=2log⁡2p(α+nβ),Tnaive=2(p−1)(α+nβ).T_{\text{ring}} = 2(p-1)\left(\alpha + \frac{n}{p\,\beta}\right), \qquad T_{\text{tree}} = 2 \log_2 p \left(\alpha + \frac{n}{\beta}\right), \qquad T_{\text{naive}} = 2(p-1)\left(\alpha + \frac{n}{\beta}\right).

Computed with H100 numbers (NVLink 450 GB/s inside an 8-GPU node, InfiniBand 50 GB/s per GPU between nodes; latencies 5 and 10 µs):

message8 GPUs, NVLink64 GPUs, InfiniBand512 GPUs, InfiniBand
4 KBtree 0.03 mstree 0.12 mstree 0.18 ms (ring 10.2)
1 GBring 4 msring 41 msring 50 ms
16 GB (8B model’s bf16 gradients)ring 62 msring 631 msring 649 ms (naive 327 s)
  • Big messages are bandwidth-bound, and the ring is optimal. Its time hardly changes from 64 to 512 GPUs. The link matters: NVLink is 9× faster than InfiniBand.
  • Small messages are latency-bound. A ring needs 2(p−1)2(p-1) sequential messages, a tree only 2log⁡2p2\log_2 p. Libraries such as NCCL switch algorithms by message size.

The slides warn that data parallelism’s scaling suffers as GPUs are added: more coordination, network communication, and stragglers (the slowest rank sets the pace of every synchronous collective).


4. Data parallelism

4.1 The idea

Replicate the model on every GPU, give each GPU a different slice of the batch, run forward and backward in parallel, then average the gradients with an all-reduce so every replica takes the same step. The course’s dist_sgd.py does exactly this. After loss.backward() it calls average_gradients, which all-reduces each parameter’s gradient and divides by the world size.

Two details make it exactly the single-device step:

  • Same starting point. Seed (or broadcast) the weights identically, and use the same optimizer everywhere.
  • Correct normalization. As in §2.5, each replica divides its token-loss sum by the global token count. One extra all-reduce of a scalar provides it.

Measured (demo 03, Lecture 5’s Transformer on Errand World, 20 Adam steps of 32 sentences):

replicassentences per replica per stepreplicas identicalmax |Δθ| vs one device
132yes0
216yes2.9e-06
48yes1.6e-06
84yes1.2e-05

With 4 real processes (torch.distributed, one all-reduce per parameter tensor), all four end with identical weights. They are 3e-07 from the simulation and 2e-06 from one device. The differences are float summation order, not algorithm.

4.2 Overlap and bucketing

The naive version waits for the whole backward pass, then all-reduces everything: the GPUs sit idle during communication. But gradients become available layer by layer, from the output back to the input. Two improvements (the slides; PyTorch DDP, Li et al., 2020):

  • Overlap: start a layer’s all-reduce as soon as its gradients are ready, while backward continues on earlier layers.
  • Bucketing: group gradients into buckets and launch one all-reduce per bucket. Fewer messages means less latency, while sending early keeps the overlap.

Measured as a timeline model (demo 03 Part D): a 1.5B model with Llama 3.2 1B’s shape, 16 GPUs across 2 nodes, 147 parameter tensors, 3 GB of gradients:

gradient communicationall-reduce callscommunication not hidden
one all-reduce after backward1113 ms
one per tensor14749 ms (latency, 147 times)
25 MB buckets (DDP’s default)5021 ms
100 MB buckets1825 ms
1 GB buckets350 ms (start too late)

The backward pass itself takes 137 ms. What can never hide is the last gradient: the embedding’s 525 MB, produced when backward is already over.

4.3 The batch-size arithmetic, and DP’s limit

With data parallelism the global batch has three factors:

gbs=mbs×grad_acc×dp.\text{gbs} = \text{mbs} \times \text{grad\_acc} \times \text{dp}.

The slides’ example:

  • a global batch of 4M tokens with 4,096-token sequences is 1,024 sequences;
  • one GPU fits 2 sequences (mbs = 2), and with 128 GPUs, 2 × 128 = 256 sequences per pass;
  • so 4 accumulation steps.

Quiz: what if we had 512 GPUs? Then 2 × 512 = 1,024, so grad_acc = 1, with no accumulation and 4× the throughput. With 1,024 GPUs, mbs must drop to 1. With 2,048, there are more GPUs than sequences. Data parallelism alone cannot use them unless the global batch grows, which changes the optimization. And if the model does not fit on one GPU at all, data parallelism does not even start.

Both limits lead to splitting the model itself. There are two ways:

  • shard its states across the data-parallel ranks (ZeRO, §5);
  • parallelize its computation (tensor and pipeline parallelism, §6–7).

5. ZeRO: removing the redundancy of data parallelism

5.1 The idea

In data parallelism, every GPU holds a full copy of the parameters, the gradients and the optimizer states, so pp GPUs store pp identical copies. The Zero Redundancy Optimizer (Rajbhandari et al., 2020) partitions them, each rank keeping 1/dp1/\text{dp}:

stageshardsmemory per GPU (Ψ parameters; slides’ 18 bytes)communication per step
DPnothing18Ψ18\Psiall-reduce: ≈2Ψ\approx 2\Psi (bf16)
ZeRO-1optimizer states (fp32 master + Adam)2Ψ+4Ψ+12Ψ/dp2\Psi + 4\Psi + 12\Psi/\text{dp}reduce-scatter + all-gather: same as DP
ZeRO-2+ gradients2Ψ+16Ψ/dp2\Psi + 16\Psi/\text{dp}same as DP
ZeRO-3 (FSDP)+ parameters18Ψ/dp18\Psi/\text{dp}+ an all-gather of the weights in forward and again in backward: ≈ 1.5× DP

How ZeRO-1/2 work in one step:

  1. Every rank computes full gradients on its data.
  2. A reduce-scatter (instead of all-reduce) gives rank kk the summed gradient of its 1/dp1/\text{dp} slice only.
  3. Rank kk updates that slice with its own Adam states.
  4. An all-gather gives everyone the updated parameters.

Since all-reduce = reduce-scatter + all-gather, ZeRO-1/2 communicate as much as plain DP, for much less memory. ZeRO-3 also keeps only 1/dp1/\text{dp} of the bf16 weights. It all-gathers each layer’s parameters just in time, computes, and frees them.

The slides’ example: a 1B model on 4 GPUs, each storing 250M parameters. At each layer, a GPU fetches that layer’s full parameters with an all-gather, computes, then frees them.

As the slides stress, this is different from TP/PP: ZeRO shards memory, not computation. Every GPU still runs the full forward and backward pass on its own data.

5.2 Measured and computed

Llama 3 8B, model states per GPU (computed; activations excluded):

sharding8 GPUs64 GPUs
DP144.5 GB144.5 GB
ZeRO-160.2 GB49.7 GB
ZeRO-232.1 GB18.1 GB
ZeRO-318.1 GB2.3 GB

Measured (demo 03 Part E): simulated ZeRO-1/2 on 4 ranks (reduce-scatter, Adam on a quarter of the parameter vector per rank, all-gather) ends bit-identical to data parallelism. Adam is elementwise, so updating slices separately computes the same numbers. Each rank keeps 115,168 Adam moments instead of 460,672.

One thing ZeRO does not shard: activations. Each rank still runs whole sequences through the whole model. Demo 05 shows the consequence for Llama 3 70B. ZeRO-3 alone on 128 GPUs needs 101 GB per GPU, because one 4,096-token sequence keeps 91 GB of activations even with selective recomputation.


6. Tensor parallelism

6.1 Splitting a matrix multiplication

Tensor parallelism (Shoeybi et al., 2019, Megatron-LM) uses the structure of matrix multiplication to split one layer’s work across GPUs. For Y=XWY = XW:

  • Column-wise: split WW into column blocks [W1∣W2][W_1 \mid W_2]. GPU kk computes XWkXW_k, a slice of the output features. Concatenating (all-gather) gives YY.
  • Row-wise: split WW into row blocks and XX into the matching column blocks. GPU kk computes XkWkX_k W_k, a partial sum of the full output. Adding them (all-reduce) gives YY:

XW=[X1  X2][W1W2]=X1W1+X2W2.XW = [X_1 \; X_2] \begin{bmatrix} W_1 \\ W_2 \end{bmatrix} = X_1 W_1 + X_2 W_2.

6.2 The feed-forward block: column, then row

The FFN is two (for SwiGLU, three) matrix products with a nonlinearity in between. The trick is to make the first column-parallel and the second row-parallel:

GPU k:Zk=silu(XW1,k)⊙(XW3,k),Yk=ZkW2,k;Y=∑kYk.\text{GPU } k: \quad Z_k = \mathrm{silu}(X W_{1,k}) \odot (X W_{3,k}), \qquad Y_k = Z_k W_{2,k}; \qquad Y = \sum_k Y_k.

Each GPU’s slice of hidden units ZkZ_k is complete by itself: the nonlinearity acts elementwise, so it needs no communication. Only the final partial sums need one all-reduce. The slides call the two conjugate operators:

  • ff: identity in the forward pass, all-reduce in backward, at the input. Every GPU reads the same XX, so their gradients w.r.t. XX must be summed.
  • gg: all-reduce in the forward pass, identity in backward, at the output.

6.3 Attention: split by heads

Heads are independent, so GPU kk takes a subset of heads:

  • its rows of WQ,WK,WVW_Q, W_K, W_V (column-parallel);
  • the matching columns of WOW_O (row-parallel);
  • one all-reduce at the end.

Per Transformer block, that makes 2 all-reduces in the forward pass and 2 in the backward pass, each of a full activation b×s×hb \times s \times h.

Measured (demo 04 Part A, one block, d = 64, 4 heads):

GPUseach GPU computesweights per GPUmax output diffmax gradient diff
14 heads, 192 FFN units53,248 (100%)00
22 heads, 96 units26,624 (50%)4.8e-072.6e-06
41 head, 48 units13,312 (25%)4.8e-072.9e-06

Each GPU holds and computes 1/K1/K of the block, and every shard’s gradient equals the corresponding slice of the full gradient.

6.4 The trade-off: communication on the critical path

TP reduces memory (weights, gradients, optimizer states, and with sequence parallelism also activations, all ÷ tp). It costs communication that cannot overlap: the next layer needs the all-reduced activation. Computed for Llama 3 70B (sequence 4,096, one micro-batch):

TPmodel states per GPUcompute per micro-batchTP all-reduces, NVLinkon InfiniBand
11,270 GB3,101 ms——
8159 GB388 ms106 ms796 ms
1679 GB194 ms(only 8 GPUs per node)901 ms
  • Inside a node (NVLink), TP = 8 costs about a quarter of the compute time.
  • Across nodes (InfiniBand), the all-reduces would cost several times the compute. Hence the rule: TP within a node (the slides: “cross-node connections particularly slow”).
  • Even TP = 8 leaves 159 GB of model states per GPU for 70B. TP must be combined with ZeRO or pipeline stages.

7. Pipeline parallelism

7.1 Split the layers, and mind the bubble

Pipeline parallelism gives each GPU a contiguous group of layers. The slides’ figure: 16 layers on 4 GPUs. Activations flow forward from GPU to GPU, and their gradients flow back, with point-to-point sends of one activation per micro-batch: much less communication than TP. The problem is idle time. While GPU 1 runs the first micro-batch, GPUs 2–4 wait; while GPU 4 runs the last backward, GPUs 1–3 wait. This idle time is the bubble.

With pp stages and mm micro-batches (forward 1 unit, backward 2), the bubble’s share of the step is:

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

More micro-batches shrink it. That is one more reason the global batch is split into many micro-batches.

7.2 Two schedules

  • All-forward-all-backward (AFAB, GPipe; Huang et al., 2019): every stage runs the forward passes of all mm micro-batches, then all backward passes. Simple, but each stage must keep the activations of all mm micro-batches until their backward.
  • One-forward-one-backward (1F1B; Narayanan et al., 2019, 2021): after a short warm-up, each stage alternates one forward and one backward. A micro-batch’s backward starts as soon as possible, so its activations are freed early.

Measured (demo 04 Part C; a digit is a forward, a letter the backward of that micro-batch, ”.” idle):

all-forward-all-backward: bubble 27.3%, up to 8 micro-batches' activations held
  GPU 0  12345678.........aabbccddeeffgghh
  GPU 1  .12345678......aabbccddeeffgghh..
  GPU 2  ..12345678...aabbccddeeffgghh....
  GPU 3  ...12345678aabbccddeeffgghh......
one-forward-one-backward: bubble 27.3%, up to 4 micro-batches' activations held
  GPU 0  1234......aa5bb6cc7dd8ee.ff.gg.hh
  GPU 1  .123....aa4bb5cc6dd7ee8ff.gg.hh..
  GPU 2  ..12..aa3bb4cc5dd6ee7ff8gg.hh....
  GPU 3  ...1aa2bb3cc4dd5ee6ff7gg8hh......

The bubble is the same, (p−1)/(m+p−1)=3/11(p-1)/(m+p-1) = 3/11. 1F1B’s gain is memory: at most pp micro-batches in flight instead of mm. Bubble vs micro-batches with 4 stages: 75% (m=1m = 1), 43% (4), 27% (8), 16% (16), 9% (32), for both schedules. Later schedules attack the bubble itself:

  • interleaved 1F1B (Narayanan et al., 2021): each GPU holds several non-adjacent layer groups;
  • zero-bubble pipelines (Qi et al., 2023): split the backward pass into its two gradients and schedule them separately.

Measured (Part D): gradients computed through 2 or 4 stages with 1–8 micro-batches equal one device’s to 1.5e-07. The simulation sends each activation forward as a fresh leaf tensor and its gradient back, which is all a stage boundary does.


8. Choosing a strategy

8.1 The strategies side by side

The slides’ recap table:

strategykey ideatrade-offsuse case
data parallelismparallelize on the batch dimensionredundancy; the model must fit on a GPUstandard models that fit in GPU memory
tensor parallelismparallelize on the hidden dimensionfine-grained, so high communication costslarge layers; within a node
pipeline parallelismparallelize on the model (layer) dimensionpipeline bubbleslarge, deep models; across nodes
ZeROshard model, optimizer, gradients in DPcommunication (all-gathers)big models that don’t fit in GPU memory

They are combined. “3D parallelism” is TP inside a node, PP across groups of nodes, and DP (often with ZeRO) on top. Llama 3 405B used 4D: TP 8, context parallelism for long sequences (Lecture 22), PP 16, and DP across 16,384 GPUs.

8.2 Three steps

The slides’ recipe:

  1. Fit the model into memory. Choose TP, PP, ZeRO and recomputation so that model states and activations fit.
  2. Satisfy the target global batch size. Choose dp, mbs and grad_acc with mbs × grad_acc × dp = gbs.
  3. Optimize training throughput. Among the configurations that pass steps 1–2, take the fastest.

The Playbook ran this search for real (the slides’ “best configuration experiment”: global batch 1M tokens, sequence 4,096, 1–64 nodes of 8 H100s).

Computed (demo 05): a cost model searches {tp≤8}×{pp≤16}×\{\text{tp} \le 8\} \times \{\text{pp} \le 16\} \times ZeRO 0–3 × mbs × recomputation for Llama 3 with the same global batch. Time is compute at 60% of peak, plus the pipeline bubble, plus TP all-reduces on NVLink, plus the non-overlapped part of the gradient all-reduce on InfiniBand.

modelGPUsfastest configurationGB / GPUMFU
8B8DP 8, ZeRO-1, selective recompute7853.9%
8B128DP 64 × TP 2, ZeRO-17752.9%
8B512DP 128 × TP 4, ZeRO-1, mbs 26443.4%
70B128DP 64 × TP 2, ZeRO-3, selective recompute5653.5%
405B512DP 64 × TP 8, ZeRO-35050.3%
405B2,048DP 128 × TP 8 × PP 2, ZeRO-2, full recompute5627.1%

What the search shows:

  • Step 1 prunes hard. Nothing fits for 70B below 32 GPUs, or for 405B below 128.
  • ZeRO alone is not enough for big models, because it does not shard activations. Without TP, the only 70B configurations that fit on 128 GPUs use full recomputation (37 of 324), and the best of them is 54% slower.
  • The batch caps data parallelism. 256 sequences per batch cannot feed more than 256 replicas, so TP becomes unavoidable for 8B on 512 GPUs, and MFU falls.
  • A fixed batch on a growing cluster hurts. On 2,048 GPUs, 405B gets 2 sequences per replica, and the pipeline bubble eats 31% of the step. Real runs grow the batch with the cluster: Llama 3 405B ended with 16M-token batches.

The model is deliberately simple: no pipeline send/recv, no stragglers, a fixed overlap fraction. Its absolute numbers are optimistic; its comparisons follow the lecture’s logic. The Playbook’s advice applies: use such estimates to shortlist, then benchmark the shortlist.

8.3 In practice

Frameworks implement these strategies so that users choose them by configuration:

  • torchtitan: PyTorch-native FSDP2, TP, PP and context parallelism.
  • Megatron-LM: the reference for TP, PP and their interleaving.
  • DeepSpeed: ZeRO.

The course code uses torch.distributed directly, the layer all of them are built on.


9. Summary

  1. Cost of a step. Compute is 6ND6ND (+ attention); MFU = achieved / peak FLOPS.
    • Memory is 18 bytes per parameter of model states plus activations, which are linear in batch and quadratic in sequence length.
    • Computed: Llama 3 8B needs 145 GB of model states, more than an H100. Measured: PyTorch’s FLOP counter equals 6ND6ND + attention exactly.
  2. One-GPU tricks.
    • Recomputation trades compute for activation memory. Measured: −91–94% memory for ×1.26 FLOPs.
    • Accumulation trades time for batch size, and is exact only if each micro-batch’s loss sum is divided by the whole batch’s token count. Measured: 9% gradient error otherwise.
  3. Collectives. All-reduce = reduce-scatter + all-gather.
    • The ring is bandwidth-optimal: each GPU sends < 2× the tensor whatever pp is. Small messages are latency-bound (trees win).
    • Measured: real gloo processes reproduce the simulated primitives.
  4. Data parallelism. Replicas + gradient all-reduce, overlapped with backward in buckets; gbs = mbs × grad_acc × dp.
    • Measured: simulated and real DP match one device to ≤ 1.2e-05.
    • Computed: 25 MB buckets leave 21 ms of communication exposed vs 113 ms without overlap.
  5. ZeRO. It shards optimizer states, then gradients, then weights. Stages 1–2 cost no extra communication; stage 3 costs 1.5×.
    • Llama 3 8B on 8 GPUs: 144.5 → 60.2 → 32.1 → 18.1 GB of model states per GPU.
    • It does not shard activations.
  6. Tensor parallelism. Column-parallel then row-parallel, heads split, 2 + 2 all-reduces per block on the critical path, so it stays within a node.
    • Measured: exact outputs and gradients.
  7. Pipeline parallelism. Layers split across stages; bubble (p−1)/(m+p−1)(p-1)/(m+p-1); 1F1B holds pp micro-batches instead of mm.
    • Measured: pipeline gradients equal one device’s.
  8. Choosing. Fit, then batch, then throughput: DP (+ZeRO) first, TP inside nodes, PP across nodes when the model demands it, and benchmark the shortlist.

Common pitfalls

  • Counting only the weights. Training needs ~9× the bf16 weights before activations.
  • Averaging per-micro-batch (or per-replica) mean losses. With variable lengths the gradient is wrong; divide token-loss sums by the global token count.
  • Different initial weights or random states across replicas. Data-parallel replicas drift apart silently; seed or broadcast.
  • Tensor parallelism across nodes. Its all-reduces sit on the critical path; keep TP inside NVLink domains.
  • Pipelines with few micro-batches. The bubble is (p−1)/(m+p−1)(p-1)/(m+p-1); with m≈pm \approx p half the time is idle.
  • Expecting ZeRO to fix activation memory. It shards model states only; use recomputation, TP/sequence parallelism or context parallelism.
  • Growing the cluster without growing the batch. Per-GPU work shrinks, communication does not, and MFU falls.
  • Trusting a cost model’s absolute numbers. Benchmark the shortlist.

Exercises

  1. Memory budget. A 13B-parameter model is trained with mixed precision and Adam. How much memory do its model states need? On 8 GPUs with ZeRO-1, ZeRO-2, ZeRO-3?

    Answer18 × 13B = 234 GB. ZeRO-1: 2N + 4N + 12N/8 = 6 × 13 + 1.5 × 13 = 97.5 GB. ZeRO-2: 2N + 16N/8 = 26 + 26 = 52 GB. ZeRO-3: 234/8 = 29.25 GB (all per GPU, activations excluded).
  2. Activations. With the slides’ formula, how much activation memory does Llama 3 8B (L=32L = 32, h=4096h = 4096, a=32a = 32) need for 2 sequences of 4,096 tokens? How much with selective recomputation? Which term did it remove, and why is it cheap to recompute?

    AnswerPer sequence 104.2 GB (demo 01), so 208 GB for 2. Selective: 32 × 4096 × 2 × 4096 × 34 bytes = 36.5 GB. It removes the 5as/h term: the s × s attention scores and softmax. They are huge (quadratic in s) but cost little to recompute: one QKᵀ product and a softmax, small next to the layer's matrix products.
  3. Gradient accumulation. Two micro-batches hold 100 and 300 tokens with total losses 50 and 90 (summed over tokens). What is the correct batch loss, and what does averaging the two micro-batch means give?

    AnswerCorrect: (50 + 90)/400 = 0.35. Averaging means: (50/100 + 90/300)/2 = (0.5 + 0.3)/2 = 0.40. The shortcut over-weights the short micro-batch's tokens (each of its tokens counts 3× as much as a token in the long one).
  4. Ring all-reduce. 16 GPUs all-reduce a 2 GB gradient over links of 50 GB/s with 10 µs latency. Compute the ring time and the naive (via one GPU) time. Which term dominates each?

    AnswerRing: 2 × 15 × (10 µs + 2 GB/16/50 GB/s) = 30 × (0.00001 + 0.0025) = 75.3 ms, bandwidth-dominated (latency 0.3 ms). Naive: 2 × 15 × (10 µs + 2/50 s) = 30 × 0.04 = 1.2 s, 16× slower, because one GPU's link carries everything.
  5. Global batch. You want a global batch of 2M tokens with 8,192-token sequences; one GPU fits 1 sequence. How many accumulation steps on 64 GPUs? What is the maximum number of GPUs pure DP can use?

    Answer2M / 8192 = 256 sequences (with 2M = 2,097,152). With 64 GPUs × 1 sequence: grad_acc = 4. Pure DP can use at most 256 GPUs (one sequence each); beyond that it needs a larger batch, or TP/PP to put several GPUs on each sequence.
  6. Tensor parallelism. Show that splitting an FFN’s first matrix by columns and the second by rows needs no communication between them, but splitting the first by rows would. Count the all-reduces per Transformer block (forward and backward).

    AnswerColumn split of $W_1$: GPU k gets complete hidden units $XW_{1,k}$, so the elementwise nonlinearity applies locally, and the row split of $W_2$ consumes exactly those units, giving partial sums that one all-reduce combines. Row split of $W_1$ would give each GPU a partial sum of every hidden unit, and the nonlinearity of a partial sum is not the partial sum of the nonlinearity, so an all-reduce would be needed before it. Per block: one all-reduce after attention and one after the FFN in forward (g), and two in backward (f): 2 + 2.
  7. Pipeline bubble. With 8 stages, how many micro-batches keep the bubble below 10%? What does 1F1B change compared to AFAB, and what does it not change?

    Answer(p − 1)/(m + p − 1) < 0.1 → 7/(m + 7) < 0.1 → m > 63, so at least 64 micro-batches. 1F1B changes memory (at most 8 micro-batches' activations held per stage instead of 64); it does not change the bubble. Interleaved schedules and zero-bubble schedules reduce the bubble itself.
  8. Which strategy? For each situation, name the first technique to reach for: (a) a 1B model on 64 GPUs; (b) a 70B model whose activations alone exceed GPU memory at the target sequence length; (c) a 400B model on 1,000 nodes; (d) your 8-GPU job’s MFU drops when you go to 16 nodes with the same global batch.

    Answer(a) Data parallelism (with ZeRO-1 if the optimizer states are tight). (b) Selective or full recomputation, and tensor parallelism with sequence parallelism (ZeRO does not shard activations); for very long sequences, context parallelism (Lecture 22). (c) 3D/4D parallelism: TP inside nodes, PP across node groups, DP (+ZeRO) on top. (d) Per-GPU work shrank while communication did not: increase the global batch (if the optimization allows), use larger buckets and overlap, or trade DP for TP/PP inside nodes; benchmark the options.
  • Assignment 1 (Build your own LLaMa) and course projects train models on one or a few GPUs. Before scaling up:
    • compute the memory of your step with §2’s formulas;
    • check that your loss normalization is token-weighted under accumulation;
    • use gradient checkpointing before buying more GPUs.
  • For multi-GPU projects, start from DDP or FSDP. Verify that a 2-GPU run matches a 1-GPU run with accumulation, as demo 03 does.
  • These notes do not provide assignment code.

Further reading

  • N. Tazi et al., The Ultra-Scale Playbook: Training LLMs on GPU Clusters, Hugging Face, 2025 (course reading).
  • S. Rajbhandari et al., “ZeRO: Memory Optimizations Toward Training Trillion Parameter Models”, SC 2020; Y. Zhao et al., “PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel”, VLDB 2023; S. Li et al., “PyTorch Distributed: Experiences on Accelerating Data Parallel Training”, VLDB 2020.
  • M. Shoeybi et al., “Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism”, 2019; D. Narayanan et al., “Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM”, SC 2021; V. Korthikanti et al., “Reducing Activation Recomputation in Large Transformer Models”, 2022.
  • Y. Huang et al., “GPipe”, NeurIPS 2019; D. Narayanan et al., “PipeDream: Generalized Pipeline Parallelism for DNN Training”, SOSP 2019; P. Qi et al., “Zero Bubble Pipeline Parallelism”, 2023.
  • T. Chen et al., “Training Deep Nets with Sublinear Memory Cost”, 2016; P. Patarasuk, X. Yuan, “Bandwidth Optimal All-reduce Algorithms for Clusters of Workstations”, JPDC 2009.
  • A. Dubey et al. (Meta), “The Llama 3 Herd of Models”, 2024 (4D parallelism at 16K GPUs); PyTorch tutorial “Writing Distributed Applications with PyTorch” (the course code’s source); torchtitan and Megatron-LM repositories.

Preview of Lecture 21 — Mixture of experts

Parallelism lets us afford more parameters; mixture-of-experts models make each token use only a few of them. Lecture 21 replaces the FFN of each block with many expert FFNs and a router:

  • top-k routing, capacity and token dropping, load-balancing losses;
  • fine-grained and shared experts;
  • expert parallelism, which needs the one collective this lecture used least: all-to-all.

术语表 (Glossary, English → 中文)

English中文
distributed training分布式训练
rank / world size / process group进程编号 / 进程总数 / 进程组
FLOPs / FLOPS / model FLOPs utilization (MFU)浮点运算量 / 每秒浮点运算次数 / 模型算力利用率
peak throughput峰值吞吐
model states: weights, gradients, optimizer states模型状态:权重、梯度、优化器状态
mixed precision / master weights混合精度 / 主权重
activations / activation memory激活值 / 激活内存
activation recomputation (gradient checkpointing): full / selective激活重计算(梯度检查点):完全 / 选择性
micro-batch / global batch / gradient accumulation微批次 / 全局批次 / 梯度累积
loss normalization损失归一化
collective communication / point-to-point集合通信 / 点对点通信
broadcast / reduce / all-reduce广播 / 归约 / 全归约
gather / all-gather / scatter / reduce-scatter / all-to-all收集 / 全收集 / 分发 / 归约分发 / 全交换
ring all-reduce / tree algorithm环形全归约 / 树形算法
latency / bandwidth / alpha-beta cost model延迟 / 带宽 / α-β 代价模型
straggler掉队者(慢节点)
NVLink / InfiniBand / NCCL / gloo节点内高速互连 / 节点间网络 / NCCL 通信库 / gloo 通信库
data parallelism / replica数据并行 / 副本
communication-computation overlap / gradient bucketing通信计算重叠 / 梯度分桶
Zero Redundancy Optimizer (ZeRO) / fully sharded data parallel (FSDP)零冗余优化器 / 全分片数据并行
sharding / partitioning分片 / 划分
tensor parallelism / column-parallel / row-parallel张量并行 / 列并行 / 行并行
sequence parallelism / context parallelism序列并行 / 上下文并行
pipeline parallelism / stage / bubble流水线并行 / 阶段 / 气泡
all-forward-all-backward (GPipe) / one-forward-one-backward (1F1B)全前向全反向 / 一前一后
interleaved schedule / zero-bubble schedule交错调度 / 零气泡调度
3D (4D) parallelism三维(四维)并行
cost model / configuration search / benchmark代价模型 / 配置搜索 / 基准测试
← 返回课程目录