Skip to content

Training at scale: data, tensor, pipeline, context and expert parallelism

Skip →Llama 3
main track #7corefundamentalbookrubric 11/122025 · Hugging Face Space (19 Feb 2025) · ~60 min

Nouamane Tazi, Ferdinand Mom, Haojun Zhao, Phuc Nguyen, Mohamed Mekkouri, Leandro von Werra, Thomas Wolf

Read first: Decoupled Weight Decay Regularization (AdamW) · FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness

Status

TL;DR. One GPU cannot hold a modern training step, and one GPU is too slow anyway. The Ultra-Scale Playbook (Hugging Face, Feb 2025) builds the whole toolbox from one question: what does a training step store, and how can we split it? Weights, gradients and Adam states cost about 16 bytes per parameter in BF16 mixed precision (20 if gradients are also kept in FP32), so a 7B model needs 112 GB before activations. The five ways to split are data (batch), tensor (hidden dimension), context/sequence (tokens), pipeline (layers) and expert (MoE experts) parallelism, plus ZeRO/FSDP sharding of the data-parallel copies. For a dense model, TP × PP × CP × DP must equal the GPU count when these are independent group dimensions. EP is usually a separate layout of the MoE layers on those ranks, not automatically another factor to multiply into that product. Each trades memory for communication. Fast, frequent communication usually goes inside a node (tensor parallelism); less frequent communication goes across nodes (pipeline, data/ZeRO).

Sources. Primary: Tazi et al., The Ultra-Scale Playbook: Training LLMs on GPU Clusters (Hugging Face Space, 2025), with Picotron and Nanotron code. It describes thousands of benchmark runs on 1–64 nodes of 8×H100. Equations are checked against the original papers: ZeRO (Rajbhandari et al., arXiv 1910.02054); Megatron-LM tensor parallelism (Shoeybi et al., arXiv 1909.08053); PTD-P, 1F1B and interleaved pipelines (Narayanan et al., arXiv 2104.04473); and Ring Attention (Liu, Zaharia, Abbeel, arXiv 2310.01889).

Why it matters to you. Every frontier report you read (DeepSeek-V3, Llama 3) states a parallel layout (TP × PP × DP degrees) and an MFU. RL post-training runs on the same stack. To direct or critique that work you need to be able to check memory and bubble arithmetic on a napkin. First read: memory accounting, DP/ZeRO, TP, the pipeline bubble and the recipe. The 60-minute assignment is this page and its worked examples. The full playbook, its code, kernel chapters and advanced schedules are optional follow-up. Skip at first: the sequence-parallel f/g bookkeeping, the two Optional subsections below (Ring Attention buffer arithmetic; zero-bubble/DualPipe), and the playbook’s later GPU-kernel and FP8 chapters.

A rank is one GPU process. A collective is a communication step that involves a whole group of ranks. All-reduce sums a tensor across ranks and gives everyone the result. Reduce-scatter sums it but gives each rank only its 1/N1/N slice. All-gather collects every rank’s slice onto all ranks. All-to-all sends a different chunk to every other rank. A ring all-reduce is a reduce-scatter followed by an all-gather. Each of the NN GPUs sends and receives 2(N−1)K/N≈2K2(N-1)K/N \approx 2K values for a tensor of KK values, so a reduce-scatter or an all-gather alone costs about KK. Inside a transformer layer, the MLP is the two-matrix feed-forward block, GeLU is its elementwise nonlinearity, LayerNorm normalises each token’s hidden vector, and Q/K/V are the query, key and value projections of attention. Intra-node links (NVLink) are fast. Inter-node links (InfiniBand/EFA) are much slower. Most of the design below follows from that gap.

1. Memory accounting: what one step stores

Section titled “1. Memory accounting: what one step stores”

Intuition: the model’s numbers are stored several times over in different precisions. The activations are a separate bill that grows with batch and sequence length.

These are persistent-state estimates, not measured peaks. Gathering one or more full layers, communication workspaces, checkpointed activations and allocator slack still need headroom.

With Ψ\Psi parameters, BF16 mixed precision and Adam (the ZeRO paper’s notation; KK is the optimizer multiplier):

2Ψ⏟BF16 weights+2Ψ⏟BF16 grads+4Ψ⏟FP32 master+4Ψ+4Ψ⏟Adam m, v=2Ψ+2Ψ+KΨ=16Ψ bytes,K=12.\underbrace{2\Psi}_{\text{BF16 weights}} + \underbrace{2\Psi}_{\text{BF16 grads}} + \underbrace{4\Psi}_{\text{FP32 master}} + \underbrace{4\Psi + 4\Psi}_{\text{Adam } m,\ v} = 2\Psi + 2\Psi + K\Psi = 16\Psi \text{ bytes},\quad K = 12.

