Distributed Training

Llama 3 405B needs 4.86 TB of training state. One H100 holds 80 GB, so the state is 61 times too big. Spread the model over thousands of GPUs and each one carries a few gigabytes.

Pick a strategy, then drag the number of GPUs. Watch the bar cross the 80 GB line, and watch what each strategy costs in network traffic. Then we build, piece by piece, every way to split a model and why each one belongs on its own kind of link.

You need what a gradient is and what a GPU does. We build the rest from zero.

Based on Stanford CS 231n, Lecture 11, Large-Scale Distributed Training.

Fit the model on the GPUs

1,024

Memory is Llama 3 405B at 12 bytes per parameter (BF16 weight and gradient, two FP32 Adam moments): 405 × 109 × 12 = 4,860 GB. It counts model state only, with no activations. TP 8 × PP 16 splits the state over 128 GPUs and does not shard across replicas. Traffic is the relative load from Chapter 8: DP 1, FSDP 3, TP 4, PP 1. These are teaching units, not measured bytes.

Chapter 0

Why Distributed? — The Scale Problem

Count the memory and the compute that Llama 3 needs, and see why no single GPU can do the job

Imagine you want to train Llama 3 405B, Meta's largest open-weight language model. It has 405 billion parameters. Let's do some back-of-the-envelope math to see why a single GPU is hopeless.

The Memory Wall

During training, every parameter needs four numbers stored alongside it:

ItemPer parameterPrecision
Weight1 numberBF16 (2 bytes)
Gradient1 numberBF16 (2 bytes)
Adam first moment (m)1 numberFP32 (4 bytes)
Adam second moment (v)1 numberFP32 (4 bytes)

That adds up to 2 + 2 + 4 + 4 = 12 bytes per parameter. This lesson uses 12 bytes everywhere. Many real setups also keep an FP32 master copy of the weights. That extra 4 bytes makes 16 bytes per parameter. For Llama 3:

Memory
The training state that must sit in GPU memory: weights, gradients and optimizer states.
405 × 109
The number of parameters in Llama 3 405B.
(2 + 2 + 4 + 4)
Bytes per parameter: weight, gradient, Adam m, Adam v.

An H100 GPU has 80 GB. The state needs over 60 GPUs' worth of memory, and that is just the model state.

It also leaves out activations (the intermediate values saved for backpropagation), communication buffers, and the data itself.

The Compute Wall

How many floating-point operations (FLOPs) does training need? Here is a widely used estimate for transformer training:

FLOPs
The total floating-point operations for the whole training run.
6
2 for the forward pass multiply-adds, plus 4 for the backward pass (twice the forward pass).
N
The number of parameters.
D
The number of training tokens.
Worked example: Llama 3 training compute

N = 405 × 109, D = 15 × 1012 tokens.

FLOPs = 6 × 405 × 109 × 15 × 1012 = 3.645 × 1025 FLOPs.

An H100 does about 989 TFLOP/s (BF16 tensor core peak) = 989 × 1012 FLOP/s.

On 1 GPU: 3.645 × 1025 / (989 × 1012) = 3.69 × 1010 seconds ≈ 1,170 years.

On 24,576 GPUs: 1,170 / 24,576 ≈ 17 days at perfect, peak speed. At about 40% hardware utilization (MFU), that is about 43 days.

Meta actually trained Llama 3 for about 54 days. Real runs add overheads and restarts, and no job holds peak speed.

The core challenge

Two walls block us: memory (the model does not fit on one GPU) and compute (training would take centuries). Distributed training solves both by spreading work across thousands of GPUs. The rest of this lesson is about how.

Model FLOPs Utilization (MFU)

No training job reaches 100% of peak GPU speed. Communication, synchronization, memory copies, and pipeline bubbles all eat into useful compute. The Model FLOPs Utilization (MFU) measures what fraction of theoretical peak goes to real model arithmetic:

MFU
The share of the GPU's peak speed that does useful model math.
model FLOPs per step
The arithmetic one training step needs (the 6ND estimate, per step).
peak FLOP/s
What the chips could do if nothing ever waited.
step time
The real seconds one step took, waits included.

Llama 3 achieved about 38 to 43% MFU on 24K H100s. Even 40% is considered excellent at this scale.

The road

