ELLMEngineering Large
Language Models
Download PDF

Chapter 39

Data Parallelism, ZeRO, and Fully Sharded Training

On this page

Data parallelism scales independent examples. Sharded variants reduce replicated model state, but replace simple gradient synchronization with a schedule of parameter gathers, gradient partitions, prefetches, and memory-lifetime decisions.

Replicated data parallelism

Each data-parallel rank owns a complete model and optimizer replica and processes different local examples. Backward produces local gradients, and an all-reduce makes the reduced gradient identical before every rank performs the same optimizer update.

For local microbatch b, gradient-accumulation steps g, and data-parallel degree d, the global batch is B_global = b * g * d. This assumes b is per rank and every rank contributes the same number of examples. Ragged or filtered batches require explicit weighting so the reduced gradient represents the intended global objective.

Scaling d increases global batch unless b or g changes. That can alter optimization, learning-rate schedule, and sample order. System scaling and training semantics must be planned together.

Normalize by supervised targets

Equal weighting of rank-local means is not a global token mean when supervised counts differ. If rank A has one target with loss 4 and rank B has three targets with loss 0, the mean of local means is 2, but the global token mean is 1. With R replicas whose gradients are averaged, each rank should backpropagate R * local_loss_sum / global_target_count to recover the global token-mean gradient. Sum the count over the complete accumulation window; do not independently average differently sized microbatches. A rank with zero targets must still participate in collectives, and a globally empty window needs a coordinated no-update policy. The DDP reduction documentation specifies the averaging assumption; custom reduction hooks can change it.

Gradient reduction and buckets

Frameworks register backward hooks and place parameters into buckets. When all gradients for a bucket are ready, its all-reduce can overlap with backward computation for earlier layers.

Small buckets start early but pay more launch and latency. Large buckets use bandwidth well but may not begin until late in backward. Bucket order should track observed gradient readiness. PyTorch DDP normally launches reductions in reverse parameter-registration order, so registering parameters in approximate forward-execution order often aligns the schedule with backward; bucket rebuilding, unused parameters, and conditional paths can change the observed order and should be inspected rather than assumed.

Gradient accumulation can suppress synchronization for intermediate microbatches and reduce once at the accumulation boundary. This saves communication but holds gradients longer and changes the overlap opportunity. Ensure the final microbatch triggers synchronization on every rank, including early termination paths.

Execute an unequal-count accumulation window

For rank r, microbatch j, summed supervised loss S_rj, and valid target count n_rj, define N=sum_r sum_j n_rj before backward. The objective is L=sum_r sum_j S_rj/N. With the standard DDP gradient average over R ranks, accumulating backward calls on R*S_rj/N gives exactly dL/dtheta after the final synchronization. There is no additional division by the number of microbatches.

examples/ddp_accumulation_lab.py executes this contract using real DDP and two Gloo processes. The two windows use target-count matrices [[1,0],[2,3]] and [[0,0],[2,3]], indexed by rank then microbatch. The second window exercises a rank with no supervised targets at all. Its loss is still connected to the model graph with zero weight, so it participates in the same backward and reduction schedule.

Wrap both the forward and backward calls for intermediate microbatches inside no_sync(). The last microbatch on every rank executes outside that context. Zero gradients once at the start of the window, not between its microbatches. These context semantics are specified by the PyTorch 2.8 DDP API, which matches the companion's tested version.

The executable compares every parameter gradient and one SGD update with a single-process union-of-targets reference in FP64. It also verifies that a globally empty window leaves parameters unchanged. The latter must skip the optimizer step, including weight decay and momentum updates, rather than merely manufacture zero gradients.

Memory accounting

For P parameters, per-rank training memory includes some combination of:

  • model parameters, possibly low precision;
  • gradients, possibly accumulated in higher precision;
  • optimizer moments and master parameters;
  • activations and saved tensors;
  • temporary workspaces, communication buckets, and allocator reserve.

For Adam-like training with low-precision parameters, optimizer states and master weights can exceed model parameter bytes several times over. State the exact dtype and optimizer representation rather than quoting a universal bytes-per-parameter number.

Activation memory follows microbatch, sequence length, hidden size, layer count, checkpoint policy, and parallel partitioning. Sharding model state does not automatically solve activation OOM.

Carry the running model across the training boundary

Use the same nominal seven-billion-parameter model as Parts III and IV, but change the task from inference to full-parameter training. Under an explicitly chosen convention of two-byte weights, two-byte gradients, four-byte master weights, and two four-byte Adam moments, persistent model state is 7e9 * 16 = 112 GB in decimal units. This excludes activations, temporary buffers, communication buckets, and allocator reserve. Different optimizers or gradient dtypes change the result.

Ordinary data parallelism replicates those 112 GB on each rank; adding replicas does not make the per-rank state fit. Ideal eight-way full sharding reduces the resident shard to 112 / 8 = 14 GB per rank, before transient all-gathers and the other excluded allocations. That number happens to equal the running model's two-byte inference weight size, but the allocations have different meanings. Training does not become a 14 GB job merely because its persistent state is sharded.

