39 Distributed Generative AI
GPT-4 required approximately 25,000 NVIDIA A100 GPUs running continuously for months before a single token could be generated. Stable Diffusion XL consumed 256 A100s in its training run. Gemini Ultra, Google's largest model, reportedly required a cluster of TPU v4 pods containing tens of thousands of chips. These are not engineering curiosities. They are the load-bearing facts beneath every generative AI system you have ever used.
No single machine can hold a trillion-parameter model. The weights of a 1.8-trillion-parameter model in 16-bit floating point occupy approximately 3.6 terabytes of memory - more than 45 times the 80,GB of memory available on a single A100 GPU, the most capable card commercially available at the time these models were trained. Distribution is not a performance optimisation. It is a prerequisite for existence.
Yet the story is richer than mere size. Even if a single chip could hold the weights, training on a trillion tokens of data at a throughput that completes in this decade requires a parallelism that no sequential pipeline can achieve. And even if compute were free, the data movement between GPU memory, CPU memory, NVLink interconnects, and InfiniBand networks would throttle every training step. The three walls - memory, compute, and communication - form a trilemma that defines the entire discipline of distributed generative AI.
This chapter maps that trilemma from first principles. We begin with the arithmetic of scale that forces distribution, move through the hardware that makes it possible, and then develop the algorithmic techniques - data parallelism, tensor parallelism, pipeline parallelism, and their modern hybrids - that close the gap between what physics allows and what engineers deliver. Understanding distributed systems is the difference between using generative AI and building it.
Why Distributed Computing for Generative AI?
The Scale Explosion
The numbers are striking enough that it is worth stating them plainly before drowning them in formalism.
In 2018, BERT-Large had 340 million parameters. In 2019, GPT-2 reached 1.5 billion. In 2020, GPT-3 crossed 175 billion. By 2022, the Chinchilla paper revealed that optimal training required not just larger models but proportionally more data. In 2023, GPT-4 is estimated to contain approximately 1.8 trillion parameters in a mixture-of-experts architecture. The growth rate over five years - from 340 million to 1.8 trillion - represents a factor of roughly 5,000.
The training data has grown in parallel. GPT-2 was trained on 40 gigabytes of web text. GPT-3 consumed roughly 570 gigabytes of filtered data (the Common Crawl corpus after deduplication and quality filtering). LLaMA-3 was trained on 15 trillion tokens, which at roughly 4 bytes per token represents 60 terabytes of raw text.
The compute required tracks with both. If a model with parameters is trained on tokens, the approximate number of floating-point operations required is: (Compute Estimate) where the factor of 6 accounts for the forward pass (2 FLOPs per multiply-add per parameter), backward pass (approximately 2 the forward), and the gradient update pass. For GPT-3 ( parameters, tokens), this gives: (GPT3 Compute) An A100 GPU achieves approximately BF16 FLOPs per second (312 teraFLOPS). Training GPT-3 on a single A100 would therefore require: (Single GPU TIME) GPT-3 was actually trained in roughly one to two months on thousands of A100s. Distribution is not an optimisation - it is the difference between a model that exists and one that does not.
Key Idea.
For any sufficiently large generative model, distributed training is not a performance choice but a feasibility threshold. Below a certain scale, a model can be trained on a single device (perhaps slowly). Above that threshold - which modern state-of-the-art models crossed around 2020 - distribution is the only path from initialisation to convergence. The arithmetic is unambiguous: the growth in model size has consistently outpaced the growth in single-device memory and compute by an order of magnitude per decade.
Why Students Should Care
There is a tempting misunderstanding in the practitioner community: that distributed training is the province of infrastructure teams at large technology companies, and that researchers and ML engineers can remain blissfully unaware of how their models actually run. This view is increasingly untenable.
The reason is that algorithmic choices - architecture decisions, optimiser configurations, precision formats, gradient accumulation schemes - are not separable from the distributed substrate on which they execute. A model designed without regard for communication overhead will underperform its theoretical potential by orders of magnitude. A training run scheduled without understanding memory layouts will fail with out-of-memory errors that no amount of hyperparameter tuning will fix. The researcher who understands tensor parallelism can design attention mechanisms that partition efficiently across heads. The one who does not will be bottlenecked by the infrastructure team's defaults.
More practically: the modern toolkit for distributed training - PyTorch FSDP, DeepSpeed ZeRO, Megatron-LM, JAX pmap and pjit - has reached a level of sophistication where using it effectively requires understanding its abstractions. “It ran” is not the same as “it ran efficiently”. A poorly configured FSDP run may achieve 5% hardware utilisation on a cluster costing thousands of dollars per hour.
Insight.
Understanding distributed systems is the difference between using AI and building AI. Every trillion-parameter model that generates a response, every diffusion model that renders an image, every code completion that appears in an IDE - each of these required someone to solve the distributed systems problem first. That someone could be you.
Data Centre Anatomy
Before formalising the mathematics of distributed training, it is worth grounding the discussion in physical reality. A machine learning data centre is organised in a strict hierarchy, and the bandwidth available at each level of that hierarchy determines which parallelism strategies are viable.
At the top level, a data centre contains rows of racks. Each rack is a 42-unit (42U) or 52U cabinet housing multiple compute nodes. A node is a server: a motherboard with one or more CPUs, DRAM, local storage, and - for AI workloads - a set of GPUs. A modern DGX H100 node, for example, packs 8 H100 GPUs into a single system with a combined GPU memory of 640 gigabytes.
Within a node, GPUs communicate via NVLink, NVIDIA's proprietary high-bandwidth interconnect. In the H100 generation, NVLink provides 900 GB/s of aggregate bidirectional bandwidth between GPUs in the same node - more than 7 the bandwidth of PCIe Gen 5.
Between nodes, the dominant interconnect is InfiniBand (or, in Google's clusters, the custom ICI interconnect, and in some cloud environments, RoCE over Ethernet). Current-generation NDR InfiniBand provides 400 Gbps (50 GB/s) per port, and nodes are typically connected to a high-radix switch fabric providing non-blocking or near-non-blocking connectivity across hundreds to thousands of nodes.
The ratio of intra-node to inter-node bandwidth is approximately 18:1 (900 GB/s NVLink vs. 50 GB/s InfiniBand per node). This ratio is the single most important fact in distributed AI: it means that algorithms that can keep their most expensive communication within a node will dramatically outperform those that must communicate across nodes.
Formal Definition of Distributed Training
We now lay the mathematical foundations.
Definition 1.
(Distributed Training.) Let be a loss function over parameters and dataset . A distributed training system consists of:
A set of workers (devices) , each with local memory bytes.
A partitioning scheme that assigns model parameters, activations, and/or data to workers such that (for parameter partitioning) or (for data partitioning).
A communication protocol specifying when and how workers exchange gradients, parameters, or activations.
A synchronisation policy , either synchronous (all workers complete a step before any update is applied) or asynchronous (workers update a parameter server independently).
The distributed system solves: (Distributed Objective) such that at no point does any single worker need to hold more than bytes in its local memory simultaneously.
The key constraint in Definition Definition 38 is the memory constraint: each worker holds only a fragment of the full computation. This motivates the two fundamental axes of distribution: data parallelism (each worker holds a full copy of the model but processes a different shard of data) and model parallelism (each worker holds a fragment of the model). Real systems use both simultaneously, leading to 3D and 4D parallelism strategies discussed in later sections.
The Three Walls
The central challenge of distributed generative AI can be decomposed into three interacting bottlenecks, each of which is a “wall” that limits achievable throughput.
The Memory Wall.
A model with parameters stored in BF16 (2 bytes each) requires bytes just for the weights. During training, gradient storage adds another bytes. The Adam optimiser (the standard choice) adds two momentum terms per parameter, requiring an additional bytes in FP32. The total model state memory footprint is: (Memory Footprint) For a 7-billion-parameter model, this is bytes ,GB, exceeding the 80,GB memory of a single A100. For GPT-4 at 1.8 trillion parameters: ,TB - requiring at least 270 A100s for model state alone, before activations.
The Compute Wall.
Even when memory is not the binding constraint, raw throughput limits training speed. The model FLOP utilisation (MFU) measures what fraction of theoretical peak FLOP/s a training job achieves in practice: (MFU) State-of-the-art distributed training typically achieves MFU of 35–55% for large models. The gap between 100% and achieved MFU represents time spent on communication, memory movement, load imbalance, and framework overhead - all of which are targets for the techniques in this chapter.
The Communication Wall.
The most subtle and often most binding wall is communication. In a data-parallel setting with workers, each worker computes gradients over its local batch and then must aggregate these gradients across all workers before the next parameter update. This all-reduce operation transfers gradient values per step (send receive), and with BF16 gradients requires: (Allreduce Volume) For GPT-3 (), this is 700,GB per step. Over a 400,Gbps (50,GB/s) InfiniBand link, the minimum communication time for a single step is: (COMM TIME) Since compute for a step with batch size 2048 and sequence length 2048 is on the order of 1–2 seconds per GPU, the communication wall is the dominant bottleneck in naive data-parallel training.
Key Idea.
In distributed AI at scale, the bottleneck is not computation - it is communication. The entire field of distributed training can be read as a systematic effort to hide, reduce, compress, or eliminate the communication that connects distributed computation. Gradient compression, pipeline bubbles, tensor parallelism, and ZeRO sharding are all different answers to the same question: how do we move less data without sacrificing convergence?
Historical Development
Historical Note.
From One GPU to Ten Thousand: A Decade of Scale.
2012 - The Single-GPU Era. AlexNet, the model that reignited deep learning, was trained on two GTX 580 GPUs with 3,GB of memory each, split manually by the authors because a single GPU could not hold the model. This was model parallelism of the most primitive kind: a manual partition of two convolutional halves. Total training time: 5–6 days.
2014 - Data Parallelism Becomes Standard. Google's DistBelief framework and later the parameter server architecture formalised data-parallel SGD across hundreds of CPU cores. The key insight was that gradient aggregation could be asynchronous, tolerating staleness for large batch sizes.
2017 - Ring-AllReduce Democratises Distributed Training. Baidu's paper on ring-allreduce showed that gradient aggregation could be performed with optimal communication efficiency - total data movement regardless of the number of workers - using a simple ring topology. This made synchronous data parallelism at scale practical without a parameter server.
2019 - Megatron-LM: Tensor Parallelism for Transformers. NVIDIA's Megatron-LM introduced structured tensor parallelism for the transformer architecture, partitioning the large weight matrices of attention and MLP layers across GPUs within a node. This allowed models too large for a single GPU's memory to be trained without the communication overhead of pipeline parallelism.
2020 - ZeRO: Memory-Efficient Data Parallelism. Microsoft DeepSpeed's ZeRO (Zero Redundancy Optimizer) partitioned not just the data but the optimizer states, gradients, and parameters themselves across data-parallel workers, eliminating the memory redundancy of standard data parallelism. ZeRO-3 enabled training models with effectively unlimited size at the cost of modest additional communication.
2022–2024 - 3D Parallelism and Hybrid Strategies. Modern training runs for models like Llama-3, Gemini, and GPT-4 combine data parallelism, tensor parallelism, and pipeline parallelism in a three-dimensional grid, with ZeRO-style sharding adding a fourth dimension. The choice of parallelism strategy has become a performance engineering discipline in its own right, requiring careful profiling of each model's computation graph and the target cluster's topology.
Connection to Generative Models
Generative models have three properties that make distribution especially necessary:
Parameter density. Language models and diffusion models are dense - almost every parameter participates in every forward pass. This contrasts with sparse models (e.g., sparse autoencoders) where most weights are zero or masked. Density means every byte of the model state is active memory, so the memory wall is hit at smaller model sizes than for sparse architectures.
Sequence length and attention. Transformer-based generative models must hold the entire attention context - the key-value cache - in memory for each sequence. At sequence length with attention heads each of dimension , and layers, the KV cache requires: (KV Cache Memory) (the factor of 2 for key and value, and 2 bytes for BF16). For a 70B model with , , , : for a single sequence - already requiring distribution at inference time, not just training.
Iterative denoising in diffusion. Diffusion models generate samples through hundreds of sequential denoising steps. While the model itself may be smaller than a large LLM (Stable Diffusion XL has 2.6 billion parameters), high-resolution generation requires storing intermediate activations at full spatial resolution, and text-to-video models operating at resolution over 120 frames produce activation tensors measured in tens of gigabytes per forward pass.
Exercises
Exercise 1.
A 13-billion-parameter language model is to be trained with the AdamW optimiser and BF16 mixed precision (weights and gradients in BF16; optimiser states in FP32).
Compute the total model state memory in gigabytes, following Equation .
If each training GPU has 80,GB of memory and 25% must be reserved for activations, determine the minimum number of GPUs required to hold the model state.
Repeat the calculation for a 70B model. At what point does tensor parallelism within a node become strictly necessary?
Exercise 2.
A cluster of 256 A100 GPUs connected by 200,Gbps (25,GB/s) InfiniBand runs data-parallel training on a 7B model.
Using the ring-allreduce formula for communication volume, compute the minimum data volume transferred per worker per step. (Hint: ring-allreduce achieves optimal total data movement per worker for large .)
If a forward+backward pass takes 0.8 seconds per step, what fraction of step time is consumed by communication?
Suggest two algorithmic strategies to reduce this fraction without increasing batch size.
Challenge 1.
The Chinchilla scaling law states that, for optimal compute allocation, the number of training tokens should scale linearly with the number of model parameters : .
Using Equation and the Chinchilla relation, express the optimal compute budget as a function of alone.
A team has a budget of FLOPs (approximately the compute used for GPT-4). What is the Chinchilla-optimal model size, and how many tokens should it be trained on?
If the target cluster achieves 40% MFU on an array of H100 GPUs (each at 989 TFLOPS BF16), how many H100s are required to complete training in 90 days?
Discuss how the answer to (c) changes if the team can double MFU through better parallelism. Quantify the cost savings at a hypothetical rate of $2 per GPU-hour.
GPU Architecture and the Accelerator Landscape
The choice of hardware for distributed generative AI is not a commodity decision. Different accelerators differ by an order of magnitude in the bandwidth and compute they provide for specific operations, and these differences determine which parallelism strategies are effective, which precision formats are viable, and ultimately how fast a model can be trained or served. This section develops the architectural understanding needed to make those choices.
GPU vs. CPU: The SIMT Paradigm
A central processing unit (CPU) is designed for latency: it executes a single instruction stream as fast as possible, with out-of-order execution, branch prediction, large caches, and speculative prefetching to minimise the time any single instruction waits. A modern server CPU (e.g., an AMD EPYC 9654) has 96 cores, each running at up to 3.7,GHz with AVX-512 vector units.
A GPU is designed for throughput: it sacrifices the latency-hiding machinery of the CPU in favour of massive parallelism over thousands of simple cores. An NVIDIA H100 GPU has 16,896 CUDA cores organised into 132 Streaming Multiprocessors (SMs), each SM running up to 2048 concurrent threads. The total concurrency is over 270,000 threads.
This architecture is called SIMT: Single Instruction, Multiple Threads. Groups of 32 threads (a warp) execute the same instruction simultaneously. If threads in a warp diverge (take different branches), the hardware serialises the divergent paths, causing warp divergence and reducing throughput. Efficient GPU kernels minimise branch divergence and maximise the fraction of cycles where all warp threads execute the same instruction path.
For matrix multiplication - the dominant operation in transformer training - this architecture is ideal. A matrix multiply times decomposes into independent dot products, each of which can be assigned to a different thread. The regularity of the computation means near-zero warp divergence and near-peak hardware utilisation, which is why matrix multiply is the one operation for which GPUs achieve hardware utilisation close to 90% of theoretical peak.
The GPU Memory Hierarchy
Understanding GPU memory is inseparable from understanding GPU performance. The memory hierarchy has three relevant levels for AI workloads:
High Bandwidth Memory (HBM).
The main GPU memory, implemented as stacked DRAM dies connected to the GPU die via a wide memory interface (typically 5120 bits). The A100 uses HBM2e at 2,TB/s bandwidth and 80,GB capacity. The H100 uses HBM3 at 3.35,TB/s and 80,GB capacity (or HBM3e at 3.35,TB/s and 141,GB in the H200 variant).
Shared Memory / L1 Cache (SRAM).
Each SM has 228,KB of combined L1 cache and shared memory on the H100. SRAM operates at approximately 19–30,TB/s effective bandwidth, roughly 10 faster than HBM. Kernels that can stage their working data in shared memory - a technique called tiling - achieve dramatically higher throughput. The FlashAttention algorithm, which achieves linear memory complexity for attention, works precisely by tiling the attention computation to fit in SRAM.
Register File.
Each CUDA thread has access to a private register file. The H100 has 65,536 32-bit registers per SM, shared among resident threads. Register spilling - when a kernel uses more registers than available and must store the overflow in slower shared memory - is a common source of unexpected performance degradation in hand-written kernels.
NVIDIA GPU Evolution: V100 to B200
The cadence of NVIDIA GPU releases has been the hardware heartbeat of the AI training era. Each generation brought architectural improvements in matrix computation, memory bandwidth, and interconnect that enabled the next step in model scale.
V100 (Volta, 2017). The V100 introduced Tensor Cores - specialised matrix multiply units that execute a matrix multiply per clock per Tensor Core. Peak throughput: 125 TFLOPS in FP16. Memory: 32,GB HBM2 at 900,GB/s. NVLink 2.0: 300,GB/s bidirectional. The V100 was the GPU of choice for GPT-2 and early BERT pre-training runs.
A100 (Ampere, 2020). Introduced BF16 training (the dominant format for LLM training), third-generation Tensor Cores with sparsity support, and NVLink 3.0. Peak throughput: 312 TFLOPS in BF16. Memory: 80,GB HBM2e at 2,TB/s. NVLink 3.0: 600,GB/s bidirectional. The A100 powered GPT-3, PaLM, and the first generation of large-scale diffusion training.
H100 (Hopper, 2022). The Hopper architecture introduced the Transformer Engine, which dynamically selects FP8/BF16 precision per layer, effectively doubling usable compute for transformer workloads. Peak throughput: 989 TFLOPS BF16 (or 1979 TFLOPS with FP8). Memory: 80,GB HBM3 at 3.35,TB/s. NVLink 4.0: 900,GB/s bidirectional. DGX H100: 8H100 with full-mesh NVSwitch for 900,GB/s between any pair. The H100 is the primary training chip for GPT-4, Llama-3, and Gemini.
B200 (Blackwell, 2024). The Blackwell B200 introduced a 2-die GPU design (connected by a 10,TB/s NVLink-C2C interconnect), FP4 support for inference, and dramatically expanded memory. Peak throughput: up to 4500 TFLOPS FP8. Memory: 192,GB HBM3e at 8,TB/s per GPU. NVLink 5.0: 1800,GB/s bidirectional. The GB200 NVL72 system connects 72 B200 GPUs in a rack-scale unit with 130,TB/s total NVLink bandwidth, effectively making 72 GPUs behave as a single logical device for many workloads.
| GPU | BF16 TFLOPS | HBM Cap. | HBM BW | NVLink BW |
| V100 (2017) | 125 | 32,GB | 900,GB/s | 300,GB/s |
| A100 (2020) | 312 | 80,GB | 2,TB/s | 600,GB/s |
| H100 (2022) | 989 | 80,GB | 3.35,TB/s | 900,GB/s |
| B200 (2024) | 4500 | 192,GB | 8,TB/s | 1800,GB/s |
NVLink and NVSwitch: Intra-Node Fabric
NVLink is a high-bandwidth, point-to-point interconnect between GPU dies developed by NVIDIA. Unlike PCIe (which routes through the CPU or a PCIe switch), NVLink provides a direct GPU-to-GPU path with much higher bandwidth and lower latency.
In the H100 DGX node, 8 GPUs are connected via NVSwitch, a full-bisection crossbar that provides 900,GB/s between every pair of GPUs simultaneously. The full-bisection property means there is no contention: GPU 0 can simultaneously send to GPU 7 at full bandwidth while GPU 1 sends to GPU 4, GPU 2 sends to GPU 5, and so on. This makes the 8-GPU DGX node behave as a single 640,GB virtual GPU for all-reduce and all-to-all operations.
The architectural implication is profound: tensor parallelism (which requires all-reduce communication at every transformer layer boundary) is practical within a node because the communication cost is amortised over the 900,GB/s NVLink fabric. Extending tensor parallelism across nodes, where the available bandwidth is 50,GB/s per InfiniBand port, is 18 more expensive in communication time.
Definition: Arithmetic Intensity and the Roofline Model
Definition 2.
(Arithmetic Intensity.) For a kernel that performs floating-point operations while transferring bytes of data between DRAM and compute units, the arithmetic intensity is: (Arithmetic Intensity) A hardware accelerator with peak compute throughput (FLOPs/s) and peak memory bandwidth (bytes/s) has a hardware ridge point: (Ridge Point) A kernel is compute-bound if and memory-bound if .
For the H100 in BF16, FLOPs/s and bytes/s, giving: (H100 Ridge) Any kernel with arithmetic intensity below 295 FLOPs/byte is memory-bandwidth-limited on the H100, regardless of how many CUDA cores are available.
Proposition 1.
(Roofline Performance Bound.) The achievable throughput (FLOPs/s) of a kernel with arithmetic intensity on hardware with peak compute and peak bandwidth satisfies: (Roofline Bound)
The roofline model provides a useful first-pass classification of every operation in a generative model:
The implications of the roofline model for generative AI design are direct. Embedding lookups, layernorm, and element-wise activations all have arithmetic intensity well below the ridge point and are therefore memory-bandwidth-limited. Large matrix multiplications - the core of MLP layers and QKV projection - have high arithmetic intensity and are compute-limited. Naive attention has low intensity (quadratic memory traffic, quadratic compute, but the memory traffic dominates for small batch sizes), while FlashAttention raises intensity by tiling into SRAM.
Insight.
The majority of operations in a generative transformer - all element-wise operations, softmax, layer normalisation, embedding lookups - are memory-bandwidth-limited, not compute-limited. This means that on the H100, most of the 989,TFLOPS of peak compute capacity sits idle during these operations. Algorithmic improvements that increase arithmetic intensity (FlashAttention, fused kernels, quantisation) unlock this latent capacity and deliver speedups that no amount of hardware scaling alone can achieve.
TPU Architecture: Systolic Arrays and Pods
Google's Tensor Processing Units (TPUs) take a different architectural approach to accelerating matrix computation. Where GPUs use many-core SIMT parallelism, TPUs use systolic arrays - a hardware design that pipes data through a 2D grid of multiply-accumulate units in a wave-like (systolic) pattern, eliminating memory traffic for intermediate results.
A systolic array of size can compute a matrix multiplication by feeding the left matrix row-by-row down the columns and the right matrix column-by-column across the rows, with each cell accumulating partial products. The key property is that each element is read from memory once and reused times as it travels across or down the array, achieving arithmetic intensity of - which for (the TPU v4 matrix unit size) gives 128 FLOPs/byte for matrix multiply.
TPU v4 and v5. The TPU v4 chip achieves 275 TFLOPS in BF16 with 32,GB of HBM. TPU v4 pods connect 4096 chips via a 3D torus ICI (Inter-Chip Interconnect) with 1.2,Tb/s bandwidth between adjacent chips. The ICI topology means that all-reduce across an entire pod is fast: ring-based all-reduce on a 3D torus achieves much lower latency than on a fat-tree InfiniBand network for large cluster sizes. TPU v5p scales to 8960 chips per pod.
Accelerator Comparison
| Chip | Vendor | BF16 TFLOPS | Mem. | Mem. BW | Interconnect BW |
| A100 SXM | NVIDIA | 312 | 80,GB | 2.0,TB/s | 600,GB/s (NVLink 3.0) |
| H100 SXM | NVIDIA | 989 | 80,GB | 3.35,TB/s | 900,GB/s (NVLink 4.0) |
| B200 SXM | NVIDIA | 4500 | 192,GB | 8.0,TB/s | 1800,GB/s (NVLink 5.0) |
| TPU v5p | 459 | 95,GB | 2.76,TB/s | 4.8,Tb/s (ICI) | |
| Gaudi 3 | Intel | 1835 | 128,GB | 3.7,TB/s | 3.7,TB/s (HCCL) |
Several observations follow from Table tab:distgen:accelerator-comparison:
The B200 achieves a 4.6 compute advantage over the H100 in BF16, driven primarily by larger Tensor Core arrays and FP8 compute units operating in BF16-equivalent mode.
The TPU v5p has lower BF16 throughput than the H100 but its 4.8,Tb/s ICI bandwidth (across the pod) enables all-reduce operations that would bottleneck on InfiniBand clusters.
Intel's Gaudi 3 offers competitive compute and high on-chip interconnect bandwidth, representing a viable alternative for workloads where NVIDIA supply constraints are binding.
Memory capacity, not raw compute, is often the binding constraint for serving very large models; the B200's 192,GB advantage over the H100's 80,GB is therefore significant for inference workloads.
Insight.
Hardware determines strategy. The 18:1 ratio of NVLink bandwidth to InfiniBand bandwidth on a typical A100 or H100 cluster means that tensor parallelism - which requires all-reduce at every transformer layer boundary - should be confined to GPUs within a single node. Pipeline parallelism, with its lower per-step communication volume (activations at layer boundaries rather than all gradients), is better suited to cross-node communication. This hardware-derived constraint shapes the entire design space of 3D parallelism strategies, and understanding it is prerequisite to making sensible parallelism decisions for any new model.
Example: Training Time for a 7B Model
Example 1.
Estimating training time for a 7B LLM.
We wish to train a 7-billion-parameter language model on 1 trillion tokens following Chinchilla-style compute allocation.
Step 1: Total FLOPs. Using Equation : (7B Flops)
Step 2: Time on different hardware. Assuming 40% MFU (realistic for a well-tuned cluster):
where is the number of devices and is peak FLOPS.
| Hardware | (TFLOPS) | (days) | |
| 8 A100 (1 node) | 312 | 8 | 586 |
| 64 A100 (8 nodes) | 312 | 64 | 73 |
| 64 H100 (8 nodes) | 989 | 64 | 23 |
| 128 H100 | 989 | 128 | 11.5 |
| 128 B200 | 4500 | 128 | 2.5 |
Step 3: Memory feasibility check. Model state memory (Equation ): . A single 80,GB A100 cannot hold the full model state; minimum 2 GPUs are required for model state alone (or ZeRO-3 with gradient/optimizer sharding).
Step 4: Efficiency reality. The 40% MFU assumed above requires careful pipeline scheduling, gradient checkpointing, and fused kernel usage. Naive PyTorch DDP with default settings typically achieves 15–20% MFU on a 7B model, tripling the wall-clock time estimates above.
Exercises
Exercise 3.
An H100 GPU runs the following operations during a transformer forward pass. For each, compute the arithmetic intensity and determine whether the operation is compute-bound or memory-bound on the H100 (ridge point: 295,FLOPs/byte; H100 HBM bandwidth 3.35,TB/s).
Linear projection. A query projection matrix is applied to an activation tensor with , . Compute the FLOPs (2 for a matmul of shape times ) and the bytes read/written.
Layernorm. Applied to the same activation tensor of shape . FLOPs: approximately (mean, variance, normalise, scale, shift). Bytes: read the activation and write the output ( data size) plus reading weight and bias vectors.
Softmax. Applied to an attention score matrix of shape with , . FLOPs: approximately . Bytes: read scores, write softmax output.
Exercise 4.
A research team is designing a 30B-parameter model and plans to use tensor parallelism with degree (splitting each attention and MLP weight matrix across GPUs). At each transformer layer, tensor parallelism requires one all-reduce of size bytes where , , .
Compute the all-reduce data volume per layer in megabytes for BF16 precision.
With the all-reduce implemented as ring-allreduce, the effective communication time is approximately where is bandwidth. For with NVLink at 900,GB/s and InfiniBand at 50,GB/s, compute the all-reduce time for each.
The forward pass compute time per layer is approximately FLOPs. For the H100 at 989,TFLOPS, compute the compute-to-communication ratio for NVLink and InfiniBand cases.
Based on your results, justify the standard practice of confining tensor parallelism to within a single NVLink domain.
Challenge 2.
A company trains a 13B LLM on 2 trillion tokens. Its current cluster has 512 A100 80,GB GPUs connected by 200,Gbps InfiniBand (25,GB/s per link) and achieves 35% MFU.
Estimate the total training time in days.
The company is offered a choice: (i) add 512 more A100s (same cluster topology), or (ii) upgrade the entire cluster to 512 H100s. Ignoring communication bottlenecks, estimate the speedup from each option.
In practice, doubling the number of A100s doubles the communication volume for all-reduce, potentially reducing MFU. Using the Amdahl-style analysis, if communication accounts for 30% of step time in the original configuration, estimate the effective speedup of option (i). (Hint: communication time stays roughly constant as more GPUs are added in a ring-allreduce topology, while compute time halves.)
If the company's goal is to complete training in under 30 days, which hardware option achieves this, and at what MFU would it need to run?
Discuss how replacing InfiniBand with 400,Gbps NDR InfiniBand (50,GB/s) affects your analysis in part (c).
Network Topologies for Distributed Training
Every distributed training system is a graph. Nodes are processing units - GPUs, TPUs, or other accelerators - and edges are the communication links that carry gradients, activations, and parameters between them. The shape of that graph, its topology, determines almost everything that matters for performance: how long all-reduce takes, how much bandwidth is available between any pair of nodes, how many hops a message must traverse before it arrives.
A model parallelism scheme that works beautifully on a ring of eight GPUs may perform catastrophically on a fat-tree network with a hundred nodes, because the communication pattern it generates is fundamentally mismatched to the graph it runs on. Topology awareness is therefore not an implementation detail to be delegated to a network engineer. It is a first-class design principle that shapes every algorithmic choice in distributed deep learning.
This section develops the formal theory of network topologies, surveys the five families that matter most in modern clusters, and establishes the quantitative tools - bisection bandwidth, diameter, cost - that allow principled topology selection. We end with the NVIDIA DGX architecture as a concrete case study that combines multiple topology levels within a single physical system.
Why Topology Matters: The Geometry of Communication
A Motivating Thought Experiment
Imagine 16 GPUs arranged in a line: GPU 0 connected to GPU 1, GPU 1 to GPU 2, and so on up to GPU 15. To broadcast a value from GPU 0 to every other GPU, the message must traverse up to 15 hops. Now rearrange the same 16 GPUs in a grid with wraparound edges. The maximum distance between any two GPUs drops to 4. The physical hardware has not changed. The bandwidth of each link has not changed. Only the wiring pattern has changed - yet communication time is cut by more than half.
This is the fundamental insight: topology controls the effective bandwidth and latency available to any distributed algorithm, not just the raw link speeds. A 100 Gbps link is useless if messages must traverse 15 of them in sequence to reach their destination.
Topology-Algorithm Co-Design
Modern distributed training frameworks select collective communication algorithms - all-reduce, broadcast, all-gather, reduce-scatter - based on the topology they detect at runtime. NCCL (NVIDIA Collective Communications Library) uses topology auto-detection to choose between ring, tree, and direct all-reduce patterns. The right algorithm for a ring is not the right algorithm for a fat-tree; running the wrong one can cost – in communication time.
The formal tools that enable this co-design begin with a precise definition of the communication graph.
Formal Definitions
Definition 3 (Network Topology).
A network topology is a weighted undirected graph where:
is the set of nodes (processing units), ;
is the set of edges (communication links);
assigns a bandwidth (bytes per second) to each edge ;
assigns a latency (seconds) to each edge .
The diameter of is , where is the length of the shortest path from to in terms of hop count.
Definition 4 (Bisection Bandwidth).
Let be a network topology. A bisection of is a partition of into two equal halves with . The bisection bandwidth of is: (Bisection) Intuitively, is the minimum total bandwidth across the worst-case cut that splits the network in half. A topology with high bisection bandwidth can sustain all-to-all communication patterns without creating bottlenecks.
Remark 1 (Bisection Bandwidth as a Bottleneck Measure).
If a distributed algorithm requires every node in to send data to every node in , the maximum aggregate throughput is bounded by , regardless of the per-link bandwidths. For data-parallel training, the bisection bandwidth determines how quickly gradients can be exchanged across the two halves of the cluster during all-reduce.
Definition 5 (Communication Volume).
For a distributed algorithm running on topology , the communication volume is the total number of bytes transmitted across all links during one step of : (Commvol) An algorithm is communication-volume-optimal if no correct algorithm for the same task on the same topology achieves smaller .
The Five Topology Families
Ring Topology
The ring is the simplest topology: each node is connected to exactly two neighbors, forming a cycle. Formally, in a -node ring, the edge set is .
The ring has diameter and bisection bandwidth where is the per-link bandwidth (the worst cut severs exactly two links). Despite its small bisection bandwidth, the ring supports an elegant all-reduce algorithm - the ring all-reduce - that is bandwidth-optimal in the sense that every link carries exactly bytes per byte of model data. We prove this in Proposition 2.
The ring is the topology of choice for NVLink connections within a single DGX node and for the baseline all-reduce in many deep-learning frameworks.
Torus Topology (2D and 3D)
A -dimensional torus arranges nodes in a -dimensional grid with wraparound edges in every dimension. In a 2D torus with nodes:
each node is connected to and ;
diameter ;
bisection bandwidth (two rows of links are cut).
The 3D torus - used in the IBM Blue Gene series and the Google TPU Pod interconnect - further reduces diameter and increases bisection bandwidth at the cost of higher wiring complexity. Each node has 6 links (two per dimension), the diameter is , and the bisection bandwidth is .
Fat-Tree Topology
The fat-tree, introduced by Charles Leiserson in 1985 and popularized in the Thinking Machines CM-5 and modern InfiniBand clusters, achieves full bisection bandwidth: the total bandwidth across any bisection equals the total bandwidth at the leaves.
A -ary fat-tree has three levels of switches.
edge (leaf) switches, each with downlinks to compute nodes and uplinks.
aggregation switches.
core switches.
Total nodes: . Diameter: hops. Bisection bandwidth: equal to total endpoint bandwidth (ideal).
In practice, fat-trees are often deployed with oversubscription ratios of 2:1 or 4:1 to reduce cost: uplinks carry less bandwidth than downlinks. A -ary fat-tree with :1 oversubscription has bisection bandwidth where is the per-endpoint bandwidth.
Fat-trees are standard in InfiniBand HPC clusters and are used by cloud providers including AWS (EFA networks) and Azure (InfiniBand for A100/H100 nodes).
Dragonfly Topology
The dragonfly topology, introduced at SC'08, targets very large systems ( nodes) where the cost of full-bisection fat-trees becomes prohibitive.
A dragonfly organizes nodes into groups (router chassis), each connected in an all-to-all pattern within the group. Groups are then connected by a smaller number of global links. This two-level hierarchy achieves:
diameter 3 (hostlocal routerglobal link destination routerdestination host);
bandwidth cost roughly half that of a fat-tree at the same scale, by reducing the number of global high-cost links;
the need for adaptive routing to avoid global link congestion when many pairs communicate simultaneously.
The Cray Slingshot interconnect used in the Frontier and Aurora exascale supercomputers implements a dragonfly+ topology.
Hypercube Topology
The -dimensional hypercube connects nodes so that two nodes are adjacent if and only if their binary addresses differ in exactly one bit. Properties:
diameter - the shortest diameter possible for any topology connecting nodes with the same node degree;
node degree (increases with , limiting scalability);
bisection bandwidth (the minimum cut severs links).
Hypercubes were prominent in early parallel computers (Intel iPSC, nCUBE) and remain theoretically important because many collective algorithms - butterfly all-reduce, recursive halving-doubling - map naturally onto hypercube communication patterns and can be emulated on fat-trees.
TikZ Figure: Five Topologies
Ring All-Reduce: Cost Analysis
The ring all-reduce algorithm proceeds in two phases. Let be the number of nodes, each holding a gradient vector of bytes.
Reduce-scatter phase: rounds. In round , each node sends its chunk of size to node and receives a chunk from node , accumulating the partial reduction. Each link carries bytes per round.
All-gather phase: rounds. Each node forwards its fully-reduced chunk to node . Again, each link carries bytes per round.
Proposition 2 (Ring All-Reduce Communication Cost).
In the alpha-beta model with latency and inverse bandwidth , the ring all-reduce of an -byte message across nodes has time cost: (RING AR COST)
Proof.
Each of the two phases has rounds. In each round, every node sends a message of size to its neighbor, incurring one startup cost and a transfer time of . The total time for the reduce-scatter phase is and identically for the all-gather phase. Summing both phases:
Remark 2 (Bandwidth Optimality of Ring All-Reduce).
As , the bandwidth term approaches . This is the information-theoretic minimum: each of the nodes must receive bytes of data (the fully reduced result), so the minimum total traffic is bytes distributed across links, giving bytes per link in each direction, or bytes per link round-trip. The ring all-reduce achieves this bound, making it bandwidth-optimal regardless of . See prop:distgen:ring-bandwidth-optimal in The Alpha-Beta Communication Model for the formal statement and proof.
Topology Comparison
tab:distgen:topology-comparison summarizes the key properties of the five topology families.
| lXXXX Topology | Diameter | Bisect. BW | Node degree | Used by |
| Ring | 2 | NVLink within DGX, MPI defaults | ||
| [4pt] 2D Torus | 4 | Google TPU Pod v2/v3 | ||
| [4pt] 3D Torus | 6 | IBM Blue Gene, Google TPU Pod v4 | ||
| [4pt] Fat-Tree (-ary) | InfiniBand HPC, AWS EFA, Azure NDv5 | |||
| [4pt] Dragonfly | 3–5 | Cray Slingshot, Frontier, Aurora | ||
| [4pt] Hypercube | Intel iPSC, algorithm emulation |
NVIDIA DGX Architecture: A Multi-Level Topology
The NVIDIA DGX A100 system exemplifies how modern AI hardware implements a hierarchy of topologies within a single product.
Within the Node: NVSwitch All-to-All
A single DGX A100 contains 8 NVIDIA A100 GPUs interconnected by 6 NVSwitch chips. Unlike a ring (where each GPU connects to 2 neighbors) or a tree, NVSwitch implements a non-blocking all-to-all switch fabric: every GPU can simultaneously communicate with every other GPU at full bandwidth. This is topologically equivalent to a complete graph on the GPU level.
NVLink 3.0 bandwidth: 600 GB/s bidirectional per GPU.
NVSwitch total bisection bandwidth: GB/s = 2.4 TB/s.
All-reduce of bytes across 8 GPUs: (single-step, no multi-hop bottleneck).
Between Nodes: InfiniBand Fat-Tree
Multiple DGX nodes are connected via InfiniBand HDR (200 Gb/s per port) in a fat-tree or dragonfly topology. Each DGX A100 has 8 InfiniBand ports, one per GPU, providing aggregate inter-node bandwidth of GB/s = 200 GB/s.
The bandwidth mismatch is stark:
Intra-node (NVLink): 600 GB/s per GPU.
Inter-node (InfiniBand): 25 GB/s per GPU.
This mismatch means that all-reduce operations that cross node boundaries are 24 times slower per byte than operations that stay within a node. This is why tensor parallelism (which requires all-to-all within a node) is placed on NVLink-connected GPUs, while pipeline and data parallelism (which require less frequent, larger messages) are placed across InfiniBand-connected nodes.
The DGX SuperPOD
A DGX SuperPOD connects 32 DGX A100 nodes ( GPUs) via a fat-tree InfiniBand fabric. The full system delivers TFLOPS = 79.9 PFLOPS of FP16 compute with GB/s = 6.4 TB/s of inter-node bandwidth.
Example: All-Reduce Through a Fat-Tree
Example 2 (Tracing an All-Reduce Through a Fat-Tree).
Consider a 2-ary fat-tree with 8 leaf nodes (GPUs) organized as two pods of 4, with 4 core switches providing full bisection bandwidth. We perform an all-reduce of a gradient tensor of size GB.
Step 1: Reduce-scatter within each pod. GPUs 0–3 (pod A) perform a ring reduce-scatter among themselves. Each GPU sends MB to its in-pod neighbor via the pod's aggregation switch. This traffic stays below the aggregation layer; no core switches are used. Time: .
Step 2: All-reduce across pods (via core switches). Each GPU in pod A sends its 256 MB reduced chunk to the corresponding GPU in pod B, traversing the aggregation and core switches. GPUs 0A and 0B perform a 2-GPU all-reduce (swap and add): each sends 256 MB up through the fat-tree. With InfiniBand HDR (25 GB/s), transmitting 256 MB takes ms. All 4 inter-pod pairs do this simultaneously; the fat-tree's full bisection bandwidth ( GB/s = 100 GB/s total) prevents congestion.
Step 3: All-gather within each pod. Each GPU broadcasts its final 256 MB chunk to the other 3 GPUs in its pod, mirroring step 1.
Total data moved per GPU: MB GB (one reduce-scatter and one all-gather, each of 256 MB per in-pod round and 256 MB for the cross-pod exchange). Total wall time (dominant term): ms.
This illustrates the key benefit of hierarchical collective algorithms: by confining as much communication as possible to the fast intra-pod links and using the slower inter-pod links only once per chunk, we minimize utilization of the bandwidth bottleneck.
Key Idea: Topology as Constraint
Key Idea.
The topology is the skeleton - every distributed algorithm must fit its shape. A ring all-reduce is bandwidth-optimal on a ring but wastes potential shortcuts on a fat-tree. A tree broadcast saturates the root's links on a ring but distributes load perfectly on a fat-tree. Before choosing a parallelism strategy or a collective algorithm, ask: what topology do I have, and what communication pattern does it reward? The answer determines whether your training run is topology-efficient or topology-oblivious - and the performance difference can exceed .
Exercises
Exercise 5.
Consider a 2D torus with 16 nodes and per-link bandwidth GB/s.
Compute the bisection bandwidth of the torus.
Compare with a 16-node ring of the same per-link bandwidth.
A 16-GPU ring all-reduce of a 10 GB gradient tensor takes time . By how much does the torus's larger bisection bandwidth allow you to speed up the corresponding torus all-reduce (assume a torus-aware 2D all-reduce algorithm that halves the distance in each dimension)?
Exercise 6.
A -ary fat-tree (no oversubscription, ) connects nodes.
Express the diameter as a function of and .
Show that bisection bandwidth scales as , i.e., it is full bisection bandwidth.
A data center uses , giving nodes. Each link runs at 25 GB/s. Compute the bisection bandwidth and compare to a 128-node hypercube with the same per-link speed.
Exercise 7.
You are training a 70B-parameter model (280 GB in FP32) using a combination of tensor parallelism () and pipeline parallelism () on a DGX SuperPOD with 256 A100 GPUs ( nodes GPUs).
How many data-parallel replicas are there?
Which parallelism dimension should be placed on NVLink (within a node) and which on InfiniBand (across nodes)? Justify your answer in terms of the bandwidth requirements of each parallelism type.
Estimate the time per all-reduce step for the data-parallel gradient synchronization if the gradient size per replica is GB. Use InfiniBand bandwidth 25 GB/s per GPU.
The Alpha-Beta Communication Model
The Fundamental Question
How long does it take to send a message from one GPU to another?
This question sounds simple, but it underlies every performance prediction, algorithm design decision, and system tuning effort in distributed deep learning. The answer depends on two completely separate physical phenomena that happen to coexist in every communication link:
Latency: the time that elapses before even the first bit of your message arrives at the destination. This is governed by the speed of light, switch forwarding delays, software stack overhead, and network protocol negotiation. It does not depend on how much data you are sending.
Bandwidth: the rate at which data flows once the link is active. This is governed by the physical signalling speed of the link and is (approximately) fixed by the hardware.
These two quantities are independent. A 400 Gbps InfiniBand link has extraordinary bandwidth but still incurs of hardware latency plus of software (MPI/NCCL) overhead. Conversely, a 1 Gbps Ethernet link may have the same latency but 400 less bandwidth. An algorithm that sends millions of tiny messages may be latency-bound even on a 400 Gbps fabric; an algorithm that sends a few enormous messages may be bandwidth-bound even on a high-latency WAN.
The Train Analogy
Before formalizing the model, consider a vivid physical analogy that makes the two terms immediately intuitive.
Imagine you need to move a large crowd of passengers from city A to city B by train. The journey has two completely distinct phases:
Waiting for the first coach to arrive at the platform. No matter how many passengers you have, no matter how long the train is, you must wait for the engine and the first coach to pull into the station. This waiting time is fixed: it depends on the distance between cities, the speed of the engine, and the time the driver takes to respond to the departure signal. It does not change whether you have 10 passengers or 10,000 passengers. This is latency: .
Passengers disembarking once the train has arrived. Once the first coach is at the platform, passengers begin streaming off. If the doors are wide and the platform is long, passengers disembark quickly (high bandwidth, small ). If the doors are narrow or the coaches are long, disembarkation takes longer (low bandwidth, large ). And crucially: the more passengers there are, the longer this takes. Time (number of passengers) . This is the bandwidth contribution: .
Total journey time = waiting for the first coach () + time for all passengers to disembark () = .
Once the first coach arrives, the rest follow quickly - coach after coach at a steady rate determined by track capacity (bandwidth). That is why reducing latency matters more than you might think: if you are sending many small messages, the term dominates and no amount of bandwidth improvement will help. Conversely, for a single enormous transfer, is a one-time fixed cost amortized over , and bandwidth is what matters.
Formal Definition
Definition 6 (Alpha-Beta Communication Model).
In the alpha-beta model (also called the linear model or Hockney model), the time to transmit a message of bytes from one node to another is: (Alphabeta) where:
is the latency (seconds), also called the startup time or overhead: the time elapsed before any data has been received, regardless of message size;
is the inverse bandwidth (seconds per byte), also called the gap: the time to transfer one additional byte once transmission has begun. If the link bandwidth is bytes/second, then ;
is the message size in bytes.
The model assumes that message transfer is pipelined: once the first byte departs, subsequent bytes follow at rate without additional startup costs.
Remark 3 (Typical Values in Practice).
Representative values for modern interconnects:
NVLink 3.0 (intra-node): , ; equivalently GB/s.
InfiniBand HDR (inter-node): , ; equivalently GB/s.
100 GbE Ethernet: , ; equivalently GB/s.
The bandwidth ratio NVLink : InfiniBand : Ethernet is roughly 600 : 25 : 12.5, while the latency ratio is much tighter: .
Point-to-Point and Collective Costs
Point-to-Point Transfer
By definition, a single point-to-point message of bytes costs: (P2P)
Broadcast
A broadcast sends a message of bytes from one root node to all other nodes. The optimal tree-based implementation proceeds in rounds, doubling the number of informed nodes each round. In round , every node that has the data sends it to one new node.
(Bcast)
Derivation. There are rounds. In each round, every active sender transmits the full -byte message to one new receiver: cost per round. Rounds are sequential, giving (Bcast).
All-Reduce: Butterfly vs Ring
Butterfly (Recursive Halving-Doubling).
The butterfly all-reduce, natural on a hypercube, proceeds in rounds. In round , each node exchanges half its data with a partner at distance . The total cost is: (AR Butterfly) The factor in the bandwidth term reflects that each node effectively sends and receives the full message once (total bytes), reduced by because its own chunk needs no transmission.
Ring.
From Proposition 2: (AR RING)
Comparison.
The bandwidth terms of and are identical. The difference lies entirely in the latency term: (butterfly) versus (ring). For large , the butterfly has latency rounds while the ring has latency rounds.
If , i.e., we are latency-bound, use the butterfly.
If , i.e., we are bandwidth-bound, both algorithms perform identically; use the ring (simpler).
In deep learning, gradient all-reduce involves large tensors (– bytes) and is modest (8–1024 GPUs), so and we are almost always bandwidth-bound. Ring all-reduce is the standard choice.
Communication Costs of Common Collectives
tab:distgen:collective-costs summarizes the alpha-beta cost formulas for the most common collective operations.
| lXX Collective | Alpha-Beta Cost | Notes |
| Point-to-point | Baseline | |
| [4pt] Broadcast (tree) | Root sends to all; optimal for large | |
| [4pt] Reduce (tree) | Same structure as broadcast | |
| [4pt] All-reduce (ring) | BW-optimal; latency rounds | |
| [4pt] All-reduce (butterfly) | Latency-optimal; same BW as ring | |
| [4pt] All-gather (ring) | Each node contributes bytes | |
| [4pt] Reduce-scatter (ring) | Symmetric to all-gather | |
| [4pt] All-to-all | Each node sends to each other | |
| [4pt] Barrier | No data; pure synchronization cost |
Bandwidth Optimality of Ring All-Reduce
Proposition 3 (Ring All-Reduce is Bandwidth-Optimal).
For an all-reduce of bytes across nodes on a ring (or any topology), the minimum total bytes transmitted across any single link is . The ring all-reduce achieves this bound.
Proof.
Consider the all-reduce problem: each of nodes starts with a vector of bytes; all must end with the element-wise sum.
Lower bound. Focus on a single link . Node must learn the contribution of every node on the “-side” of the link, and vice versa. In the worst case (a single link cut), all information from one side must pass through this link. Each side has nodes, collectively holding bytes of unique data. However, the output at requires knowing only the sum (not individual values), so it suffices to send bytes across the link in each direction. Thus every link must carry at least bytes in each direction, i.e., at least bytes total per link.
More precisely, for the ring with nodes, each link carries exactly bytes per direction in the ring all-reduce, giving per link round-trip. As , this approaches per link.
Achievability. In the reduce-scatter phase of ring all-reduce, node sends chunk of size to node in round 1, and in round it forwards the chunk it received in round . Over rounds, each link carries bytes in one direction. The all-gather phase is symmetric. Total per link: , matching the lower bound up to the factor .
Timeline Diagram: Latency vs Bandwidth
fig:distgen:timeline illustrates how the alpha-beta model decomposes communication time into latency and bandwidth contributions for three different message sizes.
Crossover Point and Regime Analysis
The crossover between the latency-dominated and bandwidth-dominated regimes occurs at: (Crossover) For , the latency term dominates and the effective throughput is far below the peak bandwidth . For , the bandwidth term dominates and throughput approaches .
Remark 4 (Regime Analysis for InfiniBand HDR).
For InfiniBand HDR with and , (equivalently ): Messages smaller than 75 kB are latency-bound on InfiniBand HDR. Gradient vectors in a 7B-parameter model are GB per replica, far above , confirming that large-model all-reduce is purely bandwidth-bound.
Example: All-Reduce for a 7B Model
Example 3 (All-Reduce Time for a 7B Model on 8 GPUs).
Setup. A 7B-parameter model in BF16 (2 bytes/parameter) has gradient tensors of size GB per data-parallel replica. We run data-parallel training across GPUs and perform a ring all-reduce after each backward pass.
Scenario A: NVLink (within a DGX node). , .
Using (AR RING): (EX Nvlink) The latency contribution is , utterly negligible compared to the bandwidth term. This is firmly in the bandwidth-bound regime.
Scenario B: InfiniBand HDR (across nodes). , .
(EX IB)
Comparison. NVLink all-reduce is faster than InfiniBand all-reduce, exactly matching the bandwidth ratio (). Since both are bandwidth-bound, the latency difference ( vs ) is irrelevant.
For a training step that also includes 100 ms of compute, the communication-to-compute ratio is:
NVLink: (communication is of step time);
InfiniBand: (communication is of step time and dominates).
This illustrates why gradient compression, communication-computation overlap, and multi-node tensor/pipeline parallelism are critical when training large models across InfiniBand-connected nodes.
Insight: Latency-Bound vs Bandwidth-Bound
Insight.
The alpha-beta model is simple but powerful - it tells you instantly whether you are latency-bound or bandwidth-bound. Compute . If your message size , no amount of bandwidth hardware will help: you need to reduce the number of messages (batching, aggregation) or reduce latency (RDMA, kernel bypass). If , no amount of latency optimization will help: you need more bandwidth (faster links, more links, topology redesign, or gradient compression to reduce ). Large-model all-reduce almost always falls in the bandwidth-bound regime; the alpha-beta model confirms this in two lines of arithmetic.
Exercises
Exercise 8.
Consider two interconnects:
Interconnect A: , (NVLink 4.0).
Interconnect B: , (hypothetical high-latency fabric).
Compute the crossover message size for each interconnect.
For a scatter-reduce of 128 MB messages across 16 GPUs, which interconnect is faster? By how much?
Explain why two interconnects with the same bandwidth can have different optimal collective algorithms.
Exercise 9.
A cluster has nodes with and (i.e., ). You need to perform an all-reduce of a 1 GB gradient tensor.
Compute and for this configuration.
At what message size does the ring become worse than the butterfly by more than 10%? (Solve for analytically, then substitute numbers.)
In practice, NCCL uses a hybrid algorithm. Sketch why a reduce-scatter (butterfly) followed by an all-gather (ring) might combine the best of both.
Exercise 10.
Continuing Example 3 (7B model, 8 GPUs, InfiniBand).
With gradient compression at a 100:1 ratio (e.g., 1-bit quantization), what is the new all-reduce time?
Assume the backward pass takes 200 ms and gradients can be pipelined: the all-reduce for layer begins as soon as the backward pass for layer completes, while the backward pass continues through layer . If gradients are evenly distributed across layers, what is the total step time with overlap? (Use uncompressed InfiniBand all-reduce time from (EX IB).)
Compare the step times in (a) and (b). Which strategy gives a larger speedup?
Message Passing Interface (MPI) Tutorial
Every framework that trains large language models across hundreds of GPUs ultimately rests on a single substrate: the ability of one process to send a buffer of bytes to another process on a different machine, reliably, at high speed, and with well-defined semantics. The Message Passing Interface-MPI-is the standard that codifies exactly this capability. It is not glamorous, and it predates transformers by three decades. But understanding MPI is to understand the grammar of distributed computation: the primitives from which all higher-level abstractions, NCCL, PyTorch Distributed, DeepSpeed's communication engine, are ultimately assembled.
Historical Note.
Three decades of MPI. The story begins in 1992 at the Supercomputing conference, where a workshop on message-passing standards drew together researchers from academia, national laboratories, and industry. The goal was to replace a zoo of vendor-specific libraries-PVM, PARMACS, P4, and others-with a single portable standard. MPI-1 was ratified in May 1994, defining the point-to-point and collective communication operations that remain central today. It specified 129 functions, a design shaped by practical consensus rather than aesthetic purity, and immediately became the lingua franca of high-performance computing.
MPI-2 arrived in 1997 and introduced two ideas that would prove transformative for machine learning decades later: one-sided communication (remote memory access without the remote process being explicitly involved) and dynamic process management. One-sided communication maps directly onto the Remote Direct Memory Access (RDMA) capabilities of modern interconnects like InfiniBand, enabling memory-to-memory transfers that bypass the CPU entirely.
MPI-3 (2012) refined the collective operations and introduced non-blocking variants of collectives, allowing computation to overlap with the communication that was previously a serial bottleneck. It also added support for shared-memory regions within a node, bridging the gap between the message-passing and shared-memory worlds.
MPI-4 (2021) brought large-count support (buffers exceeding elements, critical for billion-parameter model gradients), persistent collective operations, and improved partitioned communication. The persistent collectives are particularly relevant for training: a ring all-reduce repeats the same communication pattern at every training step, and persistent operations eliminate the per-step setup overhead.
Today, MPI is maintained by the MPI Forum, a consortium of over 40 organizations, and implemented by OpenMPI, MPICH, Intel MPI, Cray MPICH, and others. Every cluster running distributed training has MPI installed; it is as fundamental to HPC as TCP/IP is to the internet.
The MPI Execution Model
MPI follows the Single Program, Multiple Data (SPMD) model. Every participating process runs the same program, but they diverge in behavior because each knows its own identity-its rank- within a communicator.
Definition 7 (MPI Communicator).
A communicator is a handle encapsulating:
A group , an ordered set of process identifiers called ranks;
A context, a unique integer tag that logically separates messages in this communicator from those in any other, preventing cross-talk between independent communication domains;
An optional topology, describing the logical arrangement of processes (Cartesian grid, graph, etc.).
The predefined communicator MPI_COMM_WORLD includes all
processes launched by mpirun, with ranks
.
Every MPI communication operation is scoped to a communicator.
When a program calls MPI_Comm_rank( MPI_COMM_WORLD,
&rank), it learns its position in the process group.
When it calls MPI_Comm_size( MPI_COMM_WORLD,
&size), it learns the total number of participants.
The canonical “hello world” in MPI-stripped to its essence-is:
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
printf("I am rank
MPI_Finalize();
Between MPI_Init and MPI_Finalize, all MPI
communication is valid.
Outside those calls, no MPI function may be used.
The runtime launches copies of this process, each printing a
different rank, producing lines of output in an unspecified order
since message passing does not impose a global ordering on
independent events.
Point-to-Point Communication
The fundamental communication primitive in MPI is the point-to-point message: one process sends, another receives.
Definition 8 (Point-to-Point Communication).
A point-to-point communication in MPI is an ordered pair of operations between a sender with rank and a receiver with rank within communicator , satisfying:
Message envelope: a message is uniquely identified by the tuple , where is an application-level label (with );
Order preservation: if rank sends messages before to rank with the same tag and communicator, then receives before ;
Non-overtaking: messages with matching envelopes are delivered in send order, but messages with different senders may arrive in any order.
The send operation specifies a buffer , count , and
datatype (e.g., MPI_DOUBLE), defining a typed
message of bytes.
The blocking send and receive have signatures:
int MPI_Send(const void *buf, int count, MPI_Datatype datatype,
int dest, int tag, MPI_Comm comm);
int MPI_Recv(void *buf, int count, MPI_Datatype datatype,
int source, int tag, MPI_Comm comm,
MPI_Status *status);
A concrete example: rank 0 sends a parameter tensor to rank 1.
if (rank == 0) {
double params[N];
// ... fill params ...
MPI_Send(params, N, MPI_DOUBLE, 1, 0, MPI_COMM_WORLD);
} else if (rank == 1) {
double params[N];
MPI_Recv(params, N, MPI_DOUBLE, 0, 0,
MPI_COMM_WORLD, MPI_STATUS_IGNORE);
// ... use params ...
}
The wildcard MPI_ANY_SOURCE and MPI_ANY_TAG
allow a receiver to accept from any sender or with any tag,
useful for work-stealing patterns where a coordinator accepts
results from whichever worker finishes first.
Blocking vs. Non-Blocking Communication
The calls MPI_Send and MPI_Recv are blocking:
they do not return until the operation is complete from the calling
process's perspective.
For MPI_Send, “complete” means the send buffer is safe to
reuse (either the message has been copied into a system buffer or the
receiver has begun receiving).
For MPI_Recv, “complete” means the data has arrived in the
receive buffer.
While blocking communication is easy to reason about, it leaves CPU and GPU cycles idle during the communication phase, exactly when we want to be computing. Non-blocking operations solve this by decoupling the initiation of communication from its completion.
MPI_Request req;
// Initiate send - returns immediately
MPI_Isend(buf, N, MPI_DOUBLE, dest, tag,
MPI_COMM_WORLD, &req);
// Do computation here while data is in flight
compute_next_layer(...);
// Wait for send to complete before touching buf again
MPI_Wait(&req, MPI_STATUS_IGNORE);
The MPI_Request handle is the key.
It represents the pending operation; MPI_Wait blocks until
that specific request completes.
Multiple requests can be waited on simultaneously:
MPI_Request reqs[2];
MPI_Isend(send_buf, N, MPI_DOUBLE, dest, 0,
MPI_COMM_WORLD, &reqs[0]);
MPI_Irecv(recv_buf, N, MPI_DOUBLE, src, 0,
MPI_COMM_WORLD, &reqs[1]);
// Overlap with computation
compute_gradients(...);
// Complete both
MPI_Waitall(2, reqs, MPI_STATUSES_IGNORE);
MPI_Send/MPI_Recv, Rank 1 is
idle while Rank 0 transmits and Rank 0 is idle while the message is
acknowledged; computation cannot overlap with the transfer.
(b) With non-blocking MPI_Isend/MPI_Irecv, both
ranks initiate the communication and immediately proceed to
computation while the data is in flight; MPI_Wait at the
end ensures completion before the buffers are reused.
This overlap of communication and computation is the primary tool for
hiding network latency in distributed training.
Figure fig:distgen:blocking-nonblocking visualises the critical difference. In the blocking scenario, every training step has a serial “send, wait, receive” phase during which the accelerators sit idle. In the non-blocking scenario, the data transfer happens in the background of a backward pass, so the next layer's gradient computation overlaps with the previous layer's gradient synchronization. This is not a minor optimisation: at the scale of a 70B-parameter model trained on 1000 GPUs, the communication volume is so large that blocking all-reduces would reduce GPU utilization to below 40%.
Remark 5 (Deadlock with blocking calls).
A subtle hazard of blocking MPI is deadlock.
If rank 0 calls MPI_Send to rank 1, and simultaneously rank 1
calls MPI_Send to rank 0, both processes block waiting for
the other to post a receive.
Neither progresses, and the program hangs.
This is a classic cyclic dependency.
The fix: use MPI_Sendrecv (which handles both directions
atomically) or restructure so that even ranks send first and odd ranks
receive first.
Non-blocking operations inherently avoid this class of deadlock because
initiation never blocks.
Collective Operations
Point-to-point operations are the atoms of MPI. Collectives are the molecules: coordinated multi-process operations that implement common communication patterns in a single call, with implementations optimised for the underlying network topology. All processes in the communicator must call the collective.
Broadcast (MPI_Bcast).
One process (the “root”) has data that every other process needs.
MPI_Bcast(buffer, count, datatype, root, comm);
After the call, every rank holds the same data. In distributed training, broadcast is used to initialize all workers with the same model parameters before training begins. The naive implementation sends point-to-point messages from root; an optimized implementation uses a binomial tree, reducing latency from to .
Reduce (MPI_Reduce).
Every process has local data; a reduction operation (sum, max, min,
logical AND, etc.) combines them, and the result lands at the root.
MPI_Reduce(sendbuf, recvbuf, count, datatype,
MPI_SUM, root, comm);
Only the root's recvbuf is meaningful after the call.
In gradient aggregation, each worker computes local gradients
, and the root obtains
.
All-Reduce (MPI_Allreduce).
Like Reduce, but the result is distributed to all processes,
not just the root.
This is the workhorse of data-parallel training.
MPI_Allreduce(sendbuf, recvbuf, count, datatype,
MPI_SUM, comm);
After MPI_Allreduce, every rank holds
(dividing by is done in the application code).
Ring all-reduce, the algorithm underlying NCCL and PyTorch DDP,
achieves near-optimal bandwidth of of peak network
throughput.
All-Gather (MPI_Allgather).
Every process contributes a piece; every process ends up with
all pieces concatenated.
In ZeRO optimizer (Zero Redundancy Optimizer), model parameters are
sharded across GPUs; before each forward pass, Allgather
reconstructs the full parameter tensor on every GPU.
MPI_Allgather(sendbuf, sendcount, sendtype,
recvbuf, recvcount, recvtype, comm);
Scatter (MPI_Scatter).
The inverse of gather: root has a large array and distributes
distinct chunks to each process.
MPI_Scatter(sendbuf, sendcount, sendtype,
recvbuf, recvcount, recvtype, root, comm);
Figure fig:distgen:collectives shows the data flow for each
collective.
These five primitives, together with their blocked variants and
the MPI_Reduce_scatter operation (reduce followed by
scatter of the result), cover the vast majority of communication
patterns in distributed deep learning.
Table tab:distgen:collectives-cost summarises the asymptotic communication cost of each collective on a -process ring with per-byte bandwidth and per-message latency .
| Collective | Latency | Bandwidth cost |
| Bcast | ||
| Reduce | ||
| Allreduce (ring) | ||
| Allgather (ring) | ||
| Scatter | ||
| Reduce-scatter |
One-Sided Communication and RDMA
Classical two-sided communication (Send/Recv) requires both the sender and receiver to participate actively. In large-scale training, this can create synchronization bottlenecks: a parameter server must explicitly post receives before workers can push updates. One-sided communication removes this requirement.
Definition 9 (One-Sided Communication).
One-sided communication is a model in which process can directly read from or write to a window without requiring to execute any matching MPI call. Formally:
creates a window object exposing memory at base;
writes elements from the caller's buffer into rank 's window;
reads elements from rank 's window into the caller's buffer;
atomically combines the caller's data with the target's window using a reduction operation (e.g.,
MPI_SUM).
Synchronization between one-sided operations is provided by
MPI_Win_fence, MPI_Win_lock/Unlock,
or MPI_Win_flush depending on the synchronization mode.
One-sided communication maps directly onto RDMA: Remote Direct Memory Access. RDMA is a hardware capability, not an MPI abstraction: it allows a network interface card (NIC) to perform DMA operations directly into a remote machine's memory without involving either machine's CPU. The transfer bypasses the operating system kernel, the protocol stack, and the remote CPU, achieving latencies under on InfiniBand networks and bandwidths exceeding on HDR InfiniBand.
MPI_Put.
Machine A's NIC performs a direct memory-to-memory transfer into
Machine B's registered window without involving CPU B at any point.
The data path: CPU A initiates the MPI_Put call,
the memory is registered with NIC A (enabling zero-copy),
NIC A sends the data over InfiniBand or RoCE, and
NIC B writes directly into Machine B's RAM window.
CPU B's involvement is limited to a synchronization call
(MPI_Win_fence) at epoch boundaries.
This path achieves sub-microsecond latency and eliminates OS and
software stack overhead.
Two network technologies enable RDMA at scale:
InfiniBand: a purpose-built interconnect developed in the late 1990s that natively supports RDMA, with current HDR InfiniBand achieving per port and latency. Mellanox (acquired by NVIDIA) and Intel manufacture InfiniBand adapters. Every major AI supercomputer cluster-Summit, Frontier, NVIDIA DGX SuperPOD, and most cloud HPC clusters-uses InfiniBand.
RoCE (RDMA over Converged Ethernet): a standard that runs the InfiniBand transport layer (IB BTH headers) over standard Ethernet, making RDMA accessible on commodity switching hardware. RoCEv2 runs over UDP/IP, enabling RDMA across routed Ethernet networks. Cloud providers (AWS EFA, Azure RDMA, Google's Jupiter network) implement RoCE-style RDMA at scale. The primary operational challenge is loss sensitivity: RDMA queues require lossless transport, so Ethernet must be configured with Priority Flow Control (PFC).
Example: Gradient All-Reduce for LLM Training
We now build a minimal but complete gradient synchronization loop using MPI collectives, illustrating the pattern that underlies every data-parallel training framework.
Suppose we are training a model with parameters across workers. Each worker holds an identical copy of the model and a different shard of the training data.
Example 4 (MPI-based gradient all-reduce).
The training loop on each rank proceeds as follows.
// Each rank owns a full copy of params[D] and grads[D]
double params[D], grads[D];
for (int step = 0; step < num_steps; step++) {
// 1. Forward pass on local data shard
double loss = forward(params, local_data[step]);
// 2. Backward pass: compute local gradient
backward(params, local_data[step], grads); // fills grads[]
// 3. Synchronize gradients across all workers
// Each rank contributes grads[], receives the sum
MPI_Allreduce(MPI_IN_PLACE, // in-place: result overwrites input
grads,
D,
MPI_DOUBLE,
MPI_SUM,
MPI_COMM_WORLD);
// 4. Scale by 1/p to get mean gradient
for (int i = 0; i < D; i++) grads[i] /= size;
// 5. Update parameters (SGD)
for (int i = 0; i < D; i++)
params[i] -= lr * grads[i];
// All ranks now have identical params for next step
}
The MPI_IN_PLACE sentinel tells MPI to use the same buffer
for input and output, avoiding an extra allocation of doubles.
After step 3, all ranks hold
,
where is the gradient computed by rank .
After step 4, all ranks hold the mean gradient
.
Since all ranks perform the same parameter update in step 5,
all model copies remain byte-identical, preserving the
data-parallel invariant.
The communication volume at each step is
bytes1 for double precision, or bytes for
float.
For a 7B-parameter model at float32, this is
per step per
all-reduce call, which at InfiniBand takes
approximately of pure communication time
if not overlapped with computation.
This calculation motivates the obsessive focus on overlap in
frameworks like Megatron-LM and DeepSpeed.
Key Idea.
MPI is the assembly language of distributed computing. Every higher-level distributed training framework implements a subset of the ideas captured in MPI: point-to-point messages for parameter server communication, broadcast for model initialization, all-reduce for gradient synchronization, one-sided operations for RDMA-based memory pooling. NCCL, Gloo, and Horovod are not alternatives to MPI; they are specialized implementations of the same abstractions, optimized for specific hardware (GPU NVLink, CPU Ethernet) and workloads (large homogeneous tensors). Understanding MPI is to understand the contract that any distributed framework must eventually fulfill.
Exercises
Exercise 11.
Ring send. Write an MPI program in which rank sends an integer token (the value ) to rank , and receives a token from rank . After the exchange, have each rank print the token it received.
(a) Implement this using blocking MPI_Send/MPI_Recv.
Verify that with ranks sending in the order ,
, , , no deadlock occurs if ranks
alternate: even ranks send first, odd ranks receive first.
(b) Repeat using MPI_Isend/MPI_Irecv/MPI_Waitall.
Confirm that the result is identical.
(c) Explain why a naive all-blocking implementation (every rank sends before any rank receives) deadlocks, and sketch the cycle in the dependency graph.
Exercise 12.
Manual reduce-scatter.
Let and let each rank hold an array of doubles.
Without calling MPI_Reduce_scatter, implement reduce-scatter
manually using four MPI_Reduce calls (one for each chunk,
with a different root each time).
(a) Measure the wall-clock time of your implementation for
and compare it to MPI_Reduce_scatter.
(b) Explain why the library implementation is faster, referencing the binomial-tree algorithm and the pipelining possible when chunks are sent concurrently.
(c) Show that the communication volume of your implementation is versus for the ring algorithm.
Exercise 13.
Communication-computation overlap. Consider a model with layers, each with parameters. After the backward pass computes the gradient for layer , this gradient can be immediately all-reduced while the backward pass continues through layer .
(a) Write pseudocode using MPI_Iallreduce
(non-blocking all-reduce, available in MPI-3) to implement this
layer-by-layer gradient overlap.
(b) Under what conditions on the compute time per layer and the communication time can the overlap hide all communication latency?
(c) Define the overlap ratio and express the effective GPU utilization . At what value of does overlap cease to help?
NCCL and GPU Communication Libraries
MPI was designed in an era when the compute node was a CPU and memory was flat RAM. It assumes that communication is managed by the CPU and that data lives in host memory. Neither assumption holds in modern GPU clusters. In a DGX H100 node, eight H100 GPUs are connected to each other via NVLink, a dedicated high-speed GPU interconnect that bypasses the CPU entirely and achieves of bidirectional bandwidth. Between nodes, GPUs communicate over InfiniBand through RDMA.
Asking the CPU to orchestrate GPU-to-GPU communication in this environment is like asking a bicycle courier to route messages in a city that has its own pneumatic tube network: the courier adds latency, CPU memory copies, and becomes a bottleneck. NCCL (NVIDIA Collective Communications Library) is NVIDIA's answer: a library that runs collective operations directly on the GPU, using NVLink for intra-node transfers and GPU-Direct RDMA for inter-node transfers, with the CPU doing nothing more than launching the operation.
Why MPI Is Insufficient for GPU Workloads
Standard MPI implementations are not GPU-aware.
When an MPI application calls MPI_Send(gpu_ptr, ...),
the implementation typically:
Copies the GPU buffer to a CPU staging buffer (a synchronous D2H memcopy that stalls the GPU);
Sends the data from CPU memory over the network;
Copies the received data back to a GPU buffer (H2D memcopy).
Each of these steps is expensive. A 1,GB gradient tensor at 900,GB/s NVLink bandwidth transfers in 1,ms NVLink-to-NVLink, but the PCIe bus between GPU and CPU saturates at 32,GB/s, making the round-trip copy take 31,ms-a slowdown.
GPU-aware MPI implementations (OpenMPI with CUDA support, Cray MPICH with GPU support) address this by detecting GPU pointers and routing via RDMA directly, but they still rely on the CPU thread to initiate every communication operation, creating synchronization overhead.
NCCL's key architectural decision: the communication kernels run on the GPU. The CPU posts an NCCL operation and returns immediately; the GPU executes the collective in a stream, overlapping with other GPU kernels scheduled in the same stream or in concurrent streams.
NCCL Architecture and Evolution
NCCL has undergone substantial algorithmic evolution since its first public release (NCCL 1.x, 2015–2016).
- NCCL 1.x: Flat ring.
All-reduce was implemented as a ring all-reduce with a single ring topology connecting all GPUs. Within a node, the ring traversed GPUs over PCIe or NVLink; between nodes, data went over InfiniBand. This achieved near-optimal bandwidth for large messages but suffered from latency for small messages (latency scales with ring circumference).
- NCCL 2.x: Tree-based algorithms.
To address small-message latency, NCCL 2.x introduced double-binary tree collectives. A binomial or binary tree achieves latency versus for a ring, making tree algorithms preferable when the message fits in a few packets. NCCL 2.x uses a dual-tree construction (two complementary binary trees) to keep all links utilized even in tree topology, avoiding the bandwidth underutilization of a single tree.
- NCCL 2.x+: Hybrid algorithms.
Modern NCCL selects the algorithm based on message size, number of ranks, and network topology: ring for large messages (bandwidth-bound), tree for small messages (latency-bound), with tuning tables built from profiling on target hardware. The transition point is typically around – per rank.
- NCCL and NVLink.
Within a DGX node, NCCL detects the NVLink topology (an all-to-all mesh for H100, a hypercube for A100) and chooses ring orderings that maximise NVLink utilization. For 8 H100s connected by NVLink4, NCCL can achieve 700,GB/s all-reduce bandwidth, approaching the NVLink bisection bandwidth.
Ring All-Reduce: The Workhorse Algorithm
Ring all-reduce is the algorithm behind the majority of gradient synchronization in production training. We now develop it formally.
Definition 10 (Ring All-Reduce).
Let processes be arranged in a ring . Each process holds a buffer . The ring all-reduce computes and delivers a copy of to every process.
The algorithm proceeds in two phases, each consisting of steps:
Phase 1: Reduce-scatter ( steps). Partition each buffer into chunks: , where each chunk .
At step , process sends chunk to process , and receives a chunk from process . The received chunk is added to the corresponding local chunk.
After steps, process holds the fully reduced chunk .
Phase 2: All-gather ( steps). Process now sends its fully reduced chunk around the ring. At step , process forwards the chunk it received in step . After steps, every process holds all reduced chunks and thus the full .
Communication volume: each of the steps in each phase transfers elements per process. Total data sent per process: (RING Volume) This is within a factor of of the optimal (the minimum data a process must send to inform all others of its contribution), confirming that ring all-reduce is bandwidth-optimal.
Tree All-Reduce: Latency-Optimal for Small Messages
Ring all-reduce requires communication steps, each taking at least one network latency . For small messages (a few kilobytes of gradients from a lightweight layer), the total latency is , which grows linearly with the number of GPUs. At GPUs with , that is 2,ms just in latency overhead before any data moves.
A tree all-reduce uses a binary or binomial tree topology:
Reduce phase: leaves send to their parent; each internal node accumulates children's values and passes the sum upward. After steps, the root holds the global sum.
Broadcast phase: root sends the global sum down the tree. After another steps, all nodes have the result.
Total latency: steps, reducing the latency from 2,ms to at . The cost: bandwidth efficiency drops because internal tree nodes are bottlenecks-the root must send and receive bytes, consuming full bandwidth, while leaves send and receive only bytes. Tree all-reduce is therefore optimal for latency-bound (small ) workloads and ring all-reduce is optimal for bandwidth-bound (large ) workloads.
The crossover point satisfies: (Crossover) where is the single-link bandwidth. For InfiniBand (, ) with : . Messages below prefer tree; larger prefer ring. This matches NCCL's empirical tuning thresholds.
PyTorch DistributedDataParallel and NCCL
PyTorch's DistributedDataParallel (DDP) is the standard
interface for data-parallel training in Python.
Its design is instructive because it exposes exactly the
communication patterns we have formalized.
Algorithm 1 (PyTorch DDP internals).
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
# Initialize NCCL process group
dist.init_process_group(backend="nccl")
rank = dist.get_rank()
world_size = dist.get_world_size()
device = torch.device(f"cuda:{rank}")
# Wrap model in DDP - hooks registered at init time
model = MyLLM().to(device)
ddp_model = DDP(model, device_ids=[rank])
optimizer = torch.optim.AdamW(ddp_model.parameters(), lr=1e-4)
for step, (inputs, labels) in enumerate(dataloader):
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
# Forward (no communication)
outputs = ddp_model(inputs)
loss = criterion(outputs, labels)
# Backward: DDP hooks fire as each parameter's gradient
# is computed, launching async NCCL all-reduce for that bucket
loss.backward()
# By here, NCCL all-reduces are complete (DDP waited)
optimizer.step()
Internally, DDP works as follows during backward():
During model construction, DDP registers a gradient hook on every parameter. When a parameter's
.gradis populated by autograd, the hook fires.DDP groups parameters into buckets (default 25,MB). When a bucket is fully populated (all parameter gradients in the bucket have been computed), DDP launches an
ncclAllReduceon the bucket asynchronously.The backward pass continues through earlier layers while NCCL transfers the completed bucket in the background.
At the end of
loss.backward(), DDP callstorch.cuda.synchronize()to wait for all pending all-reduces.optimizer.step()sees the averaged gradients (DDP divides by world size during the all-reduce).
The bucket size is the key tuning parameter: too small means many small NCCL calls (high per-call overhead); too large means insufficient overlap because the large bucket takes longer to fill before communication begins.
Gloo: CPU-Based Alternative
Not all distributed training happens on GPU clusters.
CPU-only deployments (federated learning on edge nodes, small models
on commodity hardware, debugging environments without GPU)
need an alternative to NCCL.
Gloo is Facebook AI Research's CPU-based collective
communications library, integrated into PyTorch as a backend for
torch.distributed.
Gloo implements the same all-reduce semantics as NCCL but over standard Ethernet (TCP/IP) without RDMA. It uses a halving-doubling all-reduce algorithm (also called recursive halving-and-doubling or butterfly all-reduce):
In steps, pairs of processes exchange half their data and accumulate;
After steps, every process holds the global sum.
Gloo also supports point-to-point sends and receives, making it a drop-in replacement for NCCL in environments where GPUs are absent.
The practical usage difference is a single argument:
dist.init_process_group(backend="gloo") # CPU
dist.init_process_group(backend="nccl") # GPU
Everything above the backend is API-compatible.
Comparison: NCCL, MPI, and Gloo
| Property | NCCL | MPI (GPU-aware) | Gloo |
| Primary hardware | GPU (NVLink/IB) | CPU/GPU | CPU (Ethernet) |
| All-reduce algo | Ring + Tree (hybrid) | Ring / Tree | Halving-doubling |
| GPU-native | Yes | Partial | No |
| CPU involvement | Minimal (launch only) | High | High |
| Intra-node BW | 700,GB/s (NVLink4) | 50,GB/s (PCIe) | 10,GB/s |
| Inter-node BW | 200,Gb/s (IB HDR) | 200,Gb/s (IB HDR) | 25,Gb/s |
| RDMA support | GPU-Direct RDMA | Yes (lib-dependent) | No |
| CPU-only mode | No | Yes | Yes |
| PyTorch backend | "nccl" | "mpi" | "gloo" |
| Typical use case | GPU LLM training | HPC workloads | CPU / debugging |
Table tab:distgen:backend-comparison makes the use-case boundaries clear. For LLM and diffusion model training on GPU clusters, NCCL is the unambiguous choice. For HPC simulation workloads where some GPUs and some CPU-only nodes mix in the same job, GPU-aware MPI can span both. For federated learning over wide-area networks, for rapid prototyping, or for environments where CUDA is unavailable, Gloo provides a friction-free fallback.
Connection to Generative AI: Every Gradient Sync Uses These Primitives
It is worth pausing to appreciate the scale at which these primitives operate in modern generative AI.
A GPT-4 scale training run involves an estimated 25,000 A100 GPUs running for months. At each optimizer step (every 1 second of wall time at typical batch sizes), NCCL performs all-reduce over gradients for hundreds of billions of parameters. The communication volume per step exceeds of data across the cluster. Keeping the GPUs busy for more than of wall time requires the pipelining, overlapping, and topology-aware routing that NCCL provides.
A Stable Diffusion 3 training run at scale uses tensor
parallelism (splitting individual attention matrices across GPUs)
in addition to data parallelism, requiring not just all-reduce but
also all-to-all collectives (for rearranging activations between
tensor-parallel and sequence-parallel regions).
ncclAllToAll and ncclAllGather appear in the
inner loop of every forward pass.
A mixture-of-experts (MoE) model introduces a unique
communication pattern: the expert dispatch operation.
Each token is routed to experts, which may reside on different
GPUs.
The tokens must be shipped to the expert GPUs (a sparse all-to-all),
processed, and then the results shipped back.
This is an irregular collective that standard NCCL's
ncclAllToAll can handle when the routing table is known
in advance, but requires custom kernels for truly dynamic routing.
Example: Profiling NCCL All-Reduce on 8 H100 GPUs
Example 5 (Profiling NCCL all-reduce on NVLink).
NVIDIA provides the nccl-tests benchmark suite for
measuring achieved bandwidth and latency.
Below is an edited excerpt of a representative profiling session
on a DGX H100 node (8 GPUs, NVLink4, aggregate
NVLink bandwidth).
# Build and run nccl-tests all-reduce benchmark
$ ./build/all_reduce_perf -b 8 -e 2G -f 2 -g 8
# NCCL version: 2.18.3
# nThread 1 nGpus 8 minBytes 8 maxBytes 2G step factor 2
# Using devices
# Rank 0 Pid 12345 on dgx01 device 0 [0x18] NVIDIA H100 SXM5 80GB
# ... (8 GPUs total)
#
# out-of-place
# size count type redop time algbw busbw
# (B) (us) (GB/s) (GB/s)
8 2 float sum 14.0 0.00 0.00
1024 256 float sum 17.0 0.06 0.11
65536 16384 float sum 22.0 2.98 5.21
1048576 262144 float sum 38.0 27.59 48.28
16777216 4194304 float sum 157.0 106.86 186.99
134217728 33554432 float sum 961.0 139.66 244.40
1073741824 268435456 float sum 7210.0 148.92 260.61
The columns:
algbw: algorithm bandwidth - message size divided by time;
busbw: bus bandwidth - algbw , the effective utilization of each NVLink, comparable to hardware peak.
Key observations:
For 8,B–1,KB (tiny messages), latency dominates: algbw is essentially zero. Here NCCL uses the tree algorithm; latency is 14–22,s.
At 128,MB, busbw reaches , which is of peak NVLink bandwidth. The efficiency gap is explained by the ring overhead on the busbw denominator: the true NVLink utilization is per link.
At 1,GB, busbw reaches , demonstrating near-linear scaling with message size in the bandwidth-bound regime.
In production LLM training, the gradient tensors per layer are typically –, placing them squarely in the bandwidth-efficient regime. The profiling confirms that DDP bucket sizes of are a sensible default: large enough for high bandwidth efficiency ( algbw) but small enough that multiple buckets can pipeline with the backward pass.
The total all-reduce time for a 70B-parameter model () at busbw is approximately per step, dominated by inter-node InfiniBand rather than intra-node NVLink. This is the irreducible communication time that the layer-wise overlap must hide.
Insight.
NCCL doesn't just move data - it hides latency by pipelining and overlapping with compute. The raw bandwidth of NVLink () and InfiniBand () is a ceiling, not a guarantee. NCCL approaches that ceiling for large messages by pipelining the reduce-scatter and all-gather phases, so that all links are simultaneously busy. But the deeper contribution is the architecture of overlap: NCCL runs entirely on the GPU in a dedicated CUDA stream, interleaving communication kernels with compute kernels scheduled by the framework. A well-tuned training loop has the GPU transferring gradients for layer at the same moment it is computing gradients for layer , hiding the communication cost in the shadow of backward pass computation. The result is that the exposed communication latency (the part not overlapped) approaches zero in the large-model regime, and GPU utilization can exceed even across thousands of nodes.
Exercises
Exercise 14.
Manual ring all-reduce in PyTorch.
Using torch.distributed point-to-point operations
(dist.send, dist.recv), implement ring
all-reduce from scratch for processes.
(a) Implement Phase 1 (reduce-scatter): divide each gradient tensor into 4 equal chunks; at each of the steps, send one chunk to the next rank and receive one chunk from the previous rank, accumulating in-place.
(b) Implement Phase 2 (all-gather): send the fully-reduced chunk around the ring, collecting all 4 reduced chunks.
(c) Verify correctness by checking that your result matches
dist.all_reduce(tensor, op=dist.ReduceOp.SUM) on a random
tensor.
(d) Measure the wall-clock time of your implementation versus
dist.all_reduce with the NCCL backend for a -element
float32 tensor.
Explain the performance gap.
Exercise 15.
Ring vs. tree crossover. Using the latency model from Section Tree All-Reduce: Latency-Optimal for Small Messages, derive the crossover message size separating latency-bound (tree-optimal) and bandwidth-bound (ring-optimal) regimes.
(a) For InfiniBand HDR (, ) with , compute in kilobytes.
(b) For NVLink4 intra-node (, per link) with , compute .
(c) Given that a transformer layer's attention projection matrix has parameters (for model dimension ), and that a gradient all-reduce is called once per layer per step, at what model dimension does the intra-node all-reduce transition from latency-bound to bandwidth-bound?
(d) Challenge: NCCL's actual crossover threshold also depends on the number of channels per GPU (typically 2 for H100) and the chunk size used by the ring. How would you modify the crossover formula to incorporate these?
Exercise 16.
DDP bucket tuning. PyTorch DDP's default bucket size is 25,MB. Consider training a 13B-parameter model with 40 transformer layers, where the parameters are uniformly distributed across layers (approximately per layer at float32).
(a) With the default 25,MB bucket size, how many NCCL all-reduce calls are issued per backward pass per layer? What is the total number of all-reduce calls per backward pass across all layers?
(b) Suppose the backward pass computes gradients at a rate of per layer, and the all-reduce for a 25,MB bucket takes . What fraction of communication is hidden by overlap?
(c) If the bucket size is increased to 325,MB (one bucket per layer), how does this change the overlap fraction? Under what conditions is the larger bucket beneficial?
(d) Propose a dynamic bucket-size strategy that adapts to the ratio observed during the first few training steps. What measurement API would you need from the framework?
Communication Hiding - The Art of Multitasking
There is a moment in every distributed training run when a layer's gradients have been computed and are waiting - waiting for the all-reduce to finish, waiting for tensors to travel across InfiniBand or NVLink, waiting for the ring-reduce to complete its circuit. During that wait, the GPUs are idle. Their thousands of CUDA cores sit dark. The power draw does not drop, the memory stays allocated, the clocks keep ticking - but no useful arithmetic is happening.
This is the central inefficiency that communication hiding is designed to eliminate. The idea is disarmingly simple: instead of computing, then communicating, then computing again - overlap the two. Arrange the work so that while the network is busy shuffling gradient bytes between nodes, the GPUs are simultaneously busy computing the next batch of gradients. Neither operation waits for the other. Both proceed in parallel.
In the best case, communication disappears entirely from the critical path. The training throughput is determined purely by compute speed, just as if the distributed cluster were a single monolithic accelerator. That ideal is rarely achieved in practice, but the gap between naive sequential execution and well-engineered overlap can be a factor of two or more in wall-clock time.
This section develops the theory, analogies, and algorithms behind communication hiding, from informal intuition to formal analysis. Application to Generative AI: DDP Backward Pass applies these ideas to the specific architectures of generative model training.
An Everyday Analogy: Laundry and Cooking
Consider a Saturday morning task list: do the laundry and cook lunch. There are two strategies.
The sequential strategy. Put the laundry in the machine. Stand in the kitchen and watch the drum spin for forty-five minutes. When the cycle finishes, move the clothes to the dryer. Then start cooking. Total time: forty-five minutes of washing plus thirty minutes of cooking equals seventy-five minutes.
The overlapping strategy. Put the laundry in the machine. While it is running, cook lunch. When the timer beeps on both, you have clean clothes and a hot meal. Total time: minutes.
You did not reduce the amount of laundry. You did not cook faster. You simply stopped waiting. The washing machine ran, as machines do, without your supervision. You used that unattended time for useful work.
This is, precisely, the logic of communication hiding. The “washing machine” is the network card sending gradient tensors. The “cooking” is the GPU computing gradients for the next layer. Neither process requires the other to be finished before it can proceed. The only constraint is that the network card cannot send gradients it has not yet received from the GPU - just as you cannot hang laundry you have not yet washed.
Remark 6.
The laundry analogy is useful but has a limit: the washing machine and the oven use different resources (electricity circuits, space) and do not compete for the same substrate. In GPU clusters, communication and compute may share PCIe bandwidth, memory controllers, or DMA engines. When they do, the overlap is imperfect and the gains are smaller than the idealised formula suggests. We revisit this in sec:distgen:comhiding:warning.
More Analogies for Intuition
Communication hiding is a form of temporal parallelism: doing two things at the same time by exploiting the fact that they use different resources. Three more everyday examples sharpen the intuition.
Downloading while editing. You need to download a large dataset (3 GB, expected to take 8 minutes) and also review and annotate 200 existing data files. Sequential: 8 minutes of download, then annotation. Overlapping: start the download, annotate files while it proceeds. The annotation takes 6 minutes; the download takes 8. Total: 8 minutes instead of 14.
Waiting for a bus while reading. You must travel to a destination (15-minute bus wait, 20-minute ride) and must also read a 30-page report. Sequential: stand at the bus stop, ride the bus, then read. Overlapping: read while waiting and riding. The travel is on the critical path regardless; the reading fits inside it.
Pipelining in chip design. A CPU pipeline fetches the next instruction while decoding the current one, while executing the one before that. This is the canonical form of communication hiding in computer architecture: latency is hidden behind useful work, not eliminated.
In all cases the key insight is the same: some operations are blocking (they force the caller to wait for a result) while others are non-blocking (the caller can continue working while the operation proceeds in the background). Communication hiding requires rewriting blocking communication as non-blocking, and then filling the gap with useful computation.
Formal Framework
We now formalise the framework. Let a distributed training iteration consist of two phases: a computation phase of duration and a communication phase of duration .
Definition 11.
(Communication Hiding.) A distributed training procedure exhibits communication hiding if the communication phase is scheduled to execute concurrently with a portion of the computation phase, so that communication does not extend the wall-clock iteration time beyond . Formally, let denote the time at which communication begins and the total iteration time. A schedule achieves full hiding if (FULL Hiding) and partial hiding if (Partial Hiding) The sequential baseline corresponds to .
The speedup from hiding is the ratio of sequential to overlapped time:
(Hiding Speedup)
When the speedup approaches 1 (communication was cheap to begin with). When the speedup is 2 - a doubling of throughput from hiding alone. When the speedup again approaches 1 from above: compute finishes quickly but we still wait for the network.
Example 6.
(Hiding Speedup Calculation.) Suppose a training step has and .
Sequential time: .
Fully hidden time: .
Speedup: .
Throughput gain: more training steps per second.
If communication grows (e.g. more GPUs, wider layers) to : sequential time is , hidden time is , speedup is . But compute is no longer on the critical path - the network is.
Key Idea.
Communication hiding does not reduce the amount of data transferred. The same gradient tensors are sent over the same network with the same bandwidth constraints. What hiding changes is the timing: the transfer is scheduled to coincide with useful computation, so its latency does not appear on the critical path. Hiding is a scheduling optimisation, not a compression or communication-reduction technique.
The Pipelining Approach
The most powerful realisation of communication hiding is pipelining: breaking both computation and communication into multiple stages and interleaving them so that stage 's communication overlaps with stage 's computation.
Consider a backward pass over layers. Each layer produces a gradient tensor that must be all-reduced across workers. A naive implementation computes all gradient tensors, then launches a single all-reduce for the entire gradient vector. The all-reduce is and blocks the next iteration.
A pipelined implementation instead launches the all-reduce for layer 's gradient immediately after that layer's backward pass completes, while the backward pass continues to layer .
Let denote the all-reduce time for layer 's gradients and the backward time for layer . Under a layer-wise overlap schedule, the total iteration time is
(Layerwise TIME) where the second term captures the “tail” all-reduce for layer 1 that cannot be hidden behind further backward computation. When , full hiding is achieved and the iteration time equals .
Communication-Hiding Conjugate Gradient
Communication hiding was studied theoretically long before it became a practical concern in deep learning. In the numerical linear algebra community, iterative solvers such as conjugate gradient (CG) contain global dot products - collective operations equivalent to all-reduces - inside their inner loops. These synchronisation points were identified as the dominant bottleneck on massively parallel machines.
Ghysels and Vanroose (2014) introduced the communication-hiding conjugate gradient (CHCG) method, which reorganises the classic CG recurrences to decouple global dot products from the subsequent computation. In standard CG, the sequence of operations per iteration is:
Compute matrix-vector product .
All-reduce to compute .
Update and using .
All-reduce to compute .
Update .
Steps 2 and 4 are blocking global dot products. Between each pair of dot products, the computation is local.
CHCG recognises that the dot products in step 4 of iteration can be pipelined with the matrix-vector product in step 1 of iteration . The reformulated algorithm reads:
Algorithm 2.
Communication-Hiding Conjugate Gradient (CHCG).
- Initialise , ,
- Launch non-blocking all-reduce:
- for
- Compute (overlaps with previous all-reduce)
- Wait for to complete
- Launch non-blocking all-reduce:
- Compute local vector updates (fills overlap gap)
- Wait for ; compute
- Update
- Update
- Launch non-blocking all-reduce:
- Update (overlaps with all-reduce above)
The key step is the non-blocking launch of all-reduce at line 11, which initiates the next iteration's computation while local updates to proceed. On clusters with fast arithmetic and slower interconnects, this reorganisation hides approximately one all-reduce latency per iteration, yielding speedups proportional to the ratio of communication to computation time.
Remark 7.
Reordering global operations in CG does not affect the mathematical result in exact arithmetic. In finite precision, the reordering introduces slightly different rounding error accumulation patterns. Numerical experiments by Ghysels and Vanroose found that the communication-hiding variant converges to the same residual tolerance as standard CG, within typical floating-point variation, for well-conditioned problems. For ill-conditioned systems, preconditioned variants of CHCG are recommended.
Deep Pipelining and Multiple Hidden Rounds
The CHCG approach hides one communication round per iteration. Deeper pipelining, as introduced by Cornelis et al. (2019), extends this to -step methods that pipeline communication rounds simultaneously.
In the -step framework, the algorithm computes Krylov vectors in a single communication-free block: which requires only one set of global communications for all steps instead of one per step. The iteration count is the same; the communication count is divided by .
The hiding efficiency improves with : (Sstep TIME) so the communication overhead per effective iteration shrinks from to . When is large enough that , communication disappears from the critical path.
The price is numerical: the -step Krylov basis can be poorly conditioned for large , and polynomial preconditioning or basis orthogonalisation is required for stability. This is a recurring theme in communication hiding: more aggressive overlap improves efficiency but may require additional care to maintain correctness.
Hiding Global Synchronisation Latency
In distributed deep learning, global synchronisation appears not only as gradient all-reduces but also as:
Barrier synchronisation at the end of each training step to ensure all workers are on the same iteration.
All-gather operations in FSDP, which reassemble sharded weight tensors before the forward pass.
Broadcast of model parameters after initialisation or checkpointing.
Reduce-scatter in ring-all-reduce, which distributes partial gradient sums before the gather phase.
Each of these collective operations can, in principle, be overlapped with local computation. The all-gather in FSDP, for instance, can be issued one layer ahead: while the current layer's forward pass is computing, the next layer's parameters are being gathered. This prefetching approach reduces the stall time for the forward pass, particularly in memory-constrained settings where FSDP shards parameters aggressively.
The Cornelis et al. (2019) framework for hiding global synchronisation latency formalises this for iterative solvers, but the principle transfers directly to deep learning:
Proposition 4.
(Hiding Latency Bound.) Let a distributed training iteration consist of collective operations of latencies and computation blocks of durations . If collective is launched at the start of computation block and the result is consumed at the end of block , then the total iteration time satisfies (Hiding Latency Bound) Full hiding of all collectives is achieved when for all .
Proof.
Collective begins at the start of block . It completes after time. The result is needed after time. If , the result is ready before it is needed and there is no stall. If , the worker must wait for the result. Summing over all collectives yields .
Application to Generative AI: DDP Backward Pass
The most widely used realisation of communication hiding in generative
AI training is the gradient overlap built into PyTorch's
DistributedDataParallel (DDP) module.
During the backward pass of a transformer-based language model or diffusion model, gradients are computed layer by layer from the output back to the input. Each layer produces a gradient tensor; these tensors must be all-reduced across all data-parallel workers before the next optimizer step.
The key observation is that layer 's gradients can be all-reduced while layers are still being differentiated. This is because, in a standard computation graph, the backward pass through layer depends only on the gradient from layer and the layer's own cached activations - not on the gradients of layers
This overlap is implemented in PyTorch DDP through gradient hooks. When a parameter's gradient is computed, a hook fires and immediately enqueues the all-reduce for that parameter's bucket. The backward pass continues through earlier layers while the all-reduce proceeds on the communication thread.
Caution.
Hiding only works when computation and communication can truly run in parallel without competing for the same resource. On systems where the GPU and the network interface card (NIC) share a PCIe bus, gradient tensors must traverse PCIe to reach the NIC. Simultaneously running a heavy backward pass (also generating PCIe traffic for weight reads) can saturate the bus, causing both operations to slow down. In the worst case, “overlapping” two operations on a shared bus can be slower than executing them sequentially, because the contention penalty exceeds the overlap benefit. NVLink-attached GPUs and dedicated GPU-to-NIC interconnects (as in NVIDIA DGX systems with ConnectX-7 NICs) largely eliminate this concern by providing dedicated paths.
Exercises
Exercise 17.
A distributed training step has and on a 16-GPU node.
Compute the speedup from full communication hiding using (Hiding Speedup).
If the cluster is scaled to 64 GPUs and scales as with the number of GPUs (ring all-reduce), compute the new speedup.
At what number of GPUs does the communication first exceed , and what does this imply for the critical path?
Exercise 18.
A transformer with layers performs a pipelined backward pass as described in The Pipelining Approach. Each layer has and (uniform across layers).
Compute using (Layerwise TIME) and show that full hiding is achieved.
Now suppose the model is partitioned into 4 equal buckets (each containing 8 layers' gradients) instead of per-layer all-reduces. Compute (assuming linear scaling with gradient volume) and the new .
Which strategy yields better hiding efficiency? Under what conditions does bucketing become preferable?
Exercise 19.
An iterative solver on a distributed cluster has per step and per global all-reduce.
Using (Sstep TIME), find the minimum value of for which communication is fully hidden behind computation.
If the -step method introduces a penalty to (due to basis orthogonalisation), does the optimal from (a) still achieve full hiding?
Sketch the effective throughput (iterations per second) as a function of for the parameters above.
Communication Hiding in Generative Model Training
The abstract principles of Communication Hiding - The Art of Multitasking acquire concrete form when applied to the training of large generative models. This section examines how communication hiding is implemented in three major contexts: data-parallel training with gradient bucketing, pipeline-parallel training with the 1F1B schedule, and fully-sharded data-parallel (FSDP) training with all-gather prefetch. We also examine diffusion model training, where the denoising structure creates additional opportunities for overlap.
Gradient Bucketing in PyTorch DDP
All-reducing each parameter tensor individually would generate a stream of tiny collectives - one per parameter. Small collectives are latency-bound: the fixed startup cost of launching a collective on the interconnect dominates over the actual data transfer time. For a typical transformer with thousands of individual weight tensors, per-tensor all-reduces would be dominated by launch overhead rather than bandwidth.
Gradient bucketing is the technique of grouping multiple parameter gradients into a single bucket and launching one all-reduce per bucket rather than one per parameter.
Definition 12.
(Gradient Bucketing.) Let be the gradient tensors for the parameters of a model. A gradient bucket partition with and groups parameters into buckets. An all-reduce is launched for bucket as soon as all gradients have been computed in the backward pass. The effective communication granularity is elements per bucket.
In PyTorch DDP, the default bucket size is 25 MB (configurable via
bucket_cap_mb).
Parameters are assigned to buckets in reverse order of their
registration (which follows layer order in typical models), so
buckets correspond approximately to contiguous segments of the
backward pass.
When the last parameter in a bucket is ready, DDP fires an
all-reduce for that bucket and continues the backward pass.
The following Python pseudocode illustrates the mechanism:
[caption={PyTorch DDP gradient bucketing (conceptual).},
label={lst:distgen:ddp-bucketing}]
# DDP registers gradient hooks on each parameter at init
for param in model.parameters():
param.register_hook(
lambda grad, param=param: ddp.gradient_ready(param, grad)
)
def gradient_ready(self, param, grad):
"""Called when param.grad is computed during backward."""
bucket = self.param_to_bucket[param]
bucket.mark_ready(param)
if bucket.all_ready():
# All gradients in this bucket are computed -
# launch non-blocking all-reduce immediately
bucket.allreduce_future = dist.all_reduce(
bucket.flat_tensor,
op=dist.ReduceOp.AVG,
async_op=True # non-blocking!
)
# Backward pass continues for earlier layers
# while the all-reduce runs on the comm thread
def synchronize(self):
"""Called after backward() completes."""
for bucket in self.buckets:
bucket.allreduce_future.wait() # wait for any tail comms
bucket.copy_gradients_back()
The non-blocking async_op=True flag is the critical
element: it launches the all-reduce on a background communication
stream without blocking the backward-pass computation stream.
Optimal Bucket Size
Choosing the right bucket size (in bytes) involves a trade-off.
Too small: Buckets fire frequently, generating many small all-reduces. Each all-reduce has a fixed latency overhead (typically – depending on the switch fabric). Total communication overhead grows with the number of buckets .
Too large: Few all-reduces are launched, reducing startup overhead, but each bucket covers many layers. The overlap window between the bucket's first layer completing and the bucket's last layer completing shrinks proportionally. A very large bucket means the all-reduce is not launched until many layers have already finished, wasting the potential overlap window.
Proposition 5.
(Optimal Bucket Size for Communication Hiding.) Consider a model with parameters distributed across equal buckets of size elements. Let:
- fixed startup latency of each all-reduce (seconds),
- available all-reduce bandwidth per element (elements/second),
- compute time per element of backward pass (seconds/element),
- bucket size in elements.
The all-reduce time for one bucket is . The compute time over one bucket's span of the backward pass is . Full hiding requires , i.e. (Hiding Condition) The minimum bucket size achieving full hiding is therefore (Optimal Bucket) provided (compute is slower than communication bandwidth, so there exists a bucket large enough).
Proof.
From , solving for : The minimum value is the smallest bucket for which the compute time during that bucket's processing is at least as large as the all-reduce time, ensuring no communication stall.
Example 7.
(Hiding Efficiency for a 13B LLM on 64 GPUs.)
Consider a 13B-parameter language model trained with data parallelism on 64 NVIDIA H100 GPUs connected by a 400 Gb/s InfiniBand HDR fabric.
Model parameters:
Total parameters: (FP16 )
Batch size per GPU: 2 sequences of 2048 tokens
Backward pass time: (measured)
Communication parameters:
Ring all-reduce bandwidth efficiency: of peak InfiniBand ( effective)
All-reduce data volume: bytes (ring-reduce formula; for large , in FP16)
All-reduce time (no overlap):
Sequential time: .
With gradient bucketing (25 MB buckets): buckets. Each bucket's all-reduce time . Each bucket's compute time . Since , the compute does not fully hide the per-bucket all-reduce.
Effective compute available for hiding . Communication hidden . Remaining communication tail . Effective iteration time: .
Hiding efficiency: Approximately 49% of the all-reduce time is hidden. The remainder (51%) cannot be hidden because communication is slower than compute. To achieve full hiding, one could use gradient compression (FP8), increase the global batch size (more compute per step), or use faster interconnects (e.g. NVLink fabric switch for a single node scale-up).
Pipeline Parallelism as Communication Hiding
Pipeline parallelism (PP) partitions the model's layers across multiple devices, with each device holding a contiguous stage. Data flows forward through stages (forward pass) and backward through stages (backward pass). The inter-stage communication is the activation tensors passed between adjacent devices.
In a naive pipeline, a bubble forms at the beginning (when earlier stages are computing but later stages have nothing to do) and at the end (when later stages are computing the backward pass but earlier stages are idle).
The one-forward-one-backward (1F1B) schedule, introduced independently in Megatron-LM and PipeDream, dramatically reduces this bubble by interleaving forward and backward micro-batches:
Definition 13.
(One-Forward-One-Backward (1F1B) Schedule.) Let pipeline stages and micro-batches constitute one training step. The 1F1B schedule assigns each stage the following sequence:
Warm-up phase: Stage performs forward passes (filling the pipeline).
Steady state: For each micro-batch, stage alternates: one forward pass (on the current micro-batch) followed immediately by one backward pass (on the oldest outstanding micro-batch).
Drain phase: Stage processes the remaining backward passes.
The inter-stage communication (activation/gradient transfer) for micro-batch overlaps with the computation for micro-batch on the adjacent stage, constituting an implicit communication-hiding schedule.
The bubble fraction (idle time as a fraction of total time) for the 1F1B schedule is: (Bubble Fraction) where is the number of pipeline stages and is the number of micro-batches per batch. As , : the bubble becomes negligible, and the schedule achieves near-perfect compute utilisation with communication (activation transfer between stages) almost entirely hidden behind computation.
Diffusion Model Training and Denoising Step Overlap
Diffusion models present a distinctive structure for communication hiding. A forward process (not to be confused with the neural network forward pass) adds noise over steps; the network learns to reverse this. During training, the model predicts the noise added at a randomly sampled timestep : The UNet or DiT backbone processes a single noisy image or video frame at timestep ; the communication pattern is identical to standard data-parallel training. However, diffusion models have two specific features that create additional hiding opportunities.
Frozen encoders. Many diffusion architectures use a pre-trained text encoder (e.g. CLIP or T5) that is frozen during training. The encoder's forward pass produces conditioning embeddings that are passed to the denoising network but do not generate gradients. The DiffusionPipe framework exploits this: the encoder forward pass on micro-batch is scheduled to fill the pipeline bubble that occurs during the backward pass of the denoising network for micro-batch . Since the encoder is frozen, its computation produces no gradients and no all-reduce is required. This is a particularly clean example of communication hiding because the “filler” computation (encoder forward) is guaranteed to be communication-free.
Independent timestep sampling. Within a mini-batch, each sample is independently assigned a timestep . Samples at different timesteps have different arithmetic intensities (early timesteps are high-noise and computationally intensive; late timesteps are near-clean and cheaper). A well-tuned pipeline can exploit this heterogeneity by assigning computationally heavy samples to stages with smaller communication requirements, balancing the compute-communication ratio across stages.
FSDP Parameter Prefetching
Fully Sharded Data Parallel (FSDP) shards model parameters, gradients, and optimizer states across all data-parallel workers. Before each forward or backward pass through a layer, FSDP must all-gather the layer's full parameter tensor from all workers. After the backward pass, it immediately shards the parameters again to free memory.
In the naive implementation, the forward pass through layer is blocked until the all-gather for layer 's parameters completes. This creates a communication stall at the start of every layer.
Prefetching eliminates this stall: while layer is executing (forward or backward), FSDP issues the all-gather for layer 's parameters in the background. By the time layer is needed, its parameters are already available.
In PyTorch FSDP, this is controlled by the
forward_prefetch flag:
[caption={FSDP prefetch configuration.},
label={lst:distgen:fsdp-prefetch}]
from torch.distributed.fsdp import (
FullyShardedDataParallel as FSDP,
ShardingStrategy,
)
model = FSDP(
model,
sharding_strategy=ShardingStrategy.FULL_SHARD,
forward_prefetch=True, # prefetch next layer's all-gather
backward_prefetch="BACKWARD_PRE", # prefetch during bwd
limit_all_gathers=True, # avoid OOM from too many in-flight
)
The backward_prefetch="BACKWARD_PRE" setting means that
during the backward pass through layer , FSDP issues the
all-gather for layer (the next layer in the backward
order) before layer 's backward pass starts.
This is analogous to the DDP bucketing scheme but applied to
parameter gathering rather than gradient synchronisation.
The limit_all_gathers=True flag prevents FSDP from
prefetching too many layers simultaneously, which would defeat the
purpose of sharding by bringing too many parameter tensors into
GPU memory at once.
Comparison of Communication Hiding Techniques
tab:distgen:hiding-comparison summarises the principal communication hiding techniques discussed in this chapter, their applicable training paradigm, the operation hidden, and the practical limitations.
| p3.0cmp2.0cmp2.2cmp2.0cmp3.5cm@ Technique | Paradigm | Hidden Op. | Framework | Limitation |
| Gradient bucketing | Data parallel | All-reduce | PyTorch DDP | Compute comm. tail exposed |
| FSDP all-gather prefetch | Data parallel (sharded) | All-gather | PyTorch FSDP | Memory limit on simultaneous gathers |
| 1F1B pipeline schedule | Pipeline parallel | Activation send/recv | Megatron-LM, PipeDream | Bubble fraction |
| DiffusionPipe frozen encoder | Pipeline parallel | Encoder fwd (no grad) | Custom | Applicable only to frozen-encoder architectures |
| CHCG / -step | Solver-based | Global dot product | Numerical solvers | Numerical instability for large |
| Tensor parallel overlap | Tensor parallel | All-reduce (row/col) | Megatron-LM | Requires column/row-parallel linear layers |
Exercises
Exercise 20.
A 7B-parameter language model (FP16; parameters) is trained with DDP on 32 A100 GPUs with 100 Gb/s InfiniBand.
Using Proposition 5, compute assuming a per-all-reduce startup latency of , effective ring-bandwidth , and backward-pass compute of per element (FP16 gradient).
If the actual DDP default bucket size is 25 MB, is this above or below ? What are the consequences of each direction?
An engineer proposes reducing the bucket size to 5 MB to increase overlap granularity. Using the formula for total startup overhead ( where ), quantify the additional overhead introduced.
Exercise 21.
A transformer model is trained with 8-stage pipeline parallelism using the 1F1B schedule.
Using (Bubble Fraction), compute the bubble fraction for micro-batches.
Plot (or tabulate) the effective GPU utilisation for these values of .
If each micro-batch uses a batch size of 1 sequence (to minimise memory), what is the minimum global batch size required to achieve a bubble fraction below ?
The interleaved 1F1B schedule (Narayanan et al., 2021) reduces the bubble fraction to where is the number of virtual stages per device. For , , what value of achieves ?
Exercise 22.
A DiT-XL model with 48 transformer blocks is trained with FSDP on 8 GPUs. Each block's parameter tensor is (FP32). The all-gather for one block completes in . The forward pass through one block takes .
Without prefetching, compute the total time spent waiting for all-gathers during the forward pass of one training step.
With
forward_prefetch=True(one layer ahead), compute the residual all-gather stall time. Assume block 's all-gather is launched when block 's forward pass starts.With
limit_all_gathers=False(unlimited prefetching), how many blocks' parameters are simultaneously in GPU memory at peak? Given 80 GB GPU memory and 250 MB per block, is this feasible?Propose a two-ahead prefetch policy and compute its stall time. Compare the memory cost against the stall reduction.
Communication Avoiding: Reorganizing the Algorithm
Every training run on a distributed cluster involves two fundamentally different activities: compute and communicate. The previous sections addressed how to hide the latency of communication by overlapping it with computation. That strategy leaves the total volume of communication unchanged: the same bytes still cross the interconnect, merely at a more convenient moment. Communication avoiding takes a more radical stance. Rather than scheduling existing communication more cleverly, it asks a deeper question: does the algorithm need to communicate this much in the first place?
The answer, in many practically important cases, is no. By redesigning the algorithm itself, we can often reduce the number of synchronization rounds, the number of bytes exchanged, or both, without sacrificing convergence or numerical correctness. The result is a category of techniques that attack the root cause of the communication bottleneck rather than its symptoms.
Key Idea.
Communication hiding attacks the time to move data by overlapping it with useful work. Communication avoiding attacks the amount of data that must be moved by redesigning the algorithm. The two strategies are complementary: combining them yields the greatest speedups.
A Motivating Analogy: The Grocery Store
Imagine you need ten items from the grocery store. One strategy is to make ten separate trips: leave the house, walk to the store, buy one item, return home, repeat. Each trip involves the full overhead of travel-putting on shoes, commuting, parking, queuing. A smarter strategy is to sit down, write a complete shopping list, and then make a single trip to collect all ten items at once.
The ten-trip strategy is analogous to communication hiding: you have the same ten trips, but perhaps you listen to a podcast during the commute to hide the latency. The single-trip strategy is analogous to communication avoiding: you redesign the task so that only one trip is needed, eliminating nine round-trips entirely.
A second analogy reinforces the same intuition. Suppose you have twenty emails to send. One approach is to compose each email and immediately hit Send, repeating twenty times. A more efficient approach is to compose all twenty drafts first, then click Send All once. The total content transmitted is identical, but the number of distinct send operations, and hence the number of times you context-switch to wait for a delivery confirmation, drops from twenty to one. In a distributed system, each “send” carries latency overhead; batching communication rounds collapses that overhead dramatically.
Communication Hiding Versus Avoiding: A Precise Comparison
It is worth making the distinction between hiding and avoiding precise before proceeding, since the two strategies are often conflated.
Definition 14 (Communication Hiding).
A distributed algorithm hides communication if it overlaps the transmission of a message with independent computation, so that the effective communication time visible on the critical path is reduced, while the total bytes transmitted are unchanged.
Definition 15 (Communication Avoiding).
A distributed algorithm avoids communication if, relative to a baseline algorithm that computes the same result, it reduces the total number of synchronization rounds , the total bytes transmitted , or both, by algebraic or algorithmic restructuring.
The practical implication is important. Communication hiding gives diminishing returns when the compute-to-communication ratio approaches one: you cannot hide a communication that takes longer than the computation it is supposed to overlap with. Communication avoiding, by contrast, reduces the irreducible minimum of communication, so it remains effective even on slow interconnects or in regimes where the model is small relative to the network overhead.
Communication-Avoiding Linear Algebra
The theoretical foundations of communication avoiding lie in numerical linear algebra, where the problem was first studied rigorously. We review the key results because they provide both a lower bound that serves as a target and a constructive method that generalises to machine learning.
The Demmel Lower Bound
Consider the problem of multiplying two matrices and to produce on a distributed system with processors, each with local memory of size words. The classical result, due to Hong and Kung (1981) and later generalised by Demmel, Dumitriu, Holtz, and Kleinberg (2012), establishes an information-theoretic lower bound on how many words any correct algorithm must transmit.
Theorem 1 (Demmel Communication Lower Bound).
Any algorithm that computes the product of two matrices using floating-point operations on processors, each with local memory of size words, must move at least (Demmel Bound) words between processors (summed over all processors), when (the memory-optimal regime).
Proof sketch.
The argument is a counting argument based on the 3D geometry of matrix multiplication. The multiplications required by form a combinatorial cube , where entry corresponds to the multiply-add .
A processor with memory can hold at most values of , , and simultaneously. By a geometric result (the Loomis-Whitney inequality), the number of triples computable using only those values is at most . Hence, to compute all triples, the processor must load new data at least times. Distributing triples across processors, each processor handles triples, requiring at least loads. In the memory-optimal regime , this evaluates to words per processor.
The classical parallel matrix multiply algorithms (ScaLAPACK, SUMMA) communicate words, which exceeds the lower bound by a factor of . Communication-avoiding algorithms (Cannon's algorithm, 2.5D algorithms) achieve the lower bound , matching it up to constant factors.
Remark 8.
The bound in Theorem 1 applies to any algorithm with the same arithmetic complexity, not just matrix multiply. For a transformer layer performing matrix multiplications of size , the same lower bound governs the minimum communication. This means there is a hard floor on how much synchronisation is required, and no implementation trick can circumvent it-only algorithmic restructuring that changes the arithmetic structure can help.
Communication-Avoiding Matrix Multiply
The key insight enabling communication-avoiding matrix multiply is to redistribute computation so that each processor can compute a three-dimensional block of the output without ever receiving data that another processor already holds. The 2.5D algorithm (Solomonik and Demmel, 2011) illustrates the idea.
Arrange the processors in a three-dimensional grid, where is a replication factor trading extra memory for reduced communication. Each processor holds a block of , , and of size . The algorithm proceeds in two phases:
Broadcast phase. Replicate and along the third dimension of the grid using broadcasts. Each broadcast moves words.
Compute phase. Each of the processor slabs independently performs a parallel matrix multiply over its local data, communicating only words.
Reduce phase. Sum the partial products along the third dimension to produce the final .
The total communication is , which matches the lower bound when and approaches it for larger at the cost of increased memory.
Communication-Avoiding Conjugate Gradient
The conjugate gradient (CG) method for solving illustrates
how communication avoidance extends beyond matrix multiply to iterative
algorithms. Classical CG requires one all-reduce per
iteration to compute the inner products and
the step sizes. With iterations, this means synchronisation
rounds.
The communication-avoiding conjugate gradient (CA-CG) algorithm (Carson and Demmel, 2015) collapses iterations into a single communication round.
Algorithm 3 (Communication-Avoiding Conjugate Gradient).
- Input: Matrix , vector , initial guess , block size
- ,
- for
- [Local] Compute the Krylov block: using repeated local matrix-vector products
- [One
all-reduce] Compute all inner products among the Krylov vectors simultaneously via a single reduction of the Gram matrix - [Local] Compute the next CG iterates from the Gram matrix using the classical three-term recurrence
The savings are dramatic: classical CG steps require all-reduce calls; CA-CG requires only call per steps, reducing synchronisation rounds by a factor of .
Proposition 6 (CA-CG Communication Savings).
Classical CG performing iterations requires synchronisation rounds. CA-CG with block size requires rounds, a reduction by factor . The total bytes exchanged decreases from to , which is lower when .
Proof sketch.
Each classical CG iteration broadcasts two scalar inner products, so iterations communicate scalars, each requiring operations in an all-reduce tree, but words of local data. CA-CG broadcasts the Gram matrix once per block, requiring scalars per block and blocks. The break-even point satisfies , i.e., , which is satisfied for any practical block size when is large.
Remark 9.
A practical concern is that computing powers naively leads to rapid loss of orthogonality in the Krylov basis. Carson and Demmel (2015) address this by using a numerically stable basis (the Newton or Chebyshev basis) rather than the monomial basis . The block size is typically chosen between 4 and 16 in practice, balancing communication savings against numerical stability.
The General Principle: Minimising Communication
The work of Ballard, Demmel, Holtz, and Schwartz (2011) on “Minimizing Communication in Numerical Linear Algebra” establishes a unifying framework. The core principle is:
Derive a communication lower bound for the problem by counting the number of distinct data items that must flow between processors to produce the answer. This is typically done via a combinatorial argument (Loomis-Whitney, pebbling arguments, or information-theoretic bounds).
Design an algorithm that matches the bound. This often requires rethinking the order of operations so that a processor computes a larger chunk of the output before needing external data, rather than ping-ponging back and forth for each output entry.
Verify that the numerical properties are preserved. Avoiding communication can change the order of floating-point operations, which may alter rounding behaviour. For machine learning, which is robust to moderate numerical noise, this is rarely a concern; for scientific computing it requires care.
Historical Note.
Origins of communication-avoiding algorithms. The theoretical lower bound on communication for matrix algorithms was first established by Hong and Kung in 1981 in the sequential (single-processor) setting, showing that any algorithm using fast memory and unlimited slow memory must perform slow-memory references. The parallel extension, showing that processors collectively must transmit words, was established by Irony, Toledo, and Tiskin (2004). The “2.5D algorithm” matching this bound was given by Solomonik and Demmel (2011), and the framework was systematised in the landmark survey by Ballard, Demmel, Holtz, and Schwartz (2011). The CA-CG algorithm was analysed rigorously by Carson and Demmel (2015). This body of work represents the most complete theory of communication complexity in numerical computing.
Applying Communication Avoidance to Machine Learning
The machine learning gradient computation has the same algebraic structure as the numerical linear algebra problems above. For a transformer layer with weight matrix , hidden state , and output , the forward pass is a matrix multiply and the backward pass computes the gradient , also a matrix multiply.
If these matrix multiplications are distributed across processors, the Demmel lower bound applies directly. A communication-avoiding implementation of the transformer forward/backward pass can therefore reduce the synchronisation cost from words (classical data-parallel distribution) to words, a saving of .
More broadly, any gradient-based training algorithm that performs iterative updates of the form has the option of batching multiple gradient steps before synchronising, computing local approximations to the gradient using only local data, and exchanging information less frequently. This is the insight that drives local SGD, discussed in the next section.
Insight.
The question “can we compute more before synchronising?” is the machine learning analogue of the numerical linear algebra question “can we compute more before loading new data?” Both are answered by the same principle: reorganise the computation so that locally available data is used to its fullest extent before a communication event is triggered.
Exercises
Exercise 23 (Shopping list bound).
Suppose you need items from a store, and each round trip to the store takes fixed overhead plus per item carried. You can carry at most items per trip.
Show that the optimal number of trips is .
Compute the total time as a function of , , , and , and find the value of that minimises total time when .
Map each quantity in your formula to its distributed-training analogue: what are , , , and in the context of gradient synchronisation?
Exercise 24 (Demmel bound for rectangular matrices).
The Demmel lower bound in Theorem 1 was stated for square matrices.
Generalise the bound to rectangular matrices and . Express the lower bound in terms of , , , and .
In a transformer with hidden dimension and sequence length , the attention weight matrix has size and the value projection has size . Apply your generalised bound to determine the minimum communication required for the attention computation on GPUs.
When is the classical all-reduce approach (which exchanges words) already optimal, and when can communication avoiding reduce it further?
Exercise 25 (CA-CG block size selection).
Consider using CA-CG with block size to train a linear model by minimising the squared loss , which leads to the normal equations .
Express the communication savings of CA-CG over classical CG as a function of , (dimension of ), and .
Show that the Krylov block where can be computed using matrix-vector products with and (not with directly), reducing the per-step compute cost.
Derive the optimal that minimises total training time (communication + compute) as a function of , , and the ratio of latency to bandwidth.
Communication Avoiding in Generative Model Training
We now turn from the general theory to specific techniques that apply communication avoidance to the training of large generative models: diffusion models, transformers, and auto-regressive language models. Each technique reduces communication by reorganising the algorithm, not merely by rescheduling it.
Local SGD: Train Locally, Synchronise Rarely
The most direct application of communication avoidance to gradient-based training is local SGD: each device runs steps of stochastic gradient descent using only its own local data, then the devices synchronise by averaging their model parameters. This reduces the number of all-reduce calls from (one per step) to (one per steps), a factor-of- reduction in synchronisation rounds.
Definition 16 (Local SGD).
Let there be workers, each holding a data shard. Let denote the parameters on worker at step , and let be the synchronisation period. Local SGD proceeds as follows:
Local update. For , each worker independently updates: (Local SGD Update) where is a mini-batch sampled from the local shard of worker .
Synchronisation. After every steps: (Local SGD SYNC) The averaged parameters are broadcast to all workers.
When , local SGD reduces to standard data-parallel SGD with all-reduce after every step.
The key concern with local SGD is gradient drift: because each worker takes independent steps using its own local data, the workers' parameters diverge from one another. After synchronisation, the averaged model may not be at a location that any individual worker would have reached, and convergence may be affected.
Proposition 7 (Local SGD Convergence with Drift Bound).
Let be -smooth () and let the stochastic gradients satisfy and (bounded variance). Denote the gradient dissimilarity across workers by . Local SGD with learning rate , synchronisation period , total steps, and workers satisfies: (Local SGD Bound) where is the mean parameter at step .
Proof sketch.
The bound is derived by expanding around using smoothness, then bounding the drift term , where denotes the parameters that vanilla SGD would have reached after steps.
The drift term accumulates over local steps: after steps, worker 's parameters satisfy Squaring and summing over , the cross-worker variance satisfies This term, multiplied by (the smoothness constant), yields the drift contribution in (Local SGD Bound). Setting balances noise and drift terms, recovering the convergence rate of standard SGD, with the drift adding only a lower-order term when .
Remark 10.
In practice, local SGD with achieves comparable final accuracy to synchronous SGD while reducing communication rounds by the same factor. The optimal depends on the data heterogeneity : with IID data across workers (homogeneous shards), can be large without quality loss; with highly heterogeneous data, smaller is preferred. For large generative models trained on curated datasets (which tend to be relatively homogeneous), or even is commonly effective.
Gradient Compression: Sparsification and Quantization
A complementary approach reduces the volume of data exchanged per synchronisation round, rather than the number of rounds. Gradient compression achieves this by transmitting only an approximation of the true gradient, using either sparsification (sending only the most important components) or quantization (reducing the precision of each component).
Top- Sparsification
In Top- sparsification, each worker computes its local gradient and transmits only the coordinates with the largest absolute values.
Definition 17 (Top- Sparsification).
Let be a gradient vector and . The Top- sparsification operator is (TOPK) The sparsified gradient is encoded as a sparse vector with nonzeros, requiring bits to transmit (indices plus values) versus bits for the dense gradient, a compression ratio of .
A critical detail is error feedback (also called error correction or memory): the components that were not transmitted are accumulated in a local buffer and added to the next gradient before sparsification.
Algorithm 4 (Top- SGD with Error Feedback).
- Input: Learning rate , compression ratio , initial parameters , initial error buffer
- for
- Compute local stochastic gradient
- Add accumulated error
- Sparsify: keep top- components
- Store residual for next step
- Transmit to all workers, receive their
Error feedback is essential for convergence: without it, the bias introduced by dropping small gradient components accumulates and the algorithm may diverge. With error feedback, Top- SGD converges at the same asymptotic rate as full SGD for smooth non-convex objectives.
1-Bit and Ternary Quantization
Quantization reduces communication by encoding each gradient coordinate with fewer bits. 1-bit SGD (Seide et al., 2014) encodes each coordinate as a single sign bit: The scale of the gradient is communicated separately (a single scalar per layer), giving a compression ratio of for 32-bit floats. Ternary quantization (Wen et al., 2017) represents each coordinate as , with a threshold below which coordinates are zeroed: Ternary encoding combined with error feedback achieves compression ratios of to with minimal accuracy degradation for large models where the gradient is approximately low-rank.
Ring Attention: Avoiding the Full KV Gather
For transformers processing very long sequences, the attention computation is a major communication bottleneck. Standard tensor parallelism gathers the full key-value (KV) cache from all devices before computing attention. For a sequence of length with - dimensional embeddings distributed across devices, this requires transmitting words per attention layer, dominating the training communication budget.
Ring Attention (Liu et al., 2023) eliminates this gather by processing attention in a ring topology: each device holds a block of queries and a block of KV pairs, and the KV blocks rotate around the ring while each device accumulates its partial attention output.
Definition 18 (Ring Attention).
Let devices be arranged in a ring . Device holds query block and initially holds KV block . Ring Attention proceeds for rounds:
Local attention. Device computes partial attention scores and weighted values using its current KV block: (with appropriate log-sum-exp accumulation for numerical stability).
KV rotation. Device sends its current KV block to device and receives a KV block from device .
Repeat for rounds, after which each device has attended to every KV block.
The final output on device is the correctly normalised attention over the full sequence, computed without any device ever holding the full KV cache.
Ring Attention has an important property: the blocks never move. Each GPU accumulates its own output in place. The KV blocks rotate, but the communication is point-to-point between neighbouring ring members, not an all-reduce. This means:
No synchronisation barrier is required between rounds (pipeline parallelism applies naturally).
Memory usage is per GPU instead of .
Computation and communication can be overlapped (ring attention is also communication-hiding).
Sequence Parallelism
Sequence parallelism splits the sequence dimension across devices, so that each device processes only a contiguous chunk of tokens. The attention mask becomes local for tokens within the same chunk, and only boundary information (key-value pairs from the first and last few tokens of each chunk) must be exchanged with neighbouring devices.
For a sequence of length split across devices, each device holds tokens. For a window attention with window size , the attention is fully local; only causal or cross-chunk dependencies require inter-device communication of words per layer. This reduces communication from (full sequence all-reduce) to (boundary exchange), a factor-of- reduction.
Remark 11.
For auto-regressive language models with causal attention, sequence parallelism is particularly effective: token only attends to tokens , so device (holding tokens ) only needs KV pairs from devices , not from device . This triangular communication pattern halves the expected inter-device traffic compared to bidirectional attention.
Communication-Avoiding Matrix Multiply for Transformer Layers
The weight matrices of a transformer ( and the feedforward matrices ) participate in large matrix multiplications at every layer. Applying the 2.5D communication-avoiding matrix multiply algorithm of Section Communication-Avoiding Matrix Multiply to these multiplications reduces the per-layer communication from to words.
In practice, the saving is most significant at large model widths and large . For a transformer with and GPUs, the classical 2D distribution communicates words per layer, while the 2.5D approach communicates words per layer, a reduction per layer.
Example 8 (CA matrix multiply for GPT-scale models).
Consider a GPT-style transformer with layers, hidden dimension , and GPUs. Each layer performs approximately 8 matrix multiplications (4 attention projections 2 feedforward, each with a forward and backward pass matrix multiply).
Classical (2D) distribution:
Communication-avoiding (2.5D) distribution:
The 2.5D approach reduces per-step communication by a factor of . At 400 Gbps interconnect bandwidth, this saves approximately ms per step, amounting to roughly 15-20% of total training time.
Communication Avoiding for Diffusion Model Training
Diffusion models present a particular opportunity for communication avoidance because their denoising process is inherently sequential: step depends on the output of step . In standard distributed training, this dependency requires synchronising parameters after every denoising step update.
Multi-step batching for diffusion training is the analogue of local SGD: instead of synchronising after every denoising step update, devices accumulate gradients over consecutive denoising steps before performing an all-reduce.
Algorithm 5 (Multi-Step Batching for Diffusion Training).
- Input: Noise schedule , batch size , synchronisation period
- for each global training step
- for to local denoising steps
- Sample
- Accumulate:
- All-reduce accumulated gradient across workers
The communication saving is exactly in synchronisation rounds. Since diffusion model training typically uses without notable degradation (the denoising objective is smooth and the mini-batch gradient is a good proxy for the full gradient), this yields significant wall-time improvements on interconnect-limited clusters.
Decentralised Training and Gossip Protocols
The communication-avoiding strategies discussed so far still rely on a periodic global synchronisation (all-reduce). The most radical form of communication avoidance is to eliminate global synchronisation entirely, replacing it with decentralised training via gossip protocols.
In a gossip protocol, at each step, each worker exchanges parameters (or gradients) with a randomly or deterministically chosen subset of its neighbours, without any global coordinator. Over time, information propagates through the network, and parameters eventually converge.
Definition 19 (Gossip-Based Decentralised SGD).
Let be a mixing graph where is the set of workers, is the set of communication links, and is a doubly stochastic mixing matrix (, , , if ). Gossip SGD at step : (Gossip) Each step, worker mixes with its neighbours (the non-zero entries of row in ) and then takes a local gradient step. No global all-reduce is required.
The convergence rate of gossip SGD depends on the spectral gap of the mixing matrix . Let be the second-largest eigenvalue of (the first is 1). A larger spectral gap leads to faster consensus and better convergence.
Remark 12.
Common mixing graph topologies and their spectral gaps:
Complete graph (): spectral gap , but edges (all-reduce equivalent).
Ring (, ): spectral gap , only edges.
Torus (2D grid): spectral gap , edges.
Exponential graph (each node connects to others): spectral gap , edges.
The exponential graph provides the best balance of convergence speed and communication overhead for decentralised training.
Gossip-based training is particularly well-suited to federated learning scenarios (discussed elsewhere in this book) where a central server is unavailable or undesirable. For datacenter training, the gossip approach sacrifices some convergence speed but gains robustness to slow or failed workers.
Taxonomy and Comparison of Communication Optimisation Techniques
We now consolidate the techniques from this section and the previous section into a unified taxonomy.
| p3.0cmp2.0cmp2.2cmp2.0cmp3.2cm@ Technique | Category | Rounds saved | Bytes saved | Main trade-off |
| Gradient overlap | Hiding | Must overlap compute comm | ||
| [3pt] Pipeline bubbles | Hiding | Bubble fraction | ||
| [3pt] Async SGD | Hiding | Staleness introduces noise | ||
| [6pt] Local SGD | Avoiding | Gradient drift | ||
| [3pt] Top- sparsify | Avoiding | Error feedback needed | ||
| [3pt] 1-bit quantization | Avoiding | Quantization noise | ||
| [3pt] Ring Attention | Avoiding | barrier free | peak | Requires ring topology |
| [3pt] CA matrix multiply | Avoiding | Extra memory for | ||
| [3pt] Gossip / decentralised | Avoiding | all-reduce free | topology-dep. | Slower consensus |
| [3pt] Local SGD Top- | Both | Both drift and bias | ||
| [3pt] |
Worked Example: Local SGD Savings for Diffusion Training
We compute the communication savings from local SGD with for a realistic diffusion model training run.
Example 9 (Local SGD with for diffusion training).
Setup. Consider training a diffusion model with , parameters, using A100 GPUs connected via NVLink ( GB/s all-reduce bandwidth). Standard data-parallel SGD performs one all-reduce per step; local SGD with performs one all-reduce every 8 steps.
Communication per all-reduce. A standard ring all-reduce for float32 parameters transmits values GB per call.
Time per all-reduce. At 600 GB/s bandwidth: ms.
Compute per step. A diffusion model forward-backward pass with batch size 8 per GPU takes approximately 120 ms on an A100 (dominated by attention and convolution).
Standard SGD communication overhead:
Local SGD with communication overhead: Only as many all-reduces, so:
Effective speedup. Local SGD reduces the communication overhead from 10% to 1.4%, recovering approximately 8.6% of training time. For a training run of 1000 A100-hours, this saves approximately 86 GPU-hours, or roughly $860 at typical cloud pricing.
Model quality. With IID data sharding and , the drift term in (Local SGD Bound) adds a small bias proportional to . Empirically, for diffusion models trained on curated image datasets, produces FID scores within 0.5 points of standard SGD, well within the noise of the evaluation.
Insight.
The best communication is the one that never happens. Local SGD, Top- sparsification, ring attention, and communication-avoiding matrix multiply all embody this principle: by reorganising computation to use locally available data more fully, they eliminate entire classes of inter-device data movement. The total computational work is essentially unchanged; only the fraction of that work that crosses device boundaries is reduced.
Combining Hiding and Avoiding
In practice, the most effective distributed training systems combine both hiding and avoiding. The two approaches are complementary: avoiding sets the floor (the minimum communication that must happen), and hiding ensures that even the remaining communication is as invisible as possible.
A prototypical combined strategy for transformer training:
Reduce rounds via local SGD (avoiding): synchronise every steps instead of every step.
Compress the remaining syncs via Top- (avoiding): send only the top 10% of gradient coordinates, using error feedback to preserve convergence.
Overlap the remaining communication with compute (hiding): use gradient checkpointing and backward-pass streaming to overlap the all-reduce of earlier layers with the backward pass of later layers.
Use ring attention for long sequences (avoiding): eliminate the KV gather, replacing it with a ring rotation that requires no all-reduce barrier.
Apply CA matrix multiply for weight updates (avoiding): use the 2.5D distribution to reduce per-layer weight gradient communication by .
Combining all five strategies on a 1024-GPU cluster training a GPT-4 scale model (, layers) can reduce total communication from approximately 4 TB/step (naive) to approximately 0.15 TB/step (combined), a reduction. With 400 Gbps interconnect, this translates from ms of communication overhead per step to ms, bringing the compute-to-communicate ratio from 2:1 to 50:1.
Exercises
Exercise 26 (Local SGD with heterogeneous data).
Suppose workers each hold a non-IID shard of a dataset, with gradient dissimilarity (in squared gradient norm units). The model has M parameters and the loss function is -smooth with .
Using the bound in Proposition 7, compute the maximum synchronisation period such that the drift term does not exceed 10% of the noise term , assuming and .
If the all-reduce takes 20 ms and each local step takes 100 ms, compute the effective speedup achieved by local SGD with the optimal from part (a), relative to .
For a diffusion model trained on a mixture of photographic and synthetic data (which tend to produce heterogeneous gradients), explain qualitatively how you would adapt the synchronisation period during training to balance speed and model quality.
Exercise 27 (Ring attention communication analysis).
Consider ring attention on GPUs processing a sequence of length with embedding dimension .
Compute the total bytes transmitted per attention head in the ring rotation scheme, and compare to the all-gather approach where every GPU gathers the full KV cache.
Ring attention requires rounds of computation and communication. If each round takes ms for the local attention and ms for the KV transfer, compute the total time with and without overlapping compute and communication.
Extend the ring to a bidirectional ring where each GPU sends KV blocks both clockwise and counter-clockwise simultaneously, halving the number of rounds to . Derive the total communication volume and compare to the unidirectional ring.
Exercise 28 (Gossip protocol mixing time).
Consider gossip SGD on a ring graph with workers and mixing matrix , .
The spectral gap of the ring mixing matrix is for large . Compute the number of gossip rounds needed for the mixing error to fall below .
Compare this to the exponential graph (spectral gap ) in terms of rounds required for the same . Express the improvement factor as a function of .
For a diffusion model with parameters trained on workers, compute the wall-clock time for gossip SGD to converge to the same accuracy as all-reduce SGD (assume each gossip round exchanges parameters with two neighbours, and all-reduce runs at 400 Gbps). Which approach is faster when the compute time per step is 50 ms?
Data Parallelism for Generative Models
Of all the strategies for distributing the training of a deep neural network across multiple accelerators, data parallelism is the oldest, the most intuitive, and in many practical regimes the most effective. Its governing idea is almost embarrassingly simple: if you want to process more data faster, give each GPU its own slice of the data and let it run independently, then synchronise gradients at the end of each step. The model is replicated, the data is partitioned, and the mathematics of stochastic gradient descent guarantees that every replica converges to the same parameter values as long as the gradient synchronisation is exact.
This simplicity is not a weakness. It is a design virtue. The engineer deploying a data-parallel job does not need to reason about which layer lives on which device, how activation memory should be sliced, or whether the forward pass needs to be pipelined across machines. The abstraction is clean: one model, many data shards, one collective communication operation per backward pass. Everything else follows.
Historical Note.
Data-parallel training predates modern deep learning. The first large-scale instantiation appeared in Google's DistBelief framework (2012), which used asynchronous parameter-server updates to train acoustic models on thousands of CPU cores. The subsequent decade of GPU cluster growth, the emergence of high-bandwidth interconnects (NVLink, InfiniBand), and the introduction of collective communication libraries (MPI, NCCL) shifted the dominant paradigm from asynchronous parameter servers to synchronous all-reduce, the architecture that underlies PyTorch DDP, Horovod, and the distributed training stacks of every major cloud provider today. The first large language models trained at billion-parameter scale - including the GPT-2 (2019) and GPT-3 (2020) families - relied heavily on data parallelism as their outermost parallelism axis, partitioning massive corpora across hundreds of GPUs while replicating the model on each.
The Data-Parallel Protocol
We now state the data-parallel training protocol precisely.
Definition 20.
(Data Parallelism.) Let be a neural network with parameters , and let be a training dataset. Data parallelism with workers partitions each mini-batch of size into disjoint shards with for each , and maintains identical copies of the parameters. At each training step :
Each worker independently computes the local loss (Local LOSS)
Each worker computes the local gradient via backpropagation.
A collective all-reduce operation computes the globally averaged gradient (Global GRAD) and delivers to every worker simultaneously.
Every worker applies the same parameter update , maintaining the invariant .
The result is mathematically equivalent to computing the gradient over the full mini-batch : since the shards are disjoint and the loss is an average, where .
The invariant is the central guarantee of synchronous data parallelism. As long as every worker receives exactly the same averaged gradient , and applies exactly the same update rule, the replicated models remain byte-for-byte identical after every step. This is not an approximation; it is exact.
Forward Pass: Independent Computation on Each Shard
The forward pass in data-parallel training is entirely independent across workers. Worker loads its local shard from storage (or from a distributed data loader), pushes it through the network , and computes the local loss . No communication occurs during the forward pass. This is the primary reason data parallelism achieves near-perfect compute scaling: if communication cost is zero, adding a -th worker reduces wall-clock time per step by exactly .
For generative models the forward pass often involves additional stochasticity. In a diffusion model, each forward pass samples a noise level and noise independently per GPU; the workers therefore process genuinely different noisy versions of their data shards even if the clean images are similar. In a language model, different shards contain different token sequences, and the causal attention patterns are entirely independent across GPUs. In both cases, the forward pass requires zero inter-GPU communication.
Backward Pass and Gradient Synchronisation
The backward pass computes on each worker using the standard backpropagation algorithm. Each worker's gradient is a noisy estimate of the true gradient with the same expected value (assuming i.i.d. data shards), but it is computed on only examples and therefore has higher variance than a gradient computed on the full batch .
The synchronisation step, implemented by an all-reduce collective (Section All-Reduce: The Workhorse of Distributed Training), computes the average . This average has the same expectation as each local gradient but variance reduced by a factor of relative to a single-worker gradient on a shard of size , and is statistically equivalent to a gradient computed on the full mini-batch of size . The synchronisation step is the only communication bottleneck in data-parallel training. Every other computation is perfectly parallelised.
Remark 13.
(Synchronous vs. Asynchronous Data Parallelism.) The protocol above is synchronous: all workers wait for the all-reduce to complete before updating parameters. An alternative, asynchronous data parallelism (as in the original DistBelief), allows each worker to update parameters independently without waiting for other workers, using a central parameter server. Asynchronous training can tolerate stragglers (slow workers) and reduces communication blocking, but introduces stale gradients: a worker may compute a gradient based on a parameter vector and then apply that gradient after the server has already applied updates from other workers, yielding the update . For deep generative models, the resulting staleness degrades convergence quality noticeably, and the homogeneous GPU clusters used in modern training-where all workers are nearly identical in speed-make the synchronous approach strongly preferable.
Parameter Update: Keeping All Replicas Synchronised
After the all-reduce delivers to every worker, each worker applies its local optimiser-Adam, AdamW, SGD with momentum, or any other stateful optimiser-to update its local copy of . Because the optimiser state (first and second moment estimates in Adam, momentum buffers in SGD) is initialised identically on all workers and updated with the same at every step, the optimiser state remains synchronised across workers throughout training without any additional communication. This is a property of deterministic optimisers applied to identical inputs; it holds exactly in floating-point arithmetic and approximately in practice due to the non-associativity of floating-point addition.
Caution.
In practice, floating-point summation is not associative: in IEEE 754 arithmetic. When the all-reduce aggregates gradients in different orders on different runs, the accumulated rounding errors may cause sub-bit divergence between workers. Most frameworks accept this as an acceptable price of performance. If strict reproducibility is required (e.g., for auditing), gradient communication must use compensated summation (Kahan summation) or must serialise the accumulation order, both of which are slower.
TikZ Figure: Data-Parallel Training Flow
Figure fig:distgen:datapar-flow illustrates the complete data-parallel training loop for four GPU workers.
PyTorch DDP: Implementation Details
PyTorch's DistributedDataParallel (DDP) module is the
canonical implementation of synchronous data parallelism.
Understanding its internals is essential for tuning large-scale
generative model training.
Process groups.
DDP organises workers into a process group-a named collection
of communicating processes identified by rank and world size.
Each process runs on one GPU and is assigned a unique integer rank
.
Rank 0 is conventionally the master process that handles logging and
checkpointing.
Process groups are initialised via the dist.init_process_group
call, which specifies a backend (nccl for GPU-to-GPU
communication over NVLink or InfiniBand, gloo for CPU
communication or debugging) and a rendezvous endpoint.
[caption={DDP initialisation and wrapping.}]
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
# Initialise the NCCL process group
dist.init_process_group(backend="nccl")
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
# Wrap the model: DDP adds gradient hooks and manages bucketing
model = MyGenerativeModel().cuda(local_rank)
model = DDP(model, device_ids=[local_rank],
find_unused_parameters=False)
# DistributedSampler ensures non-overlapping shards
sampler = torch.utils.data.DistributedSampler(dataset)
loader = DataLoader(dataset, batch_size=B // world_size,
sampler=sampler)
# Standard training loop -- gradient sync is automatic
for batch in loader:
optimizer.zero_grad()
loss = criterion(model(batch))
loss.backward() # all-reduce fires here
optimizer.step()
Gradient hooks and bucketing.
The key performance optimisation in DDP is gradient bucketing
combined with communication-computation overlap.
Rather than waiting for the entire backward pass to finish and then
issuing a single large all-reduce for all parameters, DDP groups
parameters into buckets of approximately 25 MB each (the
default, tunable via bucket_cap_mb).
Each bucket's all-reduce is launched as soon as all gradients in that
bucket have been computed during the backward pass, overlapping
communication with the remaining backward computation.
The mechanism works through PyTorch's autograd hooks.
DDP registers a hook on each parameter tensor that fires immediately
when that parameter's gradient is ready (i.e., when the autograd
engine calls AccumulateGrad for that parameter).
When all parameters in a bucket have fired their hooks, DDP issues
the NCCL all-reduce for that bucket asynchronously.
By the time the backward pass reaches the first layer (and its
parameters' gradients become ready), the all-reduces for later layers
are often already complete.
Remark 14.
The find_unused_parameters=False flag in the DDP
constructor disables a scan that checks whether any parameters did
not receive gradients during the backward pass (which can happen in
models with dynamic computation graphs, e.g., mixture-of-experts
with conditional routing).
Setting it to False when all parameters are always used
removes a non-trivial overhead proportional to the number of
parameters.
For LLMs with static computation graphs (standard transformer blocks
without conditional computation), always set
find_unused_parameters=False.
Data loading.
The DistributedSampler ensures that each worker receives
a non-overlapping subset of the dataset indices at each epoch.
It does so by computing the modular assignment:
worker receives indices after
shuffling with a fixed random seed derived from the epoch number.
This guarantees that the union of all shards covers the dataset
exactly once per epoch and that no two workers process the same
sample in the same step.
Batch Size Scaling and the Linear Scaling Rule
Data parallelism with workers multiplies the effective batch size by . A natural question arises: if the batch size increases -fold, should the learning rate also change? The empirical answer, due to Goyal et al. (2017) in the context of large-scale ImageNet training, is the linear scaling rule: scale the learning rate linearly with the batch size.
Definition 21.
(Effective Batch Size.) In a data-parallel job with workers each processing a local mini-batch of size , the effective batch size is (Effective Batch) The gradient computed across all workers by the all-reduce is mathematically equivalent to the gradient computed on a single device with mini-batch size . Consequently, all hyperparameter choices that depend on batch size- learning rate, learning rate schedule, weight decay-should be treated as functions of , not of .
The linear scaling rule.
Consider SGD with learning rate and mini-batch size . After one step, parameters move by , where is the mean gradient over samples. If instead we use batch size (with -fold more data per step), the mean gradient changes but the step magnitude is now (gradients average out over more samples, reducing variance but not changing the expected step direction substantially). To maintain the same expected parameter displacement per unit of data processed, we set : (Linear Scaling) Here and are the reference batch size and learning rate (typically tuned for a single-GPU run), and is the effective batch size in the distributed job.
The linear scaling rule has been validated empirically across image classification, object detection, and language model pre-training. It fails in two regimes: (i) very small batch sizes, where gradient noise plays a beneficial regularisation role that disappears as , and (ii) very large batch sizes (beyond the critical batch size ), where the gradient signal becomes dominated by curvature rather than noise and linear scaling overestimates the optimal learning rate.
Warmup: Stabilising Large-Batch Training
When the effective batch size is very large-as it is in practice, with 32 or more GPUs each processing hundreds of tokens or images-training can become unstable in the early steps. The reason is that parameter initialisations are random, and the gradients computed on random initialised parameters have much higher variance than gradients computed near a local minimum. A large learning rate applied immediately can cause the loss to diverge before the network has settled into a stable optimisation trajectory.
The standard remedy is linear learning rate warmup: (Warmup) where is the number of warmup steps (typically 1000–5000 for LLM pre-training, or 500–2000 for diffusion model training). After step , the learning rate is held at or decayed by a cosine, linear, or inverse-square-root schedule.
Goyal et al. recommend setting proportional to the effective batch size: roughly five training epochs' worth of steps at the reference batch size. For large language models the warmup is often shorter in terms of tokens processed but longer in wall-clock time because the effective batch size is measured in tokens per step (often or more for GPT-3-scale training) rather than in images.
Remark 15.
Warmup is arguably even more important for adaptive optimisers (Adam, AdamW) than for SGD. In the first few steps, Adam's second-moment estimate is very small (it is initialised to zero and accumulates only gradually), causing the effective step size to be much larger than intended. The bias-correction terms in Adam partially address this, but for very large learning rates the correction is insufficient. Warmup limits the maximum early learning rate and allows to stabilise before full-scale updates begin. This is why virtually every published LLM training recipe, from BERT to LLaMA to GPT-4, specifies a warmup period regardless of batch size.
LLM Training with Data Parallelism
GPT-2 (1.5B parameters) was trained primarily using data parallelism across 32 V100 GPUs. At 1.5B parameters in FP32, the model occupies roughly 6 GB-well within the 16 GB memory of a V100-leaving substantial memory for activations and gradients. With 32 GPUs each processing sequences of 1024 tokens at a local batch size of 8 sequences, the effective batch size was sequences, or approximately tokens per gradient step.
GPT-3 (175B parameters) required a fundamentally different approach: no single GPU can hold 175B parameters in FP32 (700 GB), so data parallelism alone was insufficient. Instead, Megatron-LM combined data parallelism with tensor parallelism and pipeline parallelism in what is now called 3D parallelism. Nevertheless, data parallelism remained the outermost axis: the full model (distributed across tensor and pipeline dimensions) was replicated across multiple data-parallel groups, each containing a complete model replica. The gradient all-reduce across data-parallel groups operated on averaged gradients that were themselves the result of pipeline parallelism within each group.
Remark 16.
Modern LLM training is governed by Chinchilla-optimal scaling laws, which prescribe training a model with parameters for approximately tokens. Data parallelism enables the throughput (tokens per second) needed to process the required token budget within a reasonable training wall-clock time. A 7B-parameter model trained to 2 trillion tokens at a throughput of 100K tokens per second (achievable with 64 A100 GPUs in data-parallel mode) requires approximately seconds years. This is why in practice, data parallelism is always combined with model parallelism for LLMs beyond approximately 10B parameters.
Diffusion Model Training with Data Parallelism
Diffusion models are exceptionally well-suited to data parallelism because their training procedure is inherently i.i.d. over data samples and noise realisations. Recall that DDPM training minimises (DDPM LOSS) where with and . Each training sample involves independently sampling from the dataset, from the noise schedule, and from a Gaussian. There is no dependence between samples, so data shards can be processed entirely independently across GPUs.
In a 32-GPU data-parallel job for Stable Diffusion training (which operates on latent-space images of size at standard compression rate):
Each GPU processes a local batch of latents per step.
Each GPU independently samples noise levels and noise vectors -different GPUs will have different pairs even for the same image .
The U-Net backbone (M parameters in SD 1.x) fits comfortably in GPU memory alongside activations for latents.
After backpropagation, the 860M-parameter gradient requires an all-reduce of approximately GB in BF16 across 32 GPUs.
Example 10.
(Throughput for Stable Diffusion with 32 GPUs.)
Setup. Training Stable Diffusion 1.5 (860M U-Net parameters) on a cluster of 32 NVIDIA A100 80 GB GPUs connected via InfiniBand HDR (200 Gb/s per link). Each GPU processes a local mini-batch of latent images per step; effective batch size .
Compute time. Each forward-backward pass on an A100 at BF16 precision on a latent with a 860M-parameter U-Net takes approximately 120 ms per GPU for a batch of 16.
Communication time. The gradient all-reduce communicates GB of BF16 gradient data. Ring all-reduce (Section All-Reduce: The Workhorse of Distributed Training) requires communicating GB total across 32 links. At InfiniBand HDR bus bandwidth of 25 GB/s per GPU, communication time ms.
Overlap. With DDP's gradient bucketing, communication and computation overlap: all-reduces for later layers begin while early layers are still computing. Effective end-to-end step time with overlap: ms.
Throughput. Steps per second per GPU: steps/s. Images per second (across all 32 GPUs): images/s.
Comparison. A single A100 at achieves images/s. The 32-GPU speedup is , corresponding to an efficiency of . The 15% efficiency loss is attributable to all-reduce communication latency not fully hidden by computation overlap.
Key Idea.
Data parallelism scales compute perfectly when communication cost is negligible: each additional GPU processes additional data, and the all-reduce cost is in gradient size regardless of the number of GPUs (in bandwidth-optimal all-reduce implementations). In practice, efficiency above 80–90% is routinely achievable for models where the gradient size is small relative to compute time, covering the majority of diffusion models and LLMs up to approximately 10B parameters. Beyond this scale, the all-reduce latency begins to dominate and additional parallelism strategies are required. The data-parallel axis should always be saturated first, before introducing the higher engineering complexity of tensor or pipeline parallelism.
Exercises
Exercise 29.
(Gradient Equivalence in Data Parallelism.) Let be the mini-batch loss over a batch of size . Partition the batch into equal shards of size , and let be the local loss on shard .
- (a)
Show algebraically that , i.e., that the averaged local gradients exactly equal the full mini-batch gradient.
- (b)
Let be the per-sample gradient variance (a scalar, for simplicity). Show that the variance of is , the same as the variance of a gradient computed on the full batch of size .
- (c)
What does this imply for the training dynamics of a data-parallel job relative to a single-GPU job with effective batch size ?
Exercise 30.
(Linear Scaling Rule and Warmup Design.) You are training a diffusion model on a single A100 GPU with local batch size , learning rate , and a warmup of steps. You scale out to GPUs using data parallelism, keeping the local batch size per GPU.
- (a)
Compute the new effective batch size and, using the linear scaling rule, determine the new peak learning rate .
- (b)
Suppose you also scale the warmup duration proportionally to . How many warmup steps should you use? Justify your answer in terms of the expected parameter change per effective unit of data processed.
- (c)
An alternative strategy keeps the learning rate fixed at and increases only the batch size. Discuss the trade-off between this approach and the linear scaling approach in terms of convergence speed and final model quality, referencing the concept of the critical batch size .
Exercise 31.
(DDP Bucketing and Communication-Computation Overlap.) A transformer language model has layers, each with parameters in BF16 (2 bytes each). DDP uses a bucket size of MB. The backward pass proceeds from layer to layer , and each layer's backward computation takes ms. The all-reduce for a full bucket of 25 MB takes ms on the available NVLink interconnect.
- (a)
How many buckets does DDP create for this model, and which layers (approximately) belong to each bucket? (Assume layers are assigned to buckets in reverse order of their backward pass.)
- (b)
If DDP launches the all-reduce for each bucket as soon as the bucket is full, compute the total wall-clock time for the backward pass plus all-reduce, assuming perfect overlap. Compare this to the wall-clock time without overlap (sequential backward then all-reduce).
- (c)
Suppose a training run uses gradient accumulation with micro-steps before each all-reduce (to simulate a larger effective batch size without paying communication cost at every micro-step). How does this change the effective computation-to-communication ratio, and why does it improve GPU utilisation?
All-Reduce: The Workhorse of Distributed Training
Every time a data-parallel job completes one iteration's backward pass, the same question must be answered: how do GPU workers, each holding a local gradient vector , collectively compute the global average and deliver it to every worker simultaneously?
This operation-every process contributes data, every process receives the global reduction-is called all-reduce. It is the single most performance-critical collective communication operation in deep learning. When training a 70B-parameter model on 256 GPUs, every gradient step requires exchanging approximately 280 GB of data (parameters in FP32) via all-reduce. The latency, bandwidth, and algorithmic efficiency of the all-reduce implementation directly determines how fast the model trains.
Remark 17.
All-reduce is one member of a family of collective communication operations. Others include broadcast (one-to-all delivery), reduce (all-to-one aggregation), all-gather (all-to-all delivery of local data), reduce-scatter (all-to-one aggregation with result partitioned across workers), and all-to-all (permutation of data across workers). All-reduce for gradient aggregation can be decomposed as reduce-scatter followed by all-gather, a decomposition that is the foundation of the ring all-reduce algorithm.
The Naive Approach: Reduce to Root and Broadcast
The simplest all-reduce implementation has two phases:
Reduce. Every worker sends its gradient to a designated root (rank 0). Rank 0 receives gradients and computes the sum . Total data received by rank 0: bytes, where bytes is the gradient size ( parameters, bytes each).
Broadcast. Rank 0 sends back to all other workers. Total data sent by rank 0: bytes.
Total communication volume at the root: bytes. Total communication time (assuming the root has bandwidth bytes/second and all links operate serially): (Naive AR) This is a root bottleneck: all inbound gradient streams and all outbound broadcast streams pass through rank 0. As grows, the root's bandwidth requirement grows linearly, making this approach bandwidth-suboptimal.
For a concrete illustration: 256 GPUs, 70B parameters in FP32 ( GB). If the root GPU has 200 Gb/s (25 GB/s) bandwidth: seconds - clearly impractical. Even with infinitely fast compute, the naive approach cannot train a 70B model in data-parallel mode on 256 GPUs without a drastic reduction in communication time.
Tree All-Reduce: Reducing Communication Depth
The tree all-reduce uses a binary tree topology to reduce the communication depth from to . The algorithm has two phases:
Reduction phase (leaves to root).
At each level of a balanced binary tree of depth , each parent node receives gradients from its two children and accumulates them. After levels, the root holds the global sum .
Broadcast phase (root to leaves).
The root sends to its children; each child forwards it to its children. After levels, all workers hold .
Total time (assuming is network latency per hop and is bandwidth): (TREE AR) The latency term is excellent-it grows only logarithmically in . However, the bandwidth term is suboptimal: every step transmits the full -byte gradient through each tree edge, and the internal nodes are bottlenecked at seconds per step. The tree is latency-optimal but not bandwidth-optimal.
Ring All-Reduce: Bandwidth Optimality
The ring all-reduce, introduced into deep learning practice by Baidu Research and popularised by the Horovod framework, achieves bandwidth optimality: it uses each link at maximum utilisation regardless of the number of workers .
Algorithm Description
Arrange workers in a directed ring: worker sends to worker and receives from worker . Divide each gradient vector into equal chunks: , each of size bytes.
Phase 1: Reduce-Scatter ( rounds).
In each round , every worker sends chunk to its right neighbour and accumulates the received chunk into its own copy. After rounds, each worker holds the fully reduced (summed across all workers) version of chunk :
Phase 2: All-Gather ( rounds).
In each round , every worker sends its fully-reduced chunk to its right neighbour. After rounds, every worker holds all reduced chunks and can assemble the global sum .
Both phases involve rounds of sending and receiving bytes per round, for a total communication volume of bytes per worker. The total time is: (RING AR) As with fixed, the bandwidth term is independent of : every worker sends and receives exactly bytes per step but does so at a time in parallel. The latency term grows linearly in , which can be significant for very high over high-latency interconnects.
Bandwidth Optimality of Ring All-Reduce
We now make precise the sense in which ring all-reduce is bandwidth-optimal.
Definition 22.
(Bandwidth-Optimal Collective.) A collective communication algorithm for workers, each contributing bytes, is bandwidth-optimal if the total data communicated per worker is , independent of . Equivalently, every worker's outgoing (or incoming) link is utilised at bytes per second, where is the algorithm's wall-clock time. An algorithm achieves the bandwidth lower bound if no other algorithm can complete the all-reduce while each worker sends fewer than bytes.
Proposition 8.
(Ring All-Reduce Achieves the Bandwidth Lower Bound.) Let workers each hold an -byte gradient vector. Any correct all-reduce algorithm must require each worker to transmit at least bytes and receive at least bytes (ignoring latency). Ring all-reduce transmits exactly bytes per worker ( in reduce-scatter and in all-gather), achieving this lower bound up to the constant factor arising from bidirectional communication.
Proof.
We prove the lower bound. Consider the workers as nodes of a communication graph. After the all-reduce, every worker must hold the global sum of all local vectors. Fix any worker . The other workers' vectors each contribute bytes to each of the chunks of . Worker must receive information about all other vectors. Since each such vector is bytes and the information cannot be compressed below bytes (assuming gradients are incompressible), worker must receive at least bytes from other workers in the network. (In the all-to-all setting where every other worker's data affects every chunk of , a flow argument shows that worker 's incoming link must carry at least bytes.) Since was arbitrary, the bound applies to every worker. Symmetrically, worker must transmit its own gradient to every other worker (each needs it for the reduction), requiring at least bytes transmitted. Ring all-reduce achieves both bounds with equality (per phase), demonstrating bandwidth optimality.
Recursive Halving-Doubling: Balancing Latency and Bandwidth
Ring all-reduce excels when is large (bandwidth-dominant regime) but suffers when is small because the sequential rounds of latency each accumulate: . For small gradient tensors (as arise for individual layer gradients or for small models), this latency dominates.
Recursive halving-doubling (also called recursive bisection) reduces the latency term to while maintaining near-bandwidth-optimal data movement. The algorithm operates in steps (assuming is a power of 2):
Reduce-scatter via recursive halving.
At step : each worker pairs with the worker at distance in the ring, and exchanges halves of its current gradient accumulation. After steps, each worker holds of the fully reduced gradient.
All-gather via recursive doubling.
The reverse: at each of steps, each worker pairs with the worker at distance and exchanges its current chunk, doubling the amount of fully-reduced data each worker holds.
Total time: (Recdouble AR) The latency term matches the tree all-reduce: . The bandwidth term matches ring all-reduce: . Recursive halving-doubling is thus simultaneously latency-optimal and bandwidth-optimal (up to constant factors), making it the preferred choice when both latency and bandwidth matter.
NCCL's Hybrid Approach
NVIDIA's Collective Communications Library (NCCL), the dominant collective communication library for GPU training, uses a hybrid strategy that selects different algorithms based on message size and topology:
Small messages ( KB): latency is dominant. NCCL uses a double binary tree algorithm that achieves latency.
Large messages ( MB): bandwidth is dominant. NCCL uses ring all-reduce, achieving bandwidth.
Intermediate messages: NCCL may use recursive halving-doubling or a tree-ring hybrid.
The switching thresholds are topology-dependent: on NVLink (high bandwidth, low latency), the crossover point shifts toward smaller messages; on InfiniBand (higher latency, moderate bandwidth), ring all-reduce becomes preferable at smaller message sizes.
Double binary tree.
The double binary tree maintains two complementary binary tree topologies over the workers such that every worker is an internal node in at least one tree. This is the key improvement over a single binary tree: in a single tree, leaf nodes only send and receive without accumulating, making them under-utilised. In a double binary tree, every worker participates actively in both trees, achieving near-bandwidth-optimal throughput with latency.
Formally, for workers arranged as ranks , NCCL constructs:
Tree A: standard binary tree rooted at rank 0, with internal nodes .
Tree B: shifted binary tree rooted at rank , whose internal nodes are the leaves of Tree A.
In phase 1, each tree performs a reduce (leaves to root). In phase 2, each tree performs a broadcast (root to leaves). Since both trees are run concurrently, every worker is simultaneously a leaf (in one tree) and an internal node (in the other), saturating all links symmetrically.
Remark 18.
NCCL exposes algorithm selection through environment variables.
NCCL_ALGO=RING forces ring all-reduce regardless of
message size; NCCL_ALGO=TREE forces the double binary
tree.
For gradient tensors in the 1–100 GB range (typical for LLM
training), NCCL_ALGO=RING is almost always optimal.
The NCCL buffer size NCCL_BUFFSIZE controls how much
data is pipelined through the communication channel; increasing
it from the default 4 MB to 64–128 MB can improve bandwidth
utilisation for very large all-reduces at the cost of additional
memory.
All-Reduce for Mixed Precision Training
Modern large-scale generative model training uses mixed precision: forward and backward passes in BF16 or FP16 (2 bytes per parameter), with parameter storage and optimiser state in FP32 (4 bytes per parameter). The all-reduce must communicate gradients efficiently while avoiding catastrophic quantisation errors.
The standard approach is:
Gradient computation. Backpropagation produces gradients in BF16 (matching the activation precision).
All-reduce in BF16. The ring all-reduce communicates BF16 gradients, halving the communication volume relative to FP32. Communication time: where bytes.
FP32 accumulation. After the all-reduce delivers the averaged BF16 gradient, each worker up-casts to FP32 before applying the optimiser update. This prevents optimiser state from accumulating BF16 rounding errors over thousands of steps.
The BF16 all-reduce introduces a small quantisation error in the averaged gradient. For typical gradient magnitudes encountered in transformer training, the BF16 format (8-bit exponent, 7-bit mantissa) introduces relative errors of approximately . This is negligible compared to the stochastic gradient noise from mini-batch sampling (which is typically 10–100 larger) and does not measurably affect final model quality in practice.
Remark 19.
FP16 (5-bit exponent, 10-bit mantissa) has a much smaller dynamic range than BF16 (8-bit exponent, 7-bit mantissa). Large gradients can overflow FP16's maximum representable value (), corrupting the all-reduce. Loss scaling-multiplying the loss by a large constant before backpropagation and dividing gradients by after the all-reduce-shifts gradient magnitudes into FP16's representable range. Automatic mixed precision (AMP) in PyTorch handles loss scaling automatically. BF16 does not require loss scaling (its dynamic range matches FP32) and is preferred for LLM training where gradient magnitudes can vary widely across layers and training stages.
TikZ Figure: Algorithm Comparison
Figure fig:distgen:allreduce-comparison compares the communication time of three all-reduce algorithms as a function of message size .
Profiling All-Reduce for a 70B LLM
Example 11.
(All-Reduce for a 70B LLM Gradient on 256 GPUs.)
Setup. A 70B-parameter LLM (similar to LLaMA-70B) is trained with data parallelism across GPUs connected via InfiniBand HDR (200 Gb/s per port, approximately 25 GB/s unidirectional bandwidth per GPU). Gradients are maintained in FP32 (4 bytes per parameter).
Gradient size. parameters. GB in FP32.
Naive all-reduce time. Root receives GB. At 25 GB/s: s. Manifestly impractical.
Ring all-reduce time (FP32). Using Eq. : The bandwidth term dominates.
Ring all-reduce time (BF16). In BF16, the gradient tensor is GB:
Compute time per step. On 256 A100 80 GB GPUs at BF16 precision with local batch size sequences of 2048 tokens (effective batch size sequences tokens), the forward-backward compute time is approximately 20–30 s per step for a 70B model.
Communication fraction. With DDP overlap, communication runs concurrently with backpropagation. Communication time ( s in BF16) vs. compute time ( s): communication-to-compute ratio . Even with perfect overlap, a residual none (compute dominates), so effective overhead from all-reduce is minimal. For smaller models or higher GPU counts (where compute time shrinks and communication time stays roughly constant), this ratio worsens.
Practical implication. At 256 GPUs in pure data-parallel mode with a 70B model, the communication-to-compute ratio is already approaching unity, explaining why practitioners switch to 3D parallelism (data + tensor + pipeline) for models above 10B parameters when scaling to hundreds of GPUs.
Insight.
All-reduce is the heartbeat of distributed training: its completion marks the synchronisation point at which every GPU transitions from independent local computation to a shared global state. The rhythm of this heartbeat-its frequency (steps per second), its cost (communication time per step), and its reliability (whether any GPU lags behind)-determines the practical throughput of the entire training cluster. Optimising all-reduce through bandwidth-optimal algorithms, communication-computation overlap, mixed-precision gradients, and topology-aware collective scheduling is not a micro-optimisation: for large-scale generative model training, it is the difference between a training run that completes in a week and one that completes in a month.
Exercises
Exercise 32.
(Ring All-Reduce Step-by-Step.) Consider workers, each holding a gradient vector partitioned into chunks: for . The ring is .
- (a)
Write out the complete state of every worker's chunk array after each of the 3 rounds of the reduce-scatter phase. Specifically, denote the partial sum as and express each entry in terms of these partial sums.
- (b)
After the reduce-scatter, worker 2 holds a fully reduced chunk. Which chunk is it, and write its value as a sum over the original gradient chunks.
- (c)
Write out the complete state of every worker's reconstructed gradient after each of the 3 rounds of the all-gather phase. Verify that after 3 rounds, every worker holds the global sum in all four chunk positions.
Exercise 33.
(Algorithm Selection and Performance Analysis.) You are choosing an all-reduce algorithm for a training job with GPUs. The interconnect has latency s and bandwidth GB/s per link. Consider three gradient sizes arising in three different training scenarios:
- (a)
KB (a single transformer layer's attention projection weights, e.g., for gradient accumulation with per-layer all-reduce).
- (b)
MB (a small 125M-parameter language model in BF16).
- (c)
GB (a 7B-parameter model in BF16).
For each scenario: (i) compute , , and using Eqs. , , and ; (ii) identify which algorithm minimises communication time; (iii) characterise whether the regime is latency-dominant or bandwidth-dominant.
Exercise 34.
(Mixed Precision All-Reduce and Gradient Quantisation.) A 13B-parameter language model () is trained with GPUs using ring all-reduce. InfiniBand bandwidth per GPU is GB/s.
- (a)
Compute the ring all-reduce time for gradients in FP32 (4 bytes/param), BF16 (2 bytes/param), and a hypothetical INT8 quantisation (1 byte/param, with a quantisation error analysis deferred to part (c)). What is the speedup of BF16 over FP32?
- (b)
Gradient compression via 1-bit quantisation (also known as 1-bit Adam or SignSGD) represents each gradient element as its sign, reducing communication to bytes. Compute the ring all-reduce time for 1-bit gradients and compare it to BF16. What is the compression ratio?
- (c)
Suppose INT8 gradient quantisation introduces a relative quantisation error of in the gradient values, and this error accumulates for training steps. Under what condition on the per-step stochastic gradient noise is the accumulated quantisation error negligible compared to the noise floor? Express your condition as a bound on relative to .
Tensor Parallelism
There is a moment in the life of every large-model practitioner when the error message changes character. It is no longer a runtime fault, an out-of-memory spike from a temporarily large batch, or a gradient explosion that a learning-rate schedule can cure. Instead, the GPU memory profiler shows that the model's weights alone - before any activations, gradients, or optimiser states are allocated - already exceed the device's capacity. A single transformer block with hidden dimension and four linear projections holds approximately ,bytes of float16 parameters: roughly 537,MB per block. Multiply by 80 transformer layers and the total parameter memory is 43,GB - more than the 40,GB HBM of an A100, before a single token has been processed.
Data parallelism cannot help here. Replicating the model across devices does not make it smaller; it makes the out-of-memory problem worse. Mixed-precision and quantisation buy a factor of two to four in memory, but at 70 billion parameters, even 4-bit quantisation still demands 35,GB. The only principled solution is to cut the model itself: to distribute the weight tensors across multiple devices so that no single device holds the complete parameter set. This is the domain of tensor parallelism.
Key Idea.
Tensor parallelism is surgery on the matrix - cut the weight, not the data. Where data parallelism replicates the entire model and partitions the dataset, tensor parallelism partitions the weight matrices themselves, distributing the arithmetic of a single linear layer across multiple devices. Every device processes the full input, but each device computes only a portion of the output.
The Core Problem: Layers Wider than GPU Memory
Modern large language models and diffusion transformers are characterised by two trends that drive memory pressure simultaneously: width and depth. Width, measured by the hidden dimension , determines the size of each weight matrix. Depth, measured by the number of transformer blocks , determines how many such matrices must be loaded.
For a single multi-head attention layer with hidden dimension , query/key/value dimension , and attention heads, the parameter count is: (ATTN Params) The feed-forward network (FFN) that follows the attention block typically uses an expansion ratio of 4, giving: (FFN Params) Combined, a single transformer layer holds parameters, and the entire model: (Total Params) For LLaMA-70B with and , this yields - consistent with the advertised parameter count. At BF16 precision (2 bytes per parameter), weights alone require 128.8,GB of device memory. No single GPU in 2024 can hold this.
Remark 20 (Memory multiplier for training).
Weight memory is only one component of total GPU memory during training. The Adam optimiser requires two additional copies of each parameter tensor (first and second moment estimates), and mixed-precision training maintains a float32 master copy. The total memory multiplier relative to the BF16 parameter count is therefore - a 70B model demands approximately 644,GB for weights and optimiser states alone. With 80,GB A100s, this requires a minimum of 9 GPUs even before activations.
Definition: Tensor Parallelism
Definition 23 (Tensor Parallelism).
Let be a linear layer with weight matrix and input , computing . Tensor parallelism over devices partitions along one of its axes into shards such that , where device stores and computes with only. The full output is recovered via a collective communication operation (all-reduce or all-gather) whose cost is independent of the number of model parameters.
The elegance of tensor parallelism lies in what it does not require: no changes to the mathematical definition of the layer, no approximations, no loss of numerical equivalence. The computation is split, but the mathematical result is identical to single-device computation, up to floating-point rounding.
Megatron-LM: Column and Row Parallel Linear Layers
The seminal work on tensor parallelism for transformers was the Megatron-LM system, which identified that the key linear layers in a transformer block can be cleanly partitioned in a way that requires only two all-reduce operations per transformer layer - an astonishingly small communication overhead for a complete layer partitioning. The insight is that attention and FFN layers come in complementary pairs that can be assigned opposing split strategies.
Column-Parallel Linear Layer
A column-parallel layer splits the weight matrix along its output (column) dimension. With devices, define: (COL Split) The full input is replicated across all devices. Device computes a partial output: (COL Compute) The full output is recovered by concatenating across the column dimension: (COL Concat) No communication is required within the column-parallel computation. Each device independently computes its shard of the output. If a non-linearity (such as GeLU) follows the linear layer, it can be applied locally on each device's partial output, since GeLU operates element-wise.
Row-Parallel Linear Layer
A row-parallel layer splits the weight matrix along its input (row) dimension. With devices: (ROW Split) The input is correspondingly split along the feature dimension, so device holds: (ROW Input) Each device computes a partial output: (ROW Compute) The full output is the sum of all partial outputs, recovered by an all-reduce operation: (ROW Allreduce) This all-reduce is the sole communication point of a row-parallel layer.
Self-Attention Parallelism: Splitting Heads Across GPUs
Multi-head attention provides a natural structure for tensor parallelism: the attention heads are independent of one another within a single attention layer. Head attends only to queries, keys, and values projected by the matrices , , of dimension where . There is no cross-head interaction until the outputs are concatenated and projected by .
This structure maps precisely onto column-parallel computation. Partition the heads across devices, with heads per device. Let , , . Denote the block of heads assigned to device as the index set . Device computes: (ATTN HEAD Parallel) The result of each device is a partial attention output of size , where is the sequence length. Concatenation across devices produces the full attention output, and the output projection is handled as a row-parallel layer.
The combined Q, K, V projections (column-parallel) followed by the output projection (row-parallel) form one complementary pair. No communication is needed between the two projections. Only one all-reduce is required at the end of the output projection to reconcile the row-parallel partial sums.
MLP Parallelism: Complementary Column-Row Pairs
The feed-forward network (FFN) in a transformer block consists of two linear layers with a non-linearity between them: (FFN) where and . The Megatron strategy applies column-parallelism to and row-parallelism to :
Column-parallel . Device holds and computes . The GeLU is applied locally since it is element-wise. No communication is needed.
Row-parallel . Device holds and computes . The partial sums are reconciled by an all-reduce: .
The critical property is that the column split of partitions the intermediate (expansion) dimension. Device 's output is exactly the chunk of intermediate features needed as input to its shard of . No cross-device communication is needed between the two layers.
The Megatron Transformer Block: Communication Cost
The communication cost of this scheme is precisely two all-reduce operations per transformer layer: one after the attention output projection and one after the FFN. Each all-reduce communicates a tensor of size (for batch size , sequence length , hidden dimension ).
Proposition 9 (Communication Volume per Layer).
With tensor-parallel devices, the all-reduce in the ring-allreduce algorithm requires each device to send and receive bytes of data per all-reduce (the factor of 2 accounts for BF16 storage), for a total of bytes per transformer layer. For large , this approaches bytes per layer regardless of - the communication overhead is bounded.
In practice, this overhead is paid in latency, not just bandwidth, because the all-reduce blocks the forward pass. The implication is that tensor parallelism is suitable only when the inter-device bandwidth is high enough to make this latency negligible: in practice, NVLink (600,GB/s bidirectional on H100) makes intra-node tensor parallelism viable, while Ethernet or InfiniBand between nodes (100–200,Gb/s) makes cross-node tensor parallelism a serious bottleneck.
Caution.
Do not deploy tensor parallelism across network nodes unless you have InfiniBand HDR (200,Gb/s) at minimum. The all-reduce latency on 25,GbE inter-node links at batch size 1 can exceed the compute time of the very operation it is supposed to speed up. Use pipeline parallelism (Section Pipeline and Sequence Parallelism) for inter-node distribution.
Tensor Parallelism for Attention: Handling KV Heads
Modern LLMs increasingly use grouped query attention (GQA) or multi-query attention (MQA) to reduce the KV cache footprint. In GQA, query heads share KV heads, with each group of query heads attending to a single KV head. This changes the head-parallelism strategy.
Let be the tensor-parallel degree. For correctness, the number of KV heads must be divisible by , so that each device holds exactly complete KV groups. Each device's query heads must be aligned with its KV head assignments: device processes query heads and KV heads . If (more tensor-parallel devices than KV heads), attention cannot be naively parallelized by heads alone, and sequence parallelism (Section Sequence Parallelism) must be used.
Tensor Parallelism for Diffusion Transformers
Diffusion Transformers (DiTs) replace the U-Net backbone of traditional diffusion models with a pure transformer architecture. DiT blocks have the same structure as language model transformer blocks - self-attention followed by a cross-attention or conditioning mechanism, followed by an MLP - and are therefore amenable to the same Megatron-style tensor parallelism.
The distinct feature of diffusion models is the conditioning signal, typically a timestep embedding and class or text embedding . These conditioning vectors are projected through adaptive layer norm (adaLN) modules that modulate scale and shift parameters of the residual stream. The adaLN projection is a linear layer from the conditioning space to (scale and shift), which can be handled as a column-parallel layer, with the scale-shift application remaining local.
Example 12 (Tensor-Parallel DiT for Video Generation).
A video DiT operating on frames at resolution with patch size produces tokens per sample - over one million tokens. With hidden dimension and 28 transformer blocks, the parameter count for attention and FFN layers is approximately parameters. At BF16, this is 11.4,GB of weights; with 4-way GQA and optimizer states, total training memory exceeds 80,GB per sample. Applying 4-way tensor parallelism across 4 GPUs on the same node (via NVLink) reduces per-GPU weight memory to ,GB for parameters, making the model comfortably fittable alongside activations and the optimizer on each 80,GB device. The communication overhead is 2 all-reduces per block, each of size BF16 - roughly 8,GB at batch size 1 and tokens, transmitted at NVLink speed (,ms per all-reduce at 600,GB/s), amounting to 14,ms of communication overhead per block.
Memory Savings and Communication Overhead: LLaMA-70B
Example 13 (Tensor Parallelism for LLaMA-70B).
LLaMA-70B has layers, , query heads, GQA heads, and an FFN expansion dimension of (using SwiGLU, which has three weight matrices). We compute memory savings and communication cost for -way tensor parallelism.
Parameter memory. The total parameter count for attention and FFN layers is: Total: parameters, requiring 156,GB at BF16. With : each GPU holds ,GB of parameters. With Adam optimizer states (factor in float32 for full training): ,GB optimizer memory per GPU - tight but feasible on 80,GB H100s.
Communication overhead. Each transformer layer requires 2 all-reduces of size BF16. For , : ,MB per layer, or ,GB total per forward pass. Over NVLink at 600,GB/s effective bandwidth: ,ms total communication per forward pass - less than 5% overhead at typical token throughputs.
Remark 21 (Limits of Tensor Parallelism).
Tensor parallelism does not scale indefinitely. At , 16 all-reduces (2 per layer 8 layers per NVLink domain) must be serialized along the critical path. Beyond on a single node, the all-reduce latency begins to dominate compute, and the per-GPU workload shrinks to the point where GPU utilisation falls below 30%. The practical ceiling for tensor parallelism is typically within a single 8-GPU node. Larger models require combining tensor parallelism with pipeline and data parallelism.
Exercises
Exercise 35 (Column-parallel backward pass).
Derive the gradient computation for a column-parallel linear layer. Specifically, show that the gradient of the loss with respect to the weight shard is and requires no inter-device communication, while the gradient with respect to the input requires an all-reduce. (Hint: recall that is replicated, so gradient accumulation happens locally on each device before reducing.)
Exercise 36 (Tensor parallelism with GQA constraint).
A model uses query heads and KV heads.
- (a)
What is the maximum tensor-parallel degree that allows exact head partitioning of the KV cache?
- (b)
If you wish to use , describe a strategy that replicates KV heads across devices and maintains correctness.
- (c)
What is the memory cost of KV replication relative to the naive single-device KV cache, for a context of length and head dimension at BF16?
Exercise 37 (Communication-compute overlap).
In the Megatron scheme, the all-reduce after the attention output projection must complete before the FFN begins. Propose and analyse a scheme to overlap the all-reduce with independent computation, and identify what architectural changes are needed. Hint: consider whether layer normalisation (which follows the attention residual) can be computed before the all-reduce completes, and under what numerical conditions this is safe.
Pipeline and Sequence Parallelism
Tensor parallelism is powerful within a node, but it saturates at the boundary of NVLink connectivity. For models that span hundreds of billions of parameters, no single 8-GPU node suffices even with perfect tensor parallelism. The model must be distributed across nodes, where the inter-device links are InfiniBand or Ethernet rather than NVLink - links that are 10 to 100 times slower.
This changes the problem fundamentally. An all-reduce that costs 13,ms over NVLink costs 1.3 seconds over 100,Gb/s InfiniBand. The same two all-reduces per layer that were invisible in a single node become catastrophically expensive across nodes.
The solution is not to send the same data everywhere, but to send each datum once, in one direction, and to structure the computation so that different groups of devices work on different layers of the model rather than different shards of the same layer. This is the domain of pipeline parallelism.
Insight.
Pipeline parallelism turns depth into time - the deeper the model, the more stages to fill. Where tensor parallelism cuts horizontally (across the width of each layer), pipeline parallelism cuts vertically (along the depth of the model), assigning consecutive transformer blocks to consecutive devices in a pipeline. The memory of each device holds only its assigned layers, not the entire model. Communication between adjacent stages consists of a single activation tensor - a point-to-point send rather than an all-reduce.
Definition: Pipeline Parallelism
Definition 24 (Pipeline Parallelism).
Let a neural network consist of sequential transformer blocks. Pipeline parallelism over devices assigns a contiguous slice of blocks to device . Device receives the activation output from device , applies its assigned blocks, and sends the result to device . Forward and backward passes are decomposed into micro-batches of size each, which are injected into the pipeline sequentially to overlap the computation of different stages.
The critical concept is the pipeline bubble: the fraction of time that pipeline stages are idle. Understanding and minimising the bubble is the central engineering challenge of pipeline parallelism.
The GPipe Schedule
The GPipe schedule is the simplest pipeline parallelism strategy. The mini-batch of size is split into micro-batches. The forward pass of all micro-batches runs through all pipeline stages before any backward pass begins. Only then does the backward pass execute through all stages for all micro-batches.
Let denote the time for one forward micro-batch through one stage, and the time for one backward micro-batch through one stage (typically ). The total time for the GPipe schedule is: (Gpipe TIME) The ideal time (if the pipeline were perfectly full and there were no bubble) would be , using all stages simultaneously. The bubble fraction is: (Gpipe Bubble) For , the bubble fraction approaches zero. For (a common setting), the bubble is - nearly half the pipeline is idle at any given moment.
Remark 22 (GPipe memory cost).
GPipe must store activations for all micro-batches simultaneously before the backward pass begins. The activation memory per device is proportional to - the full batch size, regardless of the number of micro-batches. This is a significant memory cost that partially offsets the weight memory savings from pipeline parallelism. Activation recomputation (rematerialisation) is typically used in conjunction with GPipe to reduce this cost, at the price of recomputing forward activations during the backward pass.
The 1F1B Schedule: Minimising the Bubble
The 1F1B (one forward, one backward) schedule was introduced in PipeDream to reduce peak activation memory while maintaining the same bubble fraction as GPipe (for the same and ), but with the key advantage that steady-state activation memory is rather than .
In steady state, each device alternates between one forward micro-batch and one backward micro-batch. Device processes the forward pass of micro-batch and immediately queues the backward pass of micro-batch , which has already completed its forward pass through all stages.
Theorem 2 (1F1B Bubble Fraction).
The bubble fraction of the 1F1B schedule is identical to GPipe: (1F1B Bubble) However, the maximum number of in-flight activations on any single device at any time is micro-batches (one per pipeline stage), compared to micro-batches in GPipe.
Proof.
In steady state, device holds activations for the micro-batches that have passed through device 's forward pass but have not yet reached their backward pass through device . In the worst case (device 1), this is micro-batches. Thus the peak activation memory on any device is proportional to , independent of . The bubble fraction computation follows from the same accounting as GPipe: the pipeline requires startup steps and drain steps, contributing of idle time against a total of .
Pipeline Schedules: GPipe vs. 1F1B
Interleaved 1F1B: Multiple Stages per Device
The interleaved 1F1B schedule reduces the bubble fraction by assigning each device multiple, non-contiguous groups of layers rather than a single contiguous block. If each device manages virtual pipeline stages (chunks), the effective pipeline has stages, and the bubble fraction is: (Interleaved Bubble) The factor of means that doubling the number of chunks per device halves the bubble fraction. The trade-off is increased communication volume: each virtual stage boundary requires a point-to-point activation send, so the total communication volume increases by a factor of .
In practice, or is common. With , , and , the bubble fraction is: This is acceptable for most training workloads.
Pipeline Parallelism for Diffusion Models
Diffusion models present a unique opportunity for pipeline parallelism that is not available in autoregressive language models: frozen components. A standard text-to-image pipeline (such as Stable Diffusion or FLUX) consists of:
A text encoder (frozen during fine-tuning, often shared across requests).
A diffusion backbone (U-Net or DiT, the primary trainable component).
A VAE decoder (frozen, maps latents to pixels).
The DiffusionPipe approach exploits the frozen nature of the encoder and decoder by placing them on dedicated pipeline stages. Because the encoder and decoder are frozen, they require no backward pass and no gradient communication. The pipeline stages are:
Stage 1 (encoder GPU): Encodes the text prompt once per request and caches the result. This stage is almost entirely idle during backward passes.
Stage 2–P-1 (backbone GPUs): Execute the forward and backward passes of the diffusion backbone.
Stage P (decoder GPU): Decodes the output latent during inference only.
Remark 23 (Multi-step diffusion sampling and pipelines).
Diffusion sampling requires sequential denoising steps, each a full forward pass through the backbone. This means a single inference request produces sequential activations through the pipeline - exactly the micro-batches that fill the pipeline. For denoising steps and pipeline stages, the bubble fraction is , even with a simple GPipe schedule. This is a natural fit between diffusion inference and pipeline parallelism that does not exist for single-pass feed-forward models.
Sequence Parallelism
Even with tensor and pipeline parallelism managing model weights, a different bottleneck emerges for very long sequences. For a transformer with hidden dimension and sequence length , the activation memory for a single layer is: (SEQ Activation) where for BF16. For , , , this is ,MB per layer. For 80 layers, activation memory alone requires 40,GB - the entire capacity of an A100. This is before any attention scores (which are ) are considered.
The solution is to split the sequence dimension itself across devices. This is sequence parallelism.
Definition 25 (Sequence Parallelism).
Sequence parallelism over devices partitions the sequence dimension of the activation tensor along the axis, so that device holds . Operations that are local along the sequence dimension (layer normalisation, element-wise transformations, FFN) proceed without communication. Operations that require cross-token context (self-attention) require communication of key-value tensors across devices.
In the Megatron-LM implementation, sequence parallelism is used for the parts of the transformer that are not tensor-parallel - specifically the layer norm and dropout layers, which cannot be column/row-parallel. The sequence dimension is split to avoid replicating activations that do not participate in the all-reduce communication of tensor parallelism.
Ring Attention: Global Attention Over Sharded Sequences
The central challenge of sequence parallelism is implementing self-attention, which requires every query token to attend to every key-value token. When queries are on device and key-values are sharded across all devices, each device must communicate its key-value chunk to all other devices to compute full attention scores.
Ring attention (also referred to as context parallelism in some frameworks) solves this by organising the devices into a logical ring. At each step of the ring, each device:
Computes local attention between its query chunk and the current key-value chunk (which it either holds locally or received from the previous device in the ring).
Sends the current key-value chunk to the next device in the ring while receiving the next key-value chunk from the previous device.
Accumulates the attention output using the flash-attention online softmax trick, which allows partial softmax accumulators to be updated iteratively.
Formally, let device hold query chunk and, initially, key-value chunk . After ring steps, device has accumulated: (RING ATTN) which is the correct full-sequence attention output for the query chunk on device .
Remark 24 (Online softmax for ring attention).
A key subtlety is that the softmax in Equation is computed over the full key sequence, but the ring processes key chunks incrementally. The flash-attention online softmax algorithm maintains running statistics - the running row maximum and the running denominator - which can be updated with each new key chunk without materialising the full attention score matrix. This allows ring attention to be computed with memory per device rather than for the full attention matrix.
The communication in ring attention consists of rounds of passing the key-value chunks around the ring. Each round communicates bytes (factor of 2 for K and V). For , (128K context), , , , BF16: Over 7 steps: ,GB of communication per attention layer. At NVLink bandwidth (600,GB/s), this requires ,ms per layer - comparable to the attention compute itself for this sequence length, making the overhead manageable when ring steps are overlapped with compute.
Sequence Parallelism for Very Long Contexts
Context parallelism (CP) is an extension of sequence parallelism developed to handle contexts beyond 128K tokens. At (1M tokens) with , the activation tensor alone requires ,GB per layer, making even 80,GB H100s insufficient at a single-device level.
Context parallelism couples sequence-dimension partitioning with the ring-attention KV communication strategy. The key additional feature for extreme contexts is causal mask awareness: in autoregressive models, token attends only to tokens . This means that the lower-left portion of the attention matrix is fully dense, while the upper-right portion is masked. Devices assigned to later sequence positions must process more attention computation than devices at earlier positions.
To balance load, context parallelism uses a striped partitioning: instead of assigning contiguous chunks , , etc., each device receives every -th token: (CP Stripe) This interleaving ensures that each device has a balanced mix of early (sparse attention) and late (dense attention) positions, equalising the FLOPs per device.
TikZ: Sequence Parallelism with Local Attention and KV Ring
Comparison of Parallelism Strategies
Table tab:distgen:parallelism-comparison summarises the four main parallelism strategies and their key properties.
| Strategy | What is split | Comm. pattern | Memory saving | Best for |
| Data parallel (DP) | Mini-batch | All-reduce gradients | None (parameters replicated) | Small models |
| Tensor parallel (TP) | Weight matrices | 2 all-reduces per layer | parameters/GPU | Intra-node (NVLink) |
| Pipeline parallel (PP) | Transformer layers | Point-to-point activations | parameters/GPU | Inter-node (IB/Eth) |
| Sequence parallel (SP) | Sequence dimension | Ring KV all-gather | activations/GPU | Long contexts (32K) |
In practice, large models use all four strategies simultaneously. The canonical configuration for training a 100B+ parameter model is:
DP degree: Number of complete model replicas, typically .
TP degree: Tensor parallelism within each node, typically .
PP degree: Pipeline stages across nodes, typically .
SP degree: Sequence parallelism equal to TP degree (shared communication groups).
The total number of GPUs is . For GPT-4-scale models (estimated 1 trillion parameters), this translates to thousands of A100 or H100 GPUs.
3D Parallelism: Putting It All Together
The combination of data parallelism (DP), tensor parallelism (TP), and pipeline parallelism (PP) is called 3D parallelism. The three dimensions are orthogonal: within each DP replica, the model is distributed via TP within nodes and via PP across nodes.
Definition 26 (3D Parallelism).
Let be the total number of GPUs. A 3D parallel configuration assigns each GPU a unique triplet where is the data parallel rank, is the pipeline stage, and is the tensor parallel rank, with . All GPUs sharing the same form a tensor-parallel group (communicating via NVLink all-reduce). All GPUs sharing the same form a pipeline group (communicating via point-to-point sends). All GPUs sharing the same form a data-parallel group (communicating via all-reduce of gradients).
The gradient all-reduce across data-parallel replicas can be overlapped with the backward pass using gradient bucketing and asynchronous communication, further hiding communication latency. In the Megatron-DeepSpeed framework, this overlap is achieved by pre-scheduling the all-reduce for each layer's gradients as soon as that layer's backward pass completes, while the backward pass continues to earlier layers.
Practical Considerations: Batch Size and Throughput
Pipeline parallelism imposes a constraint on the micro-batch size and the number of micro-batches . To keep the pipeline full and the bubble fraction below 10%, we need (from the bubble fraction formula with ). For , this requires micro-batches. If each micro-batch has samples with sequence length , the total batch size is samples, or roughly tokens per gradient step. This is consistent with the global batch sizes used in large LLM training ( million tokens per step), achieved by further data parallelism over many replicas.
Remark 25 (Pipeline parallelism and gradient staleness).
In the PipeDream-1F1B schedule, the weights used for the forward pass of micro-batch on stage may differ from the weights used for the backward pass of the same micro-batch, because weight updates occur between the forward and backward passes of different micro-batches. This introduces weight staleness of up to update steps. Megatron-LM avoids this by treating all micro-batches in a single gradient accumulation step as a single logical batch: no weight updates occur until all micro-batches have completed their full forward-backward passes, at which point a single synchronised update is applied.
Exercises
Exercise 38 (Bubble fraction algebra).
- (a)
Derive the bubble fraction formula for the GPipe schedule from first principles. Specifically, draw the time-space diagram for stages and micro-batches, identify the idle time, and verify Equation .
- (b)
Show that for fixed total compute time, increasing always reduces the bubble fraction, and compute the asymptotic bubble fraction as .
- (c)
For and a target bubble fraction of at most 5%, what is the minimum number of micro-batches required?
Exercise 39 (Ring attention communication complexity).
Consider ring attention over devices with sequence length , hidden dimension , attention heads, and head dimension .
- (a)
Derive the total bytes of communication per layer per forward pass in ring attention.
- (b)
Compare this to the all-reduce communication cost of tensor parallelism (Proposition Proposition 9) for the same and . Under what conditions (as a function of and ) does ring attention communicate more than tensor parallelism?
- (c)
For , , , , compute the ring attention communication per layer in GB and estimate the time at 600,GB/s NVLink bandwidth.
Exercise 40 (3D parallelism configuration).
You have 256 H100 GPUs (8 per node, 32 nodes) and wish to train a model with 200 billion parameters ( layers, , heads).
- (a)
Enumerate all valid 3D parallelism configurations with , , and a divisor of .
- (b)
For each configuration, compute: (i) parameter memory per GPU, (ii) bubble fraction with micro-batches, and (iii) total communication per forward pass per GPU.
- (c)
Which configuration minimises the bubble fraction while keeping parameter memory below 40,GB per GPU? Justify whether this configuration is viable for NVLink connectivity within each 8-GPU node.
ZeRO: Zero Redundancy Optimizer
Training large language models is, at its core, a memory management problem as much as a computation problem. A model with seven billion parameters sounds impressive in the abstract, but the concrete arithmetic of what must reside in GPU memory during training is humbling. Before a single batch has been processed, before activations have been stored or gradients computed, the optimizer state alone for a seven-billion-parameter model trained with Adam exceeds one hundred gigabytes. No single consumer GPU holds that much memory. Even the largest data-centre accelerators available today top out at 80–141 GB of HBM. The naive approach to distributing this load - replicating the entire model state on every participating GPU, as classical data-parallel training does - is not just wasteful; for models of this scale it is simply impossible.
The Zero Redundancy Optimizer (ZeRO) addresses this problem systematically. Rather than replicating all model state across every GPU, ZeRO partitions it. Each GPU holds only a fraction of the full state, and GPUs cooperate through collective communication to assemble the pieces they momentarily need. The key insight is that redundancy is the enemy of scale: data-parallel training replicates copies of every tensor across GPUs, consuming times more memory than strictly necessary. ZeRO eliminates that redundancy stage by stage.
The Memory Arithmetic of Large-Model Training
To understand why ZeRO is necessary, we must first understand exactly what occupies GPU memory during training. Consider a model with parameters trained in mixed precision (FP16 forward/backward, FP32 optimizer state) using Adam.
Parameters.
Each parameter is stored in 16-bit floating point (FP16 or BF16) during the forward and backward passes. At 2 bytes per parameter, a model with parameters consumes
Gradients.
Gradients are accumulated in the same precision as parameters during the backward pass - FP16, 2 bytes per parameter:
Optimizer state.
Adam maintains three quantities per parameter in FP32 (4 bytes each): the first moment (momentum) , the second moment (variance) , and the full-precision master copy of the parameter . That is bytes per parameter:
Total (before activations).
For : . Activations - the intermediate tensors needed for backpropagation - add further tens of gigabytes depending on batch size and sequence length. A single A100 GPU has 80 GB of HBM. The 7B model cannot be trained on a single GPU, and classical data-parallel training simply replicates this burden across every GPU.
Remark 26 (Why master weights exist).
FP16 arithmetic is fast and memory-efficient, but it has limited dynamic range and precision. Gradient updates are often many orders of magnitude smaller than parameter values. If the update is too small to be represented in FP16 relative to the current parameter value, the update is silently lost. Storing a full-precision (FP32) master copy of each parameter and applying updates in FP32 prevents this catastrophic precision loss. The FP16 working copy is then cast from the FP32 master at the start of each forward pass.
The memory cost per GPU under classical data-parallel training (DDP) is exactly bytes, regardless of how many GPUs participate. Adding more GPUs reduces computation time via gradient averaging, but it does not reduce the per-GPU memory burden at all. ZeRO changes this.
ZeRO Stage 1: Optimizer State Partitioning
ZeRO-1 targets the dominant memory consumer: the optimizer state. Instead of every GPU holding the full bytes of Adam state, the GPUs collectively partition it. GPU holds optimizer state for parameter indices such that . Each GPU thus maintains bytes of optimizer state rather than bytes.
The training loop under ZeRO-1 proceeds as follows. The forward pass and backward pass are identical to standard DDP: each GPU holds a full copy of the parameters ( bytes) and accumulates a full copy of the gradients ( bytes) via all-reduce. After the all-reduce, however, each GPU discards the gradients it does not own: GPU retains only bytes of gradients. It then applies the optimizer step to its shard of parameters using its shard of optimizer state, and broadcasts the updated parameter shard to all other GPUs via an all-gather.
Definition 27 (ZeRO-1 Memory Consumption).
Let be the number of parameters and the number of GPUs. Under ZeRO-1, the memory consumed per GPU for model state is For large this approaches bytes, a reduction relative to the DDP baseline of bytes.
The communication overhead of ZeRO-1 relative to DDP is modest. The all-reduce on gradients is identical to DDP (communication volume bytes). The additional all-gather after the optimizer step communicates another bytes (FP16 updated parameters). Total communication is thus approximately bytes per training step, compared with bytes for DDP - a factor of two increase, but with up to memory savings.
ZeRO Stage 2: Gradient Partitioning
ZeRO-2 extends the partitioning to gradients as well. During the backward pass, as gradients are computed for each layer, each GPU immediately reduce-scatters the gradients it does not own. GPU accumulates only the gradient shard for parameters , discarding the rest. After the backward pass, GPU holds bytes of gradients and bytes of optimizer state, applies the optimizer step locally, and all-gathers the updated parameter shards.
Definition 28 (ZeRO-2 Memory Consumption).
Under ZeRO-2, the memory consumed per GPU for model state is For large this approaches bytes, an reduction relative to the DDP baseline.
The communication volume of ZeRO-2 equals that of ZeRO-1: the reduce-scatter during backward replaces the full all-reduce of DDP, and the all-gather after the optimizer step restores the parameters. No extra communication is required compared with ZeRO-1 because the reduce-scatter is merely a restructuring of the all-reduce.
ZeRO Stage 3: Full Parameter Partitioning
ZeRO-3 partitions all three components: parameters, gradients, and optimizer state. This is the most aggressive stage and the most powerful in terms of memory reduction - at the cost of higher communication volume.
Under ZeRO-3, GPU permanently holds only the parameter shard . During the forward pass, each layer's parameters must be assembled from all GPUs before they can be used. This requires an all-gather immediately before each layer's forward computation. After the layer's forward computation is complete, the assembled parameters can be discarded - only the shard is retained. The same pattern applies during the backward pass: an all-gather assembles parameters for gradient computation, after which the non-owned shards are discarded. Gradients are then reduce-scattered so that each GPU accumulates only its owned gradient shard, and the optimizer step proceeds locally.
Definition 29 (ZeRO-3 Memory Consumption).
Under ZeRO-3, the memory consumed per GPU for model state is This is the optimal linear scaling: adding GPUs reduces the per-GPU model-state memory by a factor of exactly .
The linear memory reduction of ZeRO-3 comes at the cost of higher communication volume. During the forward pass, each layer triggers an all-gather of its parameters ( bytes total per pass). During the backward pass, another all-gather retrieves parameters for gradient computation ( bytes), followed by a reduce-scatter of gradients ( bytes). Total communication is approximately bytes per step, versus bytes for DDP - a factor of .
Remark 27 (Communication volume comparison).
Summing the communication volumes:
| Method | Memory per GPU | Communication per step |
| DDP (no ZeRO) | bytes | bytes (all-reduce) |
| ZeRO-1 | bytes | bytes |
| ZeRO-2 | bytes | bytes |
| ZeRO-3 | bytes | bytes |
ZeRO-3 Forward and Backward Communication Pattern
The communication pattern of ZeRO-3 deserves careful examination because it is qualitatively different from the simple all-reduce used by DDP. Algorithm sec:distgen:zero:z3-algo traces the operations for a single layer with parameter matrix .
Before each layer's forward pass.
GPU holds shard , a contiguous slice of of 's flattened parameters. An all-gather operation assembles the full on every GPU. This requires communicating bytes (FP16) across all GPUs, with each GPU sending and receiving approximately bytes. After the forward pass, GPUs discard their copies of ; only the local shard is retained.
Before each layer's backward pass.
The same all-gather repeats so that each GPU can compute the gradient correctly.
After each layer's backward pass.
Each GPU has computed a local estimate of . A reduce-scatter aggregates these estimates: GPU accumulates the true gradient shard , the average over all GPUs' local estimates restricted to indices owned by .
Optimizer step.
GPU applies the Adam update to its shards using its local optimizer state shards , . No inter-GPU communication is required for this step.
The total communication per training step is thus: which is the bytes of the DDP all-reduce. Whether this overhead is acceptable depends on the ratio of compute time to communication time. On NVLink-connected clusters, bandwidth is high enough that the overhead is typically small compared with the matrix-multiplication arithmetic. On clusters connected only via Ethernet or InfiniBand at lower bandwidth, ZeRO-3 can become communication-bound, making ZeRO-1 or ZeRO-2 preferable.
Remark 28 (Prefetching to hide latency).
A practical optimisation is to overlap the all-gather for layer with the computation of layer . This prefetching strategy hides the all-gather latency behind arithmetic, provided the communication bandwidth is sufficient. Frameworks such as DeepSpeed implement this automatically, and FSDP (discussed below) exposes it as a tunable parameter. Without prefetching, the GPU stalls waiting for parameters; with prefetching, the communication and computation timelines are nearly perfectly overlapped.
PyTorch FSDP: Fully Sharded Data Parallel
PyTorch's Fully Sharded Data Parallel (FSDP) is the canonical implementation of ZeRO-3 semantics within the PyTorch ecosystem. Introduced in PyTorch 1.11 and substantially matured in subsequent releases, FSDP has become the standard tool for training models that do not fit on a single GPU within the research and production PyTorch community.
Flat Parameter Tensors
FSDP operates at the level of FSDP units: contiguous groups of parameters that are sharded, communicated, and managed together. Typically each Transformer block (attention + feed-forward sublayer) constitutes one FSDP unit, though the granularity is configurable. Within each FSDP unit, all parameters are concatenated into a single flat parameter tensor, which is then divided into equal shards along the outermost dimension. This flattening is essential: it ensures that collective operations (all-gather, reduce-scatter) touch contiguous memory, maximising bandwidth utilisation and minimising the overhead of many small collectives.
Concretely, if an FSDP unit contains parameter tensors of total size , the flat parameter tensor is GPU permanently holds shard .
Sharding, Resharding, and the FSDP Lifecycle
The lifecycle of an FSDP unit during one training step is:
All-gather (before forward): All GPUs contribute their shards; each GPU receives the full flat parameter tensor. The allgather is issued asynchronously and overlapped with the previous unit's computation if prefetching is enabled.
Forward pass: The unit computes its output using the assembled full parameters.
Reshard (after forward): Non-local parameter shards are freed, restoring the per-GPU memory to the shard-only footprint. This is the memory saving: the full parameters exist in GPU memory only briefly during computation.
All-gather (before backward): The full parameters are reassembled for gradient computation.
Backward pass: Gradients with respect to inputs are computed and passed to the preceding unit. Gradients with respect to the unit's own parameters are accumulated locally.
Reduce-scatter (after backward): The local gradient accumulation buffer is reduce-scattered, so each GPU accumulates the gradient shard corresponding to its parameter shard.
Reshard: The assembled full parameters (used during backward) are freed.
Optimizer step: Each GPU updates its parameter shard using its gradient shard and optimizer state shard. No communication is required.
Definition 30 (Fully Sharded Data Parallel (FSDP)).
Let be the set of model parameters, partitioned into FSDP units . For each unit and a cluster of GPUs, FSDP assigns to GPU the parameter shard , the gradient shard, and the optimizer state shard. At any given moment during training, the full parameter tensor for exists in GPU memory only when an all-gather has been issued for it and before the subsequent reshard. The per-GPU memory for model state satisfies , where the term accounts for the temporarily materialized full parameters of the currently active unit.
FSDP Sharding Strategies
FSDP exposes multiple sharding strategies, corresponding to the three ZeRO stages:
NO_SHARD: Equivalent to DDP; parameters are fully replicated. Useful as a correctness baseline.SHARD_GRAD_OP: Equivalent to ZeRO-2; parameters are fully replicated during computation but gradient shards are maintained. Optimizer state is sharded.FULL_SHARD: Full ZeRO-3 behaviour as described above. Parameters, gradients, and optimizer state are all sharded.HYBRID_SHARD: A two-level strategy in which parameters are fully sharded within a sharding group (e.g., GPUs on the same node sharing NVLink) but replicated across sharding groups. This reduces inter-node communication volume while retaining intra-node memory savings.
The hybrid strategy deserves elaboration. In a cluster of nodes each with GPUs, a common topology is NVLink within-node (high bandwidth, 600 GB/s) and InfiniBand or Ethernet across nodes (lower bandwidth, 25–400 GB/s). Performing ZeRO-3 all-gathers across all GPUs saturates the inter-node links. With hybrid sharding, only within-node all-gathers are performed (over NVLink), achieving a memory reduction per GPU. The gradient reduce-scatter and parameter broadcast across nodes use DDP-style all-reduce, which can be overlapped with computation. This trades the full linear memory scaling of ZeRO-3 for a hybrid that better matches the cluster's communication topology.
Key Idea: Memory–Communication Trade-Off in ZeRO
Key Idea.
ZeRO trades communication for memory. Classical data-parallel training (DDP) replicates all model state on every GPU, using bytes per GPU but only bytes of inter-GPU communication per step. ZeRO-3 shards all model state, using only bytes per GPU - a linear reduction - but requires bytes of communication, the DDP baseline. The practical trade-off is governed by the ratio of inter-GPU bandwidth to GPU arithmetic throughput: on high-bandwidth interconnects (NVLink), ZeRO-3 is nearly free in wall-clock time; on low-bandwidth networks, ZeRO-1 or ZeRO-2 may be preferable. The more you shard, the less memory but the more communication.
Worked Example: LLaMA-13B Memory with ZeRO
Example 14 (Memory budgets for LLaMA-13B on 8 GPUs).
Consider training LLaMA-13B ( parameters) in mixed precision on a cluster of A100-80GB GPUs.
Baseline (DDP, no sharding). This exceeds the 80 GB of a single A100. Training is not feasible.
ZeRO-1 (optimizer state sharded). This fits within an 80 GB A100, though with little headroom for activations.
ZeRO-3 (all state sharded). This leaves 54 GB of headroom for activations, enabling large batch sizes and long sequence lengths that would be impossible with ZeRO-1.
Memory for activations (approximate). For a transformer with hidden dimension , sequence length , and batch size , the activation memory per layer is approximately bytes MB per layer. LLaMA-13B has 40 layers, so activations occupy approximately GB without checkpointing. ZeRO-3 accommodates this comfortably.
ZeRO-Infinity: Offloading to CPU and NVMe
ZeRO-Infinity extends the partitioning principle beyond GPU memory to encompass CPU DRAM and NVMe SSDs. The motivation is that a modern training node may have 1–2 TB of DRAM and tens of terabytes of NVMe storage, both dwarfing GPU memory. ZeRO-Infinity partitions optimizer state and parameters across this three-level hierarchy: GPU HBM for active computation, CPU DRAM for the larger optimizer state, and NVMe for cold parameters.
The key engineering challenge is bandwidth. PCIe bandwidth between GPU and CPU DRAM is 32–64 GB/s - fast but not as fast as NVLink. NVMe SSD sequential read bandwidth is 3–7 GB/s. To avoid making computation GPU-stall on NVMe reads, ZeRO-Infinity uses aggressive prefetching: while layer is computing, the parameters for layer are being fetched from CPU or NVMe into a GPU prefetch buffer. The prefetch pipeline is designed so that the NVMe read completes before the GPU needs the data.
ZeRO-Infinity introduces the concept of infinity offload engine, a software-managed pipeline that issues asynchronous reads and writes across the memory hierarchy, interleaving them with GPU computation to maximise utilisation. The result is that models with hundreds of billions of parameters can be trained on commodity hardware - at the cost of significantly reduced throughput relative to NVLink-connected GPU clusters where all state fits in HBM.
Exercises
Exercise 41 (ZeRO memory calculation).
A model with parameters (70B) is trained in mixed precision using Adam on a cluster of A100-80GB GPUs using ZeRO-3.
Compute the per-GPU model-state memory under ZeRO-3.
What is the smallest such that the per-GPU model-state memory is below 80 GB?
If the same cluster were limited to ZeRO-1, what is the per-GPU model-state memory for GPUs? Does it fit in 80 GB?
Exercise 42 (Communication volume analysis).
Suppose inter-GPU bandwidth is GB/s (NVLink) and GPU compute throughput is TFLOPS (BF16). A training step processes a batch that requires FLOPs.
For a 70B model ( parameters) with ZeRO-3, compute the total communication volume per training step in bytes.
Compute the communication time at GB/s and the compute time at TFLOPS.
Under what condition (in terms of , , , and ) is ZeRO-3 communication-bound rather than compute-bound? Derive the inequality.
Exercise 43 (FSDP hybrid sharding design).
You are designing a training cluster for a 30B-parameter model. The cluster has 16 nodes, each with 8 A100-80GB GPUs connected via NVLink ( GB/s). Nodes are connected via InfiniBand HDR ( GB/s aggregate).
Compute the per-GPU memory under full ZeRO-3 across all GPUs.
Compute the per-GPU memory under FSDP hybrid sharding (ZeRO-3 within each node of 8 GPUs, DDP across nodes).
For each configuration, estimate the communication time per training step, assuming the dominant cost is the parameter all-gather. Which configuration has lower inter-node traffic?
Discuss when hybrid sharding is preferable to full ZeRO-3.
Activation Checkpointing and Mixed Precision Training
Sections ZeRO: Zero Redundancy Optimizer through the preceding material have focused on reducing the memory consumed by model parameters, gradients, and optimizer state. These are static costs: they depend only on the number of parameters and the optimizer choice, not on the batch size or sequence length. But there is a second, equally important class of memory consumer that grows with the size of each training batch: activation memory.
Understanding and controlling activation memory is essential for training large models with meaningful batch sizes. A 70-billion-parameter transformer model with 80 layers, hidden dimension 8192, and a batch of 4 sequences of length 2048 produces intermediate activations totalling over 100 GB. This is before any model-state memory. Even with ZeRO-3 reducing model-state to a fraction of a single GPU's capacity, activations can make training infeasible.
This section develops two complementary techniques for managing this memory burden. Activation checkpointing (also called gradient checkpointing) trades computation for memory: rather than storing all activations for backpropagation, only a selected subset is retained, and the rest are recomputed on demand. Mixed precision training uses lower-precision arithmetic (FP16 or BF16) for most operations, reducing both memory and arithmetic cost, while maintaining a higher-precision master copy for numerical stability. Together, these techniques form the practical bedrock of large-model training.
Activation Memory: Where Does It Come From?
To compute gradients via backpropagation, the chain rule requires intermediate values computed during the forward pass. Specifically, for a layer with parameters , the gradient with respect to depends on the input activation to that layer. If is not stored, it must be recomputed from (or from the network input).
For a standard transformer layer with:
batch size ,
sequence length ,
hidden dimension ,
number of attention heads ,
the activations that must be stored for backpropagation include:
The input to the layer: values.
The query, key, and value projections: values.
The attention scores (pre-softmax): values.
The attention weights (post-softmax): values.
The attention output before projection: values.
Feed-forward network intermediates: values (for the standard 4 expansion ratio).
LayerNorm statistics: values (mean and variance).
Summing these (and counting at 2 bytes per value in FP16): For , , , (a 70B-scale model): With 80 layers, total activation memory is approximately . This exceeds the GPU memory of an entire node of 8 A100s.
Remark 29 (Activation memory dominates at long context).
The term in the activation formula shows that attention score memory grows quadratically with sequence length. For (a common modern context length), this term is 16 larger than for . At (increasingly common in recent models), it is 256 larger. This quadratic growth is one of the primary motivations for flash attention - an attention algorithm that avoids materialising the full attention matrix by computing attention block by block and is the primary strategy for long-context activation memory reduction.
Activation Checkpointing
Activation checkpointing (also called gradient checkpointing or rematerialisation) addresses the activation memory problem by discarding most activation tensors after the forward pass and recomputing them during backpropagation. The forward pass is re-executed for the discarded segments just before the backward pass requires them.
Definition 31 (Activation Checkpointing).
Let be a -layer neural network with input and layer outputs . Let be the checkpoint set. Activation checkpointing stores only after the forward pass. During the backward pass, to compute gradients at layer requiring , the sub-network is re-executed from the most recent checkpoint (where ) to reconstruct .
The simplest instance of activation checkpointing is full checkpointing at uniform intervals: set for some interval . Between consecutive checkpoints, no activations are stored during the forward pass; they are recomputed on demand during backpropagation.
Memory reduction.
With uniform checkpointing every layers, the maximum activation memory is: Instead of for no checkpointing, we need only - a factor of reduction. For , (checkpoint every layer), memory reduces to , a factor of 80 reduction.
Compute overhead.
The recomputed segments are executed once during the forward pass (for the original computation) and once again during the backward pass (for rematerialisation). The total number of forward-pass executions is thus at most rather than , giving an overhead of at most additional forward computation. In practice, because the backward pass is already the compute of the forward pass (computing two Jacobian-vector products per layer), the overhead of full rematerialisation is approximately of total training compute.
Remark 30 (The optimal checkpoint strategy).
With checkpoints, the optimal strategy minimises the sum of memory and recomputation. For the simplest case of uniform checkpointing, the optimal interval is , yielding memory and compute overhead additional layers. This is the Griewank–Walther optimal rematerialisation result. The general case with non-uniform layer costs has been studied extensively and admits dynamic-programming solutions, but the heuristic is widely used in practice because it requires no profiling.
Selective Checkpointing
Full activation checkpointing at every layer incurs the full compute overhead. Selective checkpointing is a pragmatic refinement: checkpoint only the expensive layers whose activations are large, and keep the cheap layers' activations in memory.
The classification is based on the compute-to-memory ratio of each layer's activations. Layers with a high ratio (large activations, low recomputation cost) are better candidates for checkpointing than layers with a low ratio (small activations, high recomputation cost).
Concretely, for a transformer layer:
Attention score matrix (): large (especially at long context) but recomputable by re-executing the QK product. Good candidate for checkpointing.
Feed-forward intermediates (): large but inexpensive to recompute (one GEMM). Moderate candidate.
LayerNorm inputs and outputs (): small, and required by the backward pass normalisation formula. Poor candidate for checkpointing - keep in memory.
A common selective strategy in production training frameworks checkpoints only the attention softmax output (discarding the attention weight matrix after each head's computation) and the feed-forward intermediate, while retaining LayerNorm activations. This achieves approximately 60% of the activation memory reduction of full checkpointing at only 10–15% compute overhead, rather than the 33% of full checkpointing.
Proposition 10 (Selective checkpointing trade-off).
Let be transformer layers with layer producing activations of size and requiring recomputation time . Let be the set of layers selected for checkpointing. The total memory savings and compute overhead satisfy: The optimal selection maximises subject to for a given compute budget , which is a variant of the fractional knapsack problem solvable in time by sorting layers by and greedily selecting those with the highest ratio.
Mixed Precision Training
Mixed precision training uses lower-precision arithmetic for the bulk of computation while maintaining higher-precision master copies for numerical stability. The result is a training procedure that is both faster (lower-precision matrix multiplications have higher hardware throughput) and more memory-efficient (lower-precision tensors occupy fewer bytes).
Definition 32 (Mixed Precision Training).
Mixed precision training is a training procedure that maintains:
A working copy of parameters in half precision (FP16 or BF16, 2 bytes each) used for the forward and backward passes.
A master copy of parameters in full precision (FP32, 4 bytes each) used for the optimizer update step.
Optimizer state (Adam first and second moments) in FP32.
Gradients computed in half precision during backpropagation and optionally scaled (see loss scaling below) before the optimizer step.
Formally, at each step : where and denote precision casting operations.
Loss Scaling for FP16 Training
FP16 arithmetic has a dynamic range spanning approximately . Gradients in deep networks are often very small in magnitude, especially in early training or in layers close to the input. If a gradient value falls below , it is flushed to zero - underflow - and that gradient signal is permanently lost. This silently corrupts training.
Loss scaling prevents underflow by multiplying the loss by a large scalar before backpropagation. By the chain rule, all gradients are scaled by , shifting them into the FP16 representable range. Before the optimizer step, gradients are divided by to restore their true values.
Algorithm 6 (Dynamic Loss Scaling).
Initialise scale (e.g., ).
For each training step: enumerate
Compute loss in FP32.
Scale: .
Backward: compute in FP16.
Check for overflow: if any element of is or NaN, skip the optimizer step and halve : .
Otherwise: unscale , apply optimizer step with .
Every steps without overflow, double : . enumerate
Dynamic loss scaling adapts automatically: it grows when gradients are small (no overflow occurs) and shrinks when gradients overflow, maintaining the scale in the optimal range.
BF16 vs FP16: Format Comparison
BF16 (Brain Floating Point 16) is an alternative 16-bit format that differs from FP16 in its allocation of bits:
| Format | Sign bits | Exponent bits | Mantissa bits |
| FP32 | 1 | 8 | 23 |
| BF16 | 1 | 8 | 7 |
| FP16 | 1 | 5 | 10 |
The critical difference is the number of exponent bits. FP32 and BF16 share 8 exponent bits, giving them the same dynamic range ( to ). FP16 has only 5 exponent bits, restricting its dynamic range to to . As a consequence:
BF16 does not require loss scaling. Gradient magnitudes that would underflow in FP16 are representable in BF16 because BF16 shares FP32's exponent range. This eliminates a significant source of implementation complexity.
BF16 has lower precision (fewer mantissa bits). With only 7 mantissa bits, BF16 represents values with relative error up to , versus for FP16. In practice, the precision of BF16 is sufficient for deep learning training, where stochastic gradient noise dominates numerical round-off.
Hardware support: BF16 is natively supported on Google TPUs (where it was introduced) and on NVIDIA A100/H100 GPUs. It is the preferred format for large-model training on modern hardware.
Remark 31 (BF16 is the practical default).
For training on A100 or H100 GPUs, BF16 is almost universally preferred over FP16 because it eliminates loss scaling, avoids underflow issues at no cost in training stability, and achieves comparable throughput. The reduced mantissa precision of BF16 has not been found to harm model quality in any published large-scale experiment. FP16 training with dynamic loss scaling remains common on older hardware (V100) that does not support BF16.
FP8 Training: The Next Frontier
FP8 (8-bit floating point) is an emerging training format supported by NVIDIA H100 and B200 GPUs. There are two FP8 variants:
E4M3: 1 sign bit, 4 exponent bits, 3 mantissa bits. Suitable for weights and activations (forward pass).
E5M2: 1 sign bit, 5 exponent bits, 2 mantissa bits. Wider dynamic range; preferred for gradients (backward pass).
FP8 arithmetic is supported in the tensor cores of H100 and B200, with theoretical throughput approximately that of BF16. The memory footprint of FP8 tensors is 1 byte per value, versus 2 bytes for BF16, potentially halving both activation and working-copy-parameter memory.
However, FP8 training introduces significant challenges:
Per-tensor scaling: With only 8 bits, the dynamic range per tensor is very limited. Each tensor requires an individual scale factor calibrated to its dynamic range. Computing, maintaining, and applying these scale factors adds implementation complexity comparable to dynamic loss scaling.
Gradient precision: Gradient tensors span a wider dynamic range than weight tensors and are more sensitive to quantisation error. E5M2 is preferred for gradients, but even so, some training instabilities have been observed at very small learning rates where gradient magnitudes approach the E5M2 precision floor.
Accumulation in higher precision: Tensor core matrix multiplications in FP8 typically accumulate results in FP32 or FP16. The accumulation precision must be chosen carefully: too low and numerical errors compound; too high and the memory and compute advantage of FP8 is diminished.
Despite these challenges, FP8 training has been demonstrated at scale by several industrial groups, achieving training quality matching BF16 baselines on language models up to 70B parameters with wall-clock speedup (after accounting for scaling overhead).
Mixed Precision Training Flow
Communication Optimisation with Mixed Precision
Mixed precision training has a direct benefit for distributed communication beyond the per-GPU memory savings. In data-parallel training, the dominant communication primitive is the all-reduce of gradients. If gradients are communicated in BF16 (2 bytes per parameter) rather than FP32 (4 bytes per parameter), the communication volume is halved, directly translating to higher effective bandwidth for the all-reduce.
Most modern training frameworks communicate gradients in BF16 by default. The accumulated FP32 gradient (after casting from BF16) is used only for the optimizer step, which is a purely local operation. The BF16 communication introduces a small quantisation error, but this is consistently found to be negligible relative to the stochastic gradient noise from mini-batch sampling.
For ZeRO-3, the same principle applies to the all-gather of parameters (communicated in FP16/BF16, 2 bytes) and the reduce-scatter of gradients (2 bytes), further amplifying the bandwidth savings at scale.
Activation Compression
A complementary technique to activation checkpointing is activation compression: quantising the stored activation tensors to lower precision before storing them, thereby reducing their memory footprint without requiring recomputation.
The most common approach is to quantise activation tensors from FP16 or BF16 to INT8 (1 byte per value), halving the activation memory. Quantisation is applied per-channel or per-tensor, with scale factors stored in FP32. During the backward pass, activations are dequantised before use.
More aggressive approaches use INT4 (4 bits per value) or even 2 bits, but these introduce significant quantisation error that can affect gradient accuracy and thus training stability. INT8 activation compression is generally considered safe for full-precision-quality training, while INT4 and below require careful tuning.
Activation compression and activation checkpointing are complementary: checkpointing stores fewer tensors; compression makes each stored tensor smaller. In production systems, both are applied simultaneously to maximise the memory budget available for batch size.
Memory Optimisation Technique Comparison
Table tab:distgen:mem-opt summarises the memory optimisation techniques discussed in this section and the preceding one.
| p2.5cmp2.2cmp4.2cm Technique | Memory | Compute | Notes |
| Reduction | Overhead | ||
| ZeRO-1 | Up to (opt. state) | comm. | Shards optimizer state only; minimal overhead |
| [4pt] ZeRO-2 | Up to (opt. + grads) | comm. | Also shards gradients; same comm. as ZeRO-1 |
| [4pt] ZeRO-3 / FSDP | Up to (all state) | comm. | Full linear memory scaling; best for very large models |
| [4pt] ZeRO-Infinity | Beyond GPU HBM | latency | Offloads to CPU/NVMe; low throughput |
| [4pt] Activation Ckpt. (full) | activation memory | FLOPs | Recomputes all activations; significant overhead |
| [4pt] Activation Ckpt. (selective) | activation memory | FLOPs | Checkpoints only high-memory layers |
| [4pt] Activation Compression (INT8) | activation memory | overhead | Quantise stored tensors; minimal accuracy impact |
| [4pt] Mixed Precision (BF16) | param memory | Neutral to speed | No loss scaling; best on A100/H100 |
| [4pt] Mixed Precision (FP16) | param memory | overhead | Requires dynamic loss scaling; older hardware |
| [4pt] FP8 Training | param memory | speed | Emerging; requires per-tensor scaling; H100/B200 |
| [4pt] |
Complete Memory Budget: Training a 70B LLM
Example 15 (Complete memory budget for a 70B LLM).
We compute the complete per-GPU memory budget for training a 70-billion-parameter language model on a cluster of A100-80GB GPUs, using ZeRO-3 (via FSDP), BF16 mixed precision, and selective activation checkpointing.
Model architecture.
Following LLaMA-70B: transformer layers, hidden dimension , number of attention heads , feedforward expansion ratio 4. Total parameters . Training: batch size sequences, sequence length .
Model state (ZeRO-3).
This comprises GB of parameters (FP16), GB of gradients (FP16), and GB of optimizer state (FP32 Adam).
Activations (with selective checkpointing).
Without checkpointing: With selective checkpointing (checkpointing attention scores and FFN intermediates, retaining LayerNorm activations): With full activation checkpointing (one checkpoint per layer): We use selective checkpointing for this budget: GB.
Total per-GPU memory.
This exceeds 80 GB. Switching to full activation checkpointing: Full activation checkpointing fits comfortably in 80 GB, leaving 57 GB of headroom. The overhead is compute (an additional forward pass per backward).
Alternative: larger batch with selective checkpointing.
If we instead use batch size (reducing activations by ): This fits in 80 GB with GB headroom and no compute overhead from full checkpointing. The trade-off is that smaller batch sizes often lead to noisier gradient estimates and may require more training steps to reach the same loss.
Summary.
For a 70B LLM on 64A100-80GB with ZeRO-3 + BF16:
Full activation checkpointing: 22.9 GB per GPU, compute.
Selective checkpointing with : 39.7 GB per GPU, compute.
No checkpointing with : 289 GB per GPU - infeasible.
The practical configuration for most production training is selective checkpointing at reduced batch size, trading some gradient noise for a manageable compute overhead.
Insight: Mixed Precision Is Free Performance
Insight.
Mixed precision training in BF16 is, for practical purposes, free performance. It halves the memory occupied by parameter working copies and gradient tensors (from 4 bytes to 2 bytes per value), doubles the arithmetic throughput on modern hardware tensor cores (which have dedicated BF16/FP16 matrix-multiplication units), and halves the communication volume for gradient all-reduces. The numerical quality is indistinguishable from FP32 training in every published study on large language models. The master weights (FP32, updated by the optimizer) ensure that small gradient updates are not lost to round-off. There is no reason not to use BF16 training on A100 or H100 hardware. The same results, half the memory, and effectively double the speed - a rare trifecta in engineering trade-offs.
Exercises
Exercise 44 (Activation memory calculation).
Consider a transformer model with 40 layers, hidden dimension , 32 attention heads, trained with batch size and sequence length .
Compute the activation memory per layer (in GB, at FP16).
Compute the total activation memory without checkpointing.
With full activation checkpointing (one checkpoint per layer), what is the activation memory? What is the compute overhead?
With the optimal strategy (checkpoint every layers), what is the activation memory? What is the worst-case recomputation (in layers)?
Exercise 45 (Mixed precision numerical analysis).
A parameter has value and receives a gradient update (learning rate , gradient ).
In FP32, what is ? Is the result representable exactly?
In FP16 (machine epsilon relative to the magnitude of the result), what is ? Is the update preserved? Explain what happens if .
With loss scaling , the gradient becomes . In FP16, compute . Does the update survive?
Why does BF16 avoid this problem without loss scaling? Compute the relative precision of BF16 and FP32 to support your answer.
Exercise 46 (Complete training system design).
You are tasked with training a 13B-parameter transformer on a budget of 16 A100-40GB GPUs (note: 40 GB, not 80 GB). The model has 40 layers, , 40 attention heads. You plan to use BF16 mixed precision and Adam.
Compute the model-state memory per GPU under ZeRO-3 with . Does it fit in 40 GB?
For batch size , sequence length , compute the per-layer activation memory.
What is the maximum total activation memory that fits in the remaining 40 GB budget (after model state)? How many layers can you store activations for without any checkpointing?
Design a checkpointing strategy (specify , the checkpoint set, in terms of layer indices) that fits within 40 GB while minimising compute overhead. What is the compute overhead of your strategy?
If you additionally apply INT8 activation compression to the stored checkpoints, by how much does this reduce the activation memory? Does this allow you to reduce the compute overhead of checkpointing?
Distributed Training of Diffusion Models
There is a peculiar irony at the heart of diffusion model training. The models that have come to define the popular imagination of generative AI - systems that produce photorealistic faces, coherent video, and intricate artwork from a few words of text - are in one sense the most natural candidates for distribution across many machines. And yet, for most of the short history of large-scale diffusion training, practitioners treated them like large language models with the serial dimension removed: they replicated the model, split the data, and hoped that synchronising gradients once per step would be enough. It usually was. But as model sizes grew from hundreds of millions to tens of billions of parameters, and as the research community began experimenting with DiT-XL, Stable Diffusion XL, and their successors, the implicit assumption that data parallelism alone could carry the load began to crack.
This section develops the systems-level understanding of what makes diffusion training different from language model training, why the distinction matters for distributed systems design, and what the state of the art looks like when all available parallelism strategies are deployed together. We begin with the fundamental differences in computation graph structure, work through the architectural innovation that made DiTs the dominant backbone, and end with a concrete design exercise for a production-scale distributed training run.
How Diffusion Training Differs from Language Model Training
Large language models are, at their core, autoregressive sequence models. Every forward pass produces a prediction for token conditioned on tokens . This imposes a causal dependency that propagates through the computation graph: the output at position depends on all previous outputs, and pipeline parallelism must be arranged to respect this dependency, splitting the model depth-wise while maintaining the temporal ordering of activations. The result is that distributing an LLM across many machines requires careful choreography of micro-batches: the pipeline must be kept occupied, but the causal mask means that each micro-batch flows through the pipeline in strict order.
Diffusion models have no such constraint. The training objective for a denoising diffusion probabilistic model (DDPM) is to predict the noise added to a clean datum at a randomly sampled noise level : (DDPM LOSS) where is the noised sample and is the cumulative noise schedule. The key observation is that each sample contributes independently to the expectation in (DDPM LOSS). There is no causal structure coupling one sample to the next. This is the foundational insight that makes diffusion training embarrassingly parallel across samples: any partition of the data into disjoint subsets yields an unbiased gradient estimate, with no communication required between workers until the gradient synchronisation step.
Remark 32 (Many Steps vs. One Step).
The absence of autoregressive dependency does not mean diffusion training is computationally cheaper than LLM training per epoch. A standard training configuration samples a different timestep for each example in each mini-batch, but across an epoch of training, the model sees examples at all noise levels from to (with a common setting). This means the effective number of gradient computations per training image is times larger than for a single-pass discriminative model. The parallelism benefit is real, but so is the computational cost.
The practical consequence for system design is that the dominant bottleneck in distributed diffusion training shifts from dependency management (which dominates in LLM pipelines) to memory per sample. High-resolution image diffusion operates in pixel space or a closely related latent space, and the U-Net or transformer backbone must maintain activations at multiple spatial resolutions during the forward pass. A single training step for a 512512 image with a large U-Net can require upward of 20,GB of activation memory, before considering the parameter and optimizer state tensors.
Latent Diffusion: Compress First, Then Distribute
The most practically impactful systems innovation in diffusion model scaling was not a parallelism strategy. It was a change of representation. Latent Diffusion Models (LDMs), as introduced in the Stable Diffusion lineage, operate not in pixel space but in the compressed latent space of a separately trained variational autoencoder.
The architecture has two stages. In the first stage, a VAE with encoder and decoder is trained to compress images from into a compact latent tensor , where typically , , and . The spatial compression factor of in each dimension reduces the number of spatial positions by a factor of 64. In the second stage, the diffusion process is trained entirely in this latent space: the noising and denoising operate on rather than on .
Key Idea.
Compress first, then distribute. Operating in a lower-dimensional latent space does not merely reduce compute and memory per training step - it transforms the shape of the distributed training problem. A reduction in spatial positions shrinks activation tensors, reduces the cost of attention over spatial positions, and makes it feasible to fit a much larger batch per device. The frozen VAE encoder becomes a free pre-processor that each worker can run independently before the denoising network sees the data. Distribution becomes tractable precisely because the heavy lifting of spatial compression has already been done.
From a systems perspective, the frozen VAE encoder has a particularly appealing property: because it requires no gradient updates, its forward pass during training is inference-only. Each worker can run the encoder locally, cache the resulting latent representations, and never communicate encoder activations across the interconnect. This is a significant saving: for a 512512 image, the pixel-space activation tensor transmitted per sample is (in float32), while the latent tensor is - a factor of smaller. In practice, training pipelines precompute and cache latent tensors on disk before the distributed training run begins, so the encoder does not even execute during training.
Remark 33 (Text Conditioning and the Frozen Text Encoder).
Latent diffusion models conditioned on text typically use a frozen CLIP or T5 text encoder to convert the text prompt into a sequence of conditioning vectors . Like the VAE encoder, the text encoder requires no gradient and can be run independently on each worker. The resulting conditioning vectors are small (a 77-token CLIP encoding at occupies ) and do not create significant communication pressure.
DiT: Diffusion Transformers Enable LLM-Style Parallelism
The U-Net architecture that dominated early diffusion models is a convolutional encoder-decoder with skip connections at matched resolution levels. It is highly effective, but its convolutional structure makes tensor and pipeline parallelism awkward to apply: the skip connections create long-range data dependencies across the computational graph, and the varying spatial resolution at each level means that partitioning the spatial dimension cleanly requires careful engineering.
The Diffusion Transformer (DiT), introduced by Peebles and Xie, replaces the U-Net backbone with a standard vision transformer operating on a sequence of non-overlapping image patches. After the VAE encoder produces a latent , the DiT patchifies it into a sequence of tokens of dimension , where is the patch size. This sequence is processed by a stack of transformer blocks, each consisting of a multi-head self-attention layer (conditioned on timestep and class/text embeddings via adaptive layer norm) and a position-wise feed-forward network. The output tokens are unpatchified to produce the predicted noise .
Remark 34 (Why Transformers Unlock Parallelism).
The transformer backbone enables the same parallelism strategies developed for LLMs to be applied directly to diffusion models. Tensor parallelism partitions the attention heads and MLP rows/columns across devices. Pipeline parallelism stacks the transformer layers across stages. Sequence parallelism distributes the token sequence across devices. None of these requires special handling of skip connections or multi-scale spatial representations. The DiT architecture therefore inherits an entire ecosystem of distributed training infrastructure developed for language models, with minimal modification.
Data Parallel Diffusion Training
The simplest distributed strategy for diffusion training is data parallelism: each of workers holds a full replica of the model parameters , processes a distinct shard of the mini-batch, computes the local gradient , and participates in an all-reduce to obtain the synchronised gradient: (Allreduce GRAD) For diffusion models, this strategy is particularly clean. Because samples at different noise levels are independent (recall (DDPM LOSS)), there is no dependency between workers during the forward or backward pass. Each worker can sample its own noise levels, apply them to its local data shard, compute the denoising loss, and backpropagate, all without any communication. The single communication event per step is the all-reduce of gradients, which can be overlapped with the backward pass using standard techniques such as bucketed ring-AllReduce.
The effective batch size under data parallelism is . For diffusion models, large batch sizes are generally well-tolerated: the loss landscape of denoising score matching is relatively smooth, and linear learning rate scaling () is effective up to batch sizes of several thousand samples, beyond which learning rate warmup and square-root scaling may be needed. SDXL was trained on 256 A100 GPUs using exactly this strategy, with data parallelism and gradient accumulation over multiple micro-batches to reach an effective batch size of images.
Tensor Parallel DiT
When the model is too large to fit on a single device, tensor parallelism becomes necessary. For a DiT block with multi-head attention and MLP, the partition follows the standard Megatron-LM approach.
Let be the number of attention heads, the hidden dimension, and the number of GPUs in the tensor parallel group. The attention heads are partitioned such that each GPU holds heads, processing its shard of the query, key, and value projections independently. Concretely, the projection matrices are split column-wise: (Tensor Parallel ATTN) Each GPU computes attention for its heads locally, then the output projection is split row-wise and followed by an all-reduce to combine the partial sums: (Tensor Parallel Output) where is the local attention output on GPU . The MLP is handled analogously: the first linear layer is column-partitioned across GPUs, the GeLU activation is applied locally, and the second linear layer is row-partitioned with an all-reduce at the end. This results in exactly two all-reduce operations per transformer block: one after the attention output projection and one after the MLP output projection.
DiffusionPipe: Pipeline Parallelism for Diffusion Models
Pipeline parallelism stages the model depth-wise across GPUs, with each GPU holding a contiguous subset of the transformer layers. The challenge is the pipeline bubble: when the first stage finishes its forward pass on micro-batch and begins processing micro-batch , the last stage has not yet produced a gradient for micro-batch , leaving intermediate stages idle. In the 1F1B (one-forward-one-backward) schedule, the bubble fraction is where is the number of pipeline stages, meaning that for stages, 25% of GPU cycles are wasted.
DiffusionPipe exploits a structural property of diffusion training to fill these bubbles. The frozen components of the diffusion stack - the VAE encoder and the text encoder - are placed on early pipeline stages. Because these components require no backward pass (their parameters are frozen), their forward passes are pure inference. When the gradient-bearing portion of the pipeline is in its backward pass, the frozen stages can begin processing the next batch immediately, since they have no backward-pass obligation.
The throughput gain from bubble filling is quantified as follows. In a standard 1F1B pipeline with stages and micro-batches, the total time is approximately where is the time per micro-batch per stage. In DiffusionPipe, the frozen stages contribute no backward time, so the effective for the backward pass is where is the number of frozen stages. Empirical results from the DiffusionPipe authors report a throughput improvement of up to on 4-GPU pipeline configurations with one frozen stage.
Definition 33 (Hybrid Parallelism for Diffusion Models).
Let be a factorisation of the total number of GPUs into a data-parallel group of size , a tensor-parallel group of size , and a pipeline-parallel group of size . A hybrid parallelism strategy for diffusion training assigns each GPU a unique index with , , , such that:
GPUs sharing the same index form a tensor-parallel group and partition the model width (attention heads and MLP columns) evenly.
GPUs sharing the same index form a pipeline-parallel group and partition the model depth (layers) into contiguous stages.
GPUs sharing the same index form a data-parallel group and process disjoint mini-batch shards, synchronising gradients via all-reduce at the end of each step.
The effective global batch size is , and the communication volume per step scales as for the all-reduce (since tensor parallelism reduces the per-GPU parameter count) plus for the activation transfers across pipeline boundaries, where is the activation tensor size at the inter-stage interface.
Open-Source and Production Frameworks
OpenDiT.
OpenDiT is an open-source framework built on top of PyTorch and Colossal-AI that provides a reference implementation of distributed DiT training with all three parallelism axes. It includes pre-built pipeline schedule implementations for DiT-XL, support for sequence parallelism via ring-attention for very long token sequences, and utilities for converting between data-parallel checkpoints and tensor-parallel shards. The framework is particularly notable for its treatment of the classifier-free guidance (CFG) training pass: both the conditional and unconditional forward passes are batched together within each worker, so the communication pattern per step remains a single all-reduce regardless of whether CFG is enabled.
NeMo Diffusion.
NVIDIA's NeMo framework extended its LLM training infrastructure to support diffusion models by treating the DiT backbone as a standard transformer compatible with Megatron-LM's tensor and pipeline parallelism. NeMo Diffusion adds diffusion-specific components including the adaptive layer-norm (adaLN) timestep conditioning, VAE-based latent encoding, and classifier-free guidance handling, while reusing the battle-tested communication kernels (NCCL-based ring-AllReduce, point-to-point activation buffers) from the LLM training side. Production training runs at NVIDIA for large text-to-image models use NeMo with (tensor parallelism across 8 GPUs) and scaled to the available cluster size.
Example: Designing a Distributed Training Plan for a 6.5B DiT
Example 16 (Distributed Training Plan for a 6.5B DiT Model).
Consider a DiT-XL variant with 6.5 billion parameters. The model has 48 transformer layers, hidden dimension , and attention heads. Each parameter occupies 2 bytes in bfloat16, so the model weights alone occupy . The Adam optimizer states (first and second moment, maintained in float32) add a further . The total parameter + optimizer memory requirement is approximately , far exceeding the 80,GB capacity of a single A100.
We design the following hybrid strategy on a cluster of A100 GPUs ():
: tensor parallelism across 4 GPUs. Each GPU holds attention heads and the corresponding MLP columns. The per-GPU parameter count is reduced to parameters ( in bfloat16), and the optimizer states to . Total per-GPU memory for model + optimizer: .
: pipeline parallelism across 4 pipeline stages, with 12 DiT layers per stage. The first stage additionally holds the frozen VAE and text encoders ( combined).
: 16-way data parallelism. With images per GPU, the effective batch size is images.
The per-step communication consists of: (i) two all-reduce operations per DiT block (attention and MLP outputs) within the tensor-parallel group, using NVLink at ; (ii) point-to-point activation transfers at pipeline boundaries (each latent activation tensor ) over InfiniBand; (iii) one gradient all-reduce across the data-parallel group per training step, amortised across micro-batches by the 1F1B schedule.
The frozen stage on the first pipeline GPU handles the VAE and text encoder, enabling DiffusionPipe-style bubble filling for an estimated throughput improvement.
At a throughput of training steps per second on this configuration, training 1 million steps (a common target for production-quality models) requires approximately 23 hours of cluster time.
Key Idea.
Diffusion models are embarrassingly parallel across noise samples. Because the denoising score matching objective decomposes as an expectation over independently drawn samples, there is no inter-sample dependency during the forward or backward pass. This makes data parallelism the natural first choice, and it means that scaling the number of data-parallel workers linearly increases throughput with no correctness penalty, provided only that the all-reduce of gradients is performed before the parameter update. Distribution is not merely possible for diffusion models; it is structurally natural.
Exercises
Exercise 47 (Memory analysis for tensor-parallel DiT).
A DiT-XXL model has 3 billion parameters, hidden dimension , 32 attention heads, and 24 transformer layers. You have access to 8 GPUs each with 40,GB of memory. (a) Compute the memory required for model parameters and Adam optimizer states in float32. (b) Determine the minimum tensor-parallel degree such that the model and optimizer states fit within the per-GPU memory budget, assuming perfect partitioning. (c) With the chosen , compute the number of additional all-reduce operations per forward pass compared to a data-parallel baseline, and estimate the communication overhead assuming NVLink bandwidth of and an activation tensor width of .
Exercise 48 (DiffusionPipe bubble analysis).
Consider a DiffusionPipe setup with pipeline stages, of which the first 2 stages hold frozen components (VAE encoder and two-stage text encoder). The time per forward micro-batch is and the time per backward micro-batch on a trainable stage is . (a) Compute the pipeline bubble fraction under the standard 1F1B schedule, treating all stages as trainable. (b) Show how the bubble fraction changes when the frozen stages are used to process the next mini-batch during the backward pass of the current mini-batch. (c) What is the effective throughput improvement (ratio of useful-compute time to total clock time) in each case?
Exercise 49 (Designing parallelism for a 20B DiT).
You are given 512 H100 GPUs (80,GB each) and asked to train a 20B DiT model with 64 transformer layers, hidden dimension , and 64 attention heads. (a) Formulate the hybrid parallelism problem as an integer program: minimise total communication volume (all-reduce + pipeline boundary transfers) subject to the constraint that per-GPU memory usage is at most 75,GB. (b) Identify the Pareto-optimal configurations in the space with . (c) Explain qualitatively how your choice would change if the cluster interconnect were Ethernet at rather than InfiniBand HDR at .
Communication Patterns in Diffusion Training
Every gradient synchronisation in a data-parallel training run is a moment of vulnerability. Hundreds of GPUs that have been computing in isolation must suddenly agree on the same parameter update, transferring potentially tens of gigabytes of gradient data across a shared interconnect before any GPU can advance to the next step. In language model training, this is expensive but predictable: there is one all-reduce per forward-backward pass, and its cost is well understood.
In diffusion training, the picture is superficially similar but structurally richer. The score matching loss ((DDPM LOSS)) induces one all-reduce per training step, identical in form to the LLM case. But the semantics of a “step” in diffusion training are different, and the choices available to the practitioner - how to accumulate gradients, when to synchronise, and how to exploit the special structure of the score function - are qualitatively distinct from the LLM setting. This section develops a precise account of those differences and their consequences for communication-efficient distributed diffusion training.
Score Matching Loss and Natural Data Parallelism
The denoising score matching objective can be written as a double expectation: (DSM Expectation) where is a timestep weighting function (often constant, but sometimes chosen to upweight noisy timesteps where the model has higher loss variance). The key property of (DSM Expectation) is that the integrand decomposes as a product of independent random variables: the sample drawn from the data distribution, the noise drawn from the standard normal, and the timestep drawn from the uniform distribution are all independent. This means the full gradient can be estimated by independently sampling each factor on separate workers and averaging the resulting gradient estimates. The estimator is unbiased by the linearity of expectation, and its variance decreases as where is the total number of samples across all workers.
Remark 35 (Communication per Step).
Under data parallelism with workers, each processing a local mini-batch of size , the communication cost per training step is exactly one all-reduce over the full parameter vector . Using ring-AllReduce, this costs bytes of data transmitted per GPU, independent of . For a 3B parameter DiT in bfloat16, this is per worker per step. This is the same order as LLM training; the number of synchronisation events per epoch, however, is different because diffusion training “sees” each training image multiple times at different noise levels within a single epoch, effectively increasing the number of gradient updates relative to the number of distinct training images.
Gradient Accumulation over Denoising Steps
A distinctive feature of diffusion training schedules is the role of the noise timestep . In principle, one could sample a single timestep per image per forward-backward pass. In practice, most production training runs sample multiple timesteps per image in each mini-batch, either explicitly by processing the same image at multiple noise levels within a single step, or implicitly by using a large enough effective batch size that the empirical distribution over approximates the target distribution after every update.
Gradient accumulation provides a way to achieve this without increasing the memory cost per step. Let be the accumulation factor. For each training step, the worker performs forward-backward passes, accumulating the gradient: (GRAD Accum) before performing a single all-reduce and parameter update. This multiplies the effective batch size by without multiplying the communication frequency by . The SDXL training run used gradient accumulation steps, effectively quadrupling the batch size while keeping the communication-to-compute ratio constant.
Remark 36 (Variance Reduction across Timesteps).
Gradient accumulation over multiple timesteps has an additional benefit in the diffusion setting: it reduces the variance in the gradient estimator induced by the random sampling of . The loss at high noise levels () and low noise levels () can differ by an order of magnitude, so single-sample estimates of the gradient can have high variance. Accumulating gradients over diverse timesteps reduces this variance, stabilising training particularly in the early phases where the model is learning the overall structure of the data distribution.
Classifier-Free Guidance and Communication Cost
Classifier-free guidance (CFG) is the dominant conditioning technique for text-to-image and text-to-video diffusion models. During training with CFG, each sample is processed with two forward passes: one conditioned on the text embedding , and one unconditioned (with replaced by a null embedding ). The model is trained to jointly estimate both and , with the conditioning randomly dropped with probability to ensure the model learns both modes.
From a communication perspective, CFG doubles the number of forward passes per training step but does not change the number of all-reduce operations. The gradients from both the conditional and unconditional passes are summed before synchronisation: (CFG GRAD) and the resulting combined gradient is all-reduced once. The communication-to-compute ratio therefore improves with CFG: twice the compute for the same communication cost.
Communication Hiding in Diffusion Training
The dominant technique for reducing the wall-clock cost of the all-reduce in data-parallel training is to overlap gradient synchronisation with the computation of the next mini-batch's forward pass. In standard PyTorch DDP (Distributed Data Parallel), this is implemented by partitioning the parameter vector into buckets of fixed size (default 25,MB), launching the all-reduce for each bucket as soon as its gradients are ready during the backward pass, and overlapping subsequent backward-pass computations with in-flight all-reduce operations.
For DiT training, the transformer structure is particularly well-suited to this overlap. Because the backward pass processes layers in reverse order (from the output layer toward the embedding layer), and because the all-reduce buckets are filled in that same order, the first bucket to complete its all-reduce (the parameters of the output projection layer) is complete long before the last bucket (the embedding layer) has even started accumulating gradients. This means that parameter updates can begin streaming in while the backward pass is still running, a technique sometimes called gradient streaming.
Local SGD for Diffusion Models
Local SGD is a communication-avoiding variant of data-parallel training in which each worker takes gradient steps independently before synchronising. Instead of all-reducing gradients every step, workers perform local updates and then average (all-reduce) the parameter vectors themselves: (Local SGD) where is the local parameter vector after independent gradient steps starting from the shared checkpoint . The communication frequency is reduced by a factor of , at the cost of some degradation in the quality of the gradient estimate due to the staleness of the consensus iterate.
For diffusion models, local SGD is particularly tractable for the following reason. The score matching loss is an expectation over all noise levels ; local workers that sample different noise levels during their independent steps will collectively explore the full noise schedule, and the consensus iterate obtained by averaging is a reasonable proxy for the iterate that would have been obtained with full synchronisation at every step. This is in contrast to LLM training with next-token prediction, where each local step updates the model for a specific sequence position, and long periods without synchronisation can cause local models to diverge significantly in their handling of different sequence lengths.
Remark 37 (FID Degradation vs. Communication Reduction).
Empirical studies of local SGD for diffusion training report a graceful trade-off between communication reduction and generation quality as measured by FID (Fréchet Inception Distance). With local steps between synchronisations, FID increases by approximately – points compared to fully synchronised training at equal total compute. With , the degradation grows to – FID points. With , the degradation becomes significant ( FID points in most studies), and post-hoc fine-tuning with full synchronisation is recommended to recover quality. These numbers depend strongly on the model scale, the noise schedule, and the learning rate: larger models and slower learning rates are more tolerant of local SGD.
Decentralized Diffusion Models and Score Composition
The communication strategies described so far all aim to train a single centralised model more efficiently. But diffusion models admit a qualitatively different approach to distribution: training entirely separate models on disjoint data distributions and composing them at inference time through the linearity of the score function.
The theoretical foundation is the product-of-experts identity for diffusion models. If and are two independent generative distributions, their product (unnormalised) has a score function: (Score SUM) In the diffusion model setting, the score function is approximated by the denoising network: . (Score SUM) therefore implies that the score of the composed distribution can be computed by summing the outputs of two independently trained diffusion models: (Score Composition) where and are the parameters of the two expert models, trained independently. No communication between the two training runs is required; composition happens entirely at inference time.
Definition 34 (Score Composition for Distributed Diffusion).
Let be a collection of diffusion model parameters, each trained independently to minimise the denoising score matching loss on data drawn from a (possibly overlapping) subset of the full training corpus. The score composition of these models is the function (Score Composition DEF) where are composition weights. The composed denoising process uses in place of a single model's output at every step of the reverse diffusion chain.
Proposition 11 (Score Composition and the Variational Bound).
Under mild regularity conditions, the score composition of independently trained expert models optimises the same variational bound as a single centralised model trained on the union of the expert datasets, up to an approximation error that decreases as the expert datasets become more complementary (less overlap).
Proof sketch.
Recall that the DDPM training objective is equivalent (up to weighting) to the ELBO on the log-likelihood of the data under the diffusion model. Specifically: (ELBO Equiv) where . Now consider the product-of-experts model . Taking logarithms and applying the bound in (ELBO Equiv) independently for each expert: (POE ELBO) If the experts have been trained to convergence on their respective data subsets (so each individual ELBO is minimised), then the sum in (POE ELBO) is minimised, and the composition in (Score Composition DEF) provides an optimal estimator for the score of . The approximation gap between and the true union distribution arises from the product-of-experts approximation and vanishes when the datasets are disjoint (expert specialisation).
Insight.
Diffusion models allow a unique trick: independently trained models can be combined at inference time through score addition. This enables a form of “training without communication” - each expert model trains on its own data shard using only local compute, and the composition is performed at inference by the end user. No gradient synchronisation, no shared parameter server, no inter-node bandwidth required during training. The price paid is that the composition is a product-of-experts approximation to the joint distribution, which is exact only when the data subsets are disjoint.
Example: Training a 24B Diffusion Model across 8 Separate GPU Nodes
Example 17 (Decentralized Training of a 24B Diffusion Model).
A research consortium has access to 8 GPU nodes, each with 8 A100-80G GPUs (64 GPUs total), connected within each node by NVLink but with only 10,Gb/s Ethernet between nodes. They wish to collectively train a 24B diffusion model.
Communication constraints.
The 10,Gb/s inter-node bandwidth makes gradient synchronisation across all 8 nodes prohibitively slow. An all-reduce of the full 24B parameter gradient in bfloat16 () over 10,Gb/s () Ethernet would require approximately per step, dwarfing the compute time per step. Standard data parallelism across nodes is therefore infeasible.
Decentralized strategy.
The consortium adopts score composition:
Each node independently trains a 24B DiT model using full hybrid parallelism within the node (, , , fully exploiting NVLink). Each node receives a disjoint subset of the training corpus, roughly of the full dataset.
Training runs for 500,000 steps on each node independently, with no inter-node communication.
At inference time, the 8 expert models are composed using (Score Composition DEF) with uniform weights . The composed model generates samples by running the standard DDMS (denoising diffusion model sampling) algorithm, summing the score estimates from all 8 models at each denoising step.
Analysis.
The training cost is the cost of training a single 24B model on of the data - the same total compute as training one model on all the data. The inter-node communication cost is zero during training. At inference, generating a single sample requires 8 forward passes per denoising step (one per expert), increasing inference compute by relative to a single model. For research and offline applications where sample quality matters more than generation speed, this trade-off is often acceptable. In production settings, the 8 expert models can be distilled into a single model using score distillation, eliminating the inference overhead while retaining the quality improvement from diverse training.
Quality assessment.
Experiments with 2 and 4 experts in the diffusion literature show that score composition over experts trained on disjoint subsets of LAION-5B achieves FID scores within – points of a centralised baseline trained on the union dataset at equal total compute. The quality gap narrows when the subsets are curated to be complementary (e.g., partitioned by domain: photography, illustration, scientific figures) and grows when subsets are random shards with significant distributional overlap.
Formal Definition: Convergence of Local SGD for Diffusion Models
We close the section with a formal statement of the convergence guarantee for local SGD applied to the denoising score matching objective, which justifies the empirical observations about FID degradation.
Let be the expected score matching loss, where is the per-sample loss. Assume is -smooth (i.e., for all ) and bounded below. Under local SGD with workers, local steps, learning rate , and gradient variance , after total gradient steps across all workers, the iterate satisfies: (Local SGD Convergence) where is the consensus iterate and is the minimum value. The third term, the local drift, quantifies the cost of taking steps without synchronisation: it grows as , explaining why large values of cause significant degradation. Setting balances the local drift against the learning rate term, giving as the optimal local step count for an -step training run. In practice, is a good heuristic for the noise levels typical of diffusion model training.
Key Idea.
The score matching objective's independence across samples enables two complementary communication-avoiding strategies. First, gradient accumulation over multiple local steps before synchronising (local SGD) reduces communication frequency by a factor of with FID degradation that scales as in the worst case. Second, score composition allows entirely separate training runs to be combined at inference time with zero training communication. Both strategies exploit the same fundamental property: the score function is an additive quantity across independent data sources, so estimates from disjoint workers can be combined without information loss beyond the product-of-experts approximation.
Exercises
Exercise 50 (Gradient accumulation and FID trade-off).
You are training a DiT-XL/2 model (600M parameters) on a cluster with 32 A100 GPUs and an inter-node bandwidth of 25,Gb/s. (a) Compute the wall-clock time per all-reduce step assuming ring-AllReduce and bfloat16 gradients. (b) Suppose you increase the gradient accumulation factor from to . By what factor does the all-reduce time change as a fraction of total training time, assuming the forward-backward compute time per micro-batch is ? (c) A colleague suggests using local SGD with instead of gradient accumulation with . Explain the difference in convergence behaviour and identify one practical scenario where each approach is preferable.
Exercise 51 (Score composition: quality vs. inference cost).
Consider a score composition of expert diffusion models, each with parameters and denoising network evaluation time per step. (a) Write a formula for the total inference time per generated image as a function of , , and the number of denoising steps . (b) Suppose each expert achieves FID on its own training subset. Assuming the experts are trained on disjoint data and their errors are uncorrelated, estimate the expected FID improvement from composition relative to a single model trained on the full dataset, stating your assumptions clearly. (c) For what values of is score composition preferable to training a single large model with twice the parameters? State the trade-offs in terms of training cost, inference cost, and generation quality.
Exercise 52 (Decentralized training under bandwidth constraints).
Eight institutions each own a cluster of 16 V100-32G GPUs. They want to collaboratively train a diffusion model with 1.5B parameters. The inter-institution network provides 1,Gb/s bandwidth. (a) Compute the time required per gradient all-reduce step if all 128 GPUs participate in synchronised data-parallel training, assuming ring-AllReduce over the 1,Gb/s link. (b) Propose a hybrid strategy that combines: (i) full data-parallel synchronisation within each institution (using NVLink at ), and (ii) local SGD across institutions with parameter averaging every steps. Determine the value of that keeps the inter-institution communication overhead below 5% of total training time, assuming a compute time of per step per GPU. (c) Alternatively, adopt score composition: each institution trains an independent expert on its local data. Compare the expected generation quality (in terms of FID on the union test set) between the two approaches, assuming the institutions' data are roughly IID samples from the same underlying distribution.
Distributed Automatic Differentiation
Every modern deep-learning framework rests on the same conceptual
bedrock: automatic differentiation. Given a computation expressed as a
sequence of elementary operations, the framework constructs a
computational graph that records the data-flow between operations
during the forward pass. When the backward pass is invoked, the engine
traverses this graph in reverse, applying the chain rule at each node to
accumulate gradients with respect to the model's parameters. The
engineer writes loss , calls loss.backward(),
and wakes to find param.grad populated, as if by a
well-organised postal service that traced the path of every partial
derivative from the scalar output back to each weight.
The postal metaphor is apt, and it becomes literal once the model is split across multiple GPUs. When layers reside on different devices, the computational graph no longer fits on a single chip. The forward pass must send activations from one GPU to another across NVLink, InfiniBand, or Ethernet; the backward pass must send gradients in the opposite direction through the same channels. The gradient mail, in other words, must cross device boundaries.
This section develops the theory and practice of distributed automatic differentiation: how single-device auto-diff generalises to the multi-device setting, what new problems arise at the boundaries between devices, and how frameworks such as PyTorch and Megatron-LM solve them.
Recap: Automatic Differentiation on a Single Device
Let be a scalar loss function computed as the composition , where each is a differentiable elementary operation (matrix multiply, elementwise nonlinearity, layer normalisation, etc.). During the forward pass, the framework evaluates
(Forward Chain)
and caches the intermediate activations that will be needed by the backward pass. During the backward pass, starting from the scalar seed , the engine propagates
(Backward Chain)
accumulating gradient contributions into each parameter tensor. The correctness of the backward pass depends on two invariants: (i) the cached activations are available when needed, and (ii) the chain-rule Jacobians are computed in the correct reverse order. On a single device, both invariants are trivially maintained by the autograd engine.
Remark 38 (Memory cost of cached activations).
For a transformer with layers, hidden dimension , sequence length , and micro-batch size , the memory required to cache all intermediate activations scales as bytes. For a 70B parameter model with , , , , this exceeds 640,GB in FP32, motivating both activation recomputation and mixed precision.
The Challenge: Computational Graphs Across Devices
Consider a model partitioned into pipeline stages, with stage residing on GPU . During the forward pass, GPU 0 computes and ships the activation tensor over the interconnect to GPU 1, which computes , and so on until GPU produces the loss. The resulting computational graph spans all devices. This creates two structural problems that do not arise in the single-device setting.
Gradient routing.
The backward pass on GPU requires the upstream gradient , which was computed on GPU . The gradient must therefore be transmitted back across the interconnect in the reverse direction of the forward data flow. If the communication is blocking, the backward pass stalls waiting for the gradient mail to arrive.
Activation availability.
The backward pass on GPU also requires the cached activation from the forward pass (to compute the Jacobian ). This activation was produced on GPU and transmitted to GPU . If GPU did not store it locally after the forward pass, it must either request it again from GPU (communication overhead) or recompute it (compute overhead).
These two problems together define the activation communication problem at pipeline boundaries, which we formalise in Section The Activation Communication Problem at Pipeline Boundaries.
Formal Definition: Distributed Computational Graph
Definition 35 (Distributed Computational Graph).
Let be a directed acyclic graph (DAG) where each node represents an elementary differentiable operation and each directed edge represents a data dependency (the output tensor of is an input tensor of ).
A distributed computational graph is a tuple where:
is a device assignment function that maps each operation to one of compute devices.
is the set of boundary edges: edges such that . Each boundary edge requires an explicit inter-device data transfer (send/receive pair) during the forward pass, and a corresponding gradient transfer in the reverse direction during the backward pass.
The communication volume of on the forward pass is bytes, where denotes the byte size of the output tensor of operation . The backward communication volume equals the forward communication volume when no gradient compression is applied.
Remark 39 (Partition quality).
Minimising while ensuring load balance across devices is NP-hard in general (it reduces to minimum bisection on DAGs). In practice, pipeline and tensor parallelism provide structured partitions that are manually designed or found by heuristic search tools such as Alpa.
PyTorch Distributed Autograd
PyTorch implements distributed auto-diff via three interlocking mechanisms: gradient hooks, the autograd engine, and process groups.
Gradient hooks.
A gradient hook is a callable attached to a tensor that is invoked
every time a gradient flows through that tensor during the backward
pass. In the distributed setting, pipeline parallelism frameworks
register send hooks on the boundary activation tensors: when
the backward pass computes the gradient with respect to a boundary
activation, the hook intercepts that gradient and issues an
asynchronous dist.isend() call to transmit it to the upstream
GPU. Conversely, receive hooks on the upstream GPU block until
the gradient arrives and then inject it into the local autograd graph.
The result is that the autograd engine on each GPU sees a locally
consistent graph, with remote dependencies handled transparently by the
hook layer.
The autograd engine.
PyTorch's autograd engine is a reverse-mode accumulator that maintains a ready queue of gradient-computing functions whose all predecessors (in the forward graph) have already received their upstream gradients. In the single-device case, the ready queue processes functions in topological order without blocking. In the distributed case, boundary nodes must wait for gradient messages from remote devices before they are enqueued. PyTorch handles this by treating each remote gradient arrival as an event that triggers enqueueing, allowing the engine to continue computing non-blocked local gradients while waiting for network messages.
Process groups.
PyTorch's dist package organises GPUs into process
groups. A process group is an abstraction over a set of ranks that
can participate in collective communications (all-reduce, all-gather,
broadcast) or point-to-point communications (send/receive). Pipeline
parallel stages typically form a point-to-point chain; data-parallel
replicas form an all-reduce group. A model combining both forms
nested process groups, and the autograd engine interleaves both types
of communication transparently.
Distributed Computational Graph: TikZ Figure
Figure fig:distgen:dist-cg illustrates a distributed computational graph spanning four GPUs. Forward activations flow left-to-right across device boundaries; backward gradients flow right-to-left through the same channels.
The Activation Communication Problem at Pipeline Boundaries
The crux of distributed auto-diff is the following: at each pipeline boundary , the activation tensor is produced by GPU during the forward pass, consumed as input by GPU during the forward pass, and needed again by GPU during the backward pass to compute its Jacobian.
There are three strategies for handling this requirement.
Strategy 1: Remote storage on the sending GPU.
GPU retains in its own memory after transmitting it. During the backward pass, GPU requests again from GPU via an explicit receive. This avoids re-computation but doubles the memory pressure on GPU (it must hold both its own activations and the boundary tensor) and adds one extra round-trip of communication in the backward pass.
Strategy 2: Local storage on the receiving GPU.
GPU stores locally after receiving it during the forward pass. This is the most common approach in practice. It adds memory pressure on GPU but requires no extra communication in the backward pass. The boundary activation is simply read from local memory when needed.
Strategy 3: Recomputation at the boundary.
GPU discards after the forward pass. During the backward pass, it sends a recompute request to GPU , which recomputes from its own stored (or recomputed) input. This trades memory for compute and an additional forward-direction communication in the backward pass. It is most useful when activations are large and the interconnect is fast.
Remark 40 (Practical recommendation).
Megatron-LM uses Strategy 2 by default: boundary activations are stored on the receiving GPU. Activation recomputation (Strategy 3) is applied within each stage (to reduce per-stage activation memory) but typically not at the boundary itself, where the communication overhead of Strategy 3 outweighs its memory savings.
Gradient Accumulation
In large-scale distributed training, the global batch is split into micro-batches, each of size , such that the effective batch size is . Rather than performing an all-reduce synchronisation after every micro-batch (which would incur collective operations per parameter update), the framework accumulates gradients across the micro-batches locally and performs a single all-reduce at the end.
Definition 36 (Gradient Accumulation).
Let be the model parameters and let be consecutive micro-batches. Gradient accumulation computes the accumulated gradient estimate
(GRAD Accum)
by executing forward-backward passes without parameter updates, summing (or averaging) the resulting local gradient tensors, and then performing one collective all-reduce across data-parallel ranks, followed by one optimiser step with .
In PyTorch, gradient accumulation is enabled by calling
loss.backward() in a no_sync() context for the
first micro-batches (suppressing the all-reduce) and calling
loss.backward() outside the context for the -th
micro-batch (triggering the all-reduce).
The mathematical equivalence of gradient accumulation to a single large batch follows from the linearity of expectation:
(Accumulation Equivalence)
provided the micro-batches are i.i.d. draws from the data distribution .
How Many Micro-Batches? The Overlap–Staleness Trade-Off
The choice of involves a three-way trade-off.
Communication overlap.
Pipeline parallelism with micro-batches allows the pipeline to remain full for a larger fraction of the total iteration time. With only micro-batch, the pipeline drains and refills at every step, wasting a fraction of GPU time in the pipeline bubble. With , the bubble fraction approaches zero, recovering near-linear efficiency.
Memory pressure.
Each in-flight micro-batch occupies activation memory. With 1F1B (one-forward-one-backward) scheduling, the maximum number of simultaneously in-flight micro-batches is , limiting peak activation memory to the product of and the per-micro-batch activation footprint.
Gradient staleness.
With asynchronous pipeline parallelism (async-PP), stage may begin processing micro-batch before receiving the backward gradient from micro-batch . The parameter update for stage is then computed with a gradient that is stale by up to micro-batches. This can slow convergence and, in the limit of very large , may prevent convergence entirely. Synchronous 1F1B scheduling avoids staleness but incurs a larger bubble.
Gradient Accumulation Timeline: TikZ Figure
Figure fig:distgen:grad-accum shows the gradient accumulation timeline for a single data-parallel rank with micro-batches.
Application: Megatron-LM's Distributed Auto-Diff
Megatron-LM (Narayanan et al., 2021; 2023) is the reference implementation of distributed auto-diff for large language models. It combines three forms of parallelism-tensor parallelism within each GPU node, pipeline parallelism across nodes, and data parallelism across replica groups-and implements a complete distributed autograd system on top of them.
Tensor parallelism and column/row splitting.
Within each transformer layer, Megatron-LM splits the weight matrices
of the attention and feed-forward sublayers along the column and row
dimensions respectively. For an attention projection with
, the column-parallel split distributes
across GPUs so that GPU holds columns
and computes the corresponding
output shard. The backward pass for column-parallel layers requires
an all-reduce of input gradients across tensor-parallel ranks;
the backward pass for row-parallel layers requires an
all-reduce of output gradients. These collectives are
inserted automatically by the tensor-parallel linear layer
implementation, making the split transparent to the rest of the
autograd graph.
Pipeline parallelism with 1F1B scheduling.
Megatron-LM uses the 1F1B (one-forward-one-backward) pipeline schedule, in which after the pipeline has been filled, each GPU alternates between processing one forward micro-batch and one backward micro-batch. This keeps all GPUs busy except during the initial fill and final drain phases, reducing the pipeline bubble fraction to where is the number of micro-batches and the number of pipeline stages.
Gradient synchronisation.
In Megatron-LM's hybrid-parallel configuration, gradients are
accumulated over micro-batches without synchronisation (using
no_sync() for data-parallel replicas) and then synchronised
in a single all-reduce across data-parallel ranks. The all-reduce is
overlapped with the last backward micro-batch using NCCL's
asynchronous mode, hiding much of the communication latency.
Application: Diffusion Model Backward Pass
Distributed auto-diff for diffusion models exhibits a qualitatively different communication pattern from language models. A denoising diffusion network maps a noisy latent and a timestep embedding to a noise estimate. For a UNet backbone, the network has an encoder path, a bottleneck, and a decoder path with skip connections that bridge corresponding encoder and decoder stages.
When this UNet is partitioned across devices, the skip connections create additional boundary edges in the distributed computational graph: the activation tensors at the encoder boundary are needed both by the adjacent encoder stage and by the spatially corresponding decoder stage, which may reside on a different device. The backward pass must therefore route gradients not only along the main pipeline but also along the skip-connection reverse paths.
In practice, DiT (Diffusion Transformer) architectures avoid this complication by using a pure transformer backbone with no skip connections, making them significantly more amenable to standard pipeline partitioning. For class-conditional and text-conditional DiTs trained at scale (e.g., Stable Diffusion 3, FLUX), pipeline parallelism is applied along the transformer depth dimension using exactly the same mechanism as for language models.
Key Idea: The Gradient Postal System
Key Idea.
Distributed automatic differentiation is automatic differentiation equipped with a postal system. During the forward pass, each GPU computes its local activations and mails them to the next stage. During the backward pass, each GPU computes its local gradients and mails them in reverse. The autograd engine on each device sees only its local portion of the computational graph; the postal layer (gradient hooks, send/receive primitives) ensures that the cross-device chain rule is applied correctly. The correctness of the distributed backward pass reduces to: (i) the postal system delivers every gradient letter to its destination, and (ii) letters arrive before they are needed by the local autograd engine.
Exercises
Exercise 53.
A transformer is partitioned into pipeline stages and trained with micro-batches per iteration using the 1F1B schedule.
- (a)
Derive the pipeline bubble fraction as a function of and .
- (b)
For , find the minimum such that the bubble fraction is below 5%.
- (c)
If each micro-batch forward-backward takes 200,ms and each inter-stage communication takes 5,ms, estimate the total iteration time for micro-batches with and without communication overlap.
Exercise 54.
In PyTorch, the following code fragment is used in a pipeline-parallel implementation:
def send_grad_hook(grad):
dist.isend(grad, dst=rank - 1)
return grad
boundary_activation.register_hook(send_grad_hook)
- (a)
Explain when this hook is invoked during the backward pass.
- (b)
Why does the hook return
gradunmodified rather than returningNone? - (c)
Write the corresponding receive hook that should be registered on the upstream GPU (rank ) to inject the arriving gradient into its autograd graph.
Exercise 55.
A distributed training job uses data-parallel ranks and gradient accumulation micro-batches.
- (a)
How many all-reduce operations are performed per parameter update step without gradient accumulation? How many with ?
- (b)
If each all-reduce of a 7B parameter model (BF16) takes 120,ms on a 400,Gb/s InfiniBand fabric, compute the time saved per step by gradient accumulation.
- (c)
Suppose the micro-batch forward-backward time is 50,ms. At what value of does the all-reduce time become negligible (less than 5% of total step time)?
Mixed Precision, Loss Scaling, and Numerical Stability
The history of numerical computation is, in large part, a history of negotiating between precision and throughput. Every bit of mantissa costs silicon area and memory bandwidth; every bit of exponent range costs the same. The question has always been: how much numerical precision does a particular computation actually require? For inference, the answer has been clear for several years: 8-bit integer quantisation suffices for most tasks. For training, the question is harder, because gradient descent is a fundamentally iterative process in which tiny errors in gradient estimation can compound across thousands of steps into large errors in the final parameters.
Mixed precision training is the art of answering this question precisely: using a lower-precision format where it is safe (the forward pass, activation storage, and gradient communication) while retaining a higher-precision format where it is necessary (the master copy of the parameters and the optimiser state). The result is a 2 reduction in memory bandwidth and a 2 to 4 improvement in tensor-core throughput, with no measurable degradation in final model quality when implemented correctly.
In the distributed setting, mixed precision provides an additional benefit: inter-node gradient communication is dominated by bandwidth, and halving the bit-width of communicated gradients directly halves the communication time. For 100,Gb/s InfiniBand links that are already the bottleneck, this is a significant win.
The Underflow Problem in FP16 Training
IEEE 754 single-precision floating point (FP32) represents numbers in with a relative precision of about . Its 16-bit half-precision cousin (FP16) covers a much narrower range: , with a minimum positive normal value of approximately . Values below in magnitude are represented as either zero (if below the subnormal threshold) or a subnormal with reduced precision.
This creates a severe problem for gradient computation. At the start of training, parameter magnitudes are of order to . After many steps of gradient descent with a learning rate of, say, , the gradients themselves may have magnitudes of order to . In FP32, these values are represented without issue. In FP16, values below are mapped to zero-a phenomenon known as gradient underflow. A training run using pure FP16 with a small learning rate will, after sufficient time, have all gradients round to zero, causing training to stall.
Remark 41 (Overflow is also a concern).
FP16 overflows to infinity (Inf) for values exceeding 65504. Loss values, logit values, and attention weights in unnormalised attention ( before dividing by ) can easily exceed this threshold for large and large batch sizes. Loss scaling (Section Loss Scaling) prevents gradient underflow; gradient clipping (Section Gradient Clipping in Distributed Settings) prevents overflow of parameter updates.
Loss Scaling
The standard solution to gradient underflow in FP16 training is loss scaling. The idea is elementary: if the gradients are too small to be represented in FP16, multiply the loss by a large scalar before the backward pass. By the chain rule, every gradient is then multiplied by as well, shifting the gradient magnitudes into the representable FP16 range. After the backward pass, divide all gradients by before applying the optimiser step. The net mathematical effect is zero: the gradients used for the parameter update are identical to those that would have been obtained without scaling.
Formally, for a loss and scale factor :
(LOSS Scaling)
The scaled loss is computed and stored in FP16; its backward pass yields scaled gradients in FP16 whose magnitudes are times larger and therefore FP16-representable. The division by and the optimiser step are performed in FP32 using the master copy of the parameters.
Choosing .
If is too small, gradients still underflow. If is too large, gradients overflow to Inf or NaN. The optimal depends on the model architecture, the learning rate, the batch size, and the training progress; it varies over the course of training. Static loss scaling requires hand-tuning per experiment.
Dynamic Loss Scaling
Dynamic loss scaling (Micikevicius et al., 2018) eliminates the need
to hand-tune by adapting it automatically. The algorithm
maintains a current scale factor and tracks whether any gradient
in the backward pass is Inf or NaN (detected by checking
torch.isinf(grad).any() after the backward pass).
If no Inf or NaN is detected for consecutive steps (typically ), double the scale: .
If Inf or NaN is detected, halve the scale and skip the parameter update for this step (the corrupted gradients are discarded).
This binary-search-like adaptation finds and tracks the maximum safe scale factor automatically. In practice, the scale typically stabilises in the range to for transformer models and adapts gracefully to changes in gradient magnitude over the course of training.
Remark 42 (Implementation in PyTorch).
PyTorch provides torch.cuda.amp.GradScaler which wraps the
entire loss-scaling protocol: scaler.scale(loss).backward(),
scaler.step(optimizer), and scaler.update() handle
gradient scaling, Inf/NaN detection, scale update, and the conditional
parameter update in a single ergonomic API.
BF16: Exponent-Rich Precision
Brain Floating Point 16 (BF16) is an alternative 16-bit format developed by Google Brain. Like FP32, it uses 8 bits for the exponent, giving the same dynamic range ( to ). It sacrifices mantissa precision: where FP32 has 23 mantissa bits ( significant decimal digits) and FP16 has 10 mantissa bits ( significant decimal digits), BF16 has only 7 mantissa bits ( significant decimal digits).
The critical implication is that BF16 cannot underflow for any gradient magnitude that is representable in FP32. Loss scaling is therefore unnecessary with BF16, eliminating a significant source of training instability and implementation complexity. The cost is reduced mantissa precision: weight updates whose magnitude is much smaller than the weight magnitude itself may be rounded to zero. In practice this is rarely a problem for modern transformer training with Adam-class optimisers, which maintain a high-precision (FP32) master copy of parameters and apply updates from a FP32 gradient estimate even when BF16 is used for the forward and backward passes.
BF16 is natively supported on NVIDIA Ampere (A100), Hopper (H100), and Blackwell (B200) GPUs, and on Google TPUs. It has become the default precision for large-scale training in 2024–2026, largely displacing FP16 for this use case.
FP8: The Emerging Frontier
FP8 (8-bit floating point) training has emerged as the next frontier in precision reduction. The H100 GPU's Transformer Engine supports two FP8 formats:
E4M3 (4 exponent bits, 3 mantissa bits): higher precision, narrower dynamic range ( max value). Used for activations and weights in the forward pass.
E5M2 (5 exponent bits, 2 mantissa bits): lower precision, wider dynamic range ( max value). Used for gradients in the backward pass, where dynamic range is more important than precision.
FP8 doubles the throughput of matrix multiply-accumulate operations on H100 tensor cores (theoretical 3958 TFLOPS for FP8 vs. 1979 TFLOPS for BF16) and halves the memory bandwidth requirement for weight and activation tensors. For communication-bound distributed training, FP8 gradient compression can halve all-reduce time relative to BF16.
However, FP8 training is significantly more sensitive to the choice of scaling factors than FP16 with dynamic loss scaling. Both the forward (E4M3) and backward (E5M2) streams require per-tensor or per-block scale factors that must be calibrated from running statistics of the tensor magnitudes. If these statistics diverge (due to outlier activations or gradient spikes), the FP8 representation silently saturates or underflows, corrupting the training signal in ways that are difficult to detect.
Formal Definition: Mixed Precision Training
Definition 37 (Mixed Precision Training with Loss Scaling).
Let and denote the sets of FP32 and FP16 (or BF16) representable values respectively. A mixed precision training iteration consists of:
Cast down: Copy the FP32 master parameters to a FP16 working copy .
Forward pass (FP16): Compute the scaled loss .
Backward pass (FP16): Compute scaled gradients .
Inf/NaN check: If contains any non-finite value, discard the gradients, adjust , and return to step 1.
Cast up and unscale: Compute the FP32 gradient estimate .
Optimiser step (FP32): Update the master parameters , where is the optimiser update rule (e.g., Adam).
Numerical Format Comparison: TikZ Figure
Figure fig:distgen:formats illustrates the bit layouts of FP32, FP16, BF16, and the two FP8 variants, and compares their dynamic ranges and precision.
Gradient Clipping in Distributed Settings
Gradient clipping is a standard technique for stabilising training of deep networks. The global gradient norm is
(Global NORM)
where the sum runs over all parameters. If (the clipping threshold, typically ), the gradient is rescaled:
(CLIP)
In the single-device setting, computing requires a single pass over all parameter gradients. In the distributed setting, the situation is more complex.
Clip before or after all-reduce?
There are two natural positions for gradient clipping in the distributed training loop.
Clip after all-reduce. The all-reduce synchronises gradients across data-parallel ranks. The clipped gradient is then identical across all ranks, ensuring consistent parameter updates. However, all-reduce must complete before clipping can be applied, which prevents overlapping all-reduce with the backward pass.
Clip before all-reduce. Each rank clips its local gradient using the local norm. This allows overlap of all-reduce with the backward pass, but the clipped gradients differ across ranks (because local norms differ), leading to inconsistent updates. In the worst case, a rank whose local gradient is small clips to a different effective learning rate than a rank whose local gradient is large.
The correct approach for distributed training is to clip after
all-reduce, using the global norm. This is the default behaviour of
torch.nn.utils.clip_grad_norm_ when called on the
synchronised gradients.
Communication cost.
Computing the global gradient norm in the distributed setting requires an all-reduce of the sum of squared gradient norms across all data-parallel ranks. This is a single all-reduce of a scalar (or a vector of per-layer norms), with negligible communication overhead compared to the gradient all-reduce itself. The standard implementation computes
(Global NORM DIST)
where is the gradient shard on rank , via
dist.all_reduce(local_norm_sq, op=dist.ReduceOp.SUM),
followed by taking the square root.
Gradient Noise and Distributed Training
Increasing the effective batch size (where is the number of data-parallel ranks and is the micro-batch size) has a well-known effect on the gradient noise level. We formalise this relationship in the following proposition.
Proposition 12 (Gradient Variance Scales as ).
Let be the per-sample gradient for sample drawn i.i.d. from . Let be the population gradient. The gradient estimate from a mini-batch of size ,
(Minibatch GRAD)
satisfies
(Variance Scaling)
where is the per-sample gradient variance.
Proof.
Since the samples are drawn i.i.d., the per-sample gradients are independent with identical distributions. By linearity of expectation, . By the variance of a sum of independent random variables,
Remark 43 (Implications for learning rate scaling).
The variance scaling is the theoretical basis for the linear scaling rule: when the batch size is multiplied by , the learning rate should also be multiplied by (keeping the signal-to-noise ratio of the gradient estimate constant). In practice, this rule holds for moderate but breaks down for very large batches, where the noise level is so low that the gradient estimate is almost deterministic and further learning rate increases cause divergence rather than faster convergence. The critical batch size , above which further scaling yields diminishing returns, is typically in the range to tokens for large language models.
Distributed Optimiser: ZeRO-1 and Adam State Partitioning
Even with mixed precision, the FP32 master parameters and the Adam optimiser state (first moment and second moment in FP32) consume 12 bytes per parameter: 4 bytes each for , , and . For a 7B parameter model, this totals , far exceeding the 80,GB HBM on a single H100.
The Zero Redundancy Optimizer (ZeRO) Stage 1 (ZeRO-1) partitions the optimiser state across data-parallel ranks. Each rank holds only of the optimiser state, corresponding to a disjoint shard of the parameter space.
The per-step procedure under ZeRO-1 is:
Each rank holds the full BF16 working copy of parameters and computes the full gradient for its micro-batch.
Gradients are all-reduced across ranks (exactly as in standard data parallelism).
Each rank updates only its shard of the optimiser state: where is the gradient shard corresponding to its parameter shard.
Each rank updates its parameter shard in FP32 and casts back to BF16.
An all-gather synchronises the updated BF16 parameters across all ranks so that each rank holds the complete model.
ZeRO-1 reduces optimiser state memory by a factor of (from 12 bytes/param to bytes/param for the optimiser state) while adding one all-gather communication per step. For , a 7B model's optimiser state fits comfortably in 1.3,GB per GPU.
ZeRO-2 additionally shards the gradients; ZeRO-3 shards the parameters themselves. Each stage adds one additional all-gather per step but provides proportionally greater memory savings.
Example: Complete Distributed Training Recipe for a 7B LLM
We now present a concrete, end-to-end distributed training configuration for a 7B parameter language model, combining all the techniques developed in this chapter.
Example 18 (Distributed Training Recipe: 7B LLM).
Hardware: 64 NVIDIA H100 SXM5 80,GB GPUs, 8 GPUs per node (8 nodes), connected by NVLink within each node and 400,Gb/s InfiniBand HDR across nodes.
Parallelism strategy:
Tensor parallelism (TP): (all 8 GPUs within each node share one model replica, splitting weight matrices along the tensor dimension).
Pipeline parallelism (PP): pipeline stages, spanning 4 nodes; each stage holds 8 transformer layers (32 layers total).
Data parallelism (DP): data-parallel replicas (8 nodes / 4 pipeline stages = 2 replicas).
Total GPU count: .
Micro-batch and gradient accumulation:
Micro-batch size: sequence of 4096 tokens.
Gradient accumulation steps: micro-batches.
Global effective batch size: sequences tokens.
Precision:
Forward pass and activations: BF16.
Gradient communication (all-reduce across DP ranks): BF16.
Master parameters and Adam state: FP32.
Loss scaling: not required (BF16 has FP32 exponent range).
Optimiser: Adam with , , , ZeRO-1 state partitioning across data-parallel ranks. FP32 master parameters.
Learning rate and clipping: Peak learning rate with cosine decay; linear warmup over 2000 steps. Gradient clipping threshold applied after gradient all-reduce (on the synchronised FP32 gradients).
Memory per GPU (estimated):
BF16 model parameters: .
FP32 master parameters: (divided by within each TP group, then by ZeRO-1).
Adam state (FP32 ): per replica, after ZeRO-1.
Activations (BF16, 8 layers, , , ): approximately .
Total: per GPU, fitting within the 80,GB HBM with headroom for communication buffers.
Training throughput (estimated): At 50% model flop utilisation on H100 (a realistic estimate for hybrid-parallel configurations), training throughput is approximately FP16 FLOP/s across all 64 GPUs. For a 7B model trained on 1 trillion tokens, the total FLOPs required are approximately FP16 FLOPs, requiring approximately seconds hours.
Warning: FP8 Training Fragility
Caution.
FP8 training is fast but fragile. The 8-bit format offers only 448 (E4M3) or 57344 (E5M2) as its maximum representable value, and only 8 distinct exponent values. Unlike BF16, which shares FP32's exponent range and gracefully downgrades precision without overflow, FP8 can silently saturate for activations or gradients whose magnitudes lie outside the format's range. Training with FP8 requires careful per-tensor or per-block calibration of scale factors, continuous monitoring of gradient statistics for signs of divergence, and explicit fallback mechanisms to BF16 or FP32 when saturation is detected. Teams deploying FP8 training in 2024–2026 have reported training instabilities manifesting as sudden loss spikes that are not present in BF16 training runs, and that can be difficult to reproduce and diagnose. FP8 training is production-ready for well-understood model families on NVIDIA H100, but should be treated with caution for novel architectures or training regimes.
Exercises
Exercise 56.
A transformer model is trained in FP16 with dynamic loss scaling. At step , the current scale factor is . The loss at this step is .
- (a)
What is the scaled loss computed in FP16? Does this value overflow FP16?
- (b)
Suppose a particular gradient tensor has true value in FP32. What is the FP16-representable value of ? Would itself be representable in FP16 without scaling?
- (c)
If the scaling algorithm doubles every 2000 steps when no overflow occurs, and halves it upon any overflow, and the current scale has been at for 1500 steps without overflow, what is the expected scale at step ?
Exercise 57.
A distributed training job uses data-parallel ranks. After all-reduce, the gradient tensor for a particular layer has global norm and the clipping threshold is .
- (a)
What is the clipping factor applied to the gradient? Write the formula and compute the numerical result.
- (b)
Suppose that before the all-reduce, the local gradient norms on the 8 ranks are , , , . Explain why clipping each local gradient to before the all-reduce would produce a different result from clipping the global gradient after all-reduce.
- (c)
Compute the communication overhead of the global norm all-reduce as a fraction of the gradient all-reduce, for a model with BF16 parameters.
Exercise 58.
A 13B parameter model () is trained with Adam (FP32 master parameters and FP32 optimiser state) using ZeRO-1 across data-parallel ranks.
- (a)
Compute the total memory required for the FP32 master parameters and Adam first and second moments per GPU, with and without ZeRO-1 sharding.
- (b)
ZeRO-1 adds an all-gather of the BF16 parameters (2 bytes/param) after each optimiser step. If the all-gather bandwidth across 32 ranks is 200,GB/s, compute the latency of this additional communication.
- (c)
Compare this all-gather latency to the gradient all-reduce latency. Under what conditions is ZeRO-1's communication overhead negligible?
Distributed vs Federated: A Clear Distinction
There is a confusion that persists in the literature, in conference hallways, and in the code repositories of practitioners who have read too many abstracts and not enough methods sections. Both distributed training and federated learning involve many devices running gradient computations simultaneously. Both involve some form of aggregation. Both produce a single model at the end. The confusion, therefore, is understandable. It is also consequential. Designing a medical imaging diffusion model as if it were a data-centre workload, or designing a data-centre workload as if it were a federated system, leads to systems that are either slower than necessary, less private than required, or simply broken.
The distinction is not subtle. It is architectural, motivational, and mathematical. Distributed training exists because a single machine is too slow: the goal is speed, and the cost is coordination overhead. Federated learning exists because data cannot or must not leave its source: the goal is privacy, and the cost is statistical heterogeneity and unreliable communication. The overlapping vocabulary - rounds, aggregation, workers, gradients - obscures a fundamental divergence in what the system is trying to achieve.
This section draws the distinction precisely, formalises both paradigms, and provides a decision framework for practitioners who need to choose. It also identifies the interesting middle ground where the two approaches borrow from each other, and connects the systems story told here to the privacy story told in Chapter 37.
The Two Paradigms Described
Distributed training.
The canonical distributed training setup consists of a cluster of homogeneous accelerators - GPUs or TPUs - housed in the same building, connected by high-bandwidth, low-latency fabrics such as NVLink (up to bidirectional on NVLink 4.0) or InfiniBand (up to with HDR200). The training data resides on a shared file system or has been partitioned across worker nodes in a balanced, predetermined way. Every worker holds an identical copy of the model. In each iteration, the workers compute gradients on different mini-batches drawn from the global dataset, communicate those gradients via an All-Reduce collective, and update their models synchronously. At the end of each step, every worker holds the same updated model.
The data distribution is i.i.d.: because the global dataset has been randomly partitioned, each worker's local mini-batch is statistically representative of the whole. The objective function is identical across workers. The challenge is purely computational: how to coordinate workers efficiently so that they collectively train times faster than a single worker, minus the overhead of communication.
Federated learning.
Federated learning was introduced by Google in 2017 precisely to handle the case where the data cannot be moved. The canonical setup involves a large population of client devices - smartphones, hospital servers, IoT sensors - each holding data that is local, private, and typically non-i.i.d. A hospital's MRI scanner has only that hospital's patients. A keyboard's prediction model has only that user's typing history. The data on device is drawn from a distribution that may differ substantially from for .
The clients communicate with a central server over the public internet: WiFi, LTE, or satellite links with bandwidths orders of magnitude lower than NVLink, with latencies measured in hundreds of milliseconds rather than microseconds, and with non-negligible probabilities of packet loss, disconnection, and device unavailability. The clients are heterogeneous: different hardware, different battery levels, different amounts of local data. Many clients drop out of each round.
Formal Definitions
Definition 38 (Distributed Training).
Let be a training dataset with global loss Distributed training with workers partitions into shards such that and for all . Each worker computes the local gradient and the aggregated gradient is an unbiased estimator of . Workers share a single global objective, operate on identically-distributed data, and maintain synchronised parameter replicas after every step. The training terminates when converges or a wall-clock budget is exhausted.
Definition 39 (Federated Learning).
Let there be clients, each holding a local dataset drawn from a client-specific distribution . The federated objective is where in general (statistical heterogeneity). In each communication round :
The server broadcasts the current global model to a sampled subset of clients.
Each client performs local gradient steps (using SGD or Adam on ), producing a local update .
The server aggregates: .
Clients are not synchronised between rounds; a client that participates in round may not participate in round . Raw data never leaves the client.
The critical structural difference is visible in these definitions. In distributed training, is an unbiased estimator of the same gradient . In federated learning, is the gradient of a different function from . The aggregated update is therefore not an unbiased estimator of unless the happen to be equal. This client drift is the fundamental statistical challenge of federated learning that has no counterpart in distributed training.
A Visual Comparison
Systematic Comparison Across Twelve Dimensions
Table tab:distgen:dist-vs-fed places the two paradigms side by side across twelve engineering and statistical dimensions. Reading the table column by column reveals why the systems look superficially similar but require entirely different engineering decisions.
| p4.4cm p4.4cm Dimension | Distributed Training | Federated Learning |
| Primary goal | Speed (reduce wall-clock time) | Privacy (keep data local) |
| [2pt] Network | NVLink / InfiniBand; –, s latency | WiFi / LTE / internet; –, ms latency |
| [2pt] Devices | Homogeneous accelerators (same GPU model, same VRAM) | Heterogeneous clients (phones, servers, IoT); different compute |
| [2pt] Data distribution | i.i.d. (balanced partition of global dataset) | Non-i.i.d. (each client has own distribution ) |
| [2pt] Data location | Shared distributed file system | Stays on device; never transmitted |
| [2pt] Synchronisation | Synchronous every step; all workers update together | Periodic (every local steps); clients drop in and out |
| [2pt] Privacy | None (data visible to all workers) | Data never leaves client; optional DP or secure aggregation |
| [2pt] Stragglers | Dominant concern; one slow worker blocks all | Tolerated; round ends after a quorum, stragglers ignored |
| [2pt] Fault tolerance | Checkpoint + restart; downtime is expensive | Built-in: missing clients simply excluded from that round |
| [2pt] Gradient bias | Unbiased: | Biased under heterogeneity: |
| [2pt] Communication rounds | Thousands to millions per run; cheap per round | Tens to hundreds per run; very expensive per round |
| [2pt] Regulatory context | GDPR less critical (data centralised, consent given) | GDPR / HIPAA core design constraint |
When to Use Which: A Decision Framework
The choice between distributed training and federated learning is determined by three primary factors: network bandwidth, data privacy constraints, and device homogeneity.
Network bandwidth.
If all compute nodes are co-located in a data centre and connected by high-speed fabric, use distributed training. If nodes communicate over the public internet or consumer wireless networks, the communication cost per gradient step becomes prohibitive: at and a 7B-parameter model with 32-bit gradients, transmitting a single gradient tensor takes seconds, far too slow for step-synchronous training.
Privacy constraints.
If training data is subject to regulatory restrictions - HIPAA for clinical records, GDPR for EU personal data, institutional data-sharing agreements that prohibit raw data transfer - then distributed training is not a legal option regardless of network speed. Federated learning (possibly augmented with differential privacy or secure aggregation) is the only viable architecture.
Device homogeneity.
Synchronous distributed training assumes that all workers complete each step in roughly the same time. When devices have wildly different compute capacities (a high-end GPU vs. a three-year-old smartphone), synchronous aggregation is impossible. Asynchronous or fully decentralised approaches are needed.
Remark 44 (The decision as a flowchart).
A practitioner can apply the following logic. (1) Can data be moved to a shared location without violating law or policy? If no, use federated learning. (2) If yes: is the network bandwidth between nodes and latency ? If yes, use synchronous distributed training. (3) If bandwidth is moderate (–) and devices are homogeneous, consider Local-SGD (Section Local-SGD as a Bridge). (4) If bandwidth is low and devices are heterogeneous, federated learning even when privacy is not the primary constraint may be the most practical choice.
The Middle Ground: Geo-Distributed Training
Between the single data-centre cluster and the federated edge, there is a middle regime: training across multiple geographically separated data centres. A company may have data centres in North America, Europe, and Asia. Each centre holds a balanced shard of the training data (so data distribution is i.i.d. across centres), but inter-centre links are WAN connections with – bandwidth and – round-trip latency, far slower than intra-cluster fabric.
Geo-distributed training is not federated (data is not private; it is simply geographically distributed for capacity reasons) but it cannot use step-synchronous All-Reduce either, because the latency penalty would dominate. Instead, it typically uses hierarchical All-Reduce: fast intra-cluster All-Reduce within each data centre, followed by a slower inter-cluster All-Reduce across the WAN links once every local steps.
The parameter server of a geo-distributed system therefore looks superficially like a federated system: periodic aggregation of locally-updated models across widely-separated nodes. The difference is that the local updates are unbiased (i.i.d. data) and the communication channels are reliable and metered, not probabilistically available and zero-cost.
Local-SGD as a Bridge
One of the most elegant observations in the distributed optimisation literature is that the same algorithm - Local-SGD - is useful for completely different reasons in distributed and federated settings.
In the distributed setting, Local-SGD reduces communication overhead. Instead of All-Reducing gradients after every step, each worker takes local SGD steps and then averages model parameters. The reduction in communication rounds is exactly -fold. The convergence penalty (the gap introduced because local models drift apart during the steps) is small when is small relative to the gradient noise scale.
In the federated setting, the same parameter (often called , the number of local epochs) is large - not because communication is merely expensive but because each communication round is a precious, scarce resource. A client may participate in only a handful of rounds over the entire training run. Local-SGD (in the federated literature: FedAvg) therefore takes very large to extract maximum information from each participation.
Proposition 13 (Local-SGD convergence gap).
Let where each is -strongly convex and -smooth, and assume the gradient variance within each client is bounded by . After communication rounds with local steps per round and step size , the iterate satisfies The first term decreases with more rounds and more local steps; the second increases with . The optimal balances these two forces, and in the distributed (i.i.d.) case the optimal is where is the total number of gradient steps.
The proposition formalises the intuition: more local steps reduce the number of rounds needed (beneficial in both settings) but increase the drift penalty (harmful when local objectives diverge, i.e., in the federated non-i.i.d. case).
Gossip Protocols: Decentralised SGD Without a Server
Both distributed training and federated learning as described above rely on a central entity: the parameter server or the federation server. This creates a single point of failure and a communication bottleneck. Gossip protocols eliminate the central server by having each node communicate only with its immediate neighbours in an overlay graph.
In gossip SGD, each worker at step has a local model . Rather than broadcasting to all workers, it sends its model to a random or fixed neighbour set and receives models from its neighbours. The update rule is: where is a doubly stochastic mixing matrix encoding the graph topology.
Definition 40 (Gossip SGD).
Let be a connected undirected graph over workers. Let be a doubly stochastic matrix compatible with (i.e., whenever ). Gossip SGD with step size performs, at each step :
Compute local gradient. .
Mix with neighbours. .
Gradient step. .
The spectral gap , where is the second-largest eigenvalue of , controls the mixing speed: a larger gap means faster consensus. A fully-connected graph recovers exact All-Reduce in one step (); a ring graph has as , corresponding to slow mixing.
Gossip SGD is fault-tolerant by construction (no single node failure disrupts the protocol), scalable (each node communicates only with neighbours rather than all workers), and naturally asynchronous. Its convergence rate depends on the spectral gap: slower mixing lengthens the effective window over which local models diverge.
The connection to federated learning is exact when is a star graph with the server at the centre: gossip SGD on a star is precisely FedAvg with local step. Decentralised federated learning (no central server) uses gossip on sparse graphs, allowing institution-to-institution model sharing without routing through a central aggregator.
Connection to Chapter 37: Systems vs Privacy
Chapter 37 is dedicated to the privacy story of federated learning. It develops differential privacy, the moments accountant, Gaussian mechanisms, and the interplay between privacy budget and model utility. It covers secure aggregation protocols based on secret sharing and homomorphic encryption that prevent even the server from seeing individual client updates. It analyses membership inference attacks and gradient inversion attacks, the adversarial setting that motivates the privacy machinery.
This chapter covers the systems story. How do we schedule clients? How do we handle stragglers? How do we implement the communication protocol efficiently? How do Local-SGD, gossip, and DiLoCo (Section DiLoCo: Distributed Low-Communication LLM Training) reduce the round-trip cost? The two stories are complementary. A federated system needs both: privacy mechanisms from Chapter 37 and communication-efficient training algorithms from this chapter.
Key Idea.
Distributed training is about speed: reduce wall-clock training time by parallelising computation across fast, homogeneous hardware with shared, i.i.d. data. Federated learning is about privacy: enable learning from data that cannot be moved, across slow, heterogeneous devices, tolerating statistical heterogeneity and device dropout. The mathematical toolkit overlaps - gradient aggregation, local update steps, mixing matrices - but the design priorities diverge completely. Confusing the two leads to systems that are either unnecessarily slow, insufficiently private, or both.
Example: Medical Imaging Diffusion Model
Example 19 (Choosing distributed vs. federated for a radiology diffusion model).
Consider training a diffusion model for thoracic CT synthesis to be used in data augmentation for a downstream cancer detection classifier. You are collaborating with five hospital systems, each with studies.
Scenario A: Central training.
All five hospitals have signed a data-sharing agreement and a HIPAA-compliant data-use agreement (DUA) allows raw DICOM transfer to a cloud data lake. The cloud cluster has 64 A100s connected by InfiniBand. Here, distributed training is correct. Pool the studies, shuffle randomly, partition into 64 shards, and run data-parallel training with ZeRO-3 sharding. Expected training time: days.
Scenario B: No data sharing.
Hospital 3 refuses to sign a DUA. Hospital 5 is in the EU and GDPR prevents export of patient data. Now raw data cannot be pooled. Federated learning is required. Each hospital trains locally for epochs between communication rounds. Expected rounds to convergence: (compared to gradient steps in the distributed setting). The FedAvg aggregated model achieves of the quality of the centralised model, with the gap attributable to non-i.i.d. scanner-specific intensity distributions across the five sites.
Scenario C: Partial sharing.
Hospitals 1, 2, and 4 can share data; hospitals 3 and 5 cannot. A hybrid approach: distributed training on the shared data, with hospitals 3 and 5 joining as federated clients. The shared cluster runs synchronous All-Reduce; the federated clients participate in periodic rounds using their local models. The server maintains separate learning rates for the two streams to account for the different noise levels.
This example illustrates that the choice is often not binary: systems in the wild frequently combine both paradigms.
Exercises
Exercise 59 (Gradient bias under heterogeneity).
Let clients with and . The federated objective is . (a) Compute . (b) Show that one step of FedAvg with local step from returns the correct global minimum in this simple case. (c) Now let and repeat with local steps and . Show that client drift causes the aggregated model to overshoot . Quantify the drift as a function of and .
Exercise 60 (Gossip mixing speed).
Consider workers arranged as a ring, so each worker communicates with workers and (modulo ). The symmetric doubly stochastic mixing matrix for the ring is if , zero otherwise. (a) Compute all eigenvalues of using the fact that the ring graph has eigenvalues for . (b) What is the spectral gap ? (c) Compare to the spectral gap of the complete graph with uniform mixing matrix for all . (d) How many gossip steps does the ring require for the average of all models to converge to the global average, versus the complete graph? Express as a function of .
Exercise 61 (Geo-distributed training latency budget).
A 70B-parameter model is trained across two data centres (North America and Europe) connected by a WAN link with round-trip latency. Parameters are stored in BF16 (2 bytes each). (a) Compute the minimum time to transmit a full-model gradient tensor from one centre to the other. (b) Each centre has 256 A100 GPUs, each achieving at BF16. A single forward+backward pass on a micro-batch costs FLOPs. How many local steps must each centre take before inter-centre communication for the communication latency to represent of total wall-clock time? (c) What is the effective batch size in this regime, and how does it compare to the critical batch size for language model training (roughly tokens)?
Collaborative and Decentralized Training
The taxonomy of distributed learning is richer than the binary distributed/federated divide. Between the tightly-synchronised all-reduce cluster and the loosely-coupled federated round, there exists a spectrum of collaborative training paradigms designed for settings where multiple institutions want to jointly train a model but cannot share data, do not trust a central server, or operate across networks too slow for synchronous training.
These paradigms have become especially relevant as foundation model training has pushed parameter counts past hundreds of billions. No single institution commands the compute to train such models from scratch, but a consortium of universities, hospitals, or volunteer contributors might. The challenge is to organise that distributed compute in a way that is efficient, fault-tolerant, and statistically sound.
This section surveys the leading collaborative training paradigms - Petals, SWARM parallelism, DiLoCo, Decentralised Diffusion Models, CollaFuse, and PDFed - and analyses the regime in which each is preferable.
Petals: Collaborative Inference and Fine-tuning
Petals, introduced by Borzunov et al. (2022), implements collaborative inference and parameter-efficient fine-tuning of large language models across volunteer contributors on the public internet. The core insight is that a very large model can be partitioned into sequential blocks distributed across many machines, with the forward pass executed as a pipeline across the network. A machine hosting blocks through receives the hidden state from the previous host, processes it through those layers, and forwards the result to the next host.
The network is organised as a distributed hash table (DHT) with no central server. Any participant can join, advertise which blocks it is serving, and exit at any time. The DHT maintains a routing table so that a client wishing to run inference can discover which peer holds each block. Redundancy is built in: multiple peers may hold the same blocks, and the routing layer selects the fastest available peer for each block in the pipeline.
Remark 45 (Why sequential blocks, not layer-parallel?).
Layer parallelism (executing all layers simultaneously on different machines) would require broadcasting the full hidden state to every participant at every layer, generating communication events where is the number of participants and the number of layers. Sequential pipeline parallelism generates only communication events (one per layer boundary), a -fold reduction. This makes pipeline parallelism the natural choice for slow, heterogeneous networks.
For fine-tuning, Petals uses adapter-based methods (LoRA, prefix tuning) that insert small trainable modules between frozen backbone blocks. The adapter parameters are held by the client; the backbone blocks remain on the volunteers. During a fine-tuning step, the client runs a forward pass through the pipeline, accumulates activations at adapter boundaries, computes a loss, and runs a backward pass. Gradients flow through the backbone via remote backward passes: the client sends a gradient tensor to each block host, which computes the local backward pass and returns the gradient to be passed to the previous host. The backbone weights are never updated; only the client's adapters change.
This architecture has a pleasant privacy property: the backbone hosts never see the training data. They see only the hidden states passing through their blocks, which are high-dimensional floating-point tensors with no direct semantic interpretation. (Gradient inversion attacks on hidden states are possible but require access to other blocks; the end-to-end privacy is therefore not guaranteed, but much stronger than sending raw data.)
SWARM Parallelism
SWARM parallelism (Ryabinin et al., 2023) extends the Petals pipeline idea to training from scratch, with explicit handling of dynamic, fault-tolerant topology. The key innovation is a stochastic pipeline: instead of assigning each model stage to a fixed device, SWARM maintains a pool of peers for each stage. At each step, the routing layer randomly selects one peer from each pool to participate in the forward and backward pass.
The routing is load-balanced: peers that are faster or have more memory are selected more often. Peers that drop out are simply not selected; the pipeline continues with the remaining peers. This means SWARM tolerates arbitrary dropout of up to fraction of peers at any stage, as long as at least one peer per stage remains.
Formally, let there be stages with peer pools . For each micro-batch, SWARM samples one peer for each stage and routes the micro-batch along the path . The probability of sampling peer from pool is proportional to its advertised throughput: where is the recent tokens-per-second throughput measured for peer . This induces a self-organising load balancer that concentrates traffic on faster peers.
Remark 46 (SWARM vs. synchronous pipeline parallelism).
Synchronous pipeline parallelism (GPipe, PipeDream) assigns each stage to a fixed device and processes micro-batches in a predetermined schedule. A single device failure stalls the entire pipeline. SWARM's stochastic routing eliminates this dependency at the cost of statistical inconsistency in the order in which micro-batches traverse stages. This is acceptable in large-batch SGD but may introduce noise in training loss trajectories that would be absent in a synchronous setting.
DiLoCo: Distributed Low-Communication LLM Training
DiLoCo (Douillard et al., 2023) is a collaborative training method designed specifically for the regime where compute is abundant but bandwidth is scarce: multiple data-centre clusters connected by intercontinental WAN links.
The algorithm is structured as a two-level optimisation: an inner optimiser runs inside each worker island for steps using standard AdamW on local data; an outer optimiser performs a Nesterov momentum step on the pseudo-gradient - the difference between the initial and final parameters of the inner loop.
Definition 41 (DiLoCo).
Let there be worker islands, each holding a replica at the start of outer round . Each island maintains its own inner optimiser state. The DiLoCo update proceeds as follows:
Inner optimisation. Each island runs steps of AdamW on its local data shard , starting from :
Pseudo-gradient computation. Each island computes its pseudo-gradient:
All-Reduce. Pseudo-gradients are averaged across islands:
Outer Nesterov step. The global model is updated using Nesterov momentum with outer learning rate and momentum :
Broadcast. is broadcast to all islands, which reset their replicas: .
Communication occurs only at step 3 (once per outer round), transmitting parameter vectors of size .
The number of communication events relative to standard distributed training is reduced by a factor of (the inner loop length). DiLoCo originally used , meaning that a full All-Reduce occurs only every 500 gradient steps. At and a 7B model, one All-Reduce transmits ; at steps of each, this represents of communication every of compute - a 50% overhead. This overhead drops to at steps.
The key empirical finding of DiLoCo is that inner steps suffers only a modest convergence penalty relative to synchronous training. The intuition is that the pseudo-gradient is a smoothed, low-variance estimate of the direction in which the global loss is improving, accumulated over many steps rather than a single noisy gradient.
Remark 47 (DiLoCo and FedAvg).
DiLoCo is structurally identical to FedAvg when the outer optimiser is a simple average with learning rate 1.0 and no momentum. The innovations in DiLoCo relative to FedAvg are: (1) a Nesterov outer momentum step rather than a plain average, which reduces oscillation in the outer loop; (2) AdamW (rather than SGD) as the inner optimiser, which matches modern LLM training practice; and (3) a focus on i.i.d. or near-i.i.d. data across islands (data-centre shards) rather than the non-i.i.d. federated setting.
Decentralised Diffusion Models
The diffusion modelling community has developed its own collaborative training paradigms, motivated by the observation that different institutions may possess expertise (and data) in different domains. Rather than training a single monolithic model on all data, decentralised diffusion approaches train expert islands independently and then compose them at inference time via score routing.
In the score-based formulation, the denoising score function for the global distribution can be expressed as a mixture: where is the local data distribution at island and is the weight assigned to expert for input . If the data partitioning is disjoint (each island specialises in a distinct domain), then for most inputs only one or a few experts have substantial weight, and the routing can be implemented by a lightweight classifier that identifies which island is most relevant.
Training.
Each island trains its own diffusion model on its local dataset using the standard denoising score-matching objective: No data leaves the island. No communication occurs during training.
Score routing at inference.
At inference time, a routing network outputs a probability distribution over the experts. The effective denoising step is: The router can be trained on a small shared dataset that each island is willing to release (e.g., de-identified validation samples), or it can be trained without any shared data using mutual information maximisation between the routing distribution and the per-island reconstruction quality.
The key advantage of this paradigm is complete separation of training from collaboration: each institution trains independently, and collaboration happens only at inference. The disadvantage is that the composed model may not be better than any individual expert on in-distribution data; the benefit materialises for out-of-distribution inputs that span multiple experts' knowledge.
CollaFuse: Split Learning for Diffusion
CollaFuse (Rieke et al., 2024) adopts a split-learning approach to diffusion model training. The key observation is that the U-Net backbone of a diffusion model has an asymmetric computational profile: the cheap early layers process high-resolution feature maps and encode local structure, while the expensive middle layers (the bottleneck attention blocks) process low-resolution features and capture global semantics.
CollaFuse proposes that each client executes the cheap local layers on its private data, transmits only the compressed latent representation (the bottleneck activations) to a shared server, and the server runs the expensive middle layers. The backward pass follows the same split: the server transmits gradients at the split point back to the client, which updates the local layers.
Let and denote the client-side encoder and decoder halves of the U-Net, and the server-side middle layers. The forward pass for client is: (Collafuse FWD1) where are client-local parameters and are shared server parameters. The client-side loss is computed on and the backward pass propagates gradients: (i) through to update (locally); (ii) a gradient is sent to the server, which updates and returns to the client; (iii) the client completes the backward through to finish updating .
Remark 48 (Privacy in CollaFuse).
The server receives intermediate activations , not raw data . For high-resolution medical images, these activations may still contain significant identifying information; activation inversion attacks (Pasquini et al., 2021) have shown that reconstruction of the input from intermediate activations is feasible for shallow splits. In practice, CollaFuse applies a small amount of noise to before transmission (effectively a split-learning variant of local differential privacy) to degrade inversion quality.
The efficiency gain of CollaFuse is measured by the fraction of computation that remains local. For a standard U-Net with 860M parameters, the head and tail together account for of parameters but only of FLOPs (because the middle blocks are computationally dense relative to their parameter count). The transmitted activation tensor is the bottleneck feature map, which for a image is floats values, far smaller than the raw image.
PDFed: Asynchronous Federated Diffusion with Blockchain Provenance
PDFed (Peng et al., 2023) addresses a different facet of the collaborative training problem: trust and provenance. In a standard federated system, clients trust that the server aggregates honestly, and the server trusts that clients submit genuine gradient updates rather than poisoning attacks. Neither party has a verifiable record of what happened.
PDFed uses a permissioned blockchain to record every model update submitted by every client in a tamper-evident ledger. Each entry contains the client identifier, the round number, the hash of the submitted update, and a zero-knowledge proof that the update was computed from data satisfying a stated constraint (e.g., minimum dataset size, not previously submitted). The smart contract governing the federation enforces the aggregation rule and releases the aggregated model only when a quorum of valid updates has been recorded.
Beyond provenance, PDFed introduces asynchronous aggregation: clients do not wait for a global synchronisation round. Instead, each client submits its update whenever it finishes local training. The smart contract aggregates updates as they arrive, using a sliding window of the most recent updates from distinct clients. The aggregated model at time is: where is the client that submitted the -th most recent update and is the local step at which that update was computed. This introduces a form of staleness: a client that trains slowly may submit updates based on a model that is rounds stale relative to the current global model. PDFed bounds the staleness impact using a decaying weight where is the current round counter.
Remark 49 (Overhead of blockchain provenance).
Recording every update on-chain is not free. For a production federated system with thousands of clients, the blockchain throughput (transactions per second) and storage cost must be accounted for. PDFed uses a Hyperledger Fabric permissioned blockchain, which can sustain transactions per second on a small validator network, sufficient for federated systems with active clients per round. Larger systems require off-chain storage of model updates (storing only the hash on-chain) or layer-2 aggregation.
Three Collaborative Paradigms: A Visual Summary
The Network-Regime Crossover: When Does Synchronous Distributed Beat Collaborative?
A natural question arises: given a fixed compute budget and a fixed network, when is it better to use synchronous distributed training (which has lower statistical variance but higher communication overhead) versus collaborative training with infrequent communication (lower overhead but potentially higher variance)?
We formalise this as a bandwidth crossover problem.
Proposition 14 (Crossover bandwidth threshold).
Consider workers each with step time (seconds per gradient step) training a model with parameters at precision bytes per parameter. Synchronous All-Reduce requires transmitting bytes per step at bandwidth bytes per second, incurring communication latency per step. The effective throughput of synchronous distributed training is A collaborative algorithm (DiLoCo-style) with local steps per communication round incurs communication latency only every steps, giving effective throughput Setting yields the crossover point, which is trivially (synchronous is always at least as fast as collaborative in terms of throughput alone). The meaningful crossover is in convergence efficiency: synchronous training with effective batch size converges in steps; collaborative training with drift accumulates extra gradient noise over each inner loop. Collaborative training is preferable to synchronous training in the bandwidth regime where where is the inner loop length that balances local noise against drift noise. For modern LLM training (, , , ), this gives .
The proposition implies that collaborative training with is preferred over synchronous all-reduce whenever the available bandwidth falls below . Intercontinental WAN links typically provide –, which straddles this threshold. Satellite links () fall well below it. Intra-data-centre NVLink () falls far above it: synchronous all-reduce is unambiguously better.
Geo-Distributed Training: RDMA and WAN-Optimised Collectives
When the collaborative clusters are the data centres of a single organisation (rather than independent institutions), the system can exploit RDMA (Remote Direct Memory Access) over the WAN backbone. RDMA allows a GPU on one continent to write directly into the GPU memory of a node on another continent, bypassing the operating system kernel and TCP/IP stack on both ends. This reduces per-byte latency from (TCP over WAN) to (RDMA over converged Ethernet), a modest improvement, but the throughput improvement is more significant: RDMA can sustain near-link-rate throughput without CPU involvement.
WAN-optimised collectives adapt the All-Reduce topology to heterogeneous inter-node bandwidth. The standard ring All-Reduce assumes all-to-all bandwidth is equal; on a WAN with two clusters, the inter-cluster link is the bottleneck. A two-level hierarchical All-Reduce addresses this:
Intra-cluster reduction. Within each data centre, a standard ring All-Reduce aggregates gradients using the fast intra-cluster fabric (NVLink / InfiniBand). Each cluster produces a local aggregate of its local gradient.
Inter-cluster reduction. The aggregates (one per cluster) are combined via a star All-Reduce over the WAN. The total inter-cluster data volume is bytes (reduced by the intra-cluster step by a factor of , where is the cluster size).
Broadcast. The final aggregate is broadcast back to all clusters and distributed intra-cluster.
The bandwidth requirement on the WAN link is reduced from bytes (naive all-to-all) to bytes (hierarchical), a factor of reduction. For workers across clusters, this is a reduction in inter-cluster traffic.
Remark 50 (Asynchronous inter-cluster All-Reduce).
Truly synchronous inter-cluster All-Reduce is impractical at WAN scale because the latency () stalls all workers during the inter-cluster step. In practice, systems overlap the inter-cluster communication with the next intra-cluster gradient computation: while cluster 1 is computing its next mini-batch, the WAN is transmitting the previous inter-cluster aggregate. This requires a one-step delay in the gradient update (the model is updated with a gradient that is one step stale across clusters), which introduces bounded bias proportional to the learning rate and the gradient Lipschitz constant.
The Hybrid Future
The dichotomy between “tight cluster” and “loose collaboration” is dissolving. Modern distributed AI systems increasingly adopt a hierarchical structure that mirrors the physical network topology: tight synchrony within a rack or pod (NVLink or InfiniBand, sub-microsecond latency), looser synchrony between racks within a data centre (Ethernet, microsecond latency), and very loose synchrony between data centres or institutions (WAN / internet, millisecond latency).
At each level of the hierarchy, the appropriate aggregation algorithm is different:
Within a rack: Synchronous All-Reduce every step. Communication is so fast that there is no benefit to accumulating local steps.
Between racks: All-Reduce every – steps. A small amount of local drift is acceptable to avoid saturating inter-rack switches.
Between data centres: DiLoCo-style with – inner steps. The outer Nesterov step provides stability across the long inner loop.
Between institutions: Federated learning with privacy mechanisms from Chapter 37, one or more full training epochs.
This hierarchical view unifies all the paradigms discussed in this chapter. The algorithms differ only in the timescale of synchronisation, which is dictated by the available bandwidth at each level of the hierarchy.
Insight.
The future of distributed AI training is hybrid: tight synchronous clusters for the heavy lifting of dense matrix multiplication, loosely coupled collaboration for aggregating knowledge across institutions, geographies, and edge devices. No single algorithm governs all levels; instead, the hierarchy of aggregation algorithms mirrors the hierarchy of the network itself. Systems that understand this structure - and tune the inner loop length and outer learning rate at each level - will be more efficient than those that apply a uniform synchronisation strategy across all scales.
Exercises
Exercise 62 (DiLoCo vs. FedAvg convergence).
Consider training a quadratic objective with workers and inner steps of gradient descent (learning rate ) followed by an outer step.
For the FedAvg outer step (plain average with outer learning rate 1.0), compute the iterate after one round starting from and .
For the DiLoCo Nesterov outer step with and (initialising ), compute .
Which converges faster in this quadratic setting after outer rounds? Plot the norm as a function of for both methods.
How does the answer change if the workers have heterogeneous local objectives with ?
Exercise 63 (Score routing for diffusion composition).
Suppose two expert diffusion models are trained on disjoint domains: and with , , . The combined distribution is a symmetric Gaussian mixture .
Write the score function in closed form.
Express this as a convex combination of the individual scores and , and identify the routing weights .
Show that the routing weights satisfy (i.e., the weight for expert is the posterior probability of belonging to ).
Implement a simple Langevin MCMC sampler using the composed score function and verify empirically that samples approximate .
Exercise 64 (Hierarchical All-Reduce bandwidth analysis).
A 70B model (BF16, ) is trained across 4 data centres, each hosting 512 A100 GPUs. The intra-data-centre network provides per node; the inter-data-centre WAN provides aggregate (shared across all 4 data centres).
Compute the time to complete one hierarchical All-Reduce (intra-DC then inter-DC) using the ring algorithm within each data centre and a star topology between data centres.
Suppose each GPU processes one micro-batch of 2048 tokens in . What is the maximum number of local steps that can be taken before inter-DC communication becomes the bottleneck (i.e., communication time exceeds of compute time for the entire inner loop)?
If you adopt DiLoCo with chosen as in (b), how many outer rounds are needed to process tokens across all 4 data centres? What is the total wall-clock time, assuming perfect overlap of intra-DC All-Reduce with compute?
Hybrid Parallelism and 3D/4D/5D Parallelism
No production system at scale uses a single parallelism strategy. When researchers trained GPT-3 with 175 billion parameters, they did not choose between data parallelism, tensor parallelism, and pipeline parallelism. They used all three simultaneously, carefully tuned in combination, to saturate thousands of GPUs across interconnected nodes. When engineers at Google trained PaLM with 540 billion parameters, they layered a fourth axis - sequence parallelism - on top of the other three. When the mixture-of-experts community built trillion-parameter models, a fifth axis - expert parallelism - entered the stack.
The move from single-strategy to multi-strategy parallelism is not a matter of preference. It is imposed by physics and economics. A single GPU in 2024 has at most 80,GB of HBM memory. GPT-3, even in half-precision, requires approximately 350,GB just to store parameters. No single strategy can bridge that gap efficiently: data parallelism replicates the model (requires the full model to fit on each device); tensor parallelism introduces expensive all-reduce operations at every layer; pipeline parallelism introduces idle bubbles. The art of large-scale training is finding the combination that minimises total time while saturating hardware.
This section formalises hybrid parallelism, works through the 3D, 4D, and 5D variants in detail, derives communication complexity, and develops a systematic decision framework for choosing the right combination. We close with the concrete recipe used for GPT-3 and an extended example scaling it to a Sora-scale video diffusion model.
Formal Definition of Hybrid Parallelism
Definition 42 (Hybrid Parallelism).
Let be a set of parallelism strategies, each mapping a model and a dataset to a partition of compute resources of GPUs. A hybrid parallelism configuration is a tuple where is the data-parallel degree, is the tensor-parallel degree, is the pipeline-parallel degree, is the sequence-parallel degree, and is the expert-parallel degree, subject to the constraint Each GPU is assigned a unique index tuple identifying its role along every parallelism axis simultaneously. The effective batch size per gradient step is , where is the micro-batch size and is the number of micro-batches per pipeline stage.
The factorisation is the fundamental constraint: every GPU must be assigned a unique role. In practice, not all five axes are non-trivial; 3D parallelism uses , 4D uses , and full 5D is reserved for MoE architectures.
Remark 51 (Commutativity of axes).
The five axes are not interchangeable. Tensor parallelism operates within a node (tight NVLink bandwidth required); pipeline parallelism operates across nodes (tolerates inter-node latency); data parallelism can span arbitrary topology; sequence parallelism replaces a sub-portion of tensor parallelism; expert parallelism requires routing infrastructure. The ordering of axes in hardware mapping matters for performance even when the product is the same.
3D Parallelism: Data, Tensor, and Pipeline
Three-dimensional parallelism, popularised by Megatron-LM and DeepSpeed, assigns each GPU a position in a three-dimensional grid .
Data-parallel dimension.
Replicas of the full (tensor+pipeline-partitioned) model are trained on different mini-batches. Gradients are synchronised via all-reduce after each backward pass. The data-parallel gradient reduction costs where is the parameter count and is the effective all-reduce bandwidth. With ZeRO partitioning, the per-GPU memory footprint reduces from to for optimizer states.
Tensor-parallel dimension.
Each transformer layer is split across GPUs. For an MLP with hidden dimension and intermediate dimension , the weight matrices and are column- and row-partitioned respectively: The forward pass requires one all-reduce after (to sum partial products); the backward pass requires one all-reduce of the input gradient. Per-layer tensor-parallel cost: where is the sequence length. NVLink bandwidth (bidirectional, A100 DGX) keeps this cost small for .
Pipeline-parallel dimension.
The transformer layers are partitioned into stages of layers each. Micro-batches flow through stages in a 1F1B (one-forward-one-backward) schedule. Inter-stage communication transfers activation tensors of shape across the inter-node fabric (InfiniBand or RoCE). Per-micro-batch communication cost: where for InfiniBand HDR.
3D Parallelism TikZ Figure
4D Parallelism: Adding Sequence Parallelism
Long-sequence models - video transformers, protein structure predictors, and long-context language models - face a new bottleneck: the activation memory within a single tensor-parallel shard grows as per layer. For tokens and (GPT-4 scale), this is approximately 6,GB per layer - far exceeding the 2–3,GB available after accounting for parameters and optimizer states.
Definition 43 (Sequence Parallelism).
In sequence parallelism, the sequence dimension is partitioned across GPUs such that each GPU holds a contiguous segment of the token sequence. The operations that are local to the sequence dimension (layer norm, dropout, non-linearities) execute independently on each shard. Operations that require full-sequence context (self-attention) use an all-gather to reconstruct the full key-value matrix, execute attention, and scatter the results. The peak activation memory per GPU reduces by a factor of .
Sequence parallelism is typically co-located with tensor parallelism: the same GPUs within a node handle both axes. In practice, and the two axes share the NVLink fabric. The attention all-gather costs over NVLink, the same as the tensor-parallel all-reduce, so 4D parallelism does not add new inter-node communication.
Remark 52 (Sequence parallelism versus context parallelism).
A related but distinct strategy is context parallelism, used in Llama 3 training at Meta, in which the attention keys and values are partitioned across GPUs using ring-based attention (each GPU sends its KV shard to the next in a ring, accumulating the attention output in communication rounds). Context parallelism scales to much longer sequences than sequence parallelism because it avoids the full -dimensional all-gather, at the cost of sequential communication rounds per attention layer.
5D Parallelism: Adding Expert Parallelism
Mixture-of-experts (MoE) models replace dense feed-forward layers with a sparse routing mechanism: each token is sent to one or two of “expert” sub-networks. With experts distributed across GPUs, each GPU stores experts. Expert parallelism introduces a new communication pattern: all-to-all routing, in which each GPU sends a different subset of tokens to each other GPU (the tokens routed to the experts on that device), and receives a corresponding set of tokens back.
Definition 44 (Expert Parallelism).
Let there be experts and expert-parallel GPUs, with experts per GPU. After the router assigns each token a target expert , expert parallelism executes a dispatch all-to-all: GPU sends all tokens routed to experts to GPU , for every . Each GPU then runs its expert networks on the received tokens and issues a combine all-to-all to return the computed outputs to the originating GPU. Total expert-parallel all-to-all cost per layer: assuming uniform token routing (capacity factor 1) and InfiniBand bandwidth .
The all-to-all is the Achilles heel of expert parallelism: unlike all-reduce (which is latency-bounded at small sizes), all-to-all is bandwidth-bounded and scales as . For 5D parallelism to be efficient, must be chosen so that the all-to-all cost is commensurate with the compute savings from sparsity.
Communication Complexity of Hybrid Parallelism
Proposition 15 (Additive Communication Cost).
Under the assumption that the five parallelism axes operate on disjoint sets of GPUs (or at least disjoint communication fabrics), the total per-iteration communication cost of a hybrid parallelism configuration is where is the total layer count, is the number of micro-batches, and is the number of MoE layers.
Proof.
Each tensor-parallel all-reduce executes once per forward and backward pass per layer: times per micro-batch, costing each. Each pipeline stage boundary transmits activations forward and gradients backward, once per micro-batch: micro-batches, costing each. Data-parallel gradient all-reduce executes once per iteration regardless of . Sequence-parallel all-gathers execute once per layer in the forward pass (and once in the backward). Expert all-to-all executes twice per MoE layer (dispatch and combine) per micro-batch. The communication events on the four distinct fabrics (NVLink for TP/SP, InfiniBand for PP/EP, data-center network for DP) proceed concurrently; their costs add independently.
Insight.
In practice, tensor-parallel communication is overlapped with compute using asynchronous NCCL all-reduces, and data-parallel gradient communication is overlapped with the backward pass using gradient bucketing (PyTorch DDP, DeepSpeed ZeRO stage 1/2). The dominant exposed (non-overlapped) cost in well-tuned 3D parallelism is typically the pipeline bubble, not communication.
The Decision Framework: Choosing the Right Combination
Given a model with parameters, layers, hidden dimension , sequence length , a cluster of GPUs with memory each, the following greedy decision tree guides the choice of :
Algorithm 7 (Hybrid Parallelism Decision Framework).
Does the model fit on one GPU? Check , where is bytes per parameter (2 for fp16/bf16, 4 for fp32). If yes, set and use data parallelism alone: . Scale batch size accordingly.
If not: apply tensor parallelism first. Tensor parallelism communicates via NVLink (fast, low-latency) and must not cross node boundaries. Choose to fit the model within per TP shard. Rule of thumb: each TP shard should hold (leave 60% for activations and optimizer states).
Still need more memory: apply pipeline parallelism. Choose to fit each pipeline stage within memory. Ensure is an integer. Pipeline parallelism crosses node boundaries and introduces a bubble; choose the smallest that satisfies the memory constraint.
Fill remaining GPUs with data parallelism. Set . Verify that the effective batch size does not harm convergence (heuristic: tokens sequence-length for language models).
Long sequences: add sequence parallelism. If activation memory per layer exceeds budget, set (co-locate with TP on NVLink).
MoE model: add expert parallelism. Choose dividing (number of experts) and adjust downward to keep .
The decision framework is greedy and may not find the globally optimal . In practice, teams run grid searches over a small set of candidate configurations, profiling a handful of iterations on target hardware before committing to full training runs.
Micro-Batch Sizing and Pipeline Fill
The pipeline bubble is the fraction of time that pipeline stages are idle, waiting for the previous stage to finish the forward pass on the first micro-batch, or waiting for backward pass gradients from later stages. For a 1F1B schedule with stages and micro-batches, the bubble fraction is: This is a decreasing function of : more micro-batches reduce the relative overhead of the startup/drain. However, is limited by activation memory: holding micro-batches' activations in flight simultaneously costs bytes per pipeline stage.
Proposition 16 (Minimum Micro-Batch Count for Bounded Bubble).
Let be a tolerated pipeline bubble fraction. Under a 1F1B schedule with pipeline stages, the minimum number of micro-batches required to achieve is:
Proof.
Setting and solving for : Taking the ceiling gives the minimum integer .
Example 20 (GPT-3 Pipeline Configuration).
GPT-3 used pipeline stages. Targeting a bubble fraction of (10% idle time): In practice, Megatron-LM used micro-batches (bubble fraction ), accepting a larger bubble in exchange for lower activation memory. The actual GPT-3 training used a global batch size of 1536 examples with micro-batch size 1, so . This illustrates the fundamental tension: reducing the bubble requires many micro-batches, but many micro-batches require either a large global batch (potentially harming convergence) or tiny per-device micro-batches (reducing GPU utilisation).
Load Balancing in Hybrid Parallelism
A hybrid parallelism configuration is only as fast as its slowest GPU: the pipeline stalls at the slowest stage, and the data-parallel all-reduce stalls at the slowest replica. Two sources of imbalance dominate in practice.
Layer-count imbalance.
If is not divisible by , some stages have layers and others have . The stage with more layers takes longer, stalling the pipeline. Solution: choose , or assign the surplus layer to the first (embedding) stage where embedding lookup is compute-cheap.
MoE token imbalance.
Expert routing is not uniform: popular experts receive more tokens than their capacity, triggering token dropping or load spikes. Standard remedy is an auxiliary load-balancing loss: where is the fraction of tokens routed to expert and is the average router probability for expert . Minimising encourages uniform routing without eliminating specialisation.
The Megatron-LM Recipe for GPT-3
The Megatron-LM system trained GPT-3 (175 billion parameters, 96 layers, , 96 attention heads) on 1024 A100 GPUs arranged in 128 nodes of 8 GPUs each. The configuration was: Each tensor-parallel group of 8 GPUs sat on a single DGX node (NVLink bandwidth 600,GB/s bidirectional). Pipeline stages of 6 layers each were separated by InfiniBand HDR connections. Data-parallel gradient synchronisation used NCCL all-reduce across 8 replicas.
Remark 53 (Why ?).
GPT-3's attention layers have 96 heads. With , each shard holds heads - a clean division. Tensor parallelism beyond 8 would require cross-node NVLink (not available), exposing the all-reduce to InfiniBand latency and bandwidth, degrading efficiency sharply. The node boundary is a hard wall for tensor parallelism.
Achieved MFU (Model FLOPs Utilisation) was approximately 38% - meaning 38% of theoretical peak FLOPs were usefully spent on matrix multiplications. This is typical for models of this scale; the remaining 62% is consumed by memory bandwidth, communication, pipeline bubbles, and non-compute operations (layer norm, activations).
Application: Hybrid Parallel Training of Video Diffusion Models
Modern video generation models such as Sora operate at a scale that would be impossible without hybrid parallelism. A 100-billion-parameter video diffusion transformer with a DiT (Diffusion Transformer) backbone processing 256 frames of pixels at 16 patches per frame produces a sequence of tokens - over 200 times the context length of a standard language model.
Example 21 (Sora-Scale Video Diffusion Parallelism Strategy).
Suppose we have a hypothetical Sora-scale video diffusion model with the following characteristics: 100B parameters, 128 DiT layers, hidden dimension , sequence length (256-frame video, 16 patches per frame, 64 channels). Available hardware: 2048 H100 GPUs in 256 nodes of 8 GPUs.
Step 1 (single GPU fit?): of parameters alone, versus 80,GB per GPU. Clearly not.
Step 2 (tensor parallelism): (full node, NVLink). Per-TP-shard parameter load: . Activation per layer per shard: .
Step 3 (sequence parallelism): Set to co-locate on NVLink. Activation memory reduced 8 to 33,MB per layer shard. Total activation budget per GPU for 128 layers: 4.3,GB.
Step 4 (pipeline parallelism): Remaining budget after parameters and activations: for optimizer states. With ZeRO stage 1, optimizer states . Set (32 layers per stage): optimizer states per GPU manageable.
Step 5 (data parallelism): . Effective batch size at micro-batch , : videos. Pipeline bubble: - acceptable.
Final configuration: , .
This example illustrates how sequence parallelism is not optional for video models: without it, the 262K-token sequence would overflow GPU memory on the very first forward pass. The decision framework naturally leads to 4D parallelism as soon as sequence length exceeds 32K tokens.
Key Idea.
Hybrid parallelism is an optimisation problem: given hardware topology,
model architecture, and memory constraints, find the configuration
subject to .
The decision framework above is a greedy heuristic that finds good
solutions quickly; production systems use auto-tuning tools
(Megatron's launch_config profiler, Microsoft's Tutel)
to search more exhaustively.
Exercises
Exercise 65 (Bubble fraction optimisation).
A model is trained with pipeline stages.
- (a)
Using the 1F1B bubble formula, compute the bubble fraction for micro-batches. Plot as a function of .
- (b)
Suppose activation memory allows at most micro-batches in flight simultaneously. What is the minimum achievable bubble fraction?
- (c)
An engineer proposes using interleaved 1F1B (virtual pipeline stages) with virtual stages per device. Derive the bubble formula for interleaved 1F1B and show that it equals . What is the bubble for , ?
Exercise 66 (Communication cost comparison).
Consider a transformer with layers, , , trained on GPUs.
- (a)
Configuration A: . Compute , (with ), and using , , . (Hint: use formulas from Section 3D Parallelism: Data, Tensor, and Pipeline.)
- (b)
Configuration B: . Repeat.
- (c)
Which configuration has lower total communication cost? Which has a lower pipeline bubble? Is there a clear winner?
Exercise 67 (5D parallelism for MoE).
A sparse MoE model has experts, 32 MoE layers out of total layers, , and is trained on GPUs.
- (a)
Propose a 5D parallelism configuration with .
- (b)
Compute the expert-parallel all-to-all cost per MoE layer using , , and .
- (c)
The auxiliary load-balancing coefficient is set to . Under perfectly uniform routing, show that regardless of .
Fault Tolerance and Elastic Training
Scale brings failure. This is not a pessimistic slogan but a theorem of probability: if each device fails independently with probability per unit time, then the probability that all devices survive a training run of duration is , which decays exponentially in both and . At the scale of 10,000 GPUs trained for 90 days, failures are not exceptional events that interrupt training. They are the normal operating condition around which training is designed.
When Meta trained Llama 3 on 16,384 H100 GPUs, the engineering team reported encountering a hardware or infrastructure issue approximately every three hours on average. When Google trained Gemini Ultra, the paper described complex redundancy mechanisms as a core architectural requirement, not an afterthought. Fault tolerance is not a feature that can be bolted on after the system is designed. It must be load-bearing from the start.
This section develops the theory and practice of fault tolerance in distributed training. We formalise the problem, analyse checkpoint strategies, examine elastic training mechanisms, and study how preemptible cloud instances force a rethinking of training reliability.
Formal Definition of Fault Tolerance
Definition 45 (Fault Tolerance in Distributed Training).
A distributed training system is said to be -fault-tolerant if it can complete a training run to the specified loss target while tolerating up to simultaneous device failures, subject to the following conditions:
Correctness: the model converged by is statistically indistinguishable from one trained on a fully healthy cluster, in the sense that the final loss and downstream metrics differ by at most with probability at least .
Progress: recovery from any -fault event () requires at most seconds of wall-clock time, during which training makes no forward progress.
State consistency: after recovery, all surviving and newly-joined devices hold identical optimizer, parameter, and dataloader states up to floating-point rounding.
The fault tolerance overhead is in expectation over the failure distribution.
Definition 46 (Mean Time Between Failures).
Let be the number of devices in a cluster, each failing independently at rate (failures per device per hour). The cluster-level failure rate is . The mean time between failures (MTBF) of the cluster is If each individual GPU has failures/hour (MTBF hours), then for GPUs: A cluster of 10,000 GPUs experiences a failure every six minutes on average, even with individually reliable hardware.
Log-Scale Reliability Analysis
Let be the probability that a single device fails during a time interval . The probability that all devices survive the full training duration (consisting of intervals) is: Taking and using the identity : The log-survival probability is which is linear in , , and . Doubling any of the three quantities halves the log-survival probability (i.e., squares , pushing it toward zero exponentially faster).
Example 22 (Survival Probability at 10,000 GPUs).
A training run uses H100 GPUs for hours (90 days). Individual GPU MTBF is conservatively estimated at failures/hour (MTBF hours). The probability of completing a 90-day run on 10,000 GPUs without a single device failure is essentially zero. Even with (MTBF = one million hours, far beyond current hardware): Still negligibly small. Fault tolerance is not optional.
Insight.
At 10,000 GPUs, something fails every hour. Fault tolerance is not a feature - it is oxygen. A training system without checkpointing and restart capability will never complete a run at this scale. The question is not whether to handle failures, but how to minimise the time and work lost when they inevitably occur.
Checkpointing: Save State Periodically
The oldest and most reliable fault-tolerance mechanism is periodic checkpointing: save the complete training state to persistent storage at regular intervals, and restart from the most recent checkpoint upon failure.
Definition 47 (Training Checkpoint).
A training checkpoint at iteration is a serialisation of the tuple where are the model parameters, are the optimiser states (first and second moment estimates for Adam), is the random number generator state (PyTorch RNG, CUDA RNG), is the data loader state (which shards and samples have been consumed), and is the learning rate schedule state. A complete checkpoint enables bit-exact resumption of training from iteration .
The checkpoint overhead depends on two quantities: (i) the time to write bytes to persistent storage, and (ii) the frequency of checkpointing. For Adam with bf16 parameters and fp32 optimizer states, bytes (2 bytes for params + 8 bytes for two moment estimates + 4 bytes for master weights + 2 bytes for grad buffer, summed across optimizer shards). For GPT-3 (175B parameters): . Writing 2.8,TB to a distributed filesystem (Lustre, GPFS) at 20,GB/s takes approximately 140 seconds.
Remark 54 (Checkpoint Frequency Trade-off).
Let be the interval between checkpoints (in wall-clock seconds), be the time to write one checkpoint, and be the cluster failure rate. The expected work lost per failure is (on average, failures occur halfway between checkpoints). The expected training overhead from checkpointing is: where the first term is the fractional write overhead and the second term is the expected wasted compute per unit time due to restart. The optimal checkpoint interval minimising (ignoring restart overhead beyond the wasted work) is: This is the classic Daly formula for checkpoint scheduling.
For the GPT-3 example: , . In practice, Megatron checkpoints every 1000 iterations 1 hour, slightly above optimal, accepting marginally more wasted work in exchange for a round checkpoint interval.
Distributed Checkpointing
Na\"ve checkpointing serialises all state through a single
coordinator GPU, which writes to a single file. At 2.8,TB, this is
prohibitively slow. Distributed checkpointing parallelises
the write: each GPU writes its own shard of the checkpoint
simultaneously. With GPUs and total checkpoint size
, the parallel write time is:
where is the per-GPU write bandwidth to the
distributed filesystem. With GPUs writing at 2,GB/s each:
A speedup of more than 100 over serialised writing.
PyTorch's torch.distributed.checkpoint (DCP) and Megatron-LM's
async checkpointing achieve this by writing tensor shards concurrently
using a distributed filesystem with high-bandwidth parallel I/O.
Fault Tolerance Timeline: TikZ Figure
Elastic Training
Elastic training extends fault tolerance beyond simple restart: the system can add or remove workers dynamically during a run, without stopping and reinitialising. This is essential for cloud deployments where spot instances are preempted and new ones become available unpredictably.
Definition 48 (Elastic Training).
A training system supports elastic training with range if:
For any , the system can initialise or reconfigure to workers within seconds.
Reconfiguration preserves training correctness: all workers converge to identical parameter states, and no training sample is lost or duplicated across a reconfiguration event.
The effective batch size and learning rate schedule adapt automatically to the current (linear scaling rule or warmup).
PyTorch Elastic (torchrun), introduced in PyTorch 1.9,
implements elastic training via a rendezvous mechanism: workers
join a rendezvous group managed by a backend (etcd, ZooKeeper,
or a C10d store), elect a coordinator, and re-establish the process
group on each worker join or leave event.
Algorithm 8 (PyTorch Elastic Training Loop).
Initialise: Worker joins rendezvous group with membership in . Wait until and a rendezvous epoch is agreed.
Setup: Elect rank based on join order. Initialise NCCL process group with all workers. Shard the model and data according to current .
Train: Execute forward, backward, and optimiser steps. Checkpoint every seconds.
Monitor: Detect worker failure (via heartbeat timeout) or new worker availability (via rendezvous watcher).
Reconfigure: On membership change, load the latest checkpoint, re-shard model and data to new , adjust learning rate, and restart from step 2.
The rendezvous step is the key novelty: workers do not hard-code a fixed set of peers. They negotiate membership dynamically, allowing the system to gracefully absorb both departures (failures, preemptions) and arrivals (new spot instances becoming available).
Preemption Handling and Spot Instances
Cloud providers (AWS, GCP, Azure) offer preemptible or spot instances at 60–90% discount compared to on-demand pricing, in exchange for the right to reclaim the instance with 2 minutes' notice (AWS Spot) or 30 seconds' notice (GCP Spot). At scale, this transforms the economics of large-model training: a 10,000-GPU training run that would cost $10 million on-demand might cost $1.5–4 million on spot - a savings of $6–8 million on a single training run.
But preemption changes the failure model fundamentally. Unlike hardware failures (sudden, unannounced), preemptions give a notice window: 2 minutes for AWS Spot, up to 60 seconds for GCP preemptible VMs. A preemption-aware system can exploit this window for a graceful checkpoint:
Algorithm 9 (Graceful Preemption Handler).
Register a SIGTERM handler on each worker process.
On SIGTERM receipt: set a global flag
preempt_flag = True.At the next iteration boundary, all workers check
preempt_flag(synchronised via all-reduce on a 1-element tensor).If any worker has the flag set: write a distributed checkpoint, notify the job scheduler, and exit cleanly.
The scheduler relaunches the job with available workers (possibly fewer), loading the graceful checkpoint.
Graceful checkpoints are strictly more efficient than crash checkpoints: the system always writes a fresh checkpoint immediately before exit, minimising lost work to the time between the preemption signal and the checkpoint write (typically seconds).
Remark 55 (Spot instance strategies in practice).
Production deployments using spot instances typically combine three strategies: (1) diverse instance pools: request capacity across multiple availability zones and instance types, reducing correlation between preemptions; (2) on-demand anchor nodes: keep a small fraction (5–10%) of the cluster on on-demand instances to ensure the job always has a legal minimum quorum () for elastic training; (3) checkpoint-on-idle: checkpoint whenever GPU utilisation drops below threshold (a heuristic indicator of an impending preemption or slow network event).
Redundant Computation and Backup Replicas
For systems where checkpoint latency or restart overhead is too large (real-time inference, online fine-tuning with SLAs), a different approach is redundant computation: maintain copies of each computation, such that any copy failures can be tolerated without interruption.
In the context of distributed training, redundant computation typically applies to the data-parallel axis: maintaining one extra data-parallel replica as a hot standby. If any active replica fails, the hot standby takes over its data shard immediately. The overhead is additional parameter memory and additional compute - acceptable for , but prohibitively expensive for .
Remark 56 (Erasure coding for checkpoint compression).
Recent work from DeepMind and others applies Reed-Solomon erasure coding to distributed checkpoints: instead of writing full checkpoint shards, write encoded shards such that any of the shards suffice to reconstruct the full checkpoint. This tolerates storage node failures during the checkpoint write without retrying. The overhead is a factor of in storage and write bandwidth, typically 10–20% for –.
How Large-Scale GenAI Handles Failures: Llama 3 Case Study
The Llama 3 training report provides the most detailed public account of fault tolerance at scale. The training run used 16,384 H100 GPUs for approximately 77 days to train the 405B parameter Llama 3.1 model. Key statistics from the report:
Total observed failures: approximately 466 job interruptions over 54 days of monitored pre-training.
Mean time between interruptions: hours.
Failure categories: 58.7% GPU hardware (HBM memory errors, NVLink faults, CUDA assertion errors), 17.5% unexpected network issues, 12.4% software/library bugs, 11.4% other (power, cooling, firmware).
Recovery time: the team targeted a checkpoint interval of 1000 iterations (approximately 20 minutes). A typical restart from checkpoint required 5–10 minutes.
Effective GPU utilisation: approximately 95.6% despite frequent failures, achieved through rapid automated restart and a diagnostic system that could identify and isolate a faulty GPU within minutes.
The 95.6% effective utilisation figure is remarkable: it implies that the average overhead per interruption was only minutes - including the time to detect the failure, write a checkpoint (if not already available), restart all 16,384 processes, reload model weights, reinitialise the NCCL communication fabric, and resume training. This was achieved through extensive automation: a job management system (internal tooling at Meta) that continuously monitored GPU health metrics, automatically quarantined nodes showing early signs of hardware degradation, and triggered restarts without human intervention.
Insight.
Llama 3 training experienced a hardware or infrastructure failure every 2.8 hours on average across 16,384 GPUs. The ability to recover within 5–10 minutes, automatically and without human intervention, was the difference between a 77-day training run and one that would have required months of manual babysitting - or simply would not have been feasible. Fault tolerance infrastructure is invisible when it works. It is everything when it doesn't.
Automatic Diagnosis and Fault Isolation
Modern large-scale training systems include dedicated diagnostic layers that run concurrently with training:
Pre-training health checks.
Before each restart, the system runs a suite of micro-benchmarks on each GPU: a matrix multiplication throughput test (to detect HBM degradation), an NVLink bandwidth test (to detect interconnect faults), and a peer-to-peer ping-pong test on InfiniBand (to detect network issues). Nodes that fail any check are automatically excluded from the next training group and flagged for replacement.
In-training anomaly detection.
A background process monitors per-GPU metrics: power draw, temperature, memory ECC error counts, and NCCL communication timestamps. Sudden spikes in ECC errors often precede a hard failure by several minutes - catching the warning gives the system time to trigger a graceful checkpoint before the GPU crashes.
Gradient anomaly detection.
Transformer training is numerically fragile: occasional loss spikes (gradient norm exceeding 10 the running average) can destabilise training for thousands of subsequent iterations. A common mitigation is gradient clipping combined with spike rollback: if the loss increases by more than a threshold factor in a single step, roll back to the previous checkpoint and skip the offending batch.
Remark 57 (Silent data corruption).
Perhaps the most insidious failure mode is silent data corruption (SDC): a GPU returns wrong numerical results without raising any error flag. SDC has been observed in multiple large-scale training campaigns and is particularly difficult to detect because the loss may not spike - the corruption simply shifts the model toward a wrong optimum. Detection requires either replicated computation (run each batch twice on different hardware and compare results) or periodic loss consistency checks against a reference compute node. SDC rates are typically – per FLOP, low enough that they are unobservable on a single GPU but aggregate to a non-negligible probability over a run of FLOPs.
Elastic Scaling and Learning Rate Adjustment
When the number of workers changes in an elastic training setup, the effective batch size changes: . To maintain the same training dynamics, the learning rate must be adjusted. The linear scaling rule prescribes: where is the learning rate calibrated for reference worker count . This rule is empirically validated for ; beyond this range, gradient noise dominates and the linear rule overestimates the safe learning rate.
A complementary approach is gradient accumulation: when drops below a threshold, increase the number of gradient accumulation steps proportionally, keeping constant. This sacrifices throughput (fewer weight updates per wall-clock second) but preserves convergence dynamics exactly.
Proposition 17 (Equivalence of Gradient Accumulation and Data Parallelism).
Let denote the gradient of the loss on the -th micro-batch at iteration . Training with data-parallel replicas each processing one micro-batch per step is mathematically equivalent to training with a single worker processing micro-batches with gradient accumulation, in the sense that the accumulated gradient is identical in expectation, provided the micro-batches are drawn i.i.d. from the same data distribution.
Proof.
Under i.i.d. sampling, for all . The all-reduce in data parallelism computes . Gradient accumulation on a single worker computes the same sum sequentially before issuing a weight update. The gradient variance is in both cases. Weight updates and optimiser states are therefore identical.
This equivalence is the theoretical basis for elastic training correctness: reducing and increasing gradient accumulation steps preserves the training trajectory.
Exercises
Exercise 68 (Optimal checkpoint interval).
A training cluster of GPUs trains a 70B-parameter model for days.
- (a)
The model uses BF16 parameters and FP32 Adam states. Compute the checkpoint size in GB.
- (b)
With distributed checkpointing at 2,GB/s per GPU and writers, compute .
- (c)
Individual GPU MTBF is 5000 hours. Compute the cluster-level MTBF and the optimal checkpoint interval using the Daly formula.
- (d)
The actual checkpoint interval is rounded to the nearest 1000 iterations (each iteration takes 8 seconds). What is the actual checkpoint interval in minutes? Compute the resulting bubble fraction (fraction of expected wasted work due to restart) assuming restart takes 5 minutes.
Exercise 69 (Survival probability and fault tolerance level).
- (a)
Compute for , assuming failures per GPU per hour. Express answers in scientific notation.
- (b)
For the largest case, what individual GPU MTBF (i.e., in hours) would be required to achieve ?
- (c)
A system claims to be fault-tolerant via redundant data-parallel replicas. If each GPU still fails independently with rate , derive the probability that the system experiences an unrecoverable failure (i.e., three or more GPUs from the same model replica fail simultaneously within a recovery window seconds) during a 30-day run.
Exercise 70 (Elastic training and learning rate scheduling).
A training run starts with workers, but due to spot preemptions drops to after 10% of training, then recovers to after 20% of training.
- (a)
Using the linear scaling rule with reference at , compute at and .
- (b)
An alternative approach maintains constant by increasing gradient accumulation steps. Compute the gradient accumulation steps required at and .
- (c)
Compare the two approaches: which produces faster wall-clock training at ? Which preserves convergence dynamics more faithfully? Justify your answer using Proposition Proposition 17.
Open Problems and Future Directions
The preceding twenty-four sections have built a comprehensive treatment of distributed training for generative models: from the alpha-beta latency model and collective communication primitives, through data, tensor, pipeline, and sequence parallelism, to ZeRO-based optimizer sharding, mixed-precision numerics, fault tolerance, and the special demands imposed by diffusion networks and autoregressive transformers. Yet every synthesis chapter is also a catalogue of what remains unknown, and the distributed systems frontier for large-scale generative modelling is unusually rich in hard open problems.
This section enumerates ten open problems that collectively define the research agenda for the next decade. Each problem is stated with enough mathematical precision to ground a doctoral dissertation or a multi-year systems project. Where connections to adjacent theory are known, they are made explicit; where the problem is genuinely opaque, that opacity is stated honestly rather than papered over with optimistic conjecture. The section closes with a formal conjecture on communication complexity lower bounds and a call to action addressed to AI researchers who have not yet recognized distributed systems as a core competency.
Open Problem 1: Communication-Optimal Hybrid Parallelism Search
Problem 1 (Hybrid Parallelism Configuration Search).
Given a transformer model with layers, attention heads, hidden dimension , and a cluster of accelerators interconnected by a network topology , find the hybrid parallelism configuration specifying degrees of data, tensor, pipeline, and sequence parallelism such that total training time per step is minimized subject to the constraint that peak memory per device does not exceed the device capacity .
The search space for hybrid parallelism is enormous even for modest cluster sizes. A cluster of GPUs admits configurations ranging from pure data parallelism () through pure pipeline parallelism () and every combinatorial product in between, constrained only by divisibility requirements and the network topology. Empirically, practitioners explore this space by hand, relying on heuristics and hardware vendor guidelines that may be several hardware generations stale.
Formal complexity.
The decision variant of the problem - does there exist a configuration achieving step time with peak memory - has not been proved NP-hard, but reduction arguments from bin-packing and scheduling strongly suggest it. Specifically, consider the subproblem of choosing a pipeline depth that minimizes bubble overhead while keeping the inter-stage activation memory below . This is equivalent to a weighted job-scheduling problem on uniform machines with release times determined by the forward-pass latency profile, which is NP-hard in general.
Approximation algorithms.
No constant-factor approximation algorithm is known for the full hybrid search problem. Current approaches include:
Dynamic programming on layer graphs. Alpa and FlexFlow enumerate pipeline stagings via DP over layer-graph partitions, achieving polynomial time in but exponential in (tensor parallelism degree) unless the search space is pruned aggressively.
Integer linear programming. Several groups have formulated the memory and bandwidth constraints as ILP and called commercial solvers. Scalability beyond is a persistent obstacle.
Reinforcement learning. Policy gradient methods over a discrete configuration space have been applied with moderate success on fixed hardware, but transfer to new topologies is poor.
Key Idea.
The hybrid parallelism search problem is best understood as a joint optimization over computation graphs and communication schedules. Progress requires bringing the theory of graph partitioning and online scheduling into direct contact with empirical performance models of real interconnects. Neither theory alone nor empirical search alone will suffice.
An important open subproblem is whether the optimal configuration varies significantly during training as gradient statistics change and batch size scheduling adapts. Dynamic reconfiguration - the ability to switch parallelism strategies mid-run without restarting - is discussed further in Open Problem 3.
Open Problem 2: Communication-Avoiding Attention Mechanisms
Problem 2 (Sublinear-Communication Self-Attention).
Design a distributed self-attention mechanism for sequences of length on devices such that the inter-device communication volume scales as per layer while the output approximates the exact softmax attention output to precision in norm.
Ring attention achieves communication per layer per device, which is optimal for exact attention under the model of full key-value sharing across the ring. The question is whether approximations to attention can be computed with strictly less communication.
Connection to sketching.
Randomized matrix sketching offers a promising starting point. If the attention matrix admits an -low-rank approximation of rank , then it is theoretically possible to communicate only values per device per layer rather than . For long sequences () this represents an asymptotic saving. The difficulty is that the attention matrix is sequence-dependent: its rank structure changes with each forward pass, making a fixed sketch basis inapplicable.
Local attention and sparse patterns.
Sliding-window attention (Longformer), dilated patterns (BigBird), and learned sparsity patterns all reduce the computation of attention but have been less systematically analyzed for their impact on distributed communication. In a ring-based distributed setting, sparse attention patterns can create load imbalance: a device holding a window boundary must communicate with both neighbors, while interior devices communicate only with one.
Remark 58 (Beyond Ring Topology).
Ring attention inherits the communication structure of ring all-reduce. An alternative based on butterfly networks - the underlying topology of FFT algorithms - could achieve latency-optimal attention with bandwidth, matching ring attention bandwidth but offering lower latency for large . Whether this trade-off is favorable depends on the relative magnitudes of (latency per message) and (reciprocal bandwidth) in the target cluster.
Insight.
Communication-avoiding attention is ultimately a question about the information content of keys and values: how much of the attention output for a query residing on device can be computed using only the keys and values already stored on ? For models trained on natural language, empirical evidence suggests that most attention mass falls within a radius of a few thousand tokens of each query, which gives hope that locality-exploiting communication patterns can be made both communication-efficient and close to exact.
Open Problem 3: Adaptive Topology for Dynamic Workloads
Problem 3 (Online Topology Reconfiguration).
Develop a protocol by which a distributed training job running on devices can reconfigure its logical communication topology - including collective group memberships, pipeline stage assignments, and tensor parallelism groups - without pausing training for more than one gradient step, without loss of optimizer state, and with provable convergence guarantees under topology switches.
The motivation for adaptive topology is twofold. First, as training progresses, the compute-to-communication ratio changes: early training with large learning rates sees significant gradient variance, making frequent synchronization beneficial; late training with small learning rates and near-convergence gradients can tolerate local SGD with large (infrequent synchronization). Second, heterogeneous clusters (Open Problem 9) see time-varying device availability as nodes fail, are preempted, or are added mid-run, requiring the logical topology to evolve in response.
Technical obstacles.
The primary technical obstacle is collective reconfiguration atomicity. When a ring all-reduce collective group is restructured - say, by adding a new device - all participants must agree on the new ring ordering before the next collective begins. Coordinating this agreement while gradients are being computed on other layers requires a distributed consensus protocol. Off-the-shelf consensus (Paxos, Raft) incurs message complexity per reconfiguration, which may dominate training time if reconfigurations are frequent.
Optimizer state migration.
ZeRO-3 shards optimizer state across devices. If the device count changes from to , the optimizer state must be re-sharded: device had responsibility for parameters and must transfer residual parameters to their new responsible devices. This is equivalent to a distributed repartition operation whose communication cost is regardless of how cleverly it is scheduled.
Key Idea.
Adaptive topology should be understood as a control plane operating above the training data plane. The key design principle is to decouple topology decisions (which happen on the timescale of hundreds of steps) from gradient synchronization (which happens every step), using a lightweight reconfiguration protocol that pipelines topology negotiation with ongoing gradient computation.
Open Problem 4: FP4/FP8 Distributed Training Stability
Problem 4 (Precision Floor for Distributed Training).
Characterize the minimum floating-point precision such that a distributed training algorithm for an -parameter generative model converges to the same loss basin as full-precision (FP32) training, with a sample complexity penalty of at most a constant factor, when gradient communication and optimizer state are also stored in bits.
FP8 training is now practical for many transformer architectures, driven by hardware support in NVIDIA H100 and H200 GPUs and by careful scaling of per-tensor quantization ranges. FP4 remains largely experimental. The distributed setting introduces additional stability concerns beyond those of single-device low-precision training:
Quantization error accumulation across devices. When devices each quantize their local gradient to bits before an all-reduce, the quantization noise adds constructively in the worst case. The expected noise magnitude scales as before the averaging step, suggesting that as grows, more bits are needed to maintain the same effective gradient signal-to-noise ratio.
Loss scaling divergence. Dynamic loss scaling adjusts the scaling factor upward when no overflow is detected and downward on overflow. In a distributed setting, overflow detection must be aggregated across all devices: a single device experiencing overflow must cause all devices to roll back. At FP4 precision, overflow events become frequent enough that rollback frequency may dominate training throughput.
Optimizer state precision. Adam's second moment estimator requires sufficient dynamic range to track gradient magnitudes across several orders of magnitude. FP8 with 5 exponent bits may be adequate; FP4 formats proposed in the literature allocate only 2 exponent bits, reducing the representable range to a factor of 16, which is inadequate for typical gradient distributions in deep networks.
Remark 59 (Stochastic Rounding and Distributed Bias).
Stochastic rounding provides an unbiased quantization scheme in expectation for a single device. In a distributed all-reduce, the stochastic rounding operations on different devices are independent, so the aggregated error after averaging gradients has variance , improving with . This suggests that large-scale distributed training may actually be more robust to low precision than single-device training, provided that the all-reduce accumulates in higher precision.
Open Problem 5: Cross-Datacenter Diffusion Training
Problem 5 (WAN-Optimized Score Function Composition).
Design a distributed diffusion model training protocol for a cluster spanning two or more geographically separated datacenters, where inter-datacenter bandwidth is two to three orders of magnitude lower than intra-datacenter bandwidth, such that model quality degradation relative to a single-datacenter baseline is less than in FID on a standard benchmark, with no increase in wall-clock time per sample throughput.
Intra-datacenter interconnects (NVLink, InfiniBand HDR, or RoCE) provide bandwidths of 400 Gb/s to 3.2 Tb/s per device. Cross-WAN links between datacenters typically provide 1–100 Gb/s aggregate, shared among all traffic. The bandwidth ratio is to , making naive gradient synchronization across datacenters impractical: a single all-reduce of a 70B model's gradients (280 GB at FP16) would occupy a 10 Gb/s inter-datacenter link for over three minutes, while a single training step takes milliseconds.
Score composition perspective.
Diffusion models offer a unique opportunity relative to other architectures: the score function is the fundamental object being trained, and score functions from different model replicas can be composed via product-of-experts or mixture-of-scores formulations without exact gradient averaging. This suggests a federated training protocol where each datacenter trains a local score network and inter-datacenter communication consists only of compressed score difference signals rather than full gradient tensors.
Open sub-questions.
The following are open:
Can score composition maintain FID parity with gradient averaging, and if not, what is the FID penalty as a function of inter-datacenter bandwidth?
Does the diffusion time step affect the optimal inter-datacenter communication frequency? Score estimates at large (high noise) have lower effective dimensionality and may be compressible to lower bit-widths than estimates at small .
How do data distribution differences between datacenters (arising from data sovereignty and regional data retention policies) affect score composition?
Key Idea.
Cross-datacenter diffusion training should exploit the compositional structure of score functions rather than treating the problem as raw gradient synchronization. The diffusion framework's separation of noise levels provides a natural curriculum for bandwidth allocation: communicate more frequently at large (cheap, high noise) and less frequently at small (expensive, low noise).
Open Problem 6: Energy-Efficient Distributed Training
Problem 6 (Carbon-Optimal Training Protocol).
Given a training budget measured in total floating-point operations , a cluster with per-device power draw and associated carbon intensity (gCOeq/kWh, varying with time as the grid energy mix changes), and a target model quality , design an adaptive training protocol that achieves while minimizing subject to the constraint that wall-clock training time does not exceed a deadline .
Training large generative models consumes extraordinary amounts of energy. Published estimates for frontier models range from MWh for 7B-parameter models to MWh for models at the 500B+ scale, corresponding to carbon emissions comparable to hundreds of transatlantic flights. The distributed systems community has largely treated energy consumption as a secondary concern, optimizing for throughput and treating power draw as a fixed hardware characteristic.
Carbon-aware scheduling.
The carbon intensity of electrical grids varies dramatically by time and location. In regions with high renewable penetration, the marginal carbon intensity during midday solar peaks can be one-fifth of the overnight baseline. A training job that can defer communication-heavy phases to low-carbon periods and accelerate compute during high-carbon periods (by using fewer devices and reducing synchronization overhead) could reduce carbon emissions without extending wall-clock time.
The speed-efficiency trade-off.
A critical tension exists between hardware utilization (which maximizes throughput per device-hour) and energy efficiency (which favors moderate utilization at a lower voltage-frequency operating point). Modern GPUs consume approximately of peak power at utilization but of peak power at utilization, making the throughput-per-watt curve concave. Jointly optimizing throughput and energy efficiency requires operating at the knee of this curve, which in a distributed setting means coordinating frequency scaling across all participating devices.
Insight.
Energy-efficient distributed training requires rethinking the basic metric of progress. Rather than minimizing wall-clock time to a target loss, the natural objective for climate-constrained deployment is minimizing carbon per unit of model capability improvement. This shifts attention toward sample efficiency methods - curriculum learning, importance sampling, and knowledge distillation - that reduce the required number of training iterations rather than merely accelerating each iteration.
Open Problem 7: Provably Communication-Optimal Distributed Auto-Differentiation
Problem 7 (Optimal Communication Schedules for Reverse-Mode AD).
For a given computational graph and device assignment , compute the gradient communication schedule - specifying which tensors to send, when to send them, and along which physical network paths - that minimizes total communication volume while producing gradients that are bit-for-bit identical to those produced by single-device reverse-mode automatic differentiation.
Reverse-mode automatic differentiation (backpropagation) requires materializing activations from the forward pass for use during the backward pass. In a distributed setting where the forward pass spans multiple devices, activations produced on device that are consumed by an operation on device must be communicated twice: once during the forward pass (from to ) and once during the backward pass (from back to as part of the gradient computation). The total activation communication volume is thus at least twice the forward communication volume.
Checkpointing and recomputation.
Gradient checkpointing can eliminate some backward communication by recomputing activations on the originating device rather than storing and re-transferring them. The trade-off is compute: recomputing activations costs additional forward-pass operations. The optimal checkpoint placement in a distributed setting is an open problem: it depends on the relative costs of computation and communication, which vary by layer type, tensor size, and network topology.
Graph-theoretic formulation.
The problem can be formulated as a minimum-cut problem on the communication graph of the reverse-mode computational graph, but the minimum cut must be computed subject to constraints on peak device memory, which couples the cut structure to the recomputation schedule in a way that makes the joint optimization NP-hard via reduction from the minimum-memory register allocation problem.
Remark 60 (Connection to Tensor Programs).
Recent work on tensor program compilation (XLA, TVM, Triton) has automated the placement of operations within a single device. Extending these frameworks to automatically discover communication-optimal gradient schedules across devices is a natural but technically demanding extension, requiring the compiler to reason about both memory hierarchies and network latency models simultaneously.
Open Problem 8: Self-Healing Distributed Training
Problem 8 (Checkpoint-Free Fault Recovery).
Design a distributed training protocol for -device clusters in which the failure of any devices is automatically detected and recovered within one training step, without reverting to a saved checkpoint, without halting the surviving devices, and without degrading final model quality relative to a fault-free baseline.
Current production training systems handle device failures by reverting to the most recent checkpoint, restarting on the surviving devices, and resuming training. For large clusters with mean-time-between-failures of a few hours, checkpoint interval is typically 15–30 minutes, meaning up to 30 minutes of computation is wasted per failure event. At clusters of GPUs, failure rates of one device per hour are observed in practice, making checkpoint-restart the dominant overhead in long training runs.
Erasure coding approaches.
An alternative to checkpointing is to encode the training state redundantly across devices so that any -of- devices can reconstruct the full state. Maximum-distance-separable (MDS) codes provide the optimal redundancy-recovery trade-off: devices can reconstruct from any survivors. The challenge is that the training state - model parameters, optimizer state, and gradient accumulators - must be encoded in a form compatible with ongoing gradient updates. Naive MDS encoding of floating-point tensors supports full reconstruction but is incompatible with in-place gradient updates on the coded data.
Byzantine fault tolerance.
If some of the failed devices are Byzantine - sending corrupted rather than no data - the problem is harder. Byzantine-robust aggregation rules (coordinate-wise median, trimmed mean, Krum) provide convergence guarantees under Byzantine failures but at the cost of increased communication and reduced aggregation accuracy. For diffusion model training, where gradient noise is already large, the additional noise from Byzantine-robust aggregation may be tolerable at the cost of a modest increase in training steps.
Key Idea.
Self-healing distributed training requires shifting from a stop-and-recover paradigm to a degrade-gracefully paradigm. Rather than treating any device failure as a training- halting event, the system should reduce the effective batch size and pipeline width automatically, maintain training momentum with the surviving devices, and reintegrate recovered or replacement devices asynchronously as they become available.
Open Problem 9: Heterogeneous Accelerator Clusters
Problem 9 (Optimal Load Balancing in Heterogeneous Clusters).
Given a cluster comprising GPUs of type , TPUs of type , and custom ASICs of type , each with distinct peak FLOP/s, memory capacity, memory bandwidth, and inter-device interconnect characteristics, design a training protocol for an -parameter model that achieves a throughput within a constant factor of the optimal homogeneous cluster of equivalent total compute, with provable load balance guarantees.
Cloud providers increasingly offer heterogeneous accelerator environments: a customer may provision a mixture of NVIDIA H100s, Google TPU v5es, and vendor-specific inference ASICs within a single virtual cluster. On-premises clusters at research labs frequently contain multiple generations of hardware as older devices are supplemented rather than replaced.
The stragglers amplification problem.
In synchronous data parallelism, all-reduce waits for the slowest device to complete its forward and backward passes before aggregating gradients. A heterogeneous cluster containing even a single slow device (a straggler) causes all fast devices to idle. If the slowest device completes in time and the fastest in , the throughput overhead is per step, which can exceed for heterogeneous clusters spanning two hardware generations.
Model parallelism as a solution.
Pipeline and tensor parallelism offer partial remedies: slow devices can be assigned fewer layers (pipeline) or narrower tensor slices (tensor parallelism) to equalize per-device compute time. The assignment problem - how to partition the model across heterogeneous devices to equalize step time - is a weighted bin-packing variant that is NP-hard in general but admits PTAS for fixed device types.
Insight.
Heterogeneous cluster management is as much an economics problem as a systems problem. The optimal strategy for a research lab is often not to solve the load-balancing problem but to avoid it entirely: quarantine legacy hardware for inference and data preprocessing, using only the fastest homogeneous set of devices for training. The open problem is important for cloud environments where quarantining is not economically feasible.
Open Problem 10: Communication Complexity Lower Bounds for Generative Model Training
Problem 10 (Communication Lower Bound for Gradient-Based Training).
Prove or disprove the following: any distributed stochastic gradient descent algorithm for minimizing an -smooth, -strongly convex loss over an -parameter model on devices must communicate at least bits per device per optimization step in the worst case over loss functions in this class and data distributions consistent with achieving -accuracy in gradient estimation.
Communication complexity lower bounds for distributed optimization are substantially less developed than for distributed computing generally. The classical results of Kushilevitz and Nisan apply to decision problems rather than continuous optimization, and the reduction from optimization to communication complexity requires careful handling of approximation.
Known partial results.
For the special case of linear models, it is known that any protocol that computes the exact gradient of the squared loss must communicate bits per step, since the gradient encodes the inner product of the data matrix with the residual vector. For nonlinear models, the gradient computation has no such exact communication lower bound, because approximate gradients (as in stochastic gradient descent on minibatches) can be computed from local data without any cross-device communication.
Approximate computation lower bounds.
The meaningful lower bound for distributed SGD is not for exact gradient computation but for approximate gradient computation to a specified statistical quality. Specifically, if the algorithm produces a gradient estimate satisfying , what is the minimum number of bits that must be communicated per device? This is related to the rate-distortion theory of gradient compression, where the distortion measure is the mean squared gradient error.
Conjecture 1 (Communication Lower Bound).
Any distributed stochastic gradient descent algorithm for training an -parameter generative model on devices such that the per-step gradient estimation error satisfies (matching the statistical quality of single-device mini-batch gradient estimation) requires at least bits of inter-device communication per step, per device.
This conjecture would imply that all existing communication compression methods (1-bit Adam, TopK sparsification, QSGD) are within a constant factor of optimal, and that no fundamentally new compression paradigm can break the barrier. Proving or disproving the conjecture requires new information-theoretic tools that bridge rate-distortion theory and stochastic optimization.
Research Frontier Map
The ten open problems above span a range of difficulty and time horizon. Figure fig:distgen:frontier positions them on two axes: the degree of communication reduction sought (horizontal) and the model fidelity that must be maintained (vertical). Problems in the upper-right quadrant demand both high compression and high fidelity and are correspondingly the hardest.
Research Challenge Specifications
The following three research challenges provide structured entry points for graduate students and practitioners beginning work in this area. Each challenge is specified with a concrete problem statement, a success criterion, and a suggested starting-point literature.
Research 1 (Challenge A: Gradient Compression with Convergence Guarantees).
Problem. Develop a gradient compression scheme for distributed data-parallel training of diffusion models that compresses each gradient tensor to bits () before all-reduce, with the following properties: (a) the decompressed gradient is an unbiased estimator of the true gradient, (b) the compression error variance satisfies for a compression factor , and (c) the training loss converges at rate where is the number of steps.
Success criterion. A scheme achieving bits with and at most FID degradation on ImageNet relative to FP32 gradient training, with wall-clock speedup of at least on a 4-GPU cluster.
Starting points. Alistarh et al. (QSGD), Stich et al. (error feedback), Karimireddy et al. (EF21), and the 1-bit Adam literature. The diffusion-specific challenge is that score matching objectives produce gradient distributions that are heavy-tailed at small noise levels , which standard compression schemes handle poorly.
Research 2 (Challenge B: Topology-Aware Pipeline Scheduling for Diffusion Models).
Problem. The 1F1B pipeline schedule was designed for models where each micro-batch makes a single forward and backward pass. Diffusion models require forward passes at multiple noise levels during inference (DDPM: 1000 steps; DDIM: 50 steps), but training requires only a single forward-backward pair per sample (the score matching objective is a simple mean-squared error). The question is whether a modified pipeline schedule, exploiting the multi-scale temporal structure of diffusion training (different noise levels produce gradients of different magnitudes and sparsities), can reduce pipeline bubbles below the bound of standard 1F1B.
Success criterion. A scheduling algorithm that achieves at most of the bubble fraction of standard 1F1B for a 4-stage pipeline with 8 micro-batches, validated on a latent diffusion model training run reaching the same FID in fewer GPU-hours.
Key insight to exploit. Micro-batches with large noise levels produce smaller activations (the input is mostly noise) and can be processed faster. Interleaving large- and small- micro-batches may reduce pipeline stalls without changing the expected gradient.
Research 3 (Challenge C: Memory-Efficient ZeRO for Diffusion VAE Training).
Problem. Latent diffusion models (Stable Diffusion, FLUX) require training both a VAE (encoder-decoder) and a diffusion backbone (U-Net or DiT). The VAE encoder must process full-resolution images ( or higher), generating very large intermediate activation tensors. ZeRO-3 as currently specified shards parameters and optimizer states but does not shard activation tensors. Design a ZeRO extension that shards VAE encoder activations across the data-parallel group during the encoding step, communicates only the latent code to the diffusion backbone, and reconstructs gradients correctly during the backward pass.
Success criterion. A protocol that reduces peak memory per GPU by at least relative to ZeRO-2 for joint VAE and diffusion backbone training at resolution with a batch size of 8 per GPU, without increasing gradient error relative to full-precision ZeRO-2.
Key challenge. The VAE encoder activation tensors at resolution may be several gigabytes per sample. Sharding these tensors requires partitioning the spatial dimensions of the feature maps across devices, which introduces boundary artifacts in convolutional layers unless the spatial partition includes appropriate overlap regions.
The Systems Research Call to Action
Key Idea.
Understanding distributed systems is a superpower for AI researchers.
This is not a rhetorical claim. It is an empirical observation from the history of the field: nearly every step change in the scale of generative modelling has been preceded by a step change in distributed systems capability. The shift from single-GPU training to data-parallel training enabled the ImageNet models of 2012. The development of model parallelism and high-speed interconnects enabled the GPT-scale language models of 2019–2020. Ring attention enabled sequence lengths beyond the practical limit of single-device memory, unlocking long-context reasoning. ZeRO-3 eliminated the memory bottleneck that would otherwise have capped model scale at the capacity of a single accelerator.
In each case, the distributed systems insight was not a minor engineering optimization layered atop the machine learning advance. It was the machine learning advance: without the systems capability, the model did not exist, and the research question could not be posed.
Practical implications for graduate students.
A graduate student who understands only the machine learning literature but not the systems literature is constrained to work on problems that can be explored on a single GPU or a small cluster managed entirely by existing frameworks. A student who also understands collective communication, memory hierarchy, and distributed auto-differentiation can:
Identify scale-dependent phenomena (emergent capabilities, grokking, phase transitions) that are invisible at small scale and design experiments to study them systematically.
Propose algorithmic improvements that are only beneficial at large scale, where communication costs dominate and a reduction in bandwidth saves more wall-clock time than a reduction in FLOPs.
Debug training instabilities whose root cause is in the distributed system (gradient accumulation rounding errors, pipeline bubble-induced batch size variation, ZeRO-3 gradient dequantization artifacts) rather than in the model architecture.
Collaborate with systems engineers on an equal footing, rather than treating the distributed training infrastructure as a black box.
Insight.
The open problems enumerated in this section are not waiting for new mathematical ideas. Most of them are waiting for researchers who are fluent in both the language of machine learning and the language of distributed systems. That fluency is a choice, and it is more accessible than it may appear: the core concepts - latency, bandwidth, collective primitives, memory hierarchy - can be understood deeply with a few weeks of focused study. The payoff, measured in research impact, is disproportionately large.
Comprehensive Exercises and Research Challenges
The exercises in this section are organized in three tiers. The first tier (Exercises 1–5) covers the foundational performance models introduced in the early sections of this chapter: the alpha-beta latency model, ring all-reduce, and network topology analysis. The second tier (Exercises 6–10) addresses parallelism strategies and memory optimization. The third tier (Exercises 11–15) treats advanced topics including mixed-precision numerics, pipeline scheduling for diffusion models, ring attention, distributed auto-differentiation, and fault tolerance. The section closes with five research challenges requiring original design and implementation.
Tier 1: Foundational Performance Models
Exercise 71 (Alpha-Beta All-Reduce Time for Large Models).
The alpha-beta model predicts that a ring all-reduce of a message of size bytes across devices takes time where is the per-hop latency (seconds per message initiation) and is the reciprocal bandwidth (seconds per byte).
For a cluster with and :
- (a)
Compute for a 1B-parameter model (4 GB gradient tensor at FP32) on GPUs.
- (b)
Repeat for a 7B-parameter model (28 GB at FP32) on GPUs, and for a 70B-parameter model (280 GB at FP32) on GPUs.
- (c)
For each configuration, compute the ratio , where a single forward-backward step takes approximately seconds per billion parameters per GPU at peak FLOP utilization. Comment on whether communication dominates compute in each case.
- (d)
FP16 gradients halve . What is the bandwidth savings? Does the savings depend on ?
Answer sketch. (a) bytes, : . Step time (per GPU; dominated by communication at ). (b–d) Follow similarly; the latency term is negligible compared to the bandwidth term for all cases above .
Exercise 72 (Ring All-Reduce: Step-by-Step Trace for 4 GPUs).
Consider 4 GPUs arranged in a ring: GPU 0 – GPU 1 – GPU 2 – GPU 3 – GPU 0. Each GPU holds a gradient vector of 4 scalar elements: GPU holds . The goal is to compute the element-wise sum on all GPUs.
- (a)
Trace the reduce-scatter phase step by step. At each of the 3 steps, state which chunk each GPU sends, which chunk it receives, and which chunk it has fully reduced after receiving. Use the initial values (so GPU 0 has , GPU 1 has , etc.).
- (b)
Trace the all-gather phase step by step. State which reduced chunk each GPU sends and which it receives at each step.
- (c)
After both phases, verify that every GPU holds the correct sum for all .
- (d)
How many bytes are transferred per GPU in total (reduce-scatter + all-gather) if each scalar is 4 bytes? Express in terms of the message size (total bytes of the gradient vector).
Answer sketch. Each GPU sends bytes per step, for steps in reduce-scatter and 3 steps in all-gather, total bytes sent per GPU. Combined with receive, each GPU sends and receives bytes for a total of bytes transferred per GPU endpoint. Verify sums: , , , .
Exercise 73 (Fat-Tree vs. Torus: Bisection Bandwidth for 64 Nodes).
Consider 64 compute nodes arranged in two candidate network topologies.
Topology A (Fat-tree): A 3-level fat-tree with branching factor . At each level, every uplink has bandwidth : level 1 (edge to aggregation) , level 2 (aggregation to core) , level 3 (core) provides full-bisection bandwidth.
Topology B (3D Torus): A -node 3D torus where each link has bandwidth . The bisection cut divides the torus into two halves along one dimension.
- (a)
Compute the bisection bandwidth of the fat-tree. (Hint: the bisection cut passes through the core switches. Count the number of links crossing the cut.)
- (b)
Compute the bisection bandwidth of the 3D torus. (Hint: bisecting along one dimension cuts links in each direction, but the torus wraps, so the bisection cut has links.)
- (c)
Which topology provides higher bisection bandwidth? Which provides lower hop count between arbitrary node pairs?
- (d)
An all-reduce of of gradient data runs on both topologies. Assuming bisection bandwidth limits the all-reduce throughput, compute the minimum time for the all-reduce in each case.
- (e)
For what workloads would you prefer the torus over the fat-tree despite lower bisection bandwidth?
Answer sketch. (a) Fat-tree: at level 3 there are uplinks from aggregation to core on each side; bisection bandwidth is . (b) Torus bisection: links . Interestingly, both achieve the same bisection bandwidth for this configuration; the fat-tree advantage manifests at higher radix. (d) .
Exercise 74 (MPI Pseudocode for Distributed Gradient Averaging).
Write detailed pseudocode for a distributed data-parallel training step using MPI-style collective communication. The pseudocode should:
- (a)
Initialize a model with parameters on a Root process (rank 0) and broadcast to all workers.
- (b)
Each worker samples a minibatch of size , computes the local loss , and computes the local gradient .
- (c)
Perform an
AllReduceto compute the globally averaged gradient . - (d)
Each worker updates using the averaged gradient.
- (e)
Extend the pseudocode to handle gradient accumulation with micro-batches per step, where the local gradient is accumulated before the AllReduce.
Note.
The pseudocode should use the following MPI-style primitives:
MPI_Bcast(buf, root),
MPI_AllReduce(sendbuf, recvbuf, op=SUM),
MPI_Barrier().
Specify the effective batch size seen by the optimizer after step (d).
Exercise 75 (Communication Hiding: Overlap Efficiency Computation).
A 6-layer transformer is trained on GPUs using data parallelism with bucketed gradient all-reduce. The backward pass and all-reduce are overlapped: as the gradient of layer finishes computing, its all-reduce is launched asynchronously.
The per-layer backward compute times are (in ms): (layer 6 to layer 1, i.e., last to first in backward order). The per-layer all-reduce times are (in ms): (same ordering).
- (a)
Compute the sequential time: backward compute time summed over all layers, then all-reduce time summed over all layers.
- (b)
Compute the overlapped time assuming that each layer's all-reduce runs concurrently with the backward pass of subsequent layers, and that the final layer's all-reduce adds to the total only if it finishes after all backward compute.
- (c)
Define overlap efficiency as , where is the communication time successfully hidden. Compute for this configuration.
- (d)
Which layer is the bottleneck for overlap, and why?
- (e)
How would bucket sizing affect ? Is it better to use one large bucket or many small buckets?
Answer sketch. Sequential time: compute, AR, total . Overlapped: layer 6 AR (3ms) overlaps with layer 5 backward (6ms), so hidden. Layer 5 AR (2ms) overlaps with layer 4 backward (10ms). Layer 4 AR (4ms) overlaps with layers 3+2+1 backward total , fully hidden. Layer 3 AR (2ms), layer 2 AR (5ms), layer 1 AR (3ms) overlap with subsequent forward startup or are the tail. Total overlapped time (only first AR not hidden), , .
Tier 2: Parallelism Strategies and Memory Optimization
Exercise 76 (Local SGD Convergence Analysis).
In local SGD, each of workers performs local gradient steps between synchronizations. The theoretical convergence bound for a smooth, nonconvex objective is where are constants depending on smoothness, is the learning rate, is a bound on the gradient norm, and is the total number of local steps.
- (a)
For (standard synchronous SGD), , , , and , find the minimum such that the convergence bound is below .
- (b)
For and with the same parameters, find the minimum and the dominant term in the bound.
- (c)
The communication cost is proportional to (one synchronization every steps). For each of , compute the total communication volume as a multiple of the baseline, assuming is set to the minimum value from (a) and (b).
- (d)
Comment on the practical implications for diffusion model training, where gradient noise is large at high noise levels and small at low noise levels. Should vary with the diffusion time step during training?
Exercise 77 (Data Parallelism: Effective Batch Size and Learning Rate Scaling).
A diffusion model is trained on a single GPU with batch size and learning rate . The training is scaled to GPUs using synchronous data parallelism.
- (a)
Compute the effective batch size under the assumption that each GPU processes samples per step.
- (b)
Apply the linear scaling rule: set the new learning rate . What is ?
- (c)
Apply the square-root scaling rule: set . What is ? Under what conditions is square-root scaling preferred to linear scaling?
- (d)
In diffusion model training, the loss at noise level is weighted by . This weighting makes the effective gradient variance depend on . Explain qualitatively how this affects the choice of the scaling rule and the warm-up schedule for the learning rate.
- (e)
Training with is known to exhibit gradient noise scale for the baseline model, where is the gradient covariance. Should the practitioner use linear or square-root scaling? Justify.
Exercise 78 (Tensor Parallelism: Memory Savings for a Transformer Layer).
A transformer layer has hidden dimension and intermediate dimension (standard 4x feedforward expansion). The layer is tensor-parallelized across GPUs.
- (a)
Compute the parameter count of the feedforward sublayer (two linear projections: and ). What is the memory usage in GB at FP16?
- (b)
With column-parallel tensor parallelism for the first linear ( per GPU) and row-parallel for the second ( per GPU), compute the parameter memory per GPU. What is the memory savings factor?
- (c)
Compute the activation memory for a forward pass with batch size and sequence length for: (i) the un-parallelized layer, and (ii) the -way tensor- parallel layer.
- (d)
The tensor-parallel feedforward requires an
AllReduceafter the row-parallel projection. Compute the communication volume per device (in GB) for the parameters above. - (e)
Compute the arithmetic intensity (FLOPs per byte of communication) for the tensor-parallel feedforward layer. Is this workload compute-bound or communication-bound on a cluster with interconnect?
Exercise 79 (Pipeline Parallelism: Bubble Fraction for GPipe vs. 1F1B).
A model is split across pipeline stages with micro-batches per batch.
- (a)
The GPipe bubble fraction is . Compute this for with . At what value of does the bubble fraction drop below ?
- (b)
The 1F1B schedule has the same asymptotic bubble fraction but with peak activation memory equal to micro-batches rather than for GPipe. For and , compute the peak activation memory ratio .
- (c)
An interleaved 1F1B schedule with virtual stages per device achieves bubble fraction . Compute the bubble fraction for , , . Compare to non-interleaved 1F1B with .
- (d)
For a diffusion model with 48 transformer layers and stages, there are two natural partitions: 6 layers per stage (uniform) or unequal partitions chosen to equalize stage compute time (profiling-based). Explain why profiling-based partitioning is essential for diffusion models with per-timestep attention masking.
- (e)
At pipeline depth and , a hardware failure causes one stage to run slower. What is the new effective bubble fraction?
Exercise 80 (ZeRO Stages: Memory per GPU for a 13B Model).
A 13B-parameter transformer model uses Adam optimizer. Each parameter is stored in FP16 for the forward pass; the optimizer maintains FP32 master weights, FP32 first moments, and FP32 second moments.
- (a)
Compute the memory per GPU for model parameters in FP16. How does this compare to the total optimizer state memory (master weights + moments in FP32)?
- (b)
ZeRO Stage 1 shards optimizer states across GPUs. Compute the memory saved per GPU for optimizer states. What is the total memory per GPU?
- (c)
ZeRO Stage 2 additionally shards gradients. Compute the additional memory saved per GPU for gradients (assuming FP16 gradients). Total memory per GPU?
- (d)
ZeRO Stage 3 shards parameters. Compute the memory per GPU for parameters, gradients, and optimizer states combined. What additional communication does ZeRO-3 require compared to ZeRO-2?
- (e)
At GPUs, re-compute the memory per GPU for all ZeRO stages. Is there a stage beyond which the memory savings become negligible? Why?
Answer sketch (13B model, ): Parameters (FP16): . Optimizer state (FP32 master weights + 2 moments): . ZeRO-1: optimizer per GPU , total per GPU (gradient not sharded). ZeRO-2: gradients sharded, per GPU additional saving. ZeRO-3: params sharded, per GPU , total for optimizer states, plus activation memory.
Tier 3: Advanced Topics
Exercise 81 (Mixed Precision: Bandwidth Savings from FP16 All-Reduce).
A training run uses FP32 gradients for all-reduce by default. The team proposes switching to FP16 gradient communication with loss scaling.
- (a)
A ring all-reduce of bytes at bandwidth takes time proportional to . Compute the time savings from FP16 (half the bytes) for a 7B model gradient tensor.
- (b)
Loss scaling requires multiplying the loss by a scale factor before the backward pass and dividing gradients by after the all-reduce. The division by costs one FLOP per gradient element. Compute the FLOP overhead of loss scaling as a fraction of the backward pass FLOP count for a 7B model.
- (c)
FP16 all-reduce followed by FP32 optimizer update requires a type conversion step. On a GPU with and memory bandwidth, is the type conversion compute-bound or memory-bound?
- (d)
NCCL implements an FP16 all-reduce using FP32 accumulation in the reduction step. Explain why accumulation in FP16 would be problematic and estimate the numerical error that would result from accumulating FP16 gradients in FP16.
- (e)
Propose a criterion for when to use BF16 instead of FP16 for gradient communication, based on the gradient magnitude distribution of a typical diffusion model.
Exercise 82 (DiffusionPipe: Speedup from Filling Pipeline Bubbles).
A 4-stage diffusion model pipeline processes micro-batches per step. Standard 1F1B has a bubble fraction .
DiffusionPipe proposes to fill pipeline bubbles with inference micro-batches from a different noise level, using the same pipeline hardware.
- (a)
Compute the number of bubble time slots available per step (in units of one stage's compute time) in standard 1F1B with , .
- (b)
If each inference micro-batch (DDIM, 50 steps for a image) takes a training micro-batch's compute time per stage, how many inference micro-batches can be processed in the available bubble time per training step?
- (c)
Define the combined throughput efficiency as , where is the wall-clock pipeline time. Compute this for your answer in (b).
- (d)
Does filling bubbles with inference micro-batches affect training convergence? Identify any assumptions required.
- (e)
What happens to the speedup estimate if the inference micro-batches have variable compute time (e.g., different denoising steps for different images)?
Exercise 83 (Ring Attention: Communication Cost for 128K Sequence).
Ring attention distributes a sequence of length across GPUs, each holding query tokens and the full key-value context via ring communication.
- (a)
For , , head dimension , and attention heads, compute the size of the key-value shard per GPU (in GB at FP16).
- (b)
In ring attention, each device sends its KV tokens to the next device in the ring at each of steps. Compute the total bytes transmitted per device over the full ring attention pass.
- (c)
Compare this to the communication cost of standard (non-ring) distributed attention where the full KV is broadcast to all devices.
- (d)
For the parameters above with interconnect bandwidth , compute the communication time for ring attention. Compare to the attention computation time assuming and FLOPs for attention per device.
- (e)
If the attention pattern is sparse (each query attends to only of the keys), does ring attention still require transmitting the full KV? Propose a modification to exploit sparsity.
Answer sketch. (a) KV shard per GPU: . (b) Each device sends its KV shard times: . (c) Broadcast: each device receives full KV from root (or for a tree broadcast), worse than ring for large . (d) Communication time . FLOPs per device FLOPs, time : communication-dominated.
Exercise 84 (Distributed Auto-Differentiation: Gradient Flow Across Pipeline Stages).
A 4-stage pipeline processes a U-Net architecture. Stage 1 holds the input encoder, Stage 2 the first half of the bottleneck, Stage 3 the second half, Stage 4 the output decoder. The U-Net has skip connections: stage 1 sends activations to stage 4, and stage 2 sends activations to stage 3.
- (a)
Draw the forward communication graph between stages. Label each edge with the direction and the tensor being communicated.
- (b)
In the backward pass, trace the gradient flow. For each forward edge , state which backward communication it generates ( gradient) and identify any skip-connection gradients that cross multiple stages.
- (c)
The skip connection from stage 1 to stage 4 means that during the backward pass, stage 4 must send a gradient back to stage 1, bypassing stages 2 and 3. Compute the additional communication volume this introduces relative to a non-skip pipeline.
- (d)
Explain why gradient checkpointing is more beneficial for the skip connection activations than for the main pathway activations in this architecture.
- (e)
If stage 1 uses gradient checkpointing (recomputing activations during the backward pass), stage 2 does not, stages 3 and 4 do, write out the complete communication schedule for a single forward-backward pass, specifying which tensors are stored, which are recomputed, and which must be communicated.
Exercise 85 (Fault Tolerance: Expected Wasted Time with MTBF and Checkpointing).
A training cluster of GPUs has individual GPU mean-time-between-failures (MTBF) of . The cluster fails (any GPU failure halts training) with cluster MTBF .
- (a)
Compute in hours. How many failures are expected per day?
- (b)
The checkpoint interval is . On failure, the team reverts to the last checkpoint and restarts. Assume restart time (save + reload + re-init) takes . Compute the expected wasted time per failure event.
- (c)
Define training efficiency as . Compute for the parameters above.
- (d)
Optimize the checkpoint interval to maximize . Express as a function of and . (Hint: minimize expected wasted fraction.)
- (e)
A new asynchronous checkpointing system reduces checkpoint save time to (overlapped with training) but still requires to reload. How does this change and ?
- (f)
If the cluster grows to GPUs (a future frontier cluster), compute and with re-optimized. Comment on the viability of checkpoint-restart at this scale.
Answer sketch. (a) . Failures per day: . (b) Expected wasted time per failure . (c) Expected failures per unit time . Wasted fraction ; . (d) .
Research Challenges
Challenge 3 (Distributed Data Parallel Training for a Toy Diffusion Model).
Problem.
Implement distributed data-parallel (DDP) training for a minimal
denoising diffusion probabilistic model (DDPM) from scratch,
using PyTorch and torch.distributed with the NCCL
backend. The model should be a small U-Net (fewer than 10M
parameters) trained to denoise images from CIFAR-10.
Requirements.
Implement the DDP wrapper manually using
dist.all_reduceon gradients rather than using PyTorch's built-inDistributedDataParallelmodule. This forces explicit understanding of the gradient averaging.Implement gradient bucketing: group layer gradients into at most 5 buckets and launch all-reduce per bucket as soon as all gradients in the bucket are ready.
Measure training throughput (images/second) on 1, 2, and 4 GPUs. Compute the parallel efficiency where is wall-clock time to reach the same loss as a single GPU.
Verify that the model trained on 4 GPUs reaches the same FID score (within 5 FID units) as the single-GPU baseline.
Deliverable. A working training script, a table of throughput and parallel efficiency measurements, and a one-page analysis of the bottlenecks observed.
Key learning outcomes. Understanding that DDP is gradient synchronization at its core; that bucket ordering matters for overlap efficiency; that the linear scaling rule for learning rates must be applied carefully for diffusion objectives.
Challenge 4 (Communication-Avoiding Attention Variant for Distributed Training).
Problem. Design and analyze (but do not necessarily implement) a distributed self-attention mechanism for sequences of length distributed across GPUs such that the communication volume is at most of ring attention's volume, while the output approximates exact attention to within in normalized mean absolute error on a held-out validation set.
Requirements.
Propose a specific attention approximation (e.g., local window + cross-device global tokens, random routing, or learned sparsity) and derive the per-device communication volume formula.
Prove or empirically estimate the approximation error as a function of the design parameters (window size, number of global tokens, etc.).
Derive the bandwidth and latency of your mechanism using the alpha-beta model with , .
Compare your mechanism to ring attention on the four criteria: communication volume, latency, approximation error, and implementation complexity.
Identify failure modes: for what input patterns would your approximation perform poorly, and how would you detect and handle them?
Deliverable. A technical report (3–5 pages) including the mechanism specification, mathematical analysis, and comparison table.
Challenge 5 (Benchmarking Ring All-Reduce vs. Tree All-Reduce on 4 GPUs).
Problem. Implement and benchmark both a ring all-reduce and a binary-tree all-reduce on a 4-GPU system using PyTorch NCCL primitives, and measure their performance for gradient tensors of varying sizes.
Requirements.
Implement ring all-reduce using
dist.sendanddist.recvwith explicitly coded ring topology. Do not usedist.all_reduce, which calls NCCL internally.Implement binary-tree reduce-scatter and all-gather using point-to-point communication.
Benchmark both implementations for tensor sizes at FP32. Report mean and standard deviation over 20 runs after a 5-run warm-up.
Plot achieved bandwidth (GB/s) vs. tensor size for both implementations. At what size does ring all-reduce begin to outperform the tree?
Compare your implementations to the built-in NCCL all-reduce (the
dist.all_reducebaseline). What fraction of NCCL performance do you achieve?
Deliverable. Source code, benchmark results table, bandwidth plot, and a one-page analysis explaining the observed crossover point using the alpha-beta model predictions from Exercise Exercise 73.
Challenge 6 (Hybrid Parallelism Configuration for a Specific Model and Hardware).
Problem. Propose and justify a complete hybrid parallelism configuration for training a 70B-parameter dense transformer on a cluster of 256 NVIDIA H100 GPUs connected by InfiniBand HDR (200 Gb/s per port, 1 port per GPU).
Specifications. The model has: 80 layers, hidden dimension 8192, 64 attention heads, FFN intermediate dimension 28672, vocabulary size 32000. Each H100 has 80 GB HBM3 memory and at BF16.
Requirements.
Propose values of such that and the configuration is memory-feasible (all parameters, optimizer states, and activations fit within 80 GB per GPU under ZeRO-1).
Compute the expected memory usage per GPU under your configuration, breaking down by parameters, optimizer states, gradients, and activations.
Estimate the communication time per step for each parallelism dimension using the alpha-beta model. Which dimension contributes the most communication overhead?
Estimate the pipeline bubble fraction for your proposed and a reasonable micro-batch count .
Compare your configuration to two alternatives: (i) pure data parallelism (), and (ii) a configuration published in the Megatron-LM paper for a similar cluster.
Justify your choice in one paragraph, citing the trade-offs between memory efficiency, communication overhead, and implementation complexity.
Deliverable. A structured report (2–3 pages) with memory analysis table, communication time estimates, bubble fraction computation, and configuration justification.
Challenge 7 (Analyzing Communication Hiding Efficiency for FSDP Prefetching).
Problem. Analyze the communication hiding efficiency of PyTorch FSDP's parameter prefetching mechanism for a 7B-parameter transformer and measure it on a 2-GPU system.
Background.
FSDP (Fully Sharded Data Parallel) shards parameters across devices.
Before each layer's forward pass, the parameters for that layer
must be gathered from all shards (AllGather). FSDP
prefetches the parameters for layer while layer
is computing, attempting to hide the AllGather latency. During
the backward pass, after computing gradients for layer ,
FSDP re-shards by performing a ReduceScatter of the
gradient and prefetches parameters for layer .
Requirements.
For a 32-layer transformer with 7B parameters ( at FP16), compute the per-layer AllGather volume and the AllGather time at .
Measure the per-layer forward compute time on your hardware using PyTorch profiler. Compute the theoretical hiding efficiency averaged across layers.
Profile an actual FSDP training run using
torch.profilerand measure the fraction of AllGather time that overlaps with compute in practice. Compare to the theoretical estimate.Identify the layers where hiding fails (AllGather cannot be fully hidden). Are these the layers with the smallest parameter counts, the largest compute intensity, or something else?
Propose a modification to the prefetching schedule (e.g., prefetch two layers ahead instead of one) and estimate the memory overhead and the hiding efficiency improvement.
Deliverable. Profiling traces (as PNG or JSON for TensorBoard), a hiding efficiency plot per layer, and a one-page analysis of the gap between theoretical and measured hiding efficiency.
Chapter Summary
This chapter has developed the mathematical and systems foundations of distributed training for generative models. Beginning from the alpha-beta latency model, we built up a precise analytical framework for predicting the performance of collective communication primitives on real cluster topologies. We then studied four complementary parallelism strategies - data, tensor, pipeline, and sequence parallelism - and analyzed the memory-communication-computation trade-offs that govern their optimal use. The ZeRO family of optimizer sharding protocols and the DiffusionPipe pipeline scheduler were presented as case studies in systems design for generative models specifically.
Key Idea.
The fundamental insight of distributed training for generative models is that memory, compute, and communication are a conserved resource. No architectural choice reduces all three simultaneously. Every parallelism strategy and memory optimization trades between them: tensor parallelism reduces memory at the cost of communication; pipeline parallelism reduces communication at the cost of idle time; ZeRO reduces memory at the cost of additional all-reduce operations. The practitioner's task is to identify the binding constraint and apply the technique that relaxes it most efficiently for their specific hardware configuration.
Key Idea.
Mixed-precision training, gradient compression, and communication hiding are orthogonal optimizations that can be layered atop any parallelism strategy. Their combined effect is multiplicative: FP16 all-reduce reduces bandwidth by ; communication hiding reduces exposed communication by another –; gradient compression can reduce bandwidth by a further –. Applied together on a communication-bottlenecked cluster, these techniques can bring communication overhead below of total step time.
The ten open problems of Section Open Problems and Future Directions represent the research frontier. Several of them - communication- optimal hybrid parallelism search, communication-avoiding attention, and the communication complexity lower bound conjecture - are sufficiently well-posed to support PhD-level research with clear success criteria. Others, such as cross-datacenter diffusion training and energy-efficient distributed training, require interdisciplinary collaboration spanning systems, optimization theory, and policy.
Insight.
Distributed systems expertise is not a prerequisite for doing research in generative modelling, but it is increasingly a differentiator. As models scale past the capacity of single devices and as the economics of large-scale training come under scrutiny, the researchers who can reason rigorously about communication complexity, memory hierarchies, and collective schedules will have a systematic advantage in both proposing new architectures and in implementing them at production scale. The exercises and challenges in this chapter are designed to build that fluency incrementally, from the alpha-beta model through ring attention to fault-tolerant training. Work through them in order, and revisit the open problems afterward: you will find that several of them look considerably more tractable than they did at first reading.
Notes
- Ring all-reduce sends and receives each element once during reduce-scatter and once during all-gather, hence the factor of 2.