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 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 GPUs can therefore store 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 jsonWe first verify on a meta/shape-only device that the 36-block GPT's 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 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 of the parameters ( bytes/parameter). Instead of an allreduce (, Section 13.5.3), the GPUs reduce-scatter the gradients so each GPU receives the summed gradient for its 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 ( bytes/parameter): as each gradient bucket fills during the backward pass, it is immediately reduce-scattered and the non-owned 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 ( 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, |
|---|---|---|---|---|---|
| data parallelism | all | all | all | 16 | 28.6 GiB |
| ZeRO stage 1 | all | all | 21.4 GiB | ||
| ZeRO stage 2 | all | 17.9 GiB | |||
| ZeRO stage 3 (FSDP) | 14.3 GiB |
The life of one block's weights under FSDP on one GPU. Between uses the block is sharded, and each GPU holds 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 bytes per step—three collective phases where a ring allreduce performs two—it moves 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.
The four collectives as data movement between two GPUs, before and after. GPU 0 starts with the chunks and GPU 1 with ; for all-gather, GPU starts with only its own shard, chunk . Raw chunks are blue and sums are green.
| collective | what every GPU ends with | where it appears |
|---|---|---|
| allreduce | the full sum | gradients in data parallelism |
| reduce-scatter | one 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 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 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 bytes per GPU, giving a total communication time of
Notice the key scaling property of FSDP: adding more GPUs divides the state memory per GPU by , but the bytes each GPU sends per step grow from (at ) toward (at large ). Only processing more tokens per GPU or using a faster interconnect reduces the communication share of a step.
We first measure for an all-gather of 256 MiB across 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 and the RTX 4090's 82.6 TFLOP/s tf32
peak (peak_flops), we can evaluate our paper predictions for per-GPU state
memory (), communication time (), and
checkpointed compute time ():
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 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 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 0Finally, 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 bytes of fp32 Adam state on every GPU. ZeRO partitions this state across GPUs: Stage 1 shards the optimizer moments ( bytes/parameter) and Stage 2 also shards the gradients ( bytes/parameter), both moving the exact same bytes per step as a ring allreduce. Stage 3 (FSDP) shards the weights as well ( bytes/parameter), gathering each block's weights for the forward and backward pass and reduce-scattering gradients at the communication volume of data parallelism ( 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 , 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 GPUs at the measured , how many tokens per GPU would a step need for checkpointed compute ( 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?
-
[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
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 and 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
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 with , , and across devices. Tensor parallelism (Figure 13.5.1, (Shoeybi et al., 2019)) splits column-wise and row-wise.
- Show that each device can compute a partial output without communication and that summing the partial outputs gives . Which collective does the forward pass need, and which does the backward pass need for ?
- Compare the values sent per device and step under tensor parallelism versus data parallelism, and find the token count 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 be
the all-gather time of one block and its compute time. Without overlap,
blocks take ; prefetching issues the all-gather of block
while block computes.
- Show that prefetching reduces the forward pass time to , and explain why no schedule can do better than .
- Evaluate and for one block of the 36-block GPT (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.