Lecture 2 · All About Performance I: Hardware Ceilings, Arithmetic Intensity and the Roofline

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 02。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

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

本篇目录

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 from code/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:

  1. 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.
  2. Count compute: estimate the FLOPs of a matrix multiply and of each Transformer submodule.
  3. Count data movement: build an explicit model of the bytes moved to and from HBM, and know that it is only a lower bound.
  4. Use arithmetic intensity: compute AI = FLOPs / bytes, interpret it, and distinguish the actual AI from an optimistic bound.
  5. Reason about shapes: predict how changing batch, sequence length, width or heads moves an operator between compute-bound and bandwidth-bound.
  6. Use roofline reasoning: predict when an operator can be compute-bound and when it must be bandwidth-bound.
  7. 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

SectionIdeaCode in code/lecture02/
§2, §5–§6two ceilings, arithmetic intensity, the knee, the rooflineroofline.py (Op, op_times, knee, ascii_roofline)
§5.3–§5.4a linear layer across token-batches, chips and formats01_linear_layer_ai.py
§7attention (MHA vs GQA, naive vs fused), MLP, glue; one block in numbersroofline.py (attention_core, block_ops, model_ops), 02_decoder_block_roofline.py, 03_attention_accounting.py
§7.7, §8the L² crossover; KV cache vs weights in decode03_attention_accounting.py Parts C–D
§9measuring one block, operator by operator04_measure_block_ops.py

0.4 Notation (the course’s global notation for this lecture)

SymbolMeaning
BBbatch size: sequences processed in parallel
LLsequence length: tokens per sequence
Btok=B⋅LB_{\text{tok}} = B \cdot Ltoken-batch (词元批量): the common reshape that turns (B,L,D)(B, L, D) activations into a (Btok,D)(B_{\text{tok}}, D) matrix
DDmodel width (d_model)
NN, HH, NKVN_{KV}query heads, head dimension (D=N⋅HD = N \cdot H), key/value heads (MHA: NKV=NN_{KV} = N; GQA/MQA: NKV<NN_{KV} < N)
FFMLP hidden width (classic 2-matrix MLP: F≈4DF \approx 4D; parameter-matched 3-matrix gated MLP: F≈8D/3F \approx 8D/3)
VVvocabulary size
bbbytes per element (BF16: 2, FP8: 1, FP32: 4)
CpeakC_{\text{peak}}the relevant peak compute for the operator and data type (FLOP/s)
BWHBMBW_{\text{HBM}}peak HBM bandwidth (bytes/s)
AI, AI*arithmetic intensity of an operator; the knee Cpeak/BWHBMC_{\text{peak}}/BW_{\text{HBM}}

The slides adopt a zero-ambiguity rule: every symbol is either in this table or defined, explicitly, where it is used. Lecture 1’s ss (sequence length) and dd (width) are this lecture’s LL and DD.


1. What “performance” means

In systems work, performance is always tied to a metric someone actually experiences:

PhaseMetrics
trainingstep time (ms/step), tokens/s, samples/s, cost per training token
inferencelatency 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):

  1. peak compute throughput CpeakC_{\text{peak}}, in FLOP/s;
  2. peak memory bandwidth BWHBMBW_{\text{HBM}}, in bytes/s, between the chip and its HBM.

Take an operator (one kernel) that must do FLOPsop\text{FLOPs}_{\text{op}} of arithmetic and move bytesop\text{bytes}_{\text{op}} to or from HBM. It cannot finish faster than either resource allows:

Top  ≥  max⁡ ⁣(FLOPsopCpeak,  bytesopBWHBM).T_{\text{op}} \;\ge\; \max\!\left(\frac{\text{FLOPs}_{\text{op}}}{C_{\text{peak}}},\; \frac{\text{bytes}_{\text{op}}}{BW_{\text{HBM}}}\right).

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: T≥bytes exchanged/BWinterconnectT \ge \text{bytes exchanged} / BW_{\text{interconnect}}. 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:

