13.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 kk 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 kk GPUs can therefore store 1/k1/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.

import json

We first verify on a meta/shape-only device that the 36-block GPT's 16N16N bytes of training state exceed the 24 GiB capacity of a single RTX 4090:

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
with torch.device('meta'):  # Shapes and dtypes only, no data
    N = d2l.num_params(d2l.GPT(**config))
print(f'{N / 1e9:.2f} billion parameters, 16N = {16 * N / 2**30:.1f} GiB')
if d2l.num_gpus():
    total = torch.cuda.mem_get_info()[1]
    print(f'one GPU holds {total / 2**30:.1f} GiB')
1.92 billion parameters, 16N = 28.6 GiB
one GPU holds 23.5 GiB

13.7.1 Partitioning the Optimizer State, Gradients, and Weights#

In standard data parallelism, all kk 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/k1/k of the parameters (8+8/k8 + 8/k bytes/parameter). Instead of an allreduce (=reduce-scatter+all-gather=\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/k1/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/k4 + 12/k bytes/parameter): as each gradient bucket fills during the backward pass, it is immediately reduce-scattered and the non-owned 1−1/k1 - 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/k16/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).
Table 13.7.1. Training state per GPU at the end of the backward pass, with Adam in fp32 on kk GPUs, and for the GPT with 36 blocks and 1.92 billion parameters on k=2k = 2.
each GPU holdsweightsgradientsAdam statebytes per parameterGPT, k=2k = 2
data parallelismallallall1628.6 GiB
ZeRO stage 1allall1/k1/k8+8/k8 + 8/k21.4 GiB
ZeRO stage 2all1/k1/k1/k1/k4+12/k4 + 12/k17.9 GiB
ZeRO stage 3 (FSDP)1/k1/k1/k1/k1/k1/k16/k16/k14.3 GiB
Figure 13.7.1:

The life of one block's weights under FSDP on one GPU. Between uses the block is sharded, and each GPU holds 1/k1/k of it; the other blocks stay sharded throughout. An all-gather assembles the whole block for its forward pass, after which it is released. A second all-gather assembles it for the backward pass, after which it is released again, and a reduce-scatter leaves each GPU with its share of the gradients.

Because FSDP performs two all-gathers (forward and backward) and one reduce-scatter of S=4NS = 4N bytes per step—three collective phases where a ring allreduce performs two—it moves 1.5×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.

Figure 13.7.2:

The four collectives as data movement between two GPUs, before and after. GPU 0 starts with the chunks a0,a1a_0, a_1 and GPU 1 with b0,b1b_0, b_1; for all-gather, GPU gg starts with only its own shard, chunk gg. Raw chunks are blue and sums are green.

Table 13.7.2. The collective operations behind data-parallel and sharded training.
collectivewhat every GPU ends withwhere it appears
allreducethe full sumgradients in data parallelism
reduce-scatterone 1/k1/k shard of the sumgradients in ZeRO and FSDP
all-gatherevery shard, concatenatedweights in ZeRO and FSDP
all-to-alla distinct slice from each GPUtoken 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=2k = 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.316N/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(k-1)S/k bytes per GPU, giving a total communication time of
tcomm=3(k−1)k S βlink.(13.7.1)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 kk, but the bytes each GPU sends per step grow from 1.5S1.5S (at k=2k = 2) toward 3S3S (at large kk). Only processing more tokens per GPU or using a faster interconnect reduces the communication share of a step.

We first measure βlink\beta_\textrm{link} for an all-gather of 256 MiB across k=2k = 2 GPUs:

GATHER = r'''
import json, torch
import torch.distributed as dist
from d2l import torch as d2l

_, k, device = d2l.init_distributed()
x = torch.zeros(2**26 // k, device=device)  # This GPU's part
y = torch.empty(2**26, device=device)       # 256 MiB, gathered
t = d2l.Benchmark(lambda: dist.all_gather_into_tensor(y, x), repeats=10).time
print(json.dumps({'beta_link': t / ((k - 1) / k * y.nbytes)}))  # Per byte sent
dist.destroy_process_group()
'''
assert d2l.num_gpus() >= k, 'The cells from here on need two GPUs'
beta_link = max(r['beta_link'] for r in d2l.torchrun(GATHER, k))
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.3 GB/s in an all-gather on 2 GPUs (beta_link = 0.44 ns/byte)