Some frameworks (Nanotron, for example) also keep an FP32 gradient buffer for stability alongside the BF16 gradients. These coexisting buffers add 4Ψ4\Psi and give 20 bytes per parameter. (A setup where FP32 gradients replace the BF16 ones is a different convention.) Mixed precision does not save memory over FP32 (16 bytes either way). Its gains are faster BF16 matmuls and smaller activations.

Activations with sequence length ss, micro-batch bb, hidden size hh, LL layers and aa heads (playbook’s formula, in bytes):

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

The 5as/h5as/h term is the stored attention matrix. It is quadratic in ss, and FlashAttention avoids storing it by recomputing it. Activation recomputation (gradient checkpointing) drops activations in the forward pass and recomputes them in the backward pass. Full recomputation keeps only layer inputs and costs up to about 30–40% more compute. Selective recomputation drops only the cheap-to-recompute attention parts: for GPT-3 175B this gives a 70% activation-memory reduction for 2.7% extra compute. Gradient accumulation runs several micro-batches before one optimizer step, so the global batch is gbs=mbs×grad_acc×dp\text{gbs} = \text{mbs}\times\text{grad\_acc}\times\text{dp}.

Worked example (7B, by hand). Ψ=7×109\Psi = 7\times10^9, 1 GB =109=10^9 bytes.

ItemBytes/param7B total
BF16 weights + BF16 grads2 + 228 GB
FP32 master weights428 GB
Adam mm and vv (FP32)4 + 456 GB
Model states16112 GB (140 GB with FP32 grads)

That alone exceeds an 80 GB H100. Now the activations, for an assumed Llama-style 7B shape (L=32L=32, h=4096h=4096, a=32a=32) at s=4096s=4096, b=1b=1. Then Lsbh=32⋅4096⋅4096≈0.537×109L s b h = 32\cdot4096\cdot4096 \approx 0.537\times10^9. The 34 term gives 34×0.537≈18.334\times0.537 \approx 18.3 GB. The attention term adds 5⋅32⋅4096/4096=1605\cdot32\cdot4096/4096 = 160, so 160×0.537≈85.9160\times0.537 \approx 85.9 GB if scores are stored. With FlashAttention-style recomputation you pay about 18 GB. Keeping only BF16 layer inputs (full recompute) costs about 2⋅Lsbh≈1.12\cdot Lsbh \approx 1.1 GB (my estimate). This is a GPT-style-block estimate using Llama-like dimensions, not an exact Llama (SwiGLU, GQA) memory model.

2. Data parallelism (DP) and its all-reduce

Section titled “2. Data parallelism (DP) and its all-reduce”

Intuition: each GPU holds a full copy of the model and processes different examples. Before the optimizer step all GPUs average their gradients so the copies stay identical. In IR terms, these are replicas of a full index serving different queries, plus a nightly sync.

The cost is one gradient all-reduce per step. For the 7B model on 8 GPUs with BF16 gradients (14 GB), each GPU moves 2⋅78⋅14≈24.52\cdot\tfrac{7}{8}\cdot14 \approx 24.5 GB per step. The playbook lists three tricks to hide it:

  • Overlap: start the all-reduce for a layer as soon as its gradients are ready, while earlier layers are still in backward.
  • Bucketing: group many small gradients into larger messages.
  • No sync while accumulating: skip the all-reduce on gradient-accumulation steps.

DP does not reduce per-GPU memory. The playbook warns that around 512+ DP ranks on some networks, ring latency can prevent full overlap. The crossover depends on network topology, collective implementation, model size and compute per micro-batch; it is not a universal GPU-count limit.

3. ZeRO-1/2/3 and FSDP: shard the redundant copies

Section titled “3. ZeRO-1/2/3 and FSDP: shard the redundant copies”

Intuition: in plain DP every GPU stores the same optimizer states, gradients and weights. ZeRO keeps one copy in total, split across the NdN_d DP ranks, and each GPU fetches the pieces it needs just in time. In IR terms, a document-partitioned index where each node holds one shard.

StageShardedPer-GPU model statesCommunication for one forward/backward micro-batch plus update (large DP group, equal wire precision)
DPnothing16Ψ16\Psiall-reduce grads ≈ 2Ψ2\Psi
ZeRO-1optimizer states4Ψ+12Ψ/Nd4\Psi + 12\Psi/N_dreduce-scatter grads + all-gather params ≈ 2Ψ2\Psi
ZeRO-2+ gradients2Ψ+14Ψ/Nd2\Psi + 14\Psi/N_dsame as ZeRO-1 ≈ 2Ψ2\Psi
ZeRO-3 / FSDP+ parameters16Ψ/Nd16\Psi/N_dall-gather params (fwd) + all-gather (bwd) + reduce-scatter ≈ 3Ψ3\Psi (1.5×)