3.35 TB/s⏟GPU↔its HBM  ≫  450 GB/s⏟GPU↔NVSwitch, per direction  ≫  50 GB/s⏟one 400 Gb/s adapter(∼7×, ∼9×).\underbrace{3.35\ \text{TB/s}}_{\text{GPU} \leftrightarrow \text{its HBM}} \;\gg\; \underbrace{450\ \text{GB/s}}_{\text{GPU} \leftrightarrow \text{NVSwitch, per direction}} \;\gg\; \underbrace{50\ \text{GB/s}}_{\text{one 400 Gb/s adapter}}\qquad(\sim 7\times,\ \sim 9\times).

(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:

LevelCapacityWhere
registers256 KB per SMinside each SM; fastest
L1 / shared memory256 KB per SM combined (shared-memory carve-out up to 228 KB)inside each SM
L2 cache50 MBshared by all SMs, on the die
HBM80 GB at 3.35 TB/son the package, off the die

The Tensor Core. One Tensor Core instruction multiplies a small tile, D=A⋅B+CD = A \cdot B + C 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 WQ,WK,WV,WOW_Q, W_K, W_V, W_O, 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-rr vectors does rr multiplies and r−1r-1 adds, which we round to 2r2r. Performance reasoning keeps the leading-order term and drops ±1s.
  • A GEMM C=ABC = AB with A∈Rm×rA \in \mathbb{R}^{m \times r} and B∈Rr×nB \in \mathbb{R}^{r \times n} has mnmn outputs, each a length-rr dot product:

FLOPs(C=AB)≈2mnr.\text{FLOPs}(C = AB) \approx 2mnr.

This formula is the backbone of almost every compute estimate in the course.

  • A linear layer Y=XWY = XW with X∈RBtok×DX \in \mathbb{R}^{B_{\text{tok}} \times D}, W∈RD×FW \in \mathbb{R}^{D \times F} is a GEMM. The BtokB_{\text{tok}} comes from reshaping (B,L,D)(B, L, D) activations to (B⋅L,D)(B \cdot L, D), which is why GEMM efficiency depends on the token-batch, not just the batch. Forward: 2BtokDF2 B_{\text{tok}} D F FLOPs.
  • Training needs, per forward GEMM, two backward GEMMs of the same size: ∇A\nabla_A and ∇B\nabla_B. So forward ≈2mnr\approx 2mnr, backward ≈4mnr\approx 4mnr, 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 (PP ≈ non-embedding parameters in the dense matmuls, NtokN_{\text{tok}} = 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

AI=FLOPsbytes moved[FLOPs/byte].\text{AI} = \frac{\text{FLOPs}}{\text{bytes moved}} \quad[\text{FLOPs/byte}].

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 (BB, LL, DD, FF) 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

AImodel=FLOPsbyteslower bound\text{AI}_{\text{model}} = \frac{\text{FLOPs}}{\text{bytes}_{\text{lower bound}}}

is an upper bound on the true arithmetic intensity. Two consequences:

  • if even this optimistic AImodel<AI∗\text{AI}_{\text{model}} < \text{AI}^*, the operator must be bandwidth-bound; the model certifies it;
  • if AImodel>AI∗\text{AI}_{\text{model}} > \text{AI}^*, compute-bound is only possible. Measure the real traffic before you believe it.

5.3 The linear layer: two regimes

For Y=XWY = XW with the byte model “read XX, read WW, write YY”:

AIlinear≈2BtokDFb (BtokD+DF+BtokF).\text{AI}_{\text{linear}} \approx \frac{2 B_{\text{tok}} D F}{b\,(B_{\text{tok}} D + D F + B_{\text{tok}} F)}.

  • Small token-batch (decode): the weight read DFDF dominates the denominator, so AI≈2Btok/b\text{AI} \approx 2B_{\text{tok}}/b; in BF16, AI≈Btok\text{AI} \approx B_{\text{tok}}. Small batches reuse each weight too little, so they are bandwidth-bound.
  • Very large token-batch (training, prefill): the activation terms dominate, so AI→2DF/(b(D+F))\text{AI} \to 2DF / (b(D+F)). Increasing BtokB_{\text{tok}} further stops helping, because the activations must still be streamed.

5.4 From AI to time: the knee

Dividing the two time lower bounds:

Tmath,minTmem,min=FLOPs/Cpeakbytes/BWHBM=AICpeak/BWHBM,AI∗≡CpeakBWHBM.\frac{T_{\text{math,min}}}{T_{\text{mem,min}}} = \frac{\text{FLOPs}/C_{\text{peak}}}{\text{bytes}/BW_{\text{HBM}}} = \frac{\text{AI}}{C_{\text{peak}}/BW_{\text{HBM}}},\qquad \textbf{AI}^* \equiv \frac{C_{\text{peak}}}{BW_{\text{HBM}}}.

Below the knee (拐点) AI∗\text{AI}^* the operator is bandwidth-bound; above it, compute-bound is possible (other limits may still bite; Lecture 3). On an H100 in dense BF16, AI∗≈989/3.35≈\text{AI}^* \approx 989/3.35 \approx 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 67/3.35≈2067/3.35 \approx 20.

Demo 01 sweeps the course’s example layer (D=4096→F=16384D = 4096 \to F = 16384, BF16) on an H100 (computed):

BtokB_{\text{tok}}FLOPsbytes (≥)AIboundtime (≥)of peak
1134 MFLOP134 MB1.0memory40.1 µs0.3%
324.29 GFLOP136 MB31.7memory40.5 µs10.7%
12817.2 GFLOP139 MB123memory41.6 µs41.7%
32443.5 GFLOP147 MB295(knee)44.0 µs99.8%
81921.10 TFLOP470 MB2,341compute1.11 ms100%
65,5368.80 TFLOP2.82 GB3,121compute8.89 ms100%

Read the time column: from Btok=1B_{\text{tok}} = 1 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 2DF/(b(D+F))=32772DF/(b(D+F)) = 3277. The same weights, read once per step, cost 295× more time per token at Btok=1B_{\text{tok}} = 1 than in training: exactly the knee.

How many tokens does a GEMM need to cross the knee? Solving AIlinear=AI∗\text{AI}_{\text{linear}} = \text{AI}^* for BtokB_{\text{tok}}:

chipformatknee AI*knee BtokB_{\text{tok}}
A100BF16153161
H100BF16295325
H100FP8591325
B200BF16 / FP8 / FP4281 / 562 / 1125308

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

Perf(AI)=min⁡ ⁣(Cpeak, BWHBM⋅AI):\text{Perf}(\text{AI}) = \min\!\big(C_{\text{peak}},\ BW_{\text{HBM}} \cdot \text{AI}\big):

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 (BtokB_{\text{tok}} = 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

  1. Compute the knee: AI∗=Cpeak/BWHBM\text{AI}^* = C_{\text{peak}}/BW_{\text{HBM}}, a property of the hardware and of which pipeline and data type the operator uses.
  2. Compute the operator’s AI: AIop=FLOPsop/bytesop\text{AI}_{\text{op}} = \text{FLOPs}_{\text{op}}/\text{bytes}_{\text{op}}, a property of the algorithm and the shapes.
  3. Compare. With the actual traffic, the lower of the two roofs at AIop\text{AI}_{\text{op}} binds. With a lower-bound byte model, AImodel<AI∗\text{AI}_{\text{model}} < \text{AI}^* certifies bandwidth-bound, while AImodel>AI∗\text{AI}_{\text{model}} > \text{AI}^* only says compute-bound is possible.

What moves an operator on the chart? Shapes and batching move it horizontally: a larger BtokB_{\text{tok}} 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 X∈RB×L×DX \in \mathbb{R}^{B \times L \times D} → 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 B×L×DB \times L \times D, 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 XX, the projections Q=XWQQ = XW_Q, K=XWKK = XW_K, V=XWVV = XW_V (W∈RD×DW \in \mathbb{R}^{D \times D}) are reshaped into heads ∈RB×L×N×H\in \mathbb{R}^{B \times L \times N \times H}. Then, per head,

S=QK⊤H∈RB×N×L×L,P=softmax(mask(S)),A=PV,S = \frac{QK^\top}{\sqrt H} \in \mathbb{R}^{B \times N \times L \times L},\qquad P = \text{softmax}(\text{mask}(S)),\qquad A = PV,

and Yattn=concat(A) WOY_{\text{attn}} = \text{concat}(A)\,W_O.

GQA/MQA: what changes, precisely. Everything about the queries stays the same. Keys and values have fewer heads, K,V∈RB×L×NKV×HK, V \in \mathbb{R}^{B \times L \times N_{KV} \times H}, so the KV cache, which scales with NKVHN_{KV} H, 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 L×LL \times L convention). With r=NKV/Nr = N_{KV}/N:

partparametersforward FLOPs
projections Q, K, V, O2(1+r)D22(1+r)D^2 (MHA: 4D24D^2)4(1+r)BLD24(1+r)BLD^2 (MHA: 8BLD28BLD^2)
QK⊤QK^\top and PVPV04BL2D4BL^2D (unchanged by GQA)

Training is ~3× these. Causal kernels that skip the masked upper triangle use about half the quadratic FLOPs, but keep the O(L2D)O(L^2D) scaling.

Demo 03 Part A makes this concrete for a Llama-3-8B-sized layer at L=8192L = 8192 (computed):

attentionrrprojection paramsprojection FLOPsQK⊤+PVQK^\top + PV FLOPsKV cache (1 layer, 8k)
MHA (32 KV heads)167.1 M1.10 TFLOP1.10 TFLOP128 MiB
GQA-8 (Llama 3)0.2541.9 M687 GFLOP1.10 TFLOP32 MiB
MQA0.0334.6 M567 GFLOP1.10 TFLOP4 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 b(8BLD+4D2)b(8BLD + 4D^2) in total. The BLDBLD terms are residual-stream traffic and the D2D^2 terms are weight reads, which dominate when BLBL is small. A naive quadratic attention materializes SS and PP: write SS, read it for the softmax, write PP, read it for PVPV:

bytesquad,naive≳b (4BLD+4BNL2).\text{bytes}_{\text{quad,naive}} \gtrsim b\,(4BLD + 4BNL^2).

The BNL2BNL^2 term is unique to naive attention and grows quadratically with LL.

Arithmetic intensity.

  • Projections: AIproj≈2BLD/(b(D+2BL))\text{AI}_{\text{proj}} \approx 2BLD/(b(D + 2BL)). This is ≈2BL/b\approx 2BL/b when BL≪DBL \ll D (weights dominate) and ≈D/b\approx D/b when BL≫DBL \gg D. Increasing BLBL pushes it up through weight reuse.
  • Naive quadratic: AIquad≈LH/(b(H+L))→H/b\text{AI}_{\text{quad}} \approx LH/(b(H + L)) \to H/b when L≫HL \gg H. This is almost independent of LL. A longer context adds FLOPs and materialized bytes together, both ∝L2\propto L^2, so naive attention never moves right on the roofline. With H=128H = 128 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. SS and PP are never written to HBM. If QQ, KK, VV are each read once and AA written once, bytes≳4bBLD\text{bytes} \gtrsim 4bBLD and AI≈L/b\text{AI} \approx L/b (about 2048 at L=4096L = 4096 in BF16, or L/(2b)L/(2b) counting causal FLOPs). The slides add an honest caveat: L/bL/b 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 BNL2BNL^2 traffic; the O(L2D)O(L^2D) arithmetic remains. In decode, the dominant issue is usually streaming the KV cache instead.

Demo 03 Part B (computed, GQA-8, B=1B = 1):

LLAI naiveAI fused (causal)naive time ≥fused time ≥naive / fused
5125620523.2 µs3.13 µs7.4×
2,04862820333 µs34.7 µs9.6×
8,192643,2775.18 ms556 µs9.3×
131,0726552,4291.31 s142 ms9.2×

The naive intensity sits at 62–65 for every context from 2k to 128k, exactly as H/b=64H/b = 64 predicts. The fused intensity grows in proportion to LL.

7.3 The MLP

A modern dense block uses a gated MLP (门控 MLP) such as SwiGLU, modelled as three matmuls:

U=XWup,G=XWgate,Z=ϕ(G)⊙U,Y=ZWdown,Wup,Wgate∈RD×F, Wdown∈RF×D.U = XW_{\text{up}},\quad G = XW_{\text{gate}},\quad Z = \phi(G) \odot U,\quad Y = ZW_{\text{down}},\qquad W_{\text{up}}, W_{\text{gate}} \in \mathbb{R}^{D \times F},\ W_{\text{down}} \in \mathbb{R}^{F \times D}.

  • Parameters ≈3DF\approx 3DF: 12D212D^2 if F=4DF = 4D, or 8D28D^2 for a parameter-matched F≈8D/3F \approx 8D/3, the same as a classic 2-matrix MLP with F=4DF = 4D. Either way the MLP carries more parameters than the attention projections (4D24D^2).
  • Forward FLOPs ≈6BLDF\approx 6BLDF, training ≈18BLDF\approx 18BLDF.
  • Bytes (naive: each sub-op reads its inputs and writes its outputs):

bytesMLP≳b (3BLD⏟residual stream+6BLF⏟hidden activations U,G,Z+3DF⏟weights).\text{bytes}_{\text{MLP}} \gtrsim b\,(\underbrace{3BLD}_{\text{residual stream}} + \underbrace{6BLF}_{\text{hidden activations } U, G, Z} + \underbrace{3DF}_{\text{weights}}).

With F=4DF = 4D, the hidden-activation traffic 6BLF=24BLD6BLF = 24BLD exceeds the residual-stream traffic. In an unfused MLP, the intermediates cost more bandwidth than the input and output.

  • AI ≈6BLDF/(b(3BLD+6BLF+3DF))\approx 6BLDF / (b(3BLD + 6BLF + 3DF)), with two regimes: small BLBL gives ≈2BL/b\approx 2BL/b (weights dominate); large BLBL gives →2DF/(b(D+2F))\to 2DF/(b(D + 2F)), which is 8D/(9b)8D/(9b) for F=4DF = 4D (1,820 at D=4096D = 4096 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 Y=X+RY = X + R: BLDBLD FLOPs, 3bBLD3bBLD bytes (read two, write one), so AI=1/(3b)=1/6\text{AI} = 1/(3b) = 1/6 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 DD, then normalize. An ideal standalone kernel reads XX once and writes YY once (2bBLD2bBLD). A naive implementation makes several passes (one for the mean, one for the variance, one to normalize), so its traffic is κ bBLD\kappa\, bBLD with κ≥2\kappa \ge 2. κ\kappa counts how many times the residual stream was streamed through HBM. Norms are archetypal bandwidth operations: O(BLD)O(BLD) math and O(BLD)O(BLD) streaming.
  • Softmax over a length-LL row: max-reduce, exponentiate, sum-reduce, divide, about cLcL FLOPs for a small constant cc, against 2bL2bL bytes. AI=c/(2b)\text{AI} = c/(2b) 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

ComponentParamsForward FLOPsForward bytes (naive, ≥)AI
attention projections (MHA)4D24D^28BLD28BLD^2b(8BLD+4D2)b(8BLD + 4D^2)2BLD/(b(D+2BL))2BLD/(b(D + 2BL))
attention quadratic (QK⊤QK^\top, softmax, PVPV)04BL2D4BL^2Db(4BLD+4BNL2)b(4BLD + 4BNL^2)LH/(b(H+L))LH/(b(H + L))
MLP (gated)3DF3DF6BLDF6BLDFb(3BLD+6BLF+3DF)b(3BLD + 6BLF + 3DF)6BLDF/(b(3BLD+6BLF+3DF))6BLDF/(b(3BLD + 6BLF + 3DF))
norms, residuals, elementwiseO(D)O(D)O(BLD)O(BLD)O(bBLD)O(bBLD), often several passesO(1)O(1)

Everything is at most linear in BLBL except naive attention, which has a quadratic BNL2BNL^2 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 (D=4096D = 4096, 32 query / 8 KV heads of 128, SwiGLU F=14,336F = 14{,}336) 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: QK⊤QK^\top and PVPV 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 2Btok/b2B_{\text{tok}}/b 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):

workloadFLOPsbytes (≥)time (≥)tokens/s (≤)FLOP/s used
prefill 4,096 tokens, naive attention70.4 TFLOP200 GB111 ms37,04364%
prefill 4,096 tokens, fused attention65.9 TFLOP62.4 GB73.2 ms55,96191%
decode step, batch 117.2 GFLOP15.6 GB4.64 ms2150.4%
decode step, batch 641.10 TFLOP50.1 GB15.0 ms4,2797.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 LL grows they eventually dominate the parameter-led linear layers. Per layer, forward (MHA projections, gated MLP, full square):

FLOPsL2FLOPslinear≈4BL2D8BLD2+6BLDF=4L8D+6F  ⟹  L×≈2D+1.5F.\frac{\text{FLOPs}_{L^2}}{\text{FLOPs}_{\text{linear}}} \approx \frac{4BL^2D}{8BLD^2 + 6BLDF} = \frac{4L}{8D + 6F} \;\Longrightarrow\; L^\times \approx 2D + 1.5F.

That is 8D8D for F=4DF = 4D and 6D6D for F=8D/3F = 8D/3, which for D≈7000D \approx 7000 is roughly 42,000–56,000 tokens. With a causal kernel, the quadratic term halves and the crossover doubles: L×≈4D+3FL^\times \approx 4D + 3F, i.e. 16D16D or 12D12D in the same examples.

A note on the slides. The slides print the full-square rule as "L∼2D+3FL \sim 2D + 3F". Their own ratio 4L/(8D+6F)4L/(8D + 6F), and their own examples (8D8D and 6D6D), give 2D+1.5F2D + 1.5F. The causal rule 4D+3F4D + 3F 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):

modelheads / KV headsrule, fullexact, fullrule, causalexact, causal
GPT-3 175B (2-matrix MLP)96 / 9673,72873,728147,456147,455
Llama-2-7B32 / 3224,70424,70449,40849,407
Llama-3-8B32 / 829,69626,62459,39253,247
Llama-3-70B64 / 859,39252,224118,784104,447
Llama-3.1-405B128 / 8112,64097,280225,280194,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 2D+F2D + F / 4D+2F4D + 2F.


8. The three headline bottlenecks

The slides organize everything above into three bottlenecks of dense Transformers. Which one dominates depends on (i) the width DD, (ii) the context length LL, and (iii) the phase: training/prefill vs autoregressive decode.

BottleneckWhat you observeTypical lever
1. MLP/FFN: dense compute and parametershigh compute and many parameters per token; every token pays for every MLP weightmixture 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 bandwidthhigh HBM use and bandwidth during generation, from re-reading the cache each stepreduce NKVN_{KV} (GQA/MQA); reduce bb (KV quantization); cache lower-dimensional representations (latent caches, MLA)
3. L² attention at long context: quadratic scalingcost explodes with context lengthif 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 ≈2LctxnlayersNKVHb\approx 2 L_{\text{ctx}} n_{\text{layers}} N_{KV} H b 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):