The inference request's KV budget also does not transfer into training unchanged. Its 32 layers, eight KV heads, head dimension 128, and two-byte elements give 128 KiB per cached token, or 250 MiB for a 2,000-token prompt. Training instead retains or recomputes the forward tensors needed by backward; use the chosen microbatch, sequence length, and checkpoint policy to budget those activations. The arithmetic is checked in tests/test_resource_models.py; neither calculation establishes measured GPU capacity.

ZeRO stages

A four-rank ownership sketch. Ordinary data parallelism retains every model-state partition; successive ZeRO stages shard optimizer state, gradients, then parameters. Cells encode ownership, not equal byte sizes across state types.
Open full diagram ↗

A four-rank ownership sketch. Ordinary data parallelism retains every model-state partition; successive ZeRO stages shard optimizer state, gradients, then parameters. Cells encode ownership, not equal byte sizes across state types.

ZeRO-style sharding progressively removes data-parallel redundancy:

Stage Sharded across data ranks Main new communication/lifetime issue
Stage 1 Optimizer states Parameter updates need shard ownership and synchronization
Stage 2 Optimizer states and gradients Gradients naturally arrive through reduce-scatter
Stage 3 Optimizer states, gradients, and parameters Parameters must be gathered around computation

Exact implementations differ. The principle is that each rank owns a partition of persistent state while temporarily materializing what its local compute needs.

Sharding reduces memory approximately with data-parallel degree for shardable objects, but replicas still carry activations, buffers, some metadata, padding, and peak gathered parameters. Peak memory, not steady shard size, decides whether the model fits.

Fully sharded execution

A fully sharded module generally performs:

  1. prefetch or all-gather parameter shards for a module group;
  2. execute forward with materialized parameters;
  3. reshard or retain parameters according to policy;
  4. if step 3 resharded parameters, gather again as backward needs the module; otherwise reuse the retained materialization;
  5. reduce-scatter gradients to owners;
  6. update local optimizer shards.

Communication-group granularity controls this schedule. Very small units issue many latency-bound gathers. Very large units raise peak memory and delay prefetch. Older flattened-parameter implementations combine parameter storage; do not assume that representation when reading a newer sharding API.

Backward prefetch can overlap the next parameter gather with current gradient computation. Forward prefetch is useful when execution order is static and CPU issue cannot stay ahead. Too much prefetch creates multiple live gathered units and causes OOM.

Read a current training implementation

PyTorch's FSDP2 tutorial uses fully_shard and per-parameter DTensor representations; it marks FSDP1 deprecated. Apply sharding to selected submodules and then the root, and construct the optimizer afterward. The grouping still controls collective timing even though parameters retain individual identities. Read the tutorial's state-dictionary and prefetch examples alongside the lifetime sequence above rather than translating old wrapper flags mechanically.

TorchTitan provides a PyTorch-native path through a training loop, parallelization, activation checkpointing, compilation, and distributed checkpointing. Follow one transformer block from model definition through parallelization to the checkpoint representation. Megatron-LM and Megatron Core provide another reference for composing tensor, pipeline, context, and expert parallelism. These are implementation study paths, not a claim that either has the best configuration for every model.

For a first experiment, compare one unsharded update with a sharded update on identical effective data. Check loss, gradients after the appropriate gathering, updated parameters, and checkpoint reload within declared tolerances. Only then profile communication and peak live memory. A configuration that launches successfully has not yet demonstrated the intended optimization problem.

Bound live memory across all-gather prefetch

Let P_s be persistent parameter, gradient, and optimizer shards, A(t) live activations, U(t) materialized full parameter units, and W(t) collective and kernel workspace. The relevant capacity constraint is max_t[P_s+A(t)+U(t)+W(t)] <= device_capacity. Summing only persistent shards can miss the peak by an entire wrapped unit or more.

Suppose unit i contains n_i parameters materialized at b bytes each. While computing unit i and prefetching i+1, full-parameter storage alone can reach b*(n_i+n_(i+1)). Whether the local shard aliases the full buffer changes the exact accounting; use the implementation's allocation trace rather than subtracting the shard twice. Backward may also retain gradient buffers whose lifetime overlaps the next all-gather.

A wrapping plan with smaller units lowers this peak but increases collective count and startup overhead. Prefetch helps only if its data is ready before the consumer and the added live allocation fits. This produces a constrained scheduling problem: minimize exposed all-gather time subject to the maximum simultaneous allocation, not an unconstrained rule to prefetch as far ahead as possible.

Reshard-after-forward decisions

Resharding immediately after forward frees parameter memory but requires another gather in backward. Retaining parameters saves communication but increases peak live state, particularly with many layers or microbatches.

Choose by available memory, module size, recomputation, pipeline schedule, and bandwidth. Hybrid sharding can fully shard within a node and replicate across nodes, reducing cross-node parameter gathers while retaining some memory savings.

Activation checkpointing and offload

Activation checkpointing saves selected boundary tensors and recomputes internal forward operations during backward. It trades compute for activation memory and can change overlap timing. Selective policies decide which operation outputs to save and which to recompute: preserving an expensive matrix multiplication while recomputing cheap pointwise operations is one useful starting hypothesis, not a universal rule.

