Foundations to Frontier
Tests
C. Programming, Tools and HPC › C6 Distributed Training

ZeRO, FSDP and DeepSpeed

Plain data parallelism keeps a full copy of the model, its gradients and its optimizer state on every GPU, which caps the model size no matter how many GPUs you have. ZeRO (Zero Redundancy Optimizer) removes that redundancy in stages: shard the optimizer states (stage 1), then the gradients (stage 2), then the parameters themselves (stage 3), gathering each layer's weights just in time and freeing them afterwards. PyTorch's FullyShardedDataParallel (FSDP) and DeepSpeed implement it, with options for offloading states to CPU or NVMe. This topic covers the memory accounting of mixed-precision Adam (16 bytes per parameter), what each stage shards and costs in communication, how FSDP's wrapping, prefetching and resharding work, and when offloading pays. In the exercises you compute per-GPU memory and communication for each stage and simulate FSDP training (shard, all-gather, reduce-scatter, sharded Adam), checking it equals ordinary data-parallel Adam; then you find the largest model each strategy can train on 8 to 1024 GPUs and when the extra communication can be hidden.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Don’t make everyone carry the whole library

Imagine a team where every member carries a complete copy of a huge encyclopedia, plus all their notes about it, plus a diary of every change. Most of that is the same for everyone, so it’s wasted weight. Instead, each person could carry only their share of the volumes and borrow a volume from a teammate for the moment they need it. ZeRO and FSDP do this for neural networks: each GPU stores only its slice of the model and its training state, and fetches the rest on demand.

Model-state memory per GPU: DDP versus ZeRO stages
80 GB GPUDDP208 GB ✗ZeRO-154 GB ✓ZeRO-229 GB ✓ZeRO-3 / FSDP3.3 GB ✓ZeRO-3 + offload813 MB ✓
blue: fp16 weights (2 B/param) · purple: fp16 gradients (2 B) · orange: optimizer states (12 B) · dashed: optimizer states offloaded to CPU memory (2.4 GB per GPU) · bars are clipped at 200 GB · activations come on top
DDP keeps a full copy of everything on every GPU, so adding GPUs never lets you train a bigger model. ZeRO-1 shards the optimizer states, ZeRO-2 also the gradients, ZeRO-3 (FSDP) also the weights, gathering each layer's weights only when it is needed: memory per GPU then falls as 16Ψ/N, at the price of 1.5× the communication.
Why engineers care

Fine-tuning or training models of tens of billions of parameters (foundation models for imagery, weather, language) on a modest cluster is only possible with sharding. FSDP is also the simplest way to train models that are slightly too big for one GPU without redesigning them for tensor or pipeline parallelism.

📝 Quick check (Level 0)
0/3 answered
  1. 1. What does ZeRO remove?
  2. 2. With full sharding, a GPU that needs a layer's weights…
  3. 3. In the demo, which strategy's memory per GPU doesn't shrink with more GPUs?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Where the memory goes

Mixed-precision Adam (C5.5) keeps, per parameter: 2 bytes of fp16/bf16 weights, 2 bytes of gradients, and 12 bytes of optimizer state (4 bytes fp32 master weights, 4 momentum, 4 variance): 16 bytes per parameter. A 7.5B-parameter model needs 120 GB of model states before any activations, more than an 80 GB GPU.

Strategy shards memory per GPU (N GPUs) communication per step
DDP nothing 16Ψ 2Ψ (all-reduce)
ZeRO-1 optimizer states 4Ψ + 12Ψ/N 2Ψ
ZeRO-2 + gradients 2Ψ + 14Ψ/N 2Ψ
ZeRO-3 / FSDP + parameters 16Ψ/N 3Ψ

For 7.5B parameters on 64 GPUs: 120, 31.4, 16.6 and 1.9 GB.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Bytes of model state per parameter for mixed-precision Adam?
  2. 2. ZeRO-2 shards…
  3. 3. ZeRO-3 communication compared with DDP?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

How ZeRO-3 / FSDP works

Parameters are flattened and split into N equal shards (padded). Each rank keeps its shard of the weights, gradients and optimizer state. For each wrapped unit (typically a transformer block):

  1. all-gather the unit’s full weights before its forward pass; free the non-local shards afterwards;
  2. all-gather again before its backward pass;
  3. reduce-scatter the gradients: each rank receives the averaged gradient for its own shard;
  4. each rank updates its shard with its own optimizer state.

Since an all-reduce is a reduce-scatter followed by an all-gather, data parallelism’s traffic (2Ψ) is reorganized, plus one extra all-gather (3Ψ total). Prefetching the next unit’s weights overlaps communication with computation; wrapping granularity trades peak memory (one unit’s full weights) against the number of collectives.

from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, ShardingStrategy, MixedPrecision
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
model = FSDP(model, sharding_strategy=ShardingStrategy.FULL_SHARD,           # ZeRO-3 (SHARD_GRAD_OP ≈ ZeRO-2)
             auto_wrap_policy=functools.partial(transformer_auto_wrap_policy, transformer_layer_cls={Block}),
             mixed_precision=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32),
             device_id=torch.cuda.current_device())