batchweights read per stepKV read per step at 8k contextKV sharecontext where KV = weights
115.0 GB1.07 GB6.7%114,512
815.0 GB8.59 GB36%14,314
3215.0 GB34.4 GB70%3,578
12815.0 GB137 GB90%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 D=2048D = 2048 block in eager PyTorch (16 heads / 4 KV heads, SwiGLU F=5632F = 5632, 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’ κ\kappa, 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 SS and PP in memory) takes 9.12 ms. PyTorch’s fused scaled_dot_product_attention gives the same result in 3.60 ms. Two things contribute: it never writes SS and PP 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/TopT_{\text{op}} and achieved bandwidth ≈ bytes/TopT_{\text{op}}. Then:

bandwidthFLOP/sdiagnosis
near peakfar from peakbandwidth-bound
far from peaknear peakcompute-bound
far from peakfar from peakanother limit is active: small shapes or occupancy, launch overhead, dependencies and stalls, missing fusion, synchronization, communication

MFU (model FLOPs utilization): MFU≈model FLOPs per step/(Tstep⋅G⋅Cpeak)\text{MFU} \approx \text{model FLOPs per step} / (T_{\text{step}} \cdot G \cdot C_{\text{peak}}) over GG 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 ≈ 6PNtok6PN_{\text{tok}}), GG GPUs of peak CpeakC_{\text{peak}} at utilization uu need

