Skip to content
Skip to lesson
Back to Topics
LearnTraining, Fine-Tuning & AlignmentDistributed Training: FSDP & ZeRO
HardFine-Tuning & Training16 min read

Distributed Training: FSDP & ZeRO

One replicated 70B AdamW state exceeds an 80 GB GPU. Shard optimizer, gradients, and parameters with FSDP2 or DeepSpeed ZeRO, manage offload and checkpoints, and compose 4D parallelism when layers or sequences overflow.

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 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]

TensorBytes / paramRole
Compute weight (BF16/FP16)2Forward and backward Tensor Core matmuls
Gradient (BF16/FP16)2Gradient awaiting optimizer step (4 B if FP32 grad accum)
FP32 master parameter4Full-precision weights preserving small updates
FP32 Adam moments (mt,vtm_t, v_t)8Running mean of gradients and uncentered squared gradients
Total16Model 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 2−242^{-24} gap, such as 1e-8):

stored_parameter_updates.py
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}")
Stored update output
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=True

At 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.

70B dense model state breakdown (16 bytes/param = 1,120 GB total): BF16 weights 140 GB, BF16 gradients 140 GB, FP32 master weights 280 GB, and FP32 Adam moments 560 GB on a shared 0 to 560 GB scale. Below, equal sharding across 16, 32, 64, or 256 ranks uses 70, 35, 17.5, or 4.375 GB of an 80 GB GPU, leaving 10, 45, 62.5, or 75.625 GB for activations and buffers.
Master weights and Adam moments dominate 70B memory (840 of 1,120 GB). Sharding scales persistent state down linearly with rank count.

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 rr an unequal count of nrn_r supervised tokens across NN ranks, default DDP averages each rank's local mean equally rather than every token equally. Scaling rank rr's local mean by Nnr/∑jnjN n_r / \sum_j n_j (summed across microbatches and ranks) recovers the exact pooled token-mean gradient:

unequal_rank_loss_weighting.py
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}")
Rank loss weighting output
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.
Equal-rank averaging skews toward sparse ranks (−4); scaling each rank by Nnr/∑jnjN n_r / \sum_j n_j restores the exact pooled gradient (−5).

ZeRO stages: sharding state and preserving Adam math

For PP parameters owned by a data-parallel group of NN ranks with (p,g,o)(p, g, o) bytes/param for compute weights, gradients, and optimizer-plus-master state, each ZeRO stage shards one more buffer:[1]