🐍 Exercise 1: ZeRO accounting and a simulated FSDP
Compute per-GPU model-state memory and per-step communication for DDP and ZeRO stages 1-3; flatten, pad and shard parameters; simulate FSDP training of an MLP (all-gather the weights, per-rank gradients, reduce-scatter, Adam on each shard with its own state) and check it equals data-parallel Adam on full replicas for several rank counts; compute peak resident weights with per-layer gathering.
📝 Quick check (Level 2)
0/3 answered
  1. 1. In FSDP, gradients are combined with…
  2. 2. Why wrap each transformer block as an FSDP unit?
  3. 3. Is FSDP training numerically the same as DDP?

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Choosing a strategy

  • ZeRO-1/2 keep full weights on every GPU, so their memory saturates at 4Ψ (or 2Ψ) per GPU: helpful for medium models with little extra communication.
  • ZeRO-3 / FSDP scales model size linearly with GPUs but adds 50% communication; it needs enough computation per GPU (tokens per GPU per step) to hide the gathers, and it is often combined with tensor parallelism inside nodes (hybrid sharding: shard within a node, replicate across nodes).
  • Offloading (ZeRO-Offload, ZeRO-Infinity) moves optimizer states (and the optimizer step) to CPU memory or NVMe: larger models per GPU at the cost of PCIe traffic, useful when GPUs are few.
  • Activations are not sharded by ZeRO; combine with activation checkpointing (C6.4) and sequence parallelism for long contexts.

DeepSpeed configures all of this in a JSON file ("zero_optimization": {"stage": 3, "offload_optimizer": {"device": "cpu"}}); PyTorch FSDP2 (fully_shard) works on DTensor shards per parameter.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Why does ZeRO-1 stop helping beyond a certain model size, however many GPUs you add?
  2. 2. ZeRO-3's extra communication is easiest to hide when…
  3. 3. Hybrid sharding means…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Sharding, measured

Exercise 1. For 7.5B parameters on 64 GPUs the formulas give 120, 31.4, 16.6 and 1.88 GB per GPU for DDP and stages 1-3, the figures of the ZeRO paper; stage 3 sends 1.5× the elements of stage 1. A simulated FSDP training of a 5-16-3 MLP (flattened, padded and sharded across 2, 4 or 7 ranks, all-gather, reduce-scatter, Adam per shard) matches data-parallel Adam on full replicas to 10⁻¹², with each rank holding 1/N of the optimizer state. Gathering one 400M-parameter block at a time (with one prefetched) keeps 2 blocks resident instead of 32.

Exercise 2: how far each strategy scales. Largest model whose states fit, with 60 GB of each 80 GB GPU available for model states and 128 GB of host memory per GPU for offloading:

GPUs DDP ZeRO-1 ZeRO-2 ZeRO-3 / FSDP ZeRO-3 + CPU offload
8 3.8B 10.9B 16.0B 30B 85B
64 3.8B 14.3B 27.0B 240B 683B
512 3.8B 14.9B 29.6B 1.9T 5.5T
1024 3.8B 15.0B 29.8B 3.8T 10.9T

DDP never grows; ZeRO-1 and ZeRO-2 saturate at 15B and 30B (their unsharded weights and gradients); only stage 3 scales with the GPU count. For a 13B model on 64 GPUs (25 GB/s per GPU, 50% kernel efficiency), communication is 2.0× (ZeRO-1) and 3.0× (ZeRO-3) the computation at 2048 tokens per GPU per step, but 0.25× and 0.37× at 16 384 tokens: large per-GPU batches make sharding’s traffic hideable behind compute. Gathering per layer keeps peak resident weights at 4.6 GB versus 29 GB when gathering the whole model at once. Activations, which ZeRO doesn’t shard, come on top of all these numbers.

🐍 Exercise 2 (research): how far each strategy scales
Compute per-GPU GPU and host memory for DDP, ZeRO-1, ZeRO-2, ZeRO-3 and ZeRO-3 with CPU offload; find by bisection the largest model each can hold on 8 to 1024 GPUs; compare communication with computation per step for small and large per-GPU batches; compute FSDP's peak memory with per-layer gathering.

Sharding in AI, robotics and aerospace

  • Fine-tuning foundation models (vision, weather, language) on a few nodes with FSDP and LoRA-style adapters.
  • Training large scientific surrogates whose parameters exceed one GPU without restructuring the code for tensor parallelism.
  • DeepSpeed and FSDP underpin most open large-model training recipes, often combined with tensor and pipeline parallelism.
  • Offloading enables experimentation with large models on a single multi-GPU workstation.

References

  1. S. Rajbhandari, J. Rasley, O. Ruwase, Y. He (2020). “ZeRO: memory optimizations toward training trillion parameter models.” SC20.
  2. J. Ren et al. (2021). “ZeRO-Offload: democratizing billion-scale model training.” USENIX ATC.
  3. S. Rajbhandari et al. (2021). “ZeRO-Infinity: breaking the GPU memory wall for extreme scale deep learning.” SC21.
  4. Y. Zhao et al. (2023). “PyTorch FSDP: experiences on scaling fully sharded data parallel.” Proc. VLDB Endowment, 16(12).
  5. DeepSpeed documentation (deepspeed.ai): ZeRO, configuration JSON.