Lecture 23 · Parallelization: Training Across Many Chips

Deep Unsupervised Learning · Lecture 23。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 12b · Thu 4/11/2024 · Parallelization in Transformers. That is the last part of the L12 deck (slides 49–74), which repeats the closing “Sharding” section of the L8 guest lecture (Hao Liu, slides 110–137). It covers:

  • Hardware: TPU / GPU basics (FLOP/s, HBM size and bandwidth, interconnect) and GEMM on GPUs vs TPUs (systolic arrays).
  • Sharding layers: matrix-multiply sharding (rows vs columns), the MLP and attention sharded Megatron-style with the f / g operators.
  • Training schemes: data parallelism, fully sharded data parallelism (FSDP), tensor parallelism, FSDP + TP, with the slides’ arithmetic-intensity rules.
  • Practical guidelines.

Basis: Megatron-LM (Shoeybi et al., 2019), the “Sharding Techniques” notes the slides cite (Rafi W.), ZeRO / FSDP, and the roofline model.

  • Hardware numbers: taken from vendor datasheets and the TPU v4 paper. The interconnect figure for TPU v5e is the one implied by the slides’ “1018 FLOPs/byte”.
  • The code: it simulates devices in numpy. Every collective is a real ring algorithm that counts the elements it sends, and every parallel training scheme reproduces single-device training to ~1e-16.

Code: code/lecture23/ (4 scripts + parallel.py; numpy only; every script runs in seconds) Reading time: 2.5 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Hardware. Read a chip’s datasheet as peak FLOP/s, memory size, memory bandwidth and interconnect bandwidth. Compute arithmetic intensity and decide, with the roofline, whether a kernel is compute- or memory-bound.
  2. Collectives. Explain the three collectives (all-reduce, reduce-scatter, all-gather), their ring algorithms, and their cost of about 1×1\times or 2×2\times the message per device.
  3. Sharding. Shard a matrix multiply, an MLP and attention across devices, and say which splits need communication (Megatron’s f and g).
  4. Training schemes. Derive the memory and communication of data parallelism, FSDP, tensor parallelism and FSDP + TP. Apply the slides’ rules (batch per chip > ~1018 for FSDP, E/nTPE/n_{TP} > ~1018 for TP) to choose a configuration.

0.2 Prerequisites and scope

AssumedIntroduced hereElsewhere
Lecture 4 (Transformers: attention, MLP blocks)roofline, arithmetic intensity, systolic arraysLecture 16 (KV caches and bandwidth-bound decoding; blockwise and ring attention; MoE)
Lecture 16 (scaling laws; 6ND training FLOPs)collectives and their costs; DP, TP, FSDP, FSDP + TP
Backpropagation for an MLPMegatron’s f / g operators; memory accounting for GPT-3

The slides do not cover pipeline parallelism, sequence parallelism or expert parallelism. They are mentioned in §7 only.

0.3 Map

