Skip to content
ImagineWorld

Distributed Training

node_idnode-book_building-frontier-llm-from-scratch_chapter-19-distributed-training
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num19
chapter_titleDistributed Training
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

A 671-billion-parameter model does not fit on a single GPU — not its weights, certainly not its weights plus gradients plus optimizer state plus activations. Training it means splitting the work across thousands of GPUs and coordinating their communication, and there are four fundamentally different ways to split, each cutting along a different axis. Real systems combine them. This chapter explains the four parallelism dimensions, then shows how DeepSeek-V3 wove them together with its open-sourced training stack — the part of frontier engineering most invisible from the outside and most decisive in practice.

The simplest split is data parallelism (DP): replicate the whole model on every GPU, give each a different slice of the batch, and average the gradients across GPUs (an all-reduce) before each step. It is the universal baseline, but it requires the entire model, gradients, and optimizer state to fit on every GPU — which a large model cannot. ZeRO (and its PyTorch embodiment, FSDP, Fully Sharded Data Parallel) fixes this by sharding those tensors across the data-parallel GPUs: each GPU holds only a slice of the optimizer state, gradients, and parameters, gathering the full parameters for a layer only momentarily when that layer runs. This keeps the convenience of data parallelism while removing its memory ceiling, and in PyTorch it is nearly a one-line wrapper:

from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
model = FSDP(model) # params, grads, optimizer state sharded across GPUs
# the training loop of Chapter 17 is otherwise unchanged

Python — FSDP shards the model across data-parallel GPUs

Tensor parallelism (TP) splits the math within a layer. A large matrix multiply is partitioned column-wise or row-wise across several GPUs, each computing a slice of the output, with a communication step to stitch the slices together. Pioneered by Megatron-LM, TP lets a single layer be larger than one GPU’s memory, but it communicates activations at every layer, so the GPUs must be tightly connected — TP is normally confined to the GPUs within a single node, where bandwidth (NVLink) is highest.

Pipeline parallelism (PP) splits the model by depth: the first group of layers lives on one set of GPUs, the next group on another, and activations pass from stage to stage like a factory line. Its weakness is the bubble — while the first stage works on the first micro-batch, later stages sit idle, and vice versa, wasting GPU time. The standard remedy splits each batch into many micro-batches to keep all stages busy; DeepSeek-V3 goes further with DualPipe, a bidirectional schedule that overlaps the forward and backward passes of different micro-batches so the pipeline bubble nearly vanishes and communication hides behind computation. Figure 19.1 shows the idea.

Pipeline schedule: naive (top) vs. overlapped (bottom)
stage 1 ▓▓ ▓▓ ░░ ░░
stage 2 ▓▓ ▓▓ ░░ grey/empty = idle (bubble)
stage 3 ▓▓ ▓▓
stage 1 ▓▓ ░░ ▓▓ ░░ ▓▓
stage 2 ▓▓ ▓▓ ░░ ▓▓ ░░ dark = forward, grey = backward;
stage 3 ▓▓ ░░ ▓▓ ░░ ▓▓ interleaved to fill the bubble
time →

Figure 19.1. Pipeline bubbles. A naive pipeline leaves later stages idle while the first fills up (top, grey); DualPipe interleaves forward and backward passes of different micro-batches across stages (bottom) so GPUs stay busy and communication overlaps computation.

Expert parallelism (EP) is specific to MoE (Chapter 11): the experts are distributed across GPUs, and each token is routed to whichever GPUs hold its chosen experts via an all-to-all dispatch, then the results are gathered by an all-to-all combine. This communication can dominate the layer, so DeepSeek built DeepEP, a library of optimized all-to-all kernels for exactly this pattern. A second problem is that real token distributions are uneven — some experts attract more tokens than others, overloading their GPUs — which DeepSeek addresses with EPLB (Expert-Parallel Load Balancer), which can replicate hot experts and rearrange placement to even out the load. Together these make the clean per-expert loop of Chapter 11 efficient across hundreds of GPUs.

No single dimension suffices; frontier runs compose them into “4D” parallelism. A common arrangement uses tensor parallelism within a node, pipeline parallelism across a handful of nodes, expert parallelism for the MoE layers, and data parallelism (with ZeRO/FSDP sharding) across the rest — chosen so that the heaviest communication stays on the fastest links. Table 19.1 summarizes the four dimensions and when each is used; the art is matching the split to the hardware topology so that compute and communication overlap rather than wait on each other.

