Estimate per-GPU memory under ZeRO stages 0 to 3

ZeRO (Rajbhandari et al.) removes the redundant copies that plain data parallelism keeps on every GPU by sharding them across the N data-parallel ranks. Stage 1 shards optimizer states, stage 2 also shards gradients, stage 3 also shards the parameters. Picking the stage is a memory-versus-communication trade-off.

Model state for mixed-precision Adam with P parameters, in bytes: fp16 parameters 2P, fp16 gradients 2P, optimizer states K * P (K = 12 by default: fp32 master weights, momentum, variance).
- stage 0: 2P + 2P + K P
- stage 1: 2P + 2P + K P / N
- stage 2: 2P + (2 + K) P / N
- stage 3: (2 + 2 + K) P / N

Write zero_memory(num_params, num_gpus, budget_gb, k=12). Return (gb, best) where gb is a list of the four per-GPU sizes in GB (1 GB = 1e9 bytes) for stages 0..3, and best is the LOWEST stage whose size is <= budget_gb (lower stages communicate less), or -1 if none fits. Activations are ignored.

Signaturedef zero_memory(num_params, num_gpus, budget_gb, k=12)

Example

1e9 params, 8 GPUs, budget 10: gb = [16.0, 5.5, 3.75, 2.0], best = 1.

Understand the idea

Plain data parallelism keeps a full copy of weights, gradients and optimizer state on every GPU. ZeRO removes that waste by splitting pieces across the N GPUs: stage 1 splits optimizer state, stage 2 also splits gradients, stage 3 also splits the weights. More splitting saves memory but adds communication. With mixed-precision Adam: 2 bytes per parameter for fp16 weights, 2 for gradients, K = 12 for optimizer state. Worked example: P = 7e9, N = 8, budget 30 GB. Stage 0: 16 * 7e9 = 112 GB. Stage 1: 4P + 12P / 8 = 28 + 10.5 = 38.5 GB. Stage 2: 2P + 14P / 8 = 14 + 12.25 = 26.25 GB. Stage 3: 16P / 8 = 14 GB. The lowest stage within 30 GB is 2. Rule: s0 = (2 + 2 + K) P, s1 = 4P + KP / N, s2 = 2P + (2 + K) P / N, s3 = (4 + K) P / N, converted with 1 GB = 1e9 bytes; best = first stage <= budget, else -1. Activations are ignored. Used when sizing large-model training with DeepSpeed or FSDP.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: worked examplezero_memory(1e9, 8, 10)
  • Sample 2: 7B on 64 GPUs, 40 GBzero_memory(7e9, 64, 40)