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).

Meta-Device Initialization and fully_shard in PyTorch

FSDP in PyTorch

To avoid ever allocating the full 28.6\text{ GiB} state on any single GPU during startup, we construct the model on the zero-memory 'meta' device, shard each block with fully_shard, and materialize only local shards via to_empty:

with torch.device('meta'):      # zero-memory shape/dtype construction
    model = d2l.GPT(**config)
for blk in model.blks:          # unit of all-gather & release: 1 Transformer block
    fully_shard(blk)
fully_shard(model)              # shard remaining embeddings and final RMSNorm
model.to_empty(device=device)   # allocate only this rank's 1/k parameter shards
...                             # initialize local shards in-place
opt = torch.optim.Adam(model.parameters(), lr=1e-4, fused=True)
  • Why fully_shard wraps each block individually: Wrapping at the block boundary ensures that only one 50\text{M}-parameter block (\sim 200\text{ MB}) is all-gathered at a time rather than the entire 1.92\text{B}-parameter model.

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.

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.

Summary: ZeRO Stages 1–3 and FSDP Trade-Offs

Key Takeaways

Strategy Sharded Across k GPUs Memory / Param (fp32 Adam) Collectives per Step Bytes Sent / GPU (S = 4N)
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