Level 3 In-Depth AI · ML Engineering and Production
Distributed Training
How one model is trained on many GPUs at once. Data parallelism copies the model and splits the data; tensor and pipeline parallelism split the model itself; ZeRO and FSDP split the memory. Together they let thousands of GPUs train one model for months.
- Level
- ●●●●● Advanced
- Reading
- 13 min
- To learn it well
- 1 hour to read, a day to practise on real hardware
- Builds on
- 27 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 27 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- NumPy and Array Thinking
- GPUs and Why AI Needs Them
- Supervised Learning
- Linear Regression
- Training, Validation and Test Sets
- The Perceptron
- Logistic Regression
- Overfitting and the Bias–Variance Tradeoff
- Regularization: L1 and L2
- Neural Networks
- Backpropagation
- Dropout and Regularizing Neural Networks
- PyTorch
- Optimizers: SGD, Momentum and Adam
- Training Neural Networks in Practice
- Distributed Training
Read them roughly in this order. See it on the concept map →
Why it matters
Two walls stop you training a big model on one GPU.
The time wall. Training compute for a transformer is roughly floating-point operations, where is the number of parameters and the number of training tokens (Scaling Laws). A 7-billion-parameter model on 2 trillion tokens needs about operations. One H100 sustaining 400 TFLOPS (about 40% of its BF16 peak) would take seconds: almost seven years. A thousand GPUs could do it in under three days.
The memory wall. Training with the Adam optimizer in Mixed Precision Training needs about 16 bytes per parameter for weights, gradients and optimizer state, before counting activations. A 7B model needs about 112 GB and a 70B model about 1,120 GB, while a single H100 has 80 GB. Some models simply don't fit on one device.
Distributed training splits the work across many GPUs, and many machines, so that both walls fall. Every frontier model is trained this way. Meta reported training Llama 3's largest model (405B parameters) on up to 16,384 H100 GPUs at once. Even if you never run a cluster, these ideas explain the shape of the field: why GPU interconnects matter (AI Hardware: GPUs, TPUs and Accelerators), why batch sizes are huge, and why fine-tuning big models needs tricks.
The intuition
Imagine a library that needs ten thousand books translated.
- Hire more translators, each with their own dictionary. Each takes a pile of books. That's data parallelism: every GPU has a full copy of the model and processes a different slice of the data. The translators must regularly agree on any updates to the shared dictionary. For GPUs, that means averaging their gradients.
- The dictionary is too heavy to carry, so tear it into volumes. Each translator holds a few letters of the alphabet, and they pass words between them as they work. That's tensor parallelism: each large matrix is split across GPUs, and they exchange partial results inside every layer.
- An assembly line. One person translates chapter openings, the next the middles, the next the endings, handing pages down the line. That's pipeline parallelism: each GPU holds a block of consecutive layers, and activations flow from one to the next.
Key idea Data parallelism copies the model and splits the data; it is simple and scales well, but every GPU must hold the whole model. Tensor and pipeline parallelism split the model itself. ZeRO/FSDP keeps data parallelism but shards the memory. Large runs combine all of them.
How it works
Data parallelism and all-reduce
With GPUs, give each one a full copy of the model and a different shard of each batch. Each computes the gradient on its own examples. Then all GPUs average their gradients and apply the same update, so the copies stay identical.
Why is this correct? The loss is an average over examples (Gradient Descent), and so is its gradient. If a batch of 256 examples is split into 4 shards of 64, the average of the four shard gradients is exactly the gradient of the full batch of 256:
So training on 4 GPUs with 64 examples each is mathematically the same as one GPU with 256. The code below confirms it to the last bit. The global batch size is the per-GPU batch times the number of GPUs.
The averaging step is a collective operation called all-reduce: every GPU starts with its own vector and ends with the sum (or average) of all of them. The naive way, sending everything to one GPU, makes that GPU a bottleneck. Ring all-reduce arranges the GPUs in a ring. Each splits its gradient into chunks. In steps of passing chunks to the next neighbour and adding, each GPU ends up owning the complete sum of one chunk (the reduce-scatter phase). In another steps, the finished chunks travel round the ring until everyone has all of them (the all-gather phase). Each GPU sends about
which is less than twice the gradient size however many GPUs there are. NVIDIA's NCCL library implements this (and faster tree variants), and PyTorch's DistributedDataParallel (DDP) calls it automatically, overlapping communication with the backward pass.
Worked example. A 1B-parameter model has 2 GB of BF16 gradients. With 8 GPUs, each sends GB per step. Over NVLink inside one server (hundreds of GB/s per GPU) that takes a few milliseconds. Over a 25 Gbit/s Ethernet link (about 3 GB/s) it takes more than a second, far longer than the computation. Fast interconnects are not a luxury.
Big batches change the optimisation
More GPUs means a bigger global batch, and that is not free. Goyal and colleagues (2017) trained ResNet-50 on ImageNet in one hour on 256 GPUs with a batch of 8,192 images. They used two now-standard tricks: scale the learning rate in proportion to the batch size (the linear scaling rule), and warm up the learning rate gradually over the first few epochs (Learning Rate Schedules). Beyond some critical batch size, which depends on the problem, extra examples per step stop speeding up training, so you can't scale data parallelism forever.
ZeRO and FSDP: data parallelism without the copies
Plain data parallelism stores the full 16 bytes per parameter on every GPU, which is pure duplication. ZeRO (Zero Redundancy Optimizer, Microsoft, 2019) removes it in three stages. Each GPU keeps only its share of:
- the optimizer state (stage 1),
- plus the gradients (stage 2),
- plus the parameters themselves (stage 3).
In stage 3, before computing a layer, the GPUs briefly all-gather that layer's full weights, use them, and throw them away. After the backward pass, a reduce-scatter leaves each GPU with just its shard of the averaged gradients. PyTorch's fully sharded data parallel (FSDP) implements the same idea.
Per-GPU memory for model state, with parameters, GPUs, 2 bytes each for BF16 weights and gradients and 12 for the FP32 master weights and Adam moments:
| Scheme | Bytes per GPU | 7B on 8 GPUs | 70B on 64 GPUs |
|---|---|---|---|
| Plain data parallel | 112 GB | 1,120 GB | |
| ZeRO-1 | 38.5 GB | 293 GB | |
| ZeRO-2 | 26.3 GB | 155 GB | |
| ZeRO-3 / FSDP | 14 GB | 17.5 GB |
The price is extra communication: about 1.5 times the traffic of plain data parallelism for stage 3, according to the ZeRO paper. Activations are not sharded by ZeRO. They are reduced with activation checkpointing (gradient checkpointing), which recomputes them in the backward pass instead of storing them.
Tensor parallelism
Some single layers are too large or too slow for one GPU. Tensor parallelism splits the matrix multiplications themselves. Megatron-LM (Shoeybi et al., NVIDIA, 2019) showed a neat split for a transformer's feed-forward block, :
- Split by columns across GPUs. Each GPU computes its slice of and applies GELU independently, because GELU acts on each element separately.
- Split by rows. Each GPU multiplies its slice and gets a partial sum of .
- One all-reduce adds the partial sums.
Attention heads are split the same way: different heads on different GPUs. The cost is an all-reduce inside every layer, in both the forward and backward passes, so tensor parallelism is normally kept within one server, where GPUs are linked by NVLink, typically 8 GPUs.
Pipeline parallelism
Pipeline parallelism puts consecutive layers on different GPUs: layers 1–20 on GPU 1, layers 21–40 on GPU 2, and so on. Only the activations at the boundaries travel between GPUs, which suits slower links between servers.
The problem is idleness. If one batch goes through stage 1, then stage 2, and so on, three of four GPUs are always waiting. GPipe (Huang et al., Google, 2018) splits each batch into micro-batches that follow each other down the pipeline, so the stages work at the same time on different micro-batches. The idle time at the start and end, the pipeline bubble, is a fraction
of the total, for stages. With 4 stages and 4 micro-batches, 3/7 ≈ 43% of the time is wasted. With 32 micro-batches it falls to 3/35 ≈ 9%. Schedules such as 1F1B (one forward, one backward) and interleaved stages shrink it further and save memory.
Putting it together
Large runs combine all three, often called 3D parallelism: tensor parallelism within a server, pipeline parallelism across a few servers, and data parallelism (usually sharded, ZeRO/FSDP style) across everything else. Long-context training adds context (sequence) parallelism, which splits the sequence across GPUs, and Mixture of Experts models add expert parallelism, which places different experts on different GPUs. Meta described Llama 3 405B's training as "4D parallelism": tensor, pipeline, context and data parallelism together.
Choosing the layout is a puzzle of memory, communication and bubbles, and teams measure success by model FLOPs utilisation (MFU): the fraction of the hardware's peak arithmetic that goes into the model's actual computation. Well-tuned large runs typically report around 35–50% (Meta reported 38–43% BF16 MFU for Llama 3 405B).
In code
A NumPy simulation of data parallelism on 4 "GPUs", with a hand-written ring all-reduce. It checks that the replicas stay identical and that the result equals single-GPU training on the full batch.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(1024, 8)); w_true = rng.normal(size=8)
y = X @ w_true + 0.1 * rng.normal(size=1024)
def grad(w, Xb, yb): # gradient of mean squared error
return 2 * Xb.T @ (Xb @ w - yb) / len(yb)
def ring_allreduce(vectors):
"""Average equal-length vectors the way NCCL does: reduce-scatter, then all-gather."""
n = len(vectors)
chunks = [np.array_split(v.copy(), n) for v in vectors] # each worker splits its vector
sent = 0
for step in range(n - 1): # reduce-scatter
for i in range(n):
c = (i - step) % n
chunks[(i + 1) % n][c] += chunks[i][c]; sent += chunks[i][c].size
for step in range(n - 1): # all-gather
for i in range(n):
c = (i + 1 - step) % n
chunks[(i + 1) % n][c] = chunks[i][c].copy(); sent += chunks[i][c].size
return [np.concatenate(ch) / n for ch in chunks], sent / n
n_workers, lr = 4, 0.05
w_single = np.zeros(8); w_dp = [np.zeros(8) for _ in range(n_workers)]
for step in range(100):
batch = rng.choice(1024, 256, replace=False)
w_single -= lr * grad(w_single, X[batch], y[batch]) # one GPU, batch of 256
shards = np.array_split(batch, n_workers) # 4 GPUs, 64 examples each
local = [grad(w_dp[k], X[s], y[s]) for k, s in enumerate(shards)]
averaged, per_worker = ring_allreduce(local)
w_dp = [w - lr * g for w, g in zip(w_dp, averaged)]
print("replicas identical:", all(np.allclose(w_dp[0], w) for w in w_dp))
print("max |single - data parallel|:", np.abs(w_single - w_dp[0]).max())
print("values sent per worker per all-reduce:", per_worker, "for a gradient of 8")
# replicas identical: True
# max |single - data parallel|: 0.0
# values sent per worker per all-reduce: 12.0 for a gradient of 8
Each worker sent 12 numbers for a gradient of 8, matching . In real PyTorch, the same data parallelism is a wrapper around the model plus a launcher. This needs several processes, so it is shown rather than run here. Start it with torchrun --nproc_per_node=4 train.py:
import os, torch, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
dist.init_process_group("nccl") # "gloo" works on CPU
rank = int(os.environ["LOCAL_RANK"]); torch.cuda.set_device(rank)
model = DDP(MyModel().cuda(rank), device_ids=[rank]) # all-reduces gradients in backward()
sampler = torch.utils.data.DistributedSampler(dataset) # a different shard per rank
loader = torch.utils.data.DataLoader(dataset, batch_size=64, sampler=sampler)
# ... the usual training loop: loss.backward(); opt.step() ...
dist.destroy_process_group()
For FSDP, PyTorch's current API is torch.distributed.fsdp.fully_shard(model) (FSDP2). Libraries such as DeepSpeed, Megatron-LM, Hugging Face Accelerate and PyTorch's TorchTitan package these strategies with sensible defaults.
Common pitfalls
- Every rank sees the same data. Forgetting the
DistributedSamplermeans each GPU trains on identical batches: you pay for GPUs and get the work of one. Callsampler.set_epoch(epoch)so shuffling changes each epoch. - Changing the global batch without changing the learning rate. Going from 1 to 64 GPUs multiplies the batch by 64. Rescale and warm up the learning rate, or use gradient accumulation to keep the global batch fixed.
- Communication-bound training. If GPU utilisation is low and adding GPUs barely helps, the network is the bottleneck. Profile, overlap communication with computation, use bigger per-GPU batches, or keep bandwidth-hungry parallelism inside a server.
- One slow or failed GPU stalls everyone. Synchronous training waits for the slowest worker. At thousands of GPUs, hardware failures happen daily, so save checkpoints frequently and plan for automatic restarts. Meta reported 419 unexpected interruptions during a 54-day period of Llama 3 405B pre-training.
- Logging and saving from every rank. Only rank 0 should print, log and save, or you get duplicated logs and corrupted files.
Watch out Distributed bugs are often silent. A wrongly sharded dataset, a parameter that isn't synchronised, or a different random seed for dropout on each rank can leave training running but learning less, or diverging slowly. Check that replicas stay identical and compare a small run against a single-GPU baseline.
Where it leads
- AI Hardware: GPUs, TPUs and Accelerators: the interconnects (NVLink, InfiniBand), memory and FLOPs that decide which parallelism layout is fast.
- Mixed Precision Training: the per-parameter memory that ZeRO shards.
- Mixture of Experts: expert parallelism and its all-to-all communication.
- Serving LLMs at Scale: tensor and pipeline parallelism reappear when a model is too big for one GPU at inference time.
- Scaling Laws and Pretraining Large Language Models: why anyone needs thousands of GPUs in the first place.
A bit of history
Distributed training of neural networks is older than GPUs being cheap. In 2012 Google's DistBelief system (Dean et al.) trained networks across thousands of CPU cores with a central "parameter server" and asynchronous updates. Synchronous data parallelism on GPUs won out. Baidu popularised ring all-reduce for deep learning in 2017, Uber's Horovod library made it easy, and Goyal et al. showed in 2017 that ImageNet could be trained in an hour with large batches. As language models outgrew single GPUs, model parallelism returned: GPipe (2018) and Megatron-LM (2019) established pipeline and tensor parallelism, and ZeRO (2019, in DeepSpeed) removed data parallelism's memory duplication. PyTorch adopted the idea as FSDP. Since then, training runs have grown to tens of thousands of GPUs, and the main challenges have shifted from algorithms to reliability, networking and power.
Try it
- Change
n_workersto 3 and 8 in the simulation. Do the replicas still match the single-GPU run? Check thatper_workerequals .- Make the shards unequal (for example split 256 into 100, 100, 56) but still average the gradients equally. Does the result still match single-GPU training? Why not, and how would you fix it?
- Using the ZeRO table, how many GPUs of 80 GB would you need to hold the model state of a 70B model with ZeRO-3, leaving 30 GB per GPU for activations?
Hint for 2: each shard gradient is a mean over its own examples. To get the full-batch mean you must weight each shard by its number of examples.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
The Ultra-Scale Playbook: Training LLMs on GPU Clusters
A long, interactive guide to data, tensor, pipeline, context and expert parallelism and ZeRO, with memory and communication arithmetic and thousands of benchmark runs.
Getting Started with Distributed Data Parallel
The official tutorial for DistributedDataParallel: process groups, launching with torchrun, and checkpointing.
ZeRO: Memory Optimizations Toward Training Trillion Parameter Models
Shards optimizer state, gradients and parameters across data-parallel GPUs, removing duplication. The basis of DeepSpeed and PyTorch FSDP.
Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism
Introduces the standard way to split transformer layers across GPUs (tensor parallelism) with only a few all-reduces per layer.
GPipe: Efficient Training of Giant Neural Networks using Pipeline Parallelism
Splits a network into stages on different accelerators and pipelines micro-batches through them to keep all stages busy.
How To Scale Your Model
A free online book on the systems view of LLMs: rooflines, TPUs and GPUs, sharding, parallelism strategies and inference, with worked problems.
Machine Learning Engineering Open Book
A practitioner's open book on the hardware and software of training and serving large models: GPUs, networking, storage and debugging.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/mlops/distributed-training.md