Skip to content
LearnAI
PART 3 · TRAINING LLMS/ Making training work

3.4Distributed training: data, tensor, pipeline & expert parallelism

A frontier model doesn't fit on one GPU, or even a hundred. Here are the four ways to split the work, and what each costs in memory and communication.

⏱ 15 minAdvanced

Two walls: memory and time

Training a model needs more than its weights in memory. In standard mixed-precisionMixed-precision trainingDoing most math in a low-precision format (FP16, BF16 or FP8) while keeping a high-precision (FP32) master copy of the weights and sensitive operations. training with AdamAdam / AdamWAn optimizer that combines momentum with a per-parameter adaptive step size. AdamW decouples weight decay from the update., every parameter carries:

  • 2 bytes: the BF16 (or FP16) working copy of the weight,
  • 2 bytes: its BF16 gradient,
  • 4 bytes: an FP32 master copy of the weight,
  • 4 + 4 bytes: Adam’s two moment estimates in FP32.

That’s 16 bytes per parameter, the breakdown used in the ZeRO paper, before counting activations (the intermediate results saved during the forward pass for use in backpropagation). A 70B-parameter model needs about 1.1 TB just for this state. A top GPU like the H100 has 80 GB. You’d need at least 14 GPUs simply to hold the model, and that’s before any computation.

The second wall is time. Llama 3.1 405B took about 3.8×10253.8 \times 10^{25} FLOPs to train (see scaling laws). Even at a very optimistic 4×10144 \times 10^{14} useful FLOPs per second per GPU, one GPU would need about 3,000 years. Meta used up to 16,384 H100 GPUs. So the question isn’t whether to split the work, but how.

ANALOGY· Building a skyscraper with many crews

You could give each crew a full set of blueprints and its own building site, then compare notes at the end of each day (data parallelism). Or have every crew work on the same floor at once, each building one section of each wall, constantly shouting measurements to each other (tensor parallelism). Or run an assembly line where crew 1 pours foundations, crew 2 frames walls and so on, passing each unit along (pipeline parallelism). Or have specialist crews (electricians, plumbers) and route each job to the right specialist (expert parallelism).

The blueprints and tools are the weights and optimizer states; the buildings are training examples; the shouting is communication between GPUs. Every scheme saves something and pays for it with more coordination.

Data parallelism and its sharded cousins

Data parallelismData parallelismEvery GPU holds the whole model and processes a different slice of the batch; gradients are averaged with an all-reduce. (DP) is the simplest: every GPU holds a full replica of the model, takes a different slice of the global batch, and computes gradients on it. Before the optimizer step, GPUs average their gradients with an all-reduce, a collective operation after which every GPU holds the same sum. With a ring all-reduce each GPU sends and receives about twice the gradient size per step, independent of the number of GPUs, and the communication can overlap with the backward pass. DP scales throughput beautifully. But it does nothing for memory: each GPU still needs 16 bytes per parameter.

ZeROZeRO / FSDPData parallelism that shards optimizer states, gradients and (at stage 3) the weights themselves across GPUs, gathering them only when needed. (Rajbhandari et al., 2019) noticed that this replication is wasteful. Every GPU stores the same optimizer states and runs the same update. So shard them:

  • ZeRO-1 shards the optimizer states (the 12-byte part): each GPU updates only its 1/N slice of the parameters, then the new weights are all-gathered.
  • ZeRO-2 also shards gradients: gradients are reduce-scattered so each GPU only receives the summed gradients for its own slice.
  • ZeRO-3 also shards the weights. Before a layer runs, GPUs all-gather its full weights, use them, and discard them. PyTorch’s FSDP (Fully Sharded Data Parallel) implements the same idea.

ZeRO-1 and 2 communicate about as much as plain DP; ZeRO-3 about 1.5× as much, in exchange for dividing all the training state by the number of GPUs.

INTERACTIVEParallelism visualizer
GPU 0L1L2L3L4dataGPU 1L1L2L3L4dataGPU 2L1L2L3L4dataGPU 3L1L2L3L4dataGPU 4L1L2L3L4dataGPU 5L1L2L3L4dataGPU 6L1L2L3L4dataGPU 7L1L2L3L4data

Rows L1–L4: the part of each layer’s weights a GPU holds. Bottom strip: its share of the global batch (a solid grey bar means it processes the whole batch together with the others). Red links: who talks to whom (a red frame around all GPUs means everyone exchanges with everyone).

Every GPU holds a full copy of everything and sees a different slice of the batch. Simple and fast, but each GPU needs ~16 bytes per parameter.

Sends: gradients (all-reduce)
Pattern: ring all-reduce
How often: once per step, overlapped with backward
Memory per GPU (weights + grads + Adam; activations excluded)
■ BF16 weights 14.0 GB■ BF16 grads 14.0 GB■ FP32 master + Adam m, v 84.0 GB| 80 GB GPU
per GPU
112 GB ✗ too big
bytes / param / GPU
16.00
Pick a strategy and watch how a 4-layer model's weights (rows L1–L4) and the batch (bottom strip) are split across 8 GPUs. Drag the model size to see when the per-GPU training state stops fitting on an 80 GB GPU.

