Pre-training frontier autoregressive Transformer models with tens of billions to over a trillion parameters across thousands of interconnected accelerators confronts two fundamental hardware physics walls: device HBM memory capacity and hierarchical cluster interconnect bandwidth. Under standard 16-bit mixed-precision training (FP16 or BF16 forward/backward compute paired with an FP32 Adam optimizer, Micikevicius et al., 2017; Kingma & Ba, 2015), a model with $\Psi$ parameters requires $2\Psi\text{ bytes}$ for its 16-bit weights and $2\Psi\text{ bytes}$ for its 16-bit gradients, but demands an additional $K\Psi = 12\Psi\text{ bytes}$ ($4\Psi$ each for FP32 master weights, first-moment momentum, and second-moment variance) to maintain numerical stability during parameter updates—totaling $2\Psi + 2\Psi + 12\Psi = 16\Psi\text{ bytes}$ of model-state memory (arXiv:1910.02054, Section 2.1). Consequently, even a modest 1.5B parameter GPT-2 model consumes $24\text{GB}$ of model states alone (plus $60\text{GB}$ of forward activations at sequence length $1024$ and batch size $32$), while a 7.5B model requires $120\text{GB}$, a 128B model requires $2,048\text{GB}$, and a 1 Trillion parameter model requires $16,000\text{GB}$ ($16\text{TB}$) of model-state memory before counting a single byte of intermediate activations or temporary communication buffers (arXiv:1910.02054, Table 1).
At the same time, scaling out across multi-GPU server nodes exposes a steep drop in communication bandwidth: while intra-node GPUs inside an 8-GPU NVIDIA DGX A100 or DGX-2 node communicate over NVLink and NVSwitch at $300\text{--}600\text{ GB/s}$, inter-node communication across InfiniBand (EDR / HDR $100\text{--}200\text{ Gbps}$ per HCA) or RoCEv2 RDMA links drops by more than an order of magnitude (12.5–25 GB/s per link, arXiv:1910.02054, Section 7.2; arXiv:2104.04473, Section 5). Naively partitioning layers across nodes either stalls Tensor Cores behind cross-node AllReduce barriers or leaves accelerators idle inside pipeline flush bubbles.
Between 2019 and 2026, seven foundational distributed systems breakthroughs solved how model states, intermediate activations, and backward gradient operators are partitioned, overlapped, and scheduled across multi-node GPU clusters:
- Zero Redundancy Optimizer (
ZeRO-DP&ZeRO-R, Rajbhandari et al., Microsoft, SC20,arXiv:1910.02054): Eliminates the $N_d$-fold replication of model states across data-parallel (DP) ranks by partitioning them in three cumulative stages: $\text{ZeRO-1}$ ($P_{\text{os}}$) shards optimizer states ($4\Psi + \frac{12\Psi}{N_d}$ bytes, yielding up to a $4\times$ memory reduction with $0\%$ extra communication over standard DP's $2\Psi$ volume); $\text{ZeRO-2}$ ($P_{\text{os+g}}$) shards both optimizer states and gradients ($2\Psi + \frac{14\Psi}{N_d}$ bytes, up to $8\times$ memory reduction at the exact same $2\Psi$ communication volume viaReduce-Scatter+All-Gather); and $\text{ZeRO-3}$ ($P_{\text{os+g+p}}$) shards optimizer states, gradients, and parameters ($\frac{16\Psi}{N_d}$ bytes, providing a linear $N_d\times$ reduction—shrinking a7.5Bmodel at $N_d = 64$ from $120\text{GB}$ to $1.88\text{GB}$ and fitting a1Tmodel in $15.6\text{GB}$ per GPU across $N_d = 1024$ GPUs—at only a $1.5\times$ ($3\Psi$) communication volume). Paired with $\text{ZeRO-R}$ (partitioned activation checkpointing $P_a$, cutting100Bmodel activation checkpoints from $33\text{GB}$ to $2\text{GB}$ per GPU at $16$-way MP),ZeRO-100Btrains models up to170Bparameters on $400$V100GPUs at $15\text{ PetaFLOPs}$ ($>30\%$ peak, $8\times$ larger and $10\times$ faster than standalone Megatron-LM) and trainedTuring-NLG 17Bto a recordWebtext-103perplexity of $10.21$ at $41.4\text{ TFLOPs/GPU}$. - Unique Optimal CPU-GPU Dataflow Graph Partitioning (
ZeRO-Offload, Ren et al., Microsoft, USENIX ATC 2021,arXiv:2101.06840): Models mixed-precision Adam training as a weighted directed dataflow graph and proves that keepingFP16parameters (p16) and $O(MB)$ forward/backward compute (FWD-BWD Super) on the GPU while offloadingFP16gradients (g16) and theFP32Update Supernode (p32,momentum32,variance32, and $O(M)$CPU-Adamupdate) to host CPU RAM is the unique optimal partition: it achieves the theoretical minimum PCIe communication volume of $4M\text{ bytes}$ ($7\times$ less thanL2L's $28M$) and an $8\times$ GPU model-state memory reduction ($16M \to 2M$). Combined with SIMD AVX-512CPU-Adam($5.0\times\text{--}6.4\times$ faster than PyTorch CPU Adam) and One-Step Delayed Parameter Update (DPU),ZeRO-Offloadtrains13Bparameters on a single $32\text{GB}$ V100 GPU at $>30\text{ TFLOPS}$ ($9.3\times$ larger than PyTorch DDP's1.4Blimit) and70Bparameters on a single 16-GPU DGX-2 node. - PyTorch Fully Sharded Data Parallel (
FSDP, Zhao et al., Meta, VLDB 2023,arXiv:2304.11277): Coalesces arbitrary submodule parameters into 1D right-paddedFlatParametertensors soNCCLAllGatherandReduceScatterexecute at maximum bandwidth without intermediate copy buffers (Figure 1b: avoiding the steep latency cliff below $33\text{M}$FP32elements). By combiningHYBRID_SHARD(intra-host sharding of factor $F$ + inter-host replication, cutting cross-host traffic from $3M\frac{W-1}{W}$ to $2M\frac{W-1}{GW}$), Dedicated Producer Stream Overlap & Backward Prefetching (reorderingAllGather(L-1)ahead ofReduceScatter(L)in the internal NCCL stream for an $18\%$ TFLOPS speedup onGPT-175B), and a CPU-to-GPU Caching Allocator Rate Limiter (capping in-flightAllGathers at $2$ to eliminatecudaMallocretry defragmentation stalls for up to a $5\times$ speedup onT5-11B),FSDPscalesGPT-175Blinearly from $128$ to $512$A100-80GBGPUs at $173\text{--}186\text{ TFLOPS/GPU}$ ($55\%\text{--}60\%$ peak hardware utilization). - Megatron-LM Intra-Layer Tensor Parallelism (
TP, Shoeybi et al., NVIDIA,arXiv:1909.08053) & Composed 3DPTD-PParallelism (Narayanan et al., NVIDIA & Stanford, SC21, arXiv:2104.04473): Splits MLP weight matrices column-wise then row-wise ($Y = \text{GeLU}(X [A_1, A_2])$, $Z = [Y_1, Y_2] [B_1^\top, B_2^\top]^\top$) and partitions multi-head attention heads across $t$ intra-node GPUs, requiring only $2$AllReduceoperations in the forward pass and $2$ in the backward pass per Transformer layer via conjugate operators $f$ and $g$. On $512$V100GPUs,Megatron-LMtrainsGPT-2 8.3Bat $15.1\text{ PetaFLOPs}$ ($76\%$ scaling efficiency vs. $39\text{ TFLOPs}$ single-GPU baseline) to10.81WikiText103 perplexity and66.51%LAMBADA accuracy, andBERT 3.9Bto90.9%RACE accuracy. Composing Tensor (t), Interleaved1F1BPipeline (p), and Data (d) Parallelism (PTD-P,arXiv:2104.04473) scales a1 Trillionparameter GPT model across $3,072$A100-80GBGPUs at $163\text{ TFLOP/s per GPU}$ ($502\text{ PetaFLOP/s}$ aggregate, $52\%$ of theoretical peak) while outperforming standaloneZeRO-3(without MP) by $+70\%$ throughput on175Band530Bmodels when doubling GPU counts. - Sequence Parallelism (
SP) and Selective Activation Recomputation (Korthikanti et al., NVIDIA, MLSys 2023, arXiv:2205.05198): StandardTPleavesLayerNorm, residual additions, andDropoutreplicated across the $t$ tensor-parallel ranks, leaving $10sbh\text{ bytes/layer}$ unsharded in the per-layer activation formula $sbh\left(10 + \frac{24}{t} + 5\frac{as}{ht}\right)$. Sequence Parallelism (SP) partitions those non-TP regions along the sequence axis $s/t$ and replaces each conjugateAllReduce($f / \bar{f}$) with a mathematically equivalentAllGather($g$) andReduceScatter($\bar{g}$) pair at zero extra communication volume, reducing activation memory to $\frac{sbh}{t}\left(34 + 5\frac{as}{h}\right)$. PairingSPwith Selective Activation Recomputation—which checkpoints and recomputes only the attention score matrix operations ($QK^\top$, $\text{Softmax}$, dropout, and attention-over-$V$, costing $5\frac{as^2b}{t}$ bytes—$70\%$ ofGPT-3 175Band $65\%$ ofMT-NLG 530Bactivations—at just $2.7\%$ and $1.6\%$ extra FLOPs)—slashes total activation memory by $5\times$, cuts single-layer22Brecomputation time overhead from $+39\%$ ($27.2\text{ ms}$) down to $+4\%$ ($20.3\text{ ms}$), acceleratesMT-NLG 530Bon $2,240$A100GPUs from $42.1\%$ to $54.2\%$ MFU ($+29\%$ speedup), and reaches $56.3\%$ MFU ($57.0\%$ HFU) on a1Tparameter model (Table 4). - Zero-Bubble Pipeline Parallelism (
ZB-H1,ZB-H2,ZB-1p,ZB-2p, andZB-V, Qi et al., Sea AI Lab, ICLR 2024,arXiv:2401.10241): Eliminates the classical synchronous pipeline bubble by splitting each layer's monolithic backward pass into two finer-grained operators: $B$ ($\nabla_{\mathbf{x}} f^\top \frac{d\ell}{d\mathbf{y}}$, input activation gradient), which must propagate immediately to stage $i-1$, and $W$ ($\nabla_{\mathbf{W}} f^\top \frac{d\ell}{d\mathbf{y}}$, parameter weight gradient), which has zero cross-stage dependency and can be dynamically scheduled into pipeline idle gaps. Combined with post-validation optimizer step rollback (replacing blocking globalAllReducegradient-norm/NaN barriers beforeoptimizer.step()) and the "V"-shaped 2-chunkZB-Vtopology (where both forward and backward passes originate from worker 1 under strict $p M_B$1F1Bmemory parity), Zero-Bubble Pipeline Parallelism reduces pipeline bubble rates to $<1\%$ (0.10%–0.66%onZB-2p) and outperforms1F1Bthroughput by up to $+23\%$ under identical memory limits (ZB-1p/ZB-V) and up to $+31\%$ under relaxed memory (ZB-2p).

