Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 2 (Aug 31, 2026), slides
lecture2.pdf(75 slides), All About Performance: hardware ceilings, roofline thinking, and transformer bottlenecks. Spring 2026 taught the same material as Lecture 2 plus a “lecture extension” session (Jan 22 and 27, 2026). Recommended readings (course schedule): J. Austin et al., How to Scale Your Model (the “Scaling Book”), chapters 1 (rooflines), 4 (Transformer math) and 7 (inference); H. He, Making Deep Learning Go Brrrr From First Principles; the GPU performance engineering resources list; A. Armbruster, How To Write A Fast Matrix Multiplication From Scratch With Tensor Cores. Other sources: S. Williams, A. Waterman, D. Patterson, Roofline: An Insightful Visual Performance Model for Multicore Architectures (CACM 2009), the origin of the model; NVIDIA’s Hopper Architecture In-Depth and Hopper Tuning Guide (the slides’ hardware numbers); T. Dao et al., FlashAttention (2022), for the attention I/O argument. Every number labelled measured comes fromcode/lecture02/run on the author’s laptop (Apple M4 Pro, Python 3.13, PyTorch 2.14). Computed numbers come from the same code’s formulas on datasheet numbers. Code:code/lecture02/:roofline.py(the accounting of this lecture as a library) and four demos. Demos 01–03 are instant and use only the standard library; demo 04 measures your machine in ~20 s. Reading time: ~2 hours for the prose; ~30 minutes for the demos.
0. How to read this lecture
0.1 Learning goals
The slides list seven goals and one meta-skill. After this lecture you should be able to:
- Know the machine: name the parts of an AI system (GPU, node, interconnect) and of a GPU (SM, Tensor Core, HBM), and the memory hierarchy between them.
- Count compute: estimate the FLOPs of a matrix multiply and of each Transformer submodule.
- Count data movement: build an explicit model of the bytes moved to and from HBM, and know that it is only a lower bound.
- Use arithmetic intensity: compute AI = FLOPs / bytes, interpret it, and distinguish the actual AI from an optimistic bound.
- Reason about shapes: predict how changing batch, sequence length, width or heads moves an operator between compute-bound and bandwidth-bound.
- Use roofline reasoning: predict when an operator can be compute-bound and when it must be bandwidth-bound.
- Decompose a Transformer layer: map parameters, FLOPs and bytes onto attention, the MLP and the “glue” operations.
The meta-skill is a repeatable workflow: symptom → resource bottleneck → intervention.
0.2 Prerequisites and scope
- Prerequisites: Lecture 1 (the H100’s headline numbers, the 2-FLOPs-per-MAC convention, the decoder block, the KV cache). Matrix multiplication; logarithms.
- Scope: one GPU, its compute and its memory, and the operators of one Transformer block. Communication between GPUs appears only as a preview (Lectures 5–6).
- Not in scope today: how a kernel is scheduled on the GPU (warps, occupancy), profilers in depth, MFU in practice, and token economics in depth. Those are Lecture 3, which the course titles Performance Strikes Back. Also not today: architectures that change the counts (MoE, MLA, sparse attention; Lecture 4).
0.3 Section → code map
| Section | Idea | Code in code/lecture02/ |
|---|---|---|
| §2, §5–§6 | two ceilings, arithmetic intensity, the knee, the roofline | roofline.py (Op, op_times, knee, ascii_roofline) |
| §5.3–§5.4 | a linear layer across token-batches, chips and formats | 01_linear_layer_ai.py |
| §7 | attention (MHA vs GQA, naive vs fused), MLP, glue; one block in numbers | roofline.py (attention_core, block_ops, model_ops), 02_decoder_block_roofline.py, 03_attention_accounting.py |
| §7.7, §8 | the L² crossover; KV cache vs weights in decode | 03_attention_accounting.py Parts C–D |
| §9 | measuring one block, operator by operator | 04_measure_block_ops.py |
0.4 Notation (the course’s global notation for this lecture)
| Symbol | Meaning |
|---|---|
| batch size: sequences processed in parallel | |
| sequence length: tokens per sequence | |
| token-batch (词元批量): the common reshape that turns activations into a matrix | |
model width (d_model) | |
| , , | query heads, head dimension (), key/value heads (MHA: ; GQA/MQA: ) |
| MLP hidden width (classic 2-matrix MLP: ; parameter-matched 3-matrix gated MLP: ) | |
| vocabulary size | |
| bytes per element (BF16: 2, FP8: 1, FP32: 4) | |
| the relevant peak compute for the operator and data type (FLOP/s) | |
| peak HBM bandwidth (bytes/s) | |
| AI, AI* | arithmetic intensity of an operator; the knee |
The slides adopt a zero-ambiguity rule: every symbol is either in this table or defined, explicitly, where it is used. Lecture 1’s (sequence length) and (width) are this lecture’s and .
1. What “performance” means
In systems work, performance is always tied to a metric someone actually experiences:
| Phase | Metrics |
|---|---|
| training | step time (ms/step), tokens/s, samples/s, cost per training token |
| inference | latency per request, throughput (tokens/s), time to first token (TTFT, 首 token 延迟), time per output token (TPOT, 每个输出 token 的时间), cost per generated token |
Whatever the metric, the slides argue that one question usually decides it: are we limited by math throughput (compute), or by moving bytes (memory bandwidth, or communication)?
An analogy helps. Think of the GPU as a factory: a hall full of extremely fast machines (the arithmetic units), fed by a conveyor belt from a warehouse (the memory). If each crate on the belt holds enough work to keep a machine busy for a long time, the factory runs at the machines’ speed; that is compute-bound. If each crate holds only a moment’s work, the machines wait for the belt, and the factory runs at the belt’s speed; that is memory-bound. Buying faster machines helps only in the first case. The rest of this lecture turns “how much work per crate” into a number, arithmetic intensity, and the factory into a picture, the roofline.
2. Two ceilings and a universal lower bound
An accelerator has two headline capabilities (there are others, which we meet later):
- peak compute throughput , in FLOP/s;
- peak memory bandwidth , in bytes/s, between the chip and its HBM.
Take an operator (one kernel) that must do of arithmetic and move to or from HBM. It cannot finish faster than either resource allows:
Why max and not sum? A well-written GPU kernel overlaps memory traffic with arithmetic: while some threads wait for data, others compute (Lecture 3 shows how). Perfect overlap gives the max. No overlap at all would give the sum, which is at most 2× worse. So the max is the right lower bound, and real kernels land between max and sum.
The bound is useful because it needs no profiler. If you know how many FLOPs an operator must do and how many bytes it must move, you can already predict the limiting resource. When work spans several GPUs, a third bound joins these two: . That one belongs to the parallelism lectures.
3. Anatomy of the hardware: a zoom tour
The slides zoom from a node down to a Tensor Core. Each level adds one number you need.
The node. A DGX/HGX H100 holds two CPUs with ~2 TB of host memory and eight H100 GPUs (80 GB each). Four NVSwitch (NVLink 交换芯片) chips connect every GPU to every other at 450 GB/s each way, and eight ConnectX-7 network adapters, up to 400 Gb/s each, connect to the rest of the cluster. A new resource appears here, interconnect bandwidth, and it is much scarcer than memory bandwidth:
(400 Gb/s is 50 GB/s by unit conversion; the application payload is lower. All eight adapters together give up to ~400 GB/s per direction.)
The package. The GH100 compute die is 814 mm² with 80 billion transistors, surrounded by HBM stacks: stacked DRAM on the same package, also called “device memory”. The module has six HBM sites, but the 80 GB H100 enables only five stacks. Everything a computation touches must fit in those 80 GB: weights, activations, the KV cache. Every byte crosses the die boundary at ≤ 3.35 TB/s. Power delivery goes up to 700 W.
The die and one SM. The die has 132 enabled streaming multiprocessors (SM, 流式多处理器) (of 144 on the full chip), a 50 MB L2 cache in the middle, the HBM controllers on the edges, NVLink on one side and PCIe on the other. The memory levels, from fast and small to slow and large:
| Level | Capacity | Where |
|---|---|---|
| registers | 256 KB per SM | inside each SM; fastest |
| L1 / shared memory | 256 KB per SM combined (shared-memory carve-out up to 228 KB) | inside each SM |
| L2 cache | 50 MB | shared by all SMs, on the die |
| HBM | 80 GB at 3.35 TB/s | on the package, off the die |
The Tensor Core. One Tensor Core instruction multiplies a small tile, with matrices of order 16 × 16. A large matmul is built from millions of such tile operations: a 4096 × 4096 matmul decomposes into millions of them. With 4 Tensor Cores per SM, the H100 has 528, and they supply essentially all of the 989 TFLOP/s BF16 peak. Their operands are usually staged through shared memory, and their accumulators live in registers.
Everything else runs on the CUDA cores (CUDA 核心): elementwise math, the inside of a softmax, index arithmetic. There are 128 per SM (also called SPs, streaming processors), for a peak of ~67 TFLOP/s in FP32, about 15× below the BF16 Tensor-Core peak. The practical rule: compare scalar and elementwise work against the CUDA-core roof, not the Tensor-Core peak. roofline.py records for every operator which roof applies (kind = "matmul" or "vector").
4. Counting FLOPs
4.1 Why matrix multiplication dominates
Transformers are linear-algebra machines. Their largest learned transformations are linear layers: the attention projections , the 2 or 3 MLP matrices, and the LM head. The token embedding is a lookup (a gather), not a GEMM. Consequence: training and prefill are dominated by highly optimized matrix multiplies (GEMM, 通用矩阵乘). During autoregressive decode, by contrast, small token-batches make weight reads and the growing KV cache strongly bandwidth-sensitive. Most of this lecture is about why.
4.2 The counting rules
- A FLOP is one floating-point operation: one multiply or one add. A dot product of two length- vectors does multiplies and adds, which we round to . Performance reasoning keeps the leading-order term and drops ±1s.
- A GEMM with and has outputs, each a length- dot product:
This formula is the backbone of almost every compute estimate in the course.
- A linear layer with , is a GEMM. The comes from reshaping activations to , which is why GEMM efficiency depends on the token-batch, not just the batch. Forward: FLOPs.
- Training needs, per forward GEMM, two backward GEMMs of the same size: and . So forward , backward , and the training total is ≈ 6mnr, 3× the forward pass. Lecture 1 checked this exactly against PyTorch’s FLOP counter.
4.3 The 6PN heuristic, and what it leaves out
The famous estimate training FLOPs ≈ 6 · P · N_tok follows ( ≈ non-embedding parameters in the dense matmuls, = training tokens). The slides list what it omits: the quadratic attention FLOPs (§7.7; Lecture 1 found 6N 3× too low at 128k context), vocabulary and embedding effects, optimizer work, softmax, normalization, activation recomputation, communication, and kernel overheads. Use it for budgeting, not for exact predictions.
5. Counting bytes, and arithmetic intensity
5.1 The other half: moving bytes
Compute is half the story. For a standalone, unfused operator, an optimistic HBM-traffic model counts:
- input tensors that must be fetched from HBM,
- weights fetched from HBM,
- outputs written back to HBM,
each exactly once. Reality can differ in both directions. Caches and fusion can keep some operands on-chip (fewer bytes). Tiling, cache evictions, temporary tensors and multiple passes add bytes.
5.2 Arithmetic intensity, and the direction of the bound
A large AI means much reuse of each byte, so compute-bound is possible. A small AI means little reuse, so bandwidth-bound is likely. Every change of shape (, , , ) can change AI, which is why shape reasoning is core to performance engineering.
The slides insist on one subtlety, and it is worth absorbing now. Our byte count is a lower bound on the true traffic, so
is an upper bound on the true arithmetic intensity. Two consequences:
- if even this optimistic , the operator must be bandwidth-bound; the model certifies it;
- if , compute-bound is only possible. Measure the real traffic before you believe it.
5.3 The linear layer: two regimes
For with the byte model “read , read , write ”:
- Small token-batch (decode): the weight read dominates the denominator, so ; in BF16, . Small batches reuse each weight too little, so they are bandwidth-bound.
- Very large token-batch (training, prefill): the activation terms dominate, so . Increasing further stops helping, because the activations must still be streamed.
5.4 From AI to time: the knee
Dividing the two time lower bounds:
Below the knee (拐点) the operator is bandwidth-bound; above it, compute-bound is possible (other limits may still bite; Lecture 3). On an H100 in dense BF16, 295 FLOPs/byte. The slides warn that ~300 is not universal. Other chips have other ratios. And norms, softmax, exponentials and scalar work use the CUDA-core pipeline, whose knee is .
Demo 01 sweeps the course’s example layer (, BF16) on an H100 (computed):
| FLOPs | bytes (≥) | AI | bound | time (≥) | of peak | |
|---|---|---|---|---|---|---|
| 1 | 134 MFLOP | 134 MB | 1.0 | memory | 40.1 µs | 0.3% |
| 32 | 4.29 GFLOP | 136 MB | 31.7 | memory | 40.5 µs | 10.7% |
| 128 | 17.2 GFLOP | 139 MB | 123 | memory | 41.6 µs | 41.7% |
| 324 | 43.5 GFLOP | 147 MB | 295 | (knee) | 44.0 µs | 99.8% |
| 8192 | 1.10 TFLOP | 470 MB | 2,341 | compute | 1.11 ms | 100% |
| 65,536 | 8.80 TFLOP | 2.82 GB | 3,121 | compute | 8.89 ms | 100% |
Read the time column: from to 128 the time barely changes (40 → 42 µs), because it is the time to read the 134 MB of weights. Up to the knee, extra tokens are almost free. Past it, time grows in proportion to the work. AI approaches the large-batch limit . The same weights, read once per step, cost 295× more time per token at than in training: exactly the knee.
How many tokens does a GEMM need to cross the knee? Solving for :
| chip | format | knee AI* | knee |
|---|---|---|---|
| A100 | BF16 | 153 | 161 |
| H100 | BF16 | 295 | 325 |
| H100 | FP8 | 591 | 325 |
| B200 | BF16 / FP8 / FP4 | 281 / 562 / 1125 | 308 |
Two lessons. First, newer chips need bigger batches to be compute-bound: from A100 to H100, compute grew about 3.2× and bandwidth only 1.6×, so the knee in tokens doubled. Second, lower precision does not move the knee in tokens. FP8 halves the bytes per element and doubles the peak, so both roofs get faster by the same factor. It makes a memory-bound GEMM twice as fast, but does not make it compute-bound.
6. The roofline model
6.1 The picture
Plot attainable performance (FLOP/s, log scale) against arithmetic intensity (log scale). The roofline is
a diagonal “memory roof” of slope 1 (left of the knee) meeting a flat “compute roof” (right of the knee). An operator at intensity AI cannot run above the roof. The model is due to Williams, Waterman and Patterson (2009). Its strength is that two hardware numbers and one property of the code, its AI, give a visual bound on performance.
Demo 01 draws it in plain text for the H100 sweep: points 1–4 ( = 1, 8, 32, 128) climb the diagonal, K sits at the knee, and points 5–7 lie on the flat roof.
6.2 The decision rule
- Compute the knee: , a property of the hardware and of which pipeline and data type the operator uses.
- Compute the operator’s AI: , a property of the algorithm and the shapes.
- Compare. With the actual traffic, the lower of the two roofs at binds. With a lower-bound byte model, certifies bandwidth-bound, while only says compute-bound is possible.
What moves an operator on the chart? Shapes and batching move it horizontally: a larger goes right for a linear layer. Fusion also moves it right, by removing bytes. A different number format or chip moves the roofs. Nothing moves an operator above its roof. An operator measured far below its roof has a problem the roofline does not explain, and Lecture 3 is about diagnosing that.
7. Applying roofline thinking to a decoder block
7.1 The block
A pre-LN (前置 LayerNorm) decoder block: input → norm → masked multi-head self-attention → residual add → norm → MLP → residual add → output, of the same shape. Throughout the block the main activation shape is , the residual stream. Performance is largely decided by the big matmuls inside attention and the MLP, plus the memory traffic of the “glue”: norms, softmax, elementwise operations.
7.2 Attention
Equations and shapes (standard MHA first). From , the projections , , () are reshaped into heads . Then, per head,
and .
GQA/MQA: what changes, precisely. Everything about the queries stays the same. Keys and values have fewer heads, , so the KV cache, which scales with , shrinks. GQA is primarily a memory and bandwidth optimization for inference. The dominant attention compute still scales with the number of query heads, because every query head still produces its own scores and outputs.
FLOPs per layer (forward, full convention). With :
| part | parameters | forward FLOPs |
|---|---|---|
| projections Q, K, V, O | (MHA: ) | (MHA: ) |
| and | 0 | (unchanged by GQA) |
Training is ~3× these. Causal kernels that skip the masked upper triangle use about half the quadratic FLOPs, but keep the scaling.
Demo 03 Part A makes this concrete for a Llama-3-8B-sized layer at (computed):
| attention | projection params | projection FLOPs | FLOPs | KV cache (1 layer, 8k) | |
|---|---|---|---|---|---|
| MHA (32 KV heads) | 1 | 67.1 M | 1.10 TFLOP | 1.10 TFLOP | 128 MiB |
| GQA-8 (Llama 3) | 0.25 | 41.9 M | 687 GFLOP | 1.10 TFLOP | 32 MiB |
| MQA | 0.03 | 34.6 M | 567 GFLOP | 1.10 TFLOP | 4 MiB |
GQA-8 cuts projection FLOPs to 62% and the cache to 25%, and leaves the score FLOPs untouched.
Bytes per layer (naive implementation, lower bounds). The projections move in total. The terms are residual-stream traffic and the terms are weight reads, which dominate when is small. A naive quadratic attention materializes and : write , read it for the softmax, write , read it for :
The term is unique to naive attention and grows quadratically with .
Arithmetic intensity.
- Projections: . This is when (weights dominate) and when . Increasing pushes it up through weight reuse.
- Naive quadratic: when . This is almost independent of . A longer context adds FLOPs and materialized bytes together, both , so naive attention never moves right on the roofline. With in BF16 it is stuck at ~64 FLOPs/byte, far below 295.
FlashAttention’s move. A fused kernel tiles the computation and uses an online softmax (Lecture 7), so score and probability tiles and the softmax statistics stay on-chip. and are never written to HBM. If , , are each read once and written once, and (about 2048 at in BF16, or counting causal FLOPs). The slides add an honest caveat: is not a formula for actual FlashAttention intensity. On-chip memory is finite, so tiled algorithms re-read K and V, and the exact I/O depends on tile sizes. The robust win is eliminating the traffic; the arithmetic remains. In decode, the dominant issue is usually streaming the KV cache instead.
Demo 03 Part B (computed, GQA-8, ):
| AI naive | AI fused (causal) | naive time ≥ | fused time ≥ | naive / fused | |
|---|---|---|---|---|---|
| 512 | 56 | 205 | 23.2 µs | 3.13 µs | 7.4× |
| 2,048 | 62 | 820 | 333 µs | 34.7 µs | 9.6× |
| 8,192 | 64 | 3,277 | 5.18 ms | 556 µs | 9.3× |
| 131,072 | 65 | 52,429 | 1.31 s | 142 ms | 9.2× |
The naive intensity sits at 62–65 for every context from 2k to 128k, exactly as predicts. The fused intensity grows in proportion to .
7.3 The MLP
A modern dense block uses a gated MLP (门控 MLP) such as SwiGLU, modelled as three matmuls:
- Parameters : if , or for a parameter-matched , the same as a classic 2-matrix MLP with . Either way the MLP carries more parameters than the attention projections ().
- Forward FLOPs , training .
- Bytes (naive: each sub-op reads its inputs and writes its outputs):
With , the hidden-activation traffic exceeds the residual-stream traffic. In an unfused MLP, the intermediates cost more bandwidth than the input and output.
- AI , with two regimes: small gives (weights dominate); large gives , which is for (1,820 at in BF16). Wide MLP matmuls can be very compute-efficient when the token-batch is large.
7.4 The glue: small math, real bandwidth
Three examples from the slides show why “small” operations are not small.
- Residual add : FLOPs, bytes (read two, write one), so in BF16. It cannot be compute-bound on any hardware. If a profile shows much time in residual adds, it is telling you about HBM traffic and kernel overhead.
- LayerNorm / RMSNorm: compute statistics per token over , then normalize. An ideal standalone kernel reads once and writes once (). A naive implementation makes several passes (one for the mean, one for the variance, one to normalize), so its traffic is with . counts how many times the residual stream was streamed through HBM. Norms are archetypal bandwidth operations: math and streaming.
- Softmax over a length- row: max-reduce, exponentiate, sum-reduce, divide, about FLOPs for a small constant , against bytes. is a constant: longer rows do not move softmax rightward.
The full list of bandwidth-sensitive operations: norms (multiple passes), softmax, elementwise activations (SiLU, GELU), residual adds (pure bandwidth), and embedding lookups (gathers). If you fuse several bandwidth-bound operations into one kernel, the intermediate reads and writes disappear and the effective AI rises. That is the lever for glue (Lecture 3).
7.5 Per-layer summary
| Component | Params | Forward FLOPs | Forward bytes (naive, ≥) | AI |
|---|---|---|---|---|
| attention projections (MHA) | ||||
| attention quadratic (, softmax, ) | 0 | |||
| MLP (gated) | ||||
| norms, residuals, elementwise | , often several passes |
Everything is at most linear in except naive attention, which has a quadratic traffic term. When you are bandwidth-limited, the fastest wins come from finding and shrinking the largest term of your current workload.
7.6 One real block, every operator (demo 02)
roofline.block_ops lists every operator of one Llama-3-8B block (, 32 query / 8 KV heads of 128, SwiGLU ) with its FLOPs, bytes, AI and roofline time on an H100 in BF16. As a check, summed over the whole model it reproduces Lecture 1’s flops_per_token exactly. Four workloads (computed lower bounds; “share” is each operator’s fraction of the block’s ideal time):
Prefill / training forward, 4,096 tokens, naive attention. Every weight-carrying matmul is compute-bound (AI 683–1,792). The three parameter-free attention operators are memory-bound: and at AI 123 and the softmax at AI 1.25. They move 4.38 GB per block, 4× the 1.11 GB moved by all the weight matmuls together, and take 39% of the block’s time. The softmax alone is the single most expensive operator (19% of the time, 0.1% of the FLOPs). The block takes ≥ 3.32 ms.
The same with fused attention. The attention core becomes one compute-bound operator (AI 1,639), 9.4× faster, and the block drops to ≥ 2.15 ms. Now the MLP’s three matmuls are 68% of the time. Vector operations (norms, residual adds, SiLU·U) still take 9.6% of the ideal time while doing 0.02% of the FLOPs: glue is cheap in math and expensive in bytes.
Decode, batch 1, 4k context. All 13 operators are memory-bound. The block reads 453 MB to do 503 MFLOP; the MLP weights alone are 78% of the bytes. Every weight matmul has AI 1.0, exactly the formula.
Decode, batch 64. The weight reads are shared, so 64× the tokens cost only 3.4× the time. But the projection AI is still only ~62, below the knee. And the 64 KV caches, which are not shared, are now 70% of the block’s time.
Whole model (demo 02 Part D):
| workload | FLOPs | bytes (≥) | time (≥) | tokens/s (≤) | FLOP/s used |
|---|---|---|---|---|---|
| prefill 4,096 tokens, naive attention | 70.4 TFLOP | 200 GB | 111 ms | 37,043 | 64% |
| prefill 4,096 tokens, fused attention | 65.9 TFLOP | 62.4 GB | 73.2 ms | 55,961 | 91% |
| decode step, batch 1 | 17.2 GFLOP | 15.6 GB | 4.64 ms | 215 | 0.4% |
| decode step, batch 64 | 1.10 TFLOP | 50.1 GB | 15.0 ms | 4,279 | 7.4% |
Same weights, two different physics. Prefill can use 91% of the GPU’s arithmetic; a decode step at batch 1 uses 0.4% of it.
7.7 The L² term and where it takes over
The quadratic matmuls contain no learned parameters, but they still cost compute. As grows they eventually dominate the parameter-led linear layers. Per layer, forward (MHA projections, gated MLP, full square):
That is for and for , which for is roughly 42,000–56,000 tokens. With a causal kernel, the quadratic term halves and the crossover doubles: , i.e. or in the same examples.
A note on the slides. The slides print the full-square rule as "". Their own ratio , and their own examples ( and ), give . The causal rule is correct as printed. Demo 03 found this when the printed rule disagreed with the exact count for GPT-3, a pure-MHA model where the rule should be exact.
Demo 03 Part C compares the rule with the exact per-layer crossover (computed):
| model | heads / KV heads | rule, full | exact, full | rule, causal | exact, causal |
|---|---|---|---|---|---|
| GPT-3 175B (2-matrix MLP) | 96 / 96 | 73,728 | 73,728 | 147,456 | 147,455 |
| Llama-2-7B | 32 / 32 | 24,704 | 24,704 | 49,408 | 49,407 |
| Llama-3-8B | 32 / 8 | 29,696 | 26,624 | 59,392 | 53,247 |
| Llama-3-70B | 64 / 8 | 59,392 | 52,224 | 118,784 | 104,447 |
| Llama-3.1-405B | 128 / 8 | 112,640 | 97,280 | 225,280 | 194,559 |
For MHA models the rule is exact. With GQA the linear part is cheaper, so attention arithmetic dominates at contexts about 10% shorter than the rule says. For a 2-matrix GELU MLP the rule becomes / .
8. The three headline bottlenecks
The slides organize everything above into three bottlenecks of dense Transformers. Which one dominates depends on (i) the width , (ii) the context length , and (iii) the phase: training/prefill vs autoregressive decode.
| Bottleneck | What you observe | Typical lever |
|---|---|---|
| 1. MLP/FFN: dense compute and parameters | high compute and many parameters per token; every token pays for every MLP weight | mixture of experts (MoE): more total parameters, only a subset activated per token; the costs are routing, communication and load balancing |
| 2. Attention / KV cache in decode: memory and bandwidth | high HBM use and bandwidth during generation, from re-reading the cache each step | reduce (GQA/MQA); reduce (KV quantization); cache lower-dimensional representations (latent caches, MLA) |
| 3. L² attention at long context: quadratic scaling | cost explodes with context length | if exact attention is I/O-limited: FlashAttention-style kernels. If the arithmetic itself is the problem: sparse, selective or hierarchical attention, or hybrid models that use full attention only in a few layers |
Bottleneck 2 deserves one more number. In decode, per sequence, the cache across all layers is bytes, and it is streamed from HBM at every step. Batching shares the weight read but not the cache. Demo 03 Part D for Llama-3-8B (computed):
| batch | weights read per step | KV read per step at 8k context | KV share | context where KV = weights |
|---|---|---|---|---|
| 1 | 15.0 GB | 1.07 GB | 6.7% | 114,512 |
| 8 | 15.0 GB | 8.59 GB | 36% | 14,314 |
| 32 | 15.0 GB | 34.4 GB | 70% | 3,578 |
| 128 | 15.0 GB | 137 GB | 90% | 895 |
Long contexts and large batches turn decode into a KV-bandwidth problem. Lecture 4 is about the architectures that attack each of the three bottlenecks.
9. Measuring one block on a laptop (demo 04)
The slides’ message is “count → predict → measure → change the right thing”. Demo 04 does the “measure” step. It first measures this laptop’s two roofs: matmul peak 3.19 TFLOP/s (fp32, 8 CPU threads), DRAM bandwidth 210 GB/s, knee 15.2 FLOPs/byte. Then it times every operator of a block in eager PyTorch (16 heads / 4 KV heads, SwiGLU , fp32) and compares each time with its roofline prediction. All numbers are measured and machine-specific.
Prefill, 1,024 tokens (block: measured 41.5 ms vs roofline 33.0 ms):
- The weight matmuls are at their roof. All six run at 85–103% of the measured peak (measured ÷ roofline 0.97–1.17).
- The glue is not. Vector operations do 0.13% of the FLOPs but take 14.0% of the measured time, against 4.2% predicted. Eager RMSNorm launches six kernels (pow, mean, add, rsqrt, mul, mul) and takes 2.8× its 2-pass prediction, as if it streamed the activations ~5.5 times; this is the slides’ , measured. Mask + softmax takes 6.5× its prediction, and SiLU·U (two kernels and a temporary) 3.3×.
- Fusion matters for attention. Naive attention (QK^T, mask+softmax, PV, with and in memory) takes 9.12 ms. PyTorch’s fused
scaled_dot_product_attentiongives the same result in 3.60 ms. Two things contribute: it never writes and out, and it skips the masked half of the causal work. Its own roofline is 1.35 ms, so even the fused CPU kernel is 2.7× off its roof.
Decode, batch 1, 1,024 tokens of context (block: measured 888 µs vs roofline 881 µs):
- The block as a whole is right at its roofline. The 46 MB MLP weights stream at 91–105% of the measured DRAM bandwidth.
- A benchmarking trap. The 4.2 MB K/V projection weights appear to stream at ~3× DRAM bandwidth. A micro-benchmark that re-runs one operator keeps its small weights in on-chip cache (a warm cache, 热缓存). In a real forward pass every layer reads different weights, so they come from DRAM.
- Overhead-bound glue. The decode-sized RMSNorm (2,048 numbers) takes ~4.5 µs against a 117 ns roofline. That is six kernel launches’ worth of fixed cost wrapped around almost no work: neither roof explains it. This is the “both far from peak” case that opens Lecture 3.
Decode, batch 16. The roofline says sharing the weight reads should make batch 16 cost only 1.37× batch 1. Measured, it costs 5.4×. This CPU’s GEMM kernels handle 16-row inputs poorly: the Q/O projections run at up to 6.6× their roofline, the same weakness Lecture 1’s demo 04 found at batch sizes 2–32. Batching only pays if the kernels can exploit it. On GPUs, too, small-batch decode GEMMs need special care, and Lecture 3 shows why (tiles, waves, occupancy).
The pattern to remember: the roofline predicted the shape of the profile (matmuls compute-bound in prefill, everything memory-bound in decode). Every place it was wrong had a name: extra passes, cache effects, fixed overheads, kernel selection. Naming that gap is the diagnosis skill.
10. Profiling and MFU: a first look
The slides close Part D with the profiling mindset; Lecture 3 develops it.
Three questions profiling must answer: (1) where is time spent (module and kernel breakdown)? (2) why is it slow (compute-, bandwidth-, overhead- or communication-bound)? (3) what do we do about it (kernel, schedule or architecture change)? The loop is measure → hypothesis → intervention → re-measure. If you cannot state the hypothesis clearly, you are not done diagnosing.
What to measure. End-to-end metrics (step time and tokens/s; TTFT and per-token latency) tell you whether you are improving. Kernel metrics (time per kernel, achieved FLOP/s, achieved bytes/s, signs of launch overhead) tell you why.
From profiler numbers to a hypothesis. For an operator with known FLOPs and bytes, achieved FLOP/s ≈ FLOPs/ and achieved bandwidth ≈ bytes/. Then:
| bandwidth | FLOP/s | diagnosis |
|---|---|---|
| near peak | far from peak | bandwidth-bound |
| far from peak | near peak | compute-bound |
| far from peak | far from peak | another limit is active: small shapes or occupancy, launch overhead, dependencies and stalls, missing fusion, synchronization, communication |
MFU (model FLOPs utilization): over accelerators. It is a compact summary of “how close to peak compute”, useful for comparing configurations when the FLOP-counting convention and the peak are held fixed. It is a symptom metric, not a diagnosis. A low MFU can come from bandwidth limits, launch overhead, unfused operations, communication or imbalance, and only the kernel breakdown tells you which.
11. Token economics: from FLOPs to wall-clock
With the dense heuristic (training FLOPs ≈ ), GPUs of peak at utilization need
Three levers change it most: more GPUs (if scaling efficiency holds; Lectures 5–6), higher utilization (kernel quality, bandwidth limits, communication: today and Lecture 3), and better algorithms that change or the effective FLOPs per token (Lecture 4). Lecture 3 adds the inference side: TTFT and TPOT are two clocks under two roofs.
12. Putting it together: the checklist
When you see a performance issue, ask in this order (the slides’ list):
- What is the dominant operator? (attention matmuls? MLP matmuls? norms? KV reads?)
- What are its shapes? (, , , , , )
- Compute FLOPs and bytes. Even approximate is useful.
- Compute AI and compare it to AI*. Lower-bound bytes give an optimistic upper bound on AI.
- Form a hypothesis: compute-, bandwidth- or overhead-bound.
- Pick the matching lever: fusion, a better kernel, batching, or an architecture change.
If you cannot do steps 2–4, you are guessing. This lecture is about eliminating guessing.
13. Summary
- On one GPU the two headline resources are compute throughput and HBM traffic; across GPUs, communication adds a third.
- . Arithmetic intensity AI = FLOPs/bytes is the roofline’s x-coordinate. With lower-bound bytes, the computed AI is an optimistic upper bound: it can certify memory-bound, never compute-bound.
- The knee AI* = is ~295 FLOPs/byte for H100 BF16 Tensor-Core work and ~20 for CUDA-core FP32 work. Always use the roof of the pipeline the operator runs on.
- A linear layer’s AI is at small token-batch and saturates at . On an H100 a GEMM needs ~325 tokens to reach the knee. Lower precision does not change that number; newer chips raise it.
- Dense MLP matmuls carry most parameters and are compute-efficient at large token-batch. Decode makes every linear layer weight-bandwidth-bound.
- GQA shrinks the KV cache and projection work, but not the score FLOPs. Naive attention’s AI is stuck near at any length. FlashAttention removes the traffic but keeps the arithmetic, which overtakes the linear layers beyond (full) or (causal).
- Glue operations (norms, softmax, activations, residual adds) do almost no math and still take a visible share of time: 9.6% ideal and 14% measured in the demos. Fusion is the lever.
- The headline bottlenecks are MLP compute, decode KV bandwidth and L² attention. Prefill and decode are different physics.
- Profiling is a loop: measure → hypothesis → intervention → re-measure. MFU is a symptom.
14. Common pitfalls
- Comparing elementwise work with the Tensor-Core peak. A norm at “0.004% of peak” is not a broken kernel; its roof is the CUDA cores and, really, the memory.
- Believing a compute-bound verdict from a byte model. The lower-bound model can only certify the memory-bound case.
- Forgetting the reshape. GEMM efficiency depends on . A decode step has , not .
- Expecting FP8 to fix a memory-bound decode. It halves the time, but the knee in tokens stays where it was.
- Assuming GQA reduces attention FLOPs. It reduces K/V projections and the cache; the score FLOPs scale with query heads.
- Treating causal masking as an algorithmic change. It halves the quadratic constant but keeps the scaling and the roofline conclusion for naive attention.
- Warm-cache micro-benchmarks. Re-running one operator keeps small inputs in cache and inflates “bandwidth”. Know your working set, and compare it with the cache sizes.
- Quoting one number for a workload with two phases. Prefill and decode differ by two orders of magnitude in FLOP/s used.
15. Exercises
- The canonical memory-bound op. What is the AI of an fp32 vector add ? How long does it take on an H100 for elements, at best?
Answer
One add per element; read 2 × 4 bytes and write 4 bytes: FLOPs/byte, about 3,500× below the knee. Bytes GB, so ms. The interesting question is never “how many FLOP/s”, but what fraction of 3.35 TB/s a kernel reaches.
- A knee in tokens. Llama-3-70B’s MLP has , . How many tokens must the up-projection GEMM process (BF16, H100) to reach the knee?
Answer
with , : . As in demo 01, a few hundred tokens: a decode batch of 64 is far below it.
- Reading a profile. A residual add over , (BF16) takes 70 µs. What bandwidth did it achieve, and what is the lever?
Answer
Bytes MB; TB/s, 86% of the HBM peak. It is at the memory roof; making the add “compute faster” is impossible. The only lever is fusion: fold the add into the kernel that produces or consumes , so that and never make a separate round trip.
- Why naive attention cannot scale. For one Llama-3-8B layer () at and , how many bytes does materializing and move (BF16), and how long does that take on an H100?
Answer
has elements, and four passes (write , read , write , read ) at 2 bytes each make 275 GB: ≥ 82 ms per layer, 2.6 s for 32 layers. That is just for the score matrices, which do not even fit in 80 GB of HBM. FlashAttention-style tiling is not an optimization at long context; it is what makes exact attention possible at all.
- The crossover, derived. Derive the context length at which the full-square attention-score FLOPs equal the linear-layer FLOPs of an MHA block with a 2-matrix MLP of width . Check it for GPT-3 (, ).
Answer
Linear FLOPs per layer (projections + two MLP matrices); quadratic . Equal when , i.e. for : 73,728 for GPT-3, exactly demo 03’s value. Causal: .
- FP8 and the knee. Show that switching a linear layer from BF16 to FP8 on an H100 leaves the knee token-batch unchanged.
Answer
depends on and only through the product . FP8 doubles , so it doubles , and halves : the product, and hence , is unchanged (325 in demo 01). Both the math time and the memory time halve.
- Can decode ever be compute-bound? For Llama-3-8B decoding with 4,096-token contexts, what is the largest arithmetic intensity a decode step can reach, whatever the batch size?
Answer
As , the shared weight read becomes negligible, and each sequence contributes its FLOPs per token, GFLOP, against its own KV bytes, MB. The cap is ~32 FLOPs/byte, about a ninth of the knee. Decode with long contexts is memory-bound at any batch size; only shrinking the cache (Lecture 4) changes that.
- Glue in a real profile. In demo 04, eager RMSNorm took 2.8× its 2-pass roofline time. Name two different reasons the true traffic exceeds , and the intervention for each.
Answer
(a) Multiple passes: eager PyTorch runs pow, mean, add, rsqrt, mul, mul as six kernels, and each streams a full-size tensor through memory. The fix is fusion: one kernel that computes the row statistic and normalizes while the row is in registers or on-chip memory. (b) Temporaries: each kernel writes an intermediate tensor that the next reads back, which adds writes and reads beyond the ideal. The fix is the same fused kernel, or a compiler that fuses the chain (torch.compile, Lecture 3). At decode sizes a third reason dominates, fixed per-kernel overhead, and fusion is again the fix, since it cuts six launches to one.
16. The related assignment (concepts only)
Fall 2026 A1 (Performance Engineering) is released with this lecture. It asks for exactly today’s skills: count FLOPs and bytes for Transformer operators; predict compute- vs memory-bound with the knee; then write and profile kernels starting from the canonical memory-bound vector add (AI ≈ 1/12), measure achieved bandwidth and FLOP/s, and compute MFU. The concepts you need from this lecture: the GEMM count and the 3× training rule (§4); the lower-bound byte model and the direction of the AI bound (§5.2); the linear-layer regimes and the knee in tokens (§5.3–5.4); the per-operator table (§7.5); and the “both far from peak” case (§10). Lecture 3 adds the kernel-launch vocabulary the assignment’s kernels use. These notes do not reproduce assignment solutions.
17. Research directions
- Hierarchical and measured rooflines for Transformer kernels. Extend the HBM-only model with L2 and shared-memory roofs, and calibrate the byte model against measured traffic. Where does the lower bound fail by the most (re-reads in tiled attention, softmax passes)?
- Small-batch GEMMs. Demo 04 found the CPU’s 16-row GEMMs 3–7× off their roofline. On GPUs, the analogous decode GEMMs underfill the SMs. Kernels that keep decode at the memory roof across batch sizes (split-K, stream-K, GEMV-specialised kernels) are an active topic.
- Fusing the glue automatically. Glue was 14% of measured time with almost no FLOPs. How much of that do compilers (
torch.compile, XLA, Triton-based fusers) recover on real models, and what still needs hand-written kernels? - Prefill/decode-aware architecture. Bottlenecks 2 and 3 are architecture choices. Quantify, for a target product (context length, batch, latency SLO), which of GQA, KV quantization, latent caches and sparse attention moves the binding term most (Lecture 4).
18. Further reading
- J. Austin et al., How to Scale Your Model (jax-ml.github.io/scaling-book): ch. 1 “Rooflines”, ch. 4 “Transformer math”, ch. 7 “Inference”.
- H. He, Making Deep Learning Go Brrrr From First Principles (horace.io/brrr_intro.html): compute, memory and overhead as the three regimes; the clearest short introduction to fusion.
- S. Williams, A. Waterman, D. Patterson, Roofline: An Insightful Visual Performance Model for Multicore Architectures, CACM 52(4), 2009.
- NVIDIA, NVIDIA Hopper Architecture In-Depth (developer blog, 2022) and the Hopper Tuning Guide.
- A. Armbruster, How To Write A Fast Matrix Multiplication From Scratch With Tensor Cores (2024): what it takes for a GEMM to actually sit on the compute roof.
- T. Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness, NeurIPS 2022 (arXiv:2205.14135).
- R. Pope et al., Efficiently Scaling Transformer Inference, MLSys 2023 (arXiv:2211.05102): prefill vs decode, KV-cache costs and partitioning, in the same accounting style.
19. Next lecture
Lecture 3 · All About Performance II (“Performance Strikes Back”): Kernels, Profiling, MFU and Token Economics. Today’s model predicted which roof binds; it said nothing about why a kernel might miss both roofs. Next time we open the GPU’s programming model: grid, blocks (Triton programs), warps, threads, and how warp scheduling and occupancy hide memory latency. We measure what fusion does to the byte count, read a profile with today’s decomposition as the map, diagnose large GEMMs, residual adds and decode with achieved FLOP/s and bytes/s, compute MFU and see why it is a symptom, and price tokens with two clocks: time to first token and time per output token.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| performance / metric | 性能 / 指标 |
| latency / throughput | 延迟 / 吞吐量 |
| time to first token (TTFT) / time per output token (TPOT) | 首 token 延迟 / 每个输出 token 的时间 |
| peak compute / memory bandwidth | 峰值算力 / 内存带宽 |
| lower bound / upper bound | 下界 / 上界 |
| overlap (of compute and memory) | (计算与访存的)重叠 |
| node / NVSwitch / NVLink / network adapter (HCA) | 节点 / NVLink 交换芯片 / NVLink 互联 / 网络适配器 |
| interconnect bandwidth | 互联带宽 |
| die / package / HBM stack | 晶粒 / 封装 / HBM 堆栈 |
| streaming multiprocessor (SM) | 流式多处理器 |
| register / shared memory / L1 / L2 cache | 寄存器 / 共享内存 / 一级缓存 / 二级缓存 |
| memory hierarchy | 存储层次 |
| Tensor Core / CUDA core | 张量核心 / CUDA 核心 |
| tile | 分块(瓦片) |
| FLOP / GEMM | 浮点运算 / 通用矩阵乘 |
| linear layer / projection | 线性层 / 投影 |
| token-batch (B_tok = B·L) | 词元批量 |
| forward / backward pass | 前向 / 反向传播 |
| bytes moved / HBM traffic | 搬运字节数 / 显存流量 |
| arithmetic intensity (AI) | 算术强度 |
| knee / ridge point (AI*) | 拐点 / 屋脊点 |
| roofline model / memory roof / compute roof | 屋顶线模型 / 访存屋顶 / 算力屋顶 |
| compute-bound / bandwidth-bound / overhead-bound | 计算受限 / 带宽受限 / 开销受限 |
| shape reasoning | 形状推理 |
| weight reuse | 权重复用 |
| pre-LN decoder block | 前置 LayerNorm 解码器块 |
| residual stream / residual add | 残差流 / 残差相加 |
| multi-head / grouped-query / multi-query attention | 多头 / 分组查询 / 多查询注意力 |
| score matrix (S) / probability matrix (P) | 分数矩阵 / 概率矩阵 |
| materialize | 物化(把中间结果写入显存) |
| causal mask / upper triangle | 因果掩码 / 上三角 |
| online softmax / tiling | 在线 softmax / 分块计算 |
| gated MLP (SwiGLU) / hidden activations | 门控 MLP / 隐藏层激活 |
| glue op / elementwise op | 胶水算子 / 逐元素算子 |
| LayerNorm / RMSNorm / pass (over memory) | 层归一化 / 均方根归一化 / 遍(对内存的一次完整读写) |
| embedding lookup (gather) | 嵌入查表(收集) |
| fusion / fused kernel | 算子融合 / 融合算子 |
| crossover | 交叉点 |
| mixture of experts (MoE) | 混合专家 |
| KV quantization / latent cache | KV 量化 / 潜在缓存 |
| sparse / hybrid attention | 稀疏 / 混合注意力 |
| warm cache / cold cache | 热缓存 / 冷缓存 |
| kernel launch overhead | 内核启动开销 |
| profiling / profiler | 性能剖析 / 剖析器 |
| model FLOPs utilization (MFU) | 模型算力利用率 |
| symptom vs diagnosis | 症状 vs 诊断 |
| wall-clock time / utilization | 墙钟时间 / 利用率 |