Ttrain≈6 P NtokG⋅u⋅Cpeak.T_{\text{train}} \approx \frac{6\,P\,N_{\text{tok}}}{G \cdot u \cdot C_{\text{peak}}}.

Three levers change it most: more GPUs GG (if scaling efficiency holds; Lectures 5–6), higher utilization uu (kernel quality, bandwidth limits, communication: today and Lecture 3), and better algorithms that change PP 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):

  1. What is the dominant operator? (attention matmuls? MLP matmuls? norms? KV reads?)
  2. What are its shapes? (BB, LL, DD, FF, NN, NKVN_{KV})
  3. Compute FLOPs and bytes. Even approximate is useful.
  4. Compute AI and compare it to AI*. Lower-bound bytes give an optimistic upper bound on AI.
  5. Form a hypothesis: compute-, bandwidth- or overhead-bound.
  6. 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

  1. On one GPU the two headline resources are compute throughput and HBM traffic; across GPUs, communication adds a third.
  2. T≥max⁡(FLOPs/Cpeak,bytes/BW)T \ge \max(\text{FLOPs}/C_{\text{peak}}, \text{bytes}/BW). 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.
  3. The knee AI* = Cpeak/BWC_{\text{peak}}/BW 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.
  4. A linear layer’s AI is ≈2Btok/b\approx 2B_{\text{tok}}/b at small token-batch and saturates at 2DF/(b(D+F))2DF/(b(D+F)). On an H100 a GEMM needs ~325 tokens to reach the knee. Lower precision does not change that number; newer chips raise it.
  5. Dense MLP matmuls carry most parameters and are compute-efficient at large token-batch. Decode makes every linear layer weight-bandwidth-bound.
  6. GQA shrinks the KV cache and projection work, but not the score FLOPs. Naive attention’s AI is stuck near H/bH/b at any length. FlashAttention removes the BNL2BNL^2 traffic but keeps the O(L2D)O(L^2D) arithmetic, which overtakes the linear layers beyond L≈2D+1.5FL \approx 2D + 1.5F (full) or 4D+3F4D + 3F (causal).
  7. 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.
  8. The headline bottlenecks are MLP compute, decode KV bandwidth and L² attention. Prefill and decode are different physics.
  9. 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 Btok=B⋅LB_{\text{tok}} = B \cdot L. A decode step has Btok=BB_{\text{tok}} = B, not B⋅LctxB \cdot L_{\text{ctx}}.
  • 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 L2L^2 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

  1. The canonical memory-bound op. What is the AI of an fp32 vector add c=a+bc = a + b? How long does it take on an H100 for 2282^{28} elements, at best?