The page below has ten chapters. Each one answers a question that the last one raised. The device at the top of this page uses ideas from every one of them.

  1. Why Distributed? The Scale Problem: the two walls, memory and compute, in numbers.
  2. GPU Hardware: The Compute Engine: SMs, tensor cores, mixed precision and the roofline.
  3. GPU Servers & Clusters: the bandwidth hierarchy and its 18× cliff.
  4. Data Parallelism (DP): split the data, all-reduce the gradients.
  5. Fully Sharded Data Parallelism: split the model state too (ZeRO).
  6. Hybrid & 3D Parallelism: match each strategy to its link.
  7. Pipeline Parallelism (PP): split by layers, and fight the bubble.
  8. Tensor Parallelism (TP): split each weight matrix.
  9. Parallelism Strategy Explorer: set all the dials yourself.
  10. Putting It All Together: the Llama 3 recipe and the one-sentence rule.
Why can one H100 not train Llama 3 405B, however long you wait?

Chapter 1

GPU Hardware — The Compute Engine

Open one H100 and learn which parts do the math, which parts hold the data, and when each one is the bottleneck

Before we distribute work, we need to know what a single GPU can do. A modern GPU is not one big processor. It is thousands of small processors that work in parallel, organized into a hierarchy.

Streaming Multiprocessors (SMs)

An NVIDIA H100 contains 132 Streaming Multiprocessors. Each SM is a self-contained compute unit with its own registers, shared memory, and two types of cores:

Definition: CUDA cores. Scalar processing units. Each one performs one FP32 multiply-add (a × x + b) per clock cycle. The H100 has 128 CUDA cores per SM × 132 SMs = 16,896 CUDA cores. These handle general-purpose parallel computation.

Definition: tensor cores. Specialized matrix-multiply units. Each tensor core computes a [16×4] · [4×8] matrix product per cycle. That is 16 × 4 × 8 = 1,024 FLOPs in a single operation. The H100 has 4 tensor cores per SM × 132 SMs = 528 tensor cores. This is where the real throughput lives.

Tensor cores are why modern GPUs reach such absurd throughput on matrix operations. A standard matmul breaks into many small [16×4]·[4×8] tiles, and the tensor cores chew through them in parallel.

Mixed Precision Training

Tensor cores are tuned for half-precision formats: FP16 (IEEE float16) or BF16 (bfloat16). The trick is to run the forward and backward pass in BF16 for speed, but keep the optimizer states and a master copy of the weights in FP32 for numerical stability.

Why BF16 over FP16?

BF16 has the same exponent range as FP32 (8 exponent bits) but fewer mantissa bits (7 vs 23). It can represent the same range of magnitudes, so there are no overflow or underflow surprises. The cost is some precision. FP16 has only 5 exponent bits and can overflow during training. BF16 is now the standard for LLM training.

GPU Evolution: 1000× in a Decade

GPUYearBF16 tensor TFLOP/sMemoryMem BW (GB/s)
K402013~5 (FP32 only)12 GB GDDR5288
V100201712532 GB HBM2900
A100202031280 GB HBM2e2,039
H100202398980 GB HBM33,352
B2002025~5,000192 GB HBM3e8,000

From K40 to B200 that is roughly 1,000× more throughput. It is not just faster transistors. It is a basic shift toward specialized matrix hardware.

Arithmetic Intensity & the Roofline Model

Not every operation can use all that throughput. The key metric is arithmetic intensity: how many FLOPs you do for each byte you load from memory.

Arithmetic intensity
FLOPs per byte. Higher means more compute-bound, which is good for GPUs.
FLOPs
The arithmetic the operation performs.
Bytes loaded
The data the operation must read from memory.
Worked example: matmul vs element-wise

Matrix multiply [M×K] · [K×N] does 2MKN FLOPs and loads (MK + KN) × 2 bytes (BF16). For M = N = K = 4096: intensity = 2×40963 / (2×40962 × 2) ≈ 2048 FLOPs/byte. Extremely compute-bound.

Element-wise ReLU on 4096×4096 does N operations and loads N × 2 bytes. Intensity = 1/2 = 0.5 FLOPs/byte. Completely memory-bandwidth-bound.

The H100 has 989 TFLOP/s of compute and 3,352 GB/s of bandwidth. The crossover point is 989,000 / 3,352 ≈ 295 FLOPs/byte. Operations below this intensity wait on memory bandwidth, not compute. Large matmuls, the core of transformers, are far above it. That is why tensor cores can actually be kept busy.

The roofline