In memory formulas Ψ\Psi is a parameter count multiplied by byte coefficients. In the communication column, 2Ψ2\Psi and 3Ψ3\Psi count transmitted values, not bytes.

In ZeRO-1, each rank updates only its 1/Nd1/N_d slice of FP32 weights and then all-gathers the BF16 weights. ZeRO-2 also keeps only the gradient slice it needs, so the gradient all-reduce becomes a reduce-scatter. The communication is the same, and the playbook calls ZeRO-2 “usually the better option”. For this single-micro-batch accounting, stages 1/2 communicate about 2Ψ2\Psi elements and stage 3 about 3Ψ3\Psi elements per rank; multiply by bytes per element and by (Nd−1)/Nd(N_d-1)/N_d for the ring estimate. With gradient accumulation, plain DP can synchronise once per optimizer update, whereas fully resharded ZeRO-3 generally gathers parameters for each micro-batch. Its update-level traffic can therefore exceed 1.5× DP. Resharding, gradient-sync and parameter-retention policies determine the actual cost. ZeRO-3 (PyTorch calls it FSDP) also shards the weights. Before each layer runs, it all-gathers that layer’s weights and frees them afterwards. Prefetching the next layer’s weights during the current layer’s compute hides most of this traffic. Let qq be communicated bytes per parameter, FF be FLOP/s and BB be bytes/s. For a layer with PP parameters and T=s⋅mbsT = s\cdot\text{mbs} tokens, one parameter all-gather costs about qP(Nd−1)/(NdB)qP(N_d-1)/(N_d B) seconds, while its forward matmul costs about 2TP/F2TP/F. A first-order overlap condition is therefore

q2T⋅Nd−1Nd⋅FB≤1,\frac{q}{2T}\cdot\frac{N_d-1}{N_d}\cdot\frac{F}{B} \le 1,

which with BF16 (q=2q=2) becomes Nd−1Nd⋅FTB≤1\frac{N_d-1}{N_d}\cdot\frac{F}{TB} \le 1. You need enough tokens per micro-batch. (The playbook’s appendix prints this without qq, labelling parameter counts as bytes; that is only consistent if BB is measured in parameter values per second.)

Worked example, continued (7B on 8 GPUs):

  • ZeRO-1: 28+84/8=38.528 + 84/8 = 38.5 GB.
  • ZeRO-2: 14+98/8=26.2514 + 98/8 = 26.25 GB.
  • ZeRO-3: 112/8=14112/8 = 14 GB, or 17.5 GB with FP32 gradients.

For one micro-batch, traffic rises from about 24.5 GB to about 36.75 GB sent per GPU (the same amount is received). ZeRO-DP stages 1–3 do not shard each rank’s distinct micro-batch activations. The original paper separately describes ZeRO-R partitioning replicated activation checkpoints across model-parallel ranks. With FlashAttention at s=4096s=4096, ZeRO-3 plus about 18 GB of activations is about 32 GB, which fits in 80 GB. For comparison, the ZeRO paper’s own table gives a 7.5B model on 64 GPUs: 120 GB under DP, then 31.4, 16.6 and 1.88 GB for ZeRO-1, 2 and 3.

4. Tensor parallelism (TP), and sequence parallelism (SP) alongside it

Section titled “4. Tensor parallelism (TP), and sequence parallelism (SP) alongside it”

Intuition: split each matrix multiply across GPUs so that every GPU holds only a slice of each layer’s weights and activations. The cost is a collective inside every layer.

Megatron-LM’s recipe for the MLP Y=GeLU(XA)Y=\text{GeLU}(XA), Z=YBZ = YB. For hidden width hh, XX has shape [tokens, hh], AA has shape [hh, 4h4h] and BB has shape [4h4h, hh] in the original GPT-style MLP. A column shard produces only its own intermediate features; the matching BB row shard turns those into a partial sum of the same output vector.

A=[A1,A2] (columns)⇒Yi=GeLU(XAi) locally;B=[B1B2] (rows)⇒Z=∑iYiBi via one all-reduce.A = [A_1, A_2]\ (\text{columns}) \Rightarrow Y_i = \text{GeLU}(XA_i)\ \text{locally};\qquad B = \begin{bmatrix}B_1\\B_2\end{bmatrix}\ (\text{rows}) \Rightarrow Z = \textstyle\sum_i Y_iB_i\ \text{via one all-reduce}.

The order matters. Splitting AA by rows would give GeLU(X1A1+X2A2)\text{GeLU}(X_1A_1+X_2A_2), which needs a synchronisation before the nonlinearity. Attention is split by heads: Q, K and V are column-parallel, so each GPU computes its own heads, and the output projection is row-parallel. Each block (MLP or attention) needs one all-reduce forward and one backward, so a complete transformer layer needs two all-reduces forward and two backward (Megatron’s conjugate operators gg and ff). The TP degree cannot usefully exceed the number of heads.