Using the measured βlink\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/k16N/k), communication time (3(k−1)Sβlink/k3(k-1)S\beta_\textrm{link}/k), and checkpointed compute time (8NbT/P8NbT/P):

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.0 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.51.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.3 Sharded Training on Two GPUs#

Now we run the sharded 36-block GPT step on two GPUs, constructing the model so that no single GPU ever materializes the full 28.6 GiB state at once.

In PyTorch, we construct the model on the 'meta' device, wrap each checkpointed block and the top-level model with fully_shard from torch.distributed.fsdp, materialize only this rank's shards via model.to_empty(device=device), and initialize them in place.

TRAIN_FSDP = r'''
import json, sys, torch
import torch.distributed as dist
from torch import nn
from torch.nn import functional as F
from torch.distributed.fsdp import fully_shard
from torch.utils.checkpoint import checkpoint
from d2l import torch as d2l

class Checkpointed(nn.Module):
    """A block whose activations the backward pass recomputes."""
    def __init__(self, blk):
        super().__init__()
        self.blk = blk

    def forward(self, X, **kwargs):
        return checkpoint(self.blk, X, use_reentrant=False, **kwargs)

config, b, T = json.loads(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])
_, k, device = d2l.init_distributed()
torch.set_float32_matmul_precision('high')  # fp32 products on tf32 cores
torch.manual_seed(0)        # The same seed in every process
with torch.device('meta'):  # Shapes only: no GPU holds the whole model
    model = d2l.GPT(**config)
model.blks = nn.ModuleList(Checkpointed(blk) for blk in model.blks)
for blk in model.blks:      # Each block is gathered and released on its own
    fully_shard(blk)
fully_shard(model)          # The rest: the embeddings and the final norm
model.to_empty(device=device)  # This GPU's shards, not yet initialized
with torch.no_grad():       # Initialize the shards as d2l.GPT does
    for m in model.modules():
        if isinstance(m, nn.RMSNorm):
            m.reset_parameters()
    for emb in (model.token_emb, model.pos_emb):
        nn.init.normal_(emb.weight, std=0.02)
    model.init_weights()
opt = torch.optim.Adam(model.parameters(), lr=1e-4, fused=True)
# The same tokens on every GPU: they only set the shapes of the step
X = torch.randint(0, config['vocab_size'], (b, T), device=device)

def step():
    loss = F.cross_entropy(model(X).flatten(0, 1), X.flatten())
    loss.backward()
    opt.step()
    opt.zero_grad()

step()                      # Warm-up; creates Adam's moment estimates
times = [d2l.Benchmark(step, warmup=0, repeats=1).time for _ in range(3)]
kernels = d2l.kernel_times(step, steps=1)
comm = sum(ms for name, ms in kernels.items() if 'nccl' in name.lower())
print(json.dumps({'peak': torch.cuda.max_memory_allocated(), 'times': times,
                  'comm': comm / 1e3}))
dist.destroy_process_group()
'''

We now launch TRAIN_FSDP across kk processes with d2l.torchrun and collect the peak allocated memory (peak_bytes), step durations (times), and NCCL communication time (comm) from rank 0:

ranks = d2l.torchrun(TRAIN_FSDP, k, json.dumps(config), b, T)
peak_bytes = max(r['peak'] for r in ranks)
times, comm = ranks[0]['times'], ranks[0]['comm']  # GPU 0

Finally, we report the measured per-GPU peak memory, median step duration, and time spent in NCCL communication kernels on GPU 0:

print(f'per GPU: peak memory {peak_bytes / 2**30:.1f} GiB; '
      f'{np.median(times):.2f} s per step ({min(times):.2f} to '
      f'{max(times):.2f})\nof each step, GPU 0 spends {comm:.2f} s in '
      f'communication kernels')
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

