import json13.7 Sharding the Training State
In Section 13.4, we saw that training with Adam in fp32 stores 16 bytes per parameter—four bytes each for the weight, its gradient, and Adam’s two moment estimates. For our 18-block, 1B-parameter GPT, that fixed state fills 15.1 GiB of a 24 GiB card before reading a single token, and data parallelism (Section 13.5, Section 13.6) replicates all 16 bytes on every GPU. If we double the depth of our GPT to 36 blocks (1.92B parameters, 28.6 GiB of state), data parallelism on four 24 GiB GPUs cannot train it any more than one GPU can.
Can \(k\) GPUs train a model that no single card can hold? They can, because a GPU needs the full weights of a block only while computing that block’s forward or backward pass, and it never needs the full gradient or full optimizer state at all. Each of the \(k\) GPUs can therefore store \(1/k\) of the weights, gradients, and optimizer moments, gather each block’s weights on the fly just before the block runs, and reduce-scatter each block’s gradients as soon as they are produced.
# XLA reads its flags once, when JAX starts, so this cell runs before the
# imports. The latency-hiding scheduler orders the step with its memory in
# view; without it, the sharded step needs more memory than JAX may
# allocate by default (see the note on stage 2). On GPUs without
# peer-to-peer access, such as ours, set NCCL_LOCAL_REGISTER=0 in the
# environment before starting: NCCL's buffer registration fails there and
# prints a warning at every collective.
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
' --xla_gpu_enable_latency_hiding_scheduler=true')import collections
import re
from jax.sharding import NamedSharding, PartitionSpec as PWe first verify on a meta/shape-only device that the 36-block GPT’s \(16N\) bytes of training state exceed the 24 GiB capacity of a single RTX 4090:
1.92 billion parameters, 16N = 28.6 GiB
one GPU holds 23.5 GiB
config = dict(vocab_size=50257, num_hiddens=2048, num_heads=16,
num_blks=36, pos='learned')
k = 2 # GPUs, from the all-gather below on
key = d2l.get_key()
N = d2l.num_params(nnx.eval_shape(lambda: d2l.GPT(**config,
rngs=nnx.Rngs(key))))
print(f'{N / 1e9:.2f} billion parameters, 16N = {16 * N / 2**30:.1f} GiB')
if jax.default_backend() == 'gpu':
limit = jax.devices()[0].memory_stats()['bytes_limit']
print(f'JAX may allocate {limit / 2**30:.1f} GiB of one GPU')1.92 billion parameters, 16N = 28.6 GiB
JAX may allocate 22.1 GiB of one GPU
13.7.1 Partitioning the Optimizer State, Gradients, and Weights
In standard data parallelism, all \(k\) GPUs hold identical copies of Adam’s moment estimates and perform identical optimizer updates. The ZeRO (Zero Redundancy Optimizer) family (Rajbhandari et al. 2020) eliminates this redundancy in three cumulative stages (Table 13.7.1):
- ZeRO Stage 1 partitions only the optimizer state: each GPU holds Adam’s two moments for \(1/k\) of the parameters (\(8 + 8/k\) bytes/parameter). Instead of an allreduce (\(=\text{reduce-scatter} + \text{all-gather}\), Section 13.5.3), the GPUs reduce-scatter the gradients so each GPU receives the summed gradient for its \(1/k\) shard, updates its own parameters, and all-gathers the updated weights—moving the exact same bytes as data parallelism.
- ZeRO Stage 2 also partitions the gradients (\(4 + 12/k\) bytes/parameter): as each gradient bucket fills during the backward pass, it is immediately reduce-scattered and the non-owned \(1 - 1/k\) gradient shards are freed, again at zero extra byte cost over data parallelism.
- ZeRO Stage 3, or Fully Sharded Data Parallelism (FSDP) (Zhao et al. 2023), shards the weights as well (\(16/k\) bytes/parameter). Before a block runs in the forward or backward pass, an all-gather assembles its full weights; immediately after the block finishes, the non-owned weight shards are freed, and the block’s gradients are reduce-scattered (Figure 13.7.1).
| each GPU holds | weights | gradients | Adam state | bytes per parameter | GPT, \(k = 2\) |
|---|---|---|---|---|---|
| data parallelism | all | all | all | 16 | 28.6 GiB |
| ZeRO stage 1 | all | all | \(1/k\) | \(8 + 8/k\) | 21.4 GiB |
| ZeRO stage 2 | all | \(1/k\) | \(1/k\) | \(4 + 12/k\) | 17.9 GiB |
| ZeRO stage 3 (FSDP) | \(1/k\) | \(1/k\) | \(1/k\) | \(16/k\) | 14.3 GiB |
Because FSDP performs two all-gathers (forward and backward) and one reduce-scatter of \(S = 4N\) bytes per step—three collective phases where a ring allreduce performs two—it moves \(1.5\times\) the communication volume of data parallelism. Table 13.7.2 summarizes the four primary collectives used across parallel training, and Figure 13.7.2 shows what each one moves between two GPUs.
| collective | what every GPU ends with | where it appears |
|---|---|---|
| allreduce | the full sum | gradients in data parallelism |
| reduce-scatter | one \(1/k\) shard of the sum | gradients in ZeRO and FSDP |
| all-gather | every shard, concatenated | weights in ZeRO and FSDP |
| all-to-all | a distinct slice from each GPU | token routing in mixtures of experts (Section 11.7) |
13.7.2 Memory and Communication
Let us predict the peak memory and step time of our 36-block GPT under FSDP on \(k = 2\) GPUs, with 2 sequences of 1,024 tokens per GPU and per-block activation checkpointing (Section 13.4.3).
Memory: The sharded training state takes \(16N/2 = 14.3\) GiB per GPU. Checkpointed activations take ~1 MiB/token (~2 GiB for 2,048 tokens), and one or two currently gathered blocks (~0.2 GB each) bring peak memory to at most ~17 GiB per GPU—comfortably below 24 GiB.
Communication: Each of the three collective phases sends \((k-1)S/k\) bytes per GPU, giving a total communication time of
\[ t_\textrm{comm} = \frac{3(k-1)}{k}\,S\,\beta_\textrm{link}. \tag{13.7.1}\]
Notice the key scaling property of FSDP: adding more GPUs divides the state memory per GPU by \(k\), but the bytes each GPU sends per step grow from \(1.5S\) (at \(k = 2\)) toward \(3S\) (at large \(k\)). Only processing more tokens per GPU or using a faster interconnect reduces the communication share of a step.
We first measure \(\beta_\textrm{link}\) for an all-gather of 256 MiB across \(k = 2\) GPUs:
bus bandwidth = 2.3 GB/s in an all-gather on 2 GPUs (beta_link = 0.44 ns/byte)
assert jax.device_count() >= k, 'The cells from here on need two GPUs'
mesh = jax.make_mesh((k,), ('data',), devices=jax.devices()[:k],
axis_types=(jax.sharding.AxisType.Auto,))
x = jnp.zeros(2**26, device=NamedSharding(mesh, P('data'))) # 256 MiB
# Asking for the result on every GPU makes the compiler gather the parts
gather = jax.jit(lambda x: x, out_shardings=NamedSharding(mesh, P()))
t = d2l.Benchmark(lambda: gather(x), repeats=10).time
beta_link = t / ((k - 1) / k * x.nbytes) # Seconds per byte sent per GPU
del x # Frees its memory before the training step
print(f'bus bandwidth = {1e-9 / beta_link:.1f} GB/s in an all-gather on {k} '
f'GPUs (beta_link = {1e9 * beta_link:.2f} ns/byte)')bus bandwidth = 2.2 GB/s in an all-gather on 2 GPUs (beta_link = 0.46 ns/byte)
Using the measured \(\beta_\textrm{link}\) and the RTX 4090’s 82.6 TFLOP/s tf32 peak (peak_flops), we can evaluate our paper predictions for per-GPU state memory (\(16N/k\)), communication time (\(3(k-1)S\beta_\textrm{link}/k\)), and checkpointed compute time (\(8NbT/P\)):
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
b, T = 2, 1024 # Sequences of T tokens per GPU and step
S = 4 * N # Bytes of the fp32 weights, and of the gradients
peak_flops = 82.6e12 # tf32 FLOP/s of the RTX 4090
print(f'state per GPU, 16N/k: {16 * N / k / 2**30:.1f} GiB')
print(f'communication, 3(k-1)S beta_link/k: '
f'{3 * (k - 1) / k * S * beta_link:.1f} s per step')
print(f'arithmetic at the peak, 8N bT/P: '
f'{8 * N * b * T / peak_flops:.2f} s per step')state per GPU, 16N/k: 14.3 GiB
communication, 3(k-1)S beta_link/k: 5.3 s per step
arithmetic at the peak, 8N bT/P: 0.38 s per step
At ~2.2 GB/s bus bandwidth over host memory, moving \(1.5S = 11.5\) GB per step takes ~5 s, whereas the 2,048 tokens of arithmetic take only ~0.4 s. Because 0.4 s of compute cannot hide 5 s of communication, the step should take ~5 s.
13.7.4 Summary
Data parallelism replicates all \(16N\) bytes of fp32 Adam state on every GPU. ZeRO partitions this state across \(k\) GPUs: Stage 1 shards the optimizer moments (\(8 + 8/k\) bytes/parameter) and Stage 2 also shards the gradients (\(4 + 12/k\) bytes/parameter), both moving the exact same \(2(k-1)S/k\) bytes per step as a ring allreduce. Stage 3 (FSDP) shards the weights as well (\(16/k\) bytes/parameter), gathering each block’s weights for the forward and backward pass and reduce-scattering gradients at \(1.5\times\) the communication volume of data parallelism (\(3(k-1)S/k\) bytes per GPU). Sharding enables two 24 GiB GPUs to train a 36-block GPT whose 28.6 GiB state fits on neither card alone.
13.7.5 Exercises
- Cost of sharding. ● Count communication per GPU and step in units of \(S = 4N\), the bytes of one full set of fp32 weights or gradients.
- A variant of ZeRO Stage 3 keeps every gathered block in memory from its forward pass until its backward pass finishes. Which collective does this eliminate, and how much memory saving from Table 13.7.1 does it give up?
- Mixed-precision FSDP all-gathers weights in bf16 and reduce-scatters gradients in bf16 while keeping each GPU’s master weight and Adam shards in fp32. Compare its bytes transferred per step with fp32 data parallelism, and its memory per parameter with the last row of Table 13.7.1.
- For the 36-block GPT on \(k = 2\) GPUs at the measured \(\beta_\textrm{link}\), how many tokens per GPU would a step need for checkpointed compute (\(8N\) FLOPs/token at 83 TFLOP/s) to match the communication time Equation 13.7.1? Do those activations fit on the card, and why does gradient accumulation not help when FSDP re-gathers weights on every micro-batch?
- [extended] Sharded optimizer state. ● Implement ZeRO Stage 1 (Rajbhandari et al. 2020) by hand starting from
TRAIN_DDP(Section 13.6) withtorch.optim.Adam.- Partition the parameter tensors across ranks so each rank owns roughly \(1/k\) of the parameters and runs Adam only on its owned tensors, then broadcast each updated tensor from its owner with
dist.broadcast. Verify that the parameters match full DDP Adam after several steps, and compare withtorch.distributed.optim.ZeroRedundancyOptimizer. - Measure allocated and peak GPU memory at \(k = 2\) and \(k = 4\) with and without sharding, and compare the total bytes sent by DDP allreduce plus owner broadcasts against Stage 1’s reduce-scatter plus all-gather.
- Partition the parameter tensors across ranks so each rank owns roughly \(1/k\) of the parameters and runs Adam only on its owned tensors, then broadcast each updated tensor from its owner with
- [code] Tensor versus data parallelism. ● Consider the MLP block \(\mathbf{Y} = \phi(\mathbf{X}\mathbf{W}_1)\mathbf{W}_2\) with \(\mathbf{X} \in \mathbb{R}^{n \times d}\), \(\mathbf{W}_1 \in \mathbb{R}^{d \times 4d}\), and \(\mathbf{W}_2 \in \mathbb{R}^{4d \times d}\) across \(k\) devices. Tensor parallelism (Figure 13.5.1, (Shoeybi et al. 2019)) splits \(\mathbf{W}_1\) column-wise and \(\mathbf{W}_2\) row-wise.
- Show that each device can compute a partial \(n \times d\) output without communication and that summing the \(k\) partial outputs gives \(\mathbf{Y}\). Which collective does the forward pass need, and which does the backward pass need for \(\nabla_{\mathbf{X}}\)?
- Compare the values sent per device and step under tensor parallelism versus data parallelism, and find the token count \(n\) below which tensor parallelism sends less data. Why is tensor parallelism nevertheless restricted to fast intra-node NVLink domains?
- Using
parallelize_modulewithColwiseParallel()andRowwiseParallel()on a 1DDeviceMesh, count the forward and backward collectives withCommDebugMode.
- Prefetching the next block. In the forward pass under FSDP, let \(g\) be the all-gather time of one block and \(c\) its compute time. Without overlap, \(L\) blocks take \(L(g + c)\); prefetching issues the all-gather of block \(l + 1\) while block \(l\) computes.
- Show that prefetching reduces the forward pass time to \(g + (L-1)\max(g, c) + c\), and explain why no schedule can do better than \(L\max(g, c)\).
- Evaluate \(g\) and \(c\) for one block of the 36-block GPT (\(50\)M parameters, 2,048 tokens/GPU, 83 TFLOP/s) on our PCIe link versus NVLink 5 (900 GB/s), and state how much prefetching saves on each interconnect.
- Cost of sharding. ● Count communication per GPU and step in units of \(S = 4N\), the bytes of one full set of fp32 weights or gradients.
- A variant of ZeRO Stage 3 keeps every gathered block in memory from its forward pass until its backward pass finishes. Which collective does this eliminate, and how much memory saving from Table 13.7.1 does it give up?
- Mixed-precision FSDP all-gathers weights in bf16 and reduce-scatters gradients in bf16 while keeping each GPU’s master weight and Adam shards in fp32. Compare its bytes transferred per step with fp32 data parallelism, and its memory per parameter with the last row of Table 13.7.1.
- For the 36-block GPT on \(k = 2\) GPUs at the measured \(\beta_\textrm{link}\), how many tokens per GPU would a step need for checkpointed compute (\(8N\) FLOPs/token at 83 TFLOP/s) to match the communication time Equation 13.7.1? Do those activations fit on the card, and why does gradient accumulation not help when FSDP re-gathers weights on every micro-batch?
- [extended] Sharded optimizer state. ● Implement ZeRO Stage 1 (Rajbhandari et al. 2020) declaratively starting from
train_step(Section 13.6) withoptax.adam. Keep the model parameters replicated (P()), and place the leaves ofnnx.state(opt)withfsdp_sharding.- Ensure parameters remain replicated at the end of
train_stepviajax.sharding.reshardif needed, and verify that multi-step parameter updates match replicated Adam. - Inspect the compiled step with
collective_megabytesand compare its collectives and live/peak memory at \(k = 2\) and \(k = 4\) against Table 13.7.1.
- Ensure parameters remain replicated at the end of
- [code] Tensor versus data parallelism. ● Consider the MLP block \(\mathbf{Y} = \phi(\mathbf{X}\mathbf{W}_1)\mathbf{W}_2\) with \(\mathbf{X} \in \mathbb{R}^{n \times d}\), \(\mathbf{W}_1 \in \mathbb{R}^{d \times 4d}\), and \(\mathbf{W}_2 \in \mathbb{R}^{4d \times d}\) across \(k\) devices. Tensor parallelism (Figure 13.5.1, (Shoeybi et al. 2019)) splits \(\mathbf{W}_1\) column-wise (
P(None, 'data')) and \(\mathbf{W}_2\) row-wise (P('data', None)).- Show that each device can compute a partial \(n \times d\) output without communication and that summing the \(k\) partial outputs gives \(\mathbf{Y}\). Which collective does the forward pass need, and which does the backward pass need for \(\nabla_{\mathbf{X}}\)?
- Compare the values sent per device and step under tensor parallelism versus data parallelism, and find the token count \(n\) below which tensor parallelism sends less data. Why is tensor parallelism nevertheless restricted to fast intra-node NVLink domains?
- Place \(\mathbf{W}_1\) with
P(None, 'data'), \(\mathbf{W}_2\) withP('data', None), and \(\mathbf{X}\) replicated on anAutomesh, jit the forward and backward pass, and inspect the emitted collectives.
- Prefetching the next block. In the forward pass under FSDP, let \(g\) be the all-gather time of one block and \(c\) its compute time. Without overlap, \(L\) blocks take \(L(g + c)\); prefetching issues the all-gather of block \(l + 1\) while block \(l\) computes.
- Show that prefetching reduces the forward pass time to \(g + (L-1)\max(g, c) + c\), and explain why no schedule can do better than \(L\max(g, c)\).
- Evaluate \(g\) and \(c\) for one block of the 36-block GPT (\(50\)M parameters, 2,048 tokens/GPU, 83 TFLOP/s) on our PCIe link versus NVLink 5 (900 GB/s), and state how much prefetching saves on each interconnect.