These collectives sit on the critical path and scale with s⋅b⋅hs\cdot b\cdot h. Frequent, latency-critical collectives make TP a strong candidate for the fastest interconnect, commonly NVLink inside a node. This is a placement heuristic, not a hardware requirement. Narayanan et al.’s Takeaway #1 is to use TP up to the number of GPUs per server, and pipeline parallelism beyond that. The playbook measures the big drop between TP = 8 and TP = 16. Sequence parallelism (SP) fixes a leak: LayerNorm and dropout still hold full (b,s,h)(b,s,h) activations under TP. SP splits those regions along the sequence instead, replacing each all-reduce with an all-gather plus a reduce-scatter. The communication volume is the same, and the formerly replicated LayerNorm/dropout activations shrink from bshbsh to bsh/tpbsh/\text{tp} elements per GPU. TP regions still materialise other shapes, including full-sequence inputs and expanded MLP intermediates; this is not a bound on the largest activation anywhere in the layer.

5. Context parallelism (CP) and Ring Attention

Section titled “5. Context parallelism (CP) and Ring Attention”

Intuition: for 128K-token sequences, even one layer’s activations do not fit. Split the sequence itself across GPUs. MLP and LayerNorm are per-token, so they need no communication. Only attention needs every key and value.

Ring Attention. Each GPU keeps its query block. Key/value blocks circulate around a ring of GPUs. At each step a GPU sends its current K/V block on, computes blockwise attention with the block it holds, and merges the partial results with FlashAttention’s online softmax. This is like a block nested-loop join in which the inner relation is streamed past each node. Write bb for batch size, cc for the local block length in tokens and hh for hidden width (the paper calls it dd). Communication hides behind compute if one block’s attention FLOPs (4hc24hc^2 for QK⊤QK^\top and PVPV) take longer than moving its K and V (4ch4ch bytes in BF16):

4hc2F≥4chB ⇒ c≥FB.\frac{4hc^2}{F} \ge \frac{4ch}{B}\ \Rightarrow\ c \ge \frac{F}{B}.

Here FF is achieved compute throughput in FLOP/s and BB is achieved one-way link bandwidth in bytes/s; using peaks gives only an optimistic design estimate. Causal masking, GQA and actual kernels alter the compute/communication balance. Because memory depends on the local block cc, not on the total length, adding devices lets the total context grow. Under a causal mask the naive layout overloads the GPUs that hold late tokens. Zig-zag assignment gives each GPU a mix of early and late chunks.

Optional: Ring Attention buffer arithmetic

Section titled “Optional: Ring Attention buffer arithmetic”

For an A100 (312 TFLOP/s) over NVLink at 300 GB/s, c≥312×1012/(300×109)=1,040c \ge 312\times10^{12}/(300\times10^9) = 1{,}040 tokens; the paper’s Table 2 lists 1.0K, and 6.2K as the minimal sequence length per device. Over InfiniBand at 12.5 GB/s, c=312×1012/(12.5×109)=24,960c = 312\times10^{12}/(12.5\times10^9) = 24{,}960 tokens, approximately 25K. The paper’s Table 2 prints 24.5K and 149.5K; the stated specifications instead give c=24.96c = 24.96K and 6c=149.766c = 149.76K. The latter is the paper’s six-block-equivalent storage quantity, not a requirement that every GPU owns six distinct input-sequence blocks.

In the paper’s six-block working-set model, each block has b×c×hb\times c\times h elements: one query, current K/V, receive K/V and one output block. This is 6bch6bch elements, or about 12bch12bch bytes in BF16. (The paper writes ”6bch6bch bytes” after counting six tensors, while using two-byte values in its own communication arithmetic.) It excludes model states and other training allocations.

6. Pipeline parallelism (PP) and the bubble

Section titled “6. Pipeline parallelism (PP) and the bubble”

Intuition: put layers 1–8 on GPU 1, 9–16 on GPU 2, and so on, and pass activations down the line. Only activations cross the stage boundaries, so PP tolerates slow inter-node links. Like a multi-stage ranking cascade on different machines, the stages sit idle while the pipeline fills and drains.

With pp stages, mm micro-batches, and per-stage forward and backward times tf,tbt_f, t_b, the bubble is tpb=(p−1)(tf+tb)t_{pb} = (p-1)(t_f+t_b) against ideal work tid=m(tf+tb)t_{id} = m(t_f+t_b):

tpbtid=p−1m(GPipe/AFAB and 1F1B),tpbtid=1v⋅p−1m(interleaved, v chunks per GPU).\frac{t_{pb}}{t_{id}} = \frac{p-1}{m}\quad\text{(GPipe/AFAB and 1F1B)},\qquad \frac{t_{pb}}{t_{id}} = \frac{1}{v}\cdot\frac{p-1}{m}\quad\text{(interleaved, } v \text{ chunks per GPU)}.