§1  why parallelize: GPT-3's memory and compute
§2  the hardware: FLOP/s, bandwidth, the roofline, systolic arrays          ← code 01
§3  collectives: all-reduce, reduce-scatter, all-gather                       ← code 02
§4  sharding a matmul, an MLP, attention (Megatron's f and g)                ← code 03
§5  training: DP, TP, FSDP, FSDP + TP -- same mathematics, different traffic ← code 04, Part 1
§6  choosing a configuration: memory and the arithmetic-intensity rules      ← code 04, Parts 2-3
§7  practical guidelines; what the slides leave out
§8 summary   §9 pitfalls   §10 exercises   §11 further reading   §12 next lecture

0.4 Notation

symbolmeaning
nnthe number of devices (chips)
EEthe model width dmodeld_{\text{model}}
BBtokens per chip (the slides’ BATCH_PER_CHIP)
PPthe number of parameters

Bytes assume bf16 (2 bytes per number) unless said otherwise. “Elements sent” counts the numbers one device sends; multiply by 2 for bf16 bytes.


1. Why parallelize?

Two numbers settle the question for GPT-3: 175B parameters, trained on 300B tokens.

Memory. At 4 bytes per parameter the weights alone take 700 GB (slide 65). An A100 or H100 has 80 GB. Training needs more:

itembytes per parameter
bf16 weights2
bf16 gradients2
fp32 master weights and Adam’s two moments12
total16

That is 2.8 TB per copy of the model (script 01), before any activations.

Compute. Training costs about 6PD6PD FLOPs (Lecture 16): 6×175×109×300×109≈3.2×10236 \times 175 \times 10^9 \times 300 \times 10^9 \approx 3.2 \times 10^{23}. One A100 at its peak bf16 rate (312 TFLOP/s) would need 10910^9 seconds, i.e. 32 years. Even a thousand chips at 50% utilization need weeks.

So we need many chips. The question of this lecture is how to split the work so that the chips compute, rather than wait for each other.


2. The hardware

2.1 What a chip offers (slide 50)

Four numbers describe a chip for our purposes:

  1. peak FLOP/s;
  2. the size of its high-bandwidth memory (HBM);
  3. HBM bandwidth;
  4. the bandwidth of the interconnect to other chips (NVLink, or the TPU’s inter-chip interconnect, ICI).

Script 01, Part 1:

chipbf16 TFLOP/sHBM GBHBM TB/sFLOP per HBM byteFLOP per interconnect byte
A100 SXM 80GB312802.041531040
H100 SXM 80GB989803.352952198
TPU v427534 (32 GiB)1.20229—
TPU v5e197160.822411018

The last two columns are the key ratios. A chip can do hundreds of FLOPs in the time it reads one byte from its own memory, and about a thousand per byte that arrives from another chip. The slides’ “1018 FLOPs/byte” is the TPU v5e’s peak divided by its interconnect bandwidth.

The NVLink figures (300 / 450 GB/s per direction) are half of NVIDIA’s bidirectional totals. Compute is cheap; moving data is expensive, and every design below follows from that.

2.2 Arithmetic intensity and the roofline

A kernel’s arithmetic intensity II is its FLOPs divided by the bytes it moves. A chip with peak Π\Pi and bandwidth β\beta can sustain at most FLOP/s≤min⁡(Π,  I⋅β).\text{FLOP/s} \le \min(\Pi,\; I \cdot \beta). This is the roofline: a slanted roof (bandwidth-bound) up to the ridge point I∗=Π/βI^* = \Pi/\beta, then a flat roof (compute-bound).

For a matrix multiply CM×N=AM×KBK×NC_{M \times N} = A_{M \times K} B_{K \times N}, the FLOPs are 2MNK2MNK and the bytes are 2(MK+KN+MN)2(MK + KN + MN) in bf16.

  • Square matrices (n×nn \times n times n×nn \times n): I=n/3I = n/3. That is 43 for n=128n = 128 and 2,731 for n=8192n = 8192. Big square matmuls are compute-bound on every chip.
  • A weight matrix applied to BB tokens (a linear layer, M=B≪K=N=EM = B \ll K = N = E): the weights dominate the bytes, so I≈2BE2/2E2=BI \approx 2BE^2 / 2E^2 = B. For E=12,288E = 12{,}288 the intensity is 1, 16, 125, 878 for BB = 1, 16, 128, 1024.

On an H100 a layer is memory-bound until about 300 tokens share each weight read (153 on an A100, about 240 on TPUs). This one fact explains two things:

  • Training uses large batches.
  • Generating one token at a time is bandwidth-bound (Lecture 16).

Measured on this computer (script 01, Part 3, numpy float32 on the machine that ran the scripts; timings vary run to run):

casemeasured
matrix-matrix products, nn = 1024–81922.0–2.7 TFLOP/s
matrix-vector product, nn = 1024 (4 MB, fits in cache)169 GFLOP/s, i.e. 338 GB/s effective
matrix-vector product, nn = 8192 (256 MB, from DRAM)78 GFLOP/s, i.e. 156 GB/s

Matrix-vector products sit at intensity 0.5. While the matrix fits in the chip’s caches, they run above the DRAM roof: caches are a higher, smaller roof, the same reason FlashAttention keeps tiles in SRAM (Lecture 16).

2.3 GEMM units: many small or few large (slide 51)

GPUs have many small matrix units; the slides’ cartoon shows 8×4×8 tensor-core operations. TPUs have a few large systolic arrays: a TPU v4 TensorCore has four 128 × 128 arrays.

In a weight-stationary systolic array:

  • each cell holds one weight;
  • inputs stream in from the left, skewed by one cycle per row;
  • every cell multiplies, adds the partial sum from above, and passes data to its right and bottom neighbours.

There are no long wires and no memory reads inside the array. That is why such an array packs 16,384 multiply-accumulates into one unit.

Script 01, Part 4 simulates one cycle by cycle. The result equals X @ W to 10−1510^{-15}. The array is busy only when many rows stream through: utilization is T/(T+2k−2)T/(T + 2k - 2), which gives 40% for 4 rows through a 4 × 4 array and 97% for 512 rows through an 8 × 8 one. Matrix units want big matrices.


3. Collectives

Every parallel scheme is a pattern of three operations among nn devices that each hold an array of MM numbers.

collectivebeforeafterring cost per device
all-reduceeach device holds its own arrayevery device holds the sum2n−1nM2\frac{n-1}{n}M
reduce-scattereach device holds its own arraydevice ii holds piece ii of the sumn−1nM\frac{n-1}{n}M
all-gatherdevice ii holds piece iievery device holds all piecesn−1nM\frac{n-1}{n}M

The ring algorithms. Arrange the devices in a ring and cut each array into nn chunks.

  • Reduce-scatter takes n−1n - 1 steps. In each, every device sends one chunk’s running sum to its neighbour, which adds its own copy of that chunk. After n−1n - 1 steps, device ii holds the complete sum of chunk ii.
  • All-gather forwards finished chunks around the ring in the same way.
  • All-reduce = reduce-scatter + all-gather.

Each device sends (n−1)/n(n - 1)/n of the array per phase, under one array whatever nn is. The naive alternative, where everybody sends to device 0 and device 0 sends the sum back, makes device 0 send (n−1)(n - 1) arrays.

Script 02 (1M-element arrays). Elements sent by the busiest device, as a multiple of MM:

devicesringnaivering steps
41.50036
81.750714
321.9383162

Results are exact up to the order of additions (10−1410^{-14}).

Latency vs bandwidth. A time model with latency α\alpha per step and bandwidth β\beta gives: Tring=2(n−1)α+2n−1nMβ.T_{\text{ring}} = 2(n - 1)\alpha + 2\tfrac{n-1}{n}\tfrac{M}{\beta}.

  • Small messages are latency-bound. With 1 KB on 512 devices, the ring takes 5.1 ms of pure latency, while the naive algorithm’s 2 steps take 0.02 ms. Libraries switch to tree algorithms for small messages.
  • Large messages are bandwidth-bound, and the time is nearly independent of nn. With 10 GB, the ring takes 175 ms on 8 devices and 205 ms on 512 (at α\alpha = 5 µs, 100 GB/s).

What it means for GPT-3. All-reducing its 350 GB of bf16 gradients once per step takes 2.3 s over A100 NVLink. At 3.2M tokens per step on 1,024 chips, that is about a fifth of the ideal compute time (10.5 s), and it can overlap with the backward pass. Communication is not what kills pure data parallelism; memory is (§6).


4. Sharding a matmul, an MLP, attention

4.1 One matrix multiply (slides 52–59)

Take Y=XAY = XA with XX of size B×dB \times d and AA of size d×fd \times f. There are three ways to split it:

  • (a) Split the contraction dimension. Shard AA by rows and XX by columns. Each device computes XiAiX_i A_i, a partial sum of the whole output, which must be all-reduced (or reduce-scattered if a sharded output is fine).
  • (b) Split the output dimension. Shard AA by columns and replicate XX. Each device computes some columns of YY, and no communication is needed.
  • (c) Split the batch. Shard XX by rows and replicate AA. This is data parallelism; no communication is needed in the forward pass.

Script 03, Part 1: all three equal XAXA to 10−1410^{-14}. Without the all-reduce, a device’s partial product in case (a) is off by up to 28.7.

4.2 The MLP (slides 60–61)

For Y=GELU(XA)BY = \mathrm{GELU}(XA)B there are two approaches.

Approach 1: split XX by columns and AA by rows. The pre-activations are then partial sums, and GELU(a+b)≠GELU(a)+GELU(b)\mathrm{GELU}(a + b) \neq \mathrm{GELU}(a) + \mathrm{GELU}(b) (1.955 vs 1.682 at a=b=1a = b = 1). So the devices must all-reduce the B×fB \times f pre-activations before the GELU. Skipping that gives an output off by up to 12.9.

Approach 2 (Megatron): split AA by columns, so each device owns some hidden units and applies the GELU to them locally. Then split BB by the matching rows, so each device computes a partial sum of the output. A single all-reduce of the B×dB \times d output finishes the block. Here that moved 4× less data than approach 1 (d=f/4d = f/4).

4.3 Backward: the f and g operators (slide 61)

Megatron writes approach 2 as   f→[local GELU MLP]→g\;\mathrm{f} \to [\text{local GELU MLP}] \to \mathrm{g}, with two conjugate operators:

  • g\mathrm{g}: all-reduce in the forward pass (sum the partial outputs); identity in the backward pass. The output gradient is the same on every device.
  • f\mathrm{f}: identity in the forward pass (the input is replicated); all-reduce in the backward pass. Each device has only a partial gradient with respect to the input, ∂L/∂X=∑iδiAi⊤\partial L/\partial X = \sum_i \delta_i A_i^\top.

Weight gradients never leave their device. Script 03, Part 3 checks every gradient against the single-device one: ∂L/∂A\partial L/\partial A and ∂L/∂B\partial L/\partial B match exactly, ∂L/∂X\partial L/\partial X to 10−1410^{-14}.

4.4 Attention (slides 62–63)

Attention’s softmax is a nonlinearity per head, so attention is split by heads:

  • WQW_Q, WKW_K, WVW_V by columns (each device gets whole heads);
  • WOW_O by rows;
  • one all-reduce of the S×dS \times d output.

With 8 heads on 4 devices (2 per device), script 03 matches full attention to 10−1510^{-15}.

4.5 The cost of a tensor-parallel Transformer layer (slide 71)

A layer needs 4 all-reduces of a B×EB \times E activation per training step: attention and MLP, forward and backward.

The slides compute the arithmetic intensity for one E×EE \times E matmul whose B×EB \times E output is reduce-scattered: 2BE2/nTP2BE=EnTP.\frac{2BE^2/n_{TP}}{2BE} = \frac{E}{n_{TP}}.

A whole layer has a constant factor more: about 4.5 E/nTP4.5\,E/n_{TP} in script 03, Part 5. Either way, tensor parallelism pays only for wide layers split few ways. For E=12,288E = 12{,}288 split 64 ways, the intensity falls to 878 FLOP/byte, below the interconnect’s ~1,000.


5. Training in parallel: same mathematics, different traffic

Script 04 trains one model (4 residual MLP blocks, d=64d = 64, hidden 256, 131,136 parameters, batch 256, 30 SGD steps) five ways on 8 simulated devices:

schemefinal lossmax |param − single device|elements sent per stepparams heldactivations stored
one device0.099742—0131,136589,824
data parallel0.0997425.6e-17229,488131,13673,728
tensor parallel (Megatron)0.0997426.9e-17229,37616,448131,072
FSDP0.0997425.6e-17344,17649,16073,728
FSDP × TP (2 × 4 mesh)0.0997421.1e-16131,13616,416 (+32,832 gathered)—

All five compute the same thing. The parameters agree to 10−1610^{-16}. Parallelism changes where numbers live and what is communicated, never the mathematics. That is also the test every real implementation must pass.

Data parallelism (slides 64–65).

  • Layout: each device keeps all parameters and processes 1/n1/n of the batch.
  • Communication: the gradients are all-reduced, 2n−1nP2\frac{n-1}{n}P per step (229,488 here). Each device stores 1/n1/n of the activations.
  • Scaling: the speedup is linear “as long as you scale batch linearly” (slide 64).
  • Limit: memory. Every device holds the whole model and its optimizer state.

Tensor parallelism (slides 69–71).

  • Layout: each device keeps 1/n1/n of every block (Megatron split) and sees the whole batch.
  • Communication: 2 all-reduces of the batch’s activations per block per step (229,376 here). This volume is independent of the number of parameters and grows with the batch.
  • Memory: activations are replicated, so each device stores more of them than under DP.

FSDP / ZeRO-3 (slides 66–68).

  • Layout: each device keeps 1/n1/n of every parameter (and of its gradient and optimizer state) and processes 1/n1/n of the batch.
  • Forward pass: before each layer, the layer’s weights are all-gathered, used, and freed.
  • Backward pass: the weights are all-gathered again, the local gradients are reduce-scattered (each device receives the summed gradient of exactly the piece it owns), and each device updates its piece.

Communication is 3n−1nP3\frac{n-1}{n}P per step: 344,176 here, 1.5× DP’s. In exchange, a device holds only its shard plus one full layer: 49,160 parameters instead of 131,136. The slides’ trick is to overlap the next layer’s all-gather with the current layer’s arithmetic.

FSDP × TP (slides 72–74). On a 2-D mesh, TP runs inside each row of devices, and FSDP shards those TP shards further across rows (and splits the batch across rows). “While processing layer ii, all-gather layer i+1i + 1; then it just becomes TP.”

Our simulation gathers each TP shard once per step and keeps it through the backward pass. A real FSDP implementation frees it and gathers it again.


6. Choosing a configuration

6.1 Memory (script 04, Part 2)

GPT-3 has 12LE212LE^2 + embeddings = 174.6B parameters. At 16 bytes per parameter, per chip:

chipsschemeGB per chip
anydata parallel2,793
anyTP only, 16 shards175
256FSDP (or FSDP × TP) over all chips10.9
1024FSDP (or FSDP × TP) over all chips2.7

Only full sharding fits an 80 GB chip, let alone a 16 GB TPU v5e. Activations come on top; they are reduced by recomputing them in the backward pass (rematerialization).

6.2 The arithmetic-intensity rules (slides 68, 71, 74)

Communication can be hidden behind compute only if the chip does enough FLOPs per byte communicated.

  • FSDP. All-gathering an E×EE \times E layer moves 2E22E^2 bytes and enables 2BE22BE^2 FLOPs of the chip’s own work. The intensity is BB, the tokens per chip, so FSDP needs B≳1018B \gtrsim 1018 on TPU v5e.
  • TP. The intensity is E/nTPE/n_{TP}, so TP needs E≳1018 nTPE \gtrsim 1018\, n_{TP}.
  • Both. With both and a safety factor of 2: E>2⋅1018⋅nTPE > 2 \cdot 1018 \cdot n_{TP} and nTP⋅B>2⋅1018n_{TP} \cdot B > 2 \cdot 1018.

TP lowers the batch per chip that FSDP needs, because each chip’s tokens are shared by nTPn_{TP} chips. That is the point of combining them. On 256 TPUs as 16 TP × 16 FSDP, the rules give E>32,576E > 32{,}576 and B>127B > 127: the slides’ “E > ~32k, BATCH_PER_CHIP > 125”.

Script 04, Part 3 checks configurations:

EETP shardstokens per chipE>2⋅1018⋅nTPE > 2 \cdot 1018 \cdot n_{TP}?nTPB>2⋅1018n_{TP} B > 2 \cdot 1018?
32,76816128yesyes
32,7681664yesno
12,28816128noyes
12,2884512yesyes
12,2881 (FSDP only)3,125yesyes

For GPT-3’s width only small TP degrees satisfy the TP rule. This is why models of that size use TP within a node (fast links) and FSDP / DP across nodes. GPT-3’s 3.2M tokens per step spread over 1,024 chips gives 3,125 tokens per chip: enough for pure FSDP.


7. Practical guidelines (slide 137), and what the slides leave out

The slides’ advice:

  • To scale model and data, use FSDP as much as possible. Use TP (or DP, or sequence parallelism) to reduce the batch per chip when the global batch is not large enough.
  • To scale context, use blockwise Transformers to reduce memory, and RingAttention to grow the context arbitrarily (Lecture 16).

Other axes exist, which the slides do not cover:

  • Pipeline parallelism (GPipe, PipeDream): consecutive layers live on different devices, and micro-batches flow through them, with “bubbles” at the start and end of each batch.
  • Sequence / context parallelism: split the sequence dimension, as RingAttention does.
  • Expert parallelism: the experts of a mixture-of-experts layer live on different devices, with all-to-all communication (Lecture 16’s MoE).

Large training runs combine several of these into a multi-dimensional mesh. Compilers such as GSPMD / XLA derive the collectives from sharding annotations, so in practice one writes the sharding of each array and the system inserts what §4 derived by hand.


8. Summary

  1. Chips do hundreds of FLOPs per byte of memory traffic and about a thousand per byte of interconnect traffic. A kernel is compute-bound only above the ridge point. A linear layer’s arithmetic intensity is the number of tokens sharing each weight read, so training needs a few hundred tokens per chip per weight read.
  2. All-reduce, reduce-scatter and all-gather have ring algorithms that cost each device about one array per phase, independent of the number of devices, but 2(n−1)2(n - 1) latency steps.
  3. Split the output dimension of a matmul and nothing is communicated; split the contraction dimension and partial sums must be all-reduced. Megatron’s MLP (columns, then rows) needs one all-reduce forward (g) and one backward (f); attention splits by heads.
  4. DP, TP, FSDP and FSDP × TP reproduced single-device training to 10−1610^{-16}. They differ in memory and in traffic:
    • DP: 2P2P per step;
    • FSDP: 3P3P per step, holding P/nP/n plus one layer;
    • TP: activations, independent of PP.
  5. For GPT-3, only full sharding fits in memory (10.9 GB per chip on 256 chips). The intensity rules (tokens per chip > ~1018 for FSDP, E/nTPE/n_{TP} > ~1018 for TP) decide how to factor a mesh into FSDP and TP. The slides’ 256-TPU example needs E>32kE > 32k and more than 125 tokens per chip.

9. Common pitfalls

  1. Quoting peak FLOP/s for memory-bound work: a matrix-vector product runs at bandwidth speed (0.5 FLOP/byte in float32).
  2. Applying a nonlinearity to partial sums. GELU(∑)≠∑GELU\mathrm{GELU}(\sum) \ne \sum \mathrm{GELU}: split the hidden dimension, not the contraction dimension, before a nonlinearity.
  3. Forgetting the backward collectives. Megatron’s f is free forward but costs an all-reduce backward. Count both passes.
  4. Thinking FSDP saves communication. It costs 1.5× DP’s traffic; what it saves is memory.
  5. Thinking more TP is always better. The intensity E/nTPE/n_{TP} falls with every extra shard, and TP’s traffic grows with the batch.
  6. Measuring “bandwidth” with one core. A single-threaded copy measured a lower bandwidth than a multi-threaded matrix-vector product on the same machine.
  7. Ignoring latency for small messages. A ring all-reduce of a few KB over hundreds of devices is all latency.

10. Exercises

Exercise 1 (ring all-reduce — derivation). Show that a ring reduce-scatter followed by a ring all-gather sends 2(n−1)M/n2(n - 1)M/n elements per device, and argue that (for algorithms in which each element of the sum is completed on one device) no all-reduce can send less on average.

Answer

Upper bound. Each of the n−1n - 1 reduce-scatter steps sends one chunk of M/nM/n elements per device, and so does each all-gather step: 2(n−1)M/n2(n - 1)M/n in total.

Lower bound. Each of the MM sums combines nn inputs held on nn different devices.

  • Reduction. Whichever device completes a sum must receive information from the other n−1n - 1 devices. Partial sums can merge contributions, but every input except the local one must leave its device at least once. That is (n−1)M(n - 1)M elements in total, or (n−1)M/n(n - 1)M/n per device.
  • Distribution. Every device must end with all MM sums. If the sums are completed evenly over the devices, each device must receive the (n−1)M/n(n - 1)M/n sums it did not complete.

Together: 2(n−1)M/n2(n - 1)M/n per device. The ring meets the bound, so it is bandwidth-optimal (Patarasuk & Yuan, 2009). What it gives up is latency: 2(n−1)2(n - 1) sequential steps.

Exercise 2 (Megatron backward — derivation). For Y=GELU(XA)BY = \mathrm{GELU}(XA)B with A=[A1,…,An]A = [A_1, \dots, A_n] (columns) and B=[B1;… ;Bn]B = [B_1; \dots; B_n] (rows), write ∂L/∂X\partial L/\partial X and show it is a sum over devices of local terms. That is why f’s backward pass is an all-reduce.

Answer

Let Hi=XAiH_i = XA_i and δi=(∂L/∂Y Bi⊤)⊙GELU′(Hi)\delta_i = (\partial L/\partial Y\, B_i^\top) \odot \mathrm{GELU}'(H_i). Since Y=∑iGELU(XAi)BiY = \sum_i \mathrm{GELU}(XA_i)B_i, the chain rule gives ∂L/∂X=∑iδiAi⊤\partial L/\partial X = \sum_i \delta_i A_i^\top. Each term needs only device ii‘s shards and the replicated ∂L/∂Y\partial L/\partial Y (g’s backward pass is the identity). The sum over ii is an all-reduce. The weight gradients X⊤δiX^\top\delta_i and GELU(Hi)⊤∂L/∂Y\mathrm{GELU}(H_i)^\top \partial L/\partial Y are local.

Exercise 3 (FSDP traffic and memory — derivation). With nn devices and PP parameters in LL equal layers, show that FSDP sends 3n−1nP3\frac{n-1}{n}P elements per device per step. Show that it holds P/n+P/LP/n + P/L parameters at most. Compare with DP.

Answer

Traffic. Each layer is all-gathered twice (forward pass, and again in the backward pass because it was freed), and its gradient is reduce-scattered once. Each of these costs n−1n\frac{n-1}{n} of the layer, so summing over layers gives 3n−1nP3\frac{n-1}{n}P.

Memory. At any moment a device holds its own shards (P/nP/n) and one gathered layer (P/LP/L); prefetching the next layer adds another P/LP/L.

DP sends 2n−1nP2\frac{n-1}{n}P and holds PP. FSDP trades 1.5× the traffic for an nn-fold memory reduction. Script 04: 344,176 vs 229,488 elements; 49,160 vs 131,136 parameters.

Exercise 4 (the slides’ FSDP rule — derivation). Derive the arithmetic intensity of an FSDP all-gather of an E×EE \times E bf16 weight matrix that is then multiplied by BB tokens on the chip. Conclude that the batch per chip must exceed the chip’s FLOP-per-interconnect-byte ratio.

Answer

The all-gather brings in about 2E22E^2 bytes (the whole matrix in bf16, of which the chip already had 1/n1/n). The matmul does 2BE22BE^2 FLOPs, so the intensity is 2BE2/2E2=B2BE^2 / 2E^2 = B.

To hide the all-gather behind the matmul, the matmul must take at least as long: 2BE2/Π≥2E2/βlink2BE^2/\Pi \ge 2E^2/\beta_{\text{link}}, i.e. B≥Π/βlinkB \ge \Pi/\beta_{\text{link}}. That is 1018 on TPU v5e; the slides ask for “comfortably larger”.

Exercise 5 (TP vs DP traffic). For a Transformer layer of width EE and a batch of BB tokens, compare TP’s per-step traffic (≈4⋅2BE\approx 4 \cdot 2BE elements) with DP’s (2⋅12E22 \cdot 12E^2 elements). For which batch sizes does TP communicate less?

Answer

TP communicates less when 8BE<24E28BE < 24E^2, i.e. B<3EB < 3E. For E=12,288E = 12{,}288 that is B<36,864B < 36{,}864 tokens per TP group per step.

DP’s traffic is fixed by the parameters. TP’s grows with the batch but not with the parameters, which is why TP suits large models with modest per-group batches, and DP / FSDP suit large batches.

Exercise 6 (coding). Change script 04 to 16 devices (with N=16N = 16; the FSDP × TP mesh becomes 4 × 4). Predict the elements sent per step by DP and FSDP before running it.

Answer

DP: 2⋅1516⋅131,136≈245,8802 \cdot \frac{15}{16} \cdot 131{,}136 \approx 245{,}880. FSDP: 3⋅1516⋅131,136≈368,8203 \cdot \frac{15}{16} \cdot 131{,}136 \approx 368{,}820 (measured 368,760: uneven chunks). TP: 2 all-reduces of 256×64256 \times 64 per block over 4 blocks, 1516⋅2⋅2⋅4⋅16,384=245,760\frac{15}{16} \cdot 2 \cdot 2 \cdot 4 \cdot 16{,}384 = 245{,}760. Measured: 245,880 / 368,760 / 245,760, and the parameters still match the single device to ~1e-16.

Exercise 7 (systolic arrays). Show that a weight-stationary k×kk \times k array needs T+2(k−1)T + 2(k - 1) cycles for TT input rows. How many rows are needed for 90% utilization of a 128 × 128 array?

Answer

Row tt enters the array’s row ii at cycle t+it + i; its last partial sum reaches the bottom of column k−1k - 1 after k−1k - 1 more hops. The last row (t=T−1t = T - 1) finishes at cycle T−1+2(k−1)T - 1 + 2(k - 1), so the array needs T+2(k−1)T + 2(k - 1) cycles.

Utilization is T/(T+2k−2)≥0.9T/(T + 2k - 2) \ge 0.9 when T≥9(2k−2)=2,286T \ge 9(2k - 2) = 2{,}286 for k=128k = 128. Large matmuls (or many tokens) keep the MXU busy.


11. Further reading

From the slides

  • M. Shoeybi et al. Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism, 2019.
  • Rafi W. Sharding Techniques: Single Slice Sharding for Dense LLMs (the source of the FSDP / TP intensity rules on the slides).
  • Google Cloud TPU documentation (system architecture, the MXU).
  • H. Liu, P. Abbeel. Blockwise Parallel Transformer for Large Context Models, NeurIPS 2023; H. Liu, M. Zaharia, P. Abbeel. Ring Attention with Blockwise Transformers for Near-Infinite Context, 2023 (Lecture 16).

Added by these notes

  • S. Rajbhandari et al. ZeRO: Memory Optimizations Toward Training Trillion Parameter Models, SC 2020; Y. Zhao et al. PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel, VLDB 2023.
  • S. Williams, A. Waterman, D. Patterson. Roofline: An Insightful Visual Performance Model for Multicore Architectures, CACM 2009.
  • H. T. Kung. Why Systolic Architectures?, IEEE Computer 1982; N. Jouppi et al. In-Datacenter Performance Analysis of a Tensor Processing Unit, ISCA 2017; TPU v4, ISCA 2023.
  • P. Patarasuk, X. Yuan. Bandwidth Optimal All-Reduce Algorithms for Clusters of Workstations, JPDC 2009 (the ring’s optimality).
  • Y. Xu et al. GSPMD: General and Scalable Parallelization for ML Computation Graphs, 2021; D. Narayanan et al. Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM, SC 2021 (TP + pipeline + DP).
  • V. Korthikanti et al. Reducing Activation Recomputation in Large Transformer Models, 2022 (sequence parallelism, activation memory).
  • J. Austin et al. How to Scale Your Model (Google DeepMind, 2025) — a book-length version of this lecture for TPUs.

12. Next lecture

Lecture 24 is the first guest lecture: generative models for science (John Ingraham). These notes cover only its general modeling methods, on abstract toys:

  • likelihoods of a generative model as zero-shot predictors;
  • amortized sampling of Boltzmann distributions with flows;
  • symmetry-aware (equivariant) diffusion on point clouds;
  • composable conditioning of diffusion models.
← 返回课程目录