Data-Parallel Matrix Partitioning Across Distributed Accelerators
This engineering reference derives the complete model-state and activation memory formulas, collective communication bandwidth cost models, pipeline bubble equations, empirical benchmark tables, and production PyTorch implementations across ZeRO-1/2/3, ZeRO-Offload, PyTorch FSDP, Megatron-LM 3D Parallelism, Sequence Parallelism + Selective Recomputation, and Zero-Bubble Pipeline Parallelism.
Executive Summary: Verified Equations & Empirical Cluster Benchmarks Across ZeRO, FSDP, Megatron-LM 3D & Zero-Bubble PP
- DeepSpeed ZeRO Stages 1/2/3 & ZeRO-R (
arXiv:1910.02054): Mixed-precision Adam requires $2\Psi + 2\Psi + 12\Psi = 16\Psi\text{ bytes}$. Partitioning across $N_d$ data-parallel ranks yields: ZeRO-1 ($P_{\text{os}}$) $= 4\Psi + \frac{12\Psi}{N_d}$ (4× reduction, $2\Psi$ comm); ZeRO-2 ($P_{\text{os+g}}$) $= 2\Psi + \frac{14\Psi}{N_d}$ (8× reduction, $2\Psi$ comm); ZeRO-3 ($P_{\text{os+g+p}}$) $= \frac{16\Psi}{N_d}$ ($N_d\times$ linear reduction, $3\Psi = 1.5\times$ comm, shrinking a7.5Bmodel at $N_d=64$ from 120GB to 1.88GB and fitting a 1T model in 15.6GB/GPU at $N_d=1024$). On 400 V100 GPUs,ZeRO-100Bscales to 170B parameters at 15 PetaFLOPs (8× larger, 10× faster than baseline MP) and trainsTuring-NLG 17Bto 10.21 Webtext-103 perplexity at 41.4 TFLOPs/GPU. - ZeRO-Offload (
arXiv:2101.06840): Keepingp16andFWD-BWD($O(MB)$) on GPU while offloadingg16andFP32 Update Super($O(M)$) to CPU RAM achieves the unique optimal $4M\text{ bytes}$ PCIe communication volume (7× lower thanL2L's $28M$) and 8× GPU model-state memory savings. With AVX-512CPU-Adam(5.0×–6.4× speedup over PyTorch CPU Adam) and 1-stepDPU(1.12×–1.59× throughput gain, preserving 92.8 SQuAD F1 on BERT-Large), it trains 13B models on a single 32GB V100 GPU and 70B models on one 16-GPU DGX-2 node at >30 TFLOPS/GPU. - PyTorch FSDP (
arXiv:2304.11277): Right-padded 1DFlatParametercoalescing,HYBRID_SHARD($2M\frac{W-1}{GW}$ cross-host traffic), backward prefetching (+18% TFLOPS on GPT-175B), and a 2-inflightAllGathercaching allocator rate limiter (up to 5× speedup on T5-11B) enable linear scaling ofGPT-175Bacross 128–512A100-80GBGPUs at 173–186 TFLOPS/GPU (55%–60% peak utilization). - Megatron-LM TP (
arXiv:1909.08053) & 3D PTD-P (arXiv:2104.04473): Intra-layer column/row GEMM partitioning uses 2AllReduces in forward and 2 in backward per layer ($8bsh\frac{t-1}{t}\text{ bytes/layer}$), trainingGPT-2 8.3Bon 512 V100s at 15.1 PetaFLOPs (76% scaling efficiency) to 10.81 WikiText103 PPL / 66.51% LAMBADA. Composing 3DPTD-Pwith Interleaved 1F1B ($\frac{1}{v}\frac{p-1}{m}$ bubble fraction) and scatter/gather cross-node optimization (+11% throughput) trains a 1T parameter GPT model on 3,072 A100 GPUs at 163 TFLOP/s/GPU (502 PetaFLOP/s aggregate, 52% peak). - Sequence Parallelism & Selective Activation Recomputation (
arXiv:2205.05198): SplittingLayerNormandDropoutalong $s/t$ viaAllGather+ReduceScatterand selectively recomputing only $5\frac{as^2b}{t}$ attention score matrices cuts per-layer activation memory from $sbh(34 + 5\frac{as}{h})$ to $34\frac{sbh}{t}$ (5× reduction) at only 2.7% (GPT-3 175B) and 1.6% (MT-NLG 530B) extra FLOPs, boosting530Bon 2,240 A100 GPUs from 42.1% to 54.2% MFU (+29% faster) and reaching 56.3% MFU on 1T parameters. - Zero-Bubble Pipeline Parallelism (
arXiv:2401.10241): Decoupling backward input-gradient $B$ ($sbh(24h+8s)$ FLOPs) from weight-gradient $W$ ($24sbh^2$ FLOPs) reduces pipeline bubble rates onGPT 1.5B–28.3Bfrom10.91%–26.46%(1F1B) down to 0.10%–0.66% (ZB-2p), delivering up to +23% throughput at equal memory (ZB-1p/ZB-V) and +31% under relaxed memory (ZB-2p).
1. Anatomy of the Training Memory Wall and DeepSpeed ZeRO Stages 1, 2, 3 & ZeRO-R (arXiv:1910.02054)
Why does a 1.5B parameter GPT-2 model—whose 16-bit (FP16 / BF16) weights occupy just $3\text{GB}$ of memory—trigger an immediate Out-Of-Memory (OOM) crash on a $32\text{GB}$ NVIDIA Tesla V100 GPU under standard PyTorch or TensorFlow Data Parallelism (arXiv:1910.02054, Section 2)? Samyam Rajbhandari et al. ("ZeRO: Memory Optimizations Toward Training Trillion Parameter Models", SC20, arXiv:1910.02054) decompose training memory into two distinct categories: Model States (optimizer states, gradients, and parameters) and Residual States (intermediate forward activations, temporary fused communication buffers, and unusable fragmented memory).
1. The $16\Psi$ Mixed-Precision Model-State Equation
In standard mixed-precision training (Micikevicius et al., 2017) with the Adam optimizer (Kingma & Ba, 2015) on a model with $\Psi$ trainable parameters (arXiv:1910.02054, Section 2.1):
- 16-Bit Parameters ($p_{16}$) and Gradients ($g_{16}$): Forward and backward propagation execute on Tensor Cores using
FP16(orBF16) weights and activations, requiring $2\Psi\text{ bytes}$ to store the parameters and $2\Psi\text{ bytes}$ to accumulate the parameter gradients. - 32-Bit Optimizer States ($K\Psi$ with $K = 12$): Because small gradient updates underflow in 16-bit floating point, the mixed-precision Adam optimizer maintains three
FP32($4\text{ bytes/element}$) tensors: a master copy of the weights ($4\Psi\text{ bytes}$), the time-averaged first-moment momentum $m_t$ ($4\Psi\text{ bytes}$), and the time-averaged second-moment variance $v_t$ ($4\Psi\text{ bytes}$). Denoting the optimizer-state memory multiplier by $K$ bytes per parameter ($K = 12$ for mixed-precision Adam), total model-state memory per device in standard Data Parallelism (DP) is:
$$M_{\text{DP}} = \underbrace{2\Psi}{\text{FP16 Params}} + \underbrace{2\Psi}{\text{FP16 Grads}} + \underbrace{K\Psi}_{\text{FP32 Master + } m_t + v_t} = 4\Psi + 12\Psi = 16\Psi \text{ bytes}$$
For GPT-2 1.5B ($\Psi = 1.5 \times 10^9$), $M_{\text{DP}} = 16 \times 1.5\text{GB} = 24\text{GB}$ of model states alone—$8\times$ larger than the $3\text{GB}$ needed for its FP16 parameters. On top of model states, residual states consume substantial HBM (arXiv:1910.02054, Section 2.2):
- Activations: Without activation checkpointing, a
GPT-2 1.5Bmodel ($\text{seq\_len} = 1024, \text{batch\_size} = 32$) requires $\approx 12 \times \text{hidden\_dim} \times \text{batch} \times \text{seq\_length} \times \text{layers} \approx \mathbf{60\text{GB}}$ of activation memory (reduced to $\approx \mathbf{8\text{GB}}$ with layer-boundary activation checkpointing at a $+33\%$ recomputation FLOP overhead, though a100Bmodel still requires $\approx \mathbf{60\text{GB}}$ even with activation checkpointing). - Temporary Fused Buffers & Memory Fragmentation: Flattening all gradients into a single contiguous
FP32buffer for high-bandwidthAllReduceor global $L_2$ norm clipping allocates $4\Psi\text{ bytes}$ ($6\text{GB}$ for a1.5Bmodel, $12\text{GB}$ for a3Bmodel). Furthermore, interleaving long-lived tensors (activation checkpoints and parameter gradients) with short-lived recomputed activations fragments the GPU heap, causingOOMerrors even when $>30\%$ of total GPU memory remains free (arXiv:1910.02054, Section 2.2).
2. Three Cumulative Partitioning Stages of ZeRO-DP ($P_{\text{os}}, P_{\text{g}}, P_{\text{p}}$)
In standard Data Parallelism across $N_d$ GPU processes, every rank stores an identical copy of all $16\Psi\text{ bytes}$ of model states. ZeRO-DP eliminates this redundancy by sharding model states across the $N_d$ data-parallel processes in three cumulative phases (arXiv:1910.02054, Section 4):
- Stage 1 — Optimizer State Partitioning ($P_{\text{os}}$,
ZeRO-1): Divides the $K\Psi = 12\Psi\text{ bytes}$ ofFP32master weights, momentum, and variance into $N_d$ equal partitions so rank $i$ stores and updates only $\frac{1}{N_d}$ of the optimizer states. At the end of each step, anAll-Gatheracross the $N_d$ DP ranks broadcasts the updatedFP16parameter slices. Per-device model-state memory drops to:
$$M_{\text{ZeRO-1}} = 4\Psi + \frac{K\Psi}{N_d} = 4\Psi + \frac{12\Psi}{N_d} \xrightarrow{N_d \to \infty} 4\Psi \quad (\mathbf{4\times \text{ reduction}})$$
- Stage 2 — Gradient Partitioning ($P_{\text{os+g}}$,
ZeRO-2): Because rank $i$ only updates parameter partition $i$, it only requires the averaged gradients for partition $i$. As gradients for each layer are produced during backpropagation, ZeRO bucketizes and reduces them strictly onto the owning rank via aReduce-Scattercollective, immediately freeing the gradient buffers for all non-owned partitions. Per-device model-state memory drops to:
$$M_{\text{ZeRO-2}} = 2\Psi + \frac{(2 + K)\Psi}{N_d} = 2\Psi + \frac{14\Psi}{N_d} \xrightarrow{N_d \to \infty} 2\Psi \quad (\mathbf{8\times \text{ reduction}})$$
- Stage 3 — Parameter Partitioning ($P_{\text{os+g+p}}$,
ZeRO-3): Each rank permanently stores only its $\frac{1}{N_d}$ partition of theFP16parameters ($2\Psi / N_d$). During the forward pass (and in reverse order during the backward pass), the owning rank broadcasts (All-Gathers) the active layer's parameters just-in-time before the layer's matrix multiplication and immediately discards the unowned weights once the layer computation finishes. Per-device model-state memory scales inversely with cluster size $N_d$:
$$M_{\text{ZeRO-3}} = \frac{(4 + K)\Psi}{N_d} = \frac{16\Psi}{N_d} \quad (\mathbf{N_d\times \text{ linear reduction}})$$
DP Degree ($N_d$, arXiv:1910.02054, Table 1) |
7.5B Model: $P_{\text{os}}$ / $P_{\text{os+g}}$ / $P_{\text{os+g+p}}$ | 128B Model: $P_{\text{os}}$ / $P_{\text{os+g}}$ / $P_{\text{os+g+p}}$ | 1T Model: $P_{\text{os}}$ / $P_{\text{os+g}}$ / $P_{\text{os+g+p}}$ | Fits in 32GB V100 HBM2? |
|---|---|---|---|---|
N_d = 1 (Baseline DP) |
120 GB / 120 GB / 120 GB |
2,048 GB / 2,048 GB / 2,048 GB |
16,000 GB / 16,000 GB / 16,000 GB |
No (<1.5B max in baseline DP) |
N_d = 4 |
52.5 GB / 41.3 GB / 30 GB |
896 GB / 704 GB / 512 GB |
7,000 GB / 5,500 GB / 4,000 GB |
7.5B fits at $P_{\text{os+g+p}}$ (30 GB) |
N_d = 16 |
35.6 GB / 21.6 GB / 7.5 GB |
608 GB / 368 GB / 128 GB |
4,750 GB / 2,875 GB / 1,000 GB |
7.5B fits at $P_{\text{os+g}}$ (21.6 GB) |
N_d = 64 |
31.4 GB / 16.6 GB / 1.88 GB |
536 GB / 284 GB / 32 GB |
4,187 GB / 2,218 GB / 250 GB |
7.5B fits at $P_{\text{os}}$; 128B fits at $P_{\text{os+g+p}}$ |
N_d = 256 |
30.4 GB / 15.4 GB / 0.47 GB |
518 GB / 263 GB / 8 GB |
4,046 GB / 2,054 GB / 62.5 GB |
128B uses only 8 GB at $P_{\text{os+g+p}}$ |
N_d = 1024 |
30.1 GB / 15.1 GB / 0.12 GB |
513 GB / 257 GB / 2 GB |
4,011 GB / 2,013 GB / 15.6 GB |
1 Trillion Model fits in 15.6 GB! |
3. Exact Communication Volume Proof ($2\Psi$ for ZeRO-1/2 vs. $3\Psi$ for ZeRO-3) and ZeRO-R
Does sharding model states across $N_d$ GPUs trigger a prohibitive communication explosion? In Section 6 of arXiv:1910.02054, Rajbhandari et al. prove why ZeRO-1 and ZeRO-2 incur zero additional communication volume over baseline Data Parallelism, and ZeRO-3 incurs at most a $1.5\times$ multiplier:
- Baseline DP Communication Volume ($2\Psi$): Standard DP averages $\Psi$-element gradients via a bandwidth-optimal pipelined
All-Reduce, which executes as a two-step sequence: aReduce-Scatter($\Psi$ elements transferred per rank) followed by anAll-Gather($\Psi$ elements transferred per rank), totaling $\Psi + \Psi = 2\Psi$ elements moved per training step. ZeRO-1andZeRO-2($P_{\text{os+g}}$) Communication Volume ($2\Psi = 1.0\times$ Baseline): Instead of running a fullAll-Reduceon gradients,ZeRO-2runs only a singleReduce-Scatteron the gradients during backpropagation ($\Psi$ elements transferred), so each rank receives the reduced gradients strictly for its $\frac{1}{N_d}$ parameter partition. After each rank updates its local parameter partition in place, a singleAll-Gather($\Psi$ elements transferred) synchronizes the updatedFP16weights across all ranks. Total data movement per step is $\Psi + \Psi = 2\Psi$, identical to baseline DP.ZeRO-3($P_{\text{os+g+p}}$) Communication Volume ($3\Psi = 1.5\times$ Baseline): Because weights are discarded immediately after each layer's computation,ZeRO-3performs one pipelined parameterAll-Gatheracross the forward pass ($\frac{\Psi \times N_d}{N_d} = \Psi$ elements), one pipelined parameterAll-Gatherin reverse order across the backward pass ($\Psi$ elements), and one gradientReduce-Scatter($\Psi$ elements). Total communication volume is $\Psi + \Psi + \Psi = 3\Psi$ ($1.5\times$ baseline DP).ZeRO-R($P_a$, $P_{a+\text{cpu}}$, $C_B$, $M_D$): When combining ZeRO-DP with Tensor Model Parallelism (MP), standard Megatron-LM replicates the checkpointed layer-boundary input activations across all $t$ MP GPUs.ZeRO-R($P_a$) partitions those activation checkpoints across the MP ranks and rematerializes them via anAll-Gatherprior to backward recomputation—incurring $<10\%$ of Megatron-LM's per-block MP communication volume ($1\times \text{seq\len}\cdot\text{hidden\_dim}$ vs. $12\times \text{seq\_len}\cdot\text{hidden\_dim}$, Section 6.3) while shrinking activation checkpoints on a100Bmodel ($\text{batch} = 32, \text{seq\_len} = 1024, \text{MP} = 16$) by $16\times$, from $33\text{GB}$ down to $2\text{GB}$ per GPU (and to $\approx 0\text{GB}$ when offloaded to host RAM via $P{a+\text{cpu}}$). Combined with constant-size fused buffers ($C_B$) and on-the-fly pre-allocated contiguous memory defragmentation ($M_D$),ZeRO-100Btrains models up to13Bparameters using Data Parallelism alone at $>40\text{ TFLOPs/GPU}$ on $128$ V100 GPUs (vs. baseline DP's1.4Bmax at $<20\text{ TFLOPs/GPU}$), scales to170Bparameters across $400$ V100 GPUs ($25$ DGX-2 nodes with $800\text{ Gbps}$ InfiniBand), and exhibits super-linear scalability on60Bmodels from $64$ to $400$ GPUs because shrinking per-GPU model-state memory unlocks larger microbatch sizes and higher GEMM arithmetic intensity (arXiv:1910.02054, Section 7.3).
2. ZeRO-Offload: Unique Optimal CPU-GPU Dataflow Graph Partitioning & Delayed Parameter Updates (arXiv:2101.06840)
While ZeRO-DP eliminates redundancy across large multi-GPU clusters, how can researchers train $10\text{B}\text{--}70\text{B}$ models on a single GPU or a single server node? In "ZeRO-Offload: Democratizing Billion-Scale Model Training" (USENIX ATC 2021, arXiv:2101.06840), Jie Ren et al. formulate mixed-precision Adam training on a model with $M$ parameters as a weighted directed dataflow graph and prove from first principles that there exists a unique optimal two-way graph partition between GPU HBM and host CPU DDR4 memory.
1. First-Principles Dataflow Graph Proof ($4M$ Minimum PCIe Volume)
In Section 4 of arXiv:2101.06840, the training iteration is represented as a directed cyclic graph connecting five data nodes (parameter16, gradient16, parameter32, momentum32, variance32) and three compute nodes (forward, backward, param update), where edge weights equal $2M\text{ bytes}$ for FP16 tensor flows and $4M\text{ bytes}$ for FP32 tensor flows:
- Constraint 1 — Limiting CPU Compute Complexity to $O(M)$: Because host CPU FLOP throughput is orders of magnitude lower than GPU Tensor Core throughput, any operator with $O(MB)$ compute complexity (where $B$ is batch token count, typically thousands) must remain on the GPU. Therefore,
forwardandbackwardare fused into a singleFWD-BWD Supernode pinned strictly to the GPU, leaving only $O(M)$ elementwise norms and parameter updates eligible for CPU offloading (Section 4.2). - Constraint 2 — Minimizing CPU-GPU PCIe Volume to $4M\text{ Bytes}$: Because the reduced dataflow graph forms a directed cycle where every edge has weight $\ge 2M$, any two-way cut between GPU and CPU must sever at least two edges, yielding a theoretical minimum PCIe communication volume of $2M + 2M = 4M\text{ bytes}$ per step (
Section 4.3). * If theFP32model states (p32,momentum32,variance32) are separated from theirParam Updateorfloat2halfcast operators, the cut must cross at least one $4M$ edge and one $2M$ edge ($\ge 6M\text{ bytes}$). Thus, allFP32states and updates must be co-located inside anUpdate Supernode. * Similarly, the edge betweenp16andFWD-BWD Superhas weight $4M$ ($2M$ read during forward + $2M$ read during backward); separating them would require $4M + 2M = 6M\text{ bytes}$ of communication. SinceFWD-BWD Superis on the GPU,p16must remain permanently on the GPU. - Constraint 3 — Maximizing GPU Memory Reduction ($16M \to 2M$, $8\times$ Savings): With
FWD-BWD Superandp16pinned to the GPU, onlyg16andUpdate Superremain to be assigned (Table 1ofarXiv:2101.06840). Placing bothg16andUpdate Superon the CPU retains the theoretical minimum $4M$ PCIe communication volume ($2M\text{ bytes}$ to streamg16from GPU to CPU during backpropagation + $2M\text{ bytes}$ to stream updatedp16from CPU to GPU) while cutting GPU model-state memory from $16M$ down to $2M$ ($8\times$ reduction)—compared to $28M\text{ bytes}$ of synchronous PCIe transfers required by Layer-to-Layer (L2L) offloading (7× less PCIe traffic, Section 6.2.2).
Partitioning & CPU-Adam Benchmark (arXiv:2101.06840, Tables 1 & 4) |
Node Placement (FWD-BWD / p16 / g16 / Update) |
GPU Model-State Memory & Reduction | CPU-Adam Step Latency (1B / 2B / 4B / 8B / 10B) |
PyTorch CPU Adam Latency & Speedup |
|---|---|---|---|---|
| Baseline On-GPU Training | GPU / GPU / GPU / GPU |
16M (1.0× baseline) |
PT-GPU (L2L): 0.10s / 0.26s / 0.64s / 0.87s / 1.00s |
1.4B max model on 1× 32GB V100 |
| Gradient-Only Offload | GPU / GPU / CPU / GPU |
14M (1.14× reduction) |
Executes update on GPU | Sub-optimal memory savings |
| Optimizer-Only Offload | GPU / GPU / GPU / CPU |
4M (4.0× reduction) |
Executes update on CPU | Retains $2M$ g16 on GPU |
| ZeRO-Offload Unique Optimal | GPU / GPU / CPU / CPU |
2M steady / 4M peak (8.0× reduction) |
CPU-Adam: 0.22s / 0.51s / 1.03s / 2.41s / 2.57s | PT-CPU: 1.39s–14.76s (5.0×–6.4× speedup; 13B on 1 GPU / 70B on 16 GPUs) |
2. AVX-512 Vectorized CPU-Adam and One-Step Delayed Parameter Update (DPU)
To prevent the host CPU from bottlenecking GPU execution when updating $10\text{B}+$ parameters (arXiv:2101.06840, Section 5.2 & Section 6.2.4):
- Three-Level Parallel
CPU-Adam(Algorithm 1&Table 4): Standard PyTorch CPU Adam (PT-CPU) requires $1.39\text{ s}$ for1Bparameters and $14.76\text{ s}$ for10Bparameters.ZeRO-Offloadimplements a custom C++ optimizer combining AVX-512 SIMD vector FMA instructions, 8-way loop unrolling (unroll_width = 8), OpenMP multi-threading, and tiled asynchronous PCIe pinned-memory copies (copying tile $k-1$'s updatedp16weights to the GPU while computing tile $k$'s Adam update on the CPU). This reducesCPU-Adamlatency to $0.22\text{ s}$ (1B, $6.38\times$ speedup), $0.51\text{ s}$ (2B, $5.38\times$), $1.03\text{ s}$ (4B, $5.55\times$), $2.41\text{ s}$ (8B, $4.96\times$), and $2.57\text{ s}$ (10B, $5.75\times$)—within $\approx 2.5\times$ of on-GPU PyTorch Adam (1.00sat10B). - One-Step Delayed Parameter Update (
DPU): For small microbatch sizes where backward computation is shorter thanCPU-Adamexecution,DPUoverlaps step $t$'s CPU optimizer update and CPU-to-GPUp16transfer with step $t+1$'s GPU forward/backward pass (activated after $40$ warmup iterations).DPUboosts training throughput by $1.12\times\text{ to }1.59\times$ at microbatch size $8$ while matching unmodifiedGPT-2pre-training loss curves over $100\text{K}$ iterations and reaching the exact same92.8SQuAD F1 score onBERT-Largefine-tuning (arXiv:2101.06840, Section 6.2.4).
3. PyTorch Fully Sharded Data Parallel (FSDP): FlatParameter Coalescing, Stream Prefetching & Rate Limiting (arXiv:2304.11277)
While DeepSpeed ZeRO-3 operates as an external runtime engine wrapping PyTorch models, PyTorch Fully Sharded Data Parallel (FSDP) (Zhao et al., Meta, VLDB 2023, arXiv:2304.11277) integrates full and hybrid parameter sharding directly into PyTorch's native nn.Module, c10d ProcessGroupNCCL, and Autograd execution graph.
1. FlatParameter Coalescing and the $33\text{M}$-Element NCCL Bandwidth Threshold
In Section 3.3.1 of arXiv:2304.11277, Yanli Zhao et al. benchmark NCCL AllGather collective efficiency across varying tensor sizes and alignments (Figure 1):
- Even Tensor Alignment (
All-Gather Basevs.All-Gather):NCCL's nativeAllGatherrequires strictly equal tensor sizes across all ranks and writes into a single contiguous destination buffer (All-Gather Base). When tensor sizes are uneven across ranks (even by $1$ or $10^6$ elements), PyTorchProcessGroupfalls back to extra tensor copies or groupedBroadcastcalls, severely degrading throughput. - Minimum Collective Payload (
33MFP32 Elements): Holding total communication fixed at $2^{30} \approx 1\text{B}$FP32elements (Figure 1b) and varying the payload size perAllGathercall reveals that once individualAllGatherpayloads drop below $33\text{M}$ elements, kernel launch overhead and network under-utilization cause total communication time to spike sharply.
To guarantee both even alignment and large collective payloads, FSDP flattens and concatenates all $p$ parameters inside an wrapped FSDP submodule unit into a single 1D FlatParameter tensor, right-padded by at most $F - 1$ elements so its length is strictly divisible by the sharding factor $F$, and partitions it into $F$ equal contiguous chunks (arXiv:2304.11277, Section 3.3.1). For a model with $\Psi = \sum_{i=1}^N \psi_i$ elements grouped into $N$ FlatParameter units, peak parameter memory per device is governed by the local shards plus the largest single unsharded unit materialized at any instant:
$$M_{\text{FSDP-param}} = \mathcal{O}\left(\sum_{i=1}^N \frac{\psi_i}{F} + \max_{i=1}^N \psi_i\right) = \mathcal{O}\left(\frac{\Psi}{F} + \max_{i=1}^N \psi_i\right)$$
Before each unit's forward or backward pass, FSDP sets the original submodule parameters as zero-copy autograd-visible torch.split() and torch.view() views into the unsharded FlatParameter, and attaches gradient reduction hooks directly to the FlatParameter's AccumulateGrad autograd node (Section 4.4).
2. Hybrid Sharding (HYBRID_SHARD), Backward Prefetching (+18%), and the Caching Allocator Rate Limiter (5×)
To maximize hardware utilization across hierarchical datacenter networks (arXiv:2304.11277, Sections 3.3.2, 3.4 & 3.5):
- Hybrid Sharding (
1 < F < W): In a cluster of $W$ total GPUs organized into hosts of $G$ GPUs each (e.g., $G = 8$ GPUs connected via intra-node NVLink), setting sharding factor $F = G$ shards parameters (AllGather/ReduceScatter) strictly within the same host while replicating across hosts and running an inter-hostAllReduceon the sharded gradients: $\sum_{r=1}^W g_r = \sum_{i=1}^{W/F} \sum_{r \in S_i} g_r$. For a model of size $M$,HYBRID_SHARDreduces cross-host network traffic per GPU from $3M\frac{W-1}{W}$ (Full Sharding) and $2M\frac{W-1}{W}$ (DDP Full Replication) down to $2M\frac{W-1}{GW}$—an $8\times$ cross-host traffic reduction on 8-GPU servers over DDP and $12\times$ over Full Sharding (Section 3.3.2). - Producer-Stream Overlap & Backward Prefetching (
+18%TFLOPS): BecauseProcessGroupNCCLsynchronizes its internal NCCL stream with the current stream upon invocation, issuingAllGatheron the default compute stream would serialize communication behind the preceding layer's GEMM.FSDPissuesAllGathers from a dedicated separate CUDA producer stream and implements Backward Prefetching: because a single NCCL stream executes collectives FIFO, issuingReduceScatter(unit_k)beforeAllGather(unit_{k-1})in the backward pass would blockAllGather(unit_{k-1})—and thus stallunit_{k-1}'s backward GEMMs—behindReduceScatter(unit_k). By recording the reverse forward execution order dynamically each step,FSDPprefetchesAllGather(unit_{k-1})ahead ofReduceScatter(unit_k), yielding a sustained $+18\%$ TFLOPS speedup onGPT-175Bacross cluster sizes (Section 3.4.2&Section 5.1). - CUDA Caching Allocator Rate Limiter (
Up to 5×Speedup onT5-11B): PyTorch's CUDA caching allocator assigns memory blocks per-stream on the CPU thread before GPU kernels execute. When the fast CPU thread runs far ahead of GPU compute streams, it allocates new producer-stream buffers for futureAllGathers before consumer-stream compute kernels finish releasing earlier buffers—exhausting all $80\text{GB}$ ofA100HBM and triggering blockingcudaFree/cudaMallocretry defragmentation stalls (num_alloc_retriesintorch.cuda.memory_stats()). For example, onGPT-175Bat $128$ GPUs (batch_size = 2), memory defragmentation inflates the backward pass from $67\%$ to $85.56\%$ of total iteration latency (Section 5.3).FSDP's Rate Limiter blocks the CPU thread whenever $2$ in-flightAllGathers are active, guaranteeing immediate block reuse and delivering up to a $5\times$ training speedup onT5-11B(Section 3.5.2&Section 5.2), enablingGPT-175Bto scale linearly from $128$ to $512$A100-80GBGPUs at $173\text{ TFLOPS/GPU}$ (batch = 1, $55\%$ peak) and $186\text{ TFLOPS/GPU}$ (batch = 2, $60\%$ peak).
4. Megatron-LM Intra-Layer Tensor Parallelism (arXiv:1909.08053) and Composed 3D PTD-P Parallelism (arXiv:2104.04473)
When a single Transformer layer or model shard exceeds single-GPU memory—or when data-parallel batch sizes ($B = 1536$ for GPT-3 175B) cap the number of data-parallel ranks well below the $3,000\text{--}10,000$ GPUs needed for practical wall-clock training times (arXiv:2104.04473, Section 1 & Section 5.4.3)—we must partition the model itself across two orthogonal dimensions: Intra-Layer Tensor Parallelism (TP) and Inter-Layer Pipeline Parallelism (PP).
1. Column-Parallel and Row-Parallel Matrix Multiplication in Megatron-LM (arXiv:1909.08053)
In "Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism" (arXiv:1909.08053, Section 3), Mohammad Shoeybi et al. observe that a standard Transformer MLP block executes two consecutive GEMMs separated by a nonlinear GeLU activation:
$$Y = \text{GeLU}(X A), \qquad Z = \text{Dropout}(Y B)$$
If weight matrix $A$ were split along its rows ($A = [A_1^\top, A_2^\top]^\top$) and input $X$ along its columns ($X = [X_1, X_2]$), computing $Y = \text{GeLU}(X_1 A_1 + X_2 A_2)$ would require an expensive All-Reduce synchronization before the nonlinear GeLU because $\text{GeLU}(X_1 A_1 + X_2 A_2) \neq \text{GeLU}(X_1 A_1) + \text{GeLU}(X_2 A_2)$. Instead, Megatron-LM eliminates intermediate synchronization via paired Column-Parallel and Row-Parallel partitioning across $t$ tensor-parallel GPUs:
- First GEMM (Column-Parallel): Split $A \in \mathbb{R}^{h \times 4h}$ column-wise into $t$ blocks $A = [A_1, A_2, \dots, A_t]$ where $A_i \in \mathbb{R}^{h \times (4h/t)}$. Because each GPU receives the full replicated input $X$ via conjugate operator $f$ (which is an identity no-op in the forward pass and an
All-Reducein the backward pass), each rank independently applies GeLU to its local column slice with zero communication:
$$[Y_1, Y_2, \dots, Y_t] = [\text{GeLU}(X A_1), \text{GeLU}(X A_2), \dots, \text{GeLU}(X A_t)]$$
- Second GEMM (Row-Parallel): Split $B \in \mathbb{R}^{4h \times h}$ row-wise into $t$ blocks $B = [B_1^\top, B_2^\top, \dots, B_t^\top]^\top$ where $B_i \in \mathbb{R}^{(4h/t) \times h}$. Each rank multiplies its local activation slice $Y_i$ by $B_i$ ($W_i = Y_i B_i \in \mathbb{R}^{s \times b \times h}$), and the partial sums are aggregated across the $t$ GPUs via conjugate operator $g$ (
All-Reducein the forward pass and identity no-op in the backward pass) prior toDropoutand residual addition. - Multi-Head Self-Attention & Fused Parallel Cross-Entropy: Analogously, in Self-Attention, the Query ($W_Q$), Key ($W_K$), and Value ($W_V$) projection matrices are partitioned column-wise across the $t$ GPUs so each GPU computes $\frac{a}{t}$ attention heads completely locally without communication, and the output linear projection ($W_O$) is partitioned row-wise, followed by a single forward
All-Reduce($g$). Consequently, an entire Transformer layer requires only $2$All-Reduceoperations in the forward pass and $2$All-Reduceoperations in the backward pass ($4$ total collectives per layer, transferring $8bsh\left(\frac{t-1}{t}\right)$ bytes per device per microbatch,arXiv:2104.04473, Section 3.2). Furthermore, parallelizing the input/output word embedding $E_{h \times V}$ along the vocabulary dimension (padded V = 51,200) and fusing the parallel output GEMM $[X E_1, X E_2]$ directly with cross-entropy loss communicates only $b \times s$ scalar losses rather than $b \times s \times V$ full vocabulary logits (arXiv:1909.08053, Section 3).
On $512$ Tesla V100 SXM3 32GB GPUs ($32$ DGX-2H nodes), Megatron-LM trains GPT-2 8.3B ($72$ layers, $h = 3072$, $32$ heads, $8$-way TP $\times$ $64$-way DP) at $15.1\text{ PetaFLOPs}$ ($77\%$ pure-MP scaling and $74\%\text{--}76\%$ MP+DP scaling vs. a $39\text{ TFLOPs/GPU}$ single-GPU 1.2B baseline), achieving 10.81 zero-shot WikiText103 perplexity (vs. prior SOTA 15.79) and 66.51% LAMBADA cloze accuracy (vs. prior SOTA 63.24%), while Megatron-BERT 3.9B achieves 91.4 / 91.4 MNLI, 95.5 / 90.0 SQuAD 1.1, 91.2 / 88.5 SQuAD 2.0, and 89.5% single-model / 90.9% ensemble RACE test accuracy (arXiv:1909.08053, Tables 3 & 5).
2. Composing 3D PTD-P Parallelism, Interleaved 1F1B, and Cross-Node Scatter/Gather (arXiv:2104.04473)
In "Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM" (SC21, arXiv:2104.04473), Deepak Narayanan et al. formalize the interactions among Pipeline Parallelism ($p$), Tensor Parallelism ($t$), and Data Parallelism ($d$) across $n = p \cdot t \cdot d$ total GPUs for global batch size $B$, microbatch size $b$, and $m = \frac{B}{d \cdot b}$ microbatches per pipeline:
- GPipe vs. PipeDream-Flush (
1F1B) vs. Interleaved1F1BBubble Fraction: In synchronous pipeline parallelism across $p$ stages, GPipe executes all $m$ forward microbatches before all $m$ backward microbatches, incurring a pipeline flush bubble time $t_{pb} = (p - 1)(t_f + t_b)$ against ideal execution time $t_{id} = m(t_f + t_b)$, yielding a bubble time fraction of $\frac{t_{pb}}{t_{id}} = \frac{p - 1}{m}$ while stashing activations for all $m$ microbatches (Section 2.2.1). PipeDream-Flush (1F1B) alternates one forward and one backward microbatch after warmup, maintaining the exact same $\frac{p - 1}{m}$ bubble fraction while bounding peak in-flight stashed microbatches to $p$ instead of $m$. To shrink the bubble itself, Interleaved1F1B(Section 2.2.2) assigns each device $v$ non-contiguous model chunks (e.g., for $v=2$ across $4$ devices, device 1 holds layers $1,2$ and $9,10$), reducing per-chunk forward/backward duration to $t_f / v$ and $t_b / v$ and dividing the pipeline bubble fraction by $v$:
$$\text{Interleaved 1F1B Bubble Fraction} = \frac{t_{pb}^{\text{int}}}{t_{id}} = \frac{1}{v} \cdot \frac{p - 1}{m}$$
- Cross-Node Scatter/Gather Communication Optimization (
+11%Throughput): Because the output of each Transformer layer is replicated across all $t = 8$ tensor-parallel ranks inside a DGX A100 node, naive point-to-point pipeline sends would transmit the exact same $bsh$ activation tensor $8$ times across the node's $8$200Gbps HDR InfiniBandNICs. By scattering the tensor into $t = 8$ chunks before inter-node transmission so each InfiniBand HCA transmits only $\frac{bsh}{t}$ bytes, and running an intra-nodeAll-Gatherover high-speed NVLink on the receiving node (arXiv:2104.04473, Section 4.1), cross-node pipeline traffic drops by $8\times$ ($t\times$), boostingGPT-3 175Binterleaved pipeline throughput by up to $+11\%$ (Section 5.7) while kernel fusion ([s, b, a, h]layout + JITbias+GeLU+bias+dropout+add+ fusedscale+mask+softmax) adds+19%throughput on175B($113 \to 135\text{ TFLOP/s/GPU}$) and+11%on530B($133 \to 148\text{ TFLOP/s/GPU}$) (Section 5.8). - Trillion-Parameter Scaling &
PTD-Pvs. StandaloneZeRO-3: Using equation $P = 12lh^2\left(1 + \frac{13}{12h} + \frac{V+s}{12lh}\right)$ and iteration FLOPs $F = 96Bslh^2\left(1 + \frac{s}{6h} + \frac{V}{16lh}\right)$ (with full activation recomputation),PTD-Pscales from1Bparameters (44%peak) toGPT-3 175Bon $1,024$ A100 GPUs at $140\text{ TFLOP/s/GPU}$ ($34\text{ days}$ for $300\text{B}$ tokens) and1 Trillionparameters on $3,072$ A100 GPUs ($384$ DGX A100 nodes) at $163\text{ TFLOP/s/GPU}$ and $502\text{ PetaFLOP/s}$ aggregate ($52\%$ of A100 theoretical $312\text{ TFLOP/s}$ peak, $84\text{ days}$ for $450\text{B}$ tokens), sustaining $892\text{ GB/s}$ pipeline bisection bandwidth, $12.9\text{ TB/s}$ data-parallel AllReduce bisection bandwidth, and $1\text{ TB/s}$ parallel filesystem read bandwidth on its $13.8\text{ TB}$ checkpoint (Sections 5.1, 5.9 & 5.10). Compared directly against standaloneZeRO-3without model parallelism on175Band530Bmodels (Section 5.2),PTD-Pachieves $+6\%$ and $+24\%$ higher throughput at low GPU counts and $+70\%$ higher throughput when GPU count is doubled at fixed global batch size due to avoiding cross-node parameterAllGathertraffic on every layer.
5. Sequence Parallelism (SP) and Selective Activation Recomputation (arXiv:2205.05198)
Even when model states are partitioned across Tensor Parallelism ($t$) and Pipeline Parallelism ($p$), intermediate forward activations create a severe memory bottleneck (Korthikanti et al., NVIDIA, MLSys 2023, arXiv:2205.05198). Why? Because to keep a $p$-stage 1F1B pipeline saturated without idle bubbles, pipeline stage 0 must hold in-flight activations for $p$ microbatches simultaneously (Section 4.2.3). Since each stage holds $L / p$ Transformer layers, stage 0 must store activations for $p \times (L / p) = L$ full layers—meaning pipeline parallelism ($p$) does not reduce stage-0 peak activation memory at all! Furthermore, checkpointing at full Transformer layer boundaries (full activation recomputation) reduces activation memory to $2sbhL\text{ bytes}$ but adds an entire extra forward pass during backpropagation, inflicting a $30\%\text{--}40\%$ wall-clock execution time penalty (Section 1 & Table 3).
1. Exact Per-Layer Activation Memory Derivation ($34sbh + 5as^2b$)
In Section 4.1 of arXiv:2205.05198, Vijay Korthikanti et al. derive the exact byte count of forward activations stored for backpropagation in a single 16-bit (2 bytes/element, 1 byte/element for binary dropout masks) Transformer layer with sequence length $s$, microbatch size $b$, hidden dimension $h$, and $a$ attention heads:
- Self-Attention Block ($11sbh + 5as^2b\text{ bytes}$): Shared input to $Q, K, V$ projections ($2sbh$), $Q$ and $K$ matrices saved for $Q K^\top$ backward ($2sbh + 2sbh = 4sbh$), $\text{Softmax}$ output ($2as^2b$), softmax dropout mask ($1as^2b$), attention-over-$V$ inputs (dropout output $2as^2b$ + Values $2sbh$), post-attention linear projection input ($2sbh$), and attention dropout mask ($1sbh$). Sum: $(2 + 4 + 2 + 2 + 1)sbh + (2 + 1 + 2)as^2b = \mathbf{11sbh + 5as^2b}\text{ bytes}$.
- MLP Block ($19sbh\text{ bytes}$): First linear layer $h \to 4h$ input ($2sbh$), GeLU input ($8sbh$), second linear layer $4h \to h$ input ($8sbh$), and MLP dropout mask ($1sbh$). Sum: $2 + 8 + 8 + 1 = \mathbf{19sbh}\text{ bytes}$.
- Two LayerNorms ($4sbh\text{ bytes}$): Input to pre-attention
LayerNorm($2sbh$) and input to pre-MLPLayerNorm($2sbh$).
Summing all three components yields the baseline single-layer activation memory without parallelism (Equation 1):
$$M_{\text{act}}^{\text{no-parallel}} = (11 + 19 + 4)sbh + 5as^2b = sbh\left(34 + 5\frac{as}{h}\right) \text{ bytes}$$
When $t$-way Megatron-LM Tensor Parallelism (TP) is applied (Section 4.2.1, Equation 2), activations inside the attention and MLP GEMMs ($24sbh + 5as^2b$) are divided by $t$, but the $10sbh\text{ bytes}$ of activations in non-TP regions (the two LayerNorm inputs $4sbh$, the two Dropout masks $2sbh$, and the shared inputs to $QKV$ and the first MLP linear layer $4sbh$) remain replicated across all $t$ GPUs:
$$M_{\text{act}}^{\text{TP}} = sbh\left(10 + \frac{24}{t} + 5\frac{as}{ht}\right) \text{ bytes}$$
2. Sequence Parallelism (SP) via Conjugate $g / \bar{g}$ (AllGather + ReduceScatter) and Selective Activation Recomputation
To eliminate the unsharded $10sbh$ term without adding a single byte of communication overhead (arXiv:2205.05198, Section 4.2.2 & Section 5):
- Sequence Parallelism (
SP): BecauseLayerNorm, residual additions, andDropoutoperate independently across tokens along the sequence axis $s$,SPpartitions their activations by $s / t$ across the $t$ tensor-parallel ranks: $X = [X_1^s, X_2^s, \dots, X_t^s]$. Rather than inserting extra collectives around Megatron-LM'sAllReduceoperators ($f, \bar{f}$),SPreplaces them with conjugate converters $g$ (All-Gatherin forward,Reduce-Scatterin backward) and $\bar{g}$ (Reduce-Scatterin forward,All-Gatherin backward) (Equation 3). Because a ringAll-Reduceis mathematically composed of oneReduce-Scatterfollowed by oneAll-Gather, replacing $4$All-Reduces per layer (forward + backward) with $4$All-Gathers and $4$Reduce-Scatters uses the exact same communication volume ($0\%$ bandwidth overhead) while dividing the $10sbh$ term by $t$ (Equation 4):
$$M_{\text{act}}^{\text{TP+SP}} = sbh\left(\frac{10}{t} + \frac{24}{t} + 5\frac{as}{ht}\right) = \frac{sbh}{t}\left(34 + 5\frac{as}{h}\right) \text{ bytes}$$
- Selective Activation Recomputation (
Section 5,Table 2&Equation 6): Notice that in $\frac{sbh}{t}\left(34 + 5\frac{as}{h}\right)$, the term $5\frac{as}{h}$ arises purely from the attention score operations ($QK^\top$, $\text{Softmax}$, softmax dropout, and attention over $V$). For frontier architectures at $s = 2048$, this term dominates the constant $34$: onGPT-3 175B($a = 96, h = 12288$), $5as/h = \mathbf{80}$ vs. $34$ ($70\%$ of total activation memory); onMT-NLG 530B($a = 128, h = 20480$), $5as/h = \mathbf{64}$ vs. $34$ ($65\%$ of total activation memory)! Yet recomputing those attention-score operations requires only $4Bs^2h$ FLOPs out of $72BLsh^2(1 + \frac{s}{6h} + \frac{v}{12hL})$ total iteration FLOPs—a hardware-to-model FLOPs ratio of just $\approx 1 + \frac{s}{6h}$ (Equation 9), which equals $+2.7\%$ extra FLOPs onGPT-3 175Band $+1.6\%$ extra FLOPs onMT-NLG 530B! Discarding and selectively recomputing only the $5as/h$ attention sub-graph reduces total stage-0 activation memory across $L$ layers to:
$$M_{\text{act}}^{\text{TP+SP+Selective}} = 34 \frac{sbhL}{t} \text{ bytes}$$
Model Scale & Cluster Config (arXiv:2205.05198, Tables 3 & 4) |
Architecture ($a / h / L$, $t=8$) | Full Recompute Iteration Time (s) | SP + Selective Recompute Time (s) | Throughput Speedup | Achieved MFU / HFU (A100 312 TFLOP/s) |
|---|---|---|---|---|---|
GPT 22B (1-Layer Timing, Table 3) |
64 / 6144 / 1 ($p=1$, 8 GPUs) |
27.2 ms (+39% vs. 19.6ms no-recompute) |
20.3 ms (7.2ms Fwd + 13.1ms Bwd) |
Overhead cut from +39% to +4% |
SP alone: 19.0 ms (-3% faster than baseline) |
GPT 22B (End-to-End, Table 4) |
64 / 6144 / 48 ($p=1$, 8 GPUs) |
1.42 s |
1.10 s | +29.0% | 41.5% MFU / 43.7% HFU |
GPT-3 175B (End-to-End, Table 4) |
96 / 12288 / 96 ($p=8, m=3$, 64 GPUs) |
18.13 s |
13.75 s | +31.8% | 51.4% MFU / 52.8% HFU (52.3% w/ MB-level) |
MT-NLG 530B (End-to-End, Table 4) |
128 / 20480 / 105 ($p=35, m=3$, 280 GPUs) |
49.05 s (42.1% MFU on 2240 GPUs) |
37.83 s (39.15 s on 2240 GPUs, 8-way DP) |
+29.7% (+29% on 2240 GPUs) | 56.0% MFU / 57.0% HFU (54.2% MFU on 2240 GPUs) |
GPT 1 Trillion (End-to-End, Table 4) |
160 / 25600 / 128 ($p=64$, 512 GPUs) |
94.42 s |
71.49 s | +32.1% | 56.3% MFU / 57.0% HFU |
6. Zero-Bubble Pipeline Parallelism: Splitting Backward $B$ and $W$ Operators & ZB-V Scheduling (arXiv:2401.10241)
For decades, pipeline bubbles at the start and end of synchronous training batches were treated as an unavoidable mathematical consequence of sequential layer dependencies. In "Zero Bubble Pipeline Parallelism" (ICLR 2024, arXiv:2401.10241), Penghui Qi, Xinyi Wan, Guangxing Huang, and Min Lin (Sea AI Lab) prove that zero pipeline bubbles can be achieved under strict synchronous training semantics by decomposing backpropagation from layer granularity to operator granularity.

