Distributed Deep Learning: Gradient Accumulation, DDP All-Reduce, ZeRO & PyTorch FSDP
Scaling from 1 GPU to 8, 64, or 1,000 GPUs: simulating giant batches with Gradient Accumulation, why DDP crushes legacy DataParallel via Ring All-Reduce, and slashing VRAM N× with ZeRO / PyTorch FSDP!
A 3-billion-parameter model needs ~48 GB just for weights + gradients + AdamW states — it won't even fit on a 24GB GPU with DDP, unless you shard it with ZeRO / FSDP!
Understanding Gradient Accumulation, DDP, and FSDP is mandatory for training modern Vision Transformers and multi-billion-parameter models.
One quick VRAM calculation (16 bytes × params / N_GPUs) tells you instantly whether a model fits on your cluster before spinning up expensive cloud nodes!
Classic ML Infra interview question: 'Why is DDP faster than DataParallel, and how does ZeRO-3 / FSDP fit a 48GB model onto four 24GB GPUs?'
If you accumulate gradients across K = 4 micro-batches WITHOUT dividing loss by 4, what happens to your effective gradient?
- Implement Gradient Accumulation cleanly (
(loss / K).backward()) to hit large effective batch sizes on 1 GPU - Explain why DistributedDataParallel (DDP) beats
nn.DataParallel(multi-process, no Python GIL, overlapped Ring All-Reduce) - Compute exact AdamW training VRAM (
~16 bytes/paramin mixed precision) and see why DDP OOMs on large models - Contrast ZeRO Stages 1, 2, 3 and PyTorch FSDP (All-Gather → Compute → Discard → Reduce-Scatter)
B_micro=8 × K=4 × 8 GPUs = 256 effective batch size.DDP gives every GPU its own full textbook and has them average their notes after every page (Ring All-Reduce). FSDP (ZeRO-3) tears the giant textbook into equal chapters (1 per GPU) and passes each page around just-in-time when needed!
1. Gradient Accumulation (1-GPU Macro-Batches)
B_eff = B_micro × K) on 1 GPU by accumulating .grad across K micro-batches before calling optimizer.step() once!When your desired batch size 256 OOMs GPU VRAM, run K = 8 micro-batches of 32, calling (loss / K).backward() on each, and call optimizer.step(); optimizer.zero_grad() only once every K steps!
2. DistributedDataParallel (DDP) & Ring All-Reduce
Never use legacy single-process nn.DataParallel (Python GIL bottleneck + GPU 0 VRAM spike!). DDP spawns 1 process per GPU and overlaps Ring All-Reduce gradient averaging directly with the backward pass — achieving near-linear multi-GPU scaling!
3. ZeRO Stages 1–3 & PyTorch FSDP Sharding
DDP duplicates all 16 bytes/param on every GPU. ZeRO / FSDP eliminates redundancy progressively:
- Stage 1: Shard Optimizer States (
4×memory cut) - Stage 2: + Shard Gradients (
8×cut) - Stage 3 (FSDP): + Shard Model Parameters (
N×cut!), All-Gathering each layer just-in-time!
Per-GPU Model+Optimizer VRAM (3B Param Model)
In mixed-precision AdamW training, why does a 1-billion-parameter model need ~16 GB of VRAM before activations?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
If your entire model + optimizer states fit comfortably on 1 GPU, DDP is faster (less communication). Once the model exceeds single-GPU VRAM, switch to PyTorch FSDP / ZeRO-3!
PyTorch FSDP / ZeRO-3 All-Gather → Compute → Reduce-Scatter Cycle
Watch sharded parameters materialize just-in-time per layer so giant models fit on smaller GPUs.
loss / K), DDP Ring All-Reduce when the model fits on 1 GPU, and PyTorch FSDP / ZeRO-3 (16·P / N bytes/GPU) when it doesn't!Multi-GPU Cloud & Cluster Training (torchrun)
Powers scalable training from 4-GPU workstations to 1,024-GPU foundation-model clusters.
import torch
import torch.nn as nn
# Gradient Accumulation: simulate large global batch size on a single GPU
model = nn.Sequential(nn.Linear(32, 64), nn.GELU(), nn.Linear(64, 4))
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
accum_steps = 4 # effective_batch = micro_batch * accum_steps
optimizer.zero_grad(set_to_none=True)
for step in range(1, accum_steps + 1):
xb, yb = torch.randn(8, 32), torch.randint(0, 4, (8,))
# Divide loss by accum_steps so summed gradients match the full-batch average
loss = nn.functional.cross_entropy(model(xb), yb) / accum_steps
loss.backward()
if step % accum_steps == 0:
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
optimizer.zero_grad(set_to_none=True)
print(f"Optimizer stepped once after {accum_steps} micro-batches (eff. batch=32)")
sampler.set_epoch(epoch) when using DistributedSampler in DDP.sampler.set_epoch(epoch), every GPU sees the exact same data order on every epoch instead of reshuffling!