Skip to content
AIAI Wranglers

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 N parameters is trained on D tokens, the approximate number of floating-point operations required is: (Compute Estimate)C6ND 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 (N=175×109 parameters, D=300×109 tokens), this gives: (GPT3 Compute)CGPT-36×175×109×300×1093.14×1023 FLOPs. An A100 GPU achieves approximately 3.12×1014 BF16 FLOPs per second (312 teraFLOPS). Training GPT-3 on a single A100 would therefore require: (Single GPU TIME)tsingle=3.14×10233.12×10141.0×109 seconds31.7 years. 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.

Data centre hierarchy for distributed AI training. Three racks each contain four compute nodes connected to a spine InfiniBand switch at 50,GB/s per link. Within each node, GPUs are connected via NVLink at 900,GB/s aggregate bandwidth - an 18:1 ratio that makes intra-node communication dramatically cheaper than inter-node communication. The expanded view of Node 1A shows four GPUs linked by NVLink. Real DGX H100 nodes house 8 GPUs; the 4-GPU depiction is for clarity.

Formal Definition of Distributed Training

We now lay the mathematical foundations.

Definition 1.

(Distributed Training.) Let (𝜽;𝒟) be a loss function over parameters 𝜽N and dataset 𝒟. A distributed training system consists of:

  1. A set of K workers (devices) {w1,,wK}, each with local memory Mk bytes.

  2. A partitioning scheme Π that assigns model parameters, activations, and/or data to workers such that k|Πk(𝜽)|=N (for parameter partitioning) or kΠk(𝒟)=𝒟 (for data partitioning).

  3. A communication protocol 𝒞 specifying when and how workers exchange gradients, parameters, or activations.

  4. 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)𝜽=argmin𝜽1|𝒟|(𝒙,𝒚)𝒟(𝜽;𝒙,𝒚) such that at no point does any single worker wk need to hold more than Mk 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 N parameters stored in BF16 (2 bytes each) requires 2N bytes just for the weights. During training, gradient storage adds another 2N bytes. The Adam optimiser (the standard choice) adds two momentum terms per parameter, requiring an additional 8N bytes in FP32. The total model state memory footprint is: (Memory Footprint)Mstate=2N+2N+8N=12N bytes. For a 7-billion-parameter model, this is 12×7×109=84×109 bytes =84,GB, exceeding the 80,GB memory of a single A100. For GPT-4 at 1.8 trillion parameters: Mstate=12×1.8×101221.6,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)MFU=observed throughput (FLOPs/s)peak hardware throughput (FLOPs/s). 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 K 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 2N gradient values per step (send + receive), and with BF16 gradients requires: (Allreduce Volume)Vallreduce=2×2N=4N bytes per step. For GPT-3 (N=175×109), 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)tcomm700GB50GB/s=14seconds per step. 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 - O(N) 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 L with H attention heads each of dimension dh, and layers, the KV cache requires: (KV Cache Memory)MKV=2×L×H×dh××2 bytes (the factor of 2 for key and value, and 2 bytes for BF16). For a 70B model with L=128,000, H=64, dh=128, =80: MKV3.3TB 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 1024×1024 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).

  1. Compute the total model state memory in gigabytes, following Equation .

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

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

  1. Using the ring-allreduce formula for communication volume, compute the minimum data volume transferred per worker per step. (Hint: ring-allreduce achieves optimal 2N(K1)/K2N total data movement per worker for large K.)

  2. If a forward+backward pass takes 0.8 seconds per step, what fraction of step time is consumed by communication?

  3. 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 D should scale linearly with the number of model parameters N: D20N.

  1. Using Equation and the Chinchilla relation, express the optimal compute budget C as a function of N alone.

  2. A team has a budget of 1024 FLOPs (approximately the compute used for GPT-4). What is the Chinchilla-optimal model size, and how many tokens should it be trained on?

  3. 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?

  4. 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 𝐀m×k times 𝐖k×n decomposes into mn 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 4×4 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: 8×H100 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.

GPUBF16 TFLOPSHBM Cap.HBM BWNVLink BW
V100 (2017)12532,GB900,GB/s300,GB/s
A100 (2020)31280,GB2,TB/s600,GB/s
H100 (2022)98980,GB3.35,TB/s900,GB/s
B200 (2024)4500192,GB8,TB/s1800,GB/s
NVIDIA GPU generation comparison for AI training workloads. BF16 throughput is the primary metric for LLM training. Memory bandwidth is the binding constraint for memory-bound operations (layernorm, softmax, embedding lookups). NVLink bandwidth determines the efficiency of intra-node tensor parallelism.

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 F floating-point operations while transferring B bytes of data between DRAM and compute units, the arithmetic intensity is: (Arithmetic Intensity)I=FB[FLOPs/byte]. A hardware accelerator with peak compute throughput π (FLOPs/s) and peak memory bandwidth β (bytes/s) has a hardware ridge point: (Ridge Point)Iridge=πβ[FLOPs/byte]. A kernel is compute-bound if I>Iridge and memory-bound if I<Iridge.

For the H100 in BF16, π=989×1012 FLOPs/s and β=3.35×1012 bytes/s, giving: (H100 Ridge)IridgeH100=989×10123.35×1012295 FLOPs/byte. 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 P (FLOPs/s) of a kernel with arithmetic intensity I on hardware with peak compute π and peak bandwidth β satisfies: (Roofline Bound)Pmin(π,βI).

The roofline model provides a useful first-pass classification of every operation in a generative model:

Roofline model for the NVIDIA H100 GPU in BF16 precision. The x-axis is arithmetic intensity (FLOPs per byte of memory traffic) on a log scale; the y-axis is achieved throughput in TFLOPS. The memory-bandwidth roof slopes up at β=3.35,TB/s until the hardware ridge point at I=295,FLOPs/byte, above which the compute ceiling at 989,TFLOPS applies. LN: LayerNorm (I10, strongly memory-bound). SM: Softmax (I20, memory-bound). Att: Standard attention at small batch size (I40, memory-bound). FA: FlashAttention (I150, near ridge point due to SRAM tiling). MM: Large matrix multiply (I300, compute-bound). The central lesson: most generative model operations are memory-bandwidth-limited, not compute-limited, motivating algorithmic efforts to increase arithmetic intensity.

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 M×M can compute a (M×K)×(K×M) 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 M times as it travels across or down the array, achieving arithmetic intensity of O(M) - which for M=128 (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

ChipVendorBF16 TFLOPSMem.Mem. BWInterconnect BW
A100 SXMNVIDIA31280,GB2.0,TB/s600,GB/s (NVLink 3.0)
H100 SXMNVIDIA98980,GB3.35,TB/s900,GB/s (NVLink 4.0)
B200 SXMNVIDIA4500192,GB8.0,TB/s1800,GB/s (NVLink 5.0)
TPU v5pGoogle45995,GB2.76,TB/s4.8,Tb/s (ICI)
Gaudi 3Intel1835128,GB3.7,TB/s3.7,TB/s (HCCL)
Comparison of major AI training accelerators. BF16 TFLOPS is the primary compute metric. Interconnect bandwidth is per-device aggregate. The TPU v5p and Gaudi 3 are competitive alternatives to NVIDIA hardware for large-scale training.

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)C=6×7×109×1×1012=4.2×1022 FLOPs.

Step 2: Time on different hardware. Assuming 40% MFU (realistic for a well-tuned cluster):

t=CMFU×π×K where K is the number of devices and π is peak FLOPS.

Hardwareπ (TFLOPS)Kt (days)
8× A100 (1 node)3128586
64× A100 (8 nodes)3126473
64× H100 (8 nodes)9896423
128× H10098912811.5
128× B20045001282.5

Step 3: Memory feasibility check. Model state memory (Equation ): Mstate=12×7×109=84GB. 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).

  1. Linear projection. A query projection matrix 𝐖Q4096×4096 is applied to an activation tensor 𝐀B×L×4096 with B=4, L=2048. Compute the FLOPs (2mnk for a matmul of shape m×k times k×n) and the bytes read/written.

  2. Layernorm. Applied to the same activation tensor of shape B×L×4096. FLOPs: approximately 8×B×L×d (mean, variance, normalise, scale, shift). Bytes: read the activation and write the output (2× data size) plus reading weight and bias vectors.

  3. Softmax. Applied to an attention score matrix of shape B×H×L×L with H=32, L=2048. FLOPs: approximately 5×B×H×L2. 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 p (splitting each attention and MLP weight matrix across p GPUs). At each transformer layer, tensor parallelism requires one all-reduce of size B×L×dmodel bytes where B=8, L=4096, dmodel=7168.

  1. Compute the all-reduce data volume per layer in megabytes for BF16 precision.

  2. With the all-reduce implemented as ring-allreduce, the effective communication time is approximately 2(p1)/p×V/β where β is bandwidth. For p=8 with NVLink at 900,GB/s and InfiniBand at 50,GB/s, compute the all-reduce time for each.

  3. The forward pass compute time per layer is approximately 2×2×dmodel2×B×L/(π×p) FLOPs. For the H100 at 989,TFLOPS, compute the compute-to-communication ratio for NVLink and InfiniBand cases.

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

  1. Estimate the total training time in days.

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

  3. 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.)

  4. 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?

  5. 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 4×4 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 2×5× 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 G=(V,E,b,) where:

  • V is the set of nodes (processing units), |V|=P;

  • EV×V is the set of edges (communication links);

  • b:E>0 assigns a bandwidth b(e) (bytes per second) to each edge e;

  • :E>0 assigns a latency (e) (seconds) to each edge e.

The diameter of G is D(G)=maxu,vVd(u,v), where d(u,v) is the length of the shortest path from u to v in terms of hop count.

Definition 4 (Bisection Bandwidth).

Let G=(V,E,b,) be a network topology. A bisection of G is a partition (S,VS) of V into two equal halves with |S|=P/2. The bisection bandwidth of G is: (Bisection)BB(G)=min(S,VS)|S|=P/2e=(u,v)EuS,vSb(e). Intuitively, BB(G) 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 S to send data to every node in VS, the maximum aggregate throughput is bounded by BB(G), 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 G, the communication volume is the total number of bytes transmitted across all links during one step of 𝒜: (Commvol)Vol(𝒜,G)=eE(bytes sent over e in one step). An algorithm is communication-volume-optimal if no correct algorithm for the same task on the same topology achieves smaller Vol.

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 P-node ring, the edge set is E={(i,(i+1)modP):i=0,,P1}.