Think of it as a speed limit. At low arithmetic intensity, memory bandwidth is the ceiling: no matter how many tensor cores you have, you wait for data. At high intensity, compute is the ceiling: you are limited by TFLOP/s. Large-batch matmuls sit firmly in the compute-bound regime, which is exactly where GPUs shine.

An H100 has a crossover point of about 295 FLOPs/byte. A large matmul has an intensity of about 2048. What does that tell you?

Chapter 2

GPU Servers & Clusters

Zoom from one chip to 24,576 and find the steep cliff in bandwidth that shapes every later choice

A single H100 has 80 GB of memory and 989 TFLOP/s. To train a 405B-parameter model, you must wire up thousands of these chips. The critical question is: how fast can they talk to each other?

The Bandwidth Hierarchy

Not all GPU connections are equal. There is a steep hierarchy of bandwidth, and understanding it is essential for choosing parallelism strategies.

Zoom out from GPU to cluster

Click a level to zoom in. Each level has much less bandwidth than the one below it.

Sizes and bandwidths are the lecture's numbers for Meta's Llama 3 cluster. The pod view draws 16 of its 192 racks. Layouts are schematic. On the GPU view, warm squares stand for tensor cores and blue squares for CUDA cores.

LevelWhatBandwidthRatio to HBM
HBM ↔ GPUOn-chip memory bus3,352 GB/s1×
GPU ↔ GPU (intra-server)NVLink / NVSwitch900 GB/s0.27×
Server ↔ Server (intra-pod)InfiniBand (8× 400G)~50 GB/s0.015×
Pod ↔ Pod (cross-pod)InfiniBand (spine)<50 GB/s<0.015×
The 18× drop

Going from intra-server NVLink (900 GB/s) to inter-server InfiniBand (~50 GB/s) is an 18× bandwidth drop. This cliff shapes every parallelism decision: put communication-heavy operations on NVLink, and communication-light operations across InfiniBand.

Cluster Anatomy: Llama 3's 24,576 GPUs

Concrete numbers: Meta's Grand Teton cluster

1 server = 8× H100 GPUs, connected via NVSwitch (900 GB/s all-to-all). 640 GB total GPU memory.

1 rack = 2 servers = 16 GPUs. 1.28 TB memory.

1 pod = 192 racks = 3,072 GPUs. Connected by an InfiniBand fat-tree network (50 GB/s per GPU). 245 TB memory.

1 cluster = 8 pods = 24,576 GPUs. Cross-pod InfiniBand (<50 GB/s). Total: 1.97 PB memory, 24.3 EFLOP/s peak.

Network Topology

Within a pod, Meta uses a fat-tree topology. Every server connects to a top-of-rack switch, which connects to spine switches, so there are many redundant paths. This gives full bisection bandwidth: any half of the pod can talk to the other half at full speed.

Across pods, bandwidth is more limited. Meta uses a rail-optimized design: GPU 0 in every server connects to the same network rail, GPU 1 to another rail, and so on. Collective operations (like all-reduce) on the same GPU index across servers then use dedicated paths that do not compete.

Failures at Scale

When things break

With 24,576 GPUs, failures are routine. Meta reported interruptions every few hours during Llama 3 pre-training. Their answer had three parts: aggressive checkpointing (save model state every few minutes), automatic job restart (detect failures, reassign work, resume from the last checkpoint), and spare capacity (extra GPUs on standby). At this scale, reliability engineering matters as much as the training algorithm.

Google TPUs

Google takes a different approach with TPUs (Tensor Processing Units). The v5p chip delivers 459 TFLOP/s (BF16), and pods scale up to 8,960 chips with a custom high-bandwidth interconnect (ICI). TPU pods are more tightly integrated than GPU clusters of the same size, but you can only get them through Google Cloud.

Where should the most communication-heavy operations run?

Chapter 3

Data Parallelism — The Simple Idea

Copy the model to every GPU, split the batch, and average the gradients with a ring that has no bottleneck

Here is the most intuitive way to use many GPUs: give every GPU a complete copy of the model, and split the training data across them. Each GPU processes a different mini-batch and computes gradients. Then they all share results.

Definition: Data Parallelism (DP). Every GPU holds a full copy of the model (weights, gradients, optimizer states). The training batch is split into N equal chunks, one per GPU. Each GPU computes local gradients on its chunk. Then the gradients are aggregated across all GPUs before the weight update.

Why Gradient Averaging Works

The key insight is that gradients are linear. The gradient over a batch is the average of the gradients over its single samples. So if you split a batch across GPUs and average the per-GPU gradients, you get exactly the same result as one GPU working on the full batch.