As a share of total wall-clock time the idle fraction is (p−1)/(m+p−1)(p-1)/(m+p-1).

Worked example (p=4p=4, m=8m=8, tb=2tf=2t_b = 2t_f = 2 units).

  • Ideal work per GPU: 8×3=248\times3 = 24 units.
  • Bubble: 3×3=93\times3 = 9 units, so 9/24=37.5%9/24 = 37.5\% overhead, and the GPUs are idle 9/33≈27%9/33 \approx 27\% of the step.
  • Interleaving with v=2v=2 halves the bubble to 4.5 units: 18.75% overhead, about 16% idle. The price is twice the point-to-point messages.

The forward half of AFAB shows the start of the bubble (. = idle):

GPU1 F1 F2 F3 F4 F5 F6 F7 F8 . . .
GPU2 . F1 F2 F3 F4 F5 F6 F7 F8 . .
GPU3 . . F1 F2 F3 F4 F5 F6 F7 F8 .
GPU4 . . . F1 F2 F3 F4 F5 F6 F7 F8 → then all backwards, mirrored

1F1B (Narayanan et al.’s PipeDream-Flush) has the same bubble as AFAB. It starts backward passes as early as possible, so each stage stashes activations for at most pp micro-batches instead of mm. That is what lets you raise mm. Here m=gbs/(dp⋅mbs)m = \text{gbs}/(\text{dp}\cdot\text{mbs}). At fixed pipeline degree pp and fixed global/micro-batch sizes, increasing DP reduces mm and increases the relative bubble (p−1)/m(p-1)/m; it also requires more GPUs. Narayanan et al.’s separate fixed-GPU-count comparison sets TP = 1 and p=n/dp = n/d, giving (n−d)/b′(n-d)/b', where nn is the total GPU count, dd is DP and b′b' = global batch/micro-batch. In that comparison, increasing DP reduces PP and makes the bubble smaller. Note that PP does not reduce activation memory for the first stage: it holds about p×(acts/p)p\times(\text{acts}/p).

Zero-bubble schedules split the backward pass into the input-gradient part (B), which the previous stage is waiting for, and the weight-gradient part (W), which can be deferred to fill gaps. DualPipe (DeepSeek-V3) extends this with micro-batches entering from both ends of the pipeline. Such schedules can be searched using integer-linear-program formulations or heuristics, but this is not a requirement of 1F1B, zero-bubble scheduling or DualPipe. DeepSeek-V3 describes a hand-designed overlap schedule rather than reporting an ILP-based tuning procedure.

For MoE layers, place different experts on different GPUs. An all-to-all sends each token to the GPUs that hold its routed experts, and a second all-to-all brings the results back. This is federated search with resource selection: route each query to the shards that matter, and the hot shard sets your latency. EP only touches MoE layers, so it is combined with DP for everything else. DeepSeek-V3 limits each token to at most 4 nodes to bound the traffic. The MoE Training Handbook covers the systems details (load imbalance, all-to-all bandwidth across nodes, overlap tricks). This page does not repeat them.

8. Putting it together (“5D”) and a decision recipe

Section titled “8. Putting it together (“5D”) and a decision recipe”
MethodSplits alongSaves memory onCommunicationMain cost
DPbatchactivations per GPU (smaller local batch)grad all-reduce, once per steplimited by max batch
ZeRO-1/2/3DP ranksoptimizer → grads → params+ param all-gathers1.5× traffic at stage 3
TP + SPhidden / sequenceparams and activationscollectives inside every layerneeds intra-node bandwidth
CPsequence (all layers)activationsK/V ring in attentionattention communication
PPlayersparamspoint-to-point activationsbubble, complex schedules
EPexpertsexpert paramsall-to-all per MoE layerneeds MoE, load balance

The playbook’s recipe, in three steps:

  1. Fit one training step in memory.
    • Under 10B: TP or ZeRO-3 with full recompute on 8 GPUs.
    • 10–100B: TP = 8 combined with PP or with ZeRO-3, or ZeRO-3 alone.
    • At around 512+ GPUs, depending on the network, pure DP/ZeRO-3 communication can stop overlapping, so combine DP with TP or PP (the limit depends on the DP group size and fabric, not total GPUs alone). At 1024+ GPUs, TP = 8 + ZeRO-2 + PP.
    • Add CP for long sequences and EP for MoE, both across nodes.
  2. Reach the target global batch with DP and gradient accumulation (or CP for long sequences).
  3. Optimise throughput:
    • Raise TP up to the node size.
    • Grow DP/ZeRO until its communication bottlenecks, then switch to PP.
    • Tune the micro-batch size.

