Sharding the Training State
Dive into Deep Learning · §13.7
ZeRO and Fully Sharded Data Parallelism (FSDP)
16N state bottleneck · ZeRO stages 1–3 · all-gather & reduce-scatter · FSDP lifecycle · communication vs. memory
When the 16N Parameter State Alone Exceeds GPU Memory
Motivation
Doubling our 1B-parameter GPT from 18 to 36 blocks (width d = 2048) produces a 1.92\text{B}-parameter model whose float32 Adam state (16N bytes) no longer fits on a 24\text{ GiB} RTX 4090:
1.92 billion parameters, 16N = 28.6 GiB
one GPU holds 23.5 GiB
- Why data parallelism cannot help: Standard DDP replicates all 16\text{ B/param} (28.6\text{ GiB}) on every GPU, so four 24\text{ GiB} cards run out of memory before processing a single token just like one card does.
Why Replicating State Across k GPUs Is Redundant
Core Insight
- Weights (\mathbf{W}_\ell, 4\text{ B/param}): Needed only while block \ell executes its forward or backward pass.
- Gradients (\nabla\mathbf{W}_\ell, 4\text{ B/param}): Needed only from block \ell’s backward pass until the optimizer step.
- Adam Moments (\mathbf{m}, \mathbf{v}, 8\text{ B/param}): Touched only inside the elementwise Adam update at the end of the step—each of the k GPUs needs to own and update only 1/k of the parameters.
The Three ZeRO Stages: Memory per GPU vs. Stage
ZeRO Taxonomy
- ZeRO-1 (8 + 8/k\text{ B/param}): Shards Adam moments \mathbf{m}, \mathbf{v} across k GPUs (21.4\text{ GiB} at k=2 for our 1.92\text{B} GPT).
- ZeRO-2 (4 + 12/k\text{ B/param}): Shards moments + gradients (17.9\text{ GiB} at k=2) at the same 2\,\frac{k-1}{k}S comm volume as DDP.
- ZeRO-3 / FSDP (16/k\text{ B/param}): Shards weights, gradients, and moments (14.3\text{ GiB} at k=2, leaving \sim 10\text{ GiB} for activations).
Collective Primitives Behind Sharded Training
Collective Operations
- Ring Allreduce = Reduce-Scatter + All-Gather: Decomposes a \frac{2(k-1)}{k}S sum into two half-collectives of \frac{k-1}{k}S bytes each.
- Reduce-Scatter (\text{Full } S \to \text{Summed } S/k): Sums gradients across GPUs and delivers shard j to owner GPU j.
- All-Gather (\text{Shard } S/k \to \text{Full } S): Reconstructs full weights across GPUs just in time for a layer or after a sharded optimizer update.
ZeRO Stage 1: Sharding Optimizer Moments at Free Comm
ZeRO Stage 1
- Insert Adam between the two halves of allreduce: (1) Reduce-scatter gradients (\frac{k-1}{k}S), (2) update owned 1/k weights with owned 1/k Adam moments, (3) all-gather updated weights (\frac{k-1}{k}S).
- Zero extra communication bytes: Total traffic per GPU is \frac{2(k-1)}{k}S, identical to standard DDP while cutting Adam state memory by k\times.
ZeRO Stage 2: Streaming Reduce-Scatter of Gradients
ZeRO Stage 2
Why hold all 4N bytes of gradients until the end of the backward pass if each GPU only updates 1/k of the parameters? ZeRO Stage 2 fuses gradient release into the backward pass:
- Bucketed reduce-scatter during
backward(): As soon as backpropagation finishes computing the gradients for a block or bucket, the GPUs immediately launch a reduce-scatter on that bucket.
- Immediate deallocation of non-owned shards: Each GPU retains only the summed 1/k gradient slice that it owns and immediately frees the other (k-1)/k gradient slices before the next backward block runs.
- Same communication volume as DDP: Across the entire backward pass and post-step weight all-gather, each GPU still transmits \frac{2(k-1)}{k}S bytes total, while never materializing the full 4N gradient tensor at once.
ZeRO Stage 3 (FSDP): Block Weight Gather and Release
Fully Sharded Data Parallel
![]()
- Sharding the weights (16N/k total state): Between uses, each GPU stores only 1/k of every block’s weights.
- Per-block lifecycle: Before block \ell runs in the forward pass, an all-gather assembles its full weights in a temporary buffer, which is freed as soon as block \ell finishes. In the backward pass, a second all-gather re-assembles block \ell’s weights, followed by a reduce-scatter of block \ell’s gradients and immediate weight release.
FSDP Communication Cost: 1.5× Data-Parallel Volume
Communication Model
t_{\textrm{comm (FSDP)}} \;=\; \frac{3(k-1)}{k}\,S\,\beta_{\textrm{link}}
- 1.5\times DDP traffic: Because FSDP frees gathered weights after the forward pass, it pays one extra all-gather in the backward pass (3 collective phases vs. 2).
- Scaling law as k grows: Adding GPUs divides steady-state memory (16N/k \downarrow), while per-GPU communication rises from 1.5\,S (k=2) toward 3S (k \to \infty).
Measuring All-Gather Bandwidth on Two RTX 4090s
Link Calibration
Before running our 36-block GPT on k = 2 GPUs, we calibrate \beta_{\textrm{link}} for a 256\text{ MiB} all-gather across two RTX 4090s:
bus bandwidth = 2.3 GB/s in an all-gather on 2 GPUs (beta_link = 0.44 ns/byte)
- Consistent host-staged link rate: Each GPU sends (k-1)/k = 1/2 of the 256\text{ MiB} output (128\text{ MiB}) at a bus bandwidth of \sim 2.2\text{--}2.3\text{ GB/s} (\beta_{\textrm{link}} \approx 0.43\text{--}0.45\text{ ns/B}), matching the bare allreduce link rate from §13.6.
Predicting Memory, Comm, and Compute for the 1.9B GPT
Step Prediction
Now we predict the peak memory, communication time, and compute time of one FSDP step of our 36-block, 1.92\text{B}-parameter GPT (S = 4N = 7.7\text{ GB}) on k = 2 GPUs with b = 2 sequences of T = 1{,}024 tokens per GPU and per-block activation checkpointing:
state per GPU, 16N/k: 14.3 GiB
communication, 3(k-1)S beta_link/k: 5.0 s per step
arithmetic at the peak, 8N bT/P: 0.38 s per step
- Memory prediction (\le 17\text{ GiB} < 24\text{ GiB}): Sharded state 16N/2 = 14.3\text{ GiB} + checkpointed activations (\sim 1\text{ MiB/token} \times 2{,}048 \approx 2\text{ GiB}) + 1–2 live gathered blocks (\sim 0.4\text{ GiB}) \approx 16.7\text{ GiB}.
- Time prediction (\sim 5\text{ s} communication vs. 0.4\text{ s} compute): At k = 2, each GPU transmits 1.5\,S = 11.5\text{ GB} over the 2.2\text{ GB/s} PCIe link (\sim 5.0\text{ s}), dwarfing the 0.4\text{ s} of
tf32 arithmetic (8N FLOPs/token with checkpointing).
Avoiding Host OOM During Multi-Process FSDP Startup
Initialization Discipline
When torchrun launches k worker processes on a single host machine, naive model initialization can crash host RAM or GPU VRAM before FSDP even starts:
- Pitfall 1 — Materializing on GPU before
fully_shard: Calling d2l.GPT(**config).to(device) before fully_shard allocates 4N = 7.7\text{ GB} on the card; for larger models (7\text{B+}), this immediately triggers a CUDA OOM.
- Pitfall 2 — k copies in host RAM: If all k = 8 processes construct and initialize a 30\text{ GB} model in CPU RAM simultaneously, they consume 8 \times 30 = 240\text{ GB} of host DRAM.
- Production pattern: Construct on
torch.device('meta') \to apply fully_shard per block \to allocate local 1/k GPU storage with model.to_empty(device=device) \to initialize or stream checkpoints directly into the sharded DTensors.
Measured FSDP Step: 16 GiB Peak, 90% Communication
Experimental Verification
Running our 36-block, 1.92\text{B}-parameter GPT step on two 24\text{ GiB} RTX 4090s confirms both our memory and timing predictions:
per GPU: peak memory 16.0 GiB; 5.73 s per step (5.70 to 5.74)
of each step, GPU 0 spends 5.69 s in communication kernels
- Memory fits cleanly: Each GPU peaks at \sim 16\text{ GiB} (below our 17\text{ GiB} bound), training a 28.6\text{ GiB}-state model that neither card could hold alone.
- Communication dominates over PCIe: Each step takes \sim 5.5\text{ s}, with GPU 0 spending over 90\% of the step (\sim 5.0\text{ s}) inside NCCL communication kernels and only \sim 0.4\text{ s} in arithmetic.
FSDP Over Host-Staged PCIe vs. NVLink 5 Fabrics
Interconnect Sensitivity
- Host-staged PCIe 4.0 (\sim 2.2\text{ GB/s}): Moving 1.5\,S = 11.5\text{ GB} takes \sim 5.0\text{ s} vs. 0.40\text{ s} compute, leaving the step deeply link-bound (\sim 7\% compute share).
- NVLink 4/5 (450\text{--}900\text{ GB/s}): The same 11.5\text{ GB} finishes in 13\text{--}26\text{ ms}, matching or beating block compute time (14\text{--}32\text{ ms}).
- Block prefetching: Overlapping block \ell+1’s all-gather with block \ell’s compute hides communication completely when g \le c.
When to Shard vs. Replicate with Gradient Accumulation
Decision Guide
- When 16N fits (e.g., 1B GPT on 24\text{ GiB}): Use DDP + gradient accumulation—GPUs communicate only once per global step after all m micro-batches finish.
- Why FSDP loses over PCIe on accumulated steps: FSDP frees weights after every block, forcing it to re-gather all weights twice on every single micro-batch (2m\times extra PCIe traffic).
- Escalation ladder: DDP \to ZeRO-1/2 \to ZeRO-3 (FSDP) only as memory demands require.
Concept Check: ZeRO Memory, FSDP Traffic, and Links
Check Your Understanding
Work out three sharding scenarios (S = 4N: bytes of one full float32 copy of the weights or gradients):
- N = 4 \times 10^9 parameters (16N = 64\text{ GB} of
float32 Adam state) on k = 4 GPUs: how many GB of state does each GPU hold after the backward pass under DDP, ZeRO-1, ZeRO-2, and ZeRO-3 (FSDP)?
- Mixed-precision FSDP keeps its
float32 shards but all-gathers weights and reduce-scatters gradients in bfloat16 (2\text{ B}). How many bytes per GPU does it transmit per step compared to float32 DDP?
- As you scale FSDP from k = 2 GPUs to k = 64 GPUs, by what factor does per-GPU state memory change, and by what factor does per-GPU communication volume per step change?
Answers:
- DDP (16N): \mathbf{64\text{ GB}}; ZeRO-1 ((8 + 8/k)N = 10N): \mathbf{40\text{ GB}}; ZeRO-2 ((4 + 12/k)N = 7N): \mathbf{28\text{ GB}}; ZeRO-3 / FSDP (16N/k = 4N): \mathbf{16\text{ GB}} per GPU.
- Less traffic than
float32 DDP: Halving the collective dtype to bfloat16 halves S_{\textrm{comm}} from 4N \to 2N = S/2, so 3 FSDP phases move \frac{3(k-1)}{k} \frac{S}{2} = \mathbf{1.5\,\frac{k-1}{k}S} bytes (25\% fewer bytes than float32 DDP’s \frac{2(k-1)}{k}S).
- Memory drops by 32\times (16N/2 \to 16N/64), while communication per GPU grows by nearly 2\times (from 3(1/2)S = 1.5\,S at k=2 to 3(63/64)S \approx 2.95\,S at k=64).
Summary: ZeRO Stages 1–3 and FSDP Trade-Offs
Key Takeaways
| Standard DDP |
Minibatch only |
16\text{ B} |
1 Allreduce |
\frac{2(k-1)}{k}S < 2S |
| ZeRO Stage 1 |
Optimizer moments (\mathbf{m}, \mathbf{v}) |
8 + \frac{8}{k}\text{ B} |
1 Reduce-Scatter + 1 All-Gather |
\frac{2(k-1)}{k}S < 2S |
| ZeRO Stage 2 |
Moments + Gradients (\nabla \mathbf{W}) |
4 + \frac{12}{k}\text{ B} |
Bucketed Reduce-Scatter + 1 All-Gather |
\frac{2(k-1)}{k}S < 2S |
| ZeRO Stage 3 (FSDP) |
Moments + Grads + Weights (\mathbf{W}) |
\frac{16}{k}\text{ B} |
2 All-Gathers + 1 Reduce-Scatter |
\frac{3(k-1)}{k}S < 3S |
bf16-Comm FSDP |
All state (master shards in fp32) |
\frac{16}{k}\text{ B} (+ live block) |
2 bf16 All-Gathers + 1 bf16 RS |
\frac{1.5(k-1)}{k}S < 1.5S |