DimensionWhat is splitWhat is communicatedUsed when
Data (DP)the batch (model replicated)gradients (all-reduce)always — the baseline
ZeRO / FSDPoptimizer, grads, params (sharded)params (gather), grads (scatter)states do not fit per GPU
Tensor (TP)matmuls within a layeractivations, every layerwithin a node (NVLink)
Pipeline (PP)layers across devicesactivations at stage edgesdeep models, across nodes
Expert (EP)MoE experts across devicestokens (all-to-all)MoE models

Table 19.1 — The four parallelism dimensions

Code reference — deepseek-ai/DualPipe · deepseek-ai/DeepEP · deepseek-ai/EPLB · NVIDIA/Megatron-LM · PyTorch FSDP

DeepSeek open-sourced the pieces that are usually proprietary: DualPipe (the overlapping pipeline schedule), DeepEP (expert-parallel all-to-all), and EPLB (expert load balancing). Megatron-LM is the reference for tensor and pipeline parallelism, and PyTorch’s FSDP for sharded data parallelism. These repositories are the clearest available window into how a frontier model is actually trained.

Splitting the model across thousands of GPUs is only part of the infrastructure. Those GPUs must be fed data fast enough to stay busy, their efficiency must be measured, and the whole run has a price tag that determines whether it is viable at all. That supporting infrastructure — and the economics it implies — is the subject of the next chapter.

19.6 Worked Example: Sharding a Model with FSDP

Section titled “19.6 Worked Example: Sharding a Model with FSDP”

The distribution strategies of this chapter reduce, in PyTorch, to wrapping the model. Fully Sharded Data Parallel shards parameters, gradients, and optimizer state across GPUs (the ZeRO-3 idea), wrapping each transformer block so only one block’s full parameters are gathered at a time:

from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp import MixedPrecision
policy = MixedPrecision(param_dtype=torch.bfloat16,
reduce_dtype=torch.float32) # bf16 compute, fp32 reduce
model = FSDP(model,
mixed_precision=policy,
auto_wrap_policy=transformer_block_policy, # wrap each block
device_id=torch.cuda.current_device())
# from here the training loop of Section 17.6 is UNCHANGED -
# FSDP gathers and re-shards each block transparently

Python — FSDP: shard a model across GPUs in a few lines

Every parallelism strategy in this chapter reduces to a small set of collective communication primitives, all provided by NCCL through torch.distributed. Three carry almost all the traffic. All-reduce sums a tensor across ranks and returns the result to everyone — it is how data-parallel ranks average gradients. All-gather concatenates each rank’s shard into the full tensor — how FSDP reassembles a layer’s parameters before forward. Reduce-scatter sums and then shards in one pass — how FSDP reduces gradients while leaving each rank only its slice.

import torch.distributed as dist
# data-parallel gradient averaging = all-reduce(SUM) then divide
for p in model.parameters():
dist.all_reduce(p.grad, op=dist.ReduceOp.SUM)
p.grad /= dist.get_world_size()
# FSDP pattern: gather full param for the layer, then reduce-scatter its grad
dist.all_gather_into_tensor(full_weight, shard_weight) # before forward
dist.reduce_scatter_tensor(shard_grad, full_grad) # after backward

Python — dist/collectives.py: the three primitives in context

The cost is predictable. A ring all-reduce of an N-byte tensor across P ranks moves about 2(P−1)/P × N bytes through each rank’s links. For a 200 MB gradient bucket over 64 ranks that is roughly 2 × 63/64 × 200 ≈ 394 MB per rank; on a 400 GB/s NVLink fabric, about 1 millisecond. Multiply by the number of buckets per step and you see immediately why frameworks bucket gradients and overlap their all-reduce with the ongoing backward pass: the communication must hide behind computation, or it becomes the run’s bottleneck.

19.8 Worked Example: Mapping a Model onto 1,024 GPUs

Section titled “19.8 Worked Example: Mapping a Model onto 1,024 GPUs”

Combining the dimensions of Section 19.5 is a factoring problem. Suppose 1,024 GPUs in 128 nodes of 8. A frontier MoE might be laid out as tensor parallelism 8 (inside a node, where the bandwidth is highest), pipeline parallelism 16 (across nodes, splitting the 78 layers into 16 stages of about 5 layers), and data parallelism 8 (replicas of the whole pipeline): 8 × 16 × 8 = 1,024. Expert parallelism is then folded into the data-parallel groups, distributing the 256 experts across those ranks so no single GPU holds them all.

The ordering is not arbitrary. Tensor parallelism demands the most bandwidth (an all-reduce inside every layer), so it is kept within a node on NVLink. Pipeline parallelism communicates least — only activations at stage boundaries — so it spans the slower inter-node network. Data parallelism’s gradient all-reduce, large but infrequent (once per optimizer step, Section 19.7), tolerates the same inter-node fabric. Reading any frontier training report, you can now reconstruct its mesh from a single line like “TP=8,

