Parallelism I: Data & Tensor

A 70-billion-parameter model needs 1,120 GB of training state. Plain data parallelism puts all of it on every GPU. ZeRO stage 3 spreads it over 64 GPUs at 17.5 GB each, for 1.5 times the traffic.

Pick a way to split the state, then a GPU count. Watch one GPU's memory against its 80 GB, and the bytes it must send every step. Then we build every piece from zero: links, collectives, the ring, data parallelism, ZeRO, FSDP, tensor and pipeline parallelism.

You need bytes per parameter from Lecture 2 and bandwidth from Lecture 5. We build the rest from zero.

Lecture 7 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto; this lecture by Tatsunori Hashimoto). Previous: Lecture 6, Kernels and Triton. Next: Lecture 8, Parallelism II.

Fit 70B across GPUs

64

Mixed-precision AdamW: 2 + 2 + 12 = 16 bytes per parameter (ZeRO paper, K = 12). Activations are not counted. Traffic is per GPU per step, bf16 gradients, at the slowest link. Within 8 H100s that is NVLink, 450 GB/s each way; between servers, 400 Gb/s (50 GB/s).

Chapter 0

One GPU Is Not Enough

Count the bytes a training run keeps for each parameter, and see a 70B model overflow one H100 fourteen times

You want to train a 70-billion-parameter model on 15 trillion tokens. Lecture 2 gave the compute: 6 FLOPs per parameter per token, 6.3 × 1024 in all. One H100 at half its 989.5 TFLOP/s peak needs about 400 years. So the work must spread over many GPUs.

Memory forces the same answer, sooner. Training keeps more than the weights. For every parameter it also keeps a gradient and the optimizer's state. Name them. The weights in bf16 take 2 bytes. The gradients in bf16 take 2 bytes. Call the optimizer's bytes per parameter K, and the number of parameters Ψ, the letter the ZeRO paper uses.

Say it aloud

M equals two plus two plus K, times psi.

M
M the bytes of training state, before any activations.
2
two bytes for each weight in bf16.
2
two bytes for each gradient in bf16.
K
K the optimizer's bytes per parameter. For mixed-precision Adam, K = 12: a float32 master weight (4), the first moment m (4) and the second moment v (4).
Ψ
psi the number of parameters.
In plain words

Add the bytes one parameter needs: 2 for its weight, 2 for its gradient and K for its optimizer state. Multiply by the parameter count Ψ. That is M.

With numbers

Ψ = 70 × 109 and K = 12. M = 16 × 70 × 109 = 1.12 × 1012 bytes, or 1,120 GB. An H100 holds 80 GB. Even split perfectly, the state fills 14 of them.

Count the bytes of one parameter

Top: one parameter, one cell per byte. Bottom: H100s of 80 GB, filled by the whole model. Choose a precision recipe, then drag the model size.

70B

Recipes from the lecture's slide: mixed precision keeps a float32 master copy; "bf16 moments" keeps Adam's m and v in bf16 (12 bytes). GPU count assumes a perfect split and no activations, so it is a floor.

Two recipes give the same 16 bytes. All-float32 AdamW stores 4 + 4 + 8. Mixed precision halves the weights and gradients but adds a float32 master copy. It is faster, not smaller. Keeping Adam's moments in bf16 brings it to 12 bytes.

Every way to split the job across GPUs trades memory for communication. The data must reach each GPU, and the GPUs must agree on one model. This lesson prices each split in bytes per step.

Symptom: CUDA out of memory at the first optimizer step, though the weights loaded fine.

Measure: 16 bytes times the parameter count, against the GPU's memory. The weights alone are only 2 of the 16.

Fix: shard the state across GPUs (Chapters 5 and 6), or split the model itself (Chapters 7 and 8).

