On this page
Two 8-GPU nodes give you sixteen 80 GB accelerators: 1,280 GB of aggregate HBM. Launch a 70B mixed-precision AdamW job with PyTorch Distributed Data Parallel (DDP), and it crashes immediately. Even one BF16 copy of 70B weights takes 140 GB, overflowing every 80 GB GPU before a single gradient, optimizer moment, or activation exists. Because DDP replicates the full model state on every rank, adding GPUs merely duplicates the bottleneck.
Fully Sharded Data Parallel (FSDP) and DeepSpeed ZeRO (Zero Redundancy Optimizer) unlock aggregate HBM by partitioning optimizer states, gradients, and parameters across data-parallel ranks, trading redundant memory for structured collective communication.[1][2]
The memory wall in numbers
Under the classic mixed-precision AdamW recipe, each parameter carries 16 bytes of model state before activations, communication buckets, or allocator overhead:[1]
| Tensor | Bytes / param | Role |
|---|---|---|
| Compute weight (BF16/FP16) | 2 | Forward and backward Tensor Core matmuls |
| Gradient (BF16/FP16) | 2 | Gradient awaiting optimizer step (4 B if FP32 grad accum) |
| FP32 master parameter | 4 | Full-precision weights preserving small updates |
| FP32 Adam moments () | 8 | Running mean of gradients and uncentered squared gradients |
| Total | 16 | Model state only (18 B with FP32 grad accum) |
Two subtleties break naive budgets. First, BF16 compute does not force BF16 gradient accumulation: setting data_types.grad_accum_dtype: "fp32" in DeepSpeed raises the ZeRO master-weight layout from 16 to 18 bytes/param.[3] Second, FP32 master weights exist because subtracting 1e-4 from 1.0 rounds back to 1.0 in FP16 and BF16 while surviving in FP32 (though even FP32 loses decrements below half its gap, such as 1e-8):
import torch
for name, dtype in (("FP16", torch.float16), ("BF16", torch.bfloat16), ("FP32", torch.float32)):
w = torch.tensor(1.0, dtype=dtype)
gap = (w - torch.nextafter(w, torch.tensor(0.0, dtype=dtype))).item()
print(f"{name}: gap={gap:.3e}, 1e-8={(w.float()-1e-8).to(dtype).item()!=1.0}, 1e-4={(w.float()-1e-4).to(dtype).item()!=1.0}")FP16: gap=4.883e-04, 1e-8=False, 1e-4=False
BF16: gap=3.906e-03, 1e-8=False, 1e-4=False
FP32: gap=5.960e-08, 1e-8=False, 1e-4=TrueAt 70B parameters, 16 bytes/param totals 1,120 GB: 140 GB weights, 140 GB gradients, and 840 GB (75%) in FP32 master weights and Adam moments.