The ring has diameter D=P/2 and bisection bandwidth 2b where b 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 2(P1)/P 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 k-dimensional torus arranges P=nk nodes in a k-dimensional grid with wraparound edges in every dimension. In a 2D torus with P×P nodes:

  • each node (i,j) is connected to (i±1modP,j) and (i,j±1modP);

  • diameter D=2P/2;

  • bisection bandwidth 2Pb (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 3P1/3/2, and the bisection bandwidth is 2P2/3b.

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 k-ary fat-tree has three levels of switches.

  • k2/4 edge (leaf) switches, each with k/2 downlinks to compute nodes and k/2 uplinks.

  • k2/4 aggregation switches.

  • k2/4 core switches.

Total nodes: k3/4. Diameter: 2logk/2P+2 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 k-ary fat-tree with r:1 oversubscription has bisection bandwidth BB=Pb/(2r) where b 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 (P>10,000 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 d-dimensional hypercube connects P=2d nodes so that two nodes are adjacent if and only if their binary addresses differ in exactly one bit. Properties:

  • diameter D=d=log2P - the shortest diameter possible for any topology connecting P nodes with the same node degree;

  • node degree d=log2P (increases with P, limiting scalability);

  • bisection bandwidth P/2b (the minimum cut severs P/2 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

Five network topologies used in distributed deep learning. Ring: each node connects to two neighbors; simple, bandwidth-optimal for all-reduce. 2D Torus: grid with wraparound edges (dashed); smaller diameter than ring; used in TPU Pods. Fat-Tree: hierarchical; squares are switches, circles are GPUs; full bisection bandwidth; common in InfiniBand clusters. Dragonfly: two router groups (squares) with all-to-all intra-group links and a single global inter-group link (thick green); used in exascale systems. Hypercube: 3D cube with 23=8 nodes; diameter =log2P; natural structure for butterfly collectives.

Ring All-Reduce: Cost Analysis

The ring all-reduce algorithm proceeds in two phases. Let P be the number of nodes, each holding a gradient vector of n bytes.

  • Reduce-scatter phase: P1 rounds. In round r, each node i sends its chunk of size n/P to node (i+1)modP and receives a chunk from node (i1)modP, accumulating the partial reduction. Each link carries n/P bytes per round.

  • All-gather phase: P1 rounds. Each node i forwards its fully-reduced chunk to node (i+1)modP. Again, each link carries n/P 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 n-byte message across P nodes has time cost: (RING AR COST)Tring-AR=2(P1)α+2P1Pnβ.

Proof.

Each of the two phases has P1 rounds. In each round, every node sends a message of size n/P to its neighbor, incurring one startup cost α and a transfer time of (n/P)β. The total time for the reduce-scatter phase is (P1)(α+(n/P)β) and identically for the all-gather phase. Summing both phases: T=2(P1)α+2(P1)nPβ=2(P1)α+2(P1)Pnβ.

Remark 2 (Bandwidth Optimality of Ring All-Reduce).

As P, the bandwidth term approaches 2nβ. This is the information-theoretic minimum: each of the P nodes must receive n bytes of data (the fully reduced result), so the minimum total traffic is Pn bytes distributed across P links, giving n bytes per link in each direction, or 2n bytes per link round-trip. The ring all-reduce achieves this bound, making it bandwidth-optimal regardless of P. 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 TopologyDiameterBisect. BWNode degreeUsed by
RingP/22b2NVLink within DGX, MPI defaults
[4pt] 2D Torus2P/22Pb4Google TPU Pod v2/v3
[4pt] 3D Torus3P1/3/22P2/3b6IBM Blue Gene, Google TPU Pod v4
[4pt] Fat-Tree (k-ary)O(logP)Pb/(2r)kInfiniBand HPC, AWS EFA, Azure NDv5
[4pt] Dragonfly3–5Pb/4O(P)Cray Slingshot, Frontier, Aurora
[4pt] Hypercubelog2PPb/2log2PIntel iPSC, algorithm emulation
Comparison of network topologies for distributed training. P = number of nodes, b = per-link bandwidth, r = oversubscription ratio (fat-tree). “Full” bisection bandwidth means BB=Pb/2.

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 K8 on the GPU level.

  • NVLink 3.0 bandwidth: 600 GB/s bidirectional per GPU.

  • NVSwitch total bisection bandwidth: 8×300 GB/s = 2.4 TB/s.

  • All-reduce of n bytes across 8 GPUs: Tα+nβNVLink (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 8×25 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 24× 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 (32×8=256 GPUs) via a fat-tree InfiniBand fabric. The full system delivers 256×312 TFLOPS = 79.9 PFLOPS of FP16 compute with 256×25 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 n=1 GB.

Step 1: Reduce-scatter within each pod. GPUs 0–3 (pod A) perform a ring reduce-scatter among themselves. Each GPU sends n/4=256 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: (Ppod1)(α+n4Ppodβ)=3(α+64 MBβ).

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 256/25,00010.2 ms. All 4 inter-pod pairs do this simultaneously; the fat-tree's full bisection bandwidth (4×25 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: 2×256 MB ×2=1 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): 2×10.2+2×3×(64/25,000×1000)20.5 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 P/21 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 5×.

Exercises

Exercise 5.

Consider a 4×4 2D torus with 16 nodes and per-link bandwidth b=100 GB/s.

  1. Compute the bisection bandwidth of the torus.

  2. Compare with a 16-node ring of the same per-link bandwidth.

  3. A 16-GPU ring all-reduce of a 10 GB gradient tensor takes time Tring. 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 k-ary fat-tree (no oversubscription, r=1) connects P=k3/4 nodes.

  1. Express the diameter D as a function of k and P.

  2. Show that bisection bandwidth scales as Θ(P), i.e., it is full bisection bandwidth.

  3. A data center uses k=8, giving P=128 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 (T=8) and pipeline parallelism (Ppipe=4) on a DGX SuperPOD with 256 A100 GPUs (32 nodes × 8 GPUs).

  1. How many data-parallel replicas are there?

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

  3. Estimate the time per all-reduce step for the data-parallel gradient synchronization if the gradient size per replica is 280/(TPpipe)=8.75 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 1μs of hardware latency plus 2μs 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:

  1. 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: α.

  2. 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: Nβ.

Total journey time = waiting for the first coach (α) + time for all passengers to disembark (Nβ) = α+Nβ.

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 Nβ, and bandwidth is what matters.

The train analogy for the alpha-beta communication model. Latency α is the fixed wait for the first coach (engine) to arrive, independent of the total volume N. The bandwidth contribution Nβ grows linearly with the number of data “coaches” once transfer begins. Total time T(N)=α+Nβ.

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 N bytes from one node to another is: (Alphabeta)T(N)=α+Nβ, where:

  • α>0 is the latency (seconds), also called the startup time or overhead: the time elapsed before any data has been received, regardless of message size;

  • β>0 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 B bytes/second, then β=1/B;

  • N is the message size in bytes.

The model assumes that message transfer is pipelined: once the first byte departs, subsequent bytes follow at rate 1/β without additional startup costs.

Remark 3 (Typical Values in Practice).

Representative values for modern interconnects:

  • NVLink 3.0 (intra-node): α15μs, β1/6001.67ns/GB; equivalently B=600 GB/s.

  • InfiniBand HDR (inter-node): α25μs, β=1/25=40ns/GB; equivalently B=25 GB/s.

  • 100 GbE Ethernet: α550μs, β80ns/GB; equivalently B=12.5 GB/s.

The bandwidth ratio NVLink : InfiniBand : Ethernet is roughly 600 : 25 : 12.5, while the latency ratio is much tighter: 1:2.5:10.

Point-to-Point and Collective Costs

Point-to-Point Transfer

By definition, a single point-to-point message of N bytes costs: (P2P)Tp2p(N)=α+Nβ.

Broadcast

A broadcast sends a message of N bytes from one root node to all P1 other nodes. The optimal tree-based implementation proceeds in log2P rounds, doubling the number of informed nodes each round. In round r, every node that has the data sends it to one new node.

(Bcast)Tbcast(N)=log2P(α+Nβ).

Derivation. There are log2P rounds. In each round, every active sender transmits the full N-byte message to one new receiver: cost α+Nβ 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 log2P rounds. In round r, each node exchanges half its data with a partner at distance 2r. The total cost is: (AR Butterfly)TAR,butterfly(N)=2log2Pα+2P1PNβ. The factor 2(P1)/P in the bandwidth term reflects that each node effectively sends and receives the full message N once (total 2N bytes), reduced by 1/P because its own chunk needs no transmission.

Ring.

From Proposition 2: (AR RING)TAR,ring(N)=2(P1)α+2P1PNβ.

Comparison.

The bandwidth terms of and are identical. The difference lies entirely in the latency term: 2log2Pα (butterfly) versus 2(P1)α (ring). For large P, the butterfly has O(logP) latency rounds while the ring has O(P) latency rounds.

  • If αNβ/P, i.e., we are latency-bound, use the butterfly.

  • If Nβ/Pα, i.e., we are bandwidth-bound, both algorithms perform identically; use the ring (simpler).

In deep learning, gradient all-reduce involves large tensors (N1081010 bytes) and P is modest (8–1024 GPUs), so NβPα 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 CollectiveAlpha-Beta CostNotes
Point-to-pointα+NβBaseline
[4pt] Broadcast (tree)log2P(α+Nβ)Root sends to all; optimal for large N
[4pt] Reduce (tree)log2P(α+Nβ)Same structure as broadcast
[4pt] All-reduce (ring)2(P1)α+2(P1)PNβBW-optimal; O(P) latency rounds
[4pt] All-reduce (butterfly)2log2Pα+2(P1)PNβLatency-optimal; same BW as ring
[4pt] All-gather (ring)(P1)α+P1PNβEach node contributes N/P bytes
[4pt] Reduce-scatter (ring)(P1)α+P1PNβSymmetric to all-gather
[4pt] All-to-all(P1)α+P1PNβEach node sends N/P to each other
[4pt] Barrierlog2PαNo data; pure synchronization cost
Communication costs of common collective operations in the alpha-beta model. P = number of processes, N = message size (bytes), α = latency, β = inverse bandwidth. “Optimal” designates the algorithm that minimizes total cost.

Bandwidth Optimality of Ring All-Reduce

Proposition 3 (Ring All-Reduce is Bandwidth-Optimal).

For an all-reduce of N bytes across P nodes on a ring (or any topology), the minimum total bytes transmitted across any single link is 2N(P1)/P. The ring all-reduce achieves this bound.

Proof.

Consider the all-reduce problem: each of P nodes starts with a vector of N bytes; all must end with the element-wise sum.

Lower bound. Focus on a single link (u,v)E. Node u must learn the contribution of every node on the “v-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 P/2 nodes, collectively holding P/2N bytes of unique data. However, the output at u requires knowing only the sum (not individual values), so it suffices to send N bytes across the link in each direction. Thus every link must carry at least N bytes in each direction, i.e., at least 2N bytes total per link.

More precisely, for the ring with P nodes, each link carries exactly N(P1)/P bytes per direction in the ring all-reduce, giving 2N(P1)/P per link round-trip. As P, this approaches 2N per link.

Achievability. In the reduce-scatter phase of ring all-reduce, node i sends chunk i of size N/P to node (i+1)modP in round 1, and in round r it forwards the chunk it received in round r1. Over P1 rounds, each link carries (P1)×N/P=N(P1)/P bytes in one direction. The all-gather phase is symmetric. Total per link: 2N(P1)/P, matching the lower bound up to the factor (P1)/P1.

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.

Timeline decomposition of communication cost T(N)=α+Nβ for three message sizes N1N2N3. Orange bars represent the fixed latency α; blue bars represent the bandwidth contribution Nβ. Small messages are latency-bound (orange dominates); large messages are bandwidth-bound (blue dominates). The crossover point N=α/β marks where both terms are equal.

Crossover Point and Regime Analysis

The crossover between the latency-dominated and bandwidth-dominated regimes occurs at: (Crossover)N=αβ. For NN, the latency term α dominates and the effective throughput N/T(N)N/α is far below the peak bandwidth 1/β. For NN, the bandwidth term dominates and throughput approaches 1/β.

Remark 4 (Regime Analysis for InfiniBand HDR).

For InfiniBand HDR with α=3μs and β=40ns/GB=4×108s/byte, (equivalently B=25GB/s): N=3×106s4×108s/byte=75000bytes=75kB. Messages smaller than 75 kB are latency-bound on InfiniBand HDR. Gradient vectors in a 7B-parameter model are 14 GB per replica, far above N, 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 N=7×109×2=14 GB per data-parallel replica. We run data-parallel training across P=8 GPUs and perform a ring all-reduce after each backward pass.

Scenario A: NVLink (within a DGX node). αNV=2μs, βNV=1/600ns/GB1.67×109s/byte.

Using (AR RING): (EX Nvlink)TAR,NV=2(P1)αNV+2(P1)PNβNV=2×7×2μs+2×78×14GB×1600ns/GB=28μs+1.75×14×109×1.67×109s=28μs+40.83ms40.9ms. The latency contribution is 28μs, utterly negligible compared to the 40.8ms bandwidth term. This is firmly in the bandwidth-bound regime.

Scenario B: InfiniBand HDR (across nodes). αIB=3μs, βIB=1/25ns/GB=40×109s/byte.

(EX IB)TAR,IB=2×7×3μs+2×78×14GB×125ns/GB=42μs+980ms980ms=0.98s.

Comparison. NVLink all-reduce is 980/40.924× faster than InfiniBand all-reduce, exactly matching the bandwidth ratio (600/25=24). Since both are bandwidth-bound, the latency difference (2μs vs 3μs) is irrelevant.

For a training step that also includes 100 ms of compute, the communication-to-compute ratio is:

  • NVLink: 40.9ms/100ms=0.41 (communication is 29% of step time);

  • InfiniBand: 980ms/100ms=9.8 (communication is 91% 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 N=α/β. If your message size NN, no amount of bandwidth hardware will help: you need to reduce the number of messages (batching, aggregation) or reduce latency (RDMA, kernel bypass). If NN, no amount of latency optimization will help: you need more bandwidth (faster links, more links, topology redesign, or gradient compression to reduce N). 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: αA=1μs, BA=400GB/s (NVLink 4.0).

  • Interconnect B: αB=10μs, BB=400GB/s (hypothetical high-latency fabric).

  1. Compute the crossover message size N for each interconnect.

  2. For a scatter-reduce of 128 MB messages across 16 GPUs, which interconnect is faster? By how much?

  3. Explain why two interconnects with the same bandwidth can have different optimal collective algorithms.

Exercise 9.

A cluster has P=64 nodes with α=5μs and β=1/100ns/byte (i.e., B=100GB/s). You need to perform an all-reduce of a 1 GB gradient tensor.

  1. Compute TAR,ring and TAR,butterfly for this configuration.

  2. At what message size N× does the ring become worse than the butterfly by more than 10%? (Solve for N× analytically, then substitute numbers.)

  3. 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).

  1. With gradient compression at a 100:1 ratio (e.g., 1-bit quantization), what is the new all-reduce time?

  2. Assume the backward pass takes 200 ms and gradients can be pipelined: the all-reduce for layer l begins as soon as the backward pass for layer l completes, while the backward pass continues through layer l1. If gradients are evenly distributed across layers, what is the total step time with overlap? (Use uncompressed InfiniBand all-reduce time from (EX IB).)

  3. 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 231 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:

  1. A group G={0,1,,p1}, an ordered set of p process identifiers called ranks;

  2. 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;

  3. An optional topology, describing the logical arrangement of processes (Cartesian grid, graph, etc.).

The predefined communicator MPI_COMM_WORLD includes all p processes launched by mpirun, with ranks 0,1,,p1. Every MPI communication operation is scoped to a communicator.

When a program calls MPI_Comm_rank( MPI_COMM_WORLD, &amp;rank), it learns its position in the process group. When it calls MPI_Comm_size( MPI_COMM_WORLD, &amp;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 p copies of this process, each printing a different rank, producing p 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 s and a receiver with rank r within communicator 𝒞, satisfying:

  1. Message envelope: a message is uniquely identified by the tuple (s,r,𝚝𝚊𝚐,𝒞), where 𝚝𝚊𝚐[0,Tmax] is an application-level label (with Tmax32767);

  2. Order preservation: if rank s sends messages m1 before m2 to rank r with the same tag and communicator, then r receives m1 before m2;

  3. 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 buf, count n, and datatype τ (e.g., MPI_DOUBLE), defining a typed message of nsizeof(τ) 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);
Blocking vs. non-blocking MPI communication. (a) With blocking 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 p1 point-to-point messages from root; an optimized implementation uses a binomial tree, reducing latency from O(p) to O(logp).

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 iL, and the root obtains i=0p1iL.

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 g=1pi=0p1iL (dividing by p is done in the application code). Ring all-reduce, the algorithm underlying NCCL and PyTorch DDP, achieves near-optimal bandwidth of 2(p1)/p 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);

MPI collective operations and their data movement patterns. Orange boxes indicate the root process. Blue boxes indicate participating processes. Bcast: root distributes its data to all; Reduce: all contribute and result accumulates at root; Allreduce: like Reduce but result goes to all (every rank ends up with the global sum); Allgather: each contributes its piece and all receive the full concatenated array; Scatter: root distributes distinct chunks to each rank. In data-parallel LLM training, Allreduce is invoked once per backward pass per parameter group, summing gradients across all workers.

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 p-process ring with per-byte bandwidth β and per-message latency α.

CollectiveLatencyBandwidth cost
BcastO(logp)αO(m)
ReduceO(logp)αO(m)
Allreduce (ring)O(p)α2(p1)m/pβ
Allgather (ring)O(p)α(p1)m/pβ
ScatterO(logp)αO(m)
Reduce-scatterO(p)α(p1)m/pβ
Asymptotic cost of MPI collectives on a p-process ring. m = message size in bytes, α = per-message latency, β = bandwidth (bytes/sec). Allreduce achieves bandwidth efficiency (p1)/p1 for large p.

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 s can directly read from or write to a window Wraddress space of r without requiring r to execute any matching MPI call. Formally:

  • 𝙼𝙿𝙸_𝚆𝚒𝚗_𝚌𝚛𝚎𝚊𝚝𝚎(𝑏𝑎𝑠𝑒,𝑠𝑖𝑧𝑒,𝑑𝑖𝑠𝑝_𝑢𝑛𝑖𝑡,𝑖𝑛𝑓𝑜,𝑐𝑜𝑚𝑚,&W) creates a window object W exposing memory at base;

  • 𝙼𝙿𝙸_𝙿𝚞𝚝(𝑜𝑟𝑖𝑔𝑖𝑛_𝑏𝑢𝑓,n,τ,r,𝑡𝑎𝑟𝑔𝑒𝑡_𝑑𝑖𝑠𝑝,n,τ,W) writes n elements from the caller's buffer into rank r's window;

  • 𝙼𝙿𝙸_𝙶𝚎𝚝(𝑜𝑟𝑖𝑔𝑖𝑛_𝑏𝑢𝑓,n,τ,r,𝑡𝑎𝑟𝑔𝑒𝑡_𝑑𝑖𝑠𝑝,n,τ,W) reads n elements from rank r'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 1μs on InfiniBand networks and bandwidths exceeding 200Gb/s on HDR InfiniBand.

RDMA-based one-sided communication with 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 200Gb/s per port and O(100ns) 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 D parameters across p=8 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 D doubles. After step 3, all p ranks hold g^=i=0p1gi, where gi is the gradient computed by rank i. After step 4, all ranks hold the mean gradient g=1pg^. 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 2D8 bytes1 for double precision, or 2D4 bytes for float. For a 7B-parameter model at float32, this is 7×109×2×4=56GB per step per all-reduce call, which at 200Gb/s InfiniBand takes approximately 2.2seconds 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 r sends an integer token (the value r) to rank (r+1)modp, and receives a token from rank (r1+p)modp. After the exchange, have each rank print the token it received.

(a) Implement this using blocking MPI_Send/MPI_Recv. Verify that with p=4 ranks sending in the order 01, 12, 23, 30, 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 p=4 and let each rank hold an array of 4n 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 n=106 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 Θ(mplogp) versus Θ(m(p1)) for the ring algorithm.

Exercise 13.

Communication-computation overlap. Consider a model with L=32 layers, each with D/L parameters. After the backward pass computes the gradient for layer , this gradient can be immediately all-reduced while the backward pass continues through layer 1.

(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 Tcompute and the communication time Tcomm can the overlap hide all communication latency?

(c) Define the overlap ratio ρ=Tcomm/Tcompute and express the effective GPU utilization U(ρ). 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 900GB/s 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:

  1. Copies the GPU buffer to a CPU staging buffer (a synchronous D2H memcopy that stalls the GPU);

  2. Sends the data from CPU memory over the network;

  3. 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 31× 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 O(p) 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 O(logp) latency versus O(p) 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 64KB256KB 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 p processes be arranged in a ring 01(p1)0. Each process i holds a buffer xiD. The ring all-reduce computes x=x0+x1++xp1D and delivers a copy of x to every process.

The algorithm proceeds in two phases, each consisting of p1 steps:

Phase 1: Reduce-scatter (p1 steps). Partition each buffer into p chunks: xi=[xi(0),xi(1),,xi(p1)], where each chunk xi(k)D/p.

At step t{1,,p1}, process i sends chunk xi((it)modp) to process (i+1)modp, and receives a chunk from process (i1)modp. The received chunk is added to the corresponding local chunk.

After p1 steps, process i holds the fully reduced chunk x(i)=k=0p1xk(i)D/p.

Phase 2: All-gather (p1 steps). Process i now sends its fully reduced chunk x(i) around the ring. At step t, process i forwards the chunk it received in step t1. After p1 steps, every process holds all p reduced chunks and thus the full xD.

Communication volume: each of the p1 steps in each phase transfers D/p elements per process. Total data sent per process: (RING Volume)Vsend=2(p1)Dp=2(p1)pDp2D. This is within a factor of p/(p1) of the optimal 2D (the minimum data a process must send to inform all others of its contribution), confirming that ring all-reduce is bandwidth-optimal.

Ring all-reduce on 4 GPUs. Each GPU initially holds 4 chunks of the gradient buffer (A through D, subscripted by GPU index). Phase 1 (reduce-scatter): over 3 steps, each GPU sends its current chunk to the next GPU and accumulates received chunks. After p1=3 steps, GPU i owns the fully reduced chunk x(i)=kxk(i) (shown as ΣA, ΣB, ΣC, ΣD). Phase 2 (all-gather): over another 3 steps, each GPU forwards its fully-reduced chunk around the ring. After p1=3 steps, every GPU holds all 4 reduced chunks, i.e., the complete summed gradient x. The ring topology ensures every link is active at every step, achieving bandwidth efficiency (p1)/p1.

Tree All-Reduce: Latency-Optimal for Small Messages

Ring all-reduce requires O(p) 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 2(p1)α, which grows linearly with the number of GPUs. At p=1000 GPUs with α=1μs, that is 2,ms just in latency overhead before any data moves.

A tree all-reduce uses a binary or binomial tree topology:

  1. Reduce phase: leaves send to their parent; each internal node accumulates children's values and passes the sum upward. After O(logp) steps, the root holds the global sum.

  2. Broadcast phase: root sends the global sum down the tree. After another O(logp) steps, all nodes have the result.

Total latency: O(logp) steps, reducing the latency from 2,ms to 20μs at p=1000. The cost: bandwidth efficiency drops because internal tree nodes are bottlenecks-the root must send and receive D bytes, consuming full bandwidth, while leaves send and receive only D/p bytes. Tree all-reduce is therefore optimal for latency-bound (small D) workloads and ring all-reduce is optimal for bandwidth-bound (large D) workloads.

The crossover point D satisfies: (Crossover)DB=αlogpD=αBlogp, where B is the single-link bandwidth. For InfiniBand (α=1μs, B=25GB/s) with p=256: D=106×25×109×log2256=200KB. Messages below 200KB 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():

  1. During model construction, DDP registers a gradient hook on every parameter. When a parameter's .grad is populated by autograd, the hook fires.

  2. 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 ncclAllReduce on the bucket asynchronously.

  3. The backward pass continues through earlier layers while NCCL transfers the completed bucket in the background.

  4. At the end of loss.backward(), DDP calls torch.cuda.synchronize() to wait for all pending all-reduces.

  5. 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 log2p steps, pairs of processes exchange half their data and accumulate;

  • After log2p 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

PropertyNCCLMPI (GPU-aware)Gloo
Primary hardwareGPU (NVLink/IB)CPU/GPUCPU (Ethernet)
All-reduce algoRing + Tree (hybrid)Ring / TreeHalving-doubling
GPU-nativeYesPartialNo
CPU involvementMinimal (launch only)HighHigh
Intra-node BW700,GB/s (NVLink4)50,GB/s (PCIe)10,GB/s
Inter-node BW200,Gb/s (IB HDR)200,Gb/s (IB HDR)25,Gb/s
RDMA supportGPU-Direct RDMAYes (lib-dependent)No
CPU-only modeNoYesYes
PyTorch backend"nccl""mpi""gloo"
Typical use caseGPU LLM trainingHPC workloadsCPU / debugging
Comparison of NCCL, MPI (GPU-aware), and Gloo communication backends for distributed deep learning. Latency and bandwidth figures are representative for an 8-GPU single-node setup; exact values depend on hardware configuration. NCCL is the default and preferred backend for GPU training in all major frameworks.

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 1TB of data across the cluster. Keeping the GPUs busy for more than 50% 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 k 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, 900GB/s 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 ×2(p1)p, the effective utilization of each NVLink, comparable to hardware peak.

Key observations:

  1. For 8,B–1,KB (tiny messages), latency dominates: algbw is essentially zero. Here NCCL uses the tree algorithm; latency is 14–22,μs.

  2. At 128,MB, busbw reaches 244GB/s, which is 244/90027% of peak NVLink bandwidth. The efficiency gap is explained by the ring overhead 2(p1)/p=7/4 on the busbw denominator: the true NVLink utilization is 244×(7/4)/90047% per link.

  3. At 1,GB, busbw reaches 260GB/s, demonstrating near-linear scaling with message size in the bandwidth-bound regime.

In production LLM training, the gradient tensors per layer are typically 1MB100MB, placing them squarely in the bandwidth-efficient regime. The profiling confirms that DDP bucket sizes of 25MB are a sensible default: large enough for high bandwidth efficiency (>100GB/s algbw) but small enough that multiple buckets can pipeline with the backward pass.

The total all-reduce time for a 70B-parameter model (70×109×4bytes=280GB) at 260GB/s busbw is approximately 280×109/(260×109)1.08s 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 (900GB/s) and InfiniBand (200Gb/s) 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 2, 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 90% 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 p=4 processes.

(a) Implement Phase 1 (reduce-scatter): divide each gradient tensor into 4 equal chunks; at each of the p1=3 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 108-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 D separating latency-bound (tree-optimal) and bandwidth-bound (ring-optimal) regimes.

(a) For InfiniBand HDR (α=1μs, B=25GB/s) with p{8,64,512}, compute D in kilobytes.

(b) For NVLink4 intra-node (α=0.5μs, B=112.5GB/s per link) with p=8, compute D.

(c) Given that a transformer layer's attention projection matrix has 4d2 parameters (for model dimension d), and that a gradient all-reduce is called once per layer per step, at what model dimension d 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 325MB 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 Tb=50ms per layer, and the all-reduce for a 25,MB bucket takes Tc=5ms. 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 Tb/Tc 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: max(45,30)=45 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.

Sequential vs. overlapping execution: the laundry analogy. Left: sequential strategy waits for communication (washing) to finish before beginning computation (cooking), wasting 30 minutes of potential overlap. Right: overlapping strategy runs both simultaneously, completing in max(45,30)=45 minutes and saving 40% of wall-clock time. In distributed training, the washing machine is the gradient communication network and cooking is GPU backward-pass computation.

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 max(Tcomp,Tcomm) 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 Tcomp and a communication phase of duration Tcomm.

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 max(Tcomp,Tcomm). Formally, let tcstart denote the time at which communication begins and Titer the total iteration time. A schedule achieves full hiding if (FULL Hiding)Titer=max(Tcomp,Tcomm), and partial hiding if (Partial Hiding)max(Tcomp,Tcomm)Titer<Tcomp+Tcomm. The sequential baseline corresponds to Titer=Tcomp+Tcomm.

The speedup from hiding is the ratio of sequential to overlapped time:

(Hiding Speedup)𝒮hide=Tcomp+Tcommmax(Tcomp,Tcomm).

When TcommTcomp the speedup approaches 1 (communication was cheap to begin with). When Tcomm=Tcomp the speedup is 2 - a doubling of throughput from hiding alone. When TcommTcomp 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 Tcomp=80ms and Tcomm=50ms.

Sequential time: 80+50=130ms.

Fully hidden time: max(80,50)=80ms.

Speedup: 130/80=1.625×.

Throughput gain: 62.5% more training steps per second.

If communication grows (e.g. more GPUs, wider layers) to Tcomm=120ms: sequential time is 200ms, hidden time is 120ms, speedup is 1.67×. 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 k's communication overlaps with stage k+1's computation.

Consider a backward pass over L layers. Each layer produces a gradient tensor 𝐠 that must be all-reduced across workers. A naive implementation computes all L gradient tensors, then launches a single all-reduce for the entire gradient vector. The all-reduce is O(model size) 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 1.

Sequential vs. pipelined backward pass with gradient all-reduce. Top: the naive schedule completes all backward passes, then launches a single all-reduce, resulting in Titer=Tcomp+Tcomm. Bottom: the pipelined schedule launches layer 's all-reduce immediately after layer 's backward pass, overlapping communication with the remaining backward computation. Only the last all-reduce (for layer 1) is not overlapped, leaving a small communication tail. With L large, the tail is a fraction 1/L of total communication.

Let TAR denote the all-reduce time for layer 's gradients and Tbwd the backward time for layer . Under a layer-wise overlap schedule, the total iteration time is

(Layerwise TIME)Titer==1LTbwd+max(0,TAR1=2LTbwd), where the second term captures the “tail” all-reduce for layer 1 that cannot be hidden behind further backward computation. When =2LTbwdTAR1, full hiding is achieved and the iteration time equals Tcomp.

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:

  1. Compute matrix-vector product 𝐪=𝐀𝐩.

  2. All-reduce to compute α=ρ/(𝐩𝐪).

  3. Update 𝐱 and 𝐫 using α.

  4. All-reduce to compute β=ρnew/ρ.

  5. 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 k can be pipelined with the matrix-vector product in step 1 of iteration k+1. The reformulated algorithm reads:

Algorithm 2.

Communication-Hiding Conjugate Gradient (CHCG).

  1. Initialise 𝐱0, 𝐫0=𝐛𝐀𝐱0, 𝐩0=𝐫0
  2. Launch non-blocking all-reduce: ρ^0=𝐫02
  3. for k=0,1,2,
  4. Compute 𝐪k=𝐀𝐩k (overlaps with previous all-reduce)
  5. Wait for ρ^k to complete
  6. Launch non-blocking all-reduce: σ^k=𝐩k𝐪k
  7. Compute local vector updates (fills overlap gap)
  8. Wait for σ^k; compute αk=ρ^k/σ^k
  9. Update 𝐱k+1=𝐱k+αk𝐩k
  10. Update 𝐫k+1=𝐫kαk𝐪k
  11. Launch non-blocking all-reduce: ρ^k+1=𝐫k+12
  12. Update 𝐩k+1=𝐫k+1+(ρ^k+1/ρ^k)𝐩k (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 𝐩k+1 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 s-step methods that pipeline s communication rounds simultaneously.

In the s-step framework, the algorithm computes s Krylov vectors in a single communication-free block: 𝐊s(𝐀,𝐫k)=[𝐫k,𝐀𝐫k,𝐀2𝐫k,,𝐀s1𝐫k], which requires only one set of global communications for all s steps instead of one per step. The iteration count is the same; the communication count is divided by s.

The hiding efficiency improves with s: (Sstep TIME)Titer(s)sTcomp(1)+1ssTcomm(1)=sTcomp(1)+Tcomm(1), so the communication overhead per effective iteration shrinks from Tcomm(1) to Tcomm(1)/s. When s is large enough that sTcomp(1)Tcomm(1), communication disappears from the critical path.

The price is numerical: the s-step Krylov basis can be poorly conditioned for large s, 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 K collective operations of latencies τ1,,τK and K+1 computation blocks of durations c0,c1,,cK. If collective k is launched at the start of computation block ck1 and the result is consumed at the end of block ck, then the total iteration time satisfies (Hiding Latency Bound)Titer=k=0Kck+k=1Kmax(0,τkck1). Full hiding of all collectives is achieved when ck1τk for all k=1,,K.

Proof.

Collective k begins at the start of block ck1. It completes after τk time. The result is needed after ck1 time. If τkck1, the result is ready before it is needed and there is no stall. If τk>ck1, the worker must wait τkck1 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 L's gradients can be all-reduced while layers L1,L2, are still being differentiated. This is because, in a standard computation graph, the backward pass through layer depends only on the gradient from layer +1 and the layer's own cached activations - not on the gradients of layers 1,2,

DDP backward pass with gradient overlap. The GPU row (blue) shows the backward pass proceeding from layer L=4 down to layer L=1. The Network row (orange) shows the all-reduce (AR) for each layer launched one step later, overlapping with the subsequent backward computation. The shaded region is the overlap zone where both GPU and network are simultaneously busy. Only the final all-reduce (AR L=1) cannot be hidden, as there is no further backward computation to fill the gap.

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 Tcomp=120ms and Tcomm=40ms on a 16-GPU node.

  1. Compute the speedup from full communication hiding using (Hiding Speedup).

  2. If the cluster is scaled to 64 GPUs and Tcomm scales as Θ(logN) with the number of GPUs N (ring all-reduce), compute the new speedup.

  3. At what number of GPUs does the communication first exceed Tcomp, and what does this imply for the critical path?

Exercise 18.

A transformer with L=32 layers performs a pipelined backward pass as described in The Pipelining Approach. Each layer has Tbwd=3ms and TAR=2ms (uniform across layers).

  1. Compute Titer using (Layerwise TIME) and show that full hiding is achieved.

  2. Now suppose the model is partitioned into 4 equal buckets (each containing 8 layers' gradients) instead of per-layer all-reduces. Compute TARbucket (assuming linear scaling with gradient volume) and the new Titer.

  3. Which strategy yields better hiding efficiency? Under what conditions does bucketing become preferable?

Exercise 19.

An iterative solver on a distributed cluster has Tcomp(1)=5ms per step and Tcomm(1)=30ms per global all-reduce.

  1. Using (Sstep TIME), find the minimum value of s for which communication is fully hidden behind computation.

  2. If the s-step method introduces a 10% penalty to Tcomp(1) (due to basis orthogonalisation), does the optimal s from (a) still achieve full hiding?

  3. Sketch the effective throughput (iterations per second) as a function of s{1,2,4,6,8} 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 {𝐠i}i=1P be the gradient tensors for the P parameters of a model. A gradient bucket partition ={B1,B2,,BM} with Bj{1,,P} and jBj={1,,P} groups parameters into M buckets. An all-reduce is launched for bucket Bj as soon as all gradients {𝐠i}iBj have been computed in the backward pass. The effective communication granularity is Ωj=iBj|𝐠i| 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.

LLM backward pass with gradient bucketing. The GPU (blue) computes backward passes in groups of layers. After each group completes, an all-reduce (orange) is fired for the bucket corresponding to those layers, while the GPU continues backward computation through earlier layers. The overlap zone covers the majority of both compute and communication, with only the tail of the final bucket exposed on the critical path.

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 τ0 (typically 50500μs depending on the switch fabric). Total communication overhead Mτ0 grows with the number of buckets M=P/Ω.

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 P parameters distributed across M equal buckets of size Ω=P/M elements. Let:

  • τ0 - fixed startup latency of each all-reduce (seconds),

  • β - available all-reduce bandwidth per element (elements/second),

  • c - compute time per element of backward pass (seconds/element),

  • Ω - bucket size in elements.

The all-reduce time for one bucket is τ(Ω)=τ0+Ω/β. The compute time over one bucket's span of the backward pass is c(Ω)=cΩ. Full hiding requires c(Ω)τ(Ω), i.e. (Hiding Condition)cΩτ0+Ω/βΩτ0c1/β. The minimum bucket size achieving full hiding is therefore (Optimal Bucket)Ω=τ0c1/β, provided c>1/β (compute is slower than communication bandwidth, so there exists a bucket large enough).

Proof.

From , solving for Ω: cΩΩ/βτ0Ω(c1/β)τ0Ωτ0c1/β. 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: P=13×109 (FP16 26GB)

  • Batch size per GPU: 2 sequences of 2048 tokens

  • Backward pass time: Tcomp=380ms (measured)

Communication parameters:

  • Ring all-reduce bandwidth efficiency: 70% of peak InfiniBand (280Gb/s effective)

  • All-reduce data volume: 2PN1N bytes (ring-reduce formula; for large N, 2P=26GB in FP16)

  • All-reduce time (no overlap): 26GB×8/280Gb/s743ms

Sequential time: Tseq=380+743=1123ms.

With gradient bucketing (25 MB buckets): M=26GB/25MB=1040 buckets. Each bucket's all-reduce time 743/10400.71ms. Each bucket's compute time 380/10400.37ms. Since 0.37ms<0.71ms, the compute does not fully hide the per-bucket all-reduce.

Effective compute available for hiding =380ms. Communication hidden min(380,743)=380ms. Remaining communication tail =743380=363ms. Effective iteration time: Teff380+363=743ms.

Hiding efficiency: ηhide=1TeffTcompTcomm=17433807430.49. 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 P pipeline stages and m micro-batches constitute one training step. The 1F1B schedule assigns each stage p the following sequence:

  1. Warm-up phase: Stage p performs Pp forward passes (filling the pipeline).

  2. Steady state: For each micro-batch, stage p alternates: one forward pass (on the current micro-batch) followed immediately by one backward pass (on the oldest outstanding micro-batch).

  3. Drain phase: Stage p processes the remaining backward passes.

The inter-stage communication (activation/gradient transfer) for micro-batch k overlaps with the computation for micro-batch k+1 on the adjacent stage, constituting an implicit communication-hiding schedule.

1F1B pipeline schedule with 4 stages and 4 micro-batches. Green (F) blocks are forward passes; blue (B) blocks are backward passes; dashed blocks () are pipeline bubbles (idle time). In the steady state (middle of the timeline), each stage alternates forward and backward on successive micro-batches. Inter-stage activation communication (not shown explicitly) is pipelined: Stage 2 begins receiving Stage 1's activations while Stage 1 continues with the next micro-batch. The bubble fraction is (P1)/m for m micro-batches, shrinking as m grows.

The bubble fraction (idle time as a fraction of total time) for the 1F1B schedule is: (Bubble Fraction)ϕbubble=P1m+P1, where P is the number of pipeline stages and m is the number of micro-batches per batch. As m, ϕbubble0: 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 T steps; the network learns to reverse this. During training, the model predicts the noise 𝝐 added at a randomly sampled timestep t: (θ)=𝔼t,𝐱0,𝝐[𝝐𝝐θ(𝐱t,t)2]. The UNet or DiT backbone processes a single noisy image or video frame at timestep t; 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 k+1 is scheduled to fill the pipeline bubble that occurs during the backward pass of the denoising network for micro-batch k. 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 tiUniform{1,,T}. 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 +1's parameters in the background. By the time layer +1 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 1 (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@ TechniqueParadigmHidden Op.FrameworkLimitation
Gradient bucketingData parallelAll-reducePyTorch DDPCompute < comm. tail exposed
FSDP all-gather prefetchData parallel (sharded)All-gatherPyTorch FSDPMemory limit on simultaneous gathers
1F1B pipeline schedulePipeline parallelActivation send/recvMegatron-LM, PipeDreamBubble fraction (P1)/m
DiffusionPipe frozen encoderPipeline parallelEncoder fwd (no grad)CustomApplicable only to frozen-encoder architectures
CHCG / s-stepSolver-basedGlobal dot productNumerical solversNumerical instability for large s
Tensor parallel overlapTensor parallelAll-reduce (row/col)Megatron-LMRequires column/row-parallel linear layers
Comparison of communication hiding techniques across distributed training frameworks. “Hidden operation” refers to the collective communication that is overlapped with computation. “Limitation” describes the primary constraint on hiding efficiency.

Exercises

Exercise 20.

A 7B-parameter language model (FP16; 14GB parameters) is trained with DDP on 32 A100 GPUs with 100 Gb/s InfiniBand.

  1. Using Proposition 5, compute Ω assuming a per-all-reduce startup latency of τ0=200μs, effective ring-bandwidth β=10GB/s, and backward-pass compute of c=0.4μs per element (FP16 gradient).

  2. If the actual DDP default bucket size is 25 MB, is this above or below Ω? What are the consequences of each direction?

  3. An engineer proposes reducing the bucket size to 5 MB to increase overlap granularity. Using the formula for total startup overhead (Mτ0 where M=Ptotal/Ω), quantify the additional overhead introduced.

Exercise 21.

A transformer model is trained with 8-stage pipeline parallelism using the 1F1B schedule.

  1. Using (Bubble Fraction), compute the bubble fraction for m{8,16,32,64} micro-batches.

  2. Plot (or tabulate) the effective GPU utilisation (1ϕbubble) for these values of m.

  3. 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 5%?

  4. The interleaved 1F1B schedule (Narayanan et al., 2021) reduces the bubble fraction to (P1)/(mv) where v is the number of virtual stages per device. For P=8, m=16, what value of v achieves ϕbubble<1%?

Exercise 22.

A DiT-XL model with 48 transformer blocks is trained with FSDP on 8 GPUs. Each block's parameter tensor is 250MB (FP32). The all-gather for one block completes in TAG=15ms. The forward pass through one block takes Tfwd=10ms.

  1. Without prefetching, compute the total time spent waiting for all-gathers during the forward pass of one training step.

  2. With forward_prefetch=True (one layer ahead), compute the residual all-gather stall time. Assume block 's all-gather is launched when block 1's forward pass starts.

  3. 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?

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

The grocery store analogy for communication avoiding. Making ten separate trips incurs ten times the round-trip overhead. Writing a complete list and making a single trip reorganizes the work to avoid nine trips entirely. In distributed training, the analogous reorganization reduces synchronization rounds from s to 1 when computing s gradient steps.

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 m with independent computation, so that the effective communication time visible on the critical path is reduced, while the total bytes transmitted |m|bytes 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 R, the total bytes transmitted B, or both, by algebraic or algorithmic restructuring.

Side-by-side comparison of baseline, communication hiding, and communication avoiding on a pipeline with three compute–communicate cycles. Hiding overlaps compute and communication, reducing wall time while preserving total data volume. Avoiding reorganizes the algorithm to collapse three communication rounds into one, reducing both rounds and total bytes.

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 n×n matrices A and B to produce C=AB on a distributed system with P processors, each with local memory of size M 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 C=AB of two n×n matrices using Θ(n3) floating-point operations on P processors, each with local memory of size M words, must move at least (Demmel Bound)Bmin(n,P,M)=Ω(n2P2/3) words between processors (summed over all processors), when M=Θ(n2/P2/3) (the memory-optimal regime).

Proof sketch.

The argument is a counting argument based on the 3D geometry of matrix multiplication. The n3 multiplications required by C=AB form a combinatorial cube [n]×[n]×[n], where entry (i,k,j) corresponds to the multiply-add cij+=aikbkj.

A processor with memory M can hold at most M values of A, B, and C simultaneously. By a geometric result (the Loomis-Whitney inequality), the number of triples (i,k,j) computable using only those M values is at most M3/2. Hence, to compute all n3 triples, the processor must load new data at least n3/M3/2 times. Distributing n3 triples across P processors, each processor handles n3/P triples, requiring at least (n3/P)/M3/2 loads. In the memory-optimal regime M=n2/P2/3, this evaluates to n2/P2/3 words per processor.

The classical parallel matrix multiply algorithms (ScaLAPACK, SUMMA) communicate Θ(n2/P1/2) words, which exceeds the lower bound by a factor of P1/6. Communication-avoiding algorithms (Cannon's algorithm, 2.5D algorithms) achieve the lower bound Θ(n2/P2/3), 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 n×n, 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 C without ever receiving data that another processor already holds. The 2.5D algorithm (Solomonik and Demmel, 2011) illustrates the idea.

Arrange the P processors in a P/c×P/c×c three-dimensional grid, where c1 is a replication factor trading extra memory for reduced communication. Each processor holds a block of A, B, and C of size n2/(P/c). The algorithm proceeds in two phases:

  1. Broadcast phase. Replicate A and B along the third dimension of the grid using c1 broadcasts. Each broadcast moves n2/P/c words.

  2. Compute phase. Each of the P/c×P/c processor slabs independently performs a parallel matrix multiply over its local data, communicating only Θ(n2/Pc) words.

  3. Reduce phase. Sum the c partial products along the third dimension to produce the final C.

The total communication is Θ(n2/P2/3c1/3), which matches the lower bound when c=1 and approaches it for larger c at the cost of increased memory.

Communication-Avoiding Conjugate Gradient

The conjugate gradient (CG) method for solving Ax=b illustrates how communication avoidance extends beyond matrix multiply to iterative algorithms. Classical CG requires one all-reduce per iteration to compute the inner products rk,rk and the step sizes. With s iterations, this means s synchronisation rounds.

The communication-avoiding conjugate gradient (CA-CG) algorithm (Carson and Demmel, 2015) collapses s iterations into a single communication round.

Algorithm 3 (Communication-Avoiding Conjugate Gradient).

  1. Input: Matrix An×n, vector bn, initial guess x0, block size s1
  2. r0bAx0, p0r0
  3. for k=0,s,2s,
  4. [Local] Compute the Krylov block: 𝒦s(A,rk)=[rk,Ark,A2rk,,Asrk] using repeated local matrix-vector products
  5. [One all-reduce] Compute all inner products among the s+1 Krylov vectors simultaneously via a single reduction of the (s+1)×(s+1) Gram matrix Gij=Airk,Ajrk
  6. [Local] Compute the next s CG iterates xk+1,,xk+s from the Gram matrix using the classical three-term recurrence

The savings are dramatic: s classical CG steps require s all-reduce calls; CA-CG requires only 1 call per s steps, reducing synchronisation rounds by a factor of s.

Proposition 6 (CA-CG Communication Savings).

Classical CG performing T iterations requires T synchronisation rounds. CA-CG with block size s requires T/s rounds, a reduction by factor s. The total bytes exchanged decreases from Θ(Tn/P) to Θ(T/ss2), which is lower when s<n/P.

Proof sketch.

Each classical CG iteration broadcasts two scalar inner products, so T iterations communicate O(T) scalars, each requiring O(P) operations in an all-reduce tree, but O(n/P) words of local data. CA-CG broadcasts the (s+1)×(s+1) Gram matrix once per block, requiring O(s2) scalars per block and T/s blocks. The break-even point satisfies s2sn/P, i.e., sn/P, which is satisfied for any practical block size when n is large.

Remark 9.

A practical concern is that computing powers Ajrk 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 {Ajrk}. The block size s 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:

  1. 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).

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

  3. 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 M fast memory and unlimited slow memory must perform Ω(n3/M1/2) slow-memory references. The parallel extension, showing that P processors collectively must transmit Ω(n2/P2/3) 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 Wd×d, hidden state Hn×d, and output Y=HW, the forward pass is a matrix multiply and the backward pass computes the gradient W=HδY, also a matrix multiply.

If these matrix multiplications are distributed across P processors, the Demmel lower bound applies directly. A communication-avoiding implementation of the transformer forward/backward pass can therefore reduce the synchronisation cost from Θ(n2/P1/2) words (classical data-parallel distribution) to Θ(n2/P2/3) words, a saving of P1/6.

More broadly, any gradient-based training algorithm that performs iterative updates of the form θt+1=θtηtθ(θt) 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 n items from a store, and each round trip to the store takes fixed overhead α plus β per item carried. You can carry at most K items per trip.

  1. Show that the optimal number of trips is n/K.

  2. Compute the total time as a function of n, K, α, and β, and find the value of K that minimises total time when αβn.

  3. Map each quantity in your formula to its distributed-training analogue: what are α, β, K, and n in the context of gradient synchronisation?

Exercise 24 (Demmel bound for rectangular matrices).

The Demmel lower bound in Theorem 1 was stated for square n×n matrices.

  1. Generalise the bound to rectangular matrices Am×k and Bk×n. Express the lower bound in terms of m, k, n, and P.

  2. In a transformer with hidden dimension d and sequence length L, the attention weight matrix has size L×L and the value projection has size L×d. Apply your generalised bound to determine the minimum communication required for the attention computation on P GPUs.

  3. When is the classical all-reduce approach (which exchanges O(Ld/P) 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 s to train a linear model f(x;θ)=θx by minimising the squared loss (θ)=Xθy2, which leads to the normal equations XXθ=Xy.

  1. Express the communication savings of CA-CG over classical CG as a function of s, n (dimension of θ), and P.

  2. Show that the Krylov block [rk,Ark,,Asrk] where A=XX can be computed using s matrix-vector products with X and X (not with A directly), reducing the per-step compute cost.

  3. Derive the optimal s that minimises total training time (communication + compute) as a function of n, P, 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 K 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 T (one per step) to T/K (one per K steps), a factor-of-K reduction in synchronisation rounds.

Definition 16 (Local SGD).

Let there be P workers, each holding a data shard. Let θt(p)d denote the parameters on worker p at step t, and let K1 be the synchronisation period. Local SGD proceeds as follows:

  1. Local update. For k=1,,K, each worker p independently updates: (Local SGD Update)θt+k(p)=θt+k1(p)ηθ(p)(θt+k1(p);ξt+k(p)), where ξt+k(p) is a mini-batch sampled from the local shard of worker p.

  2. Synchronisation. After every K steps: (Local SGD SYNC)θt+K=1Pp=1Pθt+K(p). The averaged parameters are broadcast to all workers.

When K=1, 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 K 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 f:d be L-smooth (2fL) and let the stochastic gradients satisfy 𝔼[(p)]=f and 𝔼[(p)f2]σ2 (bounded variance). Denote the gradient dissimilarity across workers by δ2=1Ppf(p)f2. Local SGD with learning rate η, synchronisation period K, T total steps, and P workers satisfies: (Local SGD Bound)1Tt=0T1𝔼[f(θt)2]2(f(θ0)f)Tη+Lησ2/Pnoise+L2η2K2δ2drift, where θt=1Ppθt(p) is the mean parameter at step t.

Proof sketch.

The bound is derived by expanding f(θt+1) around f(θt) using smoothness, then bounding the drift term θt+Kθt, where θt denotes the parameters that vanilla SGD would have reached after K steps.

The drift term accumulates over K local steps: after kK steps, worker p's parameters satisfy θt+k(p)θt(p)kη(f(θt(p))+σ). Squaring and summing over p, the cross-worker variance satisfies 1Ppθt+K(p)θt+K2O(K2η2δ2). This term, multiplied by L (the smoothness constant), yields the drift contribution L2η2K2δ2 in (Local SGD Bound). Setting η=O(1/T) balances noise and drift terms, recovering the O(1/T) convergence rate of standard SGD, with the drift adding only a lower-order term when K=O(T1/4).

Remark 10.

In practice, local SGD with K{4,8,16} achieves comparable final accuracy to synchronous SGD while reducing communication rounds by the same factor. The optimal K depends on the data heterogeneity δ2: with IID data across workers (homogeneous shards), K can be large without quality loss; with highly heterogeneous data, smaller K is preferred. For large generative models trained on curated datasets (which tend to be relatively homogeneous), K=8 or even K=16 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-K Sparsification

In Top-K sparsification, each worker computes its local gradient gd and transmits only the K coordinates with the largest absolute values.

Definition 17 (Top-K Sparsification).

Let gd be a gradient vector and 0<Kd. The Top-K sparsification operator is (TOPK)TopK(g)i={giif |gi| is among the K largest values of |g|,0otherwise. The sparsified gradient g^=TopK(g) is encoded as a sparse vector with K nonzeros, requiring O(Klogd) bits to transmit (indices plus values) versus O(d) bits for the dense gradient, a compression ratio of d/K.

A critical detail is error feedback (also called error correction or memory): the components that were not transmitted are accumulated in a local buffer et(p) and added to the next gradient before sparsification.

Algorithm 4 (Top-K SGD with Error Feedback).

  1. Input: Learning rate η, compression ratio K, initial parameters θ0, initial error buffer e0=0
  2. for t=0,1,2,
  3. gt(θt;ξt) Compute local stochastic gradient
  4. g~tgt+et Add accumulated error
  5. g^tTopK(g~t) Sparsify: keep top-K components
  6. et+1g~tg^t Store residual for next step
  7. Transmit g^t to all workers, receive their g^t(p)
  8. θt+1θtη1Ppg^t(p)

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-K 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: Sign(g)i=+1 if gi0,1 otherwise. The scale of the gradient is communicated separately (a single scalar per layer), giving a compression ratio of 32× for 32-bit floats. Ternary quantization (Wen et al., 2017) represents each coordinate as {1,0,+1}, with a threshold τ below which coordinates are zeroed: Ternary(g,τ)i={+1gi>τ,0|gi|τ,1gi<τ. Ternary encoding combined with error feedback achieves compression ratios of 16× to 32× 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 L with d- dimensional embeddings distributed across P devices, this requires transmitting O(Ld) 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 Q(p) 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 P devices be arranged in a ring 01P10. Device p holds query block Q(p)(L/P)×d and initially holds KV block (K(p),V(p))(L/P)×d×2. Ring Attention proceeds for P rounds:

  1. Local attention. Device p computes partial attention scores and weighted values using its current KV block: Opartial(p)+=softmax(Q(p)(K(p,current))d)V(p,current) (with appropriate log-sum-exp accumulation for numerical stability).

  2. KV rotation. Device p sends its current KV block to device (p+1)modP and receives a KV block from device (p1)modP.

  3. Repeat for P rounds, after which each device has attended to every KV block.

The final output on device p is the correctly normalised attention over the full sequence, computed without any device ever holding the full L×d KV cache.

Ring Attention data flow on four GPUs. Each GPU holds its query block Q(p) locally throughout training. The KV blocks rotate around the ring over P rounds; each GPU computes a partial attention contribution at each round and accumulates the result. No GPU ever gathers the full sequence-length KV cache, reducing peak communication from O(Ld) (a full gather) to O(Ld/P) per round for P rounds - the same total bytes, but with no synchronisation barrier and no memory peak.

Ring Attention has an important property: the Q blocks never move. Each GPU accumulates its own output O(p) 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 O(Ld/P) per GPU instead of O(Ld).

  • 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 L split across P devices, each device holds L/P tokens. For a window attention with window size w<L/P, the attention is fully local; only causal or cross-chunk dependencies require inter-device communication of O(wd) words per layer. This reduces communication from O(Ld) (full sequence all-reduce) to O(wd) (boundary exchange), a factor-of-L/w reduction.

Remark 11.

For auto-regressive language models with causal attention, sequence parallelism is particularly effective: token t only attends to tokens 1,,t, so device p (holding tokens [(p1)L/P+1,pL/P]) only needs KV pairs from devices 0,1,,p1, not from device p+1,,P1. 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 (WQ,WK,WV,WO and the feedforward matrices W1,W2) 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 Θ(d2/P1/2) to Θ(d2/P2/3) words.

In practice, the saving is most significant at large model widths d and large P. For a transformer with d=8192 and P=512 GPUs, the classical 2D distribution communicates d2/P1/23×106 words per layer, while the 2.5D approach communicates d2/P2/31×106 words per layer, a 3× reduction per layer.

Example 8 (CA matrix multiply for GPT-scale models).

Consider a GPT-style transformer with L=96 layers, hidden dimension d=12288, and P=1024 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: B2D=8×96×d2P1/2=768×(12288)2323.6×109 words per training step.

Communication-avoiding (2.5D) distribution: B2.5D=8×96×d2P2/3=768×(12288)21011.15×109 words per training step.

The 2.5D approach reduces per-step communication by a factor of P1/6=10241/63.2×. At 400 Gbps interconnect bandwidth, this saves approximately (3.61.15)×109×4400×10924 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 t depends on the output of step t1. 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 K consecutive denoising steps before performing an all-reduce.

Algorithm 5 (Multi-Step Batching for Diffusion Training).

  1. Input: Noise schedule {αt}t=1T, batch size B, synchronisation period K
  2. for each global training step
  3. for k=1 to K K local denoising steps
  4. Sample (x0,t,ϵ)𝒟×{1,,T}×𝒩(0,I)
  5. xtαtx0+1αtϵ
  6. ϵ^ϵθ(xt,t)
  7. Accumulate: G+=θϵϵ^2/K
  8. All-reduce accumulated gradient G across workers
  9. θθηG

The communication saving is exactly K× in synchronisation rounds. Since diffusion model training typically uses K{4,8} 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 G=(V,E,W) be a mixing graph where V is the set of workers, E is the set of communication links, and WP×P is a doubly stochastic mixing matrix (W=W, W𝟏=𝟏, Wpq0, Wpq=0 if (p,q)E). Gossip SGD at step t: (Gossip)θt+1(p)=q=1PWpqθt(q)ηθ(p)(θt(p);ξt(p)). Each step, worker p mixes with its neighbours (the non-zero entries of row p in W) 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 W. Let λ2 be the second-largest eigenvalue of W (the first is 1). A larger spectral gap 1λ2 leads to faster consensus and better convergence.

Remark 12.

Common mixing graph topologies and their spectral gaps:

  • Complete graph (Wpq=1/P): spectral gap =1, but O(P2) edges (all-reduce equivalent).

  • Ring (Wpp=1/2, Wp,p±1=1/4): spectral gap =O(1/P2), only P edges.

  • Torus (2D grid): spectral gap =O(1/P), O(P) edges.

  • Exponential graph (each node connects to logP others): spectral gap =Ω(1), O(PlogP) 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@ TechniqueCategoryRounds savedBytes savedMain trade-off
Gradient overlapHiding0×0×Must overlap compute comm
[3pt] Pipeline bubblesHiding0×0×Bubble fraction 1/m
[3pt] Async SGDHiding0×0×Staleness introduces noise
[6pt] Local SGDAvoidingK×K×Gradient drift K2
[3pt] Top-K sparsifyAvoiding0×d/K×Error feedback needed
[3pt] 1-bit quantizationAvoiding0×32×Quantization noise
[3pt] Ring AttentionAvoidingbarrier freeP× peakRequires ring topology
[3pt] CA matrix multiplyAvoiding0×P1/6×Extra memory for c>1
[3pt] Gossip / decentralisedAvoidingall-reduce freetopology-dep.Slower consensus
[3pt] Local SGD + Top-KBothK×Kd/Ks×Both drift and bias
[3pt]
Comparison of communication optimisation strategies for distributed generative model training. “Rounds saved” and “bytes saved” are relative to synchronous data-parallel SGD. K = sync period, P = number of workers.
Taxonomy of communication optimisation techniques for distributed training. The hiding branch reduces the time that communication consumes on the critical path; the avoiding branch reduces the total amount of communication required. Modern training systems typically combine techniques from both branches.

Worked Example: Local SGD Savings for Diffusion Training

We compute the communication savings from local SGD with K=8 for a realistic diffusion model training run.

Example 9 (Local SGD with K=8 for diffusion training).

Setup. Consider training a diffusion model with θd, d=109 parameters, using P=64 A100 GPUs connected via NVLink (600 GB/s all-reduce bandwidth). Standard data-parallel SGD performs one all-reduce per step; local SGD with K=8 performs one all-reduce every 8 steps.

Communication per all-reduce. A standard ring all-reduce for d=109 float32 parameters transmits 2d(P1)/P2×109×63/642×109 values 8 GB per call.

Time per all-reduce. At 600 GB/s bandwidth: tAR=8 GB/600 GB/s13.3 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: Overhead=tARtAR+tcompute=13.313.3+12010%.

Local SGD with K=8 communication overhead: Only 1/8 as many all-reduces, so: Overheadlocal=tAR/8tAR/8+tcompute=1.661.66+1201.4%.

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 K=8, the drift term in (Local SGD Bound) adds a small bias proportional to K2η2δ2. Empirically, for diffusion models trained on curated image datasets, K=8 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-K 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:

  1. Reduce rounds via local SGD (avoiding): synchronise every K=8 steps instead of every step.

  2. Compress the remaining syncs via Top-K (avoiding): send only the top 10% of gradient coordinates, using error feedback to preserve convergence.

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

  4. Use ring attention for long sequences (avoiding): eliminate the KV gather, replacing it with a ring rotation that requires no all-reduce barrier.

  5. Apply CA matrix multiply for weight updates (avoiding): use the 2.5D distribution to reduce per-layer weight gradient communication by P1/6.

Combining all five strategies on a 1024-GPU cluster training a GPT-4 scale model (d=12288, L=96 layers) can reduce total communication from approximately 4 TB/step (naive) to approximately 0.15 TB/step (combined), a 27× reduction. With 400 Gbps interconnect, this translates from 80 ms of communication overhead per step to 3 ms, bringing the compute-to-communicate ratio from 2:1 to 50:1.

Exercises

Exercise 26 (Local SGD with heterogeneous data).

Suppose P=16 workers each hold a non-IID shard of a dataset, with gradient dissimilarity δ2=0.01 (in squared gradient norm units). The model has d=500M parameters and the loss function is L-smooth with L=10.

  1. Using the bound in Proposition 7, compute the maximum synchronisation period K such that the drift term L2η2K2δ2 does not exceed 10% of the noise term Lησ2/P, assuming σ2=1 and η=0.01.

  2. 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 K from part (a), relative to K=1.

  3. 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 P=8 GPUs processing a sequence of length L=65536 with embedding dimension d=4096.

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

  2. Ring attention requires P rounds of computation and communication. If each round takes tcomp=5 ms for the local attention and tcomm=3 ms for the KV transfer, compute the total time with and without overlapping compute and communication.

  3. 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 P/2. 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 P workers and mixing matrix Wpp=1/2, Wp,p±1modP=1/4.

  1. The spectral gap of the ring mixing matrix is 1cos(2π/P)2π2/P2 for large P. Compute the number of gossip rounds needed for the mixing error (Wt𝟏𝟏/P)θ0 to fall below ϵθ0.

  2. Compare this to the exponential graph (spectral gap 1/2) in terms of rounds required for the same ϵ. Express the improvement factor as a function of P.

  3. For a diffusion model with d=108 parameters trained on P=256 workers, compute the wall-clock time for gossip SGD to converge to the same accuracy as all-reduce SGD (assume each gossip round exchanges O(d/P) 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 f𝜽:𝒳𝒴 be a neural network with parameters 𝜽P, and let 𝒟={(𝒙i,𝒚i)}i=1N be a training dataset. Data parallelism with K workers partitions each mini-batch 𝒟 of size B into K disjoint shards 1,,K with |k|=B/K for each k, and maintains K identical copies 𝜽(1)==𝜽(K)=𝜽 of the parameters. At each training step t:

  1. Each worker k independently computes the local loss (Local LOSS)k(𝜽)=1|k|(𝒙,𝒚)k(f𝜽(𝒙),𝒚).

  2. Each worker k computes the local gradient 𝒈k=𝜽k(𝜽(k)) via backpropagation.

  3. A collective all-reduce operation computes the globally averaged gradient (Global GRAD)𝒈=1Kk=1K𝒈k, and delivers 𝒈 to every worker simultaneously.

  4. Every worker applies the same parameter update 𝜽𝜽η𝒈, maintaining the invariant 𝜽(1)==𝜽(K).

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 (𝜽)=1B(𝒙,𝒚)(f𝜽(𝒙),𝒚).

The invariant 𝜽(1)==𝜽(K) 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 k loads its local shard k from storage (or from a distributed data loader), pushes it through the network f𝜽(k), and computes the local loss k. 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 K-th worker reduces wall-clock time per step by exactly 1/K.

For generative models the forward pass often involves additional stochasticity. In a diffusion model, each forward pass samples a noise level t𝒰({1,,T}) 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 𝒈k=𝜽k(𝜽) on each worker using the standard backpropagation algorithm. Each worker's gradient 𝒈k 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 B/K 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 𝒈=1Kk𝒈k. This average has the same expectation as each local gradient but variance reduced by a factor of K relative to a single-worker gradient on a shard of size B/K, and is statistically equivalent to a gradient computed on the full mini-batch of size B. 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 𝜽t and then apply that gradient after the server has already applied updates from τ>0 other workers, yielding the update 𝜽t+τ𝜽t+τη𝒈(𝜽t). 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: (a+b)+ca+(b+c) in IEEE 754 arithmetic. When the all-reduce aggregates K 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.

Data-parallel training flow with four GPU workers. The training dataset 𝒟 is partitioned into disjoint shards 1,,4. Each GPU holds an identical copy of the model f𝜽 and independently performs a forward and backward pass on its local shard, producing a local gradient 𝒈k. An all-reduce collective then averages the four local gradients into the global gradient 𝒈, which is delivered to every GPU simultaneously. All four workers apply the identical parameter update, maintaining the replica synchronisation invariant 𝜽(1)==𝜽(4) throughout training. The only communication occurs during the all-reduce step.

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 r{0,,K1}. 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 P 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 k receives indices {i:imodK=k} 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 K workers multiplies the effective batch size by K. A natural question arises: if the batch size increases K-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 K workers each processing a local mini-batch of size b, the effective batch size is (Effective Batch)Beff=Kb. 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 Beff. Consequently, all hyperparameter choices that depend on batch size- learning rate, learning rate schedule, weight decay-should be treated as functions of Beff, not of b.

The linear scaling rule.

Consider SGD with learning rate η and mini-batch size B. After one step, parameters move by η𝒈B, where 𝒈B is the mean gradient over B samples. If instead we use batch size B=λB (with λ-fold more data per step), the mean gradient changes but the step magnitude is now η𝒈Bη𝒈B (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)η=BeffBbaseηbase. Here Bbase and ηbase are the reference batch size and learning rate (typically tuned for a single-GPU run), and Beff=Kb 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 Beff, and (ii) very large batch sizes (beyond the critical batch size B), 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 Beff 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 η=(Beff/Bbase)ηbase 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)ηt=tTwarmη,t{1,,Twarm}, where Twarm is the number of warmup steps (typically 1000–5000 for LLM pre-training, or 500–2000 for diffusion model training). After step Twarm, the learning rate is held at η or decayed by a cosine, linear, or inverse-square-root schedule.

Goyal et al. recommend setting Twarm 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 4×106 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 v^t is very small (it is initialised to zero and accumulates only gradually), causing the effective step size η/v^t+ε 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 v^t 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 32×8=256 sequences, or approximately 256,000 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 N parameters for approximately 20N 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 2×1013/105=2×108 seconds 6.3 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)simple(𝜽)=𝔼t,𝒙0,𝝐[𝝐𝝐𝜽(𝒙t,t)2], where 𝒙t=αt𝒙0+1αt𝝐 with 𝝐𝒩(𝟎,𝐈) and t𝒰({1,,T}). Each training sample involves independently sampling 𝒙0 from the dataset, t 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 64×64×4 at standard compression rate):

  • Each GPU processes a local batch of b=16 latents per step.

  • Each GPU independently samples noise levels t and noise vectors 𝝐-different GPUs will have different (ti,𝝐i) pairs even for the same image 𝒙0.

  • The U-Net backbone (860M parameters in SD 1.x) fits comfortably in GPU memory alongside activations for b=16 latents.

  • After backpropagation, the 860M-parameter gradient requires an all-reduce of approximately 860M×2=1.72 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 b=16 latent images per step; effective batch size Beff=32×16=512.

Compute time. Each forward-backward pass on an A100 at BF16 precision on a 64×64×4 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 860M×2=1.72 GB of BF16 gradient data. Ring all-reduce (Section All-Reduce: The Workhorse of Distributed Training) requires communicating 2(K1)/K×1.722×1.72=3.44 GB total across 32 links. At InfiniBand HDR bus bandwidth of 25 GB/s per GPU, communication time 1.72/2569 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: 140 ms.

Throughput. Steps per second per GPU: 1/0.147.1 steps/s. Images per second (across all 32 GPUs): 32×16×7.13,635 images/s.

Comparison. A single A100 at b=16 achieves 16/0.12133 images/s. The 32-GPU speedup is 3,635/13327.3×, corresponding to an efficiency of 27.3/3285%. 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 O(P) in gradient size regardless of the number of GPUs K (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 (𝜽)=1Bi=1B(f𝜽(𝒙i)) be the mini-batch loss over a batch of size B. Partition the batch into K equal shards of size b=B/K, and let k(𝜽)=1bi=(k1)b+1kb(f𝜽(𝒙i)) be the local loss on shard k.

  1. (a)

    Show algebraically that 𝜽(𝜽)=1Kk=1K𝜽k(𝜽), i.e., that the averaged local gradients exactly equal the full mini-batch gradient.

  2. (b)

    Let σ2=Var[𝜽(f𝜽(𝒙))] be the per-sample gradient variance (a scalar, for simplicity). Show that the variance of 1Kk=1K𝒈k is σ2/B, the same as the variance of a gradient computed on the full batch of size B.

  3. (c)

    What does this imply for the training dynamics of a data-parallel job relative to a single-GPU job with effective batch size B?

Exercise 30.

(Linear Scaling Rule and Warmup Design.) You are training a diffusion model on a single A100 GPU with local batch size b=32, learning rate ηbase=104, and a warmup of Twarm=1000 steps. You scale out to K=16 GPUs using data parallelism, keeping the local batch size b=32 per GPU.

  1. (a)

    Compute the new effective batch size Beff and, using the linear scaling rule, determine the new peak learning rate η.

  2. (b)

    Suppose you also scale the warmup duration proportionally to Beff. How many warmup steps Twarm should you use? Justify your answer in terms of the expected parameter change per effective unit of data processed.

  3. (c)

    An alternative strategy keeps the learning rate fixed at ηbase 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 B.

Exercise 31.

(DDP Bucketing and Communication-Computation Overlap.) A transformer language model has L=24 layers, each with P=50M parameters in BF16 (2 bytes each). DDP uses a bucket size of Cbucket=25 MB. The backward pass proceeds from layer L to layer 1, and each layer's backward computation takes Δ=8 ms. The all-reduce for a full bucket of 25 MB takes tar=5 ms on the available NVLink interconnect.

  1. (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.)

  2. (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).

  3. (c)

    Suppose a training run uses gradient accumulation with G=4 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 K GPU workers, each holding a local gradient vector 𝒈kP, collectively compute the global average 𝒈=1Kk=1K𝒈k 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:

  1. Reduce. Every worker k0 sends its gradient 𝒈k to a designated root (rank 0). Rank 0 receives K1 gradients and computes the sum 𝒈~=k=0K1𝒈k. Total data received by rank 0: (K1)N bytes, where N=Pd bytes is the gradient size (P parameters, d bytes each).

  2. Broadcast. Rank 0 sends 𝒈~ back to all other workers. Total data sent by rank 0: (K1)N bytes.

Total communication volume at the root: 2(K1)N bytes. Total communication time (assuming the root has bandwidth β bytes/second and all links operate serially): (Naive AR)Tnaive=2(K1)Nβ2KNβfor large K. This is a root bottleneck: all K1 inbound gradient streams and all K1 outbound broadcast streams pass through rank 0. As K grows, the root's bandwidth requirement grows linearly, making this approach bandwidth-suboptimal.

For a concrete illustration: 256 GPUs, 70B parameters in FP32 (N=280 GB). If the root GPU has 200 Gb/s (25 GB/s) bandwidth: Tnaive2×255×280/255,712 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 O(K) to O(log2K). The algorithm has two phases:

Reduction phase (leaves to root).

At each level of a balanced binary tree of depth D=log2K, each parent node receives gradients from its two children and accumulates them. After D 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 D levels, all workers hold 𝒈~.

Total time (assuming α is network latency per hop and β is bandwidth): (TREE AR)Ttree=2Dα+2Nβ2log2(K)α+2Nβ. The latency term 2log2(K)α is excellent-it grows only logarithmically in K. However, the bandwidth term 2N/β is suboptimal: every step transmits the full N-byte gradient through each tree edge, and the internal nodes are bottlenecked at N/β 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 K.

Algorithm Description

Arrange K workers in a directed ring: worker k sends to worker (k+1)modK and receives from worker (k1)modK. Divide each gradient vector 𝒈kP into K equal chunks: 𝒈k=[𝒈k(0),𝒈k(1),,𝒈k(K1)], each of size N/K bytes.

Phase 1: Reduce-Scatter (K1 rounds).

In each round r{0,,K2}, every worker k sends chunk (kr)modK to its right neighbour (k+1)modK and accumulates the received chunk into its own copy. After K1 rounds, each worker k holds the fully reduced (summed across all workers) version of chunk k: 𝒈~(k)=j=0K1𝒈j(k).

Phase 2: All-Gather (K1 rounds).

In each round r{0,,K2}, every worker k sends its fully-reduced chunk (kr)modK to its right neighbour. After K1 rounds, every worker holds all K reduced chunks and can assemble the global sum 𝒈~.

Both phases involve (K1) rounds of sending and receiving N/K bytes per round, for a total communication volume of 2(K1)N/K bytes per worker. The total time is: (RING AR)Tring=2(K1)α+2(K1)KNβ2Kα+2Nβfor large K. As K with N fixed, the bandwidth term 2N/β is independent of K: every worker sends and receives exactly 2N/KK=2N bytes per step but does so K at a time in parallel. The latency term 2Kα grows linearly in K, which can be significant for very high K over high-latency interconnects.

Ring all-reduce with four GPUs. Left: In the reduce-scatter phase, each GPU sends a chunk of its local gradient to the next GPU in the ring. After K1=3 rounds, each GPU k holds the fully reduced sum g~(k)=j=03gj(k) of chunk k. Right: In the all-gather phase, each GPU propagates its fully-reduced chunk around the ring. After K1=3 further rounds, every GPU holds all four reduced chunks and can assemble the complete global gradient 𝒈=14𝒈~. Total communication per GPU: 2(K1)/KN2N bytes, independent of K.

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 K workers, each contributing N bytes, is bandwidth-optimal if the total data communicated per worker is Θ(N), independent of K. Equivalently, every worker's outgoing (or incoming) link is utilised at Θ(N/T) bytes per second, where T 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 2(K1)N/K bytes.

Proposition 8.

(Ring All-Reduce Achieves the Bandwidth Lower Bound.) Let K workers each hold an N-byte gradient vector. Any correct all-reduce algorithm must require each worker to transmit at least (K1)N/K bytes and receive at least (K1)N/K bytes (ignoring latency). Ring all-reduce transmits exactly 2(K1)N/K bytes per worker ((K1)N/K in reduce-scatter and (K1)N/K in all-gather), achieving this lower bound up to the constant factor 2 arising from bidirectional communication.

Proof.

We prove the lower bound. Consider the K workers as nodes of a communication graph. After the all-reduce, every worker must hold the global sum 𝒈~ of all K local vectors. Fix any worker k. The K1 other workers' vectors {𝒈k}kk each contribute N/K bytes to each of the K chunks of 𝒈~. Worker k must receive information about all K1 other vectors. Since each such vector is N bytes and the information cannot be compressed below N bytes (assuming gradients are incompressible), worker k must receive at least (K1)(N/K) 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 k's incoming link must carry at least (K1)N/K bytes.) Since k was arbitrary, the bound applies to every worker. Symmetrically, worker k must transmit its own gradient 𝒈k to every other worker (each needs it for the reduction), requiring at least (K1)(N/K) 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 N is large (bandwidth-dominant regime) but suffers when N is small because the 2(K1) sequential rounds of latency α each accumulate: Tring2Kα. 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 O(logK) while maintaining near-bandwidth-optimal data movement. The algorithm operates in log2K steps (assuming K is a power of 2):

Reduce-scatter via recursive halving.

At step s=0,1,,log2K1: each worker pairs with the worker at distance 2s in the ring, and exchanges halves of its current gradient accumulation. After log2K steps, each worker holds 1/K of the fully reduced gradient.

All-gather via recursive doubling.

The reverse: at each of log2K steps, each worker pairs with the worker at distance 2s and exchanges its current chunk, doubling the amount of fully-reduced data each worker holds.

Total time: (Recdouble AR)Trec=2log2(K)α+(K1)K2Nβ2log2(K)α+2Nβ. The latency term matches the tree all-reduce: O(logK). The bandwidth term matches ring all-reduce: 2N/β. 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 (N256 KB): latency is dominant. NCCL uses a double binary tree algorithm that achieves O(logK) latency.

  • Large messages (N4 MB): bandwidth is dominant. NCCL uses ring all-reduce, achieving 2N/β 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 K 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 O(logK) latency.

Formally, for K=2d workers arranged as ranks {0,,K1}, NCCL constructs:

  • Tree A: standard binary tree rooted at rank 0, with internal nodes {0,K/4,K/2,3K/4,}.

  • Tree B: shifted binary tree rooted at rank K/2, 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:

  1. Gradient computation. Backpropagation produces gradients in BF16 (matching the activation precision).

  2. All-reduce in BF16. The ring all-reduce communicates BF16 gradients, halving the communication volume relative to FP32. Communication time: NBF1/β where NBF1=2P bytes.

  3. 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 270.8%. 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 (65,504), corrupting the all-reduce. Loss scaling-multiplying the loss by a large constant s before backpropagation and dividing gradients by s 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 N.

All-reduce algorithm comparison for K=64 GPUs with per-link bandwidth β=200 Gb/s and latency α=5μs (NVLink-class interconnect). For small messages (N4 MB), latency dominates and the double binary tree (and recursive halving-doubling) outperform ring all-reduce, which pays O(Kα) latency. For large messages (N4 MB), bandwidth dominates and ring all-reduce and recursive halving-doubling converge to the same 2N/β cost, while tree all-reduce is suboptimal (higher bandwidth coefficient). NCCL's hybrid algorithm (dotted amber) follows the tree for small messages and switches to ring for large messages, tracking the Pareto-optimal frontier.

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 K=256 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. P=70×109 parameters. N=P×4=280 GB in FP32.

Naive all-reduce time. Root receives (K1)×N=255×280=71,400 GB. At 25 GB/s: 71,400/252,856 s. Manifestly impractical.

Ring all-reduce time (FP32). Using Eq. : Tring2Kα+2Nβ=2×256×5×106+2×280250.003+22.422.4 s. The bandwidth term dominates.

Ring all-reduce time (BF16). In BF16, the gradient tensor is NBF1=140 GB: TringBF12×1402511.2 s.

Compute time per step. On 256 A100 80 GB GPUs at BF16 precision with local batch size b=2 sequences of 2048 tokens (effective batch size Beff=512 sequences 106 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 (11 s in BF16) vs. compute time (25 s): communication-to-compute ratio 0.44. Even with perfect overlap, a residual 1125= 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 K=4 workers, each holding a gradient vector partitioned into K=4 chunks: 𝒈k=[gk(0),gk(1),gk(2),gk(3)] for k{0,1,2,3}. The ring is 01230.

  1. (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 j=abgj(c) as Sa:b(c) and express each entry in terms of these partial sums.

  2. (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.

  3. (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 𝒈~=k=03𝒈k in all four chunk positions.

Exercise 33.

(Algorithm Selection and Performance Analysis.) You are choosing an all-reduce algorithm for a training job with K=32 GPUs. The interconnect has latency α=2μs and bandwidth β=50 GB/s per link. Consider three gradient sizes arising in three different training scenarios:

  1. (a)

    N=100 KB (a single transformer layer's attention projection weights, e.g., for gradient accumulation with per-layer all-reduce).

  2. (b)

    N=50 MB (a small 125M-parameter language model in BF16).

  3. (c)

    N=14 GB (a 7B-parameter model in BF16).

For each scenario: (i) compute Ttree, Tring, and Trec 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 (P=13×109) is trained with K=128 GPUs using ring all-reduce. InfiniBand bandwidth per GPU is β=25 GB/s.

  1. (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?

  2. (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 P/8 bytes. Compute the ring all-reduce time for 1-bit gradients and compare it to BF16. What is the compression ratio?

  3. (c)

    Suppose INT8 gradient quantisation introduces a relative quantisation error of εq=27 in the gradient values, and this error accumulates for T=10,000 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 Tεq 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 d=8192 and four linear projections holds approximately 4×81922×2,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 dmodel, determines the size of each weight matrix. Depth, measured by the number of transformer blocks L, determines how many such matrices must be loaded.

For a single multi-head attention layer with hidden dimension d, query/key/value dimension dkv, and H attention heads, the parameter count is: (ATTN Params)Nattn=3ddkv(Q, K, V projections)+dkvd(output projection)=4d2when dkv=d. The feed-forward network (FFN) that follows the attention block typically uses an expansion ratio of 4, giving: (FFN Params)Nffn=2×4d2=8d2. Combined, a single transformer layer holds Nlayer=12d2 parameters, and the entire model: (Total Params)Ntotal=12Ld2. For LLaMA-70B with L=80 and d=8192, this yields Ntotal64.4×109 - 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 1+2+2=5× - 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 f:B×dinB×dout be a linear layer with weight matrix 𝐖din×dout and input 𝐗B×din, computing 𝐘=𝐗𝐖. Tensor parallelism over T devices partitions 𝐖 along one of its axes into T shards {𝐖(1),,𝐖(T)} such that 𝐖=concat(𝐖(1),,𝐖(T),axis=split axis), where device i stores and computes with 𝐖(i) 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 T devices, define: (COL Split)𝐖=[𝐖1|𝐖2||𝐖T],𝐖idin×(dout/T). The full input 𝐗B×din is replicated across all T devices. Device i computes a partial output: (COL Compute)𝐘i=𝐗𝐖i,𝐘iB×(dout/T). The full output is recovered by concatenating across the column dimension: (COL Concat)𝐘=[𝐘1|𝐘2||𝐘T]B×dout. 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 T devices: (ROW Split)𝐖=[𝐖1𝐖2𝐖T],𝐖i(din/T)×dout. The input 𝐗 is correspondingly split along the feature dimension, so device i holds: (ROW Input)𝐗iB×(din/T). Each device computes a partial output: (ROW Compute)𝐘~i=𝐗i𝐖i,𝐘~iB×dout. The full output is the sum of all partial outputs, recovered by an all-reduce operation: (ROW Allreduce)𝐘=i=1T𝐘~i. This all-reduce is the sole communication point of a row-parallel layer.

Column-parallel vs. row-parallel matrix multiplication across two GPUs. In column-parallel mode, each GPU holds a subset of columns of 𝐖 and processes the full input independently; outputs are concatenated without communication. In row-parallel mode, each GPU holds a subset of rows and a partition of the input; outputs are summed via an all-reduce.

Self-Attention Parallelism: Splitting Heads Across GPUs

Multi-head attention provides a natural structure for tensor parallelism: the H attention heads are independent of one another within a single attention layer. Head h attends only to queries, keys, and values projected by the matrices 𝐖hQ, 𝐖hK, 𝐖hV of dimension d×dh where dh=d/H. There is no cross-head interaction until the outputs are concatenated and projected by 𝐖O.

This structure maps precisely onto column-parallel computation. Partition the H heads across T devices, with H/T heads per device. Let 𝐐=𝐗𝐖Q, 𝐊=𝐗𝐖K, 𝐕=𝐗𝐖V. Denote the block of heads assigned to device i as the index set i={(i1)H/T+1,,iH/T}. Device i computes: (ATTN HEAD Parallel)headh=softmax(𝐐h𝐊hdh)𝐕h,hi. The result of each device is a partial attention output of size B×S×(H/T)dh, where S is the sequence length. Concatenation across devices produces the full B×S×d attention output, and the output projection 𝐖O 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)𝐙=GeLU(𝐗𝐖1+𝐛1),𝐘=𝐙𝐖2+𝐛2, where 𝐖1d×4d and 𝐖24d×d. The Megatron strategy applies column-parallelism to 𝐖1 and row-parallelism to 𝐖2:

  1. Column-parallel 𝐖1. Device i holds 𝐖1(i)d×(4d/T) and computes 𝐙i=GeLU(𝐗𝐖1(i)). The GeLU is applied locally since it is element-wise. No communication is needed.

  2. Row-parallel 𝐖2. Device i holds 𝐖2(i)(4d/T)×d and computes 𝐘~i=𝐙i𝐖2(i). The partial sums are reconciled by an all-reduce: 𝐘=i=1T𝐘~i.

The critical property is that the column split of 𝐖1 partitions the intermediate (expansion) dimension. Device i's output 𝐙i is exactly the chunk of intermediate features needed as input to its shard of 𝐖2. No cross-device communication is needed between the two layers.

The Megatron Transformer Block: Communication Cost

Megatron-style tensor-parallel transformer block across two GPUs. Each GPU holds complementary shards of the weight matrices. The column-parallel QKV and FFN1 layers need no inter-device communication; only two all-reduce operations are required per transformer layer - one after the attention output projection and one after the FFN output projection.

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 B×S×d (for batch size B, sequence length S, hidden dimension d).

Proposition 9 (Communication Volume per Layer).

With T tensor-parallel devices, the all-reduce in the ring-allreduce algorithm requires each device to send and receive T1TBSd2 bytes of data per all-reduce (the factor of 2 accounts for BF16 storage), for a total of 4(T1)TBSd bytes per transformer layer. For large T, this approaches 4BSd bytes per layer regardless of T - 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, H query heads share G<H KV heads, with each group of H/G query heads attending to a single KV head. This changes the head-parallelism strategy.

Let T be the tensor-parallel degree. For correctness, the number of KV heads G must be divisible by T, so that each device holds exactly G/T complete KV groups. Each device's query heads i must be aligned with its KV head assignments: device i processes query heads {(i1)H/T+1,,iH/T} and KV heads {(i1)G/T+1,,iG/T}. If G<T (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 𝐜t and class or text embedding 𝐜cond. 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 2d (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 Tv=16 frames at 512×512 resolution with patch size p=2 produces 16×(512/2)2=16×65536=1,048,576 tokens per sample - over one million tokens. With hidden dimension d=4096 and 28 transformer blocks, the parameter count for attention and FFN layers is approximately 12×28×409625.7×109 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 11.4/4=2.85,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 B×S×4096 BF16 - roughly 8,GB at batch size 1 and S=106 tokens, transmitted at NVLink speed (13,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 L=80 layers, d=8192, H=64 query heads, G=8 GQA heads, and an FFN expansion dimension of dffn=28672 (using SwiGLU, which has three weight matrices). We compute memory savings and communication cost for T=8-way tensor parallelism.

Parameter memory. The total parameter count for attention and FFN layers is: Nattn=L(ddQH/H+2ddKVG/G+d2)4×80×81922=21.5×109params,Nffn=L×3×d×dffn=80×3×8192×28672=56.4×109params. Total: 78×109 parameters, requiring 156,GB at BF16. With T=8: each GPU holds 156/8=19.5,GB of parameters. With Adam optimizer states (factor 4× in float32 for full training): 19.5×4=78,GB optimizer memory per GPU - tight but feasible on 80,GB H100s.

Communication overhead. Each transformer layer requires 2 all-reduces of size B×S×8192 BF16. For B=1, S=4096: 2×4096×8192×2=128,MB per layer, or 128×80=10.24,GB total per forward pass. Over NVLink at 600,GB/s effective bandwidth: 17,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 T=8, 16 all-reduces (2 per layer × 8 layers per NVLink domain) must be serialized along the critical path. Beyond T=8 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 T{4,8} 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 𝐖i is 𝐖i=𝐗𝐘i 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 H=32 query heads and G=4 KV heads.

  1. (a)

    What is the maximum tensor-parallel degree T that allows exact head partitioning of the KV cache?

  2. (b)

    If you wish to use T=8, describe a strategy that replicates KV heads across devices and maintains correctness.

  3. (c)

    What is the memory cost of KV replication relative to the naive single-device KV cache, for a context of length S=8192 and head dimension dh=128 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 f=fLfL1f1 consist of L sequential transformer blocks. Pipeline parallelism over P devices assigns a contiguous slice p={f(p1)L/P+1,,fpL/P} of L/P blocks to device p{1,,P}. Device p receives the activation output from device p1, applies its assigned blocks, and sends the result to device p+1. Forward and backward passes are decomposed into M micro-batches {𝐱(1),,𝐱(M)} of size B/M 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 B is split into M micro-batches. The forward pass of all M micro-batches runs through all P pipeline stages before any backward pass begins. Only then does the backward pass execute through all stages for all micro-batches.

Let tf denote the time for one forward micro-batch through one stage, and tb the time for one backward micro-batch through one stage (typically tb2tf). The total time for the GPipe schedule is: (Gpipe TIME)TGPipe=(M+P1)(tf+tb). The ideal time (if the pipeline were perfectly full and there were no bubble) would be M(tf+tb), using all P stages simultaneously. The bubble fraction is: (Gpipe Bubble)ϵbubbleGPipe=TGPipeM(tf+tb)TGPipe=P1M+P1. For MP, the bubble fraction approaches zero. For M=P=4 (a common setting), the bubble is 3/743% - nearly half the pipeline is idle at any given moment.

Remark 22 (GPipe memory cost).

GPipe must store activations for all M micro-batches simultaneously before the backward pass begins. The activation memory per device is proportional to M×B/M=B - 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 M and P), but with the key advantage that steady-state activation memory is O(P) rather than O(M).

In steady state, each device alternates between one forward micro-batch and one backward micro-batch. Device p processes the forward pass of micro-batch m and immediately queues the backward pass of micro-batch mP+p, 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)ϵbubble1F1B=P1M+P1. However, the maximum number of in-flight activations on any single device at any time is P micro-batches (one per pipeline stage), compared to M micro-batches in GPipe.

Proof.

In steady state, device p holds activations for the Pp micro-batches that have passed through device p's forward pass but have not yet reached their backward pass through device p. In the worst case (device 1), this is P1 micro-batches. Thus the peak activation memory on any device is proportional to P, independent of M. The bubble fraction computation follows from the same accounting as GPipe: the pipeline requires P1 startup steps and P1 drain steps, contributing (P1)(tf+tb) of idle time against a total of (M+P1)(tf+tb).

Pipeline Schedules: GPipe vs. 1F1B

GPipe vs. 1F1B pipeline schedules for P=4 stages and M=4 micro-batches. Gray cells represent idle (bubble) time. Both schedules have the same bubble fraction (P1)/(M+P1)=3/7, but 1F1B interleaves forward and backward passes to reduce peak activation memory from O(M) to O(P) micro-batches per device.

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 V virtual pipeline stages (chunks), the effective pipeline has PV stages, and the bubble fraction is: (Interleaved Bubble)ϵbubbleinterleaved=1VP1M+P1. The factor of 1/V 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 V.

In practice, V=2 or V=4 is common. With P=8, M=16, and V=4, the bubble fraction is: ϵ=147237.6%. 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:

  1. A text encoder (frozen during fine-tuning, often shared across requests).

  2. A diffusion backbone (U-Net or DiT, the primary trainable component).

  3. 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 Nsteps sequential denoising steps, each a full forward pass through the backbone. This means a single inference request produces Nsteps sequential activations through the pipeline - exactly the M micro-batches that fill the pipeline. For Nsteps=50 denoising steps and P=8 pipeline stages, the bubble fraction is (81)/(50+81)=7/5712%, 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 d and sequence length S, the activation memory for a single layer is: (SEQ Activation)act=B×S×d×Nbytes, where Nbytes=2 for BF16. For B=1, S=32768, d=8192, this is 1×32768×8192×2=512,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 O(S2)) are considered.

The solution is to split the sequence dimension itself across devices. This is sequence parallelism.

Definition 25 (Sequence Parallelism).

Sequence parallelism over T devices partitions the sequence dimension of the activation tensor 𝐗B×S×d along the S axis, so that device i holds 𝐗(i)B×(S/T)×d. 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 i and key-values are sharded across all T 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 T devices into a logical ring. At each step of the ring, each device:

  1. 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).

  2. Sends the current key-value chunk to the next device in the ring while receiving the next key-value chunk from the previous device.

  3. Accumulates the attention output using the flash-attention online softmax trick, which allows partial softmax accumulators to be updated iteratively.

Formally, let device i hold query chunk 𝐐(i)B×(S/T)×dh×H and, initially, key-value chunk 𝐊(i),𝐕(i)B×(S/T)×dh×H. After T ring steps, device i has accumulated: (RING ATTN)𝐎(i)=softmax(𝐐(i)[𝐊(1);;𝐊(T)]dh)[𝐕(1);;𝐕(T)], which is the correct full-sequence attention output for the query chunk on device i.

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 (𝐦i,i) - 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 O(S/T) memory per device rather than O(S2/T) for the full attention matrix.

The communication in ring attention consists of T1 rounds of passing the key-value chunks around the ring. Each round communicates 2×B×(S/T)×dh×H×Nbytes bytes (factor of 2 for K and V). For B=1, S=131072 (128K context), T=8, H=32, dh=128, BF16: 2×1×1310728×128×32×2=2×16384×128×32×2=268 MB per ring step. Over 7 steps: 7×268=1.88,GB of communication per attention layer. At NVLink bandwidth (600,GB/s), this requires 3.1,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 S=1,048,576 (1M tokens) with d=8192, the activation tensor alone requires 1,048,576×8192×2=16,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 t attends only to tokens 1,,t. 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 {1,,S/T}, {S/T+1,,2S/T}, etc., each device receives every T-th token: (CP Stripe)𝒮i={i,i+T,i+2T,},i{1,,T}. 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

Sequence parallelism with ring attention across T=4 devices. Each device holds a shard of the sequence (tokens 1–4, 5–8, 9–12, 13–16). Layer norm and FFN are applied locally. Self-attention is computed by circulating key-value chunks around the ring for T1 steps; each device accumulates the full-context attention output for its query shard using the flash-attention online softmax.

Comparison of Parallelism Strategies

Table tab:distgen:parallelism-comparison summarises the four main parallelism strategies and their key properties.

StrategyWhat is splitComm. patternMemory savingBest for
Data parallel (DP)Mini-batchAll-reduce gradientsNone (parameters replicated)Small models
Tensor parallel (TP)Weight matrices2 all-reduces per layer1/T parameters/GPUIntra-node (NVLink)
Pipeline parallel (PP)Transformer layersPoint-to-point activations1/P parameters/GPUInter-node (IB/Eth)
Sequence parallel (SP)Sequence dimensionRing KV all-gather1/T activations/GPULong contexts (>32K)
Comparison of parallelism strategies for distributed training of large generative models. “Comm. pattern” refers to the collective operation required per layer. “Memory savings” refers to parameter memory; activation savings depend on configuration.

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

  • TP degree: Tensor parallelism within each node, typically T{4,8}.

  • PP degree: Pipeline stages across nodes, typically P{4,8,16}.

  • SP degree: Sequence parallelism equal to TP degree (shared communication groups).

The total number of GPUs is DP×TP×PP. 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 G be the total number of GPUs. A 3D parallel configuration assigns each GPU a unique triplet (d,p,t) where d{1,,D} is the data parallel rank, p{1,,P} is the pipeline stage, and t{1,,T} is the tensor parallel rank, with D×P×T=G. All GPUs sharing the same (d,p) form a tensor-parallel group (communicating via NVLink all-reduce). All GPUs sharing the same (d,t) form a pipeline group (communicating via point-to-point sends). All GPUs sharing the same (p,t) 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 M. To keep the pipeline full and the bubble fraction below 10%, we need M9(P1) (from the bubble fraction formula with ϵ<0.1). For P=16, this requires M135 micro-batches. If each micro-batch has Bμ=2 samples with sequence length S=2048, the total batch size is MBμ=270 samples, or roughly 270×2048=552,960 tokens per gradient step. This is consistent with the global batch sizes used in large LLM training (4 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 m on stage p 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 P1 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 M micro-batches have completed their full forward-backward passes, at which point a single synchronised update is applied.

Exercises

Exercise 38 (Bubble fraction algebra).

  1. (a)

    Derive the bubble fraction formula for the GPipe schedule from first principles. Specifically, draw the time-space diagram for P=3 stages and M=5 micro-batches, identify the idle time, and verify Equation .

  2. (b)

    Show that for fixed total compute time, increasing M always reduces the bubble fraction, and compute the asymptotic bubble fraction as M.

  3. (c)

    For P=8 and a target bubble fraction of at most 5%, what is the minimum number of micro-batches M required?

Exercise 39 (Ring attention communication complexity).

Consider ring attention over T devices with sequence length S, hidden dimension d, H attention heads, and head dimension dh=d/H.

  1. (a)

    Derive the total bytes of communication per layer per forward pass in ring attention.

  2. (b)

    Compare this to the all-reduce communication cost of tensor parallelism (Proposition Proposition 9) for the same T and d. Under what conditions (as a function of S and T) does ring attention communicate more than tensor parallelism?

  3. (c)

    For S=1,048,576, d=4096, H=32, T=8, 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 (L=96 layers, d=12288, H=96 heads).

  1. (a)

    Enumerate all valid 3D parallelism configurations (D,P,T) with D×P×T=256, T{4,8}, and P a divisor of L.

  2. (b)

    For each configuration, compute: (i) parameter memory per GPU, (ii) bubble fraction with M=32 micro-batches, and (iii) total communication per forward pass per GPU.

  3. (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 P copies of every tensor across P GPUs, consuming P 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 N 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 N=7×109 parameters consumes Mθ=2Nbytes=14GB.

Gradients.

Gradients are accumulated in the same precision as parameters during the backward pass - FP16, 2 bytes per parameter: M=2Nbytes=14GB.

Optimizer state.

Adam maintains three quantities per parameter in FP32 (4 bytes each): the first moment (momentum) mt, the second moment (variance) vt, and the full-precision master copy of the parameter θfp32. That is 3×4=12 bytes per parameter: Mopt=12Nbytes=84GB.

Total (before activations).

Mtotal=Mθ+M+Mopt=2N+2N+12N=16Nbytes. For N=7×109: Mtotal=112GB. 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 ηg 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 16N 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 12N bytes of Adam state, the P GPUs collectively partition it. GPU r holds optimizer state for parameter indices i such that imodP=r. Each GPU thus maintains 12N/P bytes of optimizer state rather than 12N 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 (2N bytes) and accumulates a full copy of the gradients (2N bytes) via all-reduce. After the all-reduce, however, each GPU discards the gradients it does not own: GPU r retains only 2N/P 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 N be the number of parameters and P the number of GPUs. Under ZeRO-1, the memory consumed per GPU for model state is MZeRO-1(N,P)=2Nparams (FP16)+2Ngradients (FP16)+12NPopt. state (FP32, sharded)=4N+12NPbytes. For large P this approaches 4N bytes, a 4× reduction relative to the DDP baseline of 16N bytes.

The communication overhead of ZeRO-1 relative to DDP is modest. The all-reduce on gradients is identical to DDP (communication volume 2N bytes). The additional all-gather after the optimizer step communicates another 2N bytes (FP16 updated parameters). Total communication is thus approximately 4N bytes per training step, compared with 2N bytes for DDP - a factor of two increase, but with up to 4× 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 r accumulates only the gradient shard for parameters ir(modP), discarding the rest. After the backward pass, GPU r holds 2N/P bytes of gradients and 12N/P 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 MZeRO-2(N,P)=2Nparams (FP16)+2NPgradients (sharded)+12NPopt. state (sharded)=2N+14NPbytes. For large P this approaches 2N bytes, an 8× 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 r permanently holds only the parameter shard θ(r)N/P. 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 MZeRO-3(N,P)=2NPparams (sharded)+2NPgradients (sharded)+12NPopt. state (sharded)=16NPbytes. This is the optimal linear scaling: adding P GPUs reduces the per-GPU model-state memory by a factor of exactly P.

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 (2N bytes total per pass). During the backward pass, another all-gather retrieves parameters for gradient computation (2N bytes), followed by a reduce-scatter of gradients (2N bytes). Total communication is approximately 6N bytes per step, versus 2N bytes for DDP - a factor of 3×.

Remark 27 (Communication volume comparison).

Summing the communication volumes:

MethodMemory per GPUCommunication per step
DDP (no ZeRO)16N bytes2N bytes (all-reduce)
ZeRO-14N+12N/P bytes4N bytes
ZeRO-22N+14N/P bytes4N bytes
ZeRO-316N/P bytes6N bytes
Note that ZeRO-2 achieves the same communication cost as ZeRO-1 while saving additional memory on gradients. ZeRO-3 requires 3× the communication of DDP but enables linear memory scaling with the number of GPUs.

Memory per GPU for a 7B-parameter model across ZeRO stages with P=8 GPUs. DDP replicates all state on every GPU (112 GB). ZeRO-1 shards only optimizer state (38.5 GB). ZeRO-2 additionally shards gradients (26.25 GB). ZeRO-3 shards everything, achieving linear scaling (14 GB =112/8). Activations are not included.

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 Wdout×din.

Before each layer's forward pass.

GPU r holds shard W(r), a contiguous slice of 1/P of W's flattened parameters. An all-gather operation assembles the full W on every GPU. This requires communicating |W|×2 bytes (FP16) across all P GPUs, with each GPU sending and receiving approximately |W|/P×2×(P1) bytes. After the forward pass, GPUs rr discard their copies of W(r); 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 /W correctly.

After each layer's backward pass.

Each GPU has computed a local estimate of /W. A reduce-scatter aggregates these estimates: GPU r accumulates the true gradient shard /W(r), the average over all GPUs' local estimates restricted to indices owned by r.

Optimizer step.

GPU r applies the Adam update to its shards W(r) using its local optimizer state shards m(r), v(r). No inter-GPU communication is required for this step.

The total communication per training step is thus: 2Nall-gather, forward+2Nall-gather, backward+2Nreduce-scatter, gradients=6Nbytes, which is 3× the 2N 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 +1 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 P 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 K parameter tensors {W(k)}k=1K of total size S=k|W(k)|, the flat parameter tensor is 𝐰flat=concat(vec(W(1)),,vec(W(K)))S. GPU r permanently holds shard 𝐰flat[rS/P:(r+1)S/P].

Sharding, Resharding, and the FSDP Lifecycle

The lifecycle of an FSDP unit during one training step is:

  1. All-gather (before forward): All P 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.

  2. Forward pass: The unit computes its output using the assembled full parameters.

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

  4. All-gather (before backward): The full parameters are reassembled for gradient computation.

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

  6. Reduce-scatter (after backward): The local gradient accumulation buffer is reduce-scattered, so each GPU accumulates the gradient shard corresponding to its parameter shard.

  7. Reshard: The assembled full parameters (used during backward) are freed.

  8. 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 Θ={θi}i=1N be the set of model parameters, partitioned into FSDP units 𝒰1,,𝒰L. For each unit 𝒰 and a cluster of P GPUs, FSDP assigns to GPU r the parameter shard 𝒰(r)={θi𝒰:imodP=r}, 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 MFSDP=16N/P+O(max|𝒰|), where the O() 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 G nodes each with Pnode 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 GPnode GPUs saturates the inter-node links. With hybrid sharding, only within-node all-gathers are performed (over NVLink), achieving a Pnode× 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 16N bytes per GPU but only 2N bytes of inter-GPU communication per step. ZeRO-3 shards all model state, using only 16N/P bytes per GPU - a linear reduction - but requires 6N bytes of communication, 3× 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 (N=13×109 parameters) in mixed precision on a cluster of P=8 A100-80GB GPUs.

Baseline (DDP, no sharding). MDDP=16N=16×13×109=208GB. This exceeds the 80 GB of a single A100. Training is not feasible.

ZeRO-1 (optimizer state sharded). MZeRO-1=4N+12NP=4×13+12×138=52+19.5=71.5GB. This fits within an 80 GB A100, though with little headroom for activations.

ZeRO-3 (all state sharded). MZeRO-3=16NP=16×138=26GB. 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 d=5120, sequence length L=2048, and batch size B=8, the activation memory per layer is approximately O(BLd)=8×2048×5120×2 bytes 160 MB per layer. LLaMA-13B has 40 layers, so activations occupy approximately 40×160=6.4 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 +1 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 N=70×109 parameters (70B) is trained in mixed precision using Adam on a cluster of P=64 A100-80GB GPUs using ZeRO-3.

  1. Compute the per-GPU model-state memory under ZeRO-3.

  2. What is the smallest P such that the per-GPU model-state memory is below 80 GB?

  3. If the same cluster were limited to ZeRO-1, what is the per-GPU model-state memory for P=64 GPUs? Does it fit in 80 GB?

Exercise 42 (Communication volume analysis).

Suppose inter-GPU bandwidth is Bw=200 GB/s (NVLink) and GPU compute throughput is T=312 TFLOPS (BF16). A training step processes a batch that requires C=1015 FLOPs.

  1. For a 70B model (N=70×109 parameters) with ZeRO-3, compute the total communication volume per training step in bytes.

  2. Compute the communication time at Bw=200 GB/s and the compute time at T=312 TFLOPS.

  3. Under what condition (in terms of Bw, T, C, and N) 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 (BNVLink=600 GB/s). Nodes are connected via InfiniBand HDR (BIB=50 GB/s aggregate).

  1. Compute the per-GPU memory under full ZeRO-3 across all 16×8=128 GPUs.

  2. Compute the per-GPU memory under FSDP hybrid sharding (ZeRO-3 within each node of 8 GPUs, DDP across nodes).

  3. 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?

  4. 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 f:xy with parameters θ, the gradient with respect to θ depends on the input activation x to that layer. If x is not stored, it must be recomputed from x1 (or from the network input).

For a standard transformer layer with:

  • batch size B,

  • sequence length L,

  • hidden dimension d,

  • number of attention heads H,

the activations that must be stored for backpropagation include:

  1. The input to the layer: B×L×d values.

  2. The query, key, and value projections: 3×B×L×d values.

  3. The attention scores (pre-softmax): B×H×L×L values.

  4. The attention weights (post-softmax): B×H×L×L values.

  5. The attention output before projection: B×L×d values.

  6. Feed-forward network intermediates: B×L×4d values (for the standard 4× expansion ratio).

  7. LayerNorm statistics: B×L values (mean and variance).

Summing these (and counting at 2 bytes per value in FP16): Mact, layer2[BLd+3BLd+2BHL2+BLd+4BLd]=2BL(9d+2HL)bytes. For B=4, L=2048, d=8192, H=64 (a 70B-scale model): Mact, layer2×4×2048×(9×8192+2×64×2048)2.4GB per layer. With 80 layers, total activation memory is approximately 80×2.4=192GB. This exceeds the GPU memory of an entire node of 8 A100s.

Remark 29 (Activation memory dominates at long context).

The 2BHL2 term in the activation formula shows that attention score memory grows quadratically with sequence length. For L=8192 (a common modern context length), this term is 16× larger than for L=2048. At L=32768 (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 L×L 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 f=fLfL1f1 be a L-layer neural network with input x0 and layer outputs x1,x2,,xL. Let 𝒞{0,1,,L} be the checkpoint set. Activation checkpointing stores only {x:𝒞} after the forward pass. During the backward pass, to compute gradients at layer requiring x1, the sub-network f1fprev+1 is re-executed from the most recent checkpoint xprev (where prev=max{𝒞:<}) to reconstruct x1.

The simplest instance of activation checkpointing is full checkpointing at uniform intervals: set 𝒞={0,k,2k,,L} for some interval k. Between consecutive checkpoints, no activations are stored during the forward pass; they are recomputed on demand during backpropagation.

Memory reduction.

With uniform checkpointing every k layers, the maximum activation memory is: Mact, ckpt=O(kMact, layer). Instead of LMact, layer for no checkpointing, we need only kMact, layer - a factor of L/k reduction. For L=80, k=1 (checkpoint every layer), memory reduces to O(Mact, layer), 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 2L rather than L, giving an overhead of at most 1× additional forward computation. In practice, because the backward pass is already 2× the compute of the forward pass (computing two Jacobian-vector products per layer), the overhead of full rematerialisation is approximately 33% of total training compute.

Remark 30 (The L optimal checkpoint strategy).

With C checkpoints, the optimal strategy minimises the sum of memory and recomputation. For the simplest case of uniform checkpointing, the optimal interval is k=L, yielding memory O(LMact, layer) and compute overhead O(L) 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 L heuristic is widely used in practice because it requires no profiling.

Selective Checkpointing

Full activation checkpointing at every layer incurs the full 33% 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 (B×H×L×L): large (especially at long context) but recomputable by re-executing the QK product. Good candidate for checkpointing.

  • Feed-forward intermediates (B×L×4d): large but inexpensive to recompute (one GEMM). Moderate candidate.

  • LayerNorm inputs and outputs (B×L×d): 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 L×L 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 f1,,fL be transformer layers with layer producing activations of size A and requiring recomputation time T. Let 𝒮{1,,L} be the set of layers selected for checkpointing. The total memory savings and compute overhead satisfy: ΔM(𝒮)=𝒮A,ΔT(𝒮)=𝒮T. The optimal selection maximises ΔM(𝒮) subject to ΔT(𝒮)Tmax for a given compute budget Tmax, which is a variant of the fractional knapsack problem solvable in O(LlogL) time by sorting layers by A/T 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:

  1. A working copy of parameters in half precision (FP16 or BF16, 2 bytes each) used for the forward and backward passes.

  2. A master copy of parameters in full precision (FP32, 4 bytes each) used for the optimizer update step.

  3. Optimizer state (Adam first and second moments) in FP32.

  4. Gradients computed in half precision during backpropagation and optionally scaled (see loss scaling below) before the optimizer step.

Formally, at each step t: yt=f(castfp16(θtfp32))(forward in FP16),gt=θ(yt)(backward in FP16),θt+1fp32=Adam(θtfp32,castfp32(gt))(optimizer in FP32), where castfp16 and castfp32 denote precision casting operations.

Loss Scaling for FP16 Training

FP16 arithmetic has a dynamic range spanning approximately [6×108,6.5×104]. 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 6×108, 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 S>1 before backpropagation. By the chain rule, all gradients are scaled by S, shifting them into the FP16 representable range. Before the optimizer step, gradients are divided by S to restore their true values.

Algorithm 6 (Dynamic Loss Scaling).

  1. Initialise scale SS0 (e.g., 216).

  2. For each training step: enumerate

  3. Compute loss in FP32.

  4. Scale: ^S.

  5. Backward: compute g^=^ in FP16.

  6. Check for overflow: if any element of g^ is ± or NaN, skip the optimizer step and halve S: SS/2.

  7. Otherwise: unscale gg^/S, apply optimizer step with g.

  8. Every K steps without overflow, double S: S2S. enumerate

Dynamic loss scaling adapts S 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:

FormatSign bitsExponent bitsMantissa bits
FP321823
BF16187
FP161510

The critical difference is the number of exponent bits. FP32 and BF16 share 8 exponent bits, giving them the same dynamic range (1038 to 3.4×1038). FP16 has only 5 exponent bits, restricting its dynamic range to 108 to 6.5×104. 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 270.78%, versus 2100.097% 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 2× 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:

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

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

  3. 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 1.3× wall-clock speedup (after accounting for scaling overhead).

Mixed Precision Training Flow

Data-type flow in mixed precision training with dynamic loss scaling. Weights are cast from FP32 master copies to FP16 for the forward and backward passes. The loss is scaled by S to prevent gradient underflow in FP16. Gradients are unscaled and cast to FP32 before the Adam update, which maintains optimizer state (first and second moments) in FP32. The master weights are updated in FP32, and the cycle repeats. BF16 training omits the loss scaling steps (dashed in conception) because BF16 shares FP32's dynamic range.

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 2× 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 TechniqueMemoryComputeNotes
ReductionOverhead
ZeRO-1Up to 4× (opt. state)2× comm.Shards optimizer state only; minimal overhead
[4pt] ZeRO-2Up to 8× (opt. + grads)2× comm.Also shards gradients; same comm. as ZeRO-1
[4pt] ZeRO-3 / FSDPUp to P× (all state)3× comm.Full linear memory scaling; best for very large models
[4pt] ZeRO-InfinityBeyond GPU HBM510× latencyOffloads to CPU/NVMe; low throughput
[4pt] Activation Ckpt. (full)6080% activation memory+33% FLOPsRecomputes all activations; significant overhead
[4pt] Activation Ckpt. (selective)4060% activation memory+1015% FLOPsCheckpoints only high-memory layers
[4pt] Activation Compression (INT8)50% activation memory5% overheadQuantise stored tensors; minimal accuracy impact
[4pt] Mixed Precision (BF16)50% param memoryNeutral to +20% speedNo loss scaling; best on A100/H100
[4pt] Mixed Precision (FP16)50% param memory+510% overheadRequires dynamic loss scaling; older hardware
[4pt] FP8 Training75% param memory+30100% speedEmerging; requires per-tensor scaling; H100/B200
[4pt]
Memory optimisation techniques for large-model training. Memory reduction is approximate and varies with model size and configuration. Compute overhead is relative to a baseline with no memory optimisations. “–” indicates negligible effect. Techniques are complementary and typically applied in combination.

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 P=64 A100-80GB GPUs, using ZeRO-3 (via FSDP), BF16 mixed precision, and selective activation checkpointing.

Model architecture.

Following LLaMA-70B: L=80 transformer layers, hidden dimension d=8192, number of attention heads H=64, feedforward expansion ratio 4. Total parameters N=70×109. Training: batch size B=4 sequences, sequence length Ls=2048.

Model state (ZeRO-3).

Mmodel state=16NP=16×70×10964=17.5GB. This comprises 16N/P=2.19 GB of parameters (FP16), 2.19 GB of gradients (FP16), and 13.13 GB of optimizer state (FP32 Adam).

Activations (with selective checkpointing).

Without checkpointing: Mact, full80×2.4GB=192GB. With selective checkpointing (checkpointing attention scores and FFN intermediates, retaining LayerNorm activations): Mact, selective0.4×192=76.8GB. With full activation checkpointing (one checkpoint per layer): Mact, full-ckpt1×2.4=2.4GB. We use selective checkpointing for this budget: 76.8 GB.

Total per-GPU memory.

Mtotal=Mmodel state+Mact, selective+Mmisc=17.5+76.8+3.0=97.3GB. This exceeds 80 GB. Switching to full activation checkpointing: Mtotal, full-ckpt=17.5+2.4+3.0=22.9GB. Full activation checkpointing fits comfortably in 80 GB, leaving 57 GB of headroom. The overhead is +33% compute (an additional forward pass per backward).

Alternative: larger batch with selective checkpointing.

If we instead use batch size B=1 (reducing activations by 4×): Mact, selective, B=176.8/4=19.2GB. Mtotal=17.5+19.2+3.0=39.7GB. This fits in 80 GB with 40 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 64×A100-80GB with ZeRO-3 + BF16:

  • Full activation checkpointing: 22.9 GB per GPU, +33% compute.

  • Selective checkpointing with B=1: 39.7 GB per GPU, +10% compute.

  • No checkpointing with B=4: 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 d=4096, 32 attention heads, trained with batch size B=8 and sequence length L=1024.

  1. Compute the activation memory per layer (in GB, at FP16).

  2. Compute the total activation memory without checkpointing.

  3. With full activation checkpointing (one checkpoint per layer), what is the activation memory? What is the compute overhead?

  4. With the L optimal strategy (checkpoint every k=40=7 layers), what is the activation memory? What is the worst-case recomputation (in layers)?

Exercise 45 (Mixed precision numerical analysis).

A parameter has value θ=1000.0 and receives a gradient update ηg=0.0001 (learning rate η=0.001, gradient g=0.1).

  1. In FP32, what is θηg? Is the result representable exactly?

  2. In FP16 (machine epsilon ϵfp169.8×104 relative to the magnitude of the result), what is fl16(θηg)? Is the update preserved? Explain what happens if ηg/θ<ϵfp16.

  3. With loss scaling S=1024, the gradient becomes Sg=102.4. In FP16, compute θ=θη(Sg)/S. Does the update survive?

  4. 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, d=5120, 40 attention heads. You plan to use BF16 mixed precision and Adam.

  1. Compute the model-state memory per GPU under ZeRO-3 with P=16. Does it fit in 40 GB?

  2. For batch size B=4, sequence length L=2048, compute the per-layer activation memory.

  3. 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?

  4. 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?

  5. 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 t+1 conditioned on tokens 1,,t. This imposes a causal dependency that propagates through the computation graph: the output at position t 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 𝐱0 at a randomly sampled noise level t: (DDPM LOSS)DDPM(θ)=𝔼𝐱0,t,𝝐[𝝐𝝐θ(𝐱t,t)2], where 𝐱t=αt𝐱0+1αt𝝐 is the noised sample and αt=s=1t(1βs) is the cumulative noise schedule. The key observation is that each sample (𝐱0,t,𝝐) 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 t for each example in each mini-batch, but across an epoch of training, the model sees examples at all noise levels from t=1 to t=T (with T=1000 a common setting). This means the effective number of gradient computations per training image is T 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 512×512 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 H×W×3 into a compact latent tensor 𝐳=(𝐱)h×w×c, where typically h=H/8, w=W/8, and c=4. The spatial compression factor of 8× 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 64× 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 512×512 image, the pixel-space activation tensor transmitted per sample is 512×512×3×4=3.1MB (in float32), while the latent tensor is 64×64×4×4=0.064MB - a factor of 48× 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 𝐜L×d. 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 d=768 occupies 0.24MB) 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 𝐳h×w×c, the DiT patchifies it into a sequence of N=(h/p)(w/p) tokens of dimension d, where p 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 K workers holds a full replica of the model parameters θ, processes a distinct shard of the mini-batch, computes the local gradient ^k, and participates in an all-reduce to obtain the synchronised gradient: (Allreduce GRAD)1Kk=1K^k. For diffusion models, this strategy is particularly clean. Because samples at different noise levels t 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 Beff=KBlocal. 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 (ηKη0) 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 2048 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 H be the number of attention heads, d the hidden dimension, and T the number of GPUs in the tensor parallel group. The attention heads are partitioned such that each GPU holds H/T heads, processing its shard of the query, key, and value projections independently. Concretely, the projection matrices are split column-wise: (Tensor Parallel ATTN)𝐖Q=[𝐖Q(1)𝐖Q(T)],𝐖K=[𝐖K(1)𝐖K(T)],𝐖V=[𝐖V(1)𝐖V(T)]. Each GPU computes attention for its H/T heads locally, then the output projection 𝐖O is split row-wise and followed by an all-reduce to combine the partial sums: (Tensor Parallel Output)𝐘=i=1T𝐙(i)𝐖O(i), where 𝐙(i) is the local attention output on GPU i. 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 m and begins processing micro-batch m+1, the last stage has not yet produced a gradient for micro-batch m, leaving intermediate stages idle. In the 1F1B (one-forward-one-backward) schedule, the bubble fraction is (p1)/p where p is the number of pipeline stages, meaning that for p=4 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.

DiffusionPipe architecture. The frozen VAE encoder and text encoder (teal, GPU 0) occupy the first pipeline stage. Because these components require no backward pass, GPU 0 can begin processing the next mini-batch's forward pass while GPUs 1–3 are executing the backward pass on the current mini-batch (amber dashed box). This bubble-filling strategy yields up to 1.41× throughput improvement over standard 1F1B pipeline schedules. Trainable DiT blocks (blue) are distributed across GPUs 1–3.

The throughput gain from bubble filling is quantified as follows. In a standard 1F1B pipeline with p stages and m micro-batches, the total time is approximately (2m+p2)tb where tb is the time per micro-batch per stage. In DiffusionPipe, the frozen stages contribute no backward time, so the effective p for the backward pass is (ppfrz) where pfrz 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 P=PdPtPp be a factorisation of the total number of GPUs into a data-parallel group of size Pd, a tensor-parallel group of size Pt, and a pipeline-parallel group of size Pp. A hybrid parallelism strategy for diffusion training assigns each GPU a unique index (d,t,p) with d[Pd], t[Pt], p[Pp], such that:

  1. GPUs sharing the same (d,p) index form a tensor-parallel group and partition the model width (attention heads and MLP columns) evenly.

  2. GPUs sharing the same (d,t) index form a pipeline-parallel group and partition the model depth (layers) into Pp contiguous stages.

  3. GPUs sharing the same (t,p) 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 Beff=PdBlocal, and the communication volume per step scales as O(|θ|/Pt) for the all-reduce (since tensor parallelism reduces the per-GPU parameter count) plus O(A) for the activation transfers across pipeline boundaries, where A 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 Pt=8 (tensor parallelism across 8 GPUs) and Pd 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 d=4096, and H=32 attention heads. Each parameter occupies 2 bytes in bfloat16, so the model weights alone occupy 6.5×109×2B=13GB. The Adam optimizer states (first and second moment, maintained in float32) add a further 6.5×109×8B=52GB. The total parameter + optimizer memory requirement is approximately 65GB, far exceeding the 80,GB capacity of a single A100.

We design the following hybrid strategy on a cluster of 256 A100 GPUs (P=256):

  • Pt=4: tensor parallelism across 4 GPUs. Each GPU holds 32/4=8 attention heads and the corresponding MLP columns. The per-GPU parameter count is reduced to 1.625B parameters (3.25GB in bfloat16), and the optimizer states to 13GB. Total per-GPU memory for model + optimizer: 16.25GB.

  • Pp=4: pipeline parallelism across 4 pipeline stages, with 12 DiT layers per stage. The first stage additionally holds the frozen VAE and text encoders (0.9GB combined).

  • Pd=256/(PtPp)=256/16=16: 16-way data parallelism. With Blocal=8 images per GPU, the effective batch size is Beff=16×8=128 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 600GB/s; (ii) point-to-point activation transfers at pipeline boundaries (each latent activation tensor 64×64×4096×2B128MB) over InfiniBand; (iii) one gradient all-reduce across the data-parallel group per training step, amortised across Pp 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 1.3× throughput improvement.

At a throughput of 12 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 d=2048, 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 Pt such that the model and optimizer states fit within the per-GPU memory budget, assuming perfect partitioning. (c) With the chosen Pt, 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 600GB/s and an activation tensor width of 2048.

Exercise 48 (DiffusionPipe bubble analysis).

Consider a DiffusionPipe setup with p=6 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 tf=80ms and the time per backward micro-batch on a trainable stage is tb=160ms. (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 d=8192, 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 (Pt,Pp,Pd) with PtPpPd=512. (c) Explain qualitatively how your choice would change if the cluster interconnect were Ethernet at 100Gb/s rather than InfiniBand HDR at 200Gb/s.

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)DSM(θ)=𝔼t𝒰[1,T]𝔼(𝐱0,𝝐)pdata×𝒩(0,𝐈)[w(t)𝝐θ(𝐱t,t)𝝐2], where w(t) 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 𝐱0 drawn from the data distribution, the noise 𝝐 drawn from the standard normal, and the timestep t drawn from the uniform distribution are all independent. This means the full gradient θDSM 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 O(1/N) where N is the total number of samples across all workers.

Remark 35 (Communication per Step).

Under data parallelism with K workers, each processing a local mini-batch of size Blocal, the communication cost per training step is exactly one all-reduce over the full parameter vector θ|θ|. Using ring-AllReduce, this costs 2(K1)/K|θ|sizeof(dtype) bytes of data transmitted per GPU, independent of Blocal. For a 3B parameter DiT in bfloat16, this is 2×3×109×2B=12GB 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 t. 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 t approximates the target distribution 𝒰[1,T] after every update.

Gradient accumulation provides a way to achieve this without increasing the memory cost per step. Let G be the accumulation factor. For each training step, the worker performs G forward-backward passes, accumulating the gradient: (GRAD Accum)g^=1Gj=1Gθw(tj)𝝐θ(𝐱tj,tj)𝝐j2, before performing a single all-reduce and parameter update. This multiplies the effective batch size by G without multiplying the communication frequency by G. The SDXL training run used G=4 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 t. The loss at high noise levels (tT) and low noise levels (t1) 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 0). The model is trained to jointly estimate both 𝝐θ(𝐱t,t,𝐜) and 𝝐θ(𝐱t,t,0), with the conditioning randomly dropped with probability pdrop0.1 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)g^CFG=θ[(𝐱t,𝐜,t)+(𝐱t,0,t)], 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.

Communication timeline for data-parallel diffusion training with overlapped all-reduce. GPU 0 and GPU 1 execute identical training steps (forward pass in blue, backward pass in green) on disjoint mini-batch shards. The gradient all-reduce (teal) begins partway through the backward pass as gradient buckets complete, and overlaps with the tail of the backward pass and the start of the next step's forward pass (orange overlap region). This overlap hides a significant fraction of the all-reduce communication latency, particularly for large models where the backward pass takes much longer than the all-reduce.

Local SGD for Diffusion Models

Local SGD is a communication-avoiding variant of data-parallel training in which each worker takes K gradient steps independently before synchronising. Instead of all-reducing gradients every step, workers perform K local updates and then average (all-reduce) the parameter vectors themselves: (Local SGD)θ(n+1)=1Pdk=1Pdθk(n+K), where θk(n+K) is the local parameter vector after K independent gradient steps starting from the shared checkpoint θ(n). The communication frequency is reduced by a factor of K, 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 t; local workers that sample different noise levels during their K 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 K=4 local steps between synchronisations, FID increases by approximately 25 points compared to fully synchronised training at equal total compute. With K=8, the degradation grows to 510 FID points. With K=16, the degradation becomes significant (>15 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 p1(𝐱) and p2(𝐱) are two independent generative distributions, their product (unnormalised) p1,2(𝐱)p1(𝐱)p2(𝐱) has a score function: (Score SUM)𝐱logp1,2(𝐱)=𝐱logp1(𝐱)+𝐱logp2(𝐱). In the diffusion model setting, the score function is approximated by the denoising network: 𝝐θ(𝐱t,t)1αt𝐱tlogpt(𝐱t). (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)𝝐θ1⊕︎θ2(𝐱t,t)=𝝐θ1(𝐱t,t)+𝝐θ2(𝐱t,t), where θ1 and θ2 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 {θk}k=1K be a collection of K diffusion model parameters, each trained independently to minimise the denoising score matching loss on data drawn from a (possibly overlapping) subset 𝒟k𝒟 of the full training corpus. The score composition of these models is the function (Score Composition DEF)𝝐comp(𝐱t,t;λ1,,λK)=k=1Kλk𝝐θk(𝐱t,t),λk>0,k=1Kλk=1, where λk are composition weights. The composed denoising process uses 𝝐comp 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 K 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)logpθ(𝐱0)t=1Tct𝔼q[𝝐θ(𝐱t,t)𝝐2]+const, where ct=βt2/(2σt2αt(1αt)). Now consider the product-of-experts model pcomp(𝐱0)k=1Kpθk(𝐱0)λk. Taking logarithms and applying the bound in (ELBO Equiv) independently for each expert: (POE ELBO)logpcomp(𝐱0)k=1Kλkt=1Tct𝔼q[𝝐θk(𝐱t,t)𝝐2]+const. 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 𝝐comp in (Score Composition DEF) provides an optimal estimator for the score of pcomp. The approximation gap between pcomp and the true union distribution p(𝐱0|k𝒟k) arises from the product-of-experts approximation and vanishes when the datasets 𝒟k 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 (24×109×2B=48GB) over 10,Gb/s (1.25GB/s) Ethernet would require approximately 48/1.25=38.4seconds per step, dwarfing the 0.5second compute time per step. Standard data parallelism across nodes is therefore infeasible.

Decentralized strategy.

The consortium adopts score composition:

  1. Each node independently trains a 24B DiT model using full hybrid parallelism within the node (Pt=4, Pp=2, Pd=1, fully exploiting NVLink). Each node receives a disjoint subset of the training corpus, roughly 1/8 of the full dataset.

  2. Training runs for 500,000 steps on each node independently, with no inter-node communication.

  3. At inference time, the 8 expert models are composed using (Score Composition DEF) with uniform weights λk=1/8. 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 8× the cost of training a single 24B model on 1/8 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 8× 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 38 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 f(θ)=𝔼𝐱0,t,𝝐[(θ;𝐱0,t,𝝐)] be the expected score matching loss, where (θ;) is the per-sample loss. Assume f is L-smooth (i.e., f(θ)f(θ)Lθθ for all θ,θ) and bounded below. Under local SGD with Pd workers, K local steps, learning rate η, and gradient variance σ2, after N total gradient steps across all workers, the iterate satisfies: (Local SGD Convergence)1Nn=0N1𝔼[f(θ(n))2]2(f(θ(0))f)ηN+ησ2LPd+η2L2K2σ2local drift, where θ(n) is the consensus iterate and f is the minimum value. The third term, the local drift, quantifies the cost of taking K steps without synchronisation: it grows as K2, explaining why large values of K cause significant degradation. Setting K=O(1/η) balances the local drift against the learning rate term, giving K=O(N1/4) as the optimal local step count for an N-step training run. In practice, K{4,8} 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 K with FID degradation that scales as K2 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 G=1 to G=8. 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 120ms? (c) A colleague suggests using local SGD with K=8 instead of gradient accumulation with G=8. 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 K expert diffusion models, each with N parameters and denoising network evaluation time τms per step. (a) Write a formula for the total inference time per generated image as a function of K, τ, and the number of denoising steps T. (b) Suppose each expert achieves FID F1 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 K 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 300GB/s), and (ii) local SGD across institutions with parameter averaging every K steps. Determine the value of K that keeps the inter-institution communication overhead below 5% of total training time, assuming a compute time of 80ms 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 =f(θ,x), 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 f:n be a scalar loss function computed as the composition f=fLfL1f1, where each f is a differentiable elementary operation (matrix multiply, elementwise nonlinearity, layer normalisation, etc.). During the forward pass, the framework evaluates

(Forward Chain)a0=x,a=f(a1;θ),=1,,L,=aL,

and caches the intermediate activations a0,a1,,aL1 that will be needed by the backward pass. During the backward pass, starting from the scalar seed /aL=1, the engine propagates

(Backward Chain)a1=fa1a,θ=fθa,

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 L layers, hidden dimension d, sequence length T, and micro-batch size B, the memory required to cache all intermediate activations scales as 𝒪(BLTD) bytes. For a 70B parameter model with L=80, d=8192, T=4096, B=1, this exceeds 640,GB in FP32, motivating both activation recomputation and mixed precision.

The Challenge: Computational Graphs Across Devices

Consider a model partitioned into S pipeline stages, with stage s residing on GPU s. During the forward pass, GPU 0 computes a1=f1(x) and ships the activation tensor a1 over the interconnect to GPU 1, which computes a2=f2(a1), and so on until GPU S1 produces the loss. The resulting computational graph spans all S devices. This creates two structural problems that do not arise in the single-device setting.

Gradient routing.

The backward pass on GPU s requires the upstream gradient /as, which was computed on GPU s+1. 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 s also requires the cached activation as1 from the forward pass (to compute the Jacobian fs/as1). This activation was produced on GPU s1 and transmitted to GPU s. If GPU s did not store it locally after the forward pass, it must either request it again from GPU s1 (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 v𝒱 represents an elementary differentiable operation fv and each directed edge (u,v) represents a data dependency (the output tensor of u is an input tensor of v).

A distributed computational graph 𝒢D is a tuple 𝒢D=(𝒢,δ,) where:

  • δ:𝒱{0,1,,D1} is a device assignment function that maps each operation to one of D compute devices.

  • is the set of boundary edges: edges (u,v) such that δ(u)δ(v). 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 𝒢D on the forward pass is (u,v)|shape(u)| bytes, where |shape(u)| denotes the byte size of the output tensor of operation u. 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.

Distributed computational graph spanning four GPUs. Each box is a GPU. Blue nodes are individual operations (attention and feed-forward layers). Green arrows carry activations from stage to stage during the forward pass; red arrows return gradients in reverse during the backward pass. Activations must be stored at each boundary for use in the backward pass; alternatively, they can be recomputed from the previous stage's output.

The Activation Communication Problem at Pipeline Boundaries

The crux of distributed auto-diff is the following: at each pipeline boundary (s,s+1), the activation tensor as is produced by GPU s during the forward pass, consumed as input by GPU s+1 during the forward pass, and needed again by GPU s+1 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 s retains as in its own memory after transmitting it. During the backward pass, GPU s+1 requests as again from GPU s via an explicit receive. This avoids re-computation but doubles the memory pressure on GPU s (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 s+1 stores as locally after receiving it during the forward pass. This is the most common approach in practice. It adds memory pressure on GPU s+1 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 s+1 discards as after the forward pass. During the backward pass, it sends a recompute request to GPU s, which recomputes as 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 K micro-batches, each of size Bμ, such that the effective batch size is B=KBμ. Rather than performing an all-reduce synchronisation after every micro-batch (which would incur K collective operations per parameter update), the framework accumulates gradients across the K micro-batches locally and performs a single all-reduce at the end.

Definition 36 (Gradient Accumulation).

Let θ be the model parameters and let x(1),x(2),,x(K) be K consecutive micro-batches. Gradient accumulation computes the accumulated gradient estimate

(GRAD Accum)gacc=1Kk=1Kθ(θ;x(k))

by executing K 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 gacc.

In PyTorch, gradient accumulation is enabled by calling loss.backward() in a no_sync() context for the first K1 micro-batches (suppressing the all-reduce) and calling loss.backward() outside the context for the K-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)𝔼[gacc]=1Kk=1K𝔼[θ(θ;x(k))]=θ𝔼x𝒟[(θ;x)],

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 K involves a three-way trade-off.

Communication overlap.

Pipeline parallelism with K micro-batches allows the pipeline to remain full for a larger fraction of the total iteration time. With only K=1 micro-batch, the pipeline drains and refills at every step, wasting a fraction (S1)/(S+K1) of GPU time in the pipeline bubble. With KS, the bubble fraction (S1)/(K+S1) 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 S, limiting peak activation memory to the product of S and the per-micro-batch activation footprint.

Gradient staleness.

With asynchronous pipeline parallelism (async-PP), stage s may begin processing micro-batch k+1 before receiving the backward gradient from micro-batch k. The parameter update for stage s is then computed with a gradient that is stale by up to S1 micro-batches. This can slow convergence and, in the limit of very large K, 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 K=4 micro-batches.

Gradient accumulation timeline for K=4 micro-batches on a single data-parallel rank. Green blocks are forward passes; red blocks are backward passes (with local gradient accumulation). The all-reduce collective (blue) fires only once after all four micro-batches, reducing communication overhead by a factor of K. The optimiser step (purple) follows immediately.

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 Y=XW with Wd×d, the column-parallel split distributes W across T GPUs so that GPU t holds columns W:,td/T:(t+1)d/T 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 (S1)/(K+S1) where K is the number of micro-batches and S the number of pipeline stages.

Gradient synchronisation.

In Megatron-LM's hybrid-parallel configuration, gradients are accumulated over K 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 ϵθ(xt,t) maps a noisy latent xt and a timestep embedding t 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 S=8 pipeline stages and trained with K micro-batches per iteration using the 1F1B schedule.

  1. (a)

    Derive the pipeline bubble fraction as a function of S and K.

  2. (b)

    For S=8, find the minimum K such that the bubble fraction is below 5%.

  3. (c)

    If each micro-batch forward-backward takes 200,ms and each inter-stage communication takes 5,ms, estimate the total iteration time for K=16 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)

  1. (a)

    Explain when this hook is invoked during the backward pass.

  2. (b)

    Why does the hook return grad unmodified rather than returning None?

  3. (c)

    Write the corresponding receive hook that should be registered on the upstream GPU (rank 1) to inject the arriving gradient into its autograd graph.

Exercise 55.

A distributed training job uses R=32 data-parallel ranks and K=8 gradient accumulation micro-batches.

  1. (a)

    How many all-reduce operations are performed per parameter update step without gradient accumulation? How many with K=8?

  2. (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.

  3. (c)

    Suppose the micro-batch forward-backward time is 50,ms. At what value of K 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 [3.4×1038,+3.4×1038] with a relative precision of about 107. Its 16-bit half-precision cousin (FP16) covers a much narrower range: [65504,+65504], with a minimum positive normal value of approximately 6.1×105. Values below 6.1×105 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 101 to 100. After many steps of gradient descent with a learning rate of, say, η=104, the gradients themselves may have magnitudes of order 104 to 106. In FP32, these values are represented without issue. In FP16, values below 104 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 (softmax(QKT/d) before dividing by d) can easily exceed this threshold for large d 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 S before the backward pass. By the chain rule, every gradient is then multiplied by S as well, shifting the gradient magnitudes into the representable FP16 range. After the backward pass, divide all gradients by S 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 S>0:

(LOSS Scaling)^=S,θ^=Sθ,g~=1Sθ^=θ.

The scaled loss ^ is computed and stored in FP16; its backward pass yields scaled gradients in FP16 whose magnitudes are S times larger and therefore FP16-representable. The division by S and the optimiser step are performed in FP32 using the master copy of the parameters.

Choosing S.

If S is too small, gradients still underflow. If S is too large, gradients overflow to Inf or NaN. The optimal S 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 S per experiment.

Dynamic Loss Scaling

Dynamic loss scaling (Micikevicius et al., 2018) eliminates the need to hand-tune S by adapting it automatically. The algorithm maintains a current scale factor St 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 Nup consecutive steps (typically Nup=2000), double the scale: St+12St.

  • If Inf or NaN is detected, halve the scale St+1St/2 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 210 to 217 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 (1038 to 1038). It sacrifices mantissa precision: where FP32 has 23 mantissa bits (7 significant decimal digits) and FP16 has 10 mantissa bits (3 significant decimal digits), BF16 has only 7 mantissa bits (2 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 (448 max value). Used for activations and weights in the forward pass.

  • E5M2 (5 exponent bits, 2 mantissa bits): lower precision, wider dynamic range (57344 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 𝔽32 and 𝔽16 denote the sets of FP32 and FP16 (or BF16) representable values respectively. A mixed precision training iteration consists of:

  1. Cast down: Copy the FP32 master parameters θ(32)𝔽32p to a FP16 working copy θ(16)=cast3216(θ(32))𝔽16p.

  2. Forward pass (FP16): Compute the scaled loss ^=S(x;θ(16))𝔽16.

  3. Backward pass (FP16): Compute scaled gradients g^(16)=θ(16)^𝔽16p.

  4. Inf/NaN check: If g^(16) contains any non-finite value, discard the gradients, adjust S, and return to step 1.

  5. Cast up and unscale: Compute the FP32 gradient estimate g(32)=cast1632(g^(16))/S𝔽32p.

  6. Optimiser step (FP32): Update the master parameters θ(32)θ(32)η𝒰(g(32)), 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.

Bit-layout comparison of floating-point formats used in deep-learning training. Red cells: sign bit; green cells: exponent bits; blue cells: mantissa bits. FP32 and BF16 share the same 8-bit exponent, giving the same dynamic range. FP16 has a wider mantissa (10 bits) but a narrower exponent (5 bits), making it susceptible to gradient underflow. FP8 formats sacrifice precision for 2× throughput and memory advantages over 16-bit formats.

Gradient Clipping in Distributed Settings

Gradient clipping is a standard technique for stabilising training of deep networks. The global 2 gradient norm is

(Global NORM)g2=(igi2)1/2,

where the sum runs over all parameters. If g2>τ (the clipping threshold, typically τ=1.0), the gradient is rescaled:

(CLIP)ggτg2.

In the single-device setting, computing g2 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.

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

  2. 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)g22=r=0R1g(r)22,

where g(r) is the gradient shard on rank r, 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 B=KRBμ (where R is the number of data-parallel ranks and Bμ 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 1/B).

Let gi=θ(θ;xi) be the per-sample gradient for sample xi drawn i.i.d. from 𝒟. Let g=𝔼[gi] be the population gradient. The gradient estimate from a mini-batch of size B,

(Minibatch GRAD)g^B=1Bi=1Bgi,

satisfies

(Variance Scaling)Var[g^B]=1BVar[gi]=σ2B,

where σ2=Var[gi] is the per-sample gradient variance.

Proof.

Since the samples x1,,xB are drawn i.i.d., the per-sample gradients g1,,gB are independent with identical distributions. By linearity of expectation, 𝔼[g^B]=g. By the variance of a sum of independent random variables, Var[g^B]=Var[1Bi=1Bgi]=1B2i=1BVar[gi]=1B2Bσ2=σ2B.

Remark 43 (Implications for learning rate scaling).

The 1/B variance scaling is the theoretical basis for the linear scaling rule: when the batch size is multiplied by k, the learning rate should also be multiplied by k (keeping the signal-to-noise ratio of the gradient estimate constant). In practice, this rule holds for moderate k 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 B, above which further scaling yields diminishing returns, is typically in the range 105 to 106 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 mt and second moment vt in FP32) consume 12 bytes per parameter: 4 bytes each for θ(32), mt, and vt. For a 7B parameter model, this totals 84GB, far exceeding the 80,GB HBM on a single H100.

The Zero Redundancy Optimizer (ZeRO) Stage 1 (ZeRO-1) partitions the optimiser state across R data-parallel ranks. Each rank r holds only 1/R of the optimiser state, corresponding to a disjoint shard θr(32),mt(r),vt(r) of the parameter space.

The per-step procedure under ZeRO-1 is:

  1. Each rank holds the full BF16 working copy of parameters and computes the full gradient for its micro-batch.

  2. Gradients are all-reduced across ranks (exactly as in standard data parallelism).

  3. Each rank updates only its shard of the optimiser state: mt(r)β1mt1(r)+(1β1)gt(r),vt(r)β2vt1(r)+(1β2)(gt(r))2, where gt(r) is the gradient shard corresponding to its parameter shard.

  4. Each rank updates its parameter shard in FP32 and casts back to BF16.

  5. 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 R (from 12 bytes/param to 12/R bytes/param for the optimiser state) while adding one all-gather communication per step. For R=64, 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): T=8 (all 8 GPUs within each node share one model replica, splitting weight matrices along the tensor dimension).

  • Pipeline parallelism (PP): S=4 pipeline stages, spanning 4 nodes; each stage holds 8 transformer layers (32 layers total).

  • Data parallelism (DP): R=2 data-parallel replicas (8 nodes / 4 pipeline stages = 2 replicas).

  • Total GPU count: T×S×R=8×4×2=64.

Micro-batch and gradient accumulation:

  • Micro-batch size: Bμ=1 sequence of 4096 tokens.

  • Gradient accumulation steps: K=16 micro-batches.

  • Global effective batch size: B=K×R×Bμ=16×2×1=32 sequences 131072 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 β1=0.9, β2=0.95, ϵ=108, ZeRO-1 state partitioning across R=2 data-parallel ranks. FP32 master parameters.

Learning rate and clipping: Peak learning rate ηmax=3×104 with cosine decay; linear warmup over 2000 steps. Gradient clipping threshold τ=1.0 applied after gradient all-reduce (on the synchronised FP32 gradients).

Memory per GPU (estimated):

  • BF16 model parameters: 7×109×2B/8 (TP)=1.75GB.

  • FP32 master parameters: 3.5GB (divided by T=8 within each TP group, then by ZeRO-1).

  • Adam state (FP32 mt,vt): 7.0GB per replica, 3.5GB after ZeRO-1.

  • Activations (BF16, 8 layers, Bμ=1, T=4096, d=4096): approximately 8GB.

  • Total: 40GB 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 2.0×1017 FP16 FLOP/s across all 64 GPUs. For a 7B model trained on 1 trillion tokens, the total FLOPs required are approximately 6×7×109×1012=4.2×1022 FP16 FLOPs, requiring approximately 4.2×1022/(2.0×1017)210000 seconds 58 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 t, the current scale factor is St=214=16384. The loss at this step is =3.42.

  1. (a)

    What is the scaled loss ^ computed in FP16? Does this value overflow FP16?

  2. (b)

    Suppose a particular gradient tensor has true value g=7.3×105 in FP32. What is the FP16-representable value of Stg? Would g itself be representable in FP16 without scaling?

  3. (c)

    If the scaling algorithm doubles St every 2000 steps when no overflow occurs, and halves it upon any overflow, and the current scale has been at 214 for 1500 steps without overflow, what is the expected scale at step t+600?

Exercise 57.

A distributed training job uses R=8 data-parallel ranks. After all-reduce, the gradient tensor for a particular layer has global norm g2=4.7 and the clipping threshold is τ=1.0.

  1. (a)

    What is the clipping factor applied to the gradient? Write the formula and compute the numerical result.

  2. (b)

    Suppose that before the all-reduce, the local gradient norms on the 8 ranks are g(0)2=0.8, g(1)2=1.2, , g(7)2=2.1. Explain why clipping each local gradient to τ=1.0 before the all-reduce would produce a different result from clipping the global gradient after all-reduce.

  3. (c)

    Compute the communication overhead of the global norm all-reduce as a fraction of the gradient all-reduce, for a model with p=7×109 BF16 parameters.

Exercise 58.

A 13B parameter model (p=1.3×1010) is trained with Adam (FP32 master parameters and FP32 optimiser state) using ZeRO-1 across R=32 data-parallel ranks.

  1. (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.

  2. (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.

  3. (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 900GB/s bidirectional on NVLink 4.0) or InfiniBand (up to 400Gbit/s 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 N workers efficiently so that they collectively train N 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 k is drawn from a distribution pk that may differ substantially from pk for kk.

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 𝒟={(xi,yi)}i=1N be a training dataset with global loss (θ)=1Ni=1N(θ;xi,yi). Distributed training with K workers partitions 𝒟 into shards 𝒟1,,𝒟K such that k𝒟k=𝒟 and |𝒟k|N/K for all k. Each worker k computes the local gradient gk=θk(θ)=1|𝒟k|(x,y)𝒟kθ(θ;x,y), and the aggregated gradient g=1Kkgk is an unbiased estimator of θ(θ). Workers share a single global objective, operate on identically-distributed data, and maintain synchronised parameter replicas θ1==θK=θ after every step. The training terminates when (θ) converges or a wall-clock budget is exhausted.

Definition 39 (Federated Learning).

Let there be K clients, each holding a local dataset 𝒟k drawn from a client-specific distribution pk. The federated objective is F(θ)=k=1K|𝒟k|NtotalFk(θ),Fk(θ)=𝔼(x,y)pk[(θ;x,y)], where in general pkpk (statistical heterogeneity). In each communication round r:

  1. The server broadcasts the current global model θ(r) to a sampled subset 𝒮(r)[K] of clients.

  2. Each client k𝒮(r) performs E local gradient steps (using SGD or Adam on 𝒟k), producing a local update Δk(r).

  3. The server aggregates: θ(r+1)=θ(r)+1|𝒮(r)|k𝒮(r)Δk(r).

Clients are not synchronised between rounds; a client that participates in round r may not participate in round r+1. Raw data never leaves the client.

The critical structural difference is visible in these definitions. In distributed training, gk is an unbiased estimator of the same gradient . In federated learning, Fk is the gradient of a different function from Fk. The aggregated update is therefore not an unbiased estimator of F unless the pk 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 DimensionDistributed TrainingFederated Learning
Primary goalSpeed (reduce wall-clock time)Privacy (keep data local)
[2pt] NetworkNVLink / InfiniBand; 100900GB/s, μs latencyWiFi / LTE / internet; 1100Mbit/s, 100ms latency
[2pt] DevicesHomogeneous accelerators (same GPU model, same VRAM)Heterogeneous clients (phones, servers, IoT); different compute
[2pt] Data distributioni.i.d. (balanced partition of global dataset)Non-i.i.d. (each client has own distribution pk)
[2pt] Data locationShared distributed file systemStays on device; never transmitted
[2pt] SynchronisationSynchronous every step; all workers update togetherPeriodic (every E local steps); clients drop in and out
[2pt] PrivacyNone (data visible to all workers)Data never leaves client; optional DP or secure aggregation
[2pt] StragglersDominant concern; one slow worker blocks allTolerated; round ends after a quorum, stragglers ignored
[2pt] Fault toleranceCheckpoint + restart; downtime is expensiveBuilt-in: missing clients simply excluded from that round
[2pt] Gradient biasUnbiased: 𝔼[gk]=Biased under heterogeneity: FkF
[2pt] Communication roundsThousands to millions per run; cheap per roundTens to hundreds per run; very expensive per round
[2pt] Regulatory contextGDPR 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 10Mbit/s and a 7B-parameter model with 32-bit gradients, transmitting a single gradient tensor takes 22 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 1GB/s and latency 1ms? If yes, use synchronous distributed training. (3) If bandwidth is moderate (10100Mbit/s) 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 10100Gbit/s bandwidth and 50150ms 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 S 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 H local SGD steps and then averages model parameters. The reduction in communication rounds is exactly H-fold. The convergence penalty (the gap introduced because local models drift apart during the H steps) is small when H is small relative to the gradient noise scale.

In the federated setting, the same parameter H (often called E, 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 E to extract maximum information from each participation.

Proposition 13 (Local-SGD convergence gap).

Let f(θ)=1Kkfk(θ) where each fk is μ-strongly convex and L-smooth, and assume the gradient variance within each client is bounded by σ2. After R communication rounds with H local steps per round and step size η1LH, the iterate θ(R) satisfies 𝔼[f(θ(R))f(θ)]σ2μKHRstatistical noise+LHη2σ22μlocal drift. The first term decreases with more rounds and more local steps; the second increases with H. The optimal H balances these two forces, and in the distributed (i.i.d.) case the optimal H is 𝒪(T/(Kσ2)) where T=RH 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 k at step t has a local model θk(t). Rather than broadcasting to all workers, it sends its model to a random or fixed neighbour set 𝒩(k) and receives models from its neighbours. The update rule is: θk(t+1)=j𝒩(k){k}Wkjθj(t)ηgk(t), where WK×K is a doubly stochastic mixing matrix encoding the graph topology.

Definition 40 (Gossip SGD).

Let G=(V,E) be a connected undirected graph over K workers. Let W be a doubly stochastic matrix compatible with G (i.e., Wkj=0 whenever (k,j)E). Gossip SGD with step size η performs, at each step t:

  1. Compute local gradient. gk(t)fk(θk(t)).

  2. Mix with neighbours. θk(t+12)jWkjθj(t).

  3. Gradient step. θk(t+1)θk(t+12)ηgk(t).

The spectral gap 1λ2(W), where λ2 is the second-largest eigenvalue of W, controls the mixing speed: a larger gap means faster consensus. A fully-connected graph recovers exact All-Reduce in one step (λ2=0); a ring graph has λ2=cos(2π/K)1 as K, corresponding to slow mixing.

Gossip SGD is fault-tolerant by construction (no single node failure disrupts the protocol), scalable (each node communicates only with |𝒩(k)| neighbours rather than all K 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 G is a star graph with the server at the centre: gossip SGD on a star is precisely FedAvg with H=1 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 50,000 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 250,000 studies, shuffle randomly, partition into 64 shards, and run data-parallel training with ZeRO-3 sharding. Expected training time: 3 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 E=5 epochs between communication rounds. Expected rounds to convergence: 100 (compared to 300,000 gradient steps in the distributed setting). The FedAvg aggregated model achieves 92% 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 K=2 clients with f1(θ)=12(θ1)2 and f2(θ)=12(θ+1)2. The federated objective is F(θ)=12(f1+f2)(θ). (a) Compute θ=argminF(θ). (b) Show that one step of FedAvg with E=1 local step from θ(0)=0 returns the correct global minimum in this simple case. (c) Now let f2(θ)=12(θ+5)2 and repeat with E=10 local steps and η=0.1. Show that client drift causes the aggregated model to overshoot θ. Quantify the drift as a function of E and η.

Exercise 60 (Gossip mixing speed).

Consider K=8 workers arranged as a ring, so each worker k communicates with workers k1 and k+1 (modulo 8). The symmetric doubly stochastic mixing matrix for the ring is Wkj=13 if |kj|1(mod8), zero otherwise. (a) Compute all eigenvalues of W using the fact that the ring graph has eigenvalues λj=13(1+2cos(2πj/K)) for j=0,1,,K1. (b) What is the spectral gap 1λ2(W)? (c) Compare to the spectral gap of the complete graph with uniform mixing matrix Wkj=1/K for all k,j. (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 K.

Exercise 61 (Geo-distributed training latency budget).

A 70B-parameter model is trained across two data centres (North America and Europe) connected by a 100Gbit/s WAN link with 80ms 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 125TFLOP/s at BF16. A single forward+backward pass on a micro-batch costs 2×6×70×109 FLOPs. How many local steps H must each centre take before inter-centre communication for the communication latency to represent <10% 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 4×106 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 Li through Lj 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 𝒪(KL) communication events where K is the number of participants and L the number of layers. Sequential pipeline parallelism generates only 𝒪(L) communication events (one per layer boundary), a K-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 (11/K) fraction of peers at any stage, as long as at least one peer per stage remains.

Formally, let there be S stages with peer pools 𝒫1,,𝒫S. For each micro-batch, SWARM samples one peer ps𝒫s for each stage s and routes the micro-batch along the path p1p2pS. The probability of sampling peer p from pool 𝒫s is proportional to its advertised throughput: Pr[ps=p]=τpq𝒫sτq, where τp is the recent tokens-per-second throughput measured for peer p. 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 H 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 N worker islands, each holding a replica θn(r) at the start of outer round r. Each island maintains its own inner optimiser state. The DiLoCo update proceeds as follows:

  1. Inner optimisation. Each island n runs H steps of AdamW on its local data shard 𝒟n, starting from θn(r): ϕn(r)=AdamWH(θn(r),𝒟n).

  2. Pseudo-gradient computation. Each island computes its pseudo-gradient: δn(r)=θn(r)ϕn(r).

  3. All-Reduce. Pseudo-gradients are averaged across islands: δ(r)=1Nn=1Nδn(r).

  4. Outer Nesterov step. The global model is updated using Nesterov momentum with outer learning rate ηout and momentum μout: m(r+1)=μoutm(r)+δ(r),θ(r+1)=θ(r)ηout(μoutm(r+1)+δ(r)).

  5. Broadcast. θ(r+1) is broadcast to all islands, which reset their replicas: θn(r+1)θ(r+1).

Communication occurs only at step 3 (once per outer round), transmitting N parameter vectors of size |θ|.

The number of communication events relative to standard distributed training is reduced by a factor of H (the inner loop length). DiLoCo originally used H=500, meaning that a full All-Reduce occurs only every 500 gradient steps. At BF1 and a 7B model, one All-Reduce transmits 14GB; at H=500 steps of 0.1s each, this represents 50s of communication every 50s of compute - a 50% overhead. This overhead drops to 5% at H=5000 steps.

The key empirical finding of DiLoCo is that H=500 inner steps suffers only a modest convergence penalty relative to synchronous training. The intuition is that the pseudo-gradient δ(r) 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 p(x) can be expressed as a mixture: xlogp(x)=k=1Kwk(x)xlogpk(x), where pk is the local data distribution at island k and wk(x) is the weight assigned to expert k for input x. 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 k trains its own diffusion model ϵθk on its local dataset 𝒟k using the standard denoising score-matching objective: k(θk)=𝔼t,x0𝒟k,ϵ[ϵϵθk(xt,t)2]. No data leaves the island. No communication occurs during training.

Score routing at inference.

At inference time, a routing network rϕ(xt,t) outputs a probability distribution over the K experts. The effective denoising step is: ϵ^(xt,t)=k=1Krϕ(k)(xt,t)ϵθk(xt,t). 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 fhead and ftail denote the client-side encoder and decoder halves of the U-Net, and fmid the server-side middle layers. The forward pass for client k is: (Collafuse FWD1)hk=fhead(xk(t);ψk),hkmid=fmid(hk;ϕ),ϵ^k=ftail(hkmid;ψk), where ψk are client-local parameters and ϕ are shared server parameters. The client-side loss is computed on ϵ^k and the backward pass propagates gradients: (i) through ftail to update ψk (locally); (ii) a gradient /hkmid is sent to the server, which updates ϕ and returns /hk to the client; (iii) the client completes the backward through fhead to finish updating ψk.

Remark 48 (Privacy in CollaFuse).

The server receives intermediate activations hk, not raw data xk. 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 hk 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 60% of parameters but only 30% 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 256×256 image is 8×32×32 floats =32768 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 Q most recent updates from distinct clients. The aggregated model at time T is: θ(T)=1Qq=1Qϕnq(τq), where nq is the client that submitted the q-th most recent update and τq 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 S rounds stale relative to the current global model. PDFed bounds the staleness impact using a decaying weight wq=exp(λ(ττq)) 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 3000 transactions per second on a small validator network, sufficient for federated systems with 3000 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 N workers each with step time τstep (seconds per gradient step) training a model with P parameters at precision b bytes per parameter. Synchronous All-Reduce requires transmitting 2(N1)Pb/N2Pb bytes per step at bandwidth B bytes per second, incurring communication latency tcomm=2Pb/B per step. The effective throughput of synchronous distributed training is 𝒯sync=Nτstep+2Pb/B. A collaborative algorithm (DiLoCo-style) with H local steps per communication round incurs communication latency 2Pb/B only every H steps, giving effective throughput 𝒯collab=Nτstep+2Pb/(BH). Setting 𝒯sync=𝒯collab yields the crossover point, which is trivially B (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 Beff=NBlocal converges in T steps; collaborative training with drift accumulates extra gradient noise σdrift2H over each inner loop. Collaborative training is preferable to synchronous training in the bandwidth regime where BBthresh=2PbτstepHopt, where Hopt=argminH[σdrift2(H)/σstep2] is the inner loop length that balances local noise against drift noise. For modern LLM training (P7×109, b=2, τstep0.1s, Hopt500), this gives Bthresh560MB/s=4.5Gbit/s.

The proposition implies that collaborative training with H=500 is preferred over synchronous all-reduce whenever the available bandwidth falls below 4.5Gbit/s. Intercontinental WAN links typically provide 110Gbit/s, which straddles this threshold. Satellite links (100Mbit/s) fall well below it. Intra-data-centre NVLink (>100GB/s=800Gbit/s) 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 80ms (TCP over WAN) to 60ms (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:

  1. 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 gk of its local gradient.

  2. Inter-cluster reduction. The aggregates g1,,gC (one per cluster) are combined via a star All-Reduce over the WAN. The total inter-cluster data volume is C×2Pb bytes (reduced by the intra-cluster step by a factor of N/C, where N/C is the cluster size).

  3. Broadcast. The final aggregate g is broadcast back to all clusters and distributed intra-cluster.

The bandwidth requirement on the WAN link is reduced from 2NPb bytes (naive all-to-all) to 2CPb bytes (hierarchical), a factor of N/C reduction. For N=1024 workers across C=4 clusters, this is a 256× 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 (100ms) stalls all N 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 H1=210 steps. A small amount of local drift is acceptable to avoid saturating inter-rack switches.

  • Between data centres: DiLoCo-style with H2=1001000 inner steps. The outer Nesterov step provides stability across the long inner loop.

  • Between institutions: Federated learning with privacy mechanisms from Chapter 37, H3= 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 H and outer learning rate ηout 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 f(θ)=12θθ2 with N=4 workers and H=10 inner steps of gradient descent (learning rate η=0.1) followed by an outer step.

  1. For the FedAvg outer step (plain average with outer learning rate 1.0), compute the iterate θ(1) after one round starting from θ(0)=𝟎 and θ=𝟏.

  2. For the DiLoCo Nesterov outer step with ηout=0.7 and μout=0.9 (initialising m(0)=𝟎), compute θ(1).

  3. Which converges faster in this quadratic setting after R=10 outer rounds? Plot the norm θ(r)θ as a function of r for both methods.

  4. How does the answer change if the workers have heterogeneous local objectives fk(θ)=12θθk2 with θ1=1,θ2=1,θ3=2,θ4=0?

Exercise 63 (Score routing for diffusion composition).

Suppose two expert diffusion models are trained on disjoint domains: p1=𝒩(μ1,σ12) and p2=𝒩(μ2,σ22) with μ1=3, μ2=+3, σ1=σ2=1. The combined distribution is a symmetric Gaussian mixture p=12p1+12p2.

  1. Write the score function xlogp(x)=xlog[12p1(x)+12p2(x)] in closed form.

  2. Express this as a convex combination of the individual scores xlogp1(x) and xlogp2(x), and identify the routing weights w1(x),w2(x).

  3. Show that the routing weights satisfy wk(x)=pk(x)/[p1(x)+p2(x)] (i.e., the weight for expert k is the posterior probability of x belonging to pk).

  4. Implement a simple Langevin MCMC sampler using the composed score function and verify empirically that samples approximate p.

Exercise 64 (Hierarchical All-Reduce bandwidth analysis).

A 70B model (BF16, 140GB) is trained across 4 data centres, each hosting 512 A100 GPUs. The intra-data-centre network provides 400Gbit/s per node; the inter-data-centre WAN provides 200Gbit/s aggregate (shared across all 4 data centres).

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

  2. Suppose each GPU processes one micro-batch of 2048 tokens in 0.05s. What is the maximum number of local steps H that can be taken before inter-DC communication becomes the bottleneck (i.e., communication time exceeds 10% of compute time for the entire inner loop)?

  3. If you adopt DiLoCo with H chosen as in (b), how many outer rounds are needed to process 300×109 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 𝒫={P1,P2,,Pk} be a set of parallelism strategies, each mapping a model and a dataset 𝒟 to a partition of compute resources 𝒢={g1,,gN} of N GPUs. A hybrid parallelism configuration is a tuple =(ddp,dtp,dpp,dsp,dep)>05 where ddp is the data-parallel degree, dtp is the tensor-parallel degree, dpp is the pipeline-parallel degree, dsp is the sequence-parallel degree, and dep is the expert-parallel degree, subject to the constraint ddpdtpdppdspdep=N. Each GPU is assigned a unique index tuple (idp,itp,ipp,isp,iep) identifying its role along every parallelism axis simultaneously. The effective batch size per gradient step is Beff=Bmicromddp, where Bmicro is the micro-batch size and m is the number of micro-batches per pipeline stage.

The factorisation ddpdtpdppdspdep=N is the fundamental constraint: every GPU must be assigned a unique role. In practice, not all five axes are non-trivial; 3D parallelism uses dsp=dep=1, 4D uses dep=1, 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 N 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 (idp,itp,ipp).

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 Cdp=2|θ|ddpddp1ddpαbw1, where |θ| is the parameter count and αbw is the effective all-reduce bandwidth. With ZeRO partitioning, the per-GPU memory footprint reduces from |θ| to |θ|/ddp for optimizer states.

Tensor-parallel dimension.

Each transformer layer is split across dtp GPUs. For an MLP with hidden dimension H and intermediate dimension 4H, the weight matrices W1H×4H and W24H×H are column- and row-partitioned respectively: W1=[W1(1)|W1(2)||W1(dtp)],W2=[W2(1)W2(2)W2(dtp)]. The forward pass requires one all-reduce after W2 (to sum partial products); the backward pass requires one all-reduce of the input gradient. Per-layer tensor-parallel cost: Ctp=2SHαNVLink1(dtp1)/dtp, where S is the sequence length. NVLink bandwidth αNVLink600GB/s (bidirectional, A100 DGX) keeps this cost small for dtp8.

Pipeline-parallel dimension.

The L transformer layers are partitioned into dpp stages of L/dpp layers each. Micro-batches flow through stages in a 1F1B (one-forward-one-backward) schedule. Inter-stage communication transfers activation tensors of shape (Bmicro,S,H) across the inter-node fabric (InfiniBand or RoCE). Per-micro-batch communication cost: Cpp=2BmicroSHαIB1, where αIB25GB/s for InfiniBand HDR.

3D Parallelism TikZ Figure

3D parallelism grid for N=ddp×dtp×dpp=2×2×4=16 GPUs. Each GPU carries a unique (idp,itp,ipp) index. Within each pipeline stage, dtp=2 GPUs share transformer layer weights via NVLink (tight bandwidth). Activations flow right across pipeline stages over InfiniBand. Two data-parallel replicas (top and bottom rows, offset for clarity) synchronise gradients via all-reduce after each micro-batch sweep. Colour distinguishes pipeline stages.

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 𝒪(SH/dtp) per layer. For S=128,000 tokens and H=12,288 (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 S is partitioned across dsp GPUs such that each GPU holds a contiguous segment si=[iS/dsp,(i+1)S/dsp) 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 dsp.

Sequence parallelism is typically co-located with tensor parallelism: the same dtp GPUs within a node handle both axes. In practice, dsp=dtp and the two axes share the NVLink fabric. The attention all-gather costs 𝒪(BSH) 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 dcp communication rounds). Context parallelism scales to much longer sequences than sequence parallelism because it avoids the full S-dimensional all-gather, at the cost of dcp 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 E “expert” sub-networks. With E experts distributed across dep GPUs, each GPU stores E/dep 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 E experts and dep expert-parallel GPUs, with E=E/dep experts per GPU. After the router assigns each token tj a target expert ej{1,,E}, expert parallelism executes a dispatch all-to-all: GPU k sends all tokens routed to experts {(k1)E+1,,kE} to GPU k, for every kk. Each GPU then runs its E 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: Cep=2BSHdep(dep1)αIB1, assuming uniform token routing (capacity factor 1) and InfiniBand bandwidth αIB.

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 Θ(NtokensH). For 5D parallelism to be efficient, dep 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 Ctotal()=CtpL+Cppm+Cdp+CspL+CepLMoE, where L is the total layer count, m is the number of micro-batches, and LMoE is the number of MoE layers.

Proof.

Each tensor-parallel all-reduce executes once per forward and backward pass per layer: 2L times per micro-batch, costing Ctp each. Each pipeline stage boundary transmits activations forward and gradients backward, once per micro-batch: m micro-batches, costing Cpp each. Data-parallel gradient all-reduce executes once per iteration regardless of m. 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, L layers, hidden dimension H, sequence length S, a cluster of N GPUs with memory MGPU each, the following greedy decision tree guides the choice of :

Algorithm 7 (Hybrid Parallelism Decision Framework).

  1. Does the model fit on one GPU? Check |θ|βprecMGPU, where βprec is bytes per parameter (2 for fp16/bf16, 4 for fp32). If yes, set dtp=dpp=1 and use data parallelism alone: ddp=N. Scale batch size accordingly.

  2. If not: apply tensor parallelism first. Tensor parallelism communicates via NVLink (fast, low-latency) and must not cross node boundaries. Choose dtp{2,4,8} to fit the model within MGPU per TP shard. Rule of thumb: each TP shard should hold |θ|/(dtpdpp)0.4MGPU (leave 60% for activations and optimizer states).

  3. Still need more memory: apply pipeline parallelism. Choose dpp to fit each pipeline stage within memory. Ensure L/dpp is an integer. Pipeline parallelism crosses node boundaries and introduces a bubble; choose the smallest dpp that satisfies the memory constraint.

  4. Fill remaining GPUs with data parallelism. Set ddp=N/(dtpdpp). Verify that the effective batch size Beff=Bmicromddp does not harm convergence (heuristic: Beff4096 tokens × sequence-length for language models).

  5. Long sequences: add sequence parallelism. If activation memory per layer exceeds budget, set dsp=dtp (co-locate with TP on NVLink).

  6. MoE model: add expert parallelism. Choose dep dividing E (number of experts) and adjust ddp downward to keep ddpdtpdppdep=N.

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 dpp stages and m micro-batches, the bubble fraction is: fbubble=dpp1m+dpp1. This is a decreasing function of m: more micro-batches reduce the relative overhead of the startup/drain. However, m is limited by activation memory: holding m micro-batches' activations in flight simultaneously costs mBmicroSHLstage bytes per pipeline stage.

Proposition 16 (Minimum Micro-Batch Count for Bounded Bubble).

Let ϵ>0 be a tolerated pipeline bubble fraction. Under a 1F1B schedule with dpp pipeline stages, the minimum number of micro-batches m required to achieve fbubbleϵ is: m=(1ϵ)(dpp1)ϵ.

Proof.

Setting fbubbleϵ and solving for m: dpp1m+dpp1ϵm+dpp1dpp1ϵmdpp1ϵ(dpp1)=(1ϵ)(dpp1)ϵ. Taking the ceiling gives the minimum integer m.

Example 20 (GPT-3 Pipeline Configuration).

GPT-3 used dpp=8 pipeline stages. Targeting a bubble fraction of ϵ=0.10 (10% idle time): m=0.90×70.10=63=63. In practice, Megatron-LM used m=8 micro-batches (bubble fraction =7/1546.7%), 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 m=1536/(ddp1). 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 L is not divisible by dpp, some stages have L/dpp layers and others have L/dpp. The stage with more layers takes longer, stalling the pipeline. Solution: choose dpp|L, 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: aux=αauxEe=1Efepe, where fe is the fraction of tokens routed to expert e and pe is the average router probability for expert e. Minimising aux 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, H=12,288, 96 attention heads) on 1024 A100 GPUs arranged in 128 nodes of 8 GPUs each. The configuration was: dtp=8,dpp=16,ddp=8,N=8×16×8=1024 GPUs. 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 dtp=8?).

GPT-3's attention layers have 96 heads. With dtp=8, each shard holds 96/8=12 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 256×256 pixels at 16 patches per frame produces a sequence of 256×1024=262,144 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 H=8,192, sequence length S=262,144 (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?): 100×109×2=200GB of parameters alone, versus 80,GB per GPU. Clearly not.

Step 2 (tensor parallelism): dtp=8 (full node, NVLink). Per-TP-shard parameter load: 200/8=25GB. Activation per layer per shard: BS/dspH=1×262,144×8,192/8268MB.

Step 3 (sequence parallelism): Set dsp=dtp=8 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: 80254.350GB for optimizer states. With ZeRO stage 1, optimizer states =12bytes/param/ddp1200GB/ddp. Set dpp=4 (32 layers per stage): optimizer states per GPU =1200/(ddp1) manageable.

Step 5 (data parallelism): ddp=2048/(8×4)=64. Effective batch size at micro-batch =1, m=16: Beff=1×16×64=1024 videos. Pipeline bubble: (41)/(16+3)15.8% - acceptable.

Final configuration: (ddp,dtp,dpp,dsp)=(64,8,4,8), N=64×8×4=2048.

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 =argminTiter() subject to i:Mi()MGPU. 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 dpp=12 pipeline stages.

  1. (a)

    Using the 1F1B bubble formula, compute the bubble fraction for m{12,24,48,96} micro-batches. Plot fbubble as a function of m.

  2. (b)

    Suppose activation memory allows at most mmax=24 micro-batches in flight simultaneously. What is the minimum achievable bubble fraction?

  3. (c)

    An engineer proposes using interleaved 1F1B (virtual pipeline stages) with v=2 virtual stages per device. Derive the bubble formula for interleaved 1F1B and show that it equals (dpp1)/(vm+dpp1). What is the bubble for m=24, v=2?

Exercise 66 (Communication cost comparison).

Consider a transformer with L=96 layers, H=8192, S=4096, trained on N=512 GPUs.

  1. (a)

    Configuration A: (dtp,dpp,ddp)=(8,8,8). Compute CtpL, Cppm (with m=16), and Cdp using αNVLink=600GB/s, αIB=25GB/s, αDC=12.5GB/s. (Hint: use formulas from Section 3D Parallelism: Data, Tensor, and Pipeline.)

  2. (b)

    Configuration B: (8,4,16). Repeat.

  3. (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 E=64 experts, 32 MoE layers out of L=64 total layers, H=4096, and is trained on N=1024 GPUs.

  1. (a)

    Propose a 5D parallelism configuration (ddp,dtp,dpp,dsp,dep) with N=1024.

  2. (b)

    Compute the expert-parallel all-to-all cost per MoE layer using B=2, S=2048, and αIB=25GB/s.

  3. (c)

    The auxiliary load-balancing coefficient is set to αaux=0.01. Under perfectly uniform routing, show that aux=αaux regardless of E.

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 p per unit time, then the probability that all N devices survive a training run of duration T is (1p)NT, which decays exponentially in both N and T. 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 k-fault-tolerant if it can complete a training run to the specified loss target while tolerating up to k simultaneous device failures, subject to the following conditions:

  1. 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 δtol with probability at least 1γ.

  2. Progress: recovery from any k-fault event (kk) requires at most trecov seconds of wall-clock time, during which training makes no forward progress.

  3. 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 ηft=trecov/Ttotal in expectation over the failure distribution.

Definition 46 (Mean Time Between Failures).

Let N be the number of devices in a cluster, each failing independently at rate λ (failures per device per hour). The cluster-level failure rate is Λ=Nλ. The mean time between failures (MTBF) of the cluster is MTBFcluster=1Λ=1Nλ. If each individual GPU has λ=0.001 failures/hour (MTBFdevice=1000 hours), then for N=10,000 GPUs: MTBFcluster=110,000×0.001=110 hour=6 minutes. A cluster of 10,000 GPUs experiences a failure every six minutes on average, even with individually reliable hardware.

Log-Scale Reliability Analysis

Let p=λΔt be the probability that a single device fails during a time interval Δt. The probability that all N devices survive the full training duration T (consisting of T/Δt intervals) is: Psurvive(N,T)=(1p)NT/Δt=(1λΔt)NT/Δt. Taking Δt0 and using the identity (1λΔt)1/Δteλ: Psurvive(N,T)=eλNT. The log-survival probability is lnPsurvive=λNT, which is linear in N, T, and λ. Doubling any of the three quantities halves the log-survival probability (i.e., squares Psurvive, pushing it toward zero exponentially faster).

Example 22 (Survival Probability at 10,000 GPUs).

A training run uses N=10,000 H100 GPUs for T=2,160 hours (90 days). Individual GPU MTBF is conservatively estimated at λ=104 failures/hour (MTBF =10,000 hours). Psurvive=e104×10,000×2,160=e216010938. The probability of completing a 90-day run on 10,000 GPUs without a single device failure is essentially zero. Even with λ=106 (MTBF = one million hours, far beyond current hardware): Psurvive=e106×104×2,160=e21.64×1010. 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 t is a serialisation of the tuple 𝒞t=(θt,vt,rt,st,σt), where θt are the model parameters, vt are the optimiser states (first and second moment estimates for Adam), rt is the random number generator state (PyTorch RNG, CUDA RNG), st is the data loader state (which shards and samples have been consumed), and σt is the learning rate schedule state. A complete checkpoint enables bit-exact resumption of training from iteration t.

The checkpoint overhead depends on two quantities: (i) the time to write |𝒞t| bytes to persistent storage, and (ii) the frequency of checkpointing. For Adam with bf16 parameters and fp32 optimizer states, |𝒞t|16|θ| 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): |𝒞t|2.8TB. 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), twrite be the time to write one checkpoint, and Λ be the cluster failure rate. The expected work lost per failure is τ/2 (on average, failures occur halfway between checkpoints). The expected training overhead from checkpointing is: ηckpt=twriteτ+Λτ21Titer, 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 ηckpt (ignoring restart overhead beyond the wasted work) is: τ=2twriteΛ. This is the classic Daly formula for checkpoint scheduling.

For the GPT-3 example: twrite=140s, Λ=1/6failures/hour=1/21,600s. τ=2×140×21,6006,048,0002459s41minutes. 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 N GPUs and total checkpoint size |𝒞|, the parallel write time is: twritedist=|𝒞|/Nαfs=|𝒞|Nαfs, where αfs is the per-GPU write bandwidth to the distributed filesystem. With N=1024 GPUs writing at 2,GB/s each: twritedist=2800GB1024×2GB/s1.37s. 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

Fault tolerance timeline. Training proceeds in blocks of τ seconds, with a checkpoint (CK, green) written at the end of each block. A failure (red triangle) occurs at time 2τ+Δ, losing Δ of work since the last checkpoint. A restart phase (amber, duration trecov) loads the last checkpoint and re-initialises the communication fabric. Training resumes from 2τ, replaying the data consumed since the checkpoint before continuing. The expected work lost per failure is τ/2.

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 [Nmin,Nmax] if:

  1. For any N[Nmin,Nmax], the system can initialise or reconfigure to N workers within trecfg seconds.

  2. Reconfiguration preserves training correctness: all workers converge to identical parameter states, and no training sample is lost or duplicated across a reconfiguration event.

  3. The effective batch size and learning rate schedule adapt automatically to the current N (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).

  1. Initialise: Worker w joins rendezvous group with membership in [Nmin,Nmax]. Wait until ||[Nmin,Nmax] and a rendezvous epoch e is agreed.

  2. Setup: Elect rank rw based on join order. Initialise NCCL process group with all || workers. Shard the model and data according to current ||.

  3. Train: Execute forward, backward, and optimiser steps. Checkpoint every τ seconds.

  4. Monitor: Detect worker failure (via heartbeat timeout) or new worker availability (via rendezvous watcher).

  5. 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).

  1. Register a SIGTERM handler on each worker process.

  2. On SIGTERM receipt: set a global flag preempt_flag = True.

  3. At the next iteration boundary, all workers check preempt_flag (synchronised via all-reduce on a 1-element tensor).

  4. If any worker has the flag set: write a distributed checkpoint, notify the job scheduler, and exit cleanly.

  5. 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 <30 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 (Nmin) 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 r>1 copies of each computation, such that any r1 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 1/ddp additional parameter memory and 1/ddp additional compute - acceptable for ddp4, but prohibitively expensive for ddp=1.

Remark 56 (Erasure coding for checkpoint compression).

Recent work from DeepMind and others applies Reed-Solomon erasure coding to distributed checkpoints: instead of writing N full checkpoint shards, write N+k encoded shards such that any N of the N+k shards suffice to reconstruct the full checkpoint. This tolerates k storage node failures during the checkpoint write without retrying. The overhead is a factor of (N+k)/N in storage and write bandwidth, typically 10–20% for k/N=0.10.2.

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: 54×24/4662.8 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 (10.956)×54×24/4665.5 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 1091012 per FLOP, low enough that they are unobservable on a single GPU but aggregate to a non-negligible probability over a run of 1024 FLOPs.

Elastic Scaling and Learning Rate Adjustment

When the number of workers changes in an elastic training setup, the effective batch size changes: Beff=BmicromNactive. To maintain the same training dynamics, the learning rate must be adjusted. The linear scaling rule prescribes: ηnew=ηrefNnewNref, where ηref is the learning rate calibrated for reference worker count Nref. This rule is empirically validated for Nnew/Nref8; beyond this range, gradient noise dominates and the linear rule overestimates the safe learning rate.

A complementary approach is gradient accumulation: when N drops below a threshold, increase the number of gradient accumulation steps proportionally, keeping Beff 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 t(k) denote the gradient of the loss on the k-th micro-batch at iteration t. Training with ddp data-parallel replicas each processing one micro-batch per step is mathematically equivalent to training with a single worker processing ddp micro-batches with gradient accumulation, in the sense that the accumulated gradient gt=1ddpk=1ddpt(k) is identical in expectation, provided the micro-batches are drawn i.i.d. from the same data distribution.

Proof.

Under i.i.d. sampling, 𝔼[t(k)]=𝔼[t(k)] for all k,k. The all-reduce in data parallelism computes gt=1ddpkt(k). Gradient accumulation on a single worker computes the same sum sequentially before issuing a weight update. The gradient variance is Var(gt)=σ2/(ddpBmicro) in both cases. Weight updates and optimiser states are therefore identical.

This equivalence is the theoretical basis for elastic training correctness: reducing ddp and increasing gradient accumulation steps preserves the training trajectory.

Exercises

Exercise 68 (Optimal checkpoint interval).

A training cluster of N=4096 GPUs trains a 70B-parameter model for T=30 days.

  1. (a)

    The model uses BF16 parameters and FP32 Adam states. Compute the checkpoint size |𝒞| in GB.

  2. (b)

    With distributed checkpointing at 2,GB/s per GPU and N=4096 writers, compute twrite.

  3. (c)

    Individual GPU MTBF is 5000 hours. Compute the cluster-level MTBF MTBFcluster and the optimal checkpoint interval τ using the Daly formula.

  4. (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).

  1. (a)

    Compute Psurvive(N,T) for (N,T){(100,1day),(1000,7days),(10000,30days)}, assuming λ=104 failures per GPU per hour. Express answers in scientific notation.

  2. (b)

    For the largest case, what individual GPU MTBF (i.e., 1/λ in hours) would be required to achieve Psurvive0.1?

  3. (c)

    A system claims to be k=2 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 trecov=60 seconds) during a 30-day run.

Exercise 70 (Elastic training and learning rate scheduling).

A training run starts with N0=512 workers, but due to spot preemptions drops to N1=384 after 10% of training, then recovers to N2=448 after 20% of training.

  1. (a)

    Using the linear scaling rule with reference ηref=3×104 at Nref=512, compute η at N1 and N2.

  2. (b)

    An alternative approach maintains Beff=512×Bmicro constant by increasing gradient accumulation steps. Compute the gradient accumulation steps required at N1 and N2.

  3. (c)

    Compare the two approaches: which produces faster wall-clock training at N1? 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 L layers, H attention heads, hidden dimension d, and a cluster of P accelerators interconnected by a network topology 𝒯, find the hybrid parallelism configuration π=(D,T,ppipe,S) 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 M.

The search space for hybrid parallelism is enormous even for modest cluster sizes. A cluster of P=512 GPUs admits configurations ranging from pure data parallelism (D=512) through pure pipeline parallelism (ppipe=512) 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 Tmax with peak memory M - 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 ppipe that minimizes bubble overhead while keeping the inter-stage activation memory below M. 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 L but exponential in T (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 P=64 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 N on P devices such that the inter-device communication volume scales as o(N/P) per layer while the output approximates the exact softmax attention output to precision ϵ in norm.

Ring attention achieves Θ(Nd/P) 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 𝐀N×N admits an ϵ-low-rank approximation of rank r=O(ϵ2logN), then it is theoretically possible to communicate only rd values per device per layer rather than Nd/P. For long sequences (NP) 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 O((N/P)logP) latency-optimal attention with O(NdlogP/P) bandwidth, matching ring attention bandwidth but offering lower latency for large P. 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 i can be computed using only the keys and values already stored on i? 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 P 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 K (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 P+1 - 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 O(P) 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 P to P, the optimizer state must be re-sharded: device i had responsibility for parameters [in/P,(i+1)n/P) and must transfer residual parameters to their new responsible devices. This is equivalent to a distributed repartition operation whose communication cost is O(n/min(P,P)) 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 q such that a distributed training algorithm for an n-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 q 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:

  1. Quantization error accumulation across devices. When P devices each quantize their local gradient to q bits before an all-reduce, the quantization noise adds constructively in the worst case. The expected noise magnitude scales as O(P2q) before the averaging step, suggesting that as P grows, more bits are needed to maintain the same effective gradient signal-to-noise ratio.

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

  3. Optimizer state precision. Adam's second moment estimator vt 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 P gradients has variance Θ(P122q), improving with P. 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 1% 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 102 to 104, 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 𝐱logpθ(𝐱) 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 t affect the optimal inter-datacenter communication frequency? Score estimates at large t (high noise) have lower effective dimensionality and may be compressible to lower bit-widths than estimates at small t.

  • 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 t (cheap, high noise) and less frequently at small t (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 Wi and associated carbon intensity ci(t) (gCO2eq/kWh, varying with time as the grid energy mix changes), and a target model quality Q, design an adaptive training protocol that achieves Q while minimizing i,tWici(t)Δt subject to the constraint that wall-clock training time does not exceed a deadline Tmax.

Training large generative models consumes extraordinary amounts of energy. Published estimates for frontier models range from 102 MWh for 7B-parameter models to 104 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 50% of peak power at 50% utilization but 95% of peak power at 95% 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 π:V(𝒢){1,,P}, 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 i that are consumed by an operation on device j must be communicated twice: once during the forward pass (from i to j) and once during the backward pass (from j back to i 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 k activations costs k 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 P-device clusters in which the failure of any f<P/3 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 10000 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 k-of-P devices can reconstruct the full state. Maximum-distance-separable (MDS) codes provide the optimal redundancy-recovery trade-off: k devices can reconstruct from any k 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 f 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 f<P/3 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 PG GPUs of type G, PT TPUs of type T, and PA custom ASICs of type A, each with distinct peak FLOP/s, memory capacity, memory bandwidth, and inter-device interconnect characteristics, design a training protocol for an n-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 Tmax and the fastest in Tmin, the throughput overhead is (TmaxTmin)/Tmax per step, which can exceed 50% 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 L-smooth, μ-strongly convex loss over an n-parameter model on P devices must communicate at least Ω(n/P) 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 Ω(n/P) 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 g^ satisfying 𝔼g^g2σ2, 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 n-parameter generative model on P devices such that the per-step gradient estimation error satisfies 𝔼g^g2σSGD2 (matching the statistical quality of single-device mini-batch gradient estimation) requires at least Ω(n/P) 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 n/P 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 frontier map for distributed generative model training. Horizontal axis measures degree of communication reduction targeted; vertical axis measures model fidelity that must be maintained. Problems in the shaded upper-right quadrant (Frontier) demand both aggressive communication reduction and high model fidelity and represent the hardest open challenges.

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 b bits (b4) 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 𝔼g^g2ωg2 for a compression factor ω<1, and (c) the training loss converges at rate O(1/T+ω/(1ω)2) where T is the number of steps.

Success criterion. A scheme achieving b=4 bits with ω0.05 and at most 2% FID degradation on ImageNet 256×256 relative to FP32 gradient training, with wall-clock speedup of at least 1.5× 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 t0, 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 t produce gradients of different magnitudes and sparsities), can reduce pipeline bubbles below the O(p1)/O(m+p1) bound of standard 1F1B.

Success criterion. A scheduling algorithm that achieves at most 50% 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 tT produce smaller activations (the input is mostly noise) and can be processed faster. Interleaving large-t and small-t 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 (512×512 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 30% relative to ZeRO-2 for joint VAE and diffusion backbone training at 1024×1024 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 512× 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 2× reduction in bandwidth saves more wall-clock time than a 2× 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 M bytes across P devices takes time TAR(M,P)=2(P1)α+2P1PβM, where α is the per-hop latency (seconds per message initiation) and β is the reciprocal bandwidth (seconds per byte).

For a cluster with α=1μs and β=1/(200GB/s)5ps/byte:

  1. (a)

    Compute TAR for a 1B-parameter model (4 GB gradient tensor at FP32) on P=64 GPUs.

  2. (b)

    Repeat for a 7B-parameter model (28 GB at FP32) on P=256 GPUs, and for a 70B-parameter model (280 GB at FP32) on P=1024 GPUs.

  3. (c)

    For each configuration, compute the ratio TAR/Tstep, where a single forward-backward step takes approximately 3×103 seconds per billion parameters per GPU at peak FLOP utilization. Comment on whether communication dominates compute in each case.

  4. (d)

    FP16 gradients halve M. What is the bandwidth savings? Does the savings depend on P?

Answer sketch. (a) M=4×109 bytes, P=64: TAR2×63×106+2×(63/64)×5×1012×4×109126μs+39.4ms39.5ms. Step time 1×3×103=3ms (per GPU; dominated by communication at P=64). (b–d) Follow similarly; the latency term 2(P1)α is negligible compared to the bandwidth term 2(P1)/PβM2βM for all cases above P8.

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 i holds [g0(i),g1(i),g2(i),g3(i)]. The goal is to compute the element-wise sum Gk=i=03gk(i) on all GPUs.

  1. (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 gk(i)=(i+1)k (so GPU 0 has [0,1,2,3], GPU 1 has [0,2,4,6], etc.).

  2. (b)

    Trace the all-gather phase step by step. State which reduced chunk each GPU sends and which it receives at each step.

  3. (c)

    After both phases, verify that every GPU holds the correct sum Gk=i=03gk(i) for all k.

  4. (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 M (total bytes of the gradient vector).

Answer sketch. Each GPU sends M/P bytes per step, for P1=3 steps in reduce-scatter and 3 steps in all-gather, total 2(P1)×M/P=6×M/4=3M/2 bytes sent per GPU. Combined with receive, each GPU sends and receives 3M/2 bytes for a total of 3M bytes transferred per GPU endpoint. Verify sums: G0=0, G1=10, G2=20, G3=30.

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 k=4. At each level, every uplink has bandwidth B: level 1 (edge to aggregation) B1=200Gb/s, level 2 (aggregation to core) B2=200Gb/s, level 3 (core) provides full-bisection bandwidth.

Topology B (3D Torus): A 4×4×4=64-node 3D torus where each link has bandwidth B=200Gb/s. The bisection cut divides the torus into two halves along one dimension.

  1. (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.)

  2. (b)

    Compute the bisection bandwidth of the 3D torus. (Hint: bisecting along one dimension cuts 4×4=16 links in each direction, but the torus wraps, so the bisection cut has 2×4×4=32 links.)

  3. (c)

    Which topology provides higher bisection bandwidth? Which provides lower hop count between arbitrary node pairs?

  4. (d)

    An all-reduce of M=10GB 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.

  5. (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 64/2=32 uplinks from aggregation to core on each side; bisection bandwidth is 32×200Gb/s=6.4Tb/s. (b) Torus bisection: 32 links ×200Gb/s=6.4Tb/s. Interestingly, both achieve the same bisection bandwidth for this configuration; the fat-tree advantage manifests at higher radix. (d) T=M/(Bbis/2)=10×1010/(3.2×1012)31ms.

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:

  1. (a)

    Initialize a model with parameters θ on a Root process (rank 0) and broadcast θ to all P workers.

  2. (b)

    Each worker i samples a minibatch i of size B, computes the local loss i(θ), and computes the local gradient gi=θi.

  3. (c)

    Perform an AllReduce to compute the globally averaged gradient g=1Pi=0P1gi.

  4. (d)

    Each worker updates θθηg using the averaged gradient.

  5. (e)

    Extend the pseudocode to handle gradient accumulation with K micro-batches per step, where the local gradient gi=1Kk=1Kθi,k 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 P=8 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): [8,6,10,5,12,7] (layer 6 to layer 1, i.e., last to first in backward order). The per-layer all-reduce times are (in ms): [3,2,4,2,5,3] (same ordering).

  1. (a)

    Compute the sequential time: backward compute time summed over all layers, then all-reduce time summed over all layers.

  2. (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.

  3. (c)

    Define overlap efficiency as ηoverlap=1Thidden/TAR,total, where Thidden is the communication time successfully hidden. Compute ηoverlap for this configuration.

  4. (d)

    Which layer is the bottleneck for overlap, and why?

  5. (e)

    How would bucket sizing affect ηoverlap? Is it better to use one large bucket or many small buckets?

Answer sketch. Sequential time: 8+6+10+5+12+7=48ms compute, 3+2+4+2+5+3=19ms AR, total 67ms. 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 5+12+7=24ms, 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 48+3=51ms (only first AR not hidden), Thidden=193=16ms, ηoverlap84%.

Tier 2: Parallelism Strategies and Memory Optimization

Exercise 76 (Local SGD Convergence Analysis).

In local SGD, each of P workers performs K local gradient steps between synchronizations. The theoretical convergence bound for a smooth, nonconvex objective f is 1Tt=1T𝔼f(θt)2C1PT+C2K2η2G2, where C1,C2 are constants depending on smoothness, η is the learning rate, G is a bound on the gradient norm, and T is the total number of local steps.

  1. (a)

    For K=1 (standard synchronous SGD), P=8, η=0.01, G=1, and C1=C2=1, find the minimum T such that the convergence bound is below 0.01.

  2. (b)

    For K=4 and K=16 with the same parameters, find the minimum T and the dominant term in the bound.

  3. (c)

    The communication cost is proportional to T/K (one synchronization every K steps). For each of K{1,4,16}, compute the total communication volume as a multiple of the K=1 baseline, assuming T is set to the minimum value from (a) and (b).

  4. (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 K 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 B0=64 and learning rate η0=104. The training is scaled to P=32 GPUs using synchronous data parallelism.

  1. (a)

    Compute the effective batch size Beff=P×B0 under the assumption that each GPU processes B0 samples per step.

  2. (b)

    Apply the linear scaling rule: set the new learning rate η=η0×Beff/B0. What is η?

  3. (c)

    Apply the square-root scaling rule: set η=η0×Beff/B0. What is η? Under what conditions is square-root scaling preferred to linear scaling?

  4. (d)

    In diffusion model training, the loss at noise level t is weighted by λ(t)=1/σ(t)2. This weighting makes the effective gradient variance depend on t. Explain qualitatively how this affects the choice of the scaling rule and the warm-up schedule for the learning rate.

  5. (e)

    Training with Beff=2048 is known to exhibit gradient noise scale noise=tr(Σ)/g2200 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 d=8192 and intermediate dimension dff=4×d=32768 (standard 4x feedforward expansion). The layer is tensor-parallelized across T=8 GPUs.

  1. (a)

    Compute the parameter count of the feedforward sublayer (two linear projections: ddff and dffd). What is the memory usage in GB at FP16?

  2. (b)

    With column-parallel tensor parallelism for the first linear (ddff/T per GPU) and row-parallel for the second (dff/Td per GPU), compute the parameter memory per GPU. What is the memory savings factor?

  3. (c)

    Compute the activation memory for a forward pass with batch size B=16 and sequence length S=4096 for: (i) the un-parallelized layer, and (ii) the T=8-way tensor- parallel layer.

  4. (d)

    The tensor-parallel feedforward requires an AllReduce after the row-parallel projection. Compute the communication volume per device (in GB) for the parameters above.

  5. (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 β1=200GB/s interconnect?

Exercise 79 (Pipeline Parallelism: Bubble Fraction for GPipe vs. 1F1B).

A model is split across p=8 pipeline stages with m micro-batches per batch.

  1. (a)

    The GPipe bubble fraction is (p1)/(m+p1). Compute this for m{8,16,32,64} with p=8. At what value of m does the bubble fraction drop below 5%?

  2. (b)

    The 1F1B schedule has the same asymptotic bubble fraction (p1)/(m+p1) but with peak activation memory equal to p micro-batches rather than m for GPipe. For m=32 and p=8, compute the peak activation memory ratio 1F1B/GPipe.

  3. (c)

    An interleaved 1F1B schedule with v=2 virtual stages per device achieves bubble fraction (p1)/(vm+p1). Compute the bubble fraction for m=16, p=8, v=2. Compare to non-interleaved 1F1B with m=32.

  4. (d)

    For a diffusion model with 48 transformer layers and p=8 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.

  5. (e)

    At pipeline depth p=8 and m=32, a hardware failure causes one stage to run 20% 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.

  1. (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)?

  2. (b)

    ZeRO Stage 1 shards optimizer states across P=64 GPUs. Compute the memory saved per GPU for optimizer states. What is the total memory per GPU?

  3. (c)

    ZeRO Stage 2 additionally shards gradients. Compute the additional memory saved per GPU for gradients (assuming FP16 gradients). Total memory per GPU?

  4. (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?

  5. (e)

    At P=256 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, P=64): Parameters (FP16): 13×109×2=26GB. Optimizer state (FP32 master weights + 2 moments): 13×109×12=156GB. ZeRO-1: optimizer per GPU =156/642.4GB, total per GPU =26+2.4+2654.4GB (gradient not sharded). ZeRO-2: gradients sharded, per GPU =26/640.4GB additional saving. ZeRO-3: params sharded, per GPU =26/640.4GB, total (26+26+156)/64=3.25GB 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.

  1. (a)

    A ring all-reduce of M bytes at bandwidth β1=400GB/s takes time proportional to M. Compute the time savings from FP16 (half the bytes) for a 7B model gradient tensor.

  2. (b)

    Loss scaling requires multiplying the loss by a scale factor s=215 before the backward pass and dividing gradients by s after the all-reduce. The division by s 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.

  3. (c)

    FP16 all-reduce followed by FP32 optimizer update requires a type conversion step. On a GPU with 1013FLOP/s and 1012B/s memory bandwidth, is the type conversion compute-bound or memory-bound?

  4. (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 P=256 FP16 gradients in FP16.

  5. (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 m=8 micro-batches per step. Standard 1F1B has a bubble fraction (p1)/(m+p1)=3/1127%.

DiffusionPipe proposes to fill pipeline bubbles with inference micro-batches from a different noise level, using the same pipeline hardware.

  1. (a)

    Compute the number of bubble time slots available per step (in units of one stage's compute time) in standard 1F1B with p=4, m=8.

  2. (b)

    If each inference micro-batch (DDIM, 50 steps for a 512×512 image) takes 0.5× 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?

  3. (c)

    Define the combined throughput efficiency as (Ttrain+Tinfer)/Tpipeline, where Tpipeline is the wall-clock pipeline time. Compute this for your answer in (b).

  4. (d)

    Does filling bubbles with inference micro-batches affect training convergence? Identify any assumptions required.

  5. (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 N across P GPUs, each holding N/P query tokens and the full key-value context via ring communication.

  1. (a)

    For N=128,000, P=8, head dimension dk=128, and H=32 attention heads, compute the size of the key-value shard per GPU (in GB at FP16).

  2. (b)

    In ring attention, each device sends its N/P KV tokens to the next device in the ring at each of P1 steps. Compute the total bytes transmitted per device over the full ring attention pass.

  3. (c)

    Compare this to the communication cost of standard (non-ring) distributed attention where the full KV is broadcast to all devices.

  4. (d)

    For the parameters above with interconnect bandwidth β1=400GB/s, compute the communication time for ring attention. Compare to the attention computation time assuming 1013FLOP/s and FLOPs for attention =4NHdk per device.

  5. (e)

    If the attention pattern is sparse (each query attends to only Ks=4096 of the N keys), does ring attention still require transmitting the full KV? Propose a modification to exploit sparsity.

Answer sketch. (a) KV shard per GPU: 2×(N/P)×H×dk×2bytes=2×16000×32×128×2263MB. (b) Each device sends its KV shard (P1)=7 times: 7×263MB1.84GB. (c) Broadcast: each device receives full KV =P×263MB=2.1GB from root (or 2(P1)/P×P×263MB for a tree broadcast), worse than ring for large P. (d) Communication time 1.84GB/400GB/s4.6ms. FLOPs per device =4×128000×32×128=2.1×109 FLOPs, time =2.1×109/10130.21ms: 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.

  1. (a)

    Draw the forward communication graph between stages. Label each edge with the direction and the tensor being communicated.

  2. (b)

    In the backward pass, trace the gradient flow. For each forward edge AB, state which backward communication it generates (BA gradient) and identify any skip-connection gradients that cross multiple stages.

  3. (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.

  4. (d)

    Explain why gradient checkpointing is more beneficial for the skip connection activations than for the main pathway activations in this architecture.

  5. (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 P=1024 GPUs has individual GPU mean-time-between-failures (MTBF) of τGPU=2000h. The cluster fails (any GPU failure halts training) with cluster MTBF τcluster=τGPU/P.

  1. (a)

    Compute τcluster in hours. How many failures are expected per day?

  2. (b)

    The checkpoint interval is Δ=20min. On failure, the team reverts to the last checkpoint and restarts. Assume restart time (save + reload + re-init) takes r=5min. Compute the expected wasted time per failure event.

  3. (c)

    Define training efficiency as η=1𝔼[wasted time]/𝔼[total time]. Compute η for the parameters above.

  4. (d)

    Optimize the checkpoint interval Δ to maximize η. Express Δ as a function of τcluster and r. (Hint: minimize expected wasted fraction.)

  5. (e)

    A new asynchronous checkpointing system reduces checkpoint save time to rs=1min (overlapped with training) but still requires rr=4min to reload. How does this change Δ and η?

  6. (f)

    If the cluster grows to P=8192 GPUs (a future frontier cluster), compute τcluster and η with Δ re-optimized. Comment on the viability of checkpoint-restart at this scale.

Answer sketch. (a) τcluster=2000/10241.95h117min. Failures per day: 24/1.9512.3. (b) Expected wasted time per failure Δ/2+r=10+5=15min. (c) Expected failures per unit time =1/τcluster. Wasted fraction 15/11712.8%; η87%. (d) Δ=2rτcluster=2×5×11734min.

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.

  1. Implement the DDP wrapper manually using dist.all_reduce on gradients rather than using PyTorch's built-in DistributedDataParallel module. This forces explicit understanding of the gradient averaging.

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

  3. Measure training throughput (images/second) on 1, 2, and 4 GPUs. Compute the parallel efficiency ηP=T1/(PTP) where TP is wall-clock time to reach the same loss as a single GPU.

  4. 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 N=32768 distributed across P=4 GPUs such that the communication volume is at most 50% of ring attention's volume, while the output approximates exact attention to within ϵ=0.01 in normalized mean absolute error on a held-out validation set.

Requirements.

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

  2. Prove or empirically estimate the approximation error as a function of the design parameters (window size, number of global tokens, etc.).

  3. Derive the bandwidth and latency of your mechanism using the alpha-beta model with α=1μs, β=5ps/byte.

  4. Compare your mechanism to ring attention on the four criteria: communication volume, latency, approximation error, and implementation complexity.

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

  1. Implement ring all-reduce using dist.send and dist.recv with explicitly coded ring topology. Do not use dist.all_reduce, which calls NCCL internally.

  2. Implement binary-tree reduce-scatter and all-gather using point-to-point communication.

  3. Benchmark both implementations for tensor sizes M{1,10,100,1000}MB at FP32. Report mean and standard deviation over 20 runs after a 5-run warm-up.

  4. Plot achieved bandwidth (GB/s) vs. tensor size for both implementations. At what size does ring all-reduce begin to outperform the tree?

  5. Compare your implementations to the built-in NCCL all-reduce (the dist.all_reduce baseline). 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 989TFLOP/s at BF16.

Requirements.

  1. Propose values of (D,T,ppipe) such that D×T×ppipe=256 and the configuration is memory-feasible (all parameters, optimizer states, and activations fit within 80 GB per GPU under ZeRO-1).

  2. Compute the expected memory usage per GPU under your configuration, breaking down by parameters, optimizer states, gradients, and activations.

  3. Estimate the communication time per step for each parallelism dimension using the alpha-beta model. Which dimension contributes the most communication overhead?

  4. Estimate the pipeline bubble fraction for your proposed ppipe and a reasonable micro-batch count m.

  5. Compare your configuration to two alternatives: (i) pure data parallelism (D=256,T=1,p=1), and (ii) a configuration published in the Megatron-LM paper for a similar cluster.

  6. 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 +1 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 1.

Requirements.

  1. For a 32-layer transformer with 7B parameters (14GB at FP16), compute the per-layer AllGather volume and the AllGather time at β1=400Gb/s.

  2. Measure the per-layer forward compute time on your hardware using PyTorch profiler. Compute the theoretical hiding efficiency ηhide=min(Tcompute,TAR+1)/TAR+1 averaged across layers.

  3. Profile an actual FSDP training run using torch.profiler and measure the fraction of AllGather time that overlaps with compute in practice. Compare to the theoretical estimate.

  4. 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?

  5. 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 2×; communication hiding reduces exposed communication by another 25×; gradient compression can reduce bandwidth by a further 48×. Applied together on a communication-bottlenecked cluster, these techniques can bring communication overhead below 10% 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

  1. Ring all-reduce sends and receives each element once during reduce-scatter and once during all-gather, hence the factor of 2.