MDP=P(p+g+o),MZ1=P(p+g+o/N),MZ2=P(p+(g+o)/N),MZ3=P(p+g+o)/N.\begin{aligned} M_{\text{DP}} &= P(p + g + o), & M_{\text{Z1}} &= P(p + g + o/N), \\ M_{\text{Z2}} &= P(p + (g + o)/N), & M_{\text{Z3}} &= P(p + g + o)/N. \end{aligned}
Four same-scale stacked bars show model-state ownership per GPU for a 70B, 16-byte recipe in an eight-rank data-parallel group. DDP stores P=140, G=140, O=840 GB for 1,120 total. ZeRO-1 stores P=140, G=140, O=105 for 385 GB. ZeRO-2 stores P=140, G=17.5, O=105 for 262.5 GB. ZeRO-3 stores P=17.5, G=17.5, O=105 for 140 GB. P is parameters, G gradients, and O the FP32 master plus Adam moments; bars share a 0–1,120 GB axis.
Per-GPU persistent state for 70B parameters across N=8N = 8 ranks under the 16-byte recipe (P: parameters, G: gradients, O: master + moments).
  • ZeRO-1 shards optimizer states (1/N1/N 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 vtv_t squares the gradient:[5] for gradients 1 and 3, reducing first yields 22=42^2 = 4, while squaring locally and averaging yields (12+32)/2=5(1^2+3^2)/2 = 5. 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 for long sequences.

zero_stage_memory.py
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")
ZeRO memory and working set
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 elems

Communication collectives and the 1.5x heuristic

NCCL implements three collective building blocks across GPUs:[7]

PrimitiveOperationRing bytes sent / rankPrimary role
All-reduceSums tensors across ranks; every rank gets the full sum2N−1NS≈2S2\frac{N-1}{N} S \approx 2SDDP gradient sync, TP RowParallel
Reduce-scatterSums tensors across ranks; each rank keeps its 1/N1/N sliceN−1NS≈1S\frac{N-1}{N} S \approx 1SZeRO-2/3 and FSDP gradient reduction
All-gatherReconstructs the full tensor on every rank from 1/N1/N shardsN−1NS≈1S\frac{N-1}{N} S \approx 1SZeRO-3 / FSDP parameter materialization

Here SS is the full tensor size. Algebraically, All-Reduce(X)≡Reduce-Scatter(X)→All-Gather(X)\text{All-Reduce}(X) \equiv \text{Reduce-Scatter}(X) \to \text{All-Gather}(X).

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.
NCCL collective semantics on two ranks. Ring traffic scales as (N−1)/N⋅S(N-1)/N \cdot S per reduce-scatter or all-gather.

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 (Ψ\Psi elements), DDP and ZeRO-2 move 2Ψ2\Psi per rank while ZeRO-3 / full-shard FSDP moves 3Ψ3\Psi (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:

communication_heuristic.py
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")
Communication heuristic output
DDP sent/rank: 278.91 GB | ZeRO-3: 418.36 GB (ratio=1.50x)
BF16 gathers + FP32 reductions ratio: 1.00x

FSDP2: 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 dX=dYWTdX = dY W^T, computes local dW=XTdYdW = X^T dY, reduce-scatters FP32 gradient shards, and frees full buffers before the local AdamW step.

Live GPU HBM footprint of a 1B FSDP2 unit across 4 ranks over six step events. The 1 GB FP32 parameter shard stays resident throughout. Forward all-gather temporarily adds 2 GB of BF16 weights to peak at 3 GB, then post-forward reshard drops back to 1 GB. Backward all-gather again peaks at 3 GB, reduce-scatter frees BF16 weights leaving 1 GB shard plus 1 GB FP32 gradient shard (2 GB), and local AdamW plus zero_grad returns to the 1 GB rest state.
For a 1B block on 4 ranks, each rank keeps a 1 GB FP32 shard and transiently gathers 2 GB BF16 weights during forward and backward.

FSDP2 hides communication via implicit prefetching on a separate NCCL stream (exposed wait ≈max⁡(0,Tgather−Twindow)\approx \max(0, T_{\text{gather}} - T_{\text{window}})).[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:

fsdp2_structure.py
from 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 kk microbatches delays updates k×k\times; 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.

ds_config.json
{
  "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:

  1. Batch identity: train_batch_size = micro_batch * grad_accum * DP_degree (2×8×4=642 \times 8 \times 4 = 64), using DP_degree, not total GPUs when TP/PP is active.[3]
  2. Buckets count elements, not bytes: reduce_bucket_size: 200_000_000 takes 400 MB in BF16 or 800 MB with grad_accum_dtype: "fp32".[16]
  3. External parameters vs dynamic routing: Initialize huge models under deepspeed.zero.Init(). Register tied cross-module weights via register_external_parameter() or GatheredParameters(...); mark dynamic MoE routers as ZeRO-3 leaf modules (set_z3_leaf_modules()) so ranks never deadlock on unmatched expert gathers.[16][17]
  4. Compatibility: AutoTP supports ZeRO 0–3, whereas PipelineModule supports 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 max⁡(2,3)=3.0 s\max(2, 3) = 3.0\text{ s}, whereas serialized transfer-before-compute exposes 5.0 s.

FSDP2 vs DeepSpeed comparison:

FeatureFSDP2 (fully_shard)DeepSpeed ZeRO
Runtime & toolingNative PyTorch (DTensor, DeviceMesh, torch.profiler)Centralized DeepSpeedEngine + ds_config.json
Sharding modesreshard_after_forward=True/False + 2D hybrid meshNative ZeRO-1, ZeRO-2, ZeRO-3
OffloadingCPU offload via CPUOffloadPolicy()CPU (ZeRO-Offload) and NVMe (ZeRO-Infinity)
Parallelism mixNative TP + PyTorch pipelining on DeviceMeshAutoTP (ZeRO 0–3); PipelineModule (ZeRO 0–1 only)
CheckpointingPyTorch 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 MTBFdevice\text{MTBF}_{\text{device}}, NN independent devices fail at:

MTBFcluster=MTBFdeviceN\text{MTBF}_{\mathrm{cluster}} = \frac{\text{MTBF}_{\mathrm{device}}}{N}

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.

GoalRequired stateVerification check
Resume trainingSharded weights, Adam moments (mt,vtm_t, v_t), step counters, LR scheduler, RNG, dataloader cursor (client_state)Next resumed parameter update matches an uninterrupted run
Export for inferenceConsolidated 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:

  1. 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.
  2. Storage completion: Every shard has flushed to durable storage and the manifest pointer has been published atomically (fsync plus 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 as latest.

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-tt weights with a prefetched cursor past step tt 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:

checkpoint_next_update.py
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))
Checkpoint continuation output
full_resume_equal= True wo_same_loss= True wo_same_update= False

Beyond data parallelism: 4D parallelism

Pure DP hits three walls at scale: global batch size (Bglobal=Bmicro×m×DPB_{\text{global}} = B_{\text{micro}} \times m \times DP), single-layer gather size, and long-context activations. 4D parallelism composes four orthogonal axes across a Cartesian mesh:[30][31][32]

World Size=DP×TP×PP×CP\text{World Size} = DP \times TP \times PP \times CP

Only DPDP multiplies independent sequence replicas; TPTP, PPPP, and CPCP cooperate on one replica.

A 128-GPU 4D parallelism mesh (DP=8, TP=4, PP=2, CP=2). One 16-GPU sequence replica spans two 8-GPU nodes as pipeline stages PP 0 and PP 1, passing activations forward and gradients backward across InfiniBand. Inside each node, 4 TP columns communicate over NVLink and 2 CP rows split sequence tokens via Ring Attention. Repeating this 16-GPU replica 8 times for DP yields 128 GPUs and 32 global sequences (1 microbatch x 4 accumulation x 8 DP).
A 128-GPU 4D mesh (DP=8,TP=4,PP=2,CP=2DP=8, TP=4, PP=2, CP=2): Bmicro=1B_{\text{micro}}=1 and m=4m=4 give 1×4×8=321 \times 4 \times 8 = 32 global sequences.
pipeline_bubble_ratios.py
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)])
Pipeline bubble output
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.
GPipe and plain 1F1B share identical bubble ratios; 1F1B cuts peak live activation sets per stage to min⁡(m,p−i)\min(m, p - i).

