Distributed training
Verify gradients, memory, collectives, nonlinear boundaries and recomputation before scaling.
Count state and allocation lifetimes
Adding workers changes two things at once: where the training state lives and which computations must exchange results. A model can fit across three devices yet run slower because every layer waits for communication. Another can finish a step faster while silently changing the loss normalization. We need a memory ledger, a computation contract and a schedule before a device count is meaningful.
This note uses original scalar data, integer vectors and hypothetical byte counts. A standard-library program executes the reductions, matrix identities, dependency schedule and gradient recomputation. It does not run PyTorch, NCCL or a GPU, and its slot counts are not measured accelerator timings.
Start with the operation that must remain unchanged
A training step reads a specified batch, computes a loss and gradients, then updates parameters and optimizer state. Distributing that step should preserve the intended objective unless a deliberate algorithm change is being evaluated. Identical filenames or equal parameter counts do not establish this: data sampling, gradient normalization and update timing matter.
First establish a small reference calculation. Compare distributed outputs and gradients against it on permitted fixed inputs. Then measure device memory, time spent computing, time waiting for collectives and input-pipeline stalls. An out-of-memory failure and low utilization require different interventions. A faster step also does not guarantee less time to the required validation quality if the effective batch or optimizer behaviour changed.
For the following memory exercise, stipulate a model with twelve million trainable scalar parameters. That is a sizing input, not an actual trained network. Separate it from the six scalar records used to check gradient averaging: each small case isolates one mechanism instead of pretending to benchmark a full training system.
Count every state and its lifetime
Assume a particular mixed-precision layout: two bytes per working parameter, four per gradient, four for a master parameter and eight for the two optimizer moments. The last three arrays are explicitly full precision. Thus persistent model-related storage is
For , this is 216 MB in decimal units. A different gradient dtype, optimizer, master-copy policy or parameter aliasing changes the ledger. There is no universal bytes-per-parameter constant for mixed precision. Count actual allocations in the implementation being considered.
This ledger excludes activations retained for backward, temporary kernel workspaces, collective buffers, allocator overhead and input batches. Peak memory depends on which objects coexist. Adding the largest independent measurements from different times can overestimate the peak; ignoring a temporarily gathered parameter block can underestimate it. A useful profile records allocation lifetimes around forward, backward and the optimizer step.
Reducing a local microbatch often reduces activations while leaving parameter and optimizer storage unchanged. Sharding optimizer state addresses a different part of the ledger. Activation recomputation trades extra work for fewer retained intermediates. These choices can be combined, but each needs its own measured effect and correctness check.
Preserve example weighting
Average examples, not arbitrary worker means
In synchronous data parallelism, workers hold compatible replicas and process different data. They combine gradients before applying the same update. For a loss defined as the mean over all examples,
where is the local mean gradient and is the number of included examples. Averaging worker means is equivalent only when those counts are equal, or when the intended weighting explicitly gives every worker equal weight.
Consider , the loss , and . The individual gradient is . Our independently specified records are:
| Worker | Records | Gradient sum | Count | Local mean |
|---|---|---|---|---|
| 0 | 1 | 1 | 1 | |
| 1 | 1 | 2 | ||
| 2 | 10 | 3 |
The six-example mean is . The unweighted mean of the three worker means is , which optimizes a different weighting. With learning rate 0.1, the correct update gives . This difference comes from normalization, before any floating-point or networking effect.
PyTorch DDP synchronizes gradient buckets during backward and lets each local optimizer update its replica. Its documentation explains ordering requirements and overlap with computation. The application still owns data partitioning and loss meaning. Check the last partial batch, duplicated sampler records and token masks: equally sized tensors can contain different numbers of eligible loss terms.
Gradient accumulation introduces another boundary. If several microbatches form one update, normalize by the intended combined count and update only after their contributions are complete. Clipping every local gradient before reduction generally differs from clipping the combined gradient. Batch-dependent layers and stochastic operations can also prevent a naive split from matching a single reference computation.
Count the stated collective payload
Account for the collective's payload
All-reduce combines corresponding values and makes the result available to every participating rank. Reduce-scatter distributes reduced chunks; all-gather distributes those chunks again. NCCL documents these semantic operations. It does not promise that every call uses the particular ring schedule we study here.
Split a length-12 vector into three chunks of four integers. Worker starts with coordinate equal to , for and . The expected sum is , namely [-3, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30].
Our ring sends one chunk to the next worker per round. Two reduction rounds leave complete chunks 1, 2 and 0 on workers 0, 1 and 2 respectively. Two distribution rounds then give every worker the full sum. The source records every round and checks the result against a direct coordinate-wise sum. The rotated ownership is a convention of this small schedule, not NCCL's API layout.
Each worker sends four chunks, or sixteen values. Assuming a four-byte payload representation, that is 64 payload bytes sent per worker. Python integer object sizes are irrelevant to this declared communication model; the program simulates messages, not actual network buffers.
For workers and a divisible full payload of bytes, the same ring pattern has two phases of rounds, each carrying bytes:
Our twelve-million-parameter ledger has a 48 MB gradient payload. With three workers, each sends 64 MB and also receives 64 MB. Do not double-count receive bytes when reporting sent traffic, or mistake this total for an end-to-end latency prediction. Latency per round, topology, concurrent flows and overlap all matter. Small buckets can expose round overhead; large buckets can postpone communication until much of backward is finished.
Separate persistent shards from temporary copies
Shard persistent state, then budget temporary gathering
The ZeRO work by Samyam Rajbhandari and coauthors organizes memory savings by distributing optimizer state, then gradients, then parameters. We apply that idea to our independently specified 18-byte layout and three workers. Master parameters and optimizer moments occupy twelve bytes per parameter in this ledger.
| Persistent state placement | Bytes per worker | Decimal MB |
|---|---|---|
| All replicated | 216 | |
| Master and optimizer state sharded | 120 | |
| Gradients also sharded | 88 | |
| All listed states sharded | 72 |
These are arithmetic persistent-state amounts, not GPU peaks or measured ZeRO performance. Full parameter groups may still be needed during computation. Gathering a group creates a temporary full copy; prefetching the next group can overlap communication while making more bytes coexist. Extremely fine groups reduce that live size but require more collective operations.
PyTorch FSDP2 describes parameter-group all-gathers around computation and gradient reduce-scatters after backward. Grouping and resharding choices affect when parameters are available and released. Its execution policy is more detailed than dividing a total by the device count. Inspect the actual chosen groups and their overlapping lifetimes.
Sharding also changes saving and recovery. A checkpoint consisting of one worker's shard is not the complete model. Preserve shard metadata, optimizer state, data position and random-state requirements for the intended restart. Validate restoration before treating distributed memory capacity as reliable training capacity. Failure after some workers update but before others do cannot be resolved by quietly continuing with inconsistent replicas.
Preserve algebra and stage dependencies
Split a tensor along a mathematically valid boundary
Tensor parallelism divides the computation of an operation. For our original row vector and matrix,
Splitting output columns gives two independent scalar outputs that can be concatenated. Splitting the input dimension instead gives partial outputs from the first two coordinates and from the last. Their sum reconstructs .
The location of the next operation matters. Applying ReLU after reduction gives . Applying it to each partial output before summation gives , a different function. An algebraically valid linear partition does not authorize moving a nonlinear operation across a reduction.
The same reasoning guides a larger network: identify which intermediate must be replicated, sharded, concatenated or reduced before its consumer runs. Communication can occur inside each layer rather than once per optimizer step. Hardware placement and matrix sizes therefore affect whether the split helps. Our exact small matrix verifies an identity and a counterexample; it is not a speedup measurement or an implementation of a framework's tensor-parallel API.
Schedule pipeline stages without changing the update
Pipeline parallelism assigns consecutive parts of a model to different workers. Microbatches let one stage work while another processes a preceding microbatch. The GPipe paper by Yanping Huang and coauthors describes synchronous microbatch accumulation; we derive a separate three-stage abstract schedule here rather than reproducing its diagrams or benchmarks.
Assume each stage's forward or backward operation takes one slot and communication is free. Process all forwards, then all backwards, and update only after every microbatch contributes. The first microbatch needs forward slots across stages; each additional microbatch extends the forward phase by one. The backward phase has the same length. For microbatches,
Here is occupied stage-slot fraction for this balanced fill-and-drain schedule, not measured GPU utilization. The fixture explicitly assigns every operation a stage and slot and verifies forward/backward dependency order.
| Stages | Microbatches | Total slots | Occupied stage-slot fraction |
|---|---|---|---|
| 3 | 1 | 6 | |
| 3 | 5 | 14 | |
| 3 | 9 | 22 |
More microbatches amortize filling and draining, but they do not make an imbalanced slow stage disappear. Making each microbatch too small can hurt kernel efficiency; keeping many activations can consume memory. Alternative schedules interleave forward and backward work, changing live activations and communication. Their correctness still depends on which parameter version each operation reads. Do not infer their memory or timing from this particular fill-and-drain table.
Replay the same function and state
Recompute the same intermediates
Activation checkpointing retains selected boundaries and regenerates intermediates during backward. It is distinct from saving a training checkpoint for recovery. The tradeoff is extra computation for less retained activation state, provided replay reproduces the needed function and its state.
Our independent scalar chain has nine affine layers, starting from 2. Its forward values are 2, 3, 5, 7, 5, 11, 12, 11, 22, 25. For the final loss , full storage gives an input gradient of 200. The fixture first stores all nine layer inputs and computes every weight gradient.
It then retains only boundary inputs at layers 0, 3 and 6. During reverse traversal it replays each three-layer segment, uses the local inputs for its gradients and discards that segment. This deliberately simple replay performs nine extra forward operations, retains three persistent boundary inputs instead of nine, and uses a temporary buffer of four scalar values. Those are separate algorithmic storage counts, not a claim of threefold peak-memory reduction. The verification program keeps the reference arrays for comparison; it does not measure allocated memory. All nine weight gradients and the input gradient match the full-storage calculation exactly.
PyTorch's checkpoint documentation highlights replay state, including random-number handling and differences between implementations. Random masks, mutable counters or side effects that change on replay can invalidate the intended derivative. Our chain has no randomness or side effects, and does not invoke a checkpoint API; it verifies only the stated deterministic recomputation.
Choose a layout around the bottleneck
Data parallelism replicates a computation over examples, tensor parallelism splits operations, and pipeline parallelism splits sequential stages. State sharding and activation recomputation modify storage. None is a universal first step: identify what prevents the reference run from meeting its objective.
A twelve-worker layout could have two data replicas, three pipeline stages and two tensor partitions per stage. If each data replica accumulates five microbatches of eight examples, the effective update batch is , not twelve times eight. Tensor and pipeline workers collaborate on the same examples. Gradient collectives must connect the corresponding parameter partitions, not arbitrary groups of twelve ranks.
Record that layout with the run. Before scaling further, verify loss weighting, gradients, optimizer timing and restoration on a small case. Then profile a representative step and the validation trajectory. Include checkpoint time, failed work and the input pipeline in elapsed cost. A configuration that reduces persistent state may expose an expensive all-gather; one that hides communication may exceed peak memory through prefetching.
What changed
The plan now identifies eighteen bytes of specified persistent state per parameter, separates them from temporary allocations, and preserves example weighting across unequal workers. Reduction, tensor partition and pipeline scheduling each have an executable invariant. Recomputation preserves gradients in a deterministic case while making its extra work explicit.
Limitations
All timings are abstract slots and all communication sizes are assumed payload bytes. There is no hardware benchmark, collective library run, network fault, full optimizer implementation or real model. Integer and rational checks avoid floating-point reduction differences; they do not prove bitwise agreement on accelerators. Balanced stages, correct clocks and synchronous updates are assumptions to test in a real system.
What to retain
Specify the objective and update boundary before distributing work. Count persistent and temporary allocations separately. Weight gradients by eligible examples. Check the communication layout and nonlinear-operation boundary. Treat pipeline utilization formulae as schedule-dependent. Verify recomputation and recovery with the state they actually require.
Next
Serving models changes the objective from completing synchronized updates to meeting request deadlines under a varying arrival process.
References
- PyTorch contributors. DDP design, FSDP2 fully_shard, and activation checkpointing, documentation 2.15, read 13 November 2026: bucket synchronization, parameter-group lifetimes and replay-state caveats. No documentation code or diagrams reused.
- NVIDIA. NCCL collective operations, documentation 2.32.3: operation semantics and participation requirements. The small ring simulator is independently written and is not NCCL source.
- Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase and Yuxiong He. ZeRO, 2020: partitioning model states. No source figure, memory table or measured performance reused; our 18-byte ledger is explicitly specified and recomputed.
- Yanping Huang and coauthors. GPipe, 2019: synchronous microbatch pipeline training. No paper diagram, data or performance result reused; the three-stage schedule is generated by our own program.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Go deeper — optional
Code and labs do not count toward the main percentage or the certificate.
- Preserve gradients across a distributed layoutoptional
All timings are abstract slots and traffic is stipulated payload bytes. No GPU, distributed runtime or tensor package is used. Persistent storage and temporary replay buffers are distinct counts, not measured peak memory.
~20 min · easier on a computer · The corresponding lesson and basic Python functions.
Self-check in the notebook — not part of mastery or the certificate.
Answers are saved on the server and tied to this browser until you sign in.