Distributed Model Training

Dive into Deep Learning · §39.6

Distributed Model Training: DDP, FSDP/ZeRO, 3D Parallelism, and Fault Tolerance
scaling ladder · DDP vs. FSDP2 · tensor & pipeline parallelism · global batch invariant · memory sharding · ZeRO-Offload · atomic checkpoints

Why Single-Accelerator Training Hits a Wall

Motivation

  • The 7B single-GPU memory wall (112\text{ GB}): Mixed-precision Adam holds BF16 weights (14\text{ GB}), BF16 grads (14\text{ GB}), FP32 master weights (28\text{ GB}), and FP32 Adam m, v (56\text{ GB})—exceeding an 80\text{ GB} H100 before any activations.
  • Four partitioning axes: Split the batch (DDP), training state (FSDP/ZeRO), layer matrices/stages (TP/PP), or sequence/experts (CP/EP).
  • Golden rule: Start from a verified 1-GPU baseline and climb one rung at a time.

The Distributed Scaling Ladder

Progressive Scaling

Climb the scaling ladder in strict order of increasing communication volume and engineering complexity:

  1. Single Accelerator Baseline: Verify loss convergence, tok/s throughput, peak memory, and checkpoint restore.
  2. Data Parallelism (DDP): Replicate the model on every GPU, split the batch, and all_reduce gradients once per step. Always use DDP while state fits on one GPU.
  3. Fully Sharded Data Parallelism (FSDP / ZeRO-3): Shard parameters, gradients, and optimizer states across W GPUs; all_gather layers on the fly (\sim 1.5\times DDP traffic).
  4. Composed 3D/4D Parallelism (TP / PP / CP / EP): Split individual layers, layer stages, sequences, or experts when a single layer or activation exceeds device capacity.

Data Parallelism (DDP) vs. FSDP2 / NamedSharding

Rungs 2 and 3

  • Rung 2: DDP (DistributedDataParallel): Replicates all 16N state on every GPU and averages bucketed gradients via all_reduce (\approx 2S traffic); best choice whenever state fits.
  • Rung 3: FSDP2 (fully_shard / DTensor & JAX NamedSharding): Divides parameters, gradients, and Adam moments by W (16N/W), overlapping per-layer all_gather and reduce_scatter (\approx 3S = 1.5\times DDP traffic).

Tensor, Pipeline, Context, and Expert Parallelism

Rung 4: Model & Sequence Axes

  • Intra-layer vs. inter-layer splits: Tensor Parallelism (TP) splits matrices inside every block (2 collectives/layer on the critical path), whereas Pipeline Parallelism (PP) passes activations point-to-point at stage boundaries.
  • Hardware topology rule (Ultra-Scale Playbook): Keep high-frequency TP inside an 8-GPU NVLink node (450\text{--}900\text{ GB/s}; stretching TP across nodes costs -43\%), and scale PP + FSDP/DDP across nodes.

Pipeline Schedules: GPipe vs. 1F1B Bubble and Memory

Pipeline Mechanics

\text{Bubble Fraction} = \frac{p - 1}{m}

  • GPipe (all m forwards, then all m backwards): Needs m \gg p to shrink the bubble, forcing stage 1 to hold all m microbatch activations at once (O(m) memory).
  • 1F1B Schedule: Alternates 1 Forward and 1 Backward after warmup, achieving the same (p-1)/m bubble while capping live activations at \le p microbatches.

The Global Batch Size Invariant Across Every Rung

Optimization Semantics

B_{\text{global}} = B_{\text{device}} \cdot N_{\text{ranks}} \cdot N_{\text{accumulation}}

  • Preserving optimization dynamics: Doubling N_{\text{ranks}} from 64 \to 128 without halving N_{\text{accumulation}} silently doubles B_{\text{global}} and halves optimizer steps.
  • When B_{\text{global}} increases: Scale Adam learning rate by \sqrt{B/B_0} and define warmup in tokens rather than steps.

Distributed Samplers and Exact Metric Aggregation

Correctness Pitfalls

\text{Acc}_{\text{exact}} = \frac{\sum_{r=0}^{W-1} c_r}{\sum_{r=0}^{W-1} n_r} \neq \frac{1}{W} \sum_{r=0}^{W-1} \frac{c_r}{n_r}

  • Padded DistributedSampler bug: Default padding repeats leading examples so every rank gets \lceil N/W \rceil items, skewing validation metrics.
  • Exact distributed evaluation: Split examples without padding, tally local (correct_r, count_r) integers, and all_reduce(SUM) numerator and denominator once.