∇L(B)
The gradient of the loss on the full batch B. This is what one big GPU would compute.
(1/|B|)
Divide by the batch size: the average over samples.
∑x ∈ B
Add up the per-sample gradients over every sample x in the batch.
(1/N)
Divide by the number of GPUs: the average over GPUs.
∇L(Bi)
The gradient GPU i computes on its own share Bi of the batch.

The average of the local gradients equals the gradient of the full batch. The two are mathematically equivalent.

All-Reduce: The Communication Primitive

After each GPU computes its local gradient, we need the sum (or average) of all of them, and every GPU needs the result. This operation is called all-reduce.

Definition: All-reduce. A collective communication operation. It takes an array from each of N participants, computes an element-wise reduction (sum, average, max), and gives the result to all participants. Every GPU ends up with the same aggregated result.

Step through ring all-reduce

Watch how N GPUs exchange gradients in a ring. Scatter-reduce comes first, then all-gather. Each GPU sends and receives exactly once per step. Press Step.

5

A schematic of the chunk bookkeeping, not a trace of real data. Chunk colours show how many GPUs' gradients are already summed into a chunk. The volume numbers are exact: each step moves M/N bytes per GPU.

Ring All-Reduce

A naive all-reduce sends everything to one GPU, sums it there, and sends the result back. That jams one link. The ring all-reduce is much smarter:

  1. Setup: Arrange N GPUs in a ring. Each GPU splits its gradient into N chunks.
  2. Scatter-reduce (N−1 steps): Each GPU sends one chunk to its right neighbor and receives one chunk from its left. It adds the received chunk to its own. After N−1 steps, each GPU holds one fully reduced chunk.
  3. All-gather (N−1 steps): Each GPU sends its fully reduced chunk to the right. After N−1 steps, every GPU has all N reduced chunks.
Worked example: communication volume

Model size M bytes, N GPUs. Each GPU's gradient is M bytes.

Naive: All GPUs send M bytes to GPU 0, then GPU 0 broadcasts M bytes. Total: 2(N−1)M bytes through GPU 0. Bottleneck: GPU 0.

Ring: Each step, every GPU sends M/N bytes. There are 2(N−1) steps in all. Per GPU: 2(N−1) × M/N ≈ 2M bytes (for large N). Every link carries equal load, so there is no bottleneck.

Communication is independent of N

In ring all-reduce, each GPU sends about 2M bytes no matter how many GPUs take part. The total time is 2(N−1)M/(N × bandwidth) ≈ 2M/bandwidth. Doubling the GPUs does not double the communication cost. It is almost free scaling.

The Problem with Pure DP

Data parallelism has one fatal flaw for large models: every GPU needs a full copy of the model. For Llama 3 405B, that is about 4.86 TB of training state on each GPU. An H100 has 80 GB of HBM and cannot hold it. We need to shard the model itself.

In ring all-reduce with N GPUs and a gradient of M bytes, about how much does each GPU send?

Chapter 4

Fully Sharded Data Parallelism

Give each GPU one slice of the state and fetch the rest only when a layer needs it

The idea behind FSDP is simple. In data parallelism, every GPU stores the entire model. But at any moment in the forward pass, it needs only one layer's weights. What if we store only the weights we need right now?

Definition: ZeRO (Zero Redundancy Optimizer). A family of memory techniques that shard (split) the model's training state across GPUs and remove the redundancy. Each weight tensor is "owned" by exactly one GPU, which stores its weight, gradient, and optimizer states. Other GPUs request it on demand.

ZeRO Stages

ZeRO comes in three stages. Each one shards more than the last:

StageWhat is shardedMemory per GPUComm. overhead
Stage 1Optimizer states only (m, v)~Nparams × (2+2+8/N) bytesSame as DP
Stage 2Optimizer states + gradients~Nparams × (2+10/N) bytesSame as DP
Stage 3 (FSDP)Everything: weights + grads + optimizer~Nparams × 12/N bytes~3× DP
Memory per GPU
The training state each GPU stores under ZeRO Stage 3.
Nparams
The number of model parameters.
12
Bytes per parameter: weight, gradient, Adam m, Adam v.
N
The number of GPUs that share the shards.
Worked example: Llama 3 with FSDP

405B params × 12 bytes = 4.86 TB total training state.

Stage 3 on 1,024 GPUs: 4.86 TB / 1,024 = 4.75 GB per GPU. That fits easily in 80 GB and leaves room for activations and buffers.