Both GPUs hold the 36-block model at a peak of ~16 GiB per card (under our 17 GiB bound), and each step takes ~5.5 s, with GPU 0 spending over 90% of the step in NCCL communication kernels—within a sixth of our 5 s paper prediction. Over NVLink 5 (900 GB/s per direction), the same 11.5 GB of collectives takes only ~13 ms, less than a thirtieth of the 0.4 s compute time.

This comparison also shows when to shard: a model whose training state fits on a single GPU alongside a reasonable micro-batch (such as our 18-block GPT) trains much faster with data parallelism and gradient accumulation (which communicates once per global step) than with FSDP over PCIe (which re-gathers the weights twice on every micro-batch).

13.7.4 Summary#

Data parallelism replicates all 16N16N bytes of fp32 Adam state on every GPU. ZeRO partitions this state across kk GPUs: Stage 1 shards the optimizer moments (8+8/k8 + 8/k bytes/parameter) and Stage 2 also shards the gradients (4+12/k4 + 12/k bytes/parameter), both moving the exact same 2(k−1)S/k2(k-1)S/k bytes per step as a ring allreduce. Stage 3 (FSDP) shards the weights as well (16/k16/k bytes/parameter), gathering each block's weights for the forward and backward pass and reduce-scattering gradients at 1.5×1.5\times the communication volume of data parallelism (3(k−1)S/k3(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#

  1. Cost of sharding. ● Count communication per GPU and step in units of S=4NS = 4N, the bytes of one full set of fp32 weights or gradients.
    1. 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?
    2. 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.
    3. For the 36-block GPT on k=2k = 2 GPUs at the measured βlink\beta_\textrm{link}, how many tokens per GPU would a step need for checkpointed compute (8N8N FLOPs/token at 83 TFLOP/s) to match the communication time (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?
  1. [extended] Sharded optimizer state. ● Implement ZeRO Stage 1 (Rajbhandari et al., 2020) by hand starting from TRAIN_DDP (Section 13.6) with torch.optim.Adam.

    1. Partition the parameter tensors across ranks so each rank owns roughly 1/k1/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 with torch.distributed.optim.ZeroRedundancyOptimizer.
    2. Measure allocated and peak GPU memory at k=2k = 2 and k=4k = 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.
  2. [code] Tensor versus data parallelism. ● Consider the MLP block Y=ϕ(XW1)W2\mathbf{Y} = \phi(\mathbf{X}\mathbf{W}_1)\mathbf{W}_2 with X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d}, W1∈Rd×4d\mathbf{W}_1 \in \mathbb{R}^{d \times 4d}, and W2∈R4d×d\mathbf{W}_2 \in \mathbb{R}^{4d \times d} across kk devices. Tensor parallelism (Figure 13.5.1, (Shoeybi et al., 2019)) splits W1\mathbf{W}_1 column-wise and W2\mathbf{W}_2 row-wise.

    1. Show that each device can compute a partial n×dn \times d output without communication and that summing the kk partial outputs gives Y\mathbf{Y}. Which collective does the forward pass need, and which does the backward pass need for ∇X\nabla_{\mathbf{X}}?
    2. Compare the values sent per device and step under tensor parallelism versus data parallelism, and find the token count nn below which tensor parallelism sends less data. Why is tensor parallelism nevertheless restricted to fast intra-node NVLink domains?
    3. Using parallelize_module with ColwiseParallel() and RowwiseParallel() on a 1D DeviceMesh, count the forward and backward collectives with CommDebugMode.
  1. Prefetching the next block. In the forward pass under FSDP, let gg be the all-gather time of one block and cc its compute time. Without overlap, LL blocks take L(g+c)L(g + c); prefetching issues the all-gather of block l+1l + 1 while block ll computes.
    1. Show that prefetching reduces the forward pass time to g+(L−1)max⁡(g,c)+cg + (L-1)\max(g, c) + c, and explain why no schedule can do better than Lmax⁡(g,c)L\max(g, c).
    2. Evaluate gg and cc for one block of the 36-block GPT (5050M 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.

Discussions