Anatomy of Peak Training Memory

Memory Budget

Peak per-GPU memory is the sum of model state, saved activations, temporary communication buffers, and allocator fragmentation:

  • Mixed-precision Adam state for a 7B model (16\text{ B/param} = 112\text{ GB}):
    • BF16 parameters: 2N = 14\text{ GB}
    • BF16 gradients: 2N = 14\text{ GB}
    • FP32 master parameters: 4N = 28\text{ GB}
    • FP32 Adam first & second moments (m, v): 8N = 56\text{ GB}
  • Dynamic terms: Activations grow linearly with B_{\text{device}} \times T, while collective staging buffers add 4\text{--}8\text{ GiB}.

Modeling Per-Device Memory: DDP vs. FSDP

Executable Memory Model

Even leaving out the 28\text{ GB} master-weight copy (84\text{ GiB} state + 18\text{ GiB} activations + 5\text{ GiB} temporary buffers), our sizing script shows why DDP cannot fit a 7B full fine-tune on 80 GB GPUs:

  • 1 GPU plain (107.0\text{ GiB}): Exceeds an 80\text{ GB} H100.
  • 8-GPU DDP + activation checkpointing (95.3\text{ GiB/GPU}): Checkpointing shrinks activations from 18\text{ GiB} to 6.3\text{ GiB}, but DDP replicates all 84\text{ GiB} of model state on every GPU—still OOM.
  • 8-GPU FSDP + activation checkpointing (21.8\text{ GiB/GPU}): Sharding state by 8 cuts per-GPU state to 10.5\text{ GiB}, leaving nearly 60\text{ GiB} of headroom for larger microbatches.
        1 GPU, plain:  107.0 GiB/device
    8 GPU DDP + ckpt:   95.3 GiB/device
   8 GPU FSDP + ckpt:   21.8 GiB/device

Modeling Per-Device Memory: DDP vs. FSDP (Code)

Executable Memory Model

terms_gib = {"parameters": 14.0, "gradients": 14.0, "optimizer": 56.0,
             "activations": 18.0, "temporary": 5.0}

def per_device_gib(world_size=1, shard_state=False, ckpt_activations=False):
    divisor = world_size if shard_state else 1
    state = sum(terms_gib[k] / divisor
                for k in ("parameters", "gradients", "optimizer"))
    activations = terms_gib["activations"] * (0.35 if ckpt_activations else 1)
    return state + activations + terms_gib["temporary"]

for label, cfg in [("1 GPU, plain", (1, False, False)),
                   ("8 GPU DDP + ckpt", (8, False, True)),
                   ("8 GPU FSDP + ckpt", (8, True, True))]:
    print(f"{label:>20s}: {per_device_gib(*cfg):6.1f} GiB/device")

Five Orthogonal Memory-Reduction Techniques

Memory Optimization Trade-Offs

  • Sharding & Checkpointing: FSDP2/ZeRO divides 16N state by W (\sim 1.5\times comm), while activation checkpointing trades +25\text{--}33\% FLOPs to shrink saved activations from O(L) \to O(1).
  • Accumulation, Offload & Adapters: Gradient accumulation shrinks microbatch B_{\text{device}}, CPU offload moves master weights/Adam across PCIe, and LoRA/QLoRA freezes base weights to drop >98\% of gradient/optimizer state.

Arithmetic of CPU Optimizer Offload (ZeRO-Offload)

Host-Device Roofline

  • Per-step offload cost (1.54\text{ s} for 7B): Sending 14\text{ GB} BF16 grads and receiving 14\text{ GB} BF16 weights over 50\text{ GB/s} PCIe takes 0.56\text{ s}, plus 0.98\text{ s} to stream 196\text{ GB} (28\text{ B/param}) through 200\text{ GB/s} CPU DDR.
  • Amortization & delayed update: Keeping offload < 20\% of step time at 400\text{ TFLOP/s} requires \ge 58{,}700\text{ tok/step} (or a 1-step delayed CPU update).

Selecting the Simplest Tool for Your Scale (Nov 2026)

Software Ecosystem

  • 1 GPU to 1 Node (2–8 GPUs): Use Unsloth or HF PEFT for single-GPU LoRA/QLoRA, and HF Accelerate, Axolotl, or LLaMA-Factory for single-node DDP/FSDP2.
  • Multi-Node & RL Post-Training: Use PyTorch FSDP2 (fully_shard) or DeepSpeed across a few nodes, TorchTitan / Megatron Core / MaxText at 64–512+ GPUs, and TRL / veRL / OpenRLHF for DPO/GRPO.

