Chapter 40 of 42 · ~20 min read & lab+80 XP
Chapter 40 · Deep Learning

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!

Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

Understanding Gradient Accumulation, DDP, and FSDP is mandatory for training modern Vision Transformers and multi-billion-parameter models.

Data Scientist

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!

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

If you accumulate gradients across K = 4 micro-batches WITHOUT dividing loss by 4, what happens to your effective gradient?

What You Will Master in This Chapter
  • 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/param in 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)
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
Beff=Bmicro×Kaccum×NGPUB_{\text{eff}} = B_{\text{micro}} \times K_{\text{accum}} \times N_{\text{GPU}}Say aloud:“Effective batch size equals micro-batch times accumulation steps times number of GPUs”
Plain-English Meaning
Exact macro-batch size formula governing optimization dynamics across single-GPU accumulation and multi-GPU DDP/FSDP!
Everyday Example
B_micro=8 × K=4 × 8 GPUs = 256 effective batch size.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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 NN equal chapters (1 per GPU) and passes each page around just-in-time when needed!

1. Gradient Accumulation (1-GPU Macro-Batches)

Gradient Accumulation: Large Effective Batch on 1 GPUMicro-Batch 1..K(loss / K).backward()Accumulate .gradNo optimizer.step() yetEvery K-th Stepopt.step() + zero_grad() ✓Effective Batch Size = B_micro × K × Num_GPUs!
Gradient Accumulation simulates a large macro-batch (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

DistributedDataParallel (DDP): Replicated Model + Ring All-ReduceGPU 0..N CopiesEach gets unique shardOverlapped BackwardRing All-Reduce bucketsSynced Update ✓Identical weights on all GPUs
DistributedDataParallel (DDP) replicates the model across N GPUs, runs independent mini-batches, and overlaps Ring All-Reduce gradient averaging directly with backward!

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

ZeRO / PyTorch FSDP Memory Sharding Across N GPUsZeRO-1Shard Optimizer States (4×)ZeRO-2+ Shard Gradients (8×)ZeRO-3 / FSDP ✓+ Shard Model Weights (N×)FSDP All-Gathers weights just-in-time for each layer, then frees them immediately!
ZeRO / PyTorch FSDP shards Optimizer States (Stage 1), Gradients (Stage 2), and Model Weights (Stage 3) across GPUs — slashing per-GPU memory by up to N×!

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!
Animated Mini-Lab • Distributed Training

Per-GPU Model+Optimizer VRAM (3B Param Model)

VRAM per GPU: 12 GB (Fits on 24GB GPU ✓)
Pause & Check · Quick Intuition Pulse

In mixed-precision AdamW training, why does a 1-billion-parameter model need ~16 GB of VRAM before activations?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS PyTorch FSDP All-Gather → Compute → Reduce-Scatter cycle.
Interactive Animation • Distributed Systems Deep Lab

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.

Step 1 / 4
1. Weights, grads & AdamW states stay sharded 1/N across all GPUs
2. Before Layer L forward: All-Gather full Layer L weights across GPUs
3. Run Layer L compute → immediately discard non-owned shards!
4. Backward: Reduce-Scatter gradients & update local 1/N optimizer shard ✓
0%
Stage 1 / 4
Intuition Takeaway: Scale training cleanly with Gradient Accumulation (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!
Where This Powers Real ML, Deep Learning & Generative AI

Multi-GPU Cloud & Cluster Training (torchrun)

Powers scalable training from 4-GPU workstations to 1,024-GPU foundation-model clusters.

Production NumPy & PyTorch Code Patterns
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)")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting sampler.set_epoch(epoch) when using DistributedSampler in DDP.
Best Practice: Without sampler.set_epoch(epoch), every GPU sees the exact same data order on every epoch instead of reshuffling!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1Approximately how much model + gradient + optimizer VRAM does a 3B-parameter model need per GPU under FSDP (ZeRO-3) across 4 GPUs?

Apply What You Learned — Solve Matching Coding Problems