Answer

One add per element; read 2 × 4 bytes and write 4 bytes: AI=1/12\text{AI} = 1/12 FLOPs/byte, about 3,500× below the knee. Bytes =12⋅228=3.22= 12 \cdot 2^{28} = 3.22 GB, so T≥3.22 GB/3.35 TB/s=0.96T \ge 3.22\ \text{GB}/3.35\ \text{TB/s} = 0.96 ms. The interesting question is never “how many FLOP/s”, but what fraction of 3.35 TB/s a kernel reaches.

  1. A knee in tokens. Llama-3-70B’s MLP has D=8192D = 8192, F=28,672F = 28{,}672. How many tokens must the up-projection GEMM process (BF16, H100) to reach the knee?
Answer

B∗=AI∗bDF/(2DF−AI∗b(D+F))B^* = \text{AI}^* b D F / (2DF - \text{AI}^* b (D + F)) with AI∗=295.3\text{AI}^* = 295.3, b=2b = 2: B∗≈310B^* \approx 310. As in demo 01, a few hundred tokens: a decode batch of 64 is far below it.

  1. Reading a profile. A residual add over Btok=8192B_{\text{tok}} = 8192, D=4096D = 4096 (BF16) takes 70 µs. What bandwidth did it achieve, and what is the lever?
