Distributed Training: Many GPUs, One Model
Where training memory goes, and the techniques that let large models train on many GPUs: mixed precision, data parallelism, ZeRO/FSDP sharding, tensor and pipeline parallelism, gradient accumulation and activation checkpointing.
A single modern GPU has 24–192 GB of memory. Training a 7B-parameter model with Adam needs over 100 GB before counting activations, and frontier models are trained for months on thousands of GPUs. Distributed training solves two problems at once: memory (the model and its training state do not fit on one device) and time (one device would take years). Even if you never pretrain a giant model, these tools — mixed precision, FSDP, gradient accumulation, checkpointing — are what make fine-tuning a 7B–70B model on rented GPUs feasible.
Where training memory goes
With mixed-precision Adam, each parameter needs 2 bytes (FP16/BF16 weights) + 2 bytes (gradients) + 12 bytes of optimizer state (an FP32 master copy, momentum and variance) = 16 bytes. A 7.5B model therefore needs 120 GB for model states alone. On top come activations saved for the backward pass, which scale with batch size × sequence length × layers × hidden size, and often dominate for long sequences.
- model states
- parameters + gradients + optimizer states (not activations)
- (2 + 2 + 12)
- bytes per parameter: FP16 weight + FP16 gradient + 3 × 4-byte FP32 Adam states
- Ψ
- psi, the number of parameters
- 16Ψ
- total bytes: 16 per parameter
- ≈
- approximately (ignores small buffers)
▸Worked example
1. Mixed precision
Mixed-precision training (Micikevicius et al., 2017)[1] runs most matrix multiplications in 16-bit floats — 2× less memory traffic and much faster on Tensor Cores — while keeping an FP32 master copy of the weights for the update. FP16 has a narrow range: small gradients underflow to zero, so FP16 training uses loss scaling (multiply the loss by e.g. 2¹⁶ before backward, divide gradients after; skip steps that overflow). BF16 keeps FP32's 8-bit exponent and range, so it usually needs no loss scaling — the default on A100/H100-class GPUs. FP8 is the next step on Hopper-class hardware.
| Format | Exponent / mantissa bits | Max value | Notes |
|---|---|---|---|
| FP32 | 8 / 23 | ≈ 3.4 × 10³⁸ | Master weights, optimizer state |
| FP16 | 5 / 10 | 65,504 | Needs loss scaling; more precise mantissa |
| BF16 | 8 / 7 | ≈ 3.4 × 10³⁸ | Same range as FP32, coarser precision; no loss scaling |
| FP8 (E4M3 / E5M2) | 4/3 or 5/2 | 448 / 57,344 | Needs per-tensor scaling; newest GPUs |
2. Data parallelism
In data parallelism every GPU holds a full replica of the model and processes a different slice of the batch. After the backward pass, gradients are averaged across GPUs with an all-reduce (PyTorch DistributedDataParallel overlaps this communication with backward computation), so every replica takes the identical optimizer step. It scales throughput nearly linearly — but it does not reduce per-GPU memory at all, since each GPU still holds all 16Ψ bytes.
3. ZeRO and FSDP: shard the redundancy
ZeRO (Rajbhandari et al., 2019)[2] noticed that data parallelism stores N identical copies of everything. It shards model states across the N_d data-parallel GPUs in three stages, gathering pieces just in time and freeing them afterwards. PyTorch's Fully Sharded Data Parallel (FSDP)[3] implements the stage-3 idea natively; DeepSpeed implements all stages. More sharding means less memory but more communication.
| Stage | What is sharded | Memory per GPU | 7.5B model, 64 GPUs |
|---|---|---|---|
| Plain DDP | Nothing | 16Ψ | 120 GB |
| ZeRO-1 | Optimizer states | 4Ψ + 12Ψ/N_d | 31.4 GB |
| ZeRO-2 | + gradients | 2Ψ + 14Ψ/N_d | 16.6 GB |
| ZeRO-3 / FSDP | + parameters | 16Ψ/N_d | 1.9 GB |
4. Model parallelism: tensor and pipeline
Model parallelism splits the model itself. Tensor parallelism (Megatron-LM, Shoeybi et al., 2019)[4] splits individual matrix multiplications: in an MLP block the first weight matrix is split by columns and the second by rows, so each GPU computes its slice and a single all-reduce combines the result; attention heads are split the same way. It needs very fast links (NVLink), so it is usually kept inside one node of 8 GPUs. Pipeline parallelism (GPipe, Huang et al., 2018)[5] assigns consecutive layers to different GPUs and streams micro-batches through them; idle time at the start and end of each batch — the bubble — shrinks as the number of micro-batches grows. Large runs combine data, tensor and pipeline parallelism (3D parallelism), plus sequence/context and expert parallelism.
- bubble fraction
- fraction of total pipeline time that is idle
- p
- number of pipeline stages (GPUs in the pipeline)
- m
- number of micro-batches per batch
- ≈
- approximately (assumes equal-cost stages)
▸Worked example
5. Gradient accumulation and activation checkpointing
Gradient accumulation runs several small micro-batches, summing their gradients, before taking one optimizer step — mathematically equivalent to a bigger batch (except for batch-dependent layers like BatchNorm). It lets a single 24 GB GPU train with an effective batch of hundreds of sequences, at the cost of time. Activation checkpointing (Chen et al., 2016)[6] stores only some activations during the forward pass and recomputes the rest during backward, trading roughly one extra forward pass (~30% more compute) for a large drop in activation memory.
- effective batch
- examples (or sequences) per optimizer step
- micro_batch_per_GPU
- examples one GPU processes in one forward/backward pass (limited by memory)
- accumulation_steps
- micro-batches whose gradients are summed before stepping
- number_of_data_parallel_GPUs
- data-parallel replicas
- ×
- multiply
▸Worked example
The knobs
- What it is
- Samples each GPU processes in one forward/backward pass.
- ↑ If you increase it
- Better GPU utilisation and fewer steps, until you hit out-of-memory (activations grow linearly).
- ↓ If you decrease it
- Fits in memory, but small matrix multiplications waste GPU throughput; compensate with gradient accumulation.
- Typical values
- The largest that fits, often 1–16 sequences for LLM fine-tuning.
- What it is
- Micro-batches summed before each optimizer step.
- ↑ If you increase it
- Larger effective batch with no extra memory: smoother gradients, but fewer updates per epoch and proportionally longer wall-clock per step. Retune the learning rate.
- ↓ If you decrease it
- More frequent, noisier updates.
- Typical values
- Chosen so the effective batch matches a recipe (e.g. 64–1024 sequences).
- What it is
- Number format for forward/backward computation.
- ↑ If you increase it
- Higher precision (FP32): most numerically safe, but ~2× memory traffic and much slower on Tensor Cores.
- ↓ If you decrease it
- BF16/FP16: ~2× faster with half the activation memory; FP16 needs loss scaling; FP8 needs careful scaling recipes.
- Typical values
- BF16 autocast with FP32 master weights.
- What it is
- How much of the model state is split across data-parallel GPUs.
- ↑ If you increase it
- Lower memory per GPU (fit bigger models or batches), but more all-gather/reduce-scatter traffic; slower across slow inter-node links.
- ↓ If you decrease it
- Less communication, faster when the model already fits.
- Typical values
- DDP if it fits; ZeRO-2 or FSDP SHARD_GRAD_OP next; full sharding (ZeRO-3 / FULL_SHARD) for the largest models.
- What it is
- Whether (and how many) layers recompute activations during backward instead of storing them.
- ↑ If you increase it
- Checkpoint more layers: much less activation memory (longer sequences, bigger batches), ~20–35% slower steps.
- ↓ If you decrease it
- Faster steps, but activation memory may cause out-of-memory errors.
- Typical values
- On for LLM fine-tuning (gradient_checkpointing=True in HF Trainer).
In code: DDP + bf16 + gradient accumulation
# launch with: torchrun --nproc_per_node=4 train.py
import os, contextlib, torch, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
dist.init_process_group("nccl")
rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(rank)
model = DDP(MyModel().cuda(rank), device_ids=[rank]) # MyModel/dataset/loss_fn: yours
sampler = DistributedSampler(dataset, shuffle=True)
loader = DataLoader(dataset, batch_size=8, sampler=sampler)
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.1)
accum = 4 # effective batch = 8 x 4 x 4 GPUs = 128
for epoch in range(3):
sampler.set_epoch(epoch) # different shuffle each epoch
for step, (x, y) in enumerate(loader):
x, y = x.cuda(rank), y.cuda(rank)
last = (step + 1) % accum == 0
ctx = contextlib.nullcontext() if last else model.no_sync() # skip all-reduce
with ctx:
with torch.autocast("cuda", dtype=torch.bfloat16):
loss = loss_fn(model(x), y) / accum
loss.backward() # backward outside autocast
if last:
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
opt.zero_grad(set_to_none=True)
dist.destroy_process_group()from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision
bf16 = MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.bfloat16,
buffer_dtype=torch.bfloat16)
model = FSDP(MyModel(), mixed_precision=bf16, device_id=torch.cuda.current_device())
# Hugging Face models: model.gradient_checkpointing_enable() to turn on activation checkpointing▸Go deeper: ring all-reduce and why its cost does not grow with GPU count
In a ring all-reduce over N GPUs, the gradient buffer is split into N chunks. In N − 1 reduce-scatter steps, each GPU sends one chunk to its neighbour and adds the chunk it receives; afterwards each GPU owns the full sum of one chunk. N − 1 all-gather steps then circulate the finished chunks. Each GPU sends about 2·(N − 1)/N × the buffer size in total — nearly independent of N — which is why data parallelism scales well when bandwidth is good. ZeRO-3/FSDP replace the all-reduce with a reduce-scatter (gradients) plus all-gathers (parameters before each layer), about 1.5× the communication volume of plain DDP.
Quiz
References
- [1]Mixed Precision TrainingPaperMicikevicius et al.2017arxiv.org
- [2]ZeRO: Memory Optimizations Toward Training Trillion Parameter ModelsPaperRajbhandari et al.2019arxiv.org
- [3]PyTorch documentation — FullyShardedDataParallelDocsdocs.pytorch.org
- [4]Megatron-LM: Training Multi-Billion Parameter Language Models Using Model ParallelismPaperShoeybi et al.2019arxiv.org
- [5]GPipe: Efficient Training of Giant Neural Networks using Pipeline ParallelismPaperHuang et al.2018arxiv.org
- [6]Training Deep Nets with Sublinear Memory CostPaperChen et al.2016arxiv.org