PP=16, DP=8, EP=64” and know why each number sits where it does.

Bandwidth dictates topology Place the chattiest parallelism on the fastest links. Tensor parallelism inside the node, pipeline and data parallelism across nodes. Get this backward and the same GPUs deliver a fraction of the throughput — the model is identical, only the wiring changed.

19.9 Overlapping Communication with Computation

Section titled “19.9 Overlapping Communication with Computation”

The collectives of Section 19.7 move enormous volumes of data, and if the GPUs sat idle waiting for them, no amount of parallelism would scale. The technique that saves it is overlap: begin communicating each layer’s gradients the moment they are ready, while the backward pass is still computing the gradients of earlier layers. Communication then happens behind computation rather than after it:

# backward runs last-to-first; fire all-reduce as buckets fill
for layer in reversed(layers):
layer.backward() # compute this layer's grad
bucket.add(layer.grad)
if bucket.is_full():
bucket.all_reduce_async() # overlaps next backward

Python — dist/overlap.py: bucketed gradients, async all-reduce

The mechanism rests on two ideas working together. Gradients are grouped into buckets of a few tens of megabytes so that a collective is launched on a worthwhile chunk rather than on every tiny tensor; and each bucket’s all-reduce is launched asynchronously, returning control immediately so the backward pass continues into the next layer while the network does its work. Done well, the gradient communication of a step is almost entirely hidden, and the measured throughput approaches what the GPUs could achieve with no communication at all. Done poorly — buckets too small, or a synchronous barrier in the wrong place — the same hardware delivers a fraction of its peak, which is why this overlap is one of the first things a profiler (Section 20.7) is used to verify.

Hide the network behind the math At scale, communication is unavoidable but need not be visible. Bucketing gradients and launching their all-reduce asynchronously lets the network work while the GPUs compute — the difference between linear scaling and a cluster running at half speed.

Tensor parallelism (Section 19.2) splits the big matrix multiplies across devices, but it leaves a gap: operations like normalization and dropout are not matrix multiplies, so they run replicated on every tensor-parallel rank, and crucially their activations are duplicated across those ranks. At long sequence length that duplicated activation memory is significant. Sequence parallelism closes the gap by splitting these replicated regions along the sequence dimension, so each rank holds only its slice of the tokens.

The two techniques interlock. Within a layer, the computation alternates between tensor-parallel regions (the attention and FFN matmuls, split across the hidden dimension) and sequence-parallel regions (the norms and residual adds, split across tokens), with lightweight communication converting between the two layouts at the boundaries. The payoff is that no activation is fully replicated anywhere — every rank stores only its share, whether that share is a slice of the hidden dimension or a slice of the sequence. For the long-context training that modern models target, this reduction in activation memory is often what makes a given parallelism configuration viable, and it is why sequence parallelism is now a standard companion to tensor parallelism rather than an optional extra.

Split the leftovers along the sequence Tensor parallelism leaves norms and residuals replicated, duplicating their activations. Sequence parallelism shards those along the token dimension so nothing is fully replicated — a memory win that matters most exactly where context is longest.

Pipeline parallelism (Section 19.3) splits the model into stages across devices, but a naive schedule wastes time: while the first microbatch works its way through the pipeline to fill it, and while the last drains out, some stages sit idle. This idle time is the pipeline bubble, and minimizing it is the central concern of pipeline scheduling. The standard improvement is the one-forward-one-backward (1F1B) schedule.

The idea is to interleave rather than batch the phases. Instead of running all forward passes and then all backward passes — which maximizes the time before any device can start useful backward work — 1F1B has each device alternate: a forward pass on one microbatch, then a backward pass on an earlier one, then forward again. This keeps every stage busy with some microbatch’s work nearly all the time, shrinking the bubble substantially. The remaining bubble fraction depends on the ratio of microbatches to pipeline stages: with many microbatches flowing through few stages, the fill-and-drain overhead is amortized to a small fraction of the total, while with too few microbatches the bubble dominates and the pipeline is inefficient. DeepSeek-V3’s DualPipe (Section 45.9) is a further refinement that overlaps the forward and backward computation with communication to shrink the bubble further still. The general lesson is that pipeline parallelism’s efficiency is largely a scheduling problem — the same stages, ordered well, can be the difference between devices that are busy and devices that wait.

Interleave forward and backward to fill the pipe The pipeline bubble is idle fill-and-drain time. The 1F1B schedule alternates forward and backward passes so every stage stays busy, and the bubble shrinks as microbatches outnumber stages. Efficiency is a scheduling problem.