Answer

Bytes =3⋅2⋅8192⋅4096=201= 3 \cdot 2 \cdot 8192 \cdot 4096 = 201 MB; 201 MB/70 μs=2.88201\ \text{MB}/70\ \mu\text{s} = 2.88 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 RR, so that XX and RR never make a separate round trip.

  1. Why naive attention cannot scale. For one Llama-3-8B layer (N=32N = 32) at L=32,768L = 32{,}768 and B=1B = 1, how many bytes does materializing SS and PP move (BF16), and how long does that take on an H100?
Answer

SS has NL2=3.44×1010N L^2 = 3.44 \times 10^{10} elements, and four passes (write SS, read SS, write PP, read PP) 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.

  1. 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 FF. Check it for GPT-3 (D=12,288D = 12{,}288, F=4DF = 4D).
Answer

Linear FLOPs per layer =8BLD2+4BLDF= 8BLD^2 + 4BLDF (projections + two MLP matrices); quadratic =4BL2D= 4BL^2D. Equal when 4L=8D+4F4L = 8D + 4F, i.e. L=2D+F=6DL = 2D + F = 6D for F=4DF = 4D: 73,728 for GPT-3, exactly demo 03’s value. Causal: 4D+2F=12D=147,4564D + 2F = 12D = 147{,}456.

  1. FP8 and the knee. Show that switching a linear layer from BF16 to FP8 on an H100 leaves the knee token-batch unchanged.
