Maps to: Stanford CS149 Fall 2025, Lecture 12 (Oct 30), slide deck
12_AI_DatacenterMapping(72 slides). Sources:
- the public Fall 2025 slides;
- M. Shoeybi et al., “Megatron-LM” (2019), and D. Narayanan et al., “Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM” (SC 2021);
- Y. Huang et al., “GPipe” (2019);
- R. Thakur, R. Rabenseifner and W. Gropp, “Optimization of Collective Communication Operations in MPICH” (2005);
- S. Rixner et al., “Memory Access Scheduling” (ISCA 2000).
Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro; clang 21, macOS 27; numpy 2.5). The author has one laptop, not a cluster: the cluster-scale results are models built on published configurations, labelled as such. One demo runs the all-reduce algorithms on the laptop’s real cores. Code:
code/lecture12/. Reading time: ~85 minutes for the prose; ~10 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain why GPUs use HBM (高带宽内存) and what 3D stacking, through-silicon vias and a silicon interposer contribute.
- Describe an AI cluster: scale-up (纵向扩展) inside a server (NVLink) vs. scale-out (横向扩展) between servers (InfiniBand), and the structure of a DGX SuperPOD.
- Define the collective operations (集合通信): broadcast, reduce, all-reduce, reduce-scatter, all-gather and all-to-all. Trace the ring all-reduce, and use the α–β cost model to choose an algorithm by message size.
- Say where the parallelism in a transformer is: data, tensor, pipeline, sequence/context and expert parallelism. Give the communication each needs and estimate its volume per training step.
- Explain how overlapping communication with computation keeps a multi-chip matrix multiply efficient as the chip count grows.
- Compute the pipeline bubble (流水线气泡) of GPipe and 1F1B schedules, and explain why 1F1B needs far less memory.
- Explain how a DRAM read works (precharge, activate, column access, burst) and why its latency is not fixed. Describe banks, channels, address mapping and the memory controller’s FR-FCFS scheduling.
- Explain the energy argument for moving less data, and how chip stacking attacks the memory bottleneck.
0.2 Prerequisites and scope
- Prerequisites:
- Lecture 1: memory latency and the energy of data movement.
- Lecture 3: bandwidth.
- Lecture 6: message passing, communication costs, overlap.
- Lecture 8: reduce and scan.
- Lecture 9: transformers.
- Lectures 10–11: accelerators, dataflow, metapipelines.
- Scope: how AI workloads are spread over many accelerators, and how memory feeds each one. The deck repeats Lecture 11’s dataflow material (slides 9–27), which §2 only summarizes. Programming models for clusters, such as MPI and NCCL, appear only through their collectives.
0.3 Section → code map
| Section | Idea | Demo in code/lecture12/ |
|---|---|---|
| §4 | collectives, α–β costs, the ring | 01_collectives.py (uses collectives.py) |
| §4.5 | all-reduce on real cores | 02_allreduce_threads |
| §5–§6 | parallelism strategies, Megatron’s table, distributed matmul and overlap | 03_parallelism.py |
| §7 | pipeline schedules, bubbles, memory | 04_pipeline_schedules.py |
| §9–§10 | DRAM internals, scheduling, mapping, HBM arithmetic | 05_dram.py (uses dram_sim.py) |
Run them all with cd code/lecture12 && make run (~4 seconds).
0.4 Notation
- Rank (进程号/设备号): one participant in a collective, usually one accelerator. P = number of ranks. n = bytes of each rank’s vector.
- α: fixed cost per message (latency). β: seconds per byte of one link = 1 / link bandwidth.
- t, p, d: degrees of tensor, pipeline and data parallelism. m = micro-batches per pipeline per step.
- DRAM timings: tRP (precharge), tRCD (activate to column), tCL (column to data, “CAS latency”), burst (several transfers per column command).
1. A short primer on memory (slides 3–8)
1.1 CPU memory vs. GPU memory
Slide 4 contrasts two buses:
- A CPU talks to its DRAM over a 64-bit memory bus per channel. DIMM sockets sit centimetres away on the motherboard.
- A GPU talks to its HBM over a 1024-bit bus per stack. The stacks sit millimetres away, in the same package.
Bandwidth is width × transfer rate, so a 16× wider interface is the most direct way to more bandwidth. Wide interfaces need many short wires, which is why the memory has to move next to the processor.
1.2 Stacking chips (slide 5)
3D stacking (三维堆叠) puts several DRAM dies on top of each other:
- Through-silicon vias (TSVs, 硅通孔) run vertically through the dies. They give a highly parallel connection between the DRAM layers and a logic layer at the bottom of the stack.
- The logic layer contains the memory controller and manages requests from the processor.
- A silicon interposer (中介层), a slab of silicon with very fine wiring, connects the stack to the processor with thousands of wires. A circuit board could not carry that many.
The technologies were Micron/Intel’s Hybrid Memory Cube and High-Bandwidth Memory (HBM), which won: a 1024-bit interface per stack.
1.3 HBM in GPUs (slides 6–8)
HBM gives more bandwidth, high power efficiency (short wires take less energy per bit) and a small footprint. Slide 7’s history:
| GPU | interface | peak bandwidth | capacity |
|---|---|---|---|
| AMD Radeon Fury (2015) | 4 HBM stacks × 1024 bits = 4096 bits | 512 GB/s | — |
| NVIDIA P100 (2016) | 4 HBM2 stacks × 1024 bits | 720 GB/s | 16 GB |
| NVIDIA H100 (2022) | 6 HBM3 stacks × 1024 bits = 6144 bits | 3.2 TB/s | 80 GB |
Slide 8 shows NVIDIA’s roadmap: each generation adds stacks, layers and speed. §9–§10 return to DRAM in detail. First, the deck zooms out to whole clusters.
2. Recap: dataflow and kernel fusion (slides 9–27)
Slides 9–27 repeat Lecture 11:
- the asynchrony problem and the data-centric answer;
- dataflow architectures (Plasticine, SN40L);
- parallel patterns and metapipelining (GDA, matmul, FlashAttention);
- fusing a whole Llama decoder into one kernel, and the “kernel loop” with 3 calls per token instead of ~800.
Lecture 11 §4–§5 covers them with demos 04–05. Two points lead into this lecture:
- Slide 25: in the kernel loop, the weight load of the next decoder overlaps the compute of the current one, so HBM is busy all the time.
- Slide 26: the all-reduce between chips can be overlapped too, and on the RDU it uses neither HBM capacity nor HBM bandwidth. Communication between chips is today’s topic.
3. The AI datacenter (slides 28–32)
3.1 Why clusters
AI progress has come from two sources together (slide 28): better algorithms and more compute. Almost all the compute is in tensor cores (slide 29: 89–98% of a GPU’s FLOPS since 2016). The compute used to train frontier models grows much faster than any single chip improves, so training runs use whole clusters. Clusters have grown from hundreds of GPUs to tens and hundreds of thousands (slide 30). Meta’s Llama 3 405B, for example, was trained on up to 16,384 H100 GPUs.
3.2 Scale up and scale out (slides 31–32)
Two kinds of networks connect the accelerators (slide 31):
- Scale-up: a small group of GPUs joined by a very fast, low-latency fabric, NVLink and NVSwitch inside one server. In an 8-GPU DGX A100 every GPU reaches every other at ~300 GB/s per direction. Newer racks (GB200 NVL72) extend one NVLink domain to 72 GPUs.
- Scale-out: servers joined by a datacenter network, InfiniBand or Ethernet, with roughly an order of magnitude less bandwidth per GPU (25 GB/s for a 200 Gb/s port) and more latency.
Slide 32’s DGX SuperPOD is the reference design for an A100 cluster:
- 140 DGX A100 nodes (1,120 GPUs) per pod;
- each node has 2 AMD EPYC 7742 CPUs, 8 A100 GPUs on a fully connected NVLink 3.0 switch, and 8 compute plus 2 storage InfiniBand ports;
- a full fat-tree (胖树) of 200 Gb/s HDR InfiniBand switches (leaf, spine, core), with separate networks for compute and storage;
- adaptive routing, and SHARPv2, in which the switches themselves perform reductions.
The two-level structure matters for every decision below. Communication that is cheap inside a node can be ruinous across nodes.
4. Collective communication (slides 33–34)
4.1 The primitives
Distributed AI workloads communicate mostly through collectives: operations in which every rank takes part at once. They are the message-passing counterparts of Lecture 8’s data-parallel primitives (slides 33–34):
| collective | before | after |
|---|---|---|
| broadcast | one rank has a vector | every rank has it |
| reduce | every rank has a vector | one rank has their sum |
| all-reduce | every rank has a vector | every rank has the sum |
| reduce-scatter | every rank has a vector of P chunks | rank r has the sum of chunk r |
| all-gather | rank r has chunk r | every rank has all P chunks |
| all-to-all | rank r has P chunks, one for each rank | rank r has chunk r of every rank (a distributed transpose) |
Slide 33’s key identity is all-reduce = reduce-scatter + all-gather.
4.2 The α–β cost model
Sending a message of m bytes costs α + m β. α is the fixed cost per message (software, network latency) and β is seconds per byte. An algorithm runs in rounds. In each round every rank may send one message and receive one, so a round costs α + (largest message) × β. collectives.py implements each algorithm as explicit rounds of messages between P simulated ranks, checks the results against numpy, and counts the cost.
The all-reduce algorithms, with n bytes per rank:
| algorithm | rounds | bytes sent by the busiest rank | time |
|---|---|---|---|
| naive: everyone to a root, then back | 2(P−1) | (P−1) n at the root | 2(P−1)(α + nβ) |
| binomial tree reduce + broadcast | 2 log₂P | up to log₂P · n | 2 log₂P (α + nβ) |
| recursive doubling (exchange with rank r XOR 2ᵏ) | log₂P | log₂P · n | log₂P (α + nβ) |
| ring: reduce-scatter then all-gather | 2(P−1) | 2(P−1)/P · n | 2(P−1)(α + (n/P) β) |
4.3 The ring all-reduce, traced
The ring is the workhorse for large messages. Cut each vector into P chunks.
- Reduce-scatter: in round s, rank r sends chunk (r − s) mod P to its right neighbour, which adds it to its own copy. After P − 1 rounds, each rank holds one chunk summed over all ranks.
- All-gather: P − 1 more rounds pass the finished chunks around the ring.
01_collectives.py, Part A traces it on 4 ranks with symbolic values (rank 0 = a, 1 = b, …):
after round 3 (reduce-scatter):
rank 0: a0 | a1+b1+c1+d1 | a2+c2+d2 | a3+d3
rank 1: a0+b0 | b1 | a2+b2+c2+d2 | a3+b3+d3
rank 2: a0+b0+c0 | b1+c1 | c2 | a3+b3+c3+d3
rank 3: a0+b0+c0+d0 | b1+c1+d1 | c2+d2 | d3
after round 6 (all-gather):
every rank: a0+b0+c0+d0 | a1+b1+c1+d1 | a2+b2+c2+d2 | a3+b3+c3+d3
Each rank sends 2(P−1) chunks of n/P bytes: 2(P−1)/P · n in total, independent of P for large P. That is the lower bound for any all-reduce: each rank’s data must get out, and the sum must get back in. The ring also keeps every link busy in every round. It is bandwidth-optimal, which is why NCCL uses it for large messages.
4.4 Which algorithm when?
Part B runs every collective on 8 ranks with 8 MiB each (all results checked). The naive all-reduce makes the root send 7 n and is 3.9× slower than the ring on an NVLink-class network. Part C compares the all-reduce algorithms by message size, with P = 8:
| size | NVLink-class (300 GB/s, 5 µs): best | InfiniBand-class (25 GB/s, 10 µs): best |
|---|---|---|
| 4 KiB | recursive doubling (15 µs; ring 70 µs) | recursive doubling |
| 256 KiB | recursive doubling | recursive doubling |
| 4 MiB | recursive doubling | ring |
| 64 MiB | ring | ring |
| 1 GiB | ring (6.3 ms; naive 50 ms) | ring |
For small messages α dominates, and the algorithm with the fewest rounds wins. For large messages β dominates, and the algorithm with the fewest bytes per rank wins. Libraries such as NCCL choose the algorithm by size, exactly like this table.
The ring has a weakness at scale (Part D, 1 GiB over InfiniBand). Its bandwidth term stays near 2nβ (86 ms) however many ranks join, but its 2(P−1) rounds of latency grow: 82 ms at 4,096 ranks. Large clusters therefore use hierarchical schemes, rings or direct exchange inside servers and trees between them, so that a single reduction does not have to cross 4,096 hops in sequence.
All-to-all (slide 34) sends (P−1)/P of each vector, like reduce-scatter but without arithmetic. It is a transpose of the chunk matrix across ranks. Expert parallelism uses it to route each token to the device holding its mixture-of-experts expert.
4.5 All-reduce on real cores
02_allreduce_threads.cpp runs three all-reduce algorithms on 2–8 cores of the author’s machine, with persistent threads, exact integer-valued inputs and every element checked:
- naive: rank 0 adds the others’ vectors into its own; then everyone copies rank 0’s result;
- ring: reduce-scatter and all-gather around a ring. Each step waits only for the left neighbour’s progress counter;
- two-shot: rank r sums chunk r over all buffers directly, a barrier, then everyone copies the other chunks from their owners. It moves the same chunks as the ring, but in 2 steps instead of 2(P − 1).
8 ranks (best of several runs; ranges across runs):
| vector per rank | naive (root) | ring | two-shot |
|---|---|---|---|
| 64 KiB | 12–14 µs | 13–14 µs | 9–10 µs |
| 1 MiB | 189 µs | 44–88 µs | 55–57 µs |
| 16 MiB | 3.0 ms | 1.5–2.2 ms | 1.2 ms |
| 64 MiB | 12.6 ms | 9.6–10.1 ms | 8.4–8.7 ms |
- While the data fits in the caches (1 MiB), the root is the bottleneck demo 01 predicted. One core does all P − 1 additions, and the ring is 2–4× faster.
- At 64 MiB the ring is only 1.3× faster. In a cluster every rank has its own link, so spreading the traffic multiplies the bandwidth. Here all ranks share one memory system. The demo counts the bytes read and written: naive and ring both move 35 n, two-shot 23 n, and all three run at ~180–240 GB/s, near the machine’s DRAM bandwidth (Lecture 6). Time follows total bytes.
- The ring loses to two-shot for a reason that does not exist in a network. In shared memory every hop writes a partial sum to memory and re-reads it. On a cluster those writes land in each GPU’s private HBM and cost no link bandwidth. A cost model must count the resource the machine actually shares.
- Small messages are latency-bound. The ring’s 14 sequential hand-offs, each a cache-line round trip between cores (Lecture 11’s ~100 ns), make it no faster than the root at 64 KiB.
- Two-shot needs every rank to reach every other directly. That is true for cores sharing memory and for GPUs behind an NVLink switch, but not for a ring or torus of links. The algorithm should match the topology, which is what NCCL does inside a node.
5. Where is the parallelism in a transformer? (slides 35–37)
5.1 The dimensions of the work
A transformer (slide 35) is a stack of identical layers. Each has attention (Q, K, V projections, softmax(QKᵀ)V, an output projection) and an MLP (two or three large matrix multiplies), with normalization and residual additions (Lecture 9). Training processes a batch of sequences: forward pass, backward pass, optimizer step.
The work has several dimensions, and each can be split across devices (slide 36):
| strategy | splits | each device holds | communication (slide 37) |
|---|---|---|---|
| data parallel (DP, 数据并行) | the batch | a full copy of the model | all-reduce of gradients (or reduce-scatter + all-gather) |
| tensor parallel (TP, 张量并行) | the hidden dimension of each matmul | a slice of every layer | all-reduce of activations (or RS + AG) |
| pipeline parallel (PP, 流水线并行) | the layers | a group of consecutive layers | send/receive between stages |
| sequence / context parallel (SP/CP) | the sequence | a slice of the tokens | all-gather / RS of activations or of K and V |
| expert parallel (EP, 专家并行) | the experts of a mixture-of-experts layer | some of the experts | all-to-all |
Real training runs combine several of these, for example “TP 8 × PP 64 × DP 6”.
5.2 Data parallelism
Each device runs the whole model on its share of the batch. After the backward pass, the gradients are summed over all devices with an all-reduce, so that every copy takes the same optimizer step. The all-reduce happens once per step and can start while the backward pass is still computing earlier layers’ gradients, so it overlaps well. Its limit is memory: every device holds the whole model.
The reduce-scatter + all-gather form (slide 37) is the basis of sharded data parallelism (ZeRO, PyTorch FSDP). Each device keeps only 1/d of the optimizer state and weights. It reduce-scatters the gradients, updates its shard, and all-gathers weights when a layer needs them.
5.3 Tensor parallelism
Megatron-LM splits each layer’s matrices so that one layer runs on t GPUs with very little communication. In the MLP, Y = GeLU(X A) and Z = Y B:
- split A by columns over t GPUs. Each computes its slice GeLU(X Aᵢ), with no communication, because GeLU is elementwise;
- split B by rows. Each computes Yᵢ Bᵢ, a partial sum of Z;
- one all-reduce sums the partial results.
Attention is split by heads, the same way. So each layer needs two all-reduces in the forward pass and two in the backward pass, each of the full activation tensor (batch × sequence × hidden). That happens in every layer and every micro-batch, which is a lot of traffic, as §5.4 measures. Sequence parallelism replaces each all-reduce by a reduce-scatter and an all-gather and shards the activations between them, the “RS + AG” of slide 37.
5.4 How much each strategy costs: Megatron’s table (slide 44)
Slide 44 reproduces the configurations of Narayanan et al. (2021): GPT models from 1.7B to 1T parameters, trained on 32 to 3,072 A100 GPUs at 41–49% of peak. 03_parallelism.py recomputes, per configuration:
- the parameter count, 12 l h² (1 + 13/(12h) + (V + s)/(12lh)), which reproduces the table’s sizes (1.65B for “1.7B”, 1.01T for “1T”);
- the model-state memory per GPU (16 bytes per parameter for mixed-precision Adam);
- the pipeline bubble;
- the bytes each GPU sends per training step for each kind of parallelism.
| model | TP × PP × DP | states / GPU | micro-batches | bubble | TP bytes | PP bytes | DP bytes |
|---|---|---|---|---|---|---|---|
| 1.7B | 1 × 1 × 32 | 26 GB | 16 | 0% | 0 | 0 | 6.4 GB |
| 18B | 8 × 1 × 32 | 37 GB | 32 | 0% | 225 GB | 0 | 8.9 GB |
| 145B | 8 × 8 × 24 | 36 GB | 96 | 6.8% | 338 GB | 1.2 GB | 8.7 GB |
| 1T | 8 × 64 × 6 | 32 GB | 512 | 11% | 752 GB | 13 GB | 6.6 GB |
(per GPU per step; micro-batches of one sequence; a first-order model)
As a fraction of the step time, if not overlapped:
| model | TP on NVLink | TP on InfiniBand | PP on InfiniBand | DP on InfiniBand |
|---|---|---|---|---|
| 18B | 7.6% | 91% | — | 3.6% |
| 145B | 4.2% | 51% | 0.2% | 1.3% |
| 1T | 2.3% | 27% | 0.5% | 0.2% |
The design rules of large-scale training fall out of this table:
- Memory forces model parallelism. A 1T model has 16 TB of model state. Only splitting it over TP × PP = 512 GPUs brings that to 32 GB per GPU, which fits an 80 GB A100 with room for activations.
- Tensor parallelism stays inside a server. It sends by far the most bytes: four all-reduces of the activations in every layer. On NVLink that is a few percent of a step; on InfiniBand it would be 27–91%. Hence TP ≤ 8, the number of GPUs in a DGX node, in every row.
- Pipeline and data parallelism cross servers. PP sends only activations at stage boundaries. DP sends one gradient all-reduce per step and overlaps it with the backward pass.
- The price of pipeline parallelism is the bubble, 11% at 1T. Larger models use larger global batches (3,072 sequences at 1T), so each pipeline gets more micro-batches and a smaller bubble (§7).
6. Distributed matrix multiply and overlap (slides 38–41)
6.1 Splitting K over chips (slide 38)
Slide 38’s benchmark multiplies inputA [16 × 24576 × 131072] by inputB [131072 × 8192], 844.4 TFLOP. The mapping splits the K dimension over S sockets:
- each socket multiplies its [M × K/S] slice by its [K/S × N] slice, producing a full-size partial result [M × N];
- an S-way reduce-scatter sums the S partial results and leaves each socket with 1/S of the final output.
Each socket’s partial result is 6.44 GB of BF16, so the reduce-scatter is large.
6.2 Overlap (slides 39–40)
Slide 39 shows the dataflow version: the all-reduce is pipelined with compute. As each tile of the partial result is produced, it streams into the reduction while the next tile is computed, without a round trip through HBM. Slide 40’s conceptual picture: without overlap (the GPU style), communication time adds to computation time. As sockets are added, computation per socket shrinks but communication per socket does not, so communication becomes the bottleneck unless the interconnect bandwidth grows too. With overlap, communication hides under computation.
6.3 Quantified (slide 41)
03_parallelism.py, Part C recomputes slide 41’s numbers. Its overlap model cuts the GEMM into 8 chunks and reduce-scatters chunk i while computing chunk i+1, using Lecture 11’s two-stage pipeline:
| sockets S | compute @100% | reduce-scatter (slide) | implied link bandwidth | no overlap (slide) | overlap, our model | measured with overlap (slide) |
|---|---|---|---|---|---|---|
| 8 | 66.3 ms | 8.6 ms | 655 GB/s | 88.5% | 98% | 72% |
| 16 | 33.1 ms | 9.7 ms | 623 GB/s | 77% | 97% | 75% |
| 32 | 16.6 ms | 15.0 ms | 416 GB/s | 52% | 90% | 79% |
- Without overlap, utilization falls from 88.5% to 52% as S grows: compute shrinks with S, while the reduce-scatter does not.
- With overlap, the measured utilization stays at 72–79%. The slide’s headline is “sustained 70+% utilization across 32 sockets”. At 32 sockets that is far above the no-overlap bound and below our idealized model, which ignores every other overhead.
- At 8 sockets the measurement (72%) is below even the no-overlap estimate (88.5%). Other inefficiencies dominate there. Overlap pays exactly when communication is a large share of the time, which is the regime large systems live in.
7. Pipeline parallelism (slides 42–44)
7.1 A pipeline with one batch is a relay (slide 42)
Split a model’s layers over p devices and feed it one batch at a time. Device 0 runs the forward pass of its layers and hands the activations to device 1, and so on. Then the backward pass returns in the opposite direction. At any moment only one device works. 04_pipeline_schedules.py, Part A (4 stages; forward 1, backward 2 time units):
stage 0 |00..................aaaa|
stage 1 |..00............aaaa....|
stage 2 |....00......aaaa........|
stage 3 |......00aaaa............| each device busy 3 of 12 time units: 75% idle
7.2 Micro-batches (slide 43)
GPipe’s fix is to split the mini-batch (the samples of one iteration) into m micro-batches (微批次) and pipeline them. While stage 1 runs the forward pass of micro-batch 0, stage 0 starts micro-batch 1. With 8 micro-batches (digits = forward of micro-batch j, letters = its backward, a = 0):
GPipe: all forwards, then all backwards
stage 0 |0011223344556677..................aaaabbbbccccddddeeeeffffgggghhhh|
stage 1 |..0011223344556677............aaaabbbbccccddddeeeeffffgggghhhh....|
stage 2 |....0011223344556677......aaaabbbbccccddddeeeeffffgggghhhh........|
stage 3 |......0011223344556677aaaabbbbccccddddeeeeffffgggghhhh............|
time 33, bubble 27%, activations kept per stage: 8 8 8 8
The idle triangles at the start and end are the bubble. The first stage waits p − 1 steps for the first backward pass, and the last stage waits p − 1 steps for the first forward. The bubble fraction is
bubble = (p − 1) / (m + p − 1)
and the simulation matches it exactly (Part C, p = 8: 87.5% at m = 1, 46.7% at m = 8, 5.2% at m = 128). The only way to shrink it is more micro-batches per step. That is why the global batch grows with the model in slide 44’s table (512 micro-batches per pipeline at 1T).
7.3 1F1B: the same bubble, a fraction of the memory
The forward pass of every micro-batch leaves activations (激活值) that its backward pass needs, so they must be kept in memory until then. GPipe runs all forwards first, so stage 0 holds all m micro-batches’ activations at once. The 1F1B schedule (PipeDream-Flush, used by Megatron-LM) works differently. After a warm-up of p − s − 1 forwards on stage s, it alternates one forward with one backward, starting each backward as early as possible:
1F1B
stage 0 |00112233............aaaa44bbbb55cccc66dddd77eeee..ffff..gggg..hhhh|
stage 1 |..001122........aaaa33bbbb44cccc55dddd66eeee77ffff..gggg..hhhh....|
stage 2 |....0011....aaaa22bbbb33cccc44dddd55eeee66ffff77gggg..hhhh........|
stage 3 |......00aaaa11bbbb22cccc33dddd44eeee55ffff66gggg77hhhh............|
time 33, bubble 27%, activations kept per stage: 4 3 2 1
Same time, same bubble, but stage s never keeps more than p − s micro-batches in memory. In Part C, with p = 8 and m = 128, GPipe keeps 128 micro-batches of activations on stage 0 and 1F1B keeps 8. That is what makes hundreds of micro-batches per step affordable.
Megatron also uses an interleaved 1F1B schedule: each device holds v non-consecutive chunks of layers, which shrinks the bubble by about a factor v at the cost of v times more pipeline communication.
7.4 Putting the strategies together (slide 44)
Slide 44 closes the discussion: the degrees of pipeline, tensor and data parallelism, the pipelining schedule, the global batch size and the micro-batch size all influence three things at once:
- the amount of communication (§5.4);
- the size of the pipeline bubble (§7.2);
- the memory footprint (§5.4, §7.3).
Choosing them is an optimization problem. The configurations of the table, TP within a server, PP across servers until the model fits, DP for the rest, with large batches to shrink the bubble, are the solution Megatron found for A100 clusters.
8. Energy: move less data (slides 45–47)
Two ideas reduce energy (slide 45): use the right processor for the job (Lectures 10–11), and move less data. Slide 46’s ballpark numbers (Bill Dally, Tom Olson) count only the operation itself, without instruction overhead:
| operation | energy |
|---|---|
| integer op | ~1 pJ |
| floating-point op | ~20 pJ |
| read 64 bits from a small local SRAM (1 mm away) | ~26 pJ |
| read 64 bits from low-power mobile DRAM (LPDDR) | ~1,200 pJ |
Implications:
- Memory traffic alone has a power cost. Reading 10 GB/s from DRAM costs ~1.6 W, which is more than the ~1 W budget of a whole mobile GPU. (10 GB/s ÷ 8 bytes × 1.2 nJ = 1.5 W.)
- Batteries are small. An iPhone 16 battery holds ~14 Wh; a MacBook Pro holds 99 Wh.
- Recompute rather than reload. When optimizing for energy, recomputing a value is often a better answer than storing it and loading it back. Activation recomputation in training (§5.4’s “96” formula) is the same trade, made for memory capacity.
Slide 47 gives Han et al.’s 45 nm numbers: 0.9 pJ for a 32-bit floating-point operation, 5 pJ for a local SRAM access, 640 pJ to load 32 bits from LPDDR, about 700× the arithmetic. Data movement limits performance (many processing elements need more bandwidth, so execution becomes bandwidth-bound) and costs energy. The rest of the lecture looks at the memory side of that bargain.
9. How DRAM works (slides 48–66)
9.1 The memory system (slide 49)
- A core issues loads and stores.
- Misses in the last-level cache become memory requests to the memory controller.
- The controller sends commands to the DRAM chips over a 64-bit memory bus.
Everything below happens between the controller and the chips. dram_sim.py simulates it for DDR4-2400 CL16 (one 64-bit channel, 16 banks, 8 KiB rows, 64-byte bursts, tRP = tRCD = tCL = 13.3 ns), and 05_dram.py runs the experiments.
9.2 The DRAM array (slide 50)
A DRAM cell is one transistor plus one capacitor that stores a bit as charge. Cells form a 2D array. A row of 2 Kbits per chip is read out at once into a row buffer (行缓冲), and 8 data pins per chip carry bytes from the row buffer to the controller.
9.3 Reading a byte (slides 51–53)
To read a byte from a row that is not open, the controller performs four steps:
- precharge: ready the bit lines (~10–15 ns, tRP);
- row activation: transfer the row into the row buffer (~10–15 ns, tRCD);
- column selection: pick the byte (tCL, the CAS latency);
- transfer the data onto the bus.
Reading the next byte from the already active row skips steps 1 and 2 (slide 52). Demo 05, Part A, for one 64-byte read on an otherwise idle bank:
| case | latency |
|---|---|
| row hit (row already in the row buffer) | 16.7 ns (tCL + burst) |
| row closed (activate + column) | 30.0 ns |
| row conflict (precharge + activate + column) | 43.3 ns |
| the same conflict under a closed-page policy | 30.0 ns |
DRAM latency is not fixed (slide 53). It depends on the state that earlier accesses left behind. A read is destructive: precharge also writes the row buffer’s contents back into the array. Slide 53’s two questions:
- When should the controller precharge? After each access (closed-page) or only when a new row is needed (open-page)? Closed-page turns conflicts into closed accesses, a gain if the next access misses anyway.
- How should the controller hide this latency? §9.4–§9.7 answer it.
9.4 The pins are the scarce resource: bursts (slides 54–55)
If each access transferred only its one byte, the data pins would be busy only a tiny fraction of the time, the rest being precharge, activation and column latency. The pins are the scarcest resource (they cost package area, board wires and power), so DRAM uses burst mode: one column command transfers several consecutive transfers, which amortizes the latency over more data. Part B (one bank, random rows):
| access | burst | bytes per access | bandwidth | data pins busy |
|---|---|---|---|---|
| random rows | 1 | 8 | 0.20 GB/s | 1% |
| random rows | 8 | 64 | 1.48 GB/s | 8% |
| same row, in order | 8 | 64 | 17.6 GB/s | 92% |
A burst of 8 on a 64-bit bus is one 64-byte cache line. That is why the unit of DRAM transfer is a whole cache line, and why access patterns that use whole lines (Lecture 6) matter so much.
9.5 Banks (slide 56)
A DRAM chip contains several banks (存储体), independent arrays that share the chip’s pins. While one bank transfers data, the controller can precharge or activate others, which pipelines requests and keeps the pins busy. Part C spreads random rows over more banks:
| banks used | FCFS | FR-FCFS |
|---|---|---|
| 1 | 1.5 GB/s (8%) | 1.5 GB/s |
| 4 | 3.1 GB/s | 5.7 GB/s |
| 16 | 5.9 GB/s (31%) | 12.1 GB/s (63%) |
(% = data pins busy; peak 19.2 GB/s)
Bank parallelism multiplies random-access bandwidth by 8×. It does not reach the peak, because opening a row draws a burst of current. DDR4 allows at most one activate per tRRD and four per tFAW window (21 ns here), which caps purely random access near 63% of peak in this model.
9.6 Chips, DIMMs and cache lines (slides 57–62)
Eight 8-bit-wide DRAM chips form a DIMM with a 64-bit bus (slide 57). The DIMM looks like one wider, higher-capacity DRAM to the controller, which commands all chips at once: “read bank B, row R, column C”. The bandwidth is higher, but the minimum transfer is now 64 bits.
How should a cache line be laid out?
- The wrong way (slides 58–60): consecutive bytes map to the same chip, so a 64-byte line comes out of one chip, 8 bits at a time, while the other seven idle.
- The right way (slides 61–62): consecutive bytes are interleaved across the chips. All eight transmit in parallel, 64 bits per transfer, and the burst delivers the next 64 bits from the next column.
The memory controller converts each physical address into (channel, bank, row, column). That address mapping decides which access patterns spread over the hardware and which collide (§9.8).
9.7 The memory controller is a scheduler (slide 63)
The controller receives load and store requests from the last-level cache and keeps per-bank request queues. Its goals conflict: maximize throughput, minimize latency, minimize energy. The common policy is FR-FCFS (first-ready, first-come-first-serve):
- serve requests to currently open rows first, which maximizes row-buffer locality;
- serve the rest in arrival order.
The controller may also coalesce small requests into larger contiguous ones to use bursts. Part D, by access pattern:
| trace | FCFS, open page | FR-FCFS, open page | FR-FCFS, closed page | row hits (FR-FCFS, open) |
|---|---|---|---|---|
| stream (sequential lines) | 18.4 GB/s | 18.4 GB/s | 1.9 GB/s | 99% |
| random lines in 1 GiB | 5.8 GB/s | 12.1 GB/s | 12.2 GB/s | 0% |
| two streams interleaved, same bank | 1.5 GB/s | 15.6 GB/s | 1.7 GB/s | 98% |
| stride of one row × 16 banks | 1.5 GB/s | 1.5 GB/s | 1.5 GB/s | 0% |
- Two streams interleaved in one bank thrash its row buffer under FCFS: every access closes the other stream’s row. FR-FCFS serves the waiting row hits first and restores the locality the program interleaved away, a 10× difference from scheduling alone. (FR-FCFS can also starve a request to a closed row while hits keep arriving, so real controllers cap how long a request may wait.)
- The page policy is a bet. Open-page wins for streams, by 10× here. Closed-page wins only when the next access to a bank is a miss anyway.
- A stride that maps every access to the same bank gets no help from any policy. Only the address mapping can fix that (§9.8).
9.8 Channels and address mapping (slide 64)
More channels, each with its own controller and its own 64-bit bus, widen the memory system. Each channel can read a different bank, row and column at the same time. Part E uses two channels (peak 38.4 GB/s) and three mappings:
| mapping | stream | stride of one row × 16 banks | random lines |
|---|---|---|---|
| A: channel = top address bit (all our data in channel 0) | 18.4 GB/s | 1.5 GB/s | 12.0 GB/s |
| B: consecutive lines alternate channels | 37.4 GB/s | 3.0 GB/s | 23.6 GB/s |
| C: B + XOR bank hashing | 37.4 GB/s | 12.2 GB/s | 23.5 GB/s |
Two channels double the bandwidth only if the data is spread over both (B). A power-of-two stride can still land every access in one or two banks. XOR bank hashing, in which the bank number is XORed with low row bits, spreads such strides over all banks without hurting streams. This is the DRAM counterpart of Lecture 11’s shared-memory swizzle and Lecture 6’s padded transpose: a permutation that breaks a pathological alignment.
9.9 Numbers for a real system (slides 65–66)
Slide 65 gives DDR4-2400 on an Intel Core i7-7700K (the Myth cluster machines):
- 64-bit bus × 1.2 GHz × 2 transfers per clock (DDR = double data rate) = 19.2 GB/s per channel;
- two channels = 38.4 GB/s;
- CAS latency ~13 ns.
The simulator’s DDR4 matches these by construction.
Slide 66 summarizes. DRAM latency depends on many low-level factors: the state of the chip (row hit or miss, precharge needed?) and the buffering and reordering of requests in the controller. Much of the complexity of a modern multi-core processor has moved into the memory controller. It schedules tens to hundreds of outstanding requests and maps physical addresses onto the geometry of the DRAM, and it remains an area of active research.
10. Bringing memory closer (slides 67–72)
The modern challenge (slide 67) is to decrease the distance data must move by putting memory closer to processors, which allows shorter but wider interfaces. That is HBM again (slides 68–70, repeating §1). Demo 05, Part F does the arithmetic, bandwidth = width × rate:
| memory | bits wide | Gb/s per pin | units | bandwidth |
|---|---|---|---|---|
| DDR4-2400, one channel (slide 65) | 64 | 2.4 | 1 | 19 GB/s |
| LPDDR5X-8533, 256-bit (the author’s Apple M4 Pro) | 256 | 8.53 | 1 | 273 GB/s |
| HBM2 stack (P100 has 4) | 1024 | 1.4 | 4 | 717 GB/s |
| HBM3 stack, 6.4 Gb/s per pin | 1024 | 6.4 | 1 | 819 GB/s |
| H100 per slide 7: 6 × 1024-bit stacks | 1024 | 4.2 | 6 | 3,200 GB/s |
The author’s laptop sits between a PC and a GPU: Apple’s LPDDR5X sits in the same package as the chip and is 256 bits wide. Lecture 6 measured 206 GB/s of its 273 GB/s peak. An HBM stack runs its pins slower than LPDDR5X but has 4× as many of them per stack, and several stacks per GPU. The bandwidth comes from width, which the interposer makes possible.
HBM4 (slide 71) goes one step further: the base die of the stack can contain custom logic built in a logic process. Candidates are an LPDDR-style interface, I/O such as Ethernet or PCIe, an SRAM cache, compute, and KV-cache compression for LLM serving. Memory starts to become a place where computation happens.
Slide 72 summarizes how the memory bottleneck is being attacked:
- by the application programmer: schedule computation to maximize locality and minimize data movement (Lectures 6, 9, 11);
- by hardware architects: intelligent DRAM request scheduling (§9.7); bringing data closer to the processor (deep cache hierarchies, 3D stacking); wider memory systems (§10); research on placing limited forms of computation in or near memory; hardware-accelerated compression.
The general principles: locate data storage near the processor, move computation to the data, and trade extra computation for less data transfer.
Summary
- HBM gets its bandwidth from width: 1024 bits per stack, possible because stacks of DRAM dies connected by TSVs sit next to the processor on a silicon interposer.
- AI clusters have two levels: scale-up (NVLink, ~300 GB/s per GPU inside a server) and scale-out (InfiniBand, ~25 GB/s per GPU between servers).
- Collectives connect the accelerators. All-reduce = reduce-scatter + all-gather. In the α–β model, few rounds win for small messages (trees, recursive doubling), and few bytes per rank win for large ones. The ring sends the minimum 2(P−1)/P · n per rank but takes 2(P−1) rounds.
- On real shared-memory cores, the root bottleneck shows up while data fits in the caches. Beyond that, every algorithm is limited by the one shared memory system. A cost model must count the resource the machine actually shares.
- Parallelism in a transformer: DP splits the batch (all-reduce gradients once per step), TP splits matrices (four all-reduces of activations per layer, so it stays inside a server), PP splits layers (sends activations, pays a bubble), SP/CP split the sequence, EP splits the experts (all-to-all). Megatron’s 1T configuration combines TP 8 × PP 64 × DP 6.
- Overlapping communication with computation keeps utilization high as chips are added (slide 41: 70+% at 32 sockets, vs. 52% without overlap by the slide’s own estimate).
- The pipeline bubble is (p − 1)/(m + p − 1) for both GPipe and 1F1B. 1F1B keeps at most p micro-batches of activations instead of m.
- DRAM latency depends on state: a row hit costs ~17 ns, a conflict ~43 ns. Bursts, banks and channels keep the scarce pins busy. The memory controller schedules (FR-FCFS) and maps addresses; both can change bandwidth by 10×.
- Moving data costs far more energy than computing on it (~700× for LPDDR vs. an FP32 operation), which drives the move to stacked memory and, eventually, computation near memory.
Common pitfalls
- Using one all-reduce algorithm for every size. Rings are best for large messages and slow for small ones (2(P−1) latencies). Libraries switch algorithms; your cost model should too.
- Counting link bytes on a machine whose bottleneck is shared memory, or the reverse. Demo 02’s ring “should” have won by P/2; on one memory system it could not.
- Putting tensor parallelism across servers. Four all-reduces of the activations per layer need NVLink-class bandwidth.
- Growing the pipeline without growing the batch. The bubble is (p−1)/(m+p−1): more stages with the same micro-batch count means more idle time.
- Using GPipe’s schedule when memory is tight. 1F1B has the same bubble and needs p, not m, micro-batches of activations.
- Treating “a memory access” as a fixed cost. A row conflict costs 2.6× a row hit, and interleaving two streams in one bank can lose 10× of the bandwidth.
- Power-of-two strides. They collide in DRAM banks (and in caches and shared-memory banks). Hash, pad or permute.
Exercises
-
Ring vs. tree. P = 64 ranks, α = 10 µs, link bandwidth 25 GB/s. Compute the ring and the recursive-doubling all-reduce times for n = 64 KiB and n = 256 MiB. Where is the crossover?
Answer
Ring: 2(P−1)(α + nβ/P) = 126 × (10 µs + n/(64 × 25 GB/s)). Recursive doubling: 6 × (10 µs + n/25 GB/s). n = 64 KiB: ring 126 × (10 + 0.04) µs ≈ 1.27 ms; doubling 6 × (10 + 2.6) µs ≈ 76 µs, so doubling wins. n = 256 MiB: ring 126 × (10 µs + 168 µs) ≈ 22.4 ms; doubling 6 × (10 µs + 10.7 ms) ≈ 64.5 ms, so the ring wins. The crossover is where 120α ≈ (6 − 126/64) nβ, i.e. nβ ≈ 120 × 10 µs / 4.03 ≈ 0.30 ms: n ≈ 7.4 MB. -
Minimum traffic. Why must every rank send at least (P−1)/P · n bytes in a reduce-scatter, and at least 2(P−1)/P · n in an all-reduce?
Answer
In a reduce-scatter, rank r's contributions to the P − 1 chunks owned by others, (P−1)/P of its data, must leave rank r in some form. An all-reduce must also deliver the P − 1 final chunks that rank r does not compute itself, another (P−1)/P · n received, and by symmetry sent. The ring meets both bounds exactly. -
Tensor-parallel traffic. A layer with hidden size h = 8192 processes a micro-batch of b = 1 sequence of s = 2048 tokens in BF16 with TP = 8. How many bytes does each GPU send per layer per micro-batch (forward and backward)? How long does it take at 300 GB/s and at 25 GB/s?
Answer
Activations: 2048 × 8192 × 2 B = 33.6 MB. Four ring all-reduces, each sending 2 × 7/8 × 33.6 MB = 58.7 MB: 235 MB in total. At 300 GB/s that is 0.78 ms; at 25 GB/s, 9.4 ms. For comparison, the layer's compute is 24 b s h² ≈ 3.3 TFLOP forward, ×4 with backward and recomputation ≈ 13 TFLOP; divided over 8 GPUs at ~150 TFLOP/s each, that takes ~11 ms. Communication is ~7% of compute on NVLink but ~85% on InfiniBand (demo 03's 18B row: 7.6% vs. 91%). -
Bubble. A model is split into p = 16 stages. How many micro-batches per step are needed for a bubble below 5%? With 1F1B, how many micro-batches of activations does stage 0 keep?
Answer
(p−1)/(m+p−1) < 0.05 ⇒ 15 < 0.05 (m + 15) ⇒ m > 285. Stage 0 keeps at most p = 16 micro-batches of activations (GPipe would keep all 285+). -
Overlap. A step computes for 20 ms and communicates for 15 ms. What is the utilization without overlap, with perfect overlap, and with the computation cut into 4 chunks that overlap with the previous chunk’s communication?
Answer
No overlap: 20/35 = 57%. Perfect overlap: 20/max(20, 15) = 100%. Four chunks: compute 5 ms per chunk, communication 3.75 ms per chunk; the pipeline takes 4 × 5 + 3.75 = 23.75 ms, so utilization is 84%. -
DRAM latencies. With tRP = tRCD = tCL = 15 ns and a 5 ns burst, what are the latencies of a row hit, a closed-bank access and a row conflict? A program alternates between two rows of the same bank. What is its bandwidth with 64-byte accesses, and what could fix it?
Answer
Hit 20 ns, closed 35 ns, conflict 50 ns. Alternating rows makes every access a conflict: 64 B / 50 ns = 1.28 GB/s. Fixes: reorder in the controller (FR-FCFS serves pending hits first), restructure the program to finish one row before the other (blocking), or change the address mapping so the two streams fall in different banks. -
Bandwidth arithmetic. HBM4 doubles the interface to 2048 bits per stack. At 8 Gb/s per pin, what is one stack’s bandwidth? How many stacks give 16 TB/s?
Answer
2048 × 8 / 8 = 2,048 GB/s per stack; 16 TB/s needs 8 stacks. -
Energy. A phone streams a 2 GB model from LPDDR at 20 tokens per second (each token reads all weights). Using slide 46’s 1,200 pJ per 64 bits, what is the DRAM read power? What does that suggest?
Answer
40 GB/s × (1,200 pJ / 8 B) = 40e9 × 150 pJ = 6 W, far beyond a phone's sustainable power for one component. On-device LLMs need fewer bytes per token: quantized weights (4-bit instead of 16-bit) and smaller models, or weights kept in on-chip memory.
The related assignment
No assignment is tied to this lecture. Programming Assignment 4’s lessons apply at the scale of a cluster:
- choose what stays close and what streams;
- overlap movement with compute;
- size the pieces so that synchronization is amortized.
These notes give no assignment solutions.
Further reading
- The Fall 2025 slides for this lecture.
- R. Thakur, R. Rabenseifner, W. Gropp, “Optimization of Collective Communication Operations in MPICH”, IJHPCA 2005; P. Patarasuk and X. Yuan, “Bandwidth Optimal All-reduce Algorithms for Clusters of Workstations”, JPDC 2009.
- NVIDIA NCCL documentation and
nccl-tests(the algbw/busbw convention). - M. Shoeybi et al., “Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism”, 2019.
- D. Narayanan et al., “Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM”, SC 2021 (slide 44’s table, interleaved 1F1B).
- Y. Huang et al., “GPipe”, NeurIPS 2019; D. Narayanan et al., “PipeDream”, SOSP 2019.
- S. Rajbhandari et al., “ZeRO: Memory Optimizations Toward Training Trillion Parameter Models”, SC 2020.
- S. Rixner et al., “Memory Access Scheduling”, ISCA 2000 (FR-FCFS).
- Z. Zhang, Z. Zhu, X. Zhang, “A Permutation-based Page Interleaving Scheme to Reduce Row-buffer Conflicts”, MICRO 2000 (XOR bank mapping).
- B. Jacob, S. Ng, D. Wang, Memory Systems: Cache, DRAM, Disk, Morgan Kaufmann, 2007.
Preview of Lecture 13 — Domain-specific programming systems and AI-driven performance optimization
Lectures 9–12 kept finding the same move: the fastest code comes from scheduling a computation (tiling, fusion, ordering, placement) separately from defining it. Lecture 13 makes that separation a programming model. Halide lets you write an image-processing algorithm once and explore its schedules: tiling, vectorizing, parallelizing, computing at different granularities. Searching the space of schedules can be automated, and the lecture ends with a newer question: can large language models write performance code, and how do we check what they write?
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| high-bandwidth memory (HBM) | 高带宽内存 |
| 3D stacking / through-silicon via (TSV) | 三维堆叠 / 硅通孔 |
| silicon interposer / logic layer (base die) | 硅中介层 / 逻辑层(基底芯片) |
| scale-up / scale-out | 纵向扩展 / 横向扩展 |
| fat-tree network | 胖树网络 |
| rank | 进程号(参与集合通信的设备) |
| collective communication | 集合通信 |
| broadcast / reduce / all-reduce | 广播 / 规约 / 全规约 |
| reduce-scatter / all-gather / all-to-all | 规约分散 / 全收集 / 全交换 |
| alpha-beta (latency-bandwidth) model | 延迟-带宽模型 |
| ring / tree / recursive doubling | 环形 / 树形 / 递归倍增 |
| bandwidth-optimal | 带宽最优 |
| data / tensor / pipeline parallelism | 数据 / 张量 / 流水线并行 |
| sequence / context / expert parallelism | 序列 / 上下文 / 专家并行 |
| mixture of experts (MoE) | 混合专家 |
| sharded data parallelism (ZeRO, FSDP) | 分片数据并行 |
| micro-batch / mini-batch / global batch | 微批次 / 小批次 / 全局批次 |
| pipeline bubble | 流水线气泡 |
| GPipe / 1F1B schedule | GPipe / 一前一后调度 |
| activations / activation recomputation | 激活值 / 激活重计算 |
| compute-communication overlap | 计算与通信重叠 |
| DRAM cell / row / column | 动态随机存储单元 / 行 / 列 |
| row buffer / row hit / row conflict | 行缓冲 / 行命中 / 行冲突 |
| precharge / activate / column access (CAS) | 预充电 / 行激活 / 列访问 |
| burst mode | 突发传输模式 |
| bank / bank-level parallelism | 存储体 / 存储体级并行 |
| DIMM / channel | 内存模组 / 通道 |
| memory controller | 内存控制器 |
| FR-FCFS (first-ready, first-come-first-serve) | 就绪优先、先来先服务调度 |
| open-page / closed-page policy | 开页 / 关页策略 |
| address mapping / bank hashing (XOR) | 地址映射 / 存储体哈希(异或) |
| double data rate (DDR) | 双倍数据速率 |
| near-memory / in-memory computing | 近存计算 / 存内计算 |