The playbook sweeps all of this at sequence length 4,096 and a 1M-token global batch, and reports results as heatmaps.

MFU (model FLOPs utilization) is the score you report. It is the model FLOPs actually needed per second divided by the hardware’s peak. It excludes recomputation, unlike hardware FLOPs utilization (HFU). A training step costs about 6⋅N⋅tokens6\cdot N\cdot \text{tokens} FLOPs (2 forward, 4 backward), plus an attention term 12⋅L⋅h⋅s212\cdot L\cdot h\cdot s^2 per sequence that this rough count ignores. Hypothetical example: a 7B model at 10,000 tokens/s per GPU needs 6×7×109×104=4.2×10146\times7\times10^9\times10^4 = 4.2\times10^{14} FLOP/s. Against a hypothetical 1,000 TFLOP/s peak, that is 42% MFU. Narayanan et al. report 502 PFLOP/s on 3,072 A100 GPUs for a 1T-parameter model, or about 52% of peak. Their Appendix FLOP accounting includes the extra forward pass for activation recomputation, so this is a hardware-FLOP-utilisation-style number, not directly the recomputation-excluding MFU defined above.

ClaimNumberSource
Model states, BF16 + Adam16Ψ bytes (K = 12); 20Ψ with FP32 gradsZeRO §3.1; playbook
7B / 70B / 405B model states112 / 1,120 / 6,480 GB (140 / 1,400 / 8,100 with FP32 grads)playbook table
ZeRO, 7.5B on 64 GPUs120 → 31.4 / 16.6 / 1.88 GB (stages 1/2/3)ZeRO Table 1
ZeRO-3 traffic3Ψ vs 2Ψ values, i.e. 1.5× (one micro-batch, no gradient accumulation)ZeRO §7.2
Selective recompute, GPT-3 175B−70% activation memory, +2.7% computeplaybook
Full recomputeup to ≈ 30–40% more computeplaybook
Cross-node scaling, p = 8 → 16 vs TP≈ 14% drop for PP vs ≈ 43% for TPplaybook
Megatron-LM 8.3B on 512 V100s (TP = 8)15.1 PFLOP/s, 76% scaling efficiencyShoeybi et al.
Interleaved schedule10+% higher throughputNarayanan et al.
PTD-P 1T parameters, reported throughput, including recomputation502 PFLOP/s on 3,072 GPUs, 52% of peak per GPUNarayanan et al.
Ring Attention minimal block, A100≈ 1K tokens (NVLink); 24.96K from the stated specs at 12.5 GB/s InfiniBand (table prints 24.5K)Liu et al. Table 2
  • Formulas are first-order. Memory ignores the 1–2 GB of CUDA kernels, communication buffers and fragmentation. The activation formula assumes a GPT-style block. The 6N6N FLOP count ignores the attention term. Real peaks come from the profiler.
  • “Overlap” is not free. The playbook notes that communication kernels use the same streaming multiprocessors as compute, so overlapped communication still slows the matmuls.
  • Rankings are implementation-dependent. In the playbook’s own runs, TP beat PP until the PP code was optimised. Treat any “X is faster” claim as a claim about one codebase and one cluster.
  • Benchmarks are narrow. The heatmaps use 8×H100 nodes, sequence length 4,096 and a 1M-token batch, measured on short runs. Frontier runs use larger batches, other fabrics and MoE models.
  • Terminology collides. “Sequence parallelism” means TP-coupled LayerNorm/dropout sharding in Megatron and the playbook, but some papers use it for what this page calls context parallelism. Megatron’s f/gf/g operator names differ from the playbook’s figures.
  • The memory rule depends on precision choices. FP8 training and BF16 optimizer moments change the bytes per parameter (see FP8-LM and DeepSeek-V3).
  • AdamW: the two FP32 moments that make up 8 of the 16 bytes per parameter.
  • Muon: its Newton-Schulz step needs whole matrices, so it clashes with ZeRO and TP sharding. Moonlight gathers each matrix under ZeRO-1, orthogonalises it, then keeps only its own shard.
  • FP8-LM: shrinks the same memory bill from the precision side and sends FP8 tensors through TP/SP and ZeRO.
  • FlashAttention: its online softmax is what lets Ring Attention merge partial results exactly, and its recomputation is the “selective checkpointing” most stacks already get for free.
  • MoE Training Handbook: the expert-parallel half of the story, including all-to-all cost, imbalance and measured overlaps.
  • DeepSeek-V3: PP + EP + ZeRO-1 with DualPipe in practice. Llama 3: the playbook cites Llama 3.1’s interleaved 1F1B schedule with tunable depth-first/breadth-first priority.
  • CS336: its parallelism lectures and napkin-math exercises (MFU, AdamW memory) drill the same arithmetic. Making DL go brrrr gives the single-GPU compute/memory/overhead picture underneath.

