Distributed training: DDP, FSDP/ZeRO, tensor and pipeline parallel¶
A frontier model does not fit on one GPU and could not be trained on one in a human lifetime, so training is split across thousands. There are only a handful of things you can split — the batch, the optimiser state, the weight matrices, the layers, the tokens, the experts — and each split trades memory or time for communication. The art is choosing splits whose communication matches the speed of the wire it runs on and hides behind computation.
10,000 ft
Compute maths gives the two numbers that force distribution: training state costs about 16 bytes per parameter (a 70B model needs 1.1 TB before any activations, against 80 GB on an H100), and a frontier run needs \(10^{24}\)–\(10^{25}\) FLOPs (Llama 3 405B: \(3.8\times10^{25}\), which is ~68 days on 16,384 H100s at 40% utilisation). Distributed training is the set of techniques that turns a cluster into one very large GPU: it is why scaling laws could be followed to trillions of tokens, why mixture-of-experts models are practical, and why long-context training is possible. It builds directly on the hierarchy in how a GPU works, extended outward: NVLink inside a server is about ten times faster than the network between servers, and nearly every design decision on this page follows from that ratio. The operational side — checkpointing, failures, monitoring — continues in MLOps.
2,000 ft
Six strategies, usually combined:
- Data parallelism (DDP): every GPU holds the whole model and processes a slice of the batch; gradients are averaged with an all-reduce.
- ZeRO / FSDP: data parallelism that also shards optimiser state, gradients and weights across the data-parallel GPUs, gathering each layer only while it is used.
- Tensor parallelism (TP): split each weight matrix across GPUs; partial results are combined with an all-reduce in every layer. Needs NVLink-class bandwidth.
- Pipeline parallelism (PP): give each GPU a contiguous block of layers; stream micro-batches through the stages. Cheap communication, but idle "bubbles".
- Context (sequence) parallelism (CP): split long sequences across GPUs; exchange keys and values for attention.
- Expert parallelism (EP): place different MoE experts on different GPUs; route tokens with all-to-all.
The rule for combining them: put the most communication-hungry split (TP) on the fastest links (inside a server), the least latency-sensitive (DP/FSDP) on the slowest (across the cluster), and size micro-batches so every collective overlaps with compute.
Ground level¶
The network you are programming¶
A typical training node is a server with eight GPUs joined by NVLink switches; nodes are joined by an InfiniBand or RoCE (Ethernet) fabric. For an H100 system (How to Scale Your Model):
| Link | Bandwidth per GPU | Reaches |
|---|---|---|
| HBM | 3.35 TB/s | the GPU's own memory |
| NVLink 4 via NVSwitch | 450 GB/s each way (900 GB/s total) | the other 7 GPUs in the server |
| InfiniBand / RoCE NIC | 400 Gb/s = 50 GB/s | every other server |
| PCIe Gen5 | 128 GB/s (both directions) | host CPU and memory |
The intra-node to inter-node ratio is 9×. Blackwell's rack-scale GB200 NVL72 extends the NVLink domain to 72 GPUs, which changes how much fits inside the fast tier but not the principle. Llama 3's servers were exactly this shape: eight NVLink-connected H100s each, with 400 Gb/s per GPU between servers (Llama 3 paper, §3.3).
Collectives: the vocabulary of communication¶
Distributed training is written in a few collective operations, implemented on NVIDIA hardware by the NCCL library. For \(p\) GPUs each holding a buffer of \(M\) bytes:
| Collective | Before → after | Bytes each GPU sends (ring) | Used by |
|---|---|---|---|
| all-reduce | each has a vector → each has the sum | \(2\frac{p-1}{p}M\) | DDP gradients, TP activations |
| reduce-scatter | each has a vector → each has \(1/p\) of the sum | \(\frac{p-1}{p}M\) | ZeRO/FSDP gradients |
| all-gather | each has \(1/p\) → each has the whole | \(\frac{p-1}{p}M\) | FSDP weights, sequence parallel |
| all-to-all | each has \(p\) pieces, one per peer → swapped | \(\frac{p-1}{p}M\) | expert parallel, Ulysses |
| send/recv | point to point | \(M\) | pipeline stages |
Note that all-reduce = reduce-scatter + all-gather, which is exactly how the ring algorithm does it and why ZeRO can shard state at no extra communication. The ring algorithm's cost per GPU, \(2(p-1)M/p\), barely grows with \(p\): the Build it simulation checks it. Time for a collective is modelled as latency plus bandwidth, \(T \approx a\,\alpha + V/\beta\), where \(a\) is the number of sequential message steps (it grows with \(p\) for a ring, which is why NCCL switches to tree algorithms at scale) and \(V\) the bytes sent.
Data parallelism¶
Every GPU holds a full copy of the model, takes a different slice of the global batch, computes its own gradients, and all GPUs all-reduce the gradients (sum, then divide by \(p\)) so they take an identical optimiser step. Mathematically it is exactly single-GPU training with a \(p\)-times larger batch.
What makes it fast is overlap. PyTorch's DistributedDataParallel
(Li et al., 2020) groups gradients into buckets (25 MB by
default) and launches each bucket's all-reduce as soon as backpropagation has produced it, while
earlier layers are still computing; the paper reports near-linear scaling to 256 GPUs. For a
gradient of \(2\Psi\) bytes (BF16), the all-reduce is hidden if
and since both sides grow with \(\Psi\), what matters is the local batch: the more tokens each GPU processes per step, the more compute there is to hide the same gradient traffic behind. Gradient accumulation (several micro-batches per optimiser step, all-reducing only at the end) raises it further.
Data parallelism's limits are not communication but memory — every GPU must hold all 16 bytes per parameter — and batch size. Past a critical batch size, which McCandlish et al. (2018) relate to the gradient noise scale, a bigger batch stops reducing the number of steps needed, so adding data-parallel GPUs stops helping. Goyal et al. (2017) showed how far careful tuning goes: ResNet-50 on ImageNet with batch 8,192 on 256 GPUs in one hour, using a learning rate scaled linearly with batch size and a warm-up.
ZeRO and FSDP: stop storing everything everywhere¶
Data parallelism stores \(p\) identical copies of the weights, gradients and optimiser state. ZeRO (Rajbhandari et al., 2019) removes the redundancy in three stages. With \(\Psi\) parameters, \(N_d\) data-parallel GPUs and mixed-precision Adam (2 bytes of weight, 2 of gradient, \(K=12\) of FP32 master weight and moments):
| Stage | Sharded | Memory per GPU | 7.5B model, 64 GPUs |
|---|---|---|---|
| Plain DP | nothing | \((2+2+K)\Psi\) | 120 GB |
| ZeRO-1 (\(P_{os}\)) | optimiser state | \(4\Psi + K\Psi/N_d\) | 31.4 GB |
| ZeRO-2 (\(P_{os+g}\)) | + gradients | \(2\Psi + (2+K)\Psi/N_d\) | 16.6 GB |
| ZeRO-3 (\(P_{os+g+p}\)) | + weights | \((2+2+K)\Psi/N_d\) | 1.9 GB |
(The formulas are the paper's; the numbers are its 7.5B example, computed.) Stages 1 and 2 cost no extra communication: instead of all-reducing gradients, each GPU reduce-scatters them (getting the summed gradient for its shard), updates its shard of the optimiser state and weights, then all-gathers the updated weights — together, exactly one all-reduce's worth of traffic. Stage 3 must also gather each layer's weights before using them, in the forward and again in the backward pass, for 1.5× the traffic of plain DP.
PyTorch's Fully Sharded Data Parallel (Zhao et al., 2023) is ZeRO-3 built into the framework. Each layer (or group of layers) is a unit: its parameters live as \(1/N_d\) shards, are all-gathered just before the unit runs, freed after, and its gradients are reduce-scattered as soon as they are computed. The next unit's all-gather is prefetched while the current one computes.
Variants trade memory back for communication: keep the gathered weights between forward and backward (Llama 3 did this for its model shards, avoiding the second all-gather), or shard only within a node and replicate across nodes (hybrid sharding, HSDP), so the frequent all-gathers stay on NVLink. Because FSDP's collectives are large and per-layer, it overlaps well and needs no changes to the model code, which is why it is the default first step beyond DDP. Its limit is that each GPU must still hold one full layer, its activations, and the micro-batch's activation memory — which for long sequences and wide models is the next wall.
Activations and recomputation¶
Sharding model state does nothing for activations, the tensors saved in the forward pass for use in the backward pass. Compute maths gives the per-layer formula, \(sbh(34 + 5as/h)\) bytes in 16-bit; with FlashAttention the quadratic term disappears, leaving \(34\,sbh\). For a 70B-shaped model (\(h=8192\), 80 layers) at an 8k context and micro-batch 1 that is 2.3 GB per layer and 182 GB in total — more than the model state on 64 GPUs. Activation checkpointing (recomputation; Chen et al., 2016) stores only each layer's input (\(2sbh\) bytes) and recomputes the rest during the backward pass, for about one extra forward pass of compute; with it, the same model needs 13 GB of activations. Selective recomputation (Korthikanti et al., 2022) recomputes only the cheap-to- recompute, expensive-to-store parts (attention internals) for a few percent of extra FLOPs.
Tensor parallelism¶
When one layer's weights or activations are too large, or you need more GPUs on the same batch than data parallelism can use, split the matrices themselves. Megatron-LM (Shoeybi et al., 2019) found a split for the transformer MLP that needs only one collective. The MLP is \(Y = \operatorname{GeLU}(XA)\,B\) with \(A\in\mathbb{R}^{h\times4h}\), \(B\in\mathbb{R}^{4h\times h}\). Split \(A\) by columns and \(B\) by rows across \(t\) GPUs:
Because GeLU is element-wise, each GPU applies it to its own columns with no communication; the row-split second matmul produces partial sums, and one all-reduce adds them. Attention splits the same way, by heads: each GPU computes a subset of heads (column-split \(W_Q, W_K, W_V\)) and the row-split output projection ends in one all-reduce.
The cost is two all-reduces of the activations (\(b\cdot s\cdot h\) values) per layer in the forward pass and two in the backward — on the critical path, every layer. Worked numbers for the 70B shape (\(h = 8192\), \(s = 8192\), \(b = 1\), \(t = 8\)): each all-reduce moves a 134 MB BF16 activation, so each GPU sends \(2\cdot\frac78\cdot134 \approx 235\) MB: 0.52 ms over NVLink (450 GB/s) but 4.7 ms over InfiniBand (50 GB/s). The layer's forward matmuls on one GPU take about 3.7 ms at 50% of peak. Over NVLink the two all-reduces cost ~28% of the compute time (and can be partly overlapped); over the network they would cost 2.6× the compute. Hence the rule: tensor parallelism stays inside the NVLink domain, usually \(t \le 8\). Megatron's original paper trained an 8.3B model on 512 GPUs at 15.1 PFLOP/s, 76% scaling efficiency against a single GPU.
Sequence parallelism (Korthikanti et al., 2022) is the companion trick. Between the TP regions, LayerNorm and dropout run on the full activation, replicated on every TP rank — wasted memory. Split those regions along the sequence instead, and replace each all-reduce with a reduce-scatter (entering the sequence-parallel region) and an all-gather (leaving it). Same communication volume, and activation memory per GPU falls by \(t\).
Pipeline parallelism¶
Split the model by depth: GPU 1 runs layers 1–20, GPU 2 runs 21–40, and so on, sending only the boundary activation (\(b\cdot s\cdot h\) values) to the next stage. Communication is small and point-to-point, so pipelines can span nodes. The problem is idleness: GPU 4 has nothing to do until GPU 1–3 finish their part. Splitting the batch into \(m\) micro-batches lets stages work on different micro-batches at once (GPipe, Huang et al., 2018), but at the start and end of every step some stages wait — the bubble.
With \(p\) stages and \(m\) micro-batches, the idle fraction is
so you want \(m \gg p\); GPipe suggests \(m \ge 4p\), where the bubble is under 20%. But GPipe runs all forwards first, so each stage stores activations for all \(m\) micro-batches. 1F1B (PipeDream and Megatron's schedule) starts each micro-batch's backward as soon as possible and alternates one forward with one backward, capping in-flight activations at \(p\) micro-batches with the same bubble. The interleaved schedule of Narayanan et al. (2021) gives each GPU \(v\) non-adjacent chunks of layers, dividing the bubble by \(v\) at the cost of more communication; that paper combined TP, PP and DP to train a 1-trillion-parameter model at 502 PFLOP/s on 3,072 GPUs, 52% of peak. Zero Bubble (Qi et al., 2024) splits the backward pass into its input-gradient and weight-gradient halves — the weight gradients are not needed by anyone downstream, so they can fill the bubbles — and reports up to 23% more throughput than 1F1B at similar memory. DeepSeek's DualPipe feeds micro-batches from both ends of the pipeline and overlaps communication with computation.
Context and expert parallelism¶
Context parallelism splits a long sequence across GPUs. Each GPU holds a chunk of queries, but attention needs every key and value. Ring Attention (Liu, Zaharia and Abbeel, 2023) passes K/V blocks around a ring while each GPU runs FlashAttention-style blockwise attention on what it currently holds — the online softmax from the kernels page makes the partial results combinable — overlapping the transfer with the compute. DeepSpeed Ulysses instead uses an all-to-all to switch from "split by sequence" to "split by heads" for the attention itself, and back. Llama 3 used CP = 16 for its 131,072-token training stage.
Expert parallelism places the experts of a mixture-of-experts layer on different GPUs. A router picks experts per token, so each MoE layer becomes two all-to-all exchanges: dispatch tokens to their experts' GPUs, and combine the results back. All-to-all traffic is irregular and crosses nodes, and an overloaded expert makes everyone wait, so load balancing is a systems requirement as much as a modelling one. DeepSeek-V3 trained on 2,048 H800s with 64-way expert parallelism across 8 nodes, 16-way pipeline parallelism and ZeRO-1 data parallelism, and no tensor parallelism at all, dedicating about 20 of each GPU's 132 SMs to communication so that all-to-all could overlap with computation (DeepSeek-V3, §3.2).
Putting it together: 4-D and 5-D parallelism¶
Real runs compose these. Llama 3 405B (Llama 3 paper, Table 4) used, with the order [TP, CP, PP, DP] from innermost (fastest links) to outermost:
| GPUs | TP | CP | PP | DP | Sequence | Tokens per batch | TFLOP/s per GPU | BF16 MFU |
|---|---|---|---|---|---|---|---|---|
| 8,192 | 8 | 1 | 16 | 64 | 8,192 | 16M | 430 | 43% |
| 16,384 | 8 | 1 | 16 | 128 | 8,192 | 16M | 400 | 41% |
| 16,384 | 8 | 16 | 16 | 8 | 131,072 | 16M | 380 | 38% |
Read the table as a set of decisions. TP = 8 because a server has eight NVLink-connected GPUs. PP = 16 because 405B parameters' worth of layers (126 of them) must be divided until each stage's weights and activations fit. DP is whatever is left, and the global batch (16M tokens) was held constant as the cluster doubled, so the per-replica batch halved — and MFU fell from 43% to 41%, as the pipeline had fewer micro-batches to fill its bubble. For long context, CP took GPUs from DP to keep the batch's token count fixed. With expert parallelism added (for MoE models), this is "5-D" parallelism.
Failures are part of the design¶
At this scale, hardware fails constantly. During a 54-day snapshot of Llama 3 405B pre-training there were 466 job interruptions, 419 of them unexpected, and GPU issues caused 58.7% of the unexpected ones. Synchronous training means one failed GPU stops all 16,384, so frequent checkpointing (sharded, asynchronous), fast restart and automated detection of slow or faulty nodes are part of the parallelism strategy, not an afterthought; see MLOps and the checkpoint-interval formula in compute maths.
History¶
Distributed deep learning began on CPUs: Google's DistBelief (Dean et al., 2012) trained networks with billions of parameters on tens of thousands of CPU cores, using asynchronous SGD against parameter servers. GPUs made synchronous data parallelism the norm: Baidu popularised ring all-reduce for deep learning, Uber's Horovod (Sergeev and Del Balso, 2018) packaged it, and Goyal et al. (2017) showed large-batch synchronous SGD could scale. Model parallelism matured with the transformer: Mesh-TensorFlow (Shazeer et al., 2018) expressed sharding as named tensor dimensions, GPipe (2018) and PipeDream (2018) gave pipelines, Megatron-LM (2019) gave transformer tensor parallelism and ZeRO (2019) sharded state, the combination culminating in Megatron-Turing NLG 530B (Smith et al., 2022). GShard (Lepikhin et al., 2020) introduced expert parallelism with automatic sharding. PyTorch absorbed these ideas as FSDP (2023), tensor/pipeline APIs and TorchTitan (Liang et al., 2024); Llama 3 (2024) and DeepSeek-V3 (2024) published unusually detailed accounts of frontier-scale parallelism.
First principles¶
Every strategy is an answer to the same three questions: what is split, what must be communicated, and how often? The ratio of communication time to compute time decides where a strategy can run.
Data parallelism communicates per step, so it scales with batch. Per optimiser step it sends \(\sim2\times\) the gradient size, \(\propto\Psi\), and computes \(6\Psi\) FLOPs per token for \(B_{\text{local}}\) tokens. Ratio \(\propto 1/B_{\text{local}}\): independent of model size, and small whenever each replica processes many tokens per step. For the 256-GPU, 70B configuration in Build it the gradient reduction is about 9 GB per GPU per step — 0.18 s over InfiniBand — against a 4.4-second step (16 micro-batches of 8,192 tokens per replica at 40% MFU): easily hidden, across the slowest links.
Tensor parallelism communicates per layer, so it scales with width. Per layer it sends \(\propto b\,s\,h\) and computes \(\propto b\,s\,h^2/t\). Ratio \(\propto t/h\): it does not improve with batch size at all, only with a wider model or faster links. That is why it lives on NVLink and why its degree rarely exceeds 8.
Pipeline parallelism communicates little but idles. Per micro-batch per stage boundary it sends \(b\,s\,h\) values — small — but wastes \((p-1)/(m+p-1)\) of the time. Its cost is paid in batch size (you need \(m\gg p\) micro-batches per step) and in schedule complexity.
Sharding is free when the collective already happens. ZeRO-½ cost nothing extra because an all-reduce is a reduce-scatter followed by an all-gather; sharding the optimiser simply inserts the update between the two halves. ZeRO-3 pays 50% more traffic for weights that are gathered twice. This is the general pattern: look for communication you are already doing and attach new work to it.
Synchronous is simpler than asynchronous. Asynchronous SGD (DistBelief's Downpour) tolerates stragglers but computes gradients on stale weights; at large scale the field chose synchronous training plus engineering for reliability, because it makes training deterministic in its mathematics and easy to reason about.
The maths¶
Derivation: the ring all-reduce is bandwidth-optimal
Split each GPU's \(M\)-byte buffer into \(p\) chunks of \(M/p\). Reduce-scatter: in step \(k = 0,\dots,p-2\), GPU \(r\) sends chunk \((r-k) \bmod p\) to GPU \(r+1\), which adds it to its own copy of that chunk. After \(p-1\) steps, GPU \(r\) holds the complete sum for chunk \((r+1)\bmod p\). All-gather: \(p-1\) more steps circulate the completed chunks. Each step sends \(M/p\) bytes per GPU, so the total is
A lower bound: every GPU must receive enough information to know the full sum, at least \((p-1)M/p\) bytes from others for the reduction plus the same for distribution, so no algorithm sends asymptotically less. The \(2(p-1)\alpha\) latency term grows with \(p\), which is why NCCL uses tree or hierarchical algorithms for small messages and large \(p\).
Derivation: the pipeline bubble
With \(p\) stages, each micro-batch taking \(t_f\) forward and \(t_b\) backward per stage, the first stage's last forward starts at \((m-1)t_f\) and reaches the last stage after another \((p-1)t_f\); the backward pass mirrors this. The step takes
of which each stage is busy \(m(t_f+t_b)\). Idle fraction: \(\frac{(p-1)}{m+p-1}\). Megatron reports it relative to ideal compute instead, \(\frac{p-1}{m}\). With \(v\) interleaved chunks per GPU, the fill and drain each shrink to \((p-1)(t_f+t_b)/v\), giving \(\frac{p-1}{v\,m}\). The Build it schedule simulation in the figure reproduces \(T=27\) for \(p=4\), \(m=6\), \(t_f=1\), \(t_b=2\).
Tensor-parallel traffic. Per transformer layer, with micro-batch \(b\), sequence \(s\), width \(h\) and \(t\)-way TP in 16-bit: forward and backward each perform 2 all-reduces of \(2bsh\) bytes, so per GPU per layer
ZeRO memory. For \(\Psi\) parameters, \(N_d\) data-parallel ranks and \(K\) bytes of optimiser state per parameter (12 for mixed-precision Adam):
With TP degree \(t\) and PP degree \(p\), replace \(\Psi\) by \(\Psi/(tp)\), the parameters held by one model-parallel rank.
Build it¶
First, a ring all-reduce among simulated workers, checking both correctness and the \(2(p-1)M/p\) traffic law:
import numpy as np
def ring_allreduce(bufs):
"""Ring all-reduce over p workers: reduce-scatter, then all-gather.
Returns every worker's result and the number of elements each one sent."""
p = len(bufs)
chunks = [np.array_split(b.astype(float), p) for b in bufs] # p chunks each
sent = 0
for step in range(p - 1): # reduce-scatter
msgs = [chunks[r][(r - step) % p].copy() for r in range(p)]
for r in range(p): # worker r receives from r-1
c = (r - 1 - step) % p
chunks[r][c] += msgs[(r - 1) % p]
sent += len(msgs[0])
for step in range(p - 1): # all-gather the reduced chunks
msgs = [chunks[r][(r + 1 - step) % p].copy() for r in range(p)]
for r in range(p):
chunks[r][(r - step) % p] = msgs[(r - 1) % p]
sent += len(msgs[0])
return [np.concatenate(c) for c in chunks], sent
rng = np.random.default_rng(0)
M = 1_200_000 # gradient elements per worker
for p in (2, 4, 8, 16):
grads = [rng.standard_normal(M) for _ in range(p)]
out, sent = ring_allreduce(grads)
ok = all(np.allclose(o, sum(grads)) for o in out)
print(f"p={p:2d}: correct={ok}, each worker sent {sent/M:.3f} x M "
f"(formula 2(p-1)/p = {2*(p-1)/p:.3f})")
p= 2: correct=True, each worker sent 1.000 x M (formula 2(p-1)/p = 1.000)
p= 4: correct=True, each worker sent 1.500 x M (formula 2(p-1)/p = 1.500)
p= 8: correct=True, each worker sent 1.750 x M (formula 2(p-1)/p = 1.750)
p=16: correct=True, each worker sent 1.875 x M (formula 2(p-1)/p = 1.875)
Second, a planner for a 70B dense model (Llama-3-70B shape) at an 8,192-token context: memory per GPU and pipeline bubble for different combinations. Activation memory assumes FlashAttention and sequence parallelism (so the TP degree divides it), and the 1F1B fact that the first stage holds \(p\) micro-batches of \(L/p\) layers.
# Per-GPU memory and pipeline bubble for a 70B dense transformer (Llama-3-70B shape)
P, L, h, s, b = 70.6e9, 80, 8192, 8192, 1 # params, layers, width, seq, micro-batch
GB = 1e9
def plan(n_gpu, tp=1, pp=1, zero=0, recompute=False, m=None):
dp = n_gpu // (tp * pp)
psi = P / (tp * pp) # params held by one model-parallel rank
w, g, opt = 2 * psi, 2 * psi, 12 * psi # BF16 weight, BF16 grad, FP32 master+m+v
if zero >= 1: opt /= dp # ZeRO-1: shard optimiser state
if zero >= 2: g /= dp # ZeRO-2: + gradients
if zero >= 3: w /= dp # ZeRO-3 / FSDP: + weights
layer_act = s * b * h * 34 / tp # bytes, FlashAttention + sequence parallel
# 1F1B: the first stage holds pp micro-batches of L/pp layers = L layers' worth
act = L * (2 * s * b * h / tp) + layer_act if recompute else L * layer_act
m = m or 4 * pp
bubble = (pp - 1) / (m + pp - 1)
return dp, (w + g + opt) / GB, act / GB, bubble
print(f"{'config':38s}{'DP':>4s}{'states':>9s}{'activ.':>9s}{'total':>9s}{'bubble':>8s}")
for n, kw in [(8, dict()),
(64, dict(zero=3)),
(64, dict(zero=3, recompute=True)),
(64, dict(tp=8)),
(64, dict(tp=8, zero=1)),
(256, dict(tp=8, pp=4, zero=1)),
(256, dict(tp=8, pp=4, zero=1, m=32))]:
dp, st, ac, bub = plan(n, **kw)
name = f"{n} GPUs " + ", ".join(f"{k}={v}" for k, v in kw.items())
print(f"{name:38s}{dp:4d}{st:8.1f}G{ac:8.1f}G{st + ac:8.1f}G{bub:8.1%}")
config DP states activ. total bubble
8 GPUs 8 1129.6G 182.5G 1312.1G 0.0%
64 GPUs zero=3 64 17.6G 182.5G 200.2G 0.0%
64 GPUs zero=3, recompute=True 64 17.6G 13.0G 30.7G 0.0%
64 GPUs tp=8 8 141.2G 22.8G 164.0G 0.0%
64 GPUs tp=8, zero=1 8 48.5G 22.8G 71.4G 0.0%
256 GPUs tp=8, pp=4, zero=1 8 12.1G 22.8G 35.0G 15.8%
256 GPUs tp=8, pp=4, zero=1, m=32 8 12.1G 22.8G 35.0G 8.6%
Read it top to bottom as a design session. Plain DP needs 1.3 TB per GPU: impossible. FSDP over 64 GPUs fixes the state (17.6 GB) but not the 182 GB of activations; adding recomputation brings the total to 31 GB, which fits an 80 GB H100 — FSDP plus checkpointing is a complete answer at this scale. TP = 8 divides both state and activations by 8 but on its own leaves 141 GB of state; with ZeRO-1 over the remaining 8-way DP it fits at 71 GB, tightly. Adding PP = 4 on 256 GPUs brings everything to 35 GB, at the price of a pipeline bubble: 15.8% of the time with 16 micro-batches per step, 8.6% with 32.
Things to try
- Add context parallelism to
plan: CP divides sequence length for activations. At \(s = 131{,}072\), what CP degree keeps the TP=8, PP=16 configuration under 80 GB? - Add the communication time per step for each configuration (DP gradients over 50 GB/s, TP all-reduces over 450 GB/s, using the formulas in The maths) and the compute time at 40% MFU. Which configuration is fastest per token, not just smallest?
- Modify
ring_allreduceinto a two-level (hierarchical) all-reduce: reduce within groups of 8 ("a node"), all-reduce across group leaders, broadcast back. Count the bytes on the slow tier. - Implement the 1F1B and interleaved schedules as event simulations and measure the bubble and the peak number of in-flight micro-batches per stage.
- Read picotron, a minimal implementation of 4-D parallelism, and map each of its files to a section of this page.
In practice¶
- Climb the ladder only as far as needed. Single GPU → DDP (fits in memory?) → FSDP with activation checkpointing (fits up to tens of billions of parameters) → add TP inside a node (very wide models, or to cut activation memory) → add PP across nodes (hundreds of billions) → CP for long context, EP for MoE. Each rung adds failure modes.
- Topology first. TP within the NVLink domain; PP across nodes; DP/FSDP outermost. Use hybrid sharding (HSDP) when the cluster network is slow relative to compute.
- Keep the global batch sensible. Adding DP ranks increases the batch; past the critical batch size it wastes compute. When scaling out at a fixed batch, the per-GPU micro-batch count falls and pipeline bubbles grow — exactly what Llama 3's MFU drop shows.
- Numerics across GPUs. Reduce gradients in FP32 (or BF16 with care); summation order now depends on the topology, so results are not bit-identical across cluster sizes.
- Use the libraries. PyTorch FSDP2 and TorchTitan, Megatron-Core, DeepSpeed and JAX's sharding APIs implement all of this; the Ultra-Scale Playbook benchmarks the combinations on real clusters.
Common misconceptions¶
\"Data parallelism is limited by communication.\"
For large models its gradient all-reduce overlaps with the backward pass and is small relative to compute whenever the local batch is reasonable. Its real limits are memory (every GPU holds the full training state, unless sharded) and the critical batch size.
\"FSDP is a form of model parallelism.\"
It shards the storage of the model, but every GPU still executes every layer on its own data — it is data parallelism with sharded state. Tensor and pipeline parallelism split the computation of a single example across GPUs.
\"More GPUs, proportionally faster.\"
Only while the batch can grow (data parallel), the pipeline has enough micro-batches, and the communication still hides. Past those points, extra GPUs mostly add bubbles, exposed communication and failure rate. Llama 3's MFU fell from 43% to 41% when doubling from 8,192 to 16,384 GPUs at a fixed global batch.
Check yourself¶
What does each GPU send in a ring all-reduce of 4 GB over 8 GPUs, and how long does it take at 50 GB/s?
\(2\cdot\frac{7}{8}\cdot4 = 7\) GB, so about 0.14 s plus latency. Note it hardly depends on the number of GPUs: with 1,024 it would be 7.99 GB.
Why are ZeRO stages 1 and 2 free in communication, but stage 3 is not?
Plain data parallelism already all-reduces gradients, and an all-reduce is a reduce-scatter followed by an all-gather. Stages 1–2 reduce-scatter gradients, update only the local shard of the optimiser state, and all-gather the updated weights: the same traffic. Stage 3 also discards the weights between uses, so it must all-gather each layer again before the forward and the backward: 1.5× the traffic.
In Megatron's MLP, why split the first matrix by columns and the second by rows rather than the other way round?
Column-splitting \(A\) gives each GPU complete columns of \(XA\), so the element-wise GeLU can be applied locally. A row split of \(A\) would give partial sums, requiring an all-reduce before the non-linearity. Row-splitting \(B\) then consumes those local columns directly and produces partial sums that need one all-reduce. One collective per MLP instead of two.
A pipeline has 8 stages. How many micro-batches per step keep the bubble under 10%?
\((p-1)/(m+p-1) < 0.1 \Rightarrow 7 < 0.1(m+7) \Rightarrow m > 63\). So at least 64 micro-batches per step, which with micro-batch size 1 and 8k tokens is a 0.5M-token batch per pipeline replica. Interleaving with \(v=4\) chunks cuts the requirement roughly fourfold.
Why does tensor parallelism stay inside a server, while data parallelism can span the whole cluster?
TP's communication is per layer and proportional to activations, and its ratio to compute scales like \(t/h\), independent of batch: it needs the fastest links. DP's communication is per step and its ratio to compute falls with the local batch, so it tolerates 9× slower inter-node links and their latency.
Hard: why did DeepSeek-V3 avoid tensor parallelism entirely, and what did it give up?
With MoE, most parameters are in experts, which expert parallelism already spreads across GPUs; pipeline parallelism handles depth and ZeRO-1 the optimiser state, so per-GPU memory fit without TP. Avoiding TP removes per-layer all-reduces from the critical path, which matters on their H800 cluster, where (per the paper) NVLink offered 160 GB/s, only about 3.2× the 50 GB/s of InfiniBand. The cost is heavier all-to-all traffic across nodes, which they hid by overlapping it with computation (DualPipe) and by dedicating ~20 SMs per GPU to communication.
Hard: a team doubles its cluster from 2,048 to 4,096 GPUs but keeps the global batch fixed. Predict what happens to MFU and why.
DP doubles, so each replica gets half as many micro-batches per step. With pipeline parallelism the bubble \((p-1)/(m+p-1)\) grows as \(m\) halves; each GPU's matmuls may also get smaller (less arithmetic intensity) and the fixed communication is amortised over less compute. MFU drops, as in Llama 3's 43% → 41% when going from 8,192 to 16,384 GPUs at 16M tokens per batch. Tokens per second still rise, but less than 2×.
Go deeper¶
Papers
- ZeRO: Memory Optimizations Toward Training Trillion Parameter Models — Rajbhandari et al., 2019. Sections 5 and 7: the three stages and their exact communication cost.
- Megatron-LM — Shoeybi et al., 2019. Section 3 is the whole of tensor parallelism in two pages.
- Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM — Narayanan et al., 2021. How TP, PP and DP compose; interleaved schedules; the best paper on choosing a configuration.
- GPipe — Huang et al., 2018. Micro-batched pipelines and the bubble.
- Reducing Activation Recomputation in Large Transformer Models — Korthikanti et al., 2022. Sequence parallelism and selective recomputation, with the activation-memory derivation.
- PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel — Zhao et al., 2023. ZeRO-3 as engineered into PyTorch: prefetching, rate limiting, hybrid sharding.
- PyTorch Distributed: Experiences on Accelerating Data Parallel Training — Li et al., 2020. Gradient bucketing and overlap: why DDP scales.
- Zero Bubble Pipeline Parallelism — Qi et al., 2024. Splitting the backward pass to fill the bubble.
- Ring Attention with Blockwise Transformers — Liu, Zaharia and Abbeel, 2023. Context parallelism via the online softmax.
- The Llama 3 Herd of Models — Meta, 2024. §3.3: 4-D parallelism, network topology, reliability at 16k GPUs.
- DeepSeek-V3 Technical Report — DeepSeek-AI, 2024. §3.2: DualPipe, expert parallelism and communication kernels without TP.
Books, courses and articles
- The Ultra-Scale Playbook — Hugging Face, 2025. Every strategy on this page, explained and benchmarked on up to 512 GPUs. The best single resource.
- How to Scale Your Model — Austin et al., Google DeepMind. The sharding and training chapters do this page's arithmetic rigorously, TPU-first.
- How to Train Really Large Models on Many GPUs? — Lilian Weng, 2021. A clear survey of the strategies with diagrams.
- Data-Parallel Distributed Training of Deep Learning Models — Simon Boehm. DDP, gradient bucketing and ZeRO built up from first principles.
- Ultimate Guide To Scaling ML Models — Aleksa Gordić. A video walk through Megatron, ZeRO and mixed precision papers.
- Stanford CS336 (2025) — Stanford Online. The parallelism lectures implement collectives and FSDP from scratch.
Code
- picotron — Hugging Face. 4-D parallelism in a few files, written for learning.
- TorchTitan — PyTorch. Production-grade FSDP2, TP, PP and CP composed in native PyTorch.
- Megatron-LM — NVIDIA. The reference implementation of TP, PP, SP, CP and EP at scale.
- NCCL documentation — NVIDIA. The collectives, their algorithms and the environment variables you will end up tuning.
Where this leads¶
- MLOps — checkpointing, failure recovery and monitoring for runs that span thousands of GPUs.
- Compute maths — turn a parallelism plan into GPU-hours and dollars.
- Mixture of experts — the architecture that expert parallelism exists for.
- Long context — why context parallelism matters, from the modelling side.
- Serving LLMs — tensor and pipeline parallelism reappear at inference time, with different trade-offs.