Fault Tolerance: Complete and Atomic Checkpointing

Surviving Hardware Failures

  • Bitwise-complete checkpoint bundle: Save sharded model weights, Adam moments, LR scheduler state, step/token counters, deterministic data cursor, and per-rank PRNG states.
  • Crash-safe atomic rename: Never overwrite ckpt in place; write to ckpt.tmp, call f.flush() + os.fsync(), swap via os.replace("ckpt.tmp", "ckpt"), and fsync the directory.

Operational Discipline for Long Distributed Runs

Production Operations

Four operational habits separate multi-week training runs that finish from runs that stall or silently diverge:

  • 1. Drill the recovery before day one:
    • Deliberately kill the training job at step 40, restore on fresh workers, and verify that step 41’s loss, gradient norm, and data batch match an uninterrupted run bitwise.
    • Design data ordering globally by example index so elastic resumption works even if you must resume on 48 GPUs after losing two 8-GPU nodes.
  • 2. Profile input pipelines separately from GPU compute:
    • Measure storage reads, image/text decoding, and host-to-device copy rates independently; adding GPUs to an I/O-bound job only increases storage contention.
  • 3. Monitor convergence alongside systems throughput:
    • Log (step, loss, grad_norm, tok/s, collective_ms, ckpt_ms) with rank and hostname on every log line; isolate bugs on 1\text{ process} \to 1\text{ node} \to N\text{ nodes}.

Concept Check: Sharding, Batch Invariants, and Recovery

Check Your Understanding

Work through these three distributed training scenarios:

  1. A pretraining job maintains a fixed global batch of B_{\text{global}} = 1{,}024 sequences (4,096 tokens each \approx 4.2\text{M} tokens), and each GPU holds at most B_{\text{device}} = 4 sequences per microbatch. What is the minimum gradient accumulation N_{\text{accumulation}} on N_{\text{ranks}} = 64 GPUs, and what is the largest world size that can train this global batch with data parallelism alone?
  2. During checkpoint restore, a colleague restores the model weights, Adam moments, and data-loader position, but forgets to restore the LambdaLR scheduler state. What happens to the training run, and will it raise an exception?
  3. Why does FSDP2 communicate roughly 1.5\times as much data per step as DDP?

Concept Check: Sharding, Batch Invariants, and Recovery (cont.)

Check Your Understanding

Answers:

  1. On 64 GPUs with B_{\text{device}} = 4, N_{\text{accumulation}} = 1024 / (64 \times 4) = \mathbf{4}. The largest pure data-parallel world size (at B_{\text{device}} = 1, N_{\text{accumulation}} = 1) is N_{\text{ranks}} = 1{,}024 GPUs (or 256 GPUs if keeping B_{\text{device}} = 4).
  2. It never raises an exception, but the learning rate resets to step 0 (re-running warmup or jumping back to peak \eta_{\max}), causing a sudden loss spike or silent accuracy degradation.
  3. For N parameters of size S = 2N bytes, DDP runs one all_reduce of gradients (\approx 2S bytes sent/received per GPU). FSDP runs an all_gather of weights in forward (S), another all_gather of weights in backward (S), and a reduce_scatter of gradients (S)—totaling 3S bytes (1.5\times DDP).

Summary: Multi-GPU and Distributed Training Systems

Key Takeaways

System Dimension Core Rule / Equation Practical Engineering Guideline
Scaling ladder 1 GPU \to DDP \to FSDP2 \to TP + PP + CP/EP Use DDP while state fits; shard state with FSDP2 next; keep TP inside an NVLink node
Global batch size B_{\text{global}} = B_{\text{device}} \cdot N_{\text{ranks}} \cdot N_{\text{accumulation}} Adjust N_{\text{accumulation}} or \eta(B) whenever changing GPU count so optimization dynamics stay invariant
Memory accounting M_{\text{state}} = 16N\text{ B} (BF16 weights/grads + FP32 master/Adam) Combine FSDP (\div W), activation checkpointing, and LoRA/QLoRA deliberately to fit target VRAM
Pipeline scheduling Bubble fraction = (p - 1)/m Use 1F1B instead of GPipe to bound in-flight activation memory to p microbatches
Distributed evaluation \text{Acc} = (\sum_r c_r) / (\sum_r n_r) Avoid padded sampler duplicates on eval sets; all_reduce numerator and denominator counts separately
Fault tolerance Atomic write: tmp \to fsync \to os.replace Save model, optimizer, scheduler, data cursor, and RNG state; drill recovery before long or spot runs