AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
★Advanced & Frontier Topics
  1. Efficient Inference: Quantization, Distillation, Pruning and Faster Decoding
  2. Mixture of Experts: Bigger Models at the Same Compute
  3. Distributed Training: Many GPUs, One Model
  4. Interpretability: Opening the Black Box
  5. AI Safety & Ethics: Bias, Hallucination, Alignment and Regulation
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Advanced & Frontier Topics

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.

Advanced~30 min·6 references
Key terms
Distributed trainingData parallelismModel parallelismMixed-precision trainingGradient accumulationGPUBatch sizeAdam / AdamW

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.

≈
Analogy: running a restaurant chain
Data parallelism: open identical kitchens that each cook different orders, then meet every evening to agree on one improved recipe book. ZeRO/FSDP: the kitchens stop keeping a full copy of every recipe and ingredient list; each stores one section and borrows the rest when needed. Tensor parallelism: several cooks work on *the same dish* at once, each chopping part of it. Pipeline parallelism: an assembly line — one station preps, the next cooks, the next plates — with many orders flowing through.

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 ≈ (2 + 2 + 12) × Ψ bytes = 16Ψ Ψ = 7.5B → 120 GB
Ψ = number of parameters. This is the example used in the ZeRO paper.
In words: “mixed-precision Adam needs 16 bytes for every parameter”: 2 for the FP16 weights, 2 for FP16 gradients, and 12 for the FP32 optimizer copies (master weights, momentum, variance). Activations come on top.
Symbols(hover a symbol in the formula)
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
Ψ = 7.5 × 10⁹ → 16 × 7.5 × 10⁹ = 120 × 10⁹ bytes = 120 GB (more than one 80 GB GPU) Ψ = 1.3B → 16 × 1.3 = 20.8 GB — just fits on a 24 GB GPU before activations.

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.

FormatExponent / mantissa bitsMax valueNotes
FP328 / 23≈ 3.4 × 10³⁸Master weights, optimizer state
FP165 / 1065,504Needs loss scaling; more precise mantissa
BF168 / 7≈ 3.4 × 10³⁸Same range as FP32, coarser precision; no loss scaling
FP8 (E4M3 / E5M2)4/3 or 5/2448 / 57,344Needs 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.

StageWhat is shardedMemory per GPU7.5B model, 64 GPUs
Plain DDPNothing16Ψ120 GB
ZeRO-1Optimizer states4Ψ + 12Ψ/N_d31.4 GB
ZeRO-2+ gradients2Ψ + 14Ψ/N_d16.6 GB
ZeRO-3 / FSDP+ parameters16Ψ/N_d1.9 GB
Model states only (numbers from the ZeRO paper); activations come on top.

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 ≈ (p − 1) / (m + p − 1) p = pipeline stages, m = micro-batches
With p = 4 stages and m = 16 micro-batches: ≈ 16% idle time.
In words: “the share of time GPUs sit idle while the pipeline fills and drains”. Filling and draining each cost p − 1 slots, the useful work takes m slots, so more micro-batches make the idle fraction small.
Symbols(hover a symbol in the formula)
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
p = 4 stages m = 4: 3 / 7 ≈ 0.43 → 43% idle m = 16: 3 / 19 ≈ 0.16 → 16% idle m = 64: 3 / 67 ≈ 0.045 → 4.5% idle
Loading interactive…
Four strategies side by side, each with 2 GPUs. Walk through the columns and compare what each GPU holds: a full replica (data parallel), half of every matrix (tensor), a slice of the layers (pipeline), or a shard of everything (ZeRO-3/FSDP). Notice where the communication happens — all-reduce, all-gather or activations between stages.

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 = micro_batch_per_GPU × accumulation_steps × number_of_data_parallel_GPUs
8 × 4 × 8 GPUs = 256 sequences per optimizer step.
In words: “how many examples contribute to one optimizer step”. You can trade GPUs for accumulation steps and keep the same effective batch, which keeps the learning-rate schedule valid.
Symbols(hover a symbol in the formula)
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
8 per GPU × 4 accumulation steps × 8 GPUs = 256 sequences per step Only 4 GPUs available? Keep 256: 256 / (8 × 4) = 8 accumulation steps (twice as slow, same result).

The knobs

knobmicro-batch size per GPU
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.
knobgradient_accumulation_steps
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).
knobprecision (fp32 / fp16 / bf16 / fp8)
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.
knobsharding level (ZeRO stage / FSDP strategy)
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.
knobactivation checkpointing
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

python
# 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()
no_sync() avoids an all-reduce on every micro-batch; gradients are synchronised only before the optimizer step.
python
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
Swapping DDP for FSDP shards parameters, gradients and optimizer state. Newer PyTorch also offers the per-module fully_shard API (FSDP2); Hugging Face Accelerate wraps both.
!
Common pitfalls
Changing the global batch changes the optimisation: when you add GPUs, retune the learning rate and warmup. Forgetting `sampler.set_epoch()` gives every epoch the same order. Divide the loss by accumulation steps, or gradients are N× too large. BatchNorm statistics are per-GPU unless you use SyncBatchNorm. Saving checkpoints with FSDP needs a full or sharded state-dict API, otherwise each rank saves a fragment. Communication is the hidden bottleneck: tensor parallelism across nodes without fast interconnects can be slower than one node. Hangs usually mean ranks took different code paths (e.g. one rank skipped a step).
▸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

1.
Using mixed-precision Adam (16 bytes per parameter), roughly how much memory do the model states of a 3B model need on a single GPU without sharding?
2.
Why does FP16 training typically need loss scaling while BF16 usually does not?
3.
Your model fits on one GPU, but you want 8× throughput on 8 GPUs with minimal communication. Which is the simplest choice?
4.
You set micro-batch 4 and accumulation 8 on one GPU, but forget to divide the loss by 8. What happens?
5.
In a 4-stage pipeline, how can you reduce the bubble (idle) fraction?
Score: 0/5

References

  1. [1]
    Mixed Precision Training
    PaperMicikevicius et al.2017arxiv.org
  2. [2]
    ZeRO: Memory Optimizations Toward Training Trillion Parameter Models
    PaperRajbhandari et al.2019arxiv.org
  3. [3]
    PyTorch documentation — FullyShardedDataParallel
    Docsdocs.pytorch.org
  4. [4]
    Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism
    PaperShoeybi et al.2019arxiv.org
  5. [5]
    GPipe: Efficient Training of Giant Neural Networks using Pipeline Parallelism
    PaperHuang et al.2018arxiv.org
  6. [6]
    Training Deep Nets with Sublinear Memory Cost
    PaperChen et al.2016arxiv.org
← Previous
Mixture of Experts: Bigger Models at the Same Compute
Next →
Interpretability: Opening the Black Box