Stage 1 on 1,024 GPUs: Each GPU stores full weights (810 GB in BF16) + full gradients (810 GB) + a sharded optimizer (4 bytes × 2 × 405B / 1024 ≈ 3.16 GB). That still does not fit, because 810 GB alone exceeds one GPU.

For 405B parameters, Stage 3 is mandatory.

How FSDP Works (Stage 3)

Imagine the model has L layers. GPU k "owns" a subset of layers. Here is what happens:

FSDP forward + backward

  1. Forward pass, layer i: The owner of Wi broadcasts (all-gather) the weights to all GPUs. Every GPU computes the forward pass for layer i. Then non-owners discard their copy of Wi to free memory.
  2. Backward pass, layer i: The owner broadcasts Wi again (it is needed for the gradient). Every GPU computes a local dL/dWi. Each GPU sends its local gradient to the owner via reduce-scatter. The owner adds them up and updates Wi.
  3. Overlap: While computing layer i, prefetch layer i+1's weights in the background. Communication and computation run in parallel.
Memory scales perfectly

With N GPUs, each GPU stores 1/N of the model. Double the GPUs, halve the memory per GPU. This is how you fit a 4.86 TB model on 80 GB GPUs: use enough of them. The cost is 3× more communication than vanilla DP (one all-gather in forward, one all-gather and one reduce-scatter in backward).

Communication vs. Computation Overlap

In practice, the magic of FSDP is prefetching. While GPU cores compute the forward pass for layer i, the network interface card (NIC) is already pulling in the weights for layer i+1. If the network is fast enough compared to the compute, the communication cost is almost entirely hidden.

When overlap fails

Say the model's layers are small (few parameters, fast to compute) but the network is slow. The GPU finishes computing before the next layer's weights arrive, and it sits idle. This is why FSDP works best on fast interconnects (NVLink) and with models that have large, compute-heavy layers.

405B parameters on 1,024 GPUs: which ZeRO stage lets the training state fit in 80 GB per GPU?

Chapter 5

Hybrid & 3D Parallelism

Put each kind of traffic on the link that can carry it, and stack several strategies into one mesh

FSDP works well inside a server, where NVLink gives 900 GB/s. Across servers the bandwidth drops 18×. If you shard with FSDP across all 24,576 GPUs, the slow links between servers become the bottleneck. The fix is HSDP: use FSDP locally and plain DP globally.

Definition: HSDP (Hybrid Sharded Data Parallelism). Split N GPUs into M groups of K. Within each group, run full FSDP (shard everything). Across groups, run plain DP (replicate the model, all-reduce the gradients). Put the within-group traffic on fast links and the across-group traffic on slow links.

Communication Analysis

Inside an FSDP group of K GPUs, the forward and backward pass needs 3× the model size in communication (two all-gathers and one reduce-scatter). Across the M groups, only the gradients need an all-reduce: 1× the model size.

Worked example: Llama 3 HSDP

24,576 GPUs. Split into M = 3,072 groups of K = 8 (one group = one server).

Intra-server (FSDP): 3× model communication over NVLink at 900 GB/s. Fast.

Inter-server (DP): 1× gradient all-reduce over InfiniBand at ~50 GB/s. Slower, but 3× less data.

HSDP puts 3× the traffic on the 18× faster link and only 1× on the slow link. It matches the network hierarchy to the communication pattern.

3D Parallelism

For the largest models, even HSDP is not enough. You must combine several parallelism strategies at once. This is 3D parallelism (or 4D, or 5D, as many dimensions as you need).

Think of the GPU cluster as a multi-dimensional mesh. Each dimension maps to a different parallelism strategy:

DimensionStrategyWhat is splitBest link
Dim 1TP (Tensor Parallelism)Weight matricesNVLink (fastest)
Dim 2PP (Pipeline Parallelism)Model layersNVLink or fast IB
Dim 3DP/FSDPData batchesInfiniBand (slowest is OK)
Dim 4CP (Context Parallelism)Sequence lengthVaries
The design principle

Communication-heavy strategies go on fast links. Communication-light strategies go on slow links. TP needs all-reduces after every layer, so put it on NVLink. DP all-reduces gradients only once per step, so InfiniBand is fine. This is the core insight behind every multi-dimensional parallelism scheme.

Llama 3 405B used 4D parallelism: TP = 8 (within a server) × PP = 16 (across servers in a pod) × CP = 1 to 4 × DP = variable across pods. That mapped the communication needs to the bandwidth hierarchy almost perfectly.