The road

  1. Links: NVLink, PCIe and the network, and the latency plus bandwidth cost of one message.
  2. Collectives: broadcast, reduce, all-gather, reduce-scatter and all-reduce.
  3. Ring all-reduce: why each GPU sends about twice the data, whatever N is.
  4. Data parallelism: copy the model, split the batch, average the gradients.
  5. ZeRO: shard optimizer state, gradients and weights (the hero's buttons).
  6. FSDP: fetch each layer's weights just before you use them.
  7. Tensor parallelism: split each matrix, and keep it inside one server.
  8. Pipelines: split the layers, and pay for the bubble.
  9. Showcase: plan a run in three dimensions.
  10. Field guide: the numbers, the cost model in code, the checks.
A 70B model trains with mixed-precision AdamW. How much training state does it keep, before activations?

Chapter 1

The Network Sets the Price

Send one message over NVLink, PCIe and the network, and split its time into a fixed start-up cost and a bandwidth cost

Eight GPUs in one server talk over NVLink, NVIDIA's direct GPU-to-GPU link. Servers talk over the datacenter network: InfiniBand or Ethernet, one network card per GPU in modern servers. The two differ by about ten times in bandwidth. Every plan in this lesson starts from that gap.

LinkEach way, per GPUWhere it isSource
NVLink 3 (A100)300 GB/sinside a server12 links × 25 GB/s (600 GB/s counting both ways)
NVLink 4 (H100 SXM)450 GB/sinside a serverNVIDIA lists 900 GB/s, both ways
PCIe Gen4 x1631.5 GB/sGPU to CPU, or cheap serversA100 whitepaper
InfiniBand HDR25 GB/sbetween servers200 Gb/s
400 Gb/s (NDR or RoCE)50 GB/sbetween serversthe Llama 3 clusters' per-GPU link

A message has two costs. Call the fixed start-up time of one message α, its size in bytes n, and the link's bandwidth in one direction β. The time to send it is:

Say it aloud

T equals alpha, plus n over beta.

T
T the time to deliver one message, in seconds.
α
alpha the latency: the fixed cost of every message, even a tiny one. We use 10 µs, an illustrative value.
n
n the message size in bytes.
β
beta the bandwidth in one direction, in bytes per second.
In plain words

Pay the latency α once. Then divide the bytes n by the bandwidth β. Small messages pay mostly α; large ones pay mostly n / β.

With numbers

n = 268 MB, one activation tensor of a 405B-size model (1 sequence of 8,192 tokens, width 16,384, bf16). Over NVLink at β = 450 GB/s: 10 µs + 0.60 ms = 0.61 ms. Over 400 Gb/s at β = 50 GB/s: 5.38 ms, nine times longer.

Send one message

Each line is one link: time against message size, both on log axes. Flat on the left is latency; the slope on the right is bandwidth. Drag the size and pick a link.

268 MB

Bandwidths from the table. One illustrative latency, 10 µs, for every link; real latencies differ by link and library. Times are for one message, one direction.

The break-even size is n = α × β, where the two costs are equal. On NVLink it is 4.5 MB; on the 50 GB/s network, 500 KB. Gradients are hundreds of megabytes, so training traffic lives on the bandwidth slope. That is why this lesson counts bytes.

The lecture adds a contrast. GPU systems connect GPUs all-to-all through NVLink switches. TPUs link each chip only to its neighbours, in a toroidal mesh. Both suit the collective operations of the next chapter.

Symptom: a job that scaled well on 8 GPUs slows down when it grows to 16.

Measure: at 16 GPUs the traffic crosses the network. Compare its β with NVLink's: 50 against 450 GB/s.

Fix: keep the chattiest split inside the server (Chapter 7), and send fewer, larger messages across servers.

A 1 GB message goes once over NVLink 4 and once over a 400 Gb/s network card. With a 10 µs latency, how long does each take?

Chapter 2

Five Ways to Talk at Once

Run each collective on four GPUs and see that an all-reduce is a reduce-scatter followed by an all-gather

Distributed training rarely sends one message from one GPU to another. Every GPU in a group joins the same operation at the same time. That is a collective. Libraries such as NCCL implement them, and the lecture names five.

  1. Broadcast: one GPU sends its vector to every GPU.
  2. Reduce: one GPU receives the sum of all the GPUs' vectors.
  3. All-gather: each GPU holds one piece; afterwards every GPU holds every piece.
  4. Reduce-scatter: each GPU holds a full vector; afterwards GPU i holds the sum of piece i only.
  5. All-reduce: each GPU holds a full vector; afterwards every GPU holds the full sum.

Run a collective on four GPUs

Each row is a GPU holding four chunks. A cell's label says whose values it holds, and a summed chunk shows all four. Pick an operation and press Run.

An illustrative vector of four chunks per GPU. The all-reduce runs in two phases, as the ring of Chapter 3 does.

Look at the all-reduce. After its first phase each GPU holds one summed chunk: that is a reduce-scatter. After its second phase every GPU holds all four: that is an all-gather. So:

all-reduce = reduce-scatter, then all-gather

The lecture stresses this identity. In the bandwidth-limited regime, the two halves together cost the same as the best all-reduce. ZeRO in Chapter 5 uses it to shard optimizer state for free.

Count the bytes. Call the full vector S bytes. In a reduce-scatter on N GPUs, each GPU ends up owning S / N bytes of sum. To get it, it receives the other GPUs' copies of its piece: (N − 1) / N × S bytes. An all-gather moves the same amount the other way.

For S = 140 GB of gradients on 4 GPUs, a reduce-scatter receives 105 GB per GPU. The all-gather receives another 105 GB. The all-reduce costs 210 GB per GPU.

Symptom: a training job hangs forever at the first gradient sync.

Measure: check that every rank reaches the same collective, in the same order, with the same tensor size.

Fix: remove any rank-dependent branch around a collective. One rank that skips an all-reduce leaves the others waiting.

Four GPUs each hold a full gradient. Afterwards, GPU 2 should hold only the sum of chunk 2. Which collective is that?

Chapter 3

Ring All-Reduce

Pass chunks around a ring step by step, and derive why each GPU sends about twice the data no matter how many GPUs join

The simple all-reduce sends every vector to one GPU, sums, and sends the sum back. With 64 GPUs and 140 GB of gradients, that GPU receives 63 × 140 = 8,820 GB. Every other GPU waits on it.

The ring all-reduce shares the work. Put the N GPUs in a circle. Cut each GPU's vector into N chunks. At every step, each GPU sends one chunk to its right neighbour and receives one from its left.

Pass chunks around a ring

Each GPU holds N chunks. A number says how many GPUs' values the chunk holds; N means fully summed. Press Step, or Play.

4

The algorithm is exact; we draw the chunks the same size. We checked it with a short simulation: on 4 GPUs every one sends 12 of 8 × 4 elements, as the formula says.

Phase one is a reduce-scatter. After N − 1 steps, each GPU holds one chunk summed over all N. Phase two is an all-gather: N − 1 more steps pass the finished chunks around. Each step sends S / N bytes, so each GPU sends 2 (N − 1) × S / N in all.

Name the pieces. Call the vector's size S bytes, the number of GPUs N, and each link's one-way bandwidth β. Every link is busy at every step, so the time is:

Say it aloud

T equals two, times N minus one over N, times S over beta.

T
T the all-reduce time, bandwidth part only.
2
two the two phases: reduce-scatter, then all-gather.
(N − 1) / N
N minus one over N the share of the vector each GPU must receive in one phase: all but its own chunk.
S
S the vector's size in bytes.
β
beta the one-way bandwidth of each GPU's link.
In plain words

Each phase moves all of S except the GPU's own chunk, so (N − 1) / N of S. Two phases double it. Divide by the bandwidth β.

With numbers

S = 140 GB of bf16 gradients for 70B parameters. N = 8 over NVLink at 450 GB/s: T = 2 × 7/8 × 140 / 450 = 0.544 s. N = 64 over 50 GB/s: T = 2 × 63/64 × 140 / 50 = 5.51 s.

The factor 2 (N − 1) / N is 1.5 at N = 4, 1.75 at 8 and 1.97 at 64. It never passes 2. Adding GPUs barely changes what each one sends. NCCL turns this into its bus bandwidth: the measured rate times 2 (N − 1) / N, compared directly with the hardware's β.

Symptom: one all-reduce at 64 GPUs takes 11 s, not the 5.5 s you planned.

Measure: run nccl-tests and read the bus bandwidth. Compare it with the link: 25 GB/s means the ring runs on HDR, not 400 Gb/s.

Fix: check that each GPU uses its own network card, and that the ring does not cross a slow link twice.

A ring all-reduce runs on 8 GPUs, a 10 GB vector, and 25 GB/s links. About how long does it take?

Chapter 4

Data Parallelism

Copy the model to every GPU, split the batch, average the gradients, and hide the all-reduce behind the backward pass

Data parallelism is the first split. Every GPU holds the whole model. Each takes a different slice of the batch, runs forward and backward on it, and gets its own gradient. Then the GPUs average their gradients, and every GPU takes the same optimizer step.

Call the number of GPUs N, the gradient GPU i computed on its slice gi, the weights θ, and the learning rate η. The update is:

Say it aloud

Theta-prime equals theta, minus eta times one over N times the sum over i of g-i.

θ′
theta-prime the weights after the step, the same on every GPU.
θ
theta the weights before the step.
η
eta the learning rate.
1/N
one over N divide by the number of GPUs, to get an average.
Σi
the sum over i add one term per GPU. The all-reduce computes this sum.
gi
g-i GPU i's gradient, the mean over its slice of the batch.
In plain words

All-reduce the gradients g-i, so every GPU holds their sum. Divide by N. Step every copy of θ by η times that average.

With numbers

With made-up numbers: four GPUs get g = 0.8, 1.2, 0.6 and 1.4 for one weight. The average is 1.0. With θ = 0.5 and η = 0.1, every GPU sets θ′ = 0.4. With equal slices this equals the gradient of the whole batch (we checked on a linear model).

The lecture scores it on three counts. Compute scales: each GPU does B / N of the examples. Communication is one all-reduce, about 2Ψ values per step, fine if batches are large. Memory does not scale at all: every GPU keeps the full 16 bytes per parameter.

PyTorch's DistributedDataParallel (DDP) hides the all-reduce. Backward makes the last layer's gradients first. DDP groups gradients into buckets, 25 MB by default, and starts each bucket's all-reduce as soon as it is full. The network works while backward continues on earlier layers.

Hide the all-reduce in backward

Top row: backward, one block per layer, last layer first. Bottom row: that layer's gradient all-reduce. Turn overlap on, then drag the communication time.

8 ms

Illustrative: 12 layers, 10 ms of backward each, one bucket per layer. Real DDP fills buckets by size, not by layer.

With 8 ms of all-reduce per 10 ms layer, serial sync takes 216 ms; overlapped, 128 ms. Only the last bucket's 8 ms sticks out. Once the all-reduce per layer is longer than its backward, the network sets the pace.

Symptom: doubling the GPUs adds almost no throughput.

Measure: in a profiler trace, look for all-reduce blocks after backward ends. Compare their length with the backward time.

Fix: raise the batch per GPU or accumulate gradients over several microbatches, so each sync buys more compute.

Eight GPUs run plain data parallelism on a batch of 8,192 examples. What does each GPU hold?

Chapter 5

ZeRO: Shard the Training State

Give each GPU one slice of the optimizer state, then of the gradients, then of the weights, and price each stage in memory and traffic

Data parallelism stores the same optimizer state N times. ZeRO, the Zero Redundancy Optimizer (Rajbhandari et al., 2019), removes the copies. It cuts each per-parameter tensor into N slices and gives GPU i slice i.

Stage 1 shards the optimizer state. Each GPU computes a full gradient. A reduce-scatter gives GPU i the summed gradient for slice i only. GPU i updates its slice with its own Adam state. An all-gather sends the new weights to everyone. By Chapter 2's identity, this costs the same 2Ψ as the all-reduce.

Shard the state, then take a step

Four GPUs, each with three rows: weights, gradients, optimizer state. A filled cell is a slice the GPU keeps. Pick a stage, then press Step to walk through one update.

Four GPUs drawn; the read-out prices a 70B model on 64 GPUs. Memory is the ZeRO paper's formulas with K = 12, activations not counted. Traffic in units of Ψ values per GPU, from the paper and the lecture.

Stage 2 also shards the gradients. During backward, each layer's gradient goes into a reduce-scatter as soon as it exists, and each GPU frees the parts it does not own. Stage 3 shards the weights too, so each GPU holds 1/N of everything. Call the GPU count N; the memory per GPU at stage 3 is:

Say it aloud

M-GPU equals two plus two plus K, times psi, over N.

MGPU
M-GPU the training state each GPU keeps, in bytes.
2 + 2 + K
two plus two plus K the 16 bytes per parameter of Chapter 0: weight, gradient, optimizer state (K = 12).
Ψ
psi the number of parameters.
N
N the number of GPUs sharing the state.
In plain words

Take the full training state, 16 bytes times Ψ. Divide it by the N GPUs. Stages 1 and 2 divide only some terms; stage 3 divides all of them.

With numbers

The ZeRO paper's example: Ψ = 7.5 × 109, N = 64. Data parallel 120 GB, stage 1 31.4 GB, stage 2 16.6 GB, stage 3 1.9 GB. For 70B on 64 GPUs: 1,120, 293, 155 and 17.5 GB.

stage 1: (2 + 2) Ψ + K Ψ / N  ·  stage 2: 2 Ψ + (2 + K) Ψ / N  ·  stage 3: (2 + 2 + K) Ψ / N

Stage 3 pays for its memory in traffic. Each GPU gathers the weights before forward and again before backward, then reduce-scatters the gradients: 3Ψ values, 1.5 times data parallelism. The lecture's verdict: stage 1 is free, stage 2 nearly free, stage 3 costs 1.5 times. On 8 H100s, the largest model goes from 5B (data parallel) to 14.5B, 21.3B and 40B.

Symptom: ZeRO-1 on 64 GPUs still runs out of memory for a 70B model.

Measure: stage 1 keeps full weights and gradients: 4 × 70 = 280 GB, plus 13 GB of state.

Fix: go to stage 3, or combine stage 1 with tensor or pipeline parallelism, which split the weights (Chapter 9).

Why can ZeRO stage 1 save memory without adding traffic?

Chapter 6

FSDP: Fetch Each Layer Just in Time

Gather one layer's weights, use them, free them, and prefetch the next layer so the network works while the GPU computes

Stage 3 sounds impossible: a GPU cannot multiply by weights it does not hold. The trick is to hold them only briefly. PyTorch's FSDP, Fully Sharded Data Parallel (Zhao et al., 2023), wraps each block of the model, such as one Transformer layer.

  1. Before a block's forward, all-gather its weights from every GPU's slice.
  2. Run the block's forward. Free the gathered weights.
  3. In backward, all-gather the block's weights again and compute its gradients.
  4. Reduce-scatter the gradients, so each GPU keeps only its slice. Free the rest.

So a GPU holds its 1/N slice of everything, plus one or two full blocks at a time. Take 70B parameters in 80 layers on 64 GPUs. Each GPU keeps a 17.5 GB slice, plus 1.75 GB for one bf16 layer, or 3.5 GB with the next one prefetched.

Prefetch the next layer

Top two rows: compute and communication for four layers, forward then backward. Bottom: the GPU's memory over time. Turn prefetch on and off, and drag the gather time.

6 ms

Illustrative: 4 layers, 10 ms forward and 20 ms backward each, reduce-scatter equal to the gather. Memory counts full layers of gathered weights and of unsharded gradients, on top of the GPU's slice.

Without prefetch, the GPU idles during every gather. With prefetch, the gather for layer i + 1 runs during layer i's compute. With 6 ms gathers and 10 ms layers, the step drops from 192 ms to 132 ms, against 120 ms of pure compute. The price is one extra layer held in memory. The lecture's figure from the FSDP paper shows the same: all-gathers queued during forward, masking the cost.

FSDP has a setting for each stage. FULL_SHARD shards weights, gradients and optimizer state: stage 3. SHARD_GRAD_OP shards gradients and optimizer state during compute, like stage 2. NO_SHARD is plain data parallelism. HYBRID_SHARD shards inside a server and copies across servers, keeping the gathers on NVLink.

Symptom: FSDP on 64 GPUs reaches half the throughput of the same model with DDP on fewer, larger GPUs.

Measure: one gather of a 1.75 GB layer over 50 GB/s takes 34.5 ms. Compare it with that layer's compute time.

Fix: raise the tokens per GPU so compute covers the gather, wrap larger blocks, or use HYBRID_SHARD.

With FSDP's full sharding, which collectives run in one training step?

Chapter 7

Tensor Parallelism

Split each matrix across GPUs, pair a column split with a row split, and count the bytes per layer

ZeRO moves weights. Model parallelism keeps each weight on one GPU and moves activations. Tensor parallelism cuts every matrix along the model's width.

A matrix product Y = XW splits two ways. Split W by columns: each GPU computes its own columns of Y, with no communication. Split W by rows and X by columns: each GPU computes a partial Y, and an all-reduce adds them.

Megatron-LM (Shoeybi et al., 2019) chains them in the MLP. It cuts the first matrix A by columns, so each GPU applies GeLU to its own columns. It cuts the second matrix B by rows, so B takes those columns directly. One all-reduce at the end gives the full output. The lecture's hooks: in forward, f is the identity and g the all-reduce; in backward, the reverse.

Split the MLP across GPUs

Left to right: the input X, matrix A in column blocks, matrix B in row blocks, and the summed output. Drag the GPU count t, then move the group across servers.

8

Times are for one layer of a 405B-size model, forward and backward: width 16,384, one sequence of 8,192 tokens, bf16, at the link's one-way bandwidth. Compute is the layer's matmul FLOPs at 40% of the H100's dense peak, attention scores not counted. Our estimates, not measurements.

Each layer has two such pairs, in attention and in the MLP: 2 all-reduces forward, 2 backward. Each sums an activation of b sequences, s tokens and width h. Call the tensor-parallel GPU count t. With the ring of Chapter 3, the values each GPU sends per layer are:

Say it aloud

V equals eight b s h, times t minus one over t.

V
V the values each GPU sends per layer, forward and backward together.
8
eight four all-reduces (2 forward, 2 backward), each costing 2 of the ring's phases.
b s h
b s h the activation's size: b sequences times s tokens times width h.
(t − 1) / t
t minus one over t the ring's share, for t GPUs.
In plain words

Each of the 4 all-reduces moves 2 (t − 1) / t times b s h. Four of them make V. Multiply by 2 for bf16 bytes.

With numbers

Take b = 1, s = 8,192, h = 16,384 and t = 8. V = 8 × 1.34 × 108 × 7/8 = 9.4 × 108 values, or 1.88 GB. That takes 4.2 ms over NVLink and 37.6 ms over 400 Gb/s. The layer's compute is about 50 ms.

This traffic sits mid-layer, so it cannot hide behind backward like DDP's. The lecture's rule: tensor parallelism inside a server, up to 8 GPUs, on NVLink. In return: no bubble, no need for a large batch, and sharded activations inside each block.

Symptom: each step runs slower at t = 16 than at t = 8.

Measure: at 16 the group spans two servers, so each all-reduce drops from 450 to 50 GB/s.

Fix: keep t at 8 or less; fit the model with pipeline stages or ZeRO across servers.

In Megatron's MLP, the first matrix is split by columns and the second by rows. Why that order?

Chapter 8

Pipelines and the Bubble

Give each GPU a run of layers, feed microbatches through, and measure the idle time at the start and end of every step

The other cut is along depth. Give GPU 1 the first quarter of the layers, GPU 2 the next quarter, and so on. Each GPU sends its output activation to the next one: a single point-to-point message of b s h values. That is cheap enough for the network between servers.

Done naively it wastes almost everything. GPU 2 waits for GPU 1's forward; GPU 1 waits for everyone's backward. With p GPUs, each one works 1/p of the time. The fix is pipeline parallelism (GPipe, Huang et al., 2019). Cut the batch into microbatches and send them in one after another, so the stages overlap.

Fill the pipeline

Rows are stages, time runs right. Teal blocks are forward passes, purple are backward, red are idle. Drag the stages and the microbatches.

4
8

GPipe's schedule: all forwards, then all backwards; backward drawn twice as long as forward. Communication time is not drawn. The ratio is exact for this schedule.

The idle wedges are the bubble. At the start, stage p waits p − 1 forward steps; at the end, stage 1 waits p − 1 backward steps. Call the stages p and the microbatches per step m. Narayanan et al. (2021) give the bubble's size against the useful work:

Say it aloud

The bubble equals p minus one, over m.

bubble
bubble idle time divided by useful compute time, per stage.
p − 1
p minus one the steps it takes to fill the pipe, and to drain it. p is the number of stages.
m
m the microbatches in one step.
In plain words

Filling and draining cost p − 1 microbatch times. The useful work is m microbatch times. Divide the first by the second.

With numbers

p = 16 and m = 64: bubble = 15 / 64 = 0.23. The idle share of the whole step is 15 / (64 + 15) = 19%. With m = 16 the ratio is 0.94: almost half the step idles.

So pipelines need many microbatches, which means a large batch. GPipe found the bubble negligible when m is at least 4p. The lecture's case for pipelines anyway: they split memory, and they send only activations, point to point. So they go on the slow links between servers. Smarter schedules and the "zero bubble" trick are in Lecture 8.

Symptom: adding pipeline stages lowers the FLOP/s of every GPU.

Measure: compute (p − 1) / m for your batch. At p = 8 and m = 8 it is 0.875.

Fix: raise m to 4p or more, with gradient accumulation if the batch per step is fixed.

A pipeline has 8 stages. How many microbatches does it need for a bubble ratio near 0.2?

Chapter 9

Showcase: Plan a 3D Run

Combine tensor, pipeline and data parallelism, then check memory, link speed and the bubble for real published runs

Large runs use all three splits at once: 3D parallelism. Each GPU belongs to a tensor group of t GPUs, a pipeline of p stages and a data-parallel group of d copies. The three are independent, so the GPU count multiplies:

Say it aloud

N equals t times p times d.

N
N the total number of GPUs.
t
t the tensor-parallel size: GPUs that share each matrix, inside a server.
p
p the pipeline stages: GPUs that share the layers.
d
d the data-parallel size: copies of the whole t × p model.
In plain words

Build one model copy from t times p GPUs. Make d copies. Multiply the three to count the GPUs.

With numbers

Llama 3 405B (Table 4 of its paper): t = 8, p = 16, d = 128, so N = 16,384 H100s. Megatron's 1-trillion run (Narayanan et al.): 8 × 64 × 6 = 3,072 A100s.

The lecture's rules of thumb come from Narayanan et al. Use tensor parallel up to the GPUs in one server. Use pipeline parallel across servers until the model fits (or ZeRO-3, if bandwidth allows). Use data parallel for the rest. Their 1-trillion run reached 502 petaFLOP/s, 52% of the A100's peak per GPU.

Plan a 3D run

Top: one model copy, its GPUs grouped by server, each filled to its memory use. Bottom: memory per GPU against 80 GB, and each split's cost. Load a published run, then change the sizes.

8
16
128

Shapes from the papers: Llama 3 405B has width 16,384, 126 layers and 8,192 tokens; Megatron 1T has width 25,600, 128 layers and 2,048 tokens. The 70B sketch is ours: width 8,192, 80 layers, 4,096 tokens. Memory counts 16 bytes per parameter, no activations. We set m = 4p microbatches of one sequence; the papers' schedules differ. Times are one-way-bandwidth bounds, not measurements.

Things to try. Load Llama 3 405B: 13 GB of state per GPU with ZeRO-1, and tensor parallelism stays on NVLink. Turn ZeRO-1 off: 50.6 GB. Push t to 16: the tensor group crosses servers, and each layer's all-reduce takes about 10 times longer. Drop p to 1: the model no longer fits.

Check yourself. Load Megatron 1T and predict its memory per GPU before you look: 1012 parameters over 8 × 64 GPUs, with ZeRO-1 over 6 copies. It is 11.8 GB.

Chapter 10

Field Guide

Keep the cost model, the plan in code, and the order of checks for a run that will not fit

Training state is 16 bytes per parameter. Each split trades that memory for traffic. Data parallelism and ZeRO-1 cost 2Ψ per step; ZeRO-3 costs 3Ψ. Tensor parallelism costs 8 b s h (t − 1) / t values per layer and belongs on NVLink. Pipelines cost a bubble of (p − 1) / m and belong between servers.

SplitWhat it shardsTrafficLinkCatch
Data parallel (DDP)the batch2Ψ per step, one all-reduceany; overlaps backwardmemory does not scale
ZeRO-1+ optimizer state2Ψ (reduce-scatter + all-gather)anyweights and gradients still full
ZeRO-2+ gradients2Ψanyweights still full
ZeRO-3 / FSDP+ weights3Ψfast, or hybridgathers every layer; activations not sharded
Tensor paralleleach matrix, and activations inside blocks8 b s h (t − 1) / t per layerNVLink, t ≤ 8sync in the middle of every layer
Pipeline parallelthe layersb s h per microbatch, point to pointbetween serversbubble (p − 1) / m; needs a large batch

The cost model in code. We ran it; the comments are its output.

python
NVLINK, NET = 450e9, 50e9        # H100 NVLink and 400 Gb/s, bytes/s each way

def ring_allreduce(S, N, beta):    # seconds, bandwidth part
    return 2 * (N - 1) / N * S / beta

def zero_bytes(psi, N, stage, K=12):   # training state per GPU
    return {0: (4 + K) * psi, 1: (4 + K / N) * psi,
            2: (2 + (2 + K) / N) * psi, 3: (4 + K) * psi / N}[stage]

def tp_bytes_per_layer(b, s, h, t):   # bf16, forward + backward, per GPU
    return 8 * b * s * h * (t - 1) / t * 2

def bubble(p, m):
    return (p - 1) / m

print(ring_allreduce(140e9, 64, NET))                   # 5.51 s
print([zero_bytes(70e9, 64, k) / 1e9 for k in range(4)])   # [1120.0, 293.1, 155.3, 17.5]
v = tp_bytes_per_layer(1, 8192, 16384, 8)
print(v / NVLINK, v / NET)                              # 0.0042 s, 0.0376 s
print(bubble(16, 64))                                  # 0.234
print(zero_bytes(405e9 / (8 * 16), 128, 1) / 1e9)         # 13.0 GB: Llama 3 405B, ZeRO-1

activations per layer (Korthikanti et al., 2022): s b h (34 + 5as/h) bytes; with t-way tensor parallelism, s b h (10 + 24/t + 5as/(h t)); a = attention heads

ZeRO does not shrink activations. Tensor parallelism shrinks the part inside each block. Recomputing activations in backward trades compute for the rest (Lecture 8).

When a run will not fit, check in this order. First, 16 bytes times Ψ against the total memory: the floor on GPUs. Second, switch on ZeRO-1, which is free. Third, tensor parallel up to 8 inside a server. Fourth, pipeline stages until the state fits, with m ≥ 4p. Last, spend the remaining GPUs on data parallelism.

Keep going

Read next

The habit. Before you pick a split, write two numbers: the bytes it must send per step, and the link it will send them on. Put the chattiest split on the fastest link.
A 3D plan uses t = 8, p = 16, d = 4. How many GPUs does it need?

Now teach it: press Present or Teach. Derive the ring's 2 (N − 1) / N, price the three ZeRO stages, and say why tensor parallelism stays inside a server. Then go back to the instrument and predict, before you drag, the fewest GPUs on which ZeRO-3 fits 70B under 80 GB.

Parallelism I: Data & Tensor · Stanford CS336, Lecture 7
Previous: Kernels and Triton · Next: Parallelism II · Course site · Back to Gleams