You should now be able to:

  • compute model-state memory for any size under DP and ZeRO-1/2/3, and estimate activations;
  • explain why TP stays inside a node and why PP and ZeRO go across nodes;
  • compute a pipeline bubble and say how 1F1B, interleaving and the global batch change it;
  • explain how Ring Attention hides communication and when it cannot (c ≥ F/B);
  • propose a TP × PP × DP (× CP × EP) layout for a given model and cluster, and say how you would validate it with MFU and memory measurements.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    A 13B-parameter model is trained in BF16 mixed precision with Adam (no FP32 gradient copy) on 16 data-parallel GPUs with 80 GB each. Compute the per-GPU memory for model states under plain DP, ZeRO-1, ZeRO-2 and ZeRO-3, say which fit, and compare the communication volume of plain DP and ZeRO-3 for one forward/backward micro-batch.

    What a strong answer covers
    • Per parameter: 2 (BF16 weights) + 2 (BF16 grads) + 4 (FP32 master copy) + 4 + 4 (Adam m and v) = 16 bytes, so plain DP needs 16 × 13e9 = 208 GB per GPU and does not fit.
    • ZeRO-1 shards the 12 bytes of optimizer state: 4Ψ + 12Ψ/16 = 52 + 9.75 ≈ 61.8 GB. ZeRO-2 also shards gradients: 2Ψ + 14Ψ/16 = 26 + 11.4 ≈ 37.4 GB. ZeRO-3 shards everything: 16Ψ/16 = 13 GB.
    • All three ZeRO stages fit the model states (not a proof that peak memory fits). ZeRO-DP stages 1–3 do not shard each rank's own micro-batch activations (ZeRO-R separately partitions activation checkpoints across model-parallel ranks), so ZeRO-1 leaves only about 18 GB for activations and buffers.
    • DP all-reduces gradients (reduce-scatter + all-gather); ZeRO-1/2 use a gradient reduce-scatter plus a parameter all-gather; ZeRO-3 all-gathers parameters in forward and backward plus the reduce-scatter. For one micro-batch and equal BF16 precision, DP sends 2 × (15/16) × 13e9 × 2 = 48.75 GB per rank; ZeRO-3 sends 73.125 GB, a 1.5× ratio. Received bytes are the same again.
    • Under gradient accumulation, DP can synchronise once per optimizer update while fully resharded ZeRO-3 re-gathers parameters for every micro-batch, so the update-level ratio can exceed 1.5×.
    • The extra ZeRO-3 traffic can be hidden by prefetching the next layer's weights, provided each layer's compute is long enough (large sequence × micro-batch) and DP is not too large.
  2. Derive / compute

    You train with pipeline parallelism p = 8 using 1F1B, a global batch of 1,024 sequences and micro-batch size 2. Compute the bubble as a fraction of ideal compute, (p − 1)/m, when the data-parallel degree is 4 and when it is 16, then with interleaving v = 2 at DP = 16. Explain the trade-off this exposes.

    What a strong answer covers
    • m = global batch / (DP × micro-batch). DP = 4: m = 1024/8 = 128, bubble = 7/128 ≈ 5.5%. DP = 16: m = 32, bubble = 7/32 ≈ 21.9%.
    • Interleaving with v = 2 divides the bubble by v: 7/64 ≈ 10.9% at DP = 16, at the cost of v times more point-to-point communication.
    • The numerical comparison holds PP fixed and changes the total GPU count. Narayanan §3.3.1 instead fixes n GPUs with TP = 1, so p = n/d and the bubble is (n − d)/b′; increasing DP there reduces PP and reduces the bubble. State what is held fixed before predicting a trend.
    • 1F1B does not shrink the bubble compared with GPipe/AFAB; it caps stashed activations at p micro-batches instead of m, which is what makes a large m affordable.
    • The global batch is set by optimisation, so m cannot grow freely; the levers are fewer stages, interleaving, or zero-bubble schedules that split the backward pass.
  3. Mechanism

    In Megatron-style tensor parallelism the MLP's first matrix is split by columns and the second by rows. Explain why this order needs only one all-reduce in the forward pass, what goes wrong if the first matrix is split by rows, how attention is split, and why the playbook keeps TP inside a node.

    What a strong answer covers
    • Column split of A: each GPU computes XAᵢ on the full input and applies GeLU locally, because GeLU acts elementwise on that GPU's own output columns.
    • Row split of B consumes those local outputs directly; each GPU produces a partial sum of the full output, and one all-reduce (Megatron's g operator) sums them before dropout. Backward needs the conjugate all-reduce (f) on the input gradient.
    • Row-splitting A first gives GeLU(X₁A₁ + X₂A₂) ≠ GeLU(X₁A₁) + GeLU(X₂A₂), so a synchronisation is needed before the nonlinearity.
    • Attention: Q, K, V projections are split by heads (column-parallel) and the output projection by rows, giving two all-reduces forward and two backward per layer; the TP degree should not exceed the number of heads.
    • These all-reduces sit on the critical path and scale with activation size (sequence × batch × hidden), so they are strong candidates for the fastest (NVLink-class) interconnect; the playbook sees the large throughput drop going from TP = 8 to TP = 16, i.e. across nodes.
  4. Mechanism

    Ring Attention assigns each GPU a c-token query block of hidden width h and circulates equally sized K/V blocks. With BF16 values, compute the FLOPs and bytes per ring step, derive the block-size condition for hiding communication, and evaluate it at F = 312 TFLOP/s for B = 300 GB/s and 12.5 GB/s. Explain how online softmax merges blocks exactly, how causal masking affects load balance, and what the six-buffer memory estimate does not include.

    What a strong answer covers
    • Each GPU keeps its query block while key/value blocks rotate around a ring. At each step a GPU sends its current K/V block on, computes blockwise attention with the block it holds, and merges results with an online softmax (running max and sum), as FlashAttention does within one GPU.
    • The simplified dense attention step uses 4hc² FLOPs (QKᵀ and PV) and transfers 4ch bytes (K and V in BF16), giving c ≥ F/B: 1,040 or 24,960 tokens. These are peak-hardware estimates, not measured universal thresholds.
    • Six buffers of shape [b, c, h] contain 6bch elements, or 12bch BF16 bytes; model states and other saved training tensors are additional. Fixed local c permits longer total contexts by adding ranks.
    • Under a causal mask the GPU holding the earliest tokens has little work and the one holding the latest has the most; zig-zag assignment gives every GPU a mix of early and late chunks so the work is balanced.
  5. What if…

    A dense model no longer fits at TP = 8 inside one 8-GPU node. One engineer proposes TP = 16 across two nodes; another proposes TP = 8 with PP = 2 across the nodes. Using the communication pattern of each and the playbook's measurements, predict which is faster and when the answer could flip.

    What a strong answer covers
    • TP moves activations with all-reduces (or all-gather + reduce-scatter with SP) several times per layer, on the critical path; across nodes these run on the slower inter-node fabric.
    • PP sends one activation tensor per micro-batch across each stage boundary (point-to-point), so it needs far less bandwidth.
    • Playbook benchmarks: throughput drops sharply from TP = 8 to TP = 16; with 1F1B, going from p = 8 to p = 16 at few micro-batches cost about 14%, against about 43% for TP in similar cross-node settings.
    • PP pays a bubble of (p − 1)/m; with p = 2 and many micro-batches it is small, but a small global batch (few micro-batches per pipeline) can make PP lose.
    • The playbook notes that implementation quality decides the ranking: its TP beat its PP until the PP code was optimised.
  6. Design

    Design the parallel layout for a dense 70B model on 64 nodes of 8 × 80 GB GPUs (512 GPUs), sequence length 8K, global batch about 4M tokens, with a later 128K-context phase. Give TP, PP, DP/ZeRO and CP degrees, check memory and the pipeline bubble, and say how you would validate the choice.

    What a strong answer covers
    • Model states: 70B × 16 bytes ≈ 1,120 GB. TP = 8 inside a node gives 140 GB per GPU, still over 80 GB, so add PP (PP = 4 gives about 35 GB) or shard with ZeRO across nodes.
    • With TP = 8 and PP = 4 a replica uses 32 GPUs, so DP = 16. The batch is 4M / 8K = 512 sequences, 32 per replica; with micro-batch 1, m = 32 and the 1F1B bubble is 3/32 ≈ 9%. ZeRO-1 over DP16 shards the optimizer state further, from 35 to about 10.4 GB before activations and buffers (DeepSeek-V3 combined PP with ZeRO-1).
    • Alternative: TP = 8 plus ZeRO-3 over the nodes has no bubble but must hide parameter all-gathers behind compute; the playbook warns that, depending on the network, DP/ZeRO-3 at around 512+ GPUs can become bound by ring latency. What matters is the size of the DP communication group (64 ranks here), not the total GPU count alone.
    • For an approximately 4,194,304-token batch at 131,072-token context there are 32 sequences. One candidate is TP8 × PP4 × CP16 × DP1 = 512: micro-batch 1 gives m = 32 and 9.375% ideal bubble overhead, with 8K local sequence blocks. Model states remain about 35 GB before activations; DP-only ZeRO-1 no longer helps at DP1. Profile memory and exposed CP traffic rather than assuming this candidate fits or hides communication.
    • Validate with short runs of 2–3 candidate layouts measuring tokens/s, MFU and peak memory; profile exposed communication; keep the layout with the best MFU that fits with headroom.

Done with this page?

Status