Why does HSDP shard with FSDP inside a server and use plain DP across servers?

Chapter 6

Pipeline Parallelism — Split by Layers

Cut the model into stages like an assembly line, then shrink the idle gaps with micro-batches

Pipeline parallelism takes a different approach. Instead of giving every GPU the full model, it splits the model by layers. GPU 1 gets layers 1 to 20, GPU 2 gets layers 21 to 40, and so on. Data flows through the pipeline like an assembly line.

Definition: Pipeline Parallelism (PP). Partition the model's layers across P stages, one stage per GPU (or group of GPUs). Each stage processes its layers, passes the output (activations) to the next stage, and receives gradients flowing back. The inter-stage communication is just the activation tensor at each layer boundary, which is much smaller than the full model.

The Bubble Problem

Naive pipelining has a bad flaw. Stage 2 cannot start until Stage 1 finishes. Stage 3 cannot start until Stage 2 finishes. During the forward pass, only one stage is active at a time and the rest idle. The same holds for the backward pass. The idle time is the pipeline bubble.

Compare pipeline schedules

Each coloured block is a micro-batch, forward (bright) or backward (dim). Tinted cells are idle: the bubble. Switch between naive, GPipe and 1F1B, then drag the stages and micro-batches.

4
8

Every forward and backward block takes one time slot, so the bubble counts idle slots exactly. Real backward blocks take about twice as long as forward blocks. The schedules are simulated live from their dependency rules.

Micro-batching: The Fix

The fix is to split the batch into micro-batches and pipeline them. While Stage 1 handles micro-batch 2, Stage 2 can handle micro-batch 1. The pipeline fills up, and most of the time all stages are busy.

GPipe Schedule

GPipe (2019) is the simplest micro-batching scheme. Run all forward micro-batches through the pipeline, then run all backward micro-batches. A bubble remains at the boundary, where the forward passes end and the backward passes begin.

1F1B Schedule

The 1F1B (one-forward-one-backward) schedule interleaves forward and backward passes. After the pipeline fills with forward micro-batches, each stage alternates: one forward, one backward. This lowers peak memory, because the gradients and activations of earlier micro-batches are freed before later ones are computed.

Bubble fraction
The share of stage-time that sits idle.
P
The number of pipeline stages.
M
The number of micro-batches. More micro-batches make a smaller bubble.
Worked example: bubble calculation

P = 4 stages, M = 8 micro-batches: bubble = 3 / (3 + 8) = 27.3%.

P = 4 stages, M = 32 micro-batches: bubble = 3 / (3 + 32) = 8.6%.

P = 16 stages, M = 8: bubble = 15 / (15 + 8) = 65.2%. Terrible!

P = 16 stages, M = 64: bubble = 15 / (15 + 64) = 19.0%. Manageable.

The rule: M should be several times larger than P to keep the bubble small.

Interleaved Pipeline Parallelism

There is an even cleverer trick: give each stage non-contiguous layers. Instead of GPU 1 getting layers 1 to 20, give it layers 1 to 5 and 21 to 25. This makes a "virtual pipeline" with more stages, and each stage computes faster. The bubble shrinks because there are more, shorter stages to pipeline.

PP communication is light

Pipeline parallelism sends only activations between stages: a single tensor at each layer boundary. For a transformer, this is [batch × seq_len × hidden_dim] × 2 bytes, far smaller than the full model weights. That is why PP works across slower InfiniBand links.

Activation Checkpointing

During the forward pass, each layer makes activations that must be saved for the backward pass. For large models with long sequences, the activations can use more memory than the model itself. Activation checkpointing (also called gradient checkpointing) saves only the input to each layer and recomputes the activations during the backward pass. It trades compute (about 33% more forward passes) for memory (roughly proportional to sqrt(L) instead of L).

A pipeline has P = 16 stages. Which choice keeps the bubble smallest?

Chapter 7

Tensor Parallelism — Split by Dimensions

Slice each weight matrix across GPUs, pair column and row splits, and see why this must stay on NVLink

Pipeline parallelism splits across layers. Tensor parallelism goes deeper: it splits individual weight matrices across GPUs. Each GPU holds a slice of every layer's weights and computes a slice of every layer's output.

Definition: Tensor Parallelism (TP). Partition individual weight matrices across T GPUs along the row or column dimension. Each GPU computes part of the matrix multiply. Then an all-reduce (or a concatenation) combines the partial results. This happens at every layer, so it needs extremely fast links between GPUs.