Try this: set the model to 7B. Plain DP needs 112 GB per GPU, which doesn’t fit. ZeRO-1 brings it to 38.5 GB; ZeRO-3, tensor or pipeline parallelism bring it to 14 GB. Now push to 70B: even full 8-way sharding needs 140 GB per GPU, so you need more GPUs and a combination of strategies.

Tensor parallelism: split the matrices

Tensor parallelismTensor parallelismSplitting individual weight matrices across GPUs so each computes part of every layer; requires very fast interconnects. (TP), popularized by NVIDIA’s Megatron-LM, splits individual weight matrices. Take a Transformer MLP: Y=GeLU(XA) BY = \text{GeLU}(X A)\, B. Split AA by columns across GPUs; each GPU computes its own slice of XAXA and applies GeLU locally (it’s elementwise, so no communication is needed). Split BB by rows; each GPU multiplies its slice and produces a partial sum of YY. One all-reduce adds the partial sums. Attention is split the same way, by heads.

All GPUs process the same tokens at the same moment, so TP divides both weight memory and per-token compute. The price is two all-reduces of activations per layer in the forward pass, and two more in the backward pass, right in the critical path. That’s only fast enough over NVLink-class links inside a single server, so TP is usually limited to the 8 GPUs of one node.

Pipeline parallelism: split the layers

Pipeline parallelismPipeline parallelismGiving each GPU a contiguous block of layers and streaming micro-batches through them like an assembly line. (PP) gives each GPU a contiguous block of layers: GPU 0 has layers 1–10, GPU 1 has layers 11–20, and so on. Communication is cheap: each stage just sends its output activations to the next stage (and gradients back). That works fine across servers.

The catch is idle time. With one batch, stage 2 waits while stage 1 computes, then stage 1 waits while the rest of the pipeline finishes forward and backward. The fix is to cut the batch into micro-batches and stream them through like an assembly line. Startup and wind-down still leave gaps, called the pipeline bubble.

INTERACTIVEPipeline bubble: GPipe vs 1F1B
Schedule
GPU 0GPU 1GPU 2GPU 3time → (filled = forward, outlined = backward, which takes 2× as long; grey gaps = idle “bubble”)
step time (units)
21
bubble (idle share)
42.9%
formula (P−1)/(M+P−1)
42.9%
peak stashed activations, GPU 0
4 micro-batches (1F1B: 4)
Each row is a GPU (pipeline stage). Filled blocks are forward passes, outlined blocks are backward passes (2× longer). Grey gaps are idle time. Increase the micro-batches and watch the bubble shrink; switch schedules and compare the peak activation memory.

GPipe runs all forward passes, then all backward passes. 1F1B (one-forward-one-backward, from PipeDream and Megatron) starts each micro-batch’s backward pass as soon as possible. In this simple model both have the same bubble, (P−1)/(M+P−1)(P-1)/(M+P-1), but 1F1B frees each micro-batch’s activations much sooner: the first stage holds at most PP micro-batches in flight instead of all MM. That’s why 1F1B (and refinements such as interleaved stages and DeepSeek’s DualPipe, which also overlaps computation with communication) is the standard.

Expert parallelism: split the experts

In a Mixture-of-Experts model, each token is routed to a few of many experts. Expert parallelismExpert parallelismPlacing different experts of a Mixture-of-Experts layer on different GPUs and sending each token to the GPU holding its chosen expert (an all-to-all exchange). (EP) places different experts on different GPUs. After the router decides, an all-to-all exchange ships every token to the GPU holding its chosen expert, and a second all-to-all brings the results back. Attention and other shared layers use ordinary data parallelism. EP is what makes trillion-parameter MoE models trainable, but the all-to-all traffic is heavy and uneven routing can leave some GPUs overloaded, so load balancing matters.

Choosing a combination

How do engineers pick the degrees for each kind of parallelism? A rough recipe, given a cluster of 8-GPU servers:

  1. Start from memory. If the model plus optimizer state fits on one GPU with ZeRO-1 or FSDP sharding, plain data parallelism with sharding is simplest and usually fastest. Many models up to tens of billions of parameters are trained this way.
  2. Add tensor parallelism inside the node when single layers or their activations get too large (very wide models, long sequences). Keep TP at 8 or below so it stays on NVLink.
  3. Add pipeline parallelism across nodes when the model still doesn’t fit. Pick enough micro-batches to keep the bubble small, which in turn constrains the global batch size.
  4. Add expert parallelism for MoE models, sized so each GPU holds a manageable number of experts and the all-to-all traffic stays within fast links where possible.
  5. Fill the remaining GPUs with data parallelism. Total GPUs = DP × TP × PP (with EP and context parallelism carved out of these dimensions).

The constraints pull against each other: the global batch size can’t grow without limit (too large a batch hurts optimization), so more DP means fewer micro-batches for PP, which means a bigger bubble. Finding a good configuration is a real optimization problem, and teams measure the result as MFU (model FLOPs utilization: useful FLOPs achieved divided by the hardware’s peak). Well-tuned large runs typically report something like 35–45% MFU on BF16 hardware; the rest is lost to communication, bubbles, memory traffic and stragglers.