Sizing, scaling, and debugging a real run

Always size above the static model-state floor. For 70B under ZeRO-3 (1,120 GB), 1,120/80=14 GPUs1{,}120 / 80 = \mathbf{14\text{ GPUs}} 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 κ\kappa under Adam, Malladi et al.'s SDE scaling rule adjusts learning rate, betas, and epsilon together (η′=κ η\eta' = \sqrt{\kappa}\,\eta, βi′=1−κ(1−βi)\beta'_i = 1 - \kappa(1 - \beta_i), ϵ′=ϵ/κ\epsilon' = \epsilon / \sqrt{\kappa}), subject to diminishing returns once batch size passes the gradient noise scale Bsimple=Tr⁡(Σ)/∥G∥2\mathcal{B}_{\mathrm{simple}} = \operatorname{Tr}(\Sigma) / \|G\|^2.[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 t+1t+1 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=1 and positive TORCH_NCCL_TRACE_BUFFER_SIZE; check dynamic MoE gather alignment.
  • Startup OOM: Instantiate on torch.device("meta") (FSDP2) or deepspeed.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 (Bmicro×m×DPB_{\text{micro}} \times m \times DP), unequal-rank token weighting, grad_accum_dtype, managed engine.step() cadence, and dataloader cursor alignment.
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.A 2B-parameter model uses 2 B/param compute weights, 4 B/param FP32 gradient accumulation (grad_accum_dtype='fp32'), and 12 B/param for FP32 master weights plus Adam moments. Across 8 data ranks, what are persistent per-rank totals under ZeRO-2 and ZeRO-3?
2.An FSDP2 model has 7 blocks of 4 GB compute weights each and a 6 GB budget per parameter all-gather. Which setup fits the gather budget and binds AdamW to sharded DTensors?
3.A DeepSpeed ZeRO-3 job with managed_gradient_accumulation=True (accum=8) offloads 18 GB across a 6 GB/s PCIe/NVMe link with 4 s of independent GPU compute. How often must the loop call engine.step(), and what are ideal-overlap vs serialized step lower bounds?
4.A ZeRO-3 checkpoint saves after batch 37. Run A exports weights via zero_to_fp32 and passes forward parity (0.003 <= 0.005). Run B restores weights, Adam moments, scheduler, and RNG, but its dataloader replays batch 37. Which goals pass?
5.A 4D mesh has DP=6, TP=2, PP=3, CP=2 with microbatch 2 and 5 accumulation steps. Separately, a 5-stage pipeline runs plain 1F1B over 12 microbatches. What are world size, global sequence batch, 1F1B peak live activation sets, and idle fraction?

5 questions remaining.

References

ZeRO: Memory Optimizations Toward Training Trillion Parameter Models.

Rajbhandari, S., et al. · 2020 · SC 2020

https://arxiv.org/abs/1910.02054

PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel.

Zhao, Y., et al. · 2023 · VLDB 2023

https://arxiv.org/abs/2304.11277

DeepSpeed Configuration JSON

DeepSpeed Contributors · 2026

https://www.deepspeed.ai/docs/config-json/

DistributedDataParallel

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html

Adam: A Method for Stochastic Optimization

Kingma, D. P., Ba, J. · 2015 · ICLR 2015

https://arxiv.org/abs/1412.6980

DeepSpeed Source Repository

DeepSpeed Contributors · 2026

https://github.com/deepspeedai/DeepSpeed/tree/c455031422641a825588c926455458c82b27b6c0

NCCL Collective Operations

NVIDIA · 2026

https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/collectives.html

How to Scale Fast Fourier Transforms to Exascale on Modern NVIDIA GPU Architectures

Xu, Z., Gray, A., Páll, S., and Alekseenko, A. · 2025

https://developer.nvidia.com/blog/how-to-scale-fast-fourier-transforms-to-exascale-on-modern-nvidia-gpu-architectures/

GB200 NVL72

NVIDIA · 2026

https://www.nvidia.com/en-us/data-center/gb200-nvl72/

NVIDIA InfiniBand Adapters

NVIDIA · 2026

https://www.nvidia.com/en-au/networking/infiniband-adapters/

GPUDirect RDMA: Overview

NVIDIA · 2026

https://docs.nvidia.com/cuda/gpudirect-rdma/

torch.distributed.fsdp.fully_shard

PyTorch Contributors · 2025

https://docs.pytorch.org/docs/2.14/distributed.fsdp.fully_shard.html

Getting Started with Fully Sharded Data Parallel (FSDP2)

PyTorch Contributors · 2025

https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html

Where to apply torch.compile?

PyTorch Contributors · 2025

https://docs.pytorch.org/docs/main/user_guide/torch_compiler/compile/programming_model.where_to_apply_compile.html

FullyShardedDataParallel

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/stable/fsdp.html

ZeRO Configuration

DeepSpeed Team · 2026

https://deepspeed.readthedocs.io/en/stable/zero3.html

Training API

DeepSpeed Team · 2026

https://deepspeed.readthedocs.io/en/latest/training.html

Pipeline Parallelism

DeepSpeed Team · 2026

https://deepspeed.readthedocs.io/en/stable/pipeline.html

ZeRO-Offload: Democratizing Billion-Scale Model Training

Ren, J., Rajbhandari, S., Aminabadi, R. Y., et al. · 2021 · USENIX ATC 2021

https://www.usenix.org/conference/atc21/presentation/ren-jie

DeepSpeed Optimizer Selection (2a4ee92)

DeepSpeed Contributors · 2026

https://github.com/deepspeedai/DeepSpeed/blob/2a4ee92b76601ef2709c4e9857eab4e232f72075/deepspeed/runtime/engine.py

ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning.

Rajbhandari, S., et al. · 2021 · SC 2021

https://arxiv.org/abs/2104.07857

HGX AI Factory H100, H200, B200: Components

NVIDIA · 2026

https://docs.nvidia.com/enterprise-reference-architectures/hgx-ai-factory-h100-h200-b200/latest/components.html

The Llama 3 Herd of Models.

Dubey, A., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2407.21783

PyTorch Distributed Checkpoint (DCP) Recipe

PyTorch Contributors · 2026

https://docs.pytorch.org/tutorials/recipes/distributed_checkpoint_recipe.html

Asynchronous Saving with Distributed Checkpoint

PyTorch Contributors · 2026

https://docs.pytorch.org/tutorials/recipes/distributed_async_checkpoint_recipe.html

Cloud Storage Request Preconditions

Google Cloud · 2026

https://docs.cloud.google.com/storage/docs/request-preconditions

TorchData Stateful DataLoader

PyTorch and TorchData Contributors · 2026

https://meta-pytorch.org/data/main/torchdata.stateful_dataloader.html

DeepSpeed Model Checkpointing

DeepSpeed Contributors · 2026

https://deepspeed.readthedocs.io/en/latest/model-checkpointing.html

Universal Checkpointing with DeepSpeed: A Practical Guide.

DeepSpeed Team · 2026

https://www.deepspeed.ai/tutorials/universal-checkpointing/

Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism.

Shoeybi, M., et al. · 2019

https://arxiv.org/abs/1909.08053

Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM

Narayanan, D., et al. · 2021 · SC 2021

https://arxiv.org/abs/2104.04473

Ring Attention with Blockwise Transformers for Near-Infinite Context.

Liu, H., et al. · 2023 · arXiv preprint

https://arxiv.org/abs/2310.01889

PipeDream: Generalized Pipeline Parallelism for DNN Training

Narayanan, D., Harlap, A., et al. · 2019 · SOSP 2019

https://aaronharlap.github.io/papers/sosp19-pipedream.pdf

Megatron-LM Pipeline Schedules (c711dc0)

NVIDIA and Contributors · 2026

https://github.com/NVIDIA/Megatron-LM/blob/c711dc0a7f4f7460045cae18ec2f9ff5f4b92b5e/megatron/core/pipeline_parallel/schedules.py

On the SDEs and Scaling Rules for Adaptive Gradient Algorithms

Malladi, S., Lyu, K., Panigrahi, A., & Arora, S. · 2022 · NeurIPS 2022

https://arxiv.org/abs/2205.10287v3

An Empirical Model of Large-Batch Training.

McCandlish, S., Kaplan, J., Amodei, D., and the OpenAI Dota Team · 2018

https://arxiv.org/abs/1812.06162

ProcessGroupNCCL Environment Variables

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/stable/torch_nccl_environment_variables.html

Parallelism Strategies Guide.

NVIDIA · 2026

https://docs.nvidia.com/megatron-core/developer-guide/latest/user-guide/parallelism-guide.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.