Column Parallel

Take a linear layer Y = XW, where W is [K × N]. Split W into T column chunks: W = [W1, W2, …, WT], each of size [K × N/T]. GPU i computes Yi = X · Wi and gets a [batch × N/T] output. Concatenate all the Yi to get the full [batch × N] output.

Y
The full [batch × N] output of the layer.
X
The input, copied to every GPU.
W1 | … | WT
The weight matrix cut into T column chunks, one per GPU.
Yi = X · Wi
GPU i's local matmul. It needs no communication.
concat
Glue the pieces side by side. This is an all-gather.

Row Parallel

Or split W along rows: W = [W1; W2; …; WT], each [K/T × N]. Now the input X must be split by columns. GPU i computes Yi = Xi · Wi. The results are partial sums that must be added: Y = ∑ Yi (an all-reduce).

Yi = Xi · Wi
GPU i's local matmul on its slice of the input and its rows of W.
Y1 + … + YT
Each Yi is a partial sum, so the full result is their sum. This is an all-reduce.

Transformer MLP Block

The transformer MLP has two linear layers. The first projects up (hidden → 4×hidden). The second projects down (4×hidden → hidden). Here is the elegant trick: use column parallel on the first layer and row parallel on the second. The column-parallel output is already split across GPUs, which is exactly the input that row parallel needs. There is no communication between the two layers!

Only one all-reduce per MLP

Column parallel on layer 1, then no communication, then row parallel on layer 2, then one all-reduce. The whole MLP block needs only one all-reduce in the forward pass (and one in the backward pass). Without this pairing you would need two.

Self-Attention

Multi-head attention is naturally column-parallel. If the model has H attention heads and T GPUs, give H/T heads to each GPU. Each GPU computes its own heads independently. Then the output projection (a row-parallel linear) combines them with a single all-reduce.

Why TP Needs NVLink

TP needs an all-reduce at every transformer block: twice per block in the forward pass (once for the MLP, once for attention), and twice more in the backward pass. For a 126-layer Llama 3 model, that is about 504 all-reduces per step. At 50 GB/s InfiniBand this would be painfully slow. At 900 GB/s NVLink it is tolerable. TP must stay inside one server.

Worked example: TP communication

Llama 3 405B, hidden dim = 16,384, batch × seq = 4M tokens. TP = 8 across one server.

Each all-reduce sends about 16,384 × 4M × 2 bytes = 128 GB per transformer block (for the activation tensor). With 126 blocks: 126 × 4 × 128 GB = 64 TB of communication per step.

At 900 GB/s NVLink: 64 TB / 900 GB/s ≈ 71 seconds for communication alone. It must overlap with computation to be viable.

Context Parallelism

When sequences get very long (128K+ tokens), even the activations inside a single layer become huge. Context parallelism (CP) splits the sequence dimension: each GPU handles a part of the sequence. Attention then needs a ring-attention scheme, where KV chunks pass around a ring so each GPU can attend to every position.

Sequence parallelism is not context parallelism

Do not confuse context parallelism with sequence parallelism. Sequence parallelism applies TP-style sharding to operations that do not split naturally (LayerNorm, Dropout). Instead of copying them on every TP rank, each GPU handles its own sequence chunk. It saves memory but uses the same TP group. It complements TP and is not a separate dimension.

In a tensor-parallel MLP, why use column parallel on the first layer and row parallel on the second?

Chapter 8

Parallelism Strategy Explorer

Set the model, the cluster and every parallel dimension, and watch memory and traffic respond

Now let's put it all together. The tool below lets you set up a distributed training run and see the memory use, the communication cost, and how the GPUs are laid out.

Configure a training run

Set your model, cluster and parallelism strategy. Memory per GPU turns red when it passes 80 GB. Try a preset first, then change one dial at a time.

70
128
1
1

Teaching model: 12 bytes per parameter, state only, with no activations. Per-GPU memory is state / (TP × PP) without FSDP and state / (TP × PP × DP) with FSDP. Communication units are relative: DP 1, FSDP 3, TP 4 (two all-reduces per block forward, two backward), PP 1. They are not measured bytes.

Try these configurations

Small model (7B), 8 GPUs: Pure DP works. Each GPU stores about 84 GB, slightly over the 80 GB limit. Turn on FSDP to fix it.