Sequential versus Data-Parallel and Pipelined Job Execution Timeline
1. Decoupling Input-Activation Gradient ($B$) from Parameter-Weight Gradient ($W$)
In any neural network layer $\mathbf{y} = f(\mathbf{x}, \mathbf{W})$, the backward pass consists of two distinct matrix multiplication operations (arXiv:2401.10241, Section 1 & Table 1):
- $B$ Pass (Input Gradient $\nabla_{\mathbf{x}} f(\mathbf{x}, \mathbf{W})^\top \frac{d\ell}{d\mathbf{y}}$): Computes the gradient with respect to the layer's input activations $\mathbf{x}$. In a Transformer layer, $B$ requires $sbh(24h + 8s)$ FLOPs and holds $M_B = sb(34h + 5as)\text{ bytes}$ of activations (
Table 1). Crucially, stage $i-1$ cannot begin its own backward pass $B_{i-1}$ until stage $i$ finishes $B_i$ and transmits $\nabla_{\mathbf{x}} \ell$. Thus, $B$ sits on the cross-stage critical path. - $W$ Pass (Weight Gradient $\nabla_{\mathbf{W}} f(\mathbf{x}, \mathbf{W})^\top \frac{d\ell}{d\mathbf{y}}$): Computes the gradient with respect to the layer's parameters $\mathbf{W}$. In a Transformer layer, $W$ requires $24sbh^2$ FLOPs (so $T_W < T_F < T_B$ and $T_B + T_W = 2T_F$) and holds only $M_W = 32sbh\text{ bytes} < M_B$ of intermediate gradients (
Table 1). Crucially, $W_i$ has zero cross-stage dependency: it only needs to complete beforeoptimizer.step()at the end of the batch!
Traditional frameworks fuse $B$ and $W$ into a single monolithic backward() function, forcing stage $i-1$ to wait idle while stage $i$ computes $W_i$. By splitting $B$ and $W$, stage $i$ executes $B_i$ immediately upon receiving $\frac{d\ell}{d\mathbf{y}}$ and forwards $\nabla_{\mathbf{x}}\ell$ to stage $i-1$ right away, deferring $W_i$ to fill any warmup, steady-state, or tail-end pipeline bubbles (Section 2).
2. Handcrafted (ZB-H1, ZB-H2), Automatically Searched (ZB-1p, ZB-2p), and V-Shaped (ZB-V) Schedules
As derived in Table 2 and Sections 2–5 of arXiv:2401.10241:
ZB-H1andZB-1p(Strict1F1BMemory Parity, Peak Memory $= p M_B$): Initiates $B$ passes earlier across all workers and shifts $W$ passes to fill the tail-end flush gaps while capping worker $i$'s activation memory at $(p - i + 1)M_B + (i - 1)M_W \le p M_B$. This slashes the theoretical pipeline bubble size from1F1B's $(p - 1)(T_F + T_B + T_W)$ down to $(p - 1)(T_F + T_B - T_W)$—one-third ($33.3\%$) of1F1B's bubble when $T_F = T_B = T_W$.ZB-H2andZB-2p(Zero-Bubble Parallelogram Schedule, Peak Memory $= (2p - 1)M_B \approx 2p M_B$): Schedules $2(p - i)$ warmup $F$ passes on worker $i$ to completely fill the gap before the first $B$ pass, and reorders tail $W$ passes to transform the schedule from a trapezoid into a dense parallelogram, reducing theoretical bubble size to $(p - 1)(T_F + T_B - 2T_W) = 0$ (Table 2). Using profiled $T_F, T_B, T_W, T_{\text{comm}}$ times in the heuristic + ILP automatic scheduler (Section 3),ZB-2preduces empirical pipeline bubble rates below $1\%$ (0.10%–0.66%across6.2B,14.6B, and28.3B, Table 5).- Post-Validation Optimizer Step Rollback (
Section 4): Standard pipeline training runs a blocking globalAllReduceacross all stages beforeoptimizer.step()to check forNaN/Infand compute the global gradient norm for clipping—which would destroy the parallelogram alignment ofZB-2p. Qi et al. replace pre-step synchronization with pipelined post-update validation: each stage propagates a partially reduced norm/NaN state forward ($1 \to p$) to step its local optimizer immediately and start the next iteration's warmup $F$ passes; during warmup, the fully reduced global state propagates backward ($p \to 1$), triggering an in-place reversible Adam rollback only on the rare steps where global clipping orNaNtriggers—producing bit-for-bit identical loss trajectories to synchronous1F1B(Section 5.1). ZB-V("V"-Shape 2-Chunk Schedule at1F1BMemory Parity $p M_B$,Section 6): To achieve zero bubbles without doubling activation memory to $2p M_B$,ZB-Vdivides the model into $2p$ chunks (2 chunks per device) and assigns them in a "V" pattern (e.g., on $p = 4$ stages with $16$ layers: worker 1 holds layers $1\text{--}2$ and $15\text{--}16$; worker 2 holds layers $3\text{--}4$ and $13\text{--}14$). Because both the forward pass (chunk 1) and the backward pass (chunk 2) originate on worker 1, worker 1 clears activation memory twice as fast, achieving zero theoretical bubble under $T_F = T_B = T_W$ within1F1B's exact $p M_B$ memory budget and balanced memory across all workers!
Model & Pipeline Config (arXiv:2401.10241, Tables 4, 5 & 6) |
1F1B Throughput / Memory / Bubble Rate |
1F1B-I (Interleaved) Throughput / Memory / Bubble |
ZB-1p Throughput / Memory / Bubble Rate |
ZB-2p Throughput / Memory / Bubble Rate |
ZB-V Equal-Memory Throughput (Table 6) |
|---|---|---|---|---|---|
GPT 1.5B ($p=8$, $m=24 / 64$) |
11.8 / 13.6 samp/s (30 GB, 24.31% / 12.40%) |
13.1 / 13.9 samp/s (40 GB, 10.55% / 4.43%) |
12.9 / 14.2 samp/s (32 GB, 15.85% / 6.74%) |
14.5 / 14.9 samp/s (59 GB, 4.33% / 0.26%) |
+22.9% faster (`ZB-2p` vs `1F1B` at $m=24$) |
GPT 6.2B ($p=8$, $m=24 / 64$) |
3.50 / 4.03 samp/s (39 GB, 23.47% / 10.91%) |
4.01 / 4.19 samp/s (48 GB, 8.08% / 3.20%) |
3.88 / 4.20 samp/s (42 GB, 13.23% / 5.54%) |
4.32 / 4.39 samp/s (70 GB, 0.29% / 0.10%) |
$p=16, m=48$: ZB-V 4.15 vs 1F1B 3.38 (+22.8% at 64GB) |
GPT 14.6B ($p=16$, $m=48 / 128$) |
1.40 / 1.64 samp/s (32 GB, 25.52% / 12.51%) |
1.54 / 1.66 samp/s (39 GB, 11.04% / 4.45%) |
1.61 / 1.76 samp/s (33 GB, 13.97% / 5.76%) |
1.81 / 1.85 samp/s (51 GB, 0.66% / 0.28%) |
$p=24, m=72$: ZB-V 1.85 vs 1F1B 1.52 (+21.7% at 45GB) |
GPT 28.3B ($p=32$, $m=96 / 256$) |
0.76 / 0.88 samp/s (43 GB, 26.46% / 13.52%) |
0.82 / 0.90 samp/s (58 GB, 14.93% / 6.24%) |
0.87 / 0.96 samp/s (44 GB, 14.21% / 5.94%) |
0.99 / 1.00 samp/s (74 GB, 0.38% / 0.18%, +30.3%) |
$p=32, m=96$: ZB-V 1.01 vs 1F1B 0.82 (+23.2% at 71GB) |
7. Production PyTorch Implementation: Megatron-LM Tensor + Sequence Parallelism, Zero-Bubble Split-$B$/$W$ Autograd & Memory Calculator
Below is a clean, self-contained PyTorch reference implementation demonstrating:
- Conjugate Tensor + Sequence Parallel Autograd Primitives (
gandg_barfromarXiv:2205.05198, Section 4.2.2) paired withColumnParallelLinearandRowParallelLinear(arXiv:1909.08053, Section 3). - Zero-Bubble Split-$B$/$W$ Linear Autograd Function (
arXiv:2401.10241, Section 1 & Section 2) that executes $\nabla_{\mathbf{x}}\ell = \frac{d\ell}{d\mathbf{y}} \mathbf{W}$ immediately during the $B$ pass while deferring $\nabla_{\mathbf{W}}\ell = \left(\frac{d\ell}{d\mathbf{y}}\right)^\top \mathbf{x}$ into a decoupled weight-gradient queue for execution during $W$ bubble slots. - Exact Analytical Cluster Memory & Pipeline Bubble Calculator implementing the closed-form equations from
arXiv:1910.02054,arXiv:2104.04473,arXiv:2205.05198, andarXiv:2401.10241.
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, List
import torch
import torch.nn as nn
import torch.distributed as dist
class _SequenceToTensorParallelG(torch.autograd.Function):
"""Conjugate operator g (arXiv:2205.05198, Eq. 3):
Forward: All-Gather along sequence dimension (s/t -> s).
Backward: Reduce-Scatter along sequence dimension (s -> s/t).
"""
@staticmethod
def forward(ctx, x_seq_sharded: torch.Tensor, tp_group: dist.ProcessGroup | None = None) -> torch.Tensor:
ctx.tp_group = tp_group
if not dist.is_initialized() or dist.get_world_size(tp_group) == 1:
return x_seq_sharded
world_size = dist.get_world_size(tp_group)
chunks = [torch.empty_like(x_seq_sharded) for _ in range(world_size)]
dist.all_gather(chunks, x_seq_sharded.contiguous(), group=tp_group)
return torch.cat(chunks, dim=0)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None]:
tp_group = ctx.tp_group
if not dist.is_initialized() or dist.get_world_size(tp_group) == 1:
return grad_output, None
world_size = dist.get_world_size(tp_group)
seq_chunk = grad_output.size(0) // world_size
grad_in = torch.empty(
(seq_chunk, *grad_output.shape[1:]),
dtype=grad_output.dtype,
device=grad_output.device,
)
input_list = list(grad_output.contiguous().chunk(world_size, dim=0))
dist.reduce_scatter(grad_in, input_list, op=dist.ReduceOp.SUM, group=tp_group)
return grad_in, None
class _TensorToSequenceParallelGBar(torch.autograd.Function):
"""Conjugate operator g_bar (arXiv:2205.05198, Eq. 3):
Forward: Reduce-Scatter along sequence dimension (s -> s/t).
Backward: All-Gather along sequence dimension (s/t -> s).
"""
@staticmethod
def forward(ctx, x_partial_sum: torch.Tensor, tp_group: dist.ProcessGroup | None = None) -> torch.Tensor:
ctx.tp_group = tp_group
if not dist.is_initialized() or dist.get_world_size(tp_group) == 1:
return x_partial_sum
world_size = dist.get_world_size(tp_group)
seq_chunk = x_partial_sum.size(0) // world_size
out_seq_sharded = torch.empty(
(seq_chunk, *x_partial_sum.shape[1:]),
dtype=x_partial_sum.dtype,
device=x_partial_sum.device,
)
input_list = list(x_partial_sum.contiguous().chunk(world_size, dim=0))
dist.reduce_scatter(out_seq_sharded, input_list, op=dist.ReduceOp.SUM, group=tp_group)
return out_seq_sharded
@staticmethod
def backward(ctx, grad_seq_sharded: torch.Tensor) -> tuple[torch.Tensor, None]:
tp_group = ctx.tp_group
if not dist.is_initialized() or dist.get_world_size(tp_group) == 1:
return grad_seq_sharded, None
world_size = dist.get_world_size(tp_group)
chunks = [torch.empty_like(grad_seq_sharded) for _ in range(world_size)]
dist.all_gather(chunks, grad_seq_sharded.contiguous(), group=tp_group)
return torch.cat(chunks, dim=0), None
class ZeroBubbleWeightGradQueue:
"""Deferred W-pass weight-gradient execution queue (arXiv:2401.10241, Section 2).
Decouples dL/dW computation from the pipeline-critical dL/dx B-pass.
"""
def __init__(self) -> None:
self._pending_w_tasks: List[Callable[[], None]] = []
def enqueue(self, task: Callable[[], None]) -> None:
self._pending_w_tasks.append(task)
def execute_one_w_slot(self) -> bool:
"""Execute a single deferred W pass during a pipeline bubble slot."""
if not self._pending_w_tasks:
return False
task = self._pending_w_tasks.pop(0)
task()
return True
def flush_all(self) -> int:
count = 0
while self._pending_w_tasks:
self.execute_one_w_slot()
count += 1
return count
class _ZeroBubbleSplitBWLinear(torch.autograd.Function):
"""Linear layer y = x W^T that executes ONLY B (dL/dx = dL/dy @ W) during
backward(), deferring W (dL/dW = (dL/dy)^T @ x) into ZeroBubbleWeightGradQueue.
"""
@staticmethod
def forward(
ctx,
x: torch.Tensor,
weight: torch.Tensor,
w_queue: ZeroBubbleWeightGradQueue,
) -> torch.Tensor:
ctx.save_for_backward(x, weight)
ctx.w_queue = w_queue
return torch.matmul(x, weight.t())
@staticmethod
def backward(ctx, grad_y: torch.Tensor) -> tuple[torch.Tensor, None, None]:
x, weight = ctx.saved_tensors
# 1. Pipeline-critical B pass: compute dL/dx immediately for stage i-1
grad_x = torch.matmul(grad_y, weight)
# 2. Pipeline-independent W pass: enqueue dL/dW for next bubble slot
x_flat = x.detach().reshape(-1, x.size(-1))
gy_flat = grad_y.detach().reshape(-1, grad_y.size(-1))
def _compute_w_grad() -> None:
dw = torch.matmul(gy_flat.t(), x_flat)
if weight.grad is None:
weight.grad = dw
else:
weight.grad.add_(dw)
ctx.w_queue.enqueue(_compute_w_grad)
return grad_x, None, None
@dataclass(frozen=True)
class DistributedClusterAnalysis:
"""Closed-form memory and bubble metrics from arXiv:1910.02054, 2104.04473 & 2205.05198."""
zero1_bytes: float
zero2_bytes: float
zero3_bytes: float
act_tp_only_bytes: float
act_tp_sp_selective_bytes: float
bubble_1f1b: float
bubble_interleaved_1f1b: float
def analyze_distributed_config(
params_count: float,
dp_degree: int,
tp_degree: int,
pp_degree: int,
num_microbatches: int,
interleaved_chunks: int,
seq_len: int,
microbatch_size: int,
hidden_dim: int,
num_heads: int,
num_layers: int,
) -> DistributedClusterAnalysis:
"""Compute exact per-GPU model-state memory, stage-0 activation memory, and pipeline bubble rates."""
# 1. ZeRO-1/2/3 Model States (arXiv:1910.02054, Section 4, K=12 for mixed-precision Adam)
zero1 = (4.0 * params_count) + (12.0 * params_count / dp_degree)
zero2 = (2.0 * params_count) + (14.0 * params_count / dp_degree)
zero3 = (16.0 * params_count) / dp_degree
# 2. Stage-0 Activation Memory across L layers (arXiv:2205.05198, Table 2 & Eq. 6)
sbh = float(seq_len * microbatch_size * hidden_dim)
attn_score_term = 5.0 * num_heads * seq_len / hidden_dim
act_tp_only = sbh * num_layers * (10.0 + (24.0 / tp_degree) + (attn_score_term / tp_degree))
act_tp_sp_selective = 34.0 * sbh * num_layers / tp_degree
# 3. Pipeline Bubble Fractions (arXiv:2104.04473, Section 2.2)
bubble_1f1b = (pp_degree - 1.0) / num_microbatches
bubble_interleaved = bubble_1f1b / interleaved_chunks
return DistributedClusterAnalysis(
zero1_bytes=zero1,
zero2_bytes=zero2,
zero3_bytes=zero3,
act_tp_only_bytes=act_tp_only,
act_tp_sp_selective_bytes=act_tp_sp_selective,
bubble_1f1b=bubble_1f1b,
bubble_interleaved_1f1b=bubble_interleaved,
)8. Frequently Asked Questions (FAQ)
Why does mixed-precision Adam training require $16\Psi\text{ bytes}$ of model-state memory when FP16 parameters occupy only $2\Psi\text{ bytes}$? In mixed-precision training (arXiv:1910.02054, Section 2.1), forward and backward matrix multiplications execute in FP16 (or BF16), requiring $2\Psi\text{ bytes}$ for the 16-bit parameters and $2\Psi\text{ bytes}$ for the 16-bit gradients. However, because small parameter updates ($\alpha \cdot \hat{m}_t / (\sqrt{\hat{v}_t} + \epsilon)$) underflow in 16-bit precision, the Adam optimizer must maintain three full-precision FP32 ($4\text{ bytes/element}$) state tensors: an FP32 master copy of the parameters ($4\Psi\text{ bytes}$), the FP32 first-moment momentum $m_t$ ($4\Psi\text{ bytes}$), and the FP32 second-moment variance $v_t$ ($4\Psi\text{ bytes}$), totaling $K\Psi = 12\Psi\text{ bytes}$ of optimizer states and $2\Psi + 2\Psi + 12\Psi = 16\Psi\text{ bytes}$ of total model states.
How do DeepSpeed ZeRO-1 and ZeRO-2 achieve $4\times$ and $8\times$ model-state memory reductions without increasing communication volume over standard Data Parallelism? Standard Data Parallelism (DP) averages $\Psi$-element gradients via a pipelined All-Reduce, which consists of a Reduce-Scatter ($\Psi$ elements transferred) followed by an All-Gather ($\Psi$ elements transferred), totaling $2\Psi$ elements of data movement per step (arXiv:1910.02054, Section 6.1). In ZeRO-2 ($P_{\text{os+g}}$), each of the $N_d$ ranks owns and updates only $\frac{1}{N_d}$ of the parameters and optimizer states. During backpropagation, ZeRO-2 replaces the full gradient All-Reduce with a single Reduce-Scatter ($\Psi$ elements transferred) and immediately frees non-owned gradients. After the local optimizer step updates each rank's $\frac{1}{N_d}$ parameter shard, a single All-Gather ($\Psi$ elements transferred) broadcasts the updated FP16 weights—achieving an $8\times$ memory reduction ($2\Psi + \frac{14\Psi}{N_d}$) at the exact same $\Psi + \Psi = 2\Psi$ communication volume.
Why must Megatron-LM Tensor Parallelism (TP) be restricted within a single multi-GPU node ($t \le 8$) while Pipeline Parallelism (PP) and Data Parallelism (DP) scale across nodes? As proved in arXiv:2104.04473 (Section 3.2, Takeaway #1), Tensor Parallelism executes $2$ All-Reduce collectives in the forward pass and $2$ All-Reduce collectives in the backward pass for every single Transformer layer and every microbatch, transferring $8bsh\left(\frac{t-1}{t}\right)$ bytes per layer per microbatch on the critical execution path. When $t \le 8$ inside an NVIDIA DGX A100 or DGX-2 node, these All-Reduce calls traverse NVLink / NVSwitch ($300\text{--}600\text{ GB/s}$); once $t$ spans across server nodes over InfiniBand ($12.5\text{--}25\text{ GB/s}$ per link), cross-node All-Reduce stalls dominate runtime and smaller sub-matrix GEMMs reduce Tensor Core occupancy. In contrast, Pipeline Parallelism sends only point-to-point activation tensors of size $\frac{bsh}{t}$ (with the scatter/gather optimization) at stage boundaries.
How does Sequence Parallelism (SP) combined with Selective Activation Recomputation reduce activation memory by $5\times$ while cutting recomputation overhead from $30\%\text{--}40\%$ down to $2\%\text{--}4\%$? In standard Tensor Parallelism (arXiv:2205.05198, Section 4.2), LayerNorm and Dropout activations ($10sbh\text{ bytes/layer}$) are replicated across all $t$ TP ranks. Sequence Parallelism splits these non-TP regions along the sequence dimension $s / t$ and replaces each All-Reduce with a mathematically equivalent All-Gather ($g$) and Reduce-Scatter ($\bar{g}$) pair at zero extra communication volume. Selective Activation Recomputation then exploits the fact that the attention score sub-graph ($QK^\top$, $\text{Softmax}$, dropout, and attention over $V$) consumes $5\frac{as^2b}{t}\text{ bytes/layer}$—accounting for $70\%$ of GPT-3 175B ($5as/h = 80$ vs. $34$) and $65\%$ of MT-NLG 530B ($5as/h = 64$ vs. $34$) activation memory—yet costs only $+2.7\%$ and $+1.6\%$ extra FLOPs to recompute. Combining both reduces per-layer stored activations to $34\frac{sbh}{t}\text{ bytes}$ ($5\times$ reduction) and boosts 530B training on $2,240$ A100 GPUs from $42.1\%$ to $54.2\%$ MFU ($+29\%$ speedup).
Why does PyTorch FSDP require a CPU-to-GPU caching allocator rate limiter (limit_all_gathers) and backward prefetching? In PyTorch FSDP (arXiv:2304.11277, Sections 3.4.2 & 3.5), all collectives share a single internal NCCL stream per process group. Without backward prefetching, ReduceScatter(layer_k) is queued before AllGather(layer_{k-1}), blocking layer_{k-1}'s backward GEMM behind gradient reduction; prefetching AllGather(layer_{k-1}) ahead of ReduceScatter(layer_k) yields an $18\%$ TFLOPS speedup on GPT-175B. Furthermore, because PyTorch's CUDA caching allocator assigns memory blocks per-stream on the CPU thread, an unthrottled CPU thread queues AllGather allocations in the producer stream faster than the default compute stream frees them, exhausting all $80\text{GB}$ of A100 HBM and triggering blocking cudaFree/cudaMalloc retry defragmentation stalls. Limiting in-flight AllGathers to $2$ eliminates cudaMalloc retries and delivers up to a $5\times$ speedup on T5-11B.
How does Zero-Bubble Pipeline Parallelism (ZB-1p, ZB-2p, ZB-V) eliminate synchronous pipeline bubbles without relaxing weight update semantics? In arXiv:2401.10241 (Sections 1, 2, 4 & 6), Qi et al. decompose each layer's backward pass into $B$ (input-activation gradient $\nabla_{\mathbf{x}}\ell$), which stage $i-1$ depends on immediately, and $W$ (parameter-weight gradient $\nabla_{\mathbf{W}}\ell$), which has no cross-stage dependency and is scheduled to fill warmup and cooldown pipeline bubbles. By replacing pre-step global AllReduce optimizer barriers (for gradient norm clipping and NaN checks) with pipelined post-update validation and reversible in-place Adam rollback (Section 4), ZB-2p reduces pipeline bubble rates to $0.10\%\text{--}0.66\%$ (up to $+31\%$ throughput over 1F1B), while the 2-chunk "V"-shaped ZB-V schedule originates both forward and backward passes on worker 1 to achieve up to $+23\%$ higher throughput under the exact same $p M_B$ peak activation memory as 1F1B.
9. Primary Sources & Technical References
- Rajbhandari, S., Rasley, J., Ruwase, O., & He, Y. (2020). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models. Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC20). https://arxiv.org/abs/1910.02054
- Ren, J., Rajbhandari, S., Aminabadi, R. Y., Ruwase, O., Yang, S., Zhang, M., Li, D., & He, Y. (2021). ZeRO-Offload: Democratizing Billion-Scale Model Training. 2021 USENIX Annual Technical Conference (USENIX ATC 21). https://arxiv.org/abs/2101.06840
- Zhao, Y., Gu, A., Varma, R., Luo, L., Huang, C.-C., Xu, M., Wright, L., Shojanazeri, H., Ott, M., Shleifer, S., Desmaison, A., Balioglu, C., Damania, P., Nguyen, B., Chauhan, G., Hao, Y., Mathews, A., & Li, S. (2023). PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel. Proceedings of the VLDB Endowment, 16(12), 3848–3860. https://arxiv.org/abs/2304.11277
- Shoeybi, M., Patwary, M., Puri, R., LeGresley, P., Casper, J., & Catanzaro, B. (2019). Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism. arXiv Preprint. https://arxiv.org/abs/1909.08053
- Narayanan, D., Shoeybi, M., Casper, J., LeGresley, P., Patwary, M., Korthikanti, V. A., Vainbrand, D., Kashinkunti, P., Bernauer, J., Catanzaro, B., Phanishayee, A., & Zaharia, M. (2021). Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM. Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC21). https://arxiv.org/abs/2104.04473
- Korthikanti, V., Casper, J., Lym, S., McAfee, L., Andersch, M., Shoeybi, M., & Catanzaro, B. (2023). Reducing Activation Recomputation in Large Transformer Models. Proceedings of Machine Learning and Systems (MLSys 2023). https://arxiv.org/abs/2205.05198
- Qi, P., Wan, X., Huang, G., & Lin, M. (2024). Zero Bubble Pipeline Parallelism. International Conference on Learning Representations (ICLR 2024). https://arxiv.org/abs/2401.10241
- NVIDIA Corporation (2026). Megatron-LM Open-Source Large Transformer Training Framework Repository. GitHub. https://github.com/NVIDIA/Megatron-LM