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 code20_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 fromcode/lecture20/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14). Large-model numbers labelled “computed” come from formulas inbudget.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:
- Compute the memory of a training step (weights, gradients, optimizer states, activations) and its compute (6ND), and explain MFU.
- Explain activation recomputation and gradient accumulation, what each trades, and how to normalize an accumulated loss correctly.
- Define the collective operations (all-reduce, reduce-scatter, all-gather, …) and explain why the ring all-reduce is bandwidth-optimal.
- Describe data parallelism, overlap and bucketing, and the global-batch arithmetic .
- Explain ZeRO stages 1–3 (and FSDP): what each shards, what it saves, what it costs in communication.
- Derive tensor parallelism (column- then row-parallel) and pipeline parallelism (bubbles, AFAB vs 1F1B), and say when each is used.
- 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: .
- 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
| Section | Idea | Demo in code/lecture20/ |
|---|---|---|
| §2 | compute, memory, activations, recomputation, accumulation | 01_memory_compute.py (+ budget.py) |
| §3 | collectives, ring all-reduce, costs, real processes | 02_collectives.py (+ collectives.py) |
| §4 | data parallelism, overlap, batch arithmetic | 03_data_parallel_zero.py Parts A–D (+ parallel_sim.py) |
| §5 | ZeRO | 03_data_parallel_zero.py Part E |
| §6–7 | tensor and pipeline parallelism | 04_tensor_pipeline.py |
| §8 | choosing a strategy | 05_choosing_strategy.py |
0.4 Notation
| Symbol | Meaning |
|---|---|
| (or ) | number of parameters |
| number of training tokens (per step or in total) | |
| layers, hidden size, attention heads | |
| , | sequence length, (micro-)batch size in sequences |
| mbs, grad_acc, gbs | micro-batch size, gradient-accumulation steps, global batch size |
| dp, tp, pp | number of data-, tensor- and pipeline-parallel ranks |
| number of ranks in a collective | |
| latency 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:
- Memory usage: a training step must fit in each device’s memory.
- Compute efficiency: the hardware should spend most of its time computing.
- 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:
counts the parameters that take part in matrix products; the embedding lookup is free. Attention adds and , which have no parameters: FLOPs per token for forward plus backward.
Measured (demo 01 Part D): PyTorch’s FLOP counter on Lecture 5’s Transformer gives exactly (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:
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, 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:
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:
| model | parameters | FFN share | model states (GB) | H100s (80 GB) just to hold them |
|---|---|---|---|---|
| Llama 3 8B | 8.03B | 70% | 145 | 1.8 |
| Llama 3 70B | 70.55B | 80% | 1,270 | 15.9 |
| Llama 3 405B | 405.85B | 81% | 7,305 | 91.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):
It has two parts:
- : inputs of the linear layers, norms, activation functions, dropout masks. Linear in sequence length.
- : the attention scores, softmax output and dropout mask of every head. Quadratic in sequence length.
Computed for Llama 3 8B, one sequence:
| sequence length | activations | without the term | full recomputation |
|---|---|---|---|
| 2,048 | 30.6 GB | 9.1 GB | 0.5 GB |
| 4,096 | 104.2 GB | 18.3 GB | 1.1 GB |
| 8,192 | 380.1 GB | 36.5 GB | 2.1 GB |
At long sequences the attention matrices dominate everything. FlashAttention (Lecture 22) never stores them, which removes the 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 term growing.
The batch size, in tokens , 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 ( 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 () 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:
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 scaled | relative gradient error vs one big batch |
|---|---|
| token-loss sum / tokens in the whole batch | 3.7e-07 (float rounding) |
| its own mean loss / 4 | 8.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 ; 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 processes (ranks). The slides’ “communication ops”; demo 02 shows each on 4 ranks, where rank starts with :
| operation | result | used by |
|---|---|---|
| broadcast | root’s tensor → everyone | initial weights |
| reduce | sum of all → root | — |
| all-reduce | sum of all → everyone ([64 68 72 76] on every rank) | data parallelism, TP |
| gather | everyone’s → root | — |
| all-gather | everyone’s → everyone (concatenated) | ZeRO-3, sequence parallelism |
| scatter | root’s chunk → rank | — |
| reduce-scatter | sum of everyone’s chunk → rank (64, 68, 72, 76) | ZeRO-2/3 |
| all-to-all | rank ‘s chunk → rank | expert 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 copies of the tensor, a bottleneck that grows with . The ring algorithm arranges ranks in a circle, cuts each tensor into chunks, and runs two phases:
- Reduce-scatter ( 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.
- All-gather ( 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 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 bytes costs : a latency per message plus size over bandwidth. For an all-reduce of bytes:
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):
| message | 8 GPUs, NVLink | 64 GPUs, InfiniBand | 512 GPUs, InfiniBand |
|---|---|---|---|
| 4 KB | tree 0.03 ms | tree 0.12 ms | tree 0.18 ms (ring 10.2) |
| 1 GB | ring 4 ms | ring 41 ms | ring 50 ms |
| 16 GB (8B model’s bf16 gradients) | ring 62 ms | ring 631 ms | ring 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 sequential messages, a tree only . 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):
| replicas | sentences per replica per step | replicas identical | max |Δθ| vs one device |
|---|---|---|---|
| 1 | 32 | yes | 0 |
| 2 | 16 | yes | 2.9e-06 |
| 4 | 8 | yes | 1.6e-06 |
| 8 | 4 | yes | 1.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 communication | all-reduce calls | communication not hidden |
|---|---|---|
| one all-reduce after backward | 1 | 113 ms |
| one per tensor | 147 | 49 ms (latency, 147 times) |
| 25 MB buckets (DDP’s default) | 50 | 21 ms |
| 100 MB buckets | 18 | 25 ms |
| 1 GB buckets | 3 | 50 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:
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 GPUs store identical copies. The Zero Redundancy Optimizer (Rajbhandari et al., 2020) partitions them, each rank keeping :
| stage | shards | memory per GPU (Ψ parameters; slides’ 18 bytes) | communication per step |
|---|---|---|---|
| DP | nothing | all-reduce: (bf16) | |
| ZeRO-1 | optimizer states (fp32 master + Adam) | reduce-scatter + all-gather: same as DP | |
| ZeRO-2 | + gradients | same as DP | |
| ZeRO-3 (FSDP) | + parameters | + an all-gather of the weights in forward and again in backward: ≈ 1.5× DP |
How ZeRO-1/2 work in one step:
- Every rank computes full gradients on its data.
- A reduce-scatter (instead of all-reduce) gives rank the summed gradient of its slice only.
- Rank updates that slice with its own Adam states.
- 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 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):
| sharding | 8 GPUs | 64 GPUs |
|---|---|---|
| DP | 144.5 GB | 144.5 GB |
| ZeRO-1 | 60.2 GB | 49.7 GB |
| ZeRO-2 | 32.1 GB | 18.1 GB |
| ZeRO-3 | 18.1 GB | 2.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 :
- Column-wise: split into column blocks . GPU computes , a slice of the output features. Concatenating (all-gather) gives .
- Row-wise: split into row blocks and into the matching column blocks. GPU computes , a partial sum of the full output. Adding them (all-reduce) gives :
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:
Each GPU’s slice of hidden units 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:
- : identity in the forward pass, all-reduce in backward, at the input. Every GPU reads the same , so their gradients w.r.t. must be summed.
- : all-reduce in the forward pass, identity in backward, at the output.
6.3 Attention: split by heads
Heads are independent, so GPU takes a subset of heads:
- its rows of (column-parallel);
- the matching columns of (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 .
Measured (demo 04 Part A, one block, d = 64, 4 heads):
| GPUs | each GPU computes | weights per GPU | max output diff | max gradient diff |
|---|---|---|---|---|
| 1 | 4 heads, 192 FFN units | 53,248 (100%) | 0 | 0 |
| 2 | 2 heads, 96 units | 26,624 (50%) | 4.8e-07 | 2.6e-06 |
| 4 | 1 head, 48 units | 13,312 (25%) | 4.8e-07 | 2.9e-06 |
Each GPU holds and computes 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):
| TP | model states per GPU | compute per micro-batch | TP all-reduces, NVLink | on InfiniBand |
|---|---|---|---|---|
| 1 | 1,270 GB | 3,101 ms | — | — |
| 8 | 159 GB | 388 ms | 106 ms | 796 ms |
| 16 | 79 GB | 194 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 stages and micro-batches (forward 1 unit, backward 2), the bubble’s share of the step is:
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 micro-batches, then all backward passes. Simple, but each stage must keep the activations of all 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, . 1F1B’s gain is memory: at most micro-batches in flight instead of . Bubble vs micro-batches with 4 stages: 75% (), 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:
| strategy | key idea | trade-offs | use case |
|---|---|---|---|
| data parallelism | parallelize on the batch dimension | redundancy; the model must fit on a GPU | standard models that fit in GPU memory |
| tensor parallelism | parallelize on the hidden dimension | fine-grained, so high communication costs | large layers; within a node |
| pipeline parallelism | parallelize on the model (layer) dimension | pipeline bubbles | large, deep models; across nodes |
| ZeRO | shard model, optimizer, gradients in DP | communication (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:
- Fit the model into memory. Choose TP, PP, ZeRO and recomputation so that model states and activations fit.
- Satisfy the target global batch size. Choose dp, mbs and grad_acc with mbs × grad_acc × dp = gbs.
- 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 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.
| model | GPUs | fastest configuration | GB / GPU | MFU |
|---|---|---|---|---|
| 8B | 8 | DP 8, ZeRO-1, selective recompute | 78 | 53.9% |
| 8B | 128 | DP 64 × TP 2, ZeRO-1 | 77 | 52.9% |
| 8B | 512 | DP 128 × TP 4, ZeRO-1, mbs 2 | 64 | 43.4% |
| 70B | 128 | DP 64 × TP 2, ZeRO-3, selective recompute | 56 | 53.5% |
| 405B | 512 | DP 64 × TP 8, ZeRO-3 | 50 | 50.3% |
| 405B | 2,048 | DP 128 × TP 8 × PP 2, ZeRO-2, full recompute | 56 | 27.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
- Cost of a step. Compute is (+ 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 + attention exactly.
- 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.
- Collectives. All-reduce = reduce-scatter + all-gather.
- The ring is bandwidth-optimal: each GPU sends < 2× the tensor whatever is. Small messages are latency-bound (trees win).
- Measured: real gloo processes reproduce the simulated primitives.
- 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.
- 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.
- 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.
- Pipeline parallelism. Layers split across stages; bubble ; 1F1B holds micro-batches instead of .
- Measured: pipeline gradients equal one device’s.
- 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 ; with 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
-
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?
Answer
18 × 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). -
Activations. With the slides’ formula, how much activation memory does Llama 3 8B (, , ) 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?
Answer
Per 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. -
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?
Answer
Correct: (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). -
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?
Answer
Ring: 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. -
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?
Answer
2M / 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. -
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).
Answer
Column 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. -
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. -
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.
Related assignment (concepts only)
- 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 | 代价模型 / 配置搜索 / 基准测试 |