Two more memory tricks complete the toolkit. Activation checkpointing (recomputation) stores only some activations and recomputes the rest during the backward pass, trading about a third more compute for much less memory. And lower precision shrinks everything; that’s the next lesson.

MATH CORNER · optionalMemory and bubble arithmetic

Training state per GPU. Let Ψ\Psi be the parameter count and NdN_d the data-parallel degree (bytes, mixed precision with Adam):

schemeweightsgradsoptimizer (FP32 master + mm + vv)total
DP2Ψ2\Psi2Ψ2\Psi12Ψ12\Psi16Ψ16\Psi
ZeRO-12Ψ2\Psi2Ψ2\Psi12Ψ/Nd12\Psi / N_d4Ψ+12Ψ/Nd4\Psi + 12\Psi/N_d
ZeRO-22Ψ2\Psi2Ψ/Nd2\Psi/N_d12Ψ/Nd12\Psi / N_d2Ψ+14Ψ/Nd2\Psi + 14\Psi/N_d
ZeRO-3 / FSDP2Ψ/Nd2\Psi/N_d2Ψ/Nd2\Psi/N_d12Ψ/Nd12\Psi / N_d16Ψ/Nd16\Psi/N_d

Worked example: Ψ=7×109\Psi = 7 \times 10^9, Nd=8N_d = 8. DP: 16×7=11216 \times 7 = 112 GB. ZeRO-1: 28+84/8=38.528 + 84/8 = 38.5 GB. ZeRO-2: 14+98/8=26.2514 + 98/8 = 26.25 GB. ZeRO-3: 112/8=14112/8 = 14 GB. (The ZeRO paper’s example: a 7.5B model needs 120 GB per GPU with plain DP.)

Ring all-reduce. For a message of SS bytes on KK GPUs, each GPU sends 2K−1KS2\frac{K-1}{K} S bytes. With 7B BF16 gradients (S=14S = 14 GB) and K=8K = 8, that’s about 24.5 GB per GPU per step, which is why the all-reduce is overlapped with the backward pass.

Pipeline bubble. With PP stages, MM micro-batches and forward/backward times tf,tbt_f, t_b, an ideal step takes (M+P−1)(tf+tb)(M + P - 1)(t_f + t_b) while each stage is busy for M(tf+tb)M(t_f + t_b), so

bubble fraction=P−1M+P−1.\text{bubble fraction} = \frac{P - 1}{M + P - 1}.

P=4P = 4: with M=4M = 4 the bubble is 3/7≈43%3/7 \approx 43\%; with M=16M = 16 it’s 3/19≈16%3/19 \approx 16\%; with M=64M = 64, about 4.5%4.5\%. More micro-batches help, but each extra in-flight micro-batch costs activation memory, which is what 1F1B keeps in check.

In code

With PyTorch, FSDP-style sharding is a wrapper around the model (shown here with the fully_shard API from FSDP2), launched with one process per GPU:

# launch: torchrun --nproc_per_node=8 train.py
import torch, torch.distributed as dist
from torch.distributed.fsdp import fully_shard   # FSDP2 API (PyTorch ≥ 2.6)

dist.init_process_group("nccl")
torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count())

model = MyTransformer().cuda()
for block in model.blocks:          # shard each Transformer block separately,
    fully_shard(block)              # so only one block's weights are gathered at a time
fully_shard(model)

opt = torch.optim.AdamW(model.parameters(), lr=3e-4)
for batch in loader:                # each rank gets a different slice of data
    loss = model(batch).loss
    loss.backward()                 # grads are reduce-scattered to their owners
    opt.step(); opt.zero_grad()     # each rank updates only its own shard
COMMON MISCONCEPTIONS
  • “Adding GPUs with data parallelism lets you train a bigger model.” Plain DP replicates everything, so the largest trainable model is set by one GPU’s memory. You need sharding (ZeRO/FSDP) or model parallelism to go bigger.
  • “Tensor parallelism scales to thousands of GPUs.” Its frequent all-reduces sit in the critical path of every layer, so it’s practical only over very fast links, typically within one 8-GPU node.
  • “Pipeline parallelism has no overhead because communication is cheap.” Its cost is idle time (the bubble) and the activation memory of micro-batches in flight, not bandwidth.
  • “The model weights are the main memory cost.” In mixed-precision Adam training, the weights’ BF16 copy is just 2 of the ~16 bytes per parameter; optimizer state dominates, and activations can exceed all of it at long sequence lengths.

Check your understanding

0/5 answered
  1. Q1.How much memory does the training state of a 13B-parameter model take with plain mixed-precision Adam (no sharding)?

  2. Q2.Which strategy shards the optimizer states but still keeps a full copy of the BF16 weights on every GPU?

  3. Q3.Why is tensor parallelism usually kept within a single server?

  4. Q4.A pipeline has 8 stages. Roughly what bubble fraction do you get with 8 micro-batches?

  5. Q5.What communication pattern does expert parallelism rely on?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.