Answer

B∗=AI∗bDF/(2DF−AI∗b(D+F))B^* = \text{AI}^* b DF / (2DF - \text{AI}^* b(D + F)) depends on AI∗\text{AI}^* and bb only through the product AI∗⋅b\text{AI}^* \cdot b. FP8 doubles CpeakC_{\text{peak}}, so it doubles AI∗\text{AI}^*, and halves bb: the product, and hence B∗B^*, is unchanged (325 in demo 01). Both the math time and the memory time halve.

  1. 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 B→∞B \to \infty, the shared weight read becomes negligible, and each sequence contributes its FLOPs per token, 2Nmatmul+4nlayersNHLctx≈17.22N_{\text{matmul}} + 4 n_{\text{layers}} N H L_{\text{ctx}} \approx 17.2 GFLOP, against its own KV bytes, 2nlayersNKVHbLctx=5372 n_{\text{layers}} N_{KV} H b L_{\text{ctx}} = 537 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.

  1. 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 2bBLD2bBLD, 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.

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 cacheKV 量化 / 潜在缓存
sparse / hybrid attention稀疏 / 混合注意力
warm cache / cold cache热缓存 / 冷缓存
kernel launch overhead内核启动开销
profiling / profiler性能剖析 / 剖析器
model FLOPs utilization (MFU)模型算力利用率
symptom vs diagnosis症状 vs 诊断
wall-clock time / utilization墙钟时间 / 利用率
← 返回课程目录