Large model (405B), 128 GPUs: You need TP = 8 + PP = 4 + FSDP. Watch how each dimension lowers memory but adds communication.

Extreme: 405B on 8 GPUs: Even with TP = 8 and FSDP, memory is crushing. You need more GPUs or model compression.

A 7B model on 8 GPUs with plain DP needs about 84 GB per GPU. What fixes it?

Chapter 9

Putting It All Together

Read Meta's Llama 3 recipe as one answer to the memory wall, the compute wall and the bandwidth cliff

Llama 3 Training Recipe

Meta trained Llama 3 405B on 24,576 H100 GPUs with 4D parallelism:

Llama 3 405B configuration

TP = 8: Within each server (8 GPUs on NVLink). Each GPU holds 1/8 of every weight matrix.

PP = 16: Across 16 servers. Each stage handles about 8 of the 126 transformer layers.

DP = 192: 24,576 / (8 × 16) = 192 data-parallel replicas, with FSDP for memory efficiency.

CP = variable: Context parallelism added for long-sequence training (up to 128K tokens).

Result: about 38 to 43% MFU, about 54 days of training, about 15 trillion tokens.

Go back to the pads at the top of the page: set TP 8 × PP 16 and drag the GPUs. The 38 GB bar you see is this recipe's model state per GPU, before FSDP shards it further across the 192 replicas.

Mixed Precision Training

Every large training job uses mixed precision. The recipe:

Mixed precision training

  1. Master weights: Stored in FP32 (the "ground truth" copy, kept by the optimizer).
  2. Forward pass: Cast the weights to BF16 and compute activations in BF16. This saves 2× memory and speeds up the matmul.
  3. Loss computation: In FP32, for numerical stability.
  4. Backward pass: Compute gradients in BF16.
  5. Optimizer step: Convert the gradients to FP32 and update the master weights in FP32. Cast back to BF16 for the next forward pass.

Gradient Accumulation

Sometimes you want a bigger effective batch than your GPUs can hold. Gradient accumulation runs several forward-backward passes and sums the gradients before one optimizer step. It is mathematically identical to a larger batch, but it uses constant memory.

The Parallelism Comparison

StrategySplitsCommunicationWhen to use
DPData (batches)All-reduce grads, 1× per stepModel fits on 1 GPU
FSDPData + model shards3× DP (all-gather + reduce-scatter)Model does not fit on 1 GPU
PPModel layersActivations between stages (small)Many layers, moderate inter-node BW
TPWeight matricesAll-reduce per layer (frequent)NVLink only, within a server
CPSequence lengthRing attention (KV rotation)Very long sequences (128K+)

Memory Breakdown

For a complete picture of GPU memory during training:

ComponentSize (Llama 3 405B)Reducible by
Weights~810 GB (BF16)TP, PP, FSDP
Gradients~810 GB (BF16)FSDP, gradient accumulation
Optimizer (m, v)~3.24 TB (FP32)FSDP
ActivationsVariable (batch × seq × hidden)Activation checkpointing, PP, CP
Comm buffers~1-2 GBOverlap scheduling
The one sentence

Distributed training maps the communication hierarchy of your algorithms to the bandwidth hierarchy of your hardware: frequent communication on fast links, infrequent communication on slow links.

Connections

This systems view complements the algorithmic side of deep learning. The Transformer lesson covers the architecture being distributed here. SSM/Mamba explores alternatives with different parallelism properties. And understanding RLHF shows why we train these massive models in the first place.

References

  1. Rajbhandari et al. "ZeRO: Memory Optimizations Toward Training Trillion Parameter Models." SC 2020. arXiv
  2. Huang et al. "GPipe: Efficient Training of Giant Neural Networks using Pipeline Parallelism." NeurIPS 2019. arXiv
  3. Shoeybi et al. "Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism." 2020. arXiv
  4. Narayanan et al. "Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM." SC 2021. arXiv
  5. Dubey et al. "The Llama 3 Herd of Models." 2024. arXiv
  6. Micikevicius et al. "Mixed Precision Training." ICLR 2018. arXiv
  7. CS 231n Lecture 11 slides: "Large-Scale Distributed Training." Stanford, 2024.
In the Llama 3 recipe, why does TP = 8 stay inside one server while DP spans pods?
Go back to the hero and run the three strategies again. Notice which one crosses the 80 GB line at which GPU count, and what it pays in traffic. Then open Present or Teach and explain why TP stays on NVLink.
CS 231n · Stanford · Large-Scale Distributed Training
← Back to Gleams