◆ AI All-in-One

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
↗ Plan a path here

Read first

Training Neural Networks in PracticeGPUs and Why AI Needs Them

This leads to

—
The full path from zero — 27 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Tensors and Shapes
  13. NumPy and Array Thinking
  14. GPUs and Why AI Needs Them
  15. Supervised Learning
  16. Linear Regression
  17. Training, Validation and Test Sets
  18. The Perceptron
  19. Logistic Regression
  20. Overfitting and the Bias–Variance Tradeoff
  21. Regularization: L1 and L2
  22. Neural Networks
  23. Backpropagation
  24. Dropout and Regularizing Neural Networks
  25. PyTorch
  26. Optimizers: SGD, Momentum and Adam
  27. Training Neural Networks in Practice
  28. 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 6ND6ND floating-point operations, where NN is the number of parameters and DD the number of training tokens (Scaling Laws). A 7-billion-parameter model on 2 trillion tokens needs about 6×7×109×2×1012≈8.4×10226 \times 7 \times 10^9 \times 2 \times 10^{12} \approx 8.4 \times 10^{22} operations. One H100 sustaining 400 TFLOPS (about 40% of its BF16 peak) would take 8.4×1022/4×1014≈2.1×1088.4 \times 10^{22} / 4 \times 10^{14} \approx 2.1 \times 10^8 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.
Data parallelwhole model on every GPU GPU 1¼ of the batch GPU 2¼ of the batch GPU 3¼ of the batch GPU 4¼ of the batch all-reduce gradients Tensor parallelevery layer split across GPUs L1 L2 L3 L4 GPU 1 GPU 2 GPU 3 GPU 4 one column = one GPU's slice Pipeline parallelconsecutive layers per GPU L1 on GPU 1 L2 on GPU 2 L3 on GPU 3 L4 on GPU 4 activations 3 2 1 micro-batches 1, 2, 3 flow downlike an assembly line simple, scales to 1000s of GPUsbut each GPU needs the whole model splits huge layerstalks in every layer: keep inside a server little traffic between stagesidle "bubble" at start and end
Fig. 1 Three ways to split training across four GPUs. Data parallelism: each GPU holds the whole model and a different quarter of the batch, and gradients are averaged. Tensor parallelism: each layer's weight matrices are cut into four slices, one per GPU. Pipeline parallelism: each GPU holds a quarter of the layers, and micro-batches flow through them like an assembly line.

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 KK 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:

∇Lbatch=1K∑k=1K∇Lshard k\nabla L_{\text{batch}} = \frac{1}{K} \sum_{k=1}^{K} \nabla L_{\text{shard } k}

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 KK GPUs in a ring. Each splits its gradient into KK chunks. In K−1K-1 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 K−1K-1 steps, the finished chunks travel round the ring until everyone has all of them (the all-gather phase). Each GPU sends about

2 K−1K×gradient size2 \, \frac{K-1}{K} \times \text{gradient size}

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 2×7/8×2=3.52 \times 7/8 \times 2 = 3.5 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 1/K1/K share of:

  1. the optimizer state (stage 1),
  2. plus the gradients (stage 2),
  3. 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 Ψ\Psi parameters, KK 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 16Ψ16\Psi 112 GB 1,120 GB
ZeRO-1 4Ψ+12Ψ/K4\Psi + 12\Psi/K 38.5 GB 293 GB
ZeRO-2 2Ψ+14Ψ/K2\Psi + 14\Psi/K 26.3 GB 155 GB
ZeRO-3 / FSDP 16Ψ/K16\Psi/K 14 GB 17.5 GB
Model-state memory per GPU: 70B parameters, 64 GPUs 0 200 400 600 800 1000 1200 GB per GPU Plain data parallelevery GPU holds everything1,120 GB ZeRO-1shard optimizer state293.1 GB ZeRO-2+ shard gradients155.3 GB ZeRO-3 / FSDP+ shard parameters17.5 GB 80 GB: one H100 BF16 weights BF16 gradients FP32 master + Adam
Fig. 2 Memory per GPU for the model state of a 70B model trained on 64 GPUs. Plain data parallelism would need 1,120 GB per GPU. ZeRO stage 1 needs 293 GB, stage 2 needs 155 GB, and stage 3 (FSDP) needs 17.5 GB, which fits on an 80 GB GPU with room for activations.

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, Y=GELU(XA) B\mathbf{Y} = \text{GELU}(\mathbf{X}\mathbf{A})\,\mathbf{B}:

  • Split A\mathbf{A} by columns across GPUs. Each GPU computes its slice of XA\mathbf{X}\mathbf{A} and applies GELU independently, because GELU acts on each element separately.
  • Split B\mathbf{B} by rows. Each GPU multiplies its slice and gets a partial sum of Y\mathbf{Y}.
  • 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 mm 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

bubble=p−1m+p−1\text{bubble} = \frac{p - 1}{m + p - 1}

of the total, for pp 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 2×34×82 \times \frac{3}{4} \times 8. 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 DistributedSampler means each GPU trains on identical batches: you pay for KK GPUs and get the work of one. Call sampler.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

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

  1. Change n_workers to 3 and 8 in the simulation. Do the replicas still match the single-GPU run? Check that per_worker equals 2(K−1)/K×82(K-1)/K \times 8.
  2. 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?
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You train with data parallelism on 64 GPUs, each with a batch of 32. What is the global batch size, and what else must you think about?

  2. With ring all-reduce over K GPUs, roughly how much data does each GPU send per step?

  3. A pipeline has 4 stages and 4 micro-batches. What share of the time is the pipeline bubble, and how do you shrink it?

  4. Why is tensor parallelism normally kept inside one server?

  5. A 70B model needs 1,120 GB per GPU for model state with plain data parallelism. Which approach brings this down to about 17.5 GB on 64 GPUs?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

The Ultra-Scale Playbook: Training LLMs on GPU Clusters

Hugging Face (nanotron team) · 2025 · Intermediate · Free

A long, interactive guide to data, tensor, pipeline, context and expert parallelism and ZeRO, with memory and communication arithmetic and thousands of benchmark runs.

Book

How To Scale Your Model

Google DeepMind · 2025 · Advanced · Free

A free online book on the systems view of LLMs: rooflines, TPUs and GPUs, sharding, parallelism strategies and inference, with worked problems.

Book

Machine Learning Engineering Open Book

Stas Bekman · Advanced · Free

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