CPU or storage offload expands capacity but introduces transfer and page-fault risk. It is viable when transfers overlap and the interconnect sustains the required bytes per step. An offload plan that fits but extends step time beyond the training budget is not a solution.

Checkpointed regions must preserve random-number behavior for dropout or other stochastic operations. Distributed recomputation also needs the same collective order as the original forward. Mutable globals or buffers can make recomputation differ even with the same RNG state. PyTorch's checkpoint reference documents non-reentrant behavior and selective policies; test gradients after changing the policy, not only peak memory.

Mixed precision and global numerical state

Ranks must agree on loss-scaling overflow, skipped optimizer steps, gradient clipping norm, and scheduler progress. A local overflow decision that only one rank follows will desynchronize parameters and future collectives.

Global norm clipping usually reduces partial squared norms across the appropriate parameter ownership group. Avoid double-counting replicated tensors or omitting shards. Optimizer-state sharding changes who owns the update but not the mathematical parameter set.

Uneven inputs and join semantics

If one data rank exhausts input early while others continue, ordinary synchronized training hangs or changes the effective gradient. Prefer globally constructed batches with equal step counts. When uneven-input support is deliberate, participating ranks must shadow collectives or adjust normalization, and additional model collectives may require stricter termination handling.

Input failures are distributed failures. A corrupt sample on one rank, data-service timeout, or divergent filtering decision can leave peers waiting in gradient reduction. Log sample/shard identity and fail the group coherently.

Design Exercises

  1. Compare replicated DDP, ZeRO stage 2, and fully sharded training.
  2. How do bucket size and parameter order affect gradient overlap?
  3. Design a wrapping and prefetch policy for a deep transformer under a hard memory limit.
  4. When should parameters be retained after forward rather than resharded?
  5. What distributed state must agree when mixed-precision overflow occurs?
  6. Why can activation checkpointing make a communication plan slower or incorrect?

Worked Solutions

1. DDP and sharded variants

DDP replicates parameters, gradients, and optimizer state and all-reduces gradients; it is simple and compute-granular but memory-heavy. ZeRO stage 2 shards optimizer and gradients, often using reduce-scatter, while parameters remain replicated. Fully sharded training also shards parameters, requiring gathers around module execution and careful reshard/prefetch timing. Compare peak bytes, collective frequency and size, overlap, checkpoint format, and local compute efficiency, not only persistent memory.

2. Buckets and order

Smaller buckets become ready earlier and overlap more but pay fixed latency and may compete with compute. Larger buckets reach bandwidth efficiency but start later and can leave a reduction tail after backward. If bucket parameter order differs from gradient-ready order, one late gradient blocks an otherwise ready bucket. Profile ready times, exposed reduction tail, and network contention, then tune size and order for the real model and accumulation schedule.

3. Wrapping and prefetch

Start with transformer-block-sized units, measure each unit's gathered bytes and compute window, and choose the largest unit that preserves peak reserve. Prefetch one dependency ahead when its gather can hide under current compute; cap outstanding gathers to a byte budget. For FSDP2, choose module-level fully_shard groups, apply them to child blocks before the root, and construct the optimizer afterward. Parameters remain individually represented as DTensors; manual flattening is not a general FSDP2 setup step. Special-case unusually large embeddings or heads, reshard after forward when memory is tight, and validate with peak snapshots across the full forward/backward and accumulation schedule.

4. Retain versus reshard

Retain when memory headroom exists and the avoided backward all-gather is expensive or difficult to overlap. Reshard when gathered parameters would accumulate to the peak limit, especially across many layers, microbatches, or pipeline stages. Hybrid policies retain small or soon-reused units and reshard large ones. Measure step time and peak live bytes; persistent shard size alone misses the decision.

5. Mixed-precision agreement

All ranks must reach the same overflow decision, loss-scale update, optimizer-step skip, global gradient norm, clipping coefficient, step counter, learning-rate schedule, and RNG/data progression policy. Reduce overflow flags and partial norms over the group that collectively owns the parameters. If one rank skips while another updates, parameters diverge and subsequent collective order or checkpoint state becomes invalid.

6. Checkpointing interactions

Recomputation adds compute where parameter gathers or gradient reductions were expected to overlap, so the critical path can change. It may repeat collectives, random operations, or mutable side effects unless the region is designed for recomputation. Preserve RNG state, use the same process-group order, avoid external side effects, and profile the new timeline. Memory saved is useful only if recompute and additional communication still meet throughput.

Two-process evidence and its boundary

examples/distributed_lab.py runs two actual Gloo CPU ranks. Their supervised-target counts are one and two. Each rank backpropagates its loss sum scaled by world_size/global_count; gradients are then summed and divided by world size. The result is compared with one unpartitioned decoder computation. This catches the equal-rank-mean error without requiring a large model.

The experiment does not instantiate FSDP2, measure gathered-parameter peaks, or validate NCCL. Use it to establish the objective before investigating sharded runtime behavior. A failed gradient-equivalence check makes a memory or throughput comparison premature.