Why DDP hits a limit (and uneven token weighting)
DDP replicates the full model on every GPU, feeds each rank a different batch slice, and averages gradients via bucketed all-reduce overlapped with backward compute.[4] When packed or response-masked batches give rank an unequal count of supervised tokens across ranks, default DDP averages each rank's local mean equally rather than every token equally. Scaling rank 's local mean by (summed across microbatches and ranks) recovers the exact pooled token-mean gradient:
import torch
targets = [torch.tensor([1.0]), torch.tensor([3.0, 3.0, 3.0])]
counts, ranks = [t.numel() for t in targets], len(targets)
total = sum(counts)
def rank_grad(t, mult):
w = torch.tensor(0.0, requires_grad=True)
return torch.autograd.grad((w - t).square().mean() * mult, w)[0]
naive = torch.stack([rank_grad(t, 1.0) for t in targets]).mean()
weighted = torch.stack([rank_grad(t, ranks * c / total) for t, c in zip(targets, counts)]).mean()
w = torch.tensor(0.0, requires_grad=True)
pooled = torch.autograd.grad((w - torch.cat(targets)).square().mean(), w)[0]
print(f"naive={naive.item():.1f} | token_weighted_DDP={weighted.item():.1f} | pooled={pooled.item():.1f}")naive=-4.0 | token_weighted_DDP=-5.0 | pooled=-5.0![At w=0 with squared-error loss, rank 0 has one target [1] (local mean gradient -2) and rank 1 has three targets [3, 3, 3] (local mean gradient -6). Equal-rank averaging gives (-2-6)/2 = -4, skewing toward sparse rank 0. Scaling each rank by N * n_r / total (0.5 and 1.5) gives (-1-9)/2 = -5, matching the exact four-target pooled mean.](https://assets.leetllm.com/v1/7542bfdaf6a6/training/distributed-training-fsdp-deepspeed-zero/illustrations/_generated/ddp_token_weighting_dark.png)
ZeRO stages: sharding state and preserving Adam math
For parameters owned by a data-parallel group of ranks with bytes/param for compute weights, gradients, and optimizer-plus-master state, each ZeRO stage shards one more buffer:[1]

- ZeRO-1 shards optimizer states ( of the 12-byte block), updating owned slices and all-gathering updated weights.
- ZeRO-2 also shards gradients via reduce-scatter during backward so unowned gradients are discarded immediately, followed by an all-gather of updated weights.
- ZeRO-3 shards parameters too: forward all-gathers each layer on demand and frees it afterward; backward re-gathers weights, reduce-scatters gradient shards, and releases full buffers.
Why can't ranks run local Adam updates and average weights afterward? Because Adam's second moment squares the gradient:[5] for gradients 1 and 3, reducing first yields , while squaring locally and averaging yields . ZeRO preserves exact Adam math by always reducing gradients first so the owner updates once on the averaged slice.
In ZeRO-3, remember live working sets: each rank retains its local shard while allocating a separate padded gather buffer for the active layer (plus another if prefetching).[6] Also remember sharding shrinks model state, not activations; pair with activation checkpointing for long sequences.
import numpy as np
def per_rank_gb(params_b: int, ranks: int, p: int, g: int, o: int) -> dict[str, float]:
return {"DP": params_b*(p+g+o), "Z1": params_b*(p+g+o/ranks),
"Z2": params_b*(p+(g+o)/ranks), "Z3": params_b*(p+g+o)/ranks}
print("70B/256r (16B BF16 grad):", {k: round(v, 2) for k, v in per_rank_gb(70, 256, 2, 2, 12).items()})
print("70B/256r (18B FP32 grad):", {k: round(v, 2) for k, v in per_rank_gb(70, 256, 2, 4, 12).items()})
sizes, ranks = np.array([8, 8, 8, 8]), 4
shards = np.ceil(sizes / ranks).astype(int)
for live in ([], [0], [0, 1]):
g = int(np.sum(shards[live] * ranks)) if live else 0
print(f"live={len(live)}: shards={int(shards.sum())} + gathered={g} = {int(shards.sum())+g} elems")70B/256r (16B BF16 grad): {'DP': 1120, 'Z1': 283.28, 'Z2': 143.83, 'Z3': 4.38}
70B/256r (18B FP32 grad): {'DP': 1260, 'Z1': 423.28, 'Z2': 144.38, 'Z3': 4.92}
live=0: shards=8 + gathered=0 = 8 elems
live=1: shards=8 + gathered=8 = 16 elems
live=2: shards=8 + gathered=16 = 24 elemsCommunication collectives and the 1.5x heuristic
NCCL implements three collective building blocks across GPUs:[7]
| Primitive | Operation | Ring bytes sent / rank | Primary role |
|---|---|---|---|
| All-reduce | Sums tensors across ranks; every rank gets the full sum | DDP gradient sync, TP RowParallel | |
| Reduce-scatter | Sums tensors across ranks; each rank keeps its slice | ZeRO-2/3 and FSDP gradient reduction | |
| All-gather | Reconstructs the full tensor on every rank from shards | ZeRO-3 / FSDP parameter materialization |
Here is the full tensor size. Algebraically, .
![Three two-rank collective primitives: All-Reduce sums [1, 2] and [10, 20] and gives both ranks [11, 22] at 2(N-1)/N * S ring volume; Reduce-Scatter sums and partitions so rank 0 keeps [11] at index 0 and rank 1 keeps [22] at index 1 at (N-1)/N * S; All-Gather reconstructs [11, 22] on both ranks from those shards at (N-1)/N * S.](https://assets.leetllm.com/v1/0c685bc7b2f5/training/distributed-training-fsdp-deepspeed-zero/illustrations/_generated/collective_primitives_map_dark.png)
Interconnect hierarchy sets placement: intra-node NVLink quotes 900 GB/s bidirectional per GPU on DGX H100 and 1,800 GB/s on B200 (with GB200 NVL72 spanning 72 GPUs),[8][9] while inter-node InfiniBand / RoCE (ConnectX-7 400 Gb/s, ConnectX-8 800 Gb/s) delivers 50–100 GB/s unidirectional per port via GPUDirect RDMA.[10][11] Keep frequent per-layer collectives (tensor parallelism) inside NVLink and place coarser data-parallel or pipeline boundaries across nodes.
With equal BF16 parameter and gradient widths ( elements), DDP and ZeRO-2 move per rank while ZeRO-3 / full-shard FSDP moves (forward gather + backward gather + backward reduce-scatter), yielding the classic 1.5x volume ratio.[1] Using BF16 gathers (140 GB) with FP32 reductions (280 GB) drops the modeled byte ratio to 1.0x, yet volume is not elapsed time: small unhidden layer gathers on higher-latency networks stall compute far more than coarse buckets:
param_gb, grad_gb, ranks = 140, 140, 256
ring = (ranks - 1) / ranks
ddp_gb = 2 * grad_gb * ring
zero3_gb = (2 * param_gb + grad_gb) * ring
print(f"DDP sent/rank: {ddp_gb:.2f} GB | ZeRO-3: {zero3_gb:.2f} GB (ratio={zero3_gb / ddp_gb:.2f}x)")
fp32_grad_gb = 280
print(f"BF16 gathers + FP32 reductions ratio: {(2 * param_gb + fp32_grad_gb) / (2 * fp32_grad_gb):.2f}x")DDP sent/rank: 278.91 GB | ZeRO-3: 418.36 GB (ratio=1.50x)
BF16 gathers + FP32 reductions ratio: 1.00xFSDP2: native PyTorch sharding on DTensors
PyTorch's torch.distributed.fsdp.fully_shard (FSDP2) stores per-parameter DTensor shards in place (replacing legacy FSDP1 FlatParameter wrappers), preserving parameter names and composing natively with DeviceMesh, torch.compile, clip_grad_norm_, and Distributed Checkpoint (DCP).[12][13][14]
Trace one transformer block with reshard_after_forward=True, FP32 persistent shards, BF16 compute, and FP32 reductions: at rest each rank holds 4B FP32 parameter shards + 8B Adam moments (reaching the same 16B/param total once 4B FP32 gradient shards materialize). Forward all-gathers BF16 weights, computes activations, and frees weights; backward re-gathers BF16 weights for , computes local , reduce-scatters FP32 gradient shards, and frees full buffers before the local AdamW step.

FSDP2 hides communication via implicit prefetching on a separate NCCL stream (exposed wait ).[13] Always shard bottom-up (transformer blocks first, then root) so peak gather memory divides by block count, and construct AdamW after fully_shard so it binds to sharded DTensors:
import torchfrom torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
model = TransformerModel()
for block in model.blocks:
fully_shard(block, mp_policy=mp, reshard_after_forward=True)
fully_shard(model, mp_policy=mp, reshard_after_forward=False)
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5)Setting reshard_after_forward=False keeps full weights through backward (higher peak VRAM than ZeRO-2); passing a 2D DeviceMesh enables hybrid sharding (sharding within each 8-GPU node and replicating across nodes, dividing 70B state by 8 instead of total ranks).[15] During gradient accumulation, set_requires_gradient_sync(False) defers intermediate reduce-scatters by holding full local gradients.
DeepSpeed ZeRO: config, engine, and CPU/NVMe offload
DeepSpeed centralizes sharding, accumulation, precision, and hierarchical offload inside DeepSpeedEngine and ds_config.json.[6][16] Under default managed_gradient_accumulation=True, call engine.backward(loss) and engine.step() on every microbatch without manually dividing loss by gradient_accumulation_steps (stepping only every microbatches delays updates ; dividing loss scales gradients twice).[17] DeepSpeed rejects DDP no_sync() for ZeRO-2/3; use engine.coalesce_grad_reduction() when trading local gradient memory for fewer collectives.
{
"train_batch_size": 64,
"train_micro_batch_size_per_gpu": 2,
"gradient_accumulation_steps": 8,
"bf16": { "enabled": true },
"data_types": { "grad_accum_dtype": "fp32" },
"zero_optimization": {
"stage": 3, "contiguous_gradients": true, "overlap_comm": true,
"reduce_bucket_size": 200000000, "stage3_prefetch_bucket_size": 50000000,
"offload_optimizer": { "device": "cpu", "pin_memory": true },
"offload_param": { "device": "nvme", "nvme_path": "/local_nvme/deepspeed" }
},
"optimizer": { "type": "AdamW", "params": { "lr": 2e-5, "weight_decay": 0.01 } }
}Four DeepSpeed rules prevent silent bugs:
- Batch identity:
train_batch_size = micro_batch * grad_accum * DP_degree(), usingDP_degree, not total GPUs when TP/PP is active.[3] - Buckets count elements, not bytes:
reduce_bucket_size: 200_000_000takes 400 MB in BF16 or 800 MB withgrad_accum_dtype: "fp32".[16] - External parameters vs dynamic routing: Initialize huge models under
deepspeed.zero.Init(). Register tied cross-module weights viaregister_external_parameter()orGatheredParameters(...); mark dynamic MoE routers as ZeRO-3 leaf modules (set_z3_leaf_modules()) so ranks never deadlock on unmatched expert gathers.[16][17] - Compatibility: AutoTP supports ZeRO 0–3, whereas
PipelineModulesupports only ZeRO 0–1 (rejecting ZeRO 2–3).[18]
CPU/NVMe offload tradeoffs (ZeRO-Offload & ZeRO-Infinity)
ZeRO-Offload moves optimizer states and updates to host RAM (selecting DeepSpeedCPUAdam automatically for "AdamW");[19][20] ZeRO-Infinity spills optimizer and ZeRO-3 parameter shards to local NVMe (updates still run on CPU cores).[21] Never confuse GPU HBM bandwidth (3.35 TB/s H100 SXM; 8 TB/s B200)[22] with PCIe/NVMe links: moving 12 GB over a 6 GB/s link takes at least 2.0 s. With 3.0 s of independent GPU compute, ideal overlap takes , whereas serialized transfer-before-compute exposes 5.0 s.
FSDP2 vs DeepSpeed comparison:
| Feature | FSDP2 (fully_shard) | DeepSpeed ZeRO |
|---|---|---|
| Runtime & tooling | Native PyTorch (DTensor, DeviceMesh, torch.profiler) | Centralized DeepSpeedEngine + ds_config.json |
| Sharding modes | reshard_after_forward=True/False + 2D hybrid mesh | Native ZeRO-1, ZeRO-2, ZeRO-3 |
| Offloading | CPU offload via CPUOffloadPolicy() | CPU (ZeRO-Offload) and NVMe (ZeRO-Infinity) |
| Parallelism mix | Native TP + PyTorch pipelining on DeviceMesh | AutoTP (ZeRO 0–3); PipelineModule (ZeRO 0–1 only) |
| Checkpointing | PyTorch Distributed Checkpoint (DCP) | Sharded save + zero_to_fp32 / Universal Checkpointing |
Default to FSDP2 for native PyTorch tooling, DeviceMesh TP/PP composition, and DCP whenever GPU HBM or CPUOffloadPolicy() suffices. Choose DeepSpeed when NVMe spillover via ZeRO-Infinity is essential or you are extending a DeepSpeed stack. In legacy FSDP1 codebases, FULL_SHARD maps to reshard_after_forward=True, SHARD_GRAD_OP to reshard_after_forward=False, HYBRID_SHARD to a 2D DeviceMesh, and limit_all_gathers=True is a CPU peak-memory rate limiter (not an overlap knob).
Checkpointing, PyTorch DCP, and failure recovery
At cluster scale, hardware faults become routine rather than exceptional. If a single device has mean time between failures , independent devices fail at:
Across thousands of GPUs, interruptions happen every few hours (Meta reported 419 unexpected interruptions across its 54-day Llama 3 405B run on 16K H100s).[23] Fast, atomic checkpointing and topology-flexible recovery are therefore core distributed-training infrastructure.
| Goal | Required state | Verification check |
|---|---|---|
| Resume training | Sharded weights, Adam moments (), step counters, LR scheduler, RNG, dataloader cursor (client_state) | Next resumed parameter update matches an uninterrupted run |
| Export for inference | Consolidated weights plus model/tokenizer config (no optimizer state) | Forward outputs on fixed inputs match within tolerance |
PyTorch Distributed Checkpoint (DCP) writes per-rank shards in parallel and automatically reshards model and optimizer state across different world sizes or topologies on restore (for example, resuming a 16-GPU checkpoint on 12 or 32 GPUs without a single-node consolidation bottleneck).[24][25] When overlapping I/O with async_save, distinguish two completion points:
- Staging completion: Live GPU tensors have been copied into pinned host memory, so training ranks can safely resume forward/backward passes without mutating the snapshot.
- Storage completion: Every shard has flushed to durable storage and the manifest pointer has been published atomically (
fsyncplus atomic rename on POSIX filesystems, or a generation-matched pointer update on object stores).[26] Only after storage completion is a checkpoint durable and safe to mark aslatest.
Treat preemption signals (SIGTERM) as a hard deadline budget covering step finish (or clean abort), staging, flush, and atomic publish. Always align the stateful dataloader cursor to the exact completed optimizer step stored in the checkpoint: pairing step- weights with a prefetched cursor past step silently drops the intervening microbatches.[27]
In DeepSpeed, every rank must call engine.save_checkpoint(save_dir, tag) with one shared tag (rank-0-only calls hang; per-rank timestamps fragment directories), and ZeRO-3 reloads must target a fresh engine.[6] Export dense ZeRO weights for inference with zero_to_fp32.py (get_fp32_state_dict_from_zero_checkpoint, budgeting full-model CPU RAM); for world-size changes, use Universal Checkpointing (ds_to_universal.py) or PyTorch DCP.[28][29]
Matching the first resumed loss never confirms a valid training resume: a weights-only reload computes the exact same step-4 loss yet takes a different AdamW step because moments reset:
import io, torch
from torch import nn
torch.set_num_threads(1)
torch.manual_seed(7)
x = torch.tensor([[1., 0.], [0., 1.], [1., 1.], [-1., 2.]])
y = torch.tensor([[1.], [-1.], [0.], [-3.]])
def make_run():
m = nn.Sequential(nn.Linear(2, 4), nn.Tanh(), nn.Dropout(0.25), nn.Linear(4, 1))
return m, torch.optim.AdamW(m.parameters(), lr=0.01)
def step(m, o):
o.zero_grad(set_to_none=True)
loss = (m(x) - y).square().mean()
loss.backward(); o.step()
return loss.detach()
m, o = make_run()
for _ in range(3): step(m, o)
buf = io.BytesIO()
torch.save({"m": m.state_dict(), "o": o.state_dict(), "rng": torch.get_rng_state()}, buf)
exp_loss = step(m, o)
exp_p = torch.cat([p.detach().flatten() for p in m.parameters()])
def restore(with_opt: bool):
buf.seek(0)
s = torch.load(buf, weights_only=True)
m2, o2 = make_run()
m2.load_state_dict(s["m"])
if with_opt: o2.load_state_dict(s["o"])
torch.set_rng_state(s["rng"])
return step(m2, o2), torch.cat([p.detach().flatten() for p in m2.parameters()])
_, res_p = restore(True)
wo_loss, wo_p = restore(False)
print("full_resume_equal=", torch.equal(res_p, exp_p), "wo_same_loss=", torch.equal(wo_loss, exp_loss), "wo_same_update=", torch.equal(wo_p, exp_p))full_resume_equal= True wo_same_loss= True wo_same_update= FalseBeyond data parallelism: 4D parallelism
Pure DP hits three walls at scale: global batch size (), single-layer gather size, and long-context activations. 4D parallelism composes four orthogonal axes across a Cartesian mesh:[30][31][32]
Only multiplies independent sequence replicas; , , and cooperate on one replica.

- Tensor parallelism (TP): Megatron-LM splits MLP via column-parallel (no comm before GeLU) and row-parallel (one All-Reduce), mirroring attention ( column-parallel by head, row-parallel) for 2 forward + 2 backward all-reduces per layer inside NVLink.[30][31]
- Pipeline parallelism (PP) & 1F1B: Assigns contiguous layer ranges to stages over point-to-point links.[31] For balanced microbatches, GPipe and plain 1F1B share the exact same bubble overhead and elapsed idle fraction ;[33] 1F1B wins on memory by holding at most live activation sets on stage instead of GPipe's .[34] Cutting the bubble itself requires or interleaved stages.
- Context parallelism (CP / Ring Attention): Splits sequence length across ranks, keeping local stationary while rotating blocks around a ring with online softmax overlapped against compute.[32]
for p, m in ((8, 1), (8, 32), (64, 256)):
print(f"p={p:>2}, m={m:>3}: overhead={(p-1)/m:7.2%}, idle={(p-1)/(m+p-1):6.2%}")
p, m = 4, 8
print("1F1B warmup:", [min(m, p-i-1) for i in range(p)], "max_live:", [min(m, p-i) for i in range(p)])p= 8, m= 1: overhead=700.00%, idle=87.50%
p= 8, m= 32: overhead= 21.88%, idle=17.95%
p=64, m=256: overhead= 24.61%, idle=19.75%
1F1B warmup: [3, 2, 1, 0] max_live: [4, 3, 2, 1]![Top panel compares peak in-flight activation sets for p=4 stages and m=8 microbatches: GPipe stores 8 sets per stage, while plain 1F1B caps live sets at [4, 3, 2, 1]. Bottom panel plots the ideal bubble fraction (p-1)/(m+p-1) for p=8 stages as microbatches m increase: 87.5% at m=1, 63.6% at m=4, 46.7% at m=8, 17.95% at m=32, and 9.9% at m=64.](https://assets.leetllm.com/v1/932e2b229508/training/distributed-training-fsdp-deepspeed-zero/illustrations/_generated/pipeline_flush_schedule_dark.png)
Sizing, scaling, and debugging a real run
Always size above the static model-state floor. For 70B under ZeRO-3 (1,120 GB), leaves 0 GB for activations, gathered layers, and allocator overhead. Adding a profiled 18 GB/GPU transient budget pushes 16 GPUs to 70 + 18 = 88 GB (OOM), whereas 24 GPUs (46.7 + 18 = 64.7 GB) and 32 GPUs (35.0 + 18 = 53.0 GB) run comfortably.
When node failures shrink the cluster, keep global batch size constant by adjusting gradient_accumulation_steps rather than silently altering update dynamics. If you intentionally scale global batch size by multiplier under Adam, Malladi et al.'s SDE scaling rule adjusts learning rate, betas, and epsilon together (, , ), subject to diminishing returns once batch size passes the gradient noise scale .[35][36] Before committing to a multi-day run, rehearse a restart drill: interrupt a short job, resume across a changed GPU count, and verify step weights, moments, and dataloader cursor match the uninterrupted run.
When distributed runs fail, turn symptoms into profiler checks:[37][38]
- NCCL hang/timeout: Read the earliest failing rank log with
TORCH_NCCL_DUMP_ON_TIMEOUT=1and positiveTORCH_NCCL_TRACE_BUFFER_SIZE; check dynamic MoE gather alignment. - Startup OOM: Instantiate on
torch.device("meta")(FSDP2) ordeepspeed.zero.Init()(DeepSpeed) before loading shards. - Exposed collectives in
torch.profiler: Tune block granularity, prefetching, or switch to hybrid sharding / intra-node TP. - Loss shift after scaling out or resuming: Audit global batch (), unequal-rank token weighting,
grad_accum_dtype, managedengine.step()cadence, and dataloader cursor alignment.