Lecture 3 · All About Performance II ("Performance Strikes Back"): Kernels, Profiling, MFU and Token Economics

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

课程源码 ZIP ↓

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

本篇目录

Maps to: UC Berkeley EE 290/194 Scalable AI, Fall 2026 Lecture 3 (Sep 2, 2026), slides lecture3.pdf (43 slides), Performance Strikes Back: Profiling, MFU, and bottlenecks. Spring 2026 covered this material in its Lecture 2 extension session (Jan 27, 2026). Recommended readings (course schedule, shared with Lecture 2): the Scaling Book (ch. 1, 4, 7); H. He, Making Deep Learning Go Brrrr From First Principles; the GPU performance engineering resources list; A. Armbruster’s tensor-core matmul tutorial. Other sources: the two NVIDIA technical blogs the slides take their screenshots from (Profiling LLM Training Workflows on NVIDIA Grace Hopper, 2025; Accelerating HPC Applications with NVIDIA Nsight Compute Roofline Analysis, 2020); the Triton documentation; the CUDA occupancy limits for compute capability 9.0; J. D. C. Little, A Proof for the Queuing Formula L = λW (1961); A. Chowdhery et al., PaLM (2022), which introduced MFU. Every number labelled measured comes from code/lecture03/ on the author’s laptop (Apple M4 Pro, Python 3.13, PyTorch 2.14). Numbers labelled computed come from the code’s models. Code: code/lecture03/: kernel_sim.py (occupancy, waves, Little’s law, a tile-program emulator) and five demos, each running in under half a minute. Reading time: ~2 hours for the prose; ~30 minutes for the demos.


0. How to read this lecture

0.1 Learning goals

From the slides. After this lecture you should be able to:

  1. Name the launch hierarchy (grid, block or Triton program, warp, thread) and say what occupancy is for.
  2. Explain fusion: why glue operations are bandwidth-bound, and how one kernel changes the byte count.
  3. Measure the right things: end-to-end metrics and an operator- or kernel-level breakdown.
  4. Diagnose a bottleneck: turn achieved FLOP/s and bytes/s into compute-, bandwidth-, overhead- or communication-bound.
  5. Compute and interpret MFU, a symptom metric, not a diagnosis.
  6. Name the active bottleneck (MLP, decode KV or L²), and convert FLOPs plus utilization into wall-clock time and cost.

Meta-skill. Lecture 2 taught count → predict. Today closes the loop: measure → hypothesis → intervention → re-measure.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 2: the two roofs, arithmetic intensity (AI), the knee (≈ 295 FLOPs/byte for H100 BF16), and the per-operator accounting of a decoder block.
  • Scope: what happens below the roofline, meaning how a kernel’s work is placed on the GPU and why it can miss both roofs. Also the tools and the arithmetic of diagnosis, MFU, and the economics of training and serving time.
  • Not in scope today: writing Triton kernels (that is the assignment; office hours teach the API); multi-GPU communication (Lectures 5–6); FlashAttention’s algorithm (Lecture 7); serving engines (Lectures 22–23).

0.3 Section → code map

SectionIdeaDemo in code/lecture03/
§2grid, blocks, warps, masks, divergence, occupancy, waves, tiles01_launch_and_occupancy.py (with kernel_sim.py)
§2.5, §3latency hiding (Little’s law), threads, fixed per-op overhead02_latency_hiding.py
§4fusion as a bytes intervention; cross-entropy’s peak memory03_fusion.py
§5–§7reading a profile; MFU vs kernel utilization04_profile_training_step.py
§7, §9MFU worked example; training days; TTFT vs TPOT; $ per token; batching under an SLO05_mfu_and_token_economics.py

0.4 Notation

As in Lecture 2: B,L,Btok=BL,D,F,N,H,NKV,bB, L, B_{\text{tok}} = B L, D, F, N, H, N_{KV}, b, CpeakC_{\text{peak}}, BWHBMBW_{\text{HBM}}, AI, AI*. New today: TopT_{\text{op}} (measured time of one operator), TstepT_{\text{step}} (measured step time), GG (number of GPUs), uu (utilization: MFU or a kernel’s own), TTFT (time to first token) and TPOT (time per output token).


1. Last time, on one page

An operator that does FLOPsop\text{FLOPs}_{\text{op}} of math and moves bytesop\text{bytes}_{\text{op}} cannot beat

Top≥max⁡ ⁣(FLOPsopCpeak, bytesopBWHBM),AI=FLOPsbytes,AI∗=CpeakBWHBM.T_{\text{op}} \ge \max\!\left(\frac{\text{FLOPs}_{\text{op}}}{C_{\text{peak}}},\ \frac{\text{bytes}_{\text{op}}}{BW_{\text{HBM}}}\right),\qquad \text{AI} = \frac{\text{FLOPs}}{\text{bytes}},\qquad \text{AI}^* = \frac{C_{\text{peak}}}{BW_{\text{HBM}}}.

The decision rule: if the actual AI < AI*, the operator is bandwidth-bound; if the actual AI > AI*, compute-bound is possible. A lower-bound byte count gives an optimistic upper bound on AI. Inside a decoder block, the attention projections and the MLP are large GEMMs whose AI rises with BtokB_{\text{tok}} through weight reuse. Quadratic attention does O(L2D)O(L^2D) math, and its naive implementation moves O(BNL2)O(BNL^2) bytes for SS and PP. The glue (norms, residual adds, softmax, elementwise) has low AI and is bandwidth-bound unless fused. H100 SXM, dense BF16: 989 TFLOP/s, 3.35 TB/s, knee ≈ 295.

Today’s job: Lecture 2 predicted the bottleneck. Today we measure it, name it, and pick the matching lever.


2. How a kernel actually runs

2.1 Why this belongs in a profiling lecture

Lecture 2 showed the hardware: SMs, Tensor Cores, an HBM roof. That does not yet say how work is chopped up when you launch a kernel. And that matters, because the most common profiler finding is neither “bandwidth-bound” nor “compute-bound”: it is “both far from peak”. That is usually occupancy, launch overhead or missing fusion, not a wrong CpeakC_{\text{peak}}, and you cannot diagnose it from FLOPs and bytes alone.

2.2 The launch hierarchy

The programming model’s vocabulary is nested:

grid⊃blocks⊃warps⊃threads.\text{grid} \supset \text{blocks} \supset \text{warps} \supset \text{threads}.

  • The grid (网格) is all the blocks you launched. Blocks are independent; the hardware may run them in any order, on any SM, concurrently.
  • An SM runs one or more blocks at a time, as many as its registers and shared memory allow.
  • Inside a block, work moves in warps (线程束) of 32 threads that execute in lockstep.

Triton, the language of the course’s assignment, calls a block a program (程序实例): tl.program_id(0) asks “which block am I?”.

2.3 A block is a program: tiles, the grid and the mask

The canonical elementwise pattern is

pid  = program_id(0)
offs = pid * BLOCK + arange(0, BLOCK)      # this program owns BLOCK consecutive elements
mask = offs < n_elements                   # lanes past the end do nothing

with #blocks = ⌈N / BLOCK⌉ (triton.cdiv). The GPU is allowed to run many of those blocks at once on many SMs. The last block usually overshoots NN, and the mask is what makes odd sizes correct. That is why tests always include sizes that are not powers of two.

kernel_sim.py contains a tiny emulator of this model. A “kernel” is a Python function of its program id that can only touch memory through masked load and store calls, and every byte is counted. Demo 01 Part A launches y=a⋅x+yy = a \cdot x + y (axpy) over N=1,000,003N = 1{,}000{,}003 fp32 elements with BLOCK = 1024 (measured in the emulator):

quantityvalue
grid = cdiv(N, BLOCK)977 programs
active lanes in the last program579 of 1024 (445 masked)
result equals numpy’s ax+ya x + yyes
bytes read / written (counted)8.00 MB / 4.00 MB
counted total vs the byte model 3 × 4 × N12,000,036 = 12,000,036
arithmetic intensity2 FLOPs / 12 bytes ≈ 0.17

Without the mask, program 976 reads past the end of the array. The emulator raises an error; a GPU would read garbage or crash. The counted traffic equals Lecture 2’s byte model exactly, because for a perfectly streaming kernel the model is not a bound but the truth. One more point from the slides: a wrapper that calls .contiguous() on its inputs before launching is itself a bytes cost, a full copy that a kernel able to handle strides would avoid.

2.4 A warp is 32 threads with one instruction stream

NVIDIA GPUs execute a block as warps: #warps = #threads / 32. In Triton this is the launch parameter num_warps (often 4, i.e. 128 threads). SIMT (single instruction, multiple threads, 单指令多线程) in one sentence: all 32 lanes issue the same instruction. If some lanes take the other side of a branch, the warp runs both sides and masks lanes off.

Demo 01 Part B computes the issue efficiency when each lane independently takes branch A with probability pp (equal-cost branches):

pp01/320.10.50.91
issue efficiency100%61%51%50%51%100%

A rare branch hurts almost as much as a fair coin: one lane on the other side is enough to make the whole warp execute it. Contiguous arange tiles keep a warp’s lanes on the same path, which is one reason the tile pattern of §2.3 is the default.

When does num_warps matter? For an elementwise kernel, hardly at all past a reasonable BLOCK: each thread is independent. For reductions (RMSNorm, softmax, cross-entropy), the threads of a block must combine values, so the number of warps changes how the reduction is staged and how busy the SM stays.

2.5 Warp scheduling hides memory latency

An HBM load takes hundreds of cycles. The SM does not wait politely: it parks the waiting warp and issues an instruction from another warp that is ready. With enough warps, every memory wait overlaps with someone else’s work. This is latency hiding (延迟隐藏), and it is what makes the max (not the sum) in the roofline bound achievable. The requirement is enough eligible warps on each SM. With only one resident warp, every HBM miss becomes idle time, and both roofs look empty.

How many is “enough”? Little’s law (Little 1961) answers it: in a steady flow, bandwidth = bytes in flight / latency. Assume an HBM load latency of ~600 ns. That is an order-of-magnitude assumption, not a datasheet number, and the conclusions scale with it. Then demo 02 Part A computes (model):

  • to stream 3.35 TB/s, 2.0 MB must be in flight, about 15 KB per SM;
  • with one 4-byte load in flight per thread, that takes 119 warps per SM, more than the 64 an SM can hold, so such a kernel cannot reach the memory roof;
  • with 16-byte (vectorized) loads it takes 30 warps; with four independent 16-byte loads per thread, only 7.4.

Wide loads and independent work per thread (instruction-level parallelism) substitute for occupancy. This is also why the course’s kernels load whole tiles at once.

The same physics is visible on a CPU (demo 02 Part B, measured). One thread copies a 512 MiB array at 126 GB/s; eight threads copy it at 237 GB/s (1.9×). A single core cannot keep enough memory requests in flight to saturate DRAM; more independent request streams can.

2.6 Occupancy: how many warps can actually live on an SM

Occupancy (占用率) is the fraction of an SM’s warp slots (64 on an H100) that are filled. It is limited by registers per thread, shared memory per block, the block size, and a cap of 32 resident blocks. Each limit gives a maximum number of resident blocks, and the smallest wins. Demo 01 Part C (computed with compute-capability-9.0 limits):

threads/blockregs/threadsmem/blockblocks/SMwarps/SMoccupancylimiter
1283201664100%warp slots
12864083250%registers
12825502812.5%registers
1024320264100%warp slots
1286448 KB41625%shared memory
51264200 KB11625%shared memory

The slides name two ways to underfill the machine:

  1. Not enough work. A decode GEMM with Btok=1B_{\text{tok}} = 1 launches a tiny grid, and most SMs get nothing.
  2. Oversized programs. A huge BLOCK, too many registers or too much shared memory means few blocks fit per SM, so few warps are around to hide latency.

How it shows up in a profile: achieved FLOP/s and achieved bandwidth are both well below peak, even though the roofline said one of them should bind. The first question is then: is the GPU busy, or are warps simply missing? High occupancy is not a goal in itself. GEMM kernels often run at low occupancy on purpose, using registers and shared memory for large tiles, and hide latency with independent work per thread instead (§2.5).

2.7 Waves and tiles: filling 132 SMs

A grid runs in waves (波次): at most (blocks per SM × 132) blocks at once. If the last wave is only partly full, the SMs that have nothing to do in it are idle; this is wave quantization (波次量化). A tiled GEMM launches one block per output tile, and partial tiles at the edges are padded. Demo 01 Part D (computed; elementwise BLOCK = 1024 with 16 blocks per SM; GEMM tiles 128 × 128 with one per SM):

kernelblocks / tileswaveswave efficiencySMs busy (1st wave)useful tile area
residual add, prefill 8192 × 409632,7681697.0%100%–
residual add, decode 1 × 4096410.2%3.0%–
MLP up GEMM, prefill 8192 × 14,3367,1685598.7%100%100%
MLP up GEMM, decode 1 × 14,336112184.8%84.8%0.8%
an unlucky GEMM with 133 tiles133250.4%100%100%

Decode is the extreme case. A 1 × 4096 residual add occupies 4 of 132 SMs. A 1 × 14,336 GEMM with 128-row tiles has 112 tiles (fewer than the SMs), and only 1/128 of each tile is real work. Real libraries therefore ship different code paths for small batches, such as GEMV kernels, split-K and stream-K decompositions. The unlucky 133-tile GEMM needs two waves for 1.01 waves of work. None of these effects appears in FLOPs or bytes; all of them miss both roofs.

2.8 Two knobs you will turn: BLOCK and num_warps

The assignment asks you to sweep or autotune two launch parameters. They are occupancy knobs, not accuracy knobs:

  • BLOCK: how many elements (or how large a tile of a row) one program owns. A larger BLOCK means fewer programs in the grid and more work per program.
  • num_warps: how many warps that program may use. More warps can help reductions; they also cost registers and can lower occupancy.

The slides give a useful prior, not a prescription: elementwise kernels often flatten out near BLOCK ≈ 1024; row reductions are the kernels that care about num_warps; very large BLOCKs per program hurt occupancy. Measure, don’t memorize.


3. The third regime: fixed overheads

Horace He’s Brrr essay, one of the recommended readings, divides time into three regimes: compute, memory bandwidth and overhead (开销), meaning time spent on anything other than moving or computing tensor data. In eager PyTorch that is the Python interpreter, operator dispatch, allocation and, on a GPU, launching each kernel. On a GPU each eager operator typically costs a few microseconds of CPU-side work. The GPU races through small kernels faster than the CPU can issue them, so it sits idle between them.

Demo 02 Part C measures the CPU’s version of this floor (measured, torch.add(a, b, out=c) in fp32):

elements1641,02416,3844,194,30467,108,864
time per op373 ns361 ns420 ns1.55 µs147 µs3.55 ms

From 1 to 1,024 elements the time is flat at ~0.36–0.42 µs: the operator does almost nothing, and the fixed cost is everything. Below roughly 6,700 elements (80 KB), the fixed cost exceeds the time to move the bytes. Such kernels are overhead-bound, far below both roofs. Lecture 2’s demo 04 met the same effect: a decode-sized RMSNorm (six eager operators on 2,048 numbers) took ~4.5 µs against a 117 ns roofline.

The remedies attack the number of launches, not their speed: fuse operators (§4); capture a whole sequence of kernels once and replay it with one launch (CUDA graphs, used by every serving engine; Lecture 23); batch more work into each call; or compile the model (torch.compile, which does both fusion and graph capture).


4. Operator fusion: a bytes intervention

4.1 Stop writing the intermediates to HBM

Eager PyTorch runs a model as a sequence of kernels. Each kernel typically reads its inputs from HBM, computes, and writes its outputs back to HBM. The slides’ example is the tail of a SwiGLU MLP,

u=SiLU(a),y=u⊙b,u = \text{SiLU}(a),\qquad y = u \odot b,

which is two kernels unless fused: read aa, write uu; then read uu and bb, write yy. The tensor uu never needed to reach HBM at all. Fusion (算子融合) keeps the same FLOPs and deletes round trips. AI = FLOPs / bytes rises because the denominator shrinks. That is why fusion is the lever for glue, and why FlashAttention is fusion plus tiling for SS and PP.

4.2 Fusion, counted

Count passes: one read or one write of a full-size tensor. Demo 03 Part A (computed, H100, BF16, Btok=8192B_{\text{tok}} = 8192, D=4096D = 4096, F=14,336F = 14{,}336):

chainpasses unfusedpasses fusedbytes unfused → fusedtime unfused → fusedbound on speed-up
scale-shift (x+r)⋅s+t(x + r) \cdot s + t73470 → 201 MB140 → 60 µs2.33×
residual add + RMSNorm104671 → 268 MB200 → 80 µs2.50×
SwiGLU tail SiLU(G)·U531.17 GB → 705 MB351 → 210 µs1.67×

Where do the passes come from? Eager residual + RMSNorm is an add (read xx, read rr, write hh), then pow (read, write), mean (read), and two multiplies (read and write each): 10 passes. A fused kernel reads xx and rr once and writes hh (the next residual stream) and yy, which is 4 passes; the per-row statistic stays in registers. The slides’ variant, a residual add folded into the kernel that produces RR, follows the same logic.

Cross-entropy over a large vocabulary shows that fusion can also be a memory fix. With Btok=8192B_{\text{tok}} = 8192 and Llama 3’s V=128,256V = 128{,}256, the logits alone are a 1-billion-element matrix. A naive forward and backward writes the softmax probabilities in fp32, keeps them alive for the backward pass, reads them back, and writes the gradient: about 12 bytes per element, 12.6 GB moved, and 4.2 GB of probabilities resident at once. A fused kernel computes each row’s maximum and sum in one pass, then the gradient ∂ℓ/∂z\partial \ell / \partial z in a second. The probabilities live only in registers and on-chip tiles. That is ~6 bytes per element (6.3 GB), and only 65.5 kB of row statistics. At this vocabulary size the peak-memory saving is often what decides the batch size that fits.

4.3 Measured: does fusion deliver?

Demo 03 Part B compares eager PyTorch with kernels fused by torch.compile, which on a CPU generates fused C++ loops. All tensors are 4096 × 4096 fp32 (measured; timings vary by tens of percent between runs, especially for the compiled kernels):

chaineagerfusedmeasured speed-upbyte-model boundfused kernel’s bandwidth
scale-shift2.15 ms0.97 ms2.22×2.33×208 GB/s
residual + RMSNorm3.04 ms1.92 ms1.58×2.50×140 GB/s
SiLU(G)·U2.59 ms2.29 ms1.13×1.67×88 GB/s

The results agree with eager to within 2×10−62 \times 10^{-6}. The last column explains the shortfalls. The fused scale-shift streams at about this machine’s DRAM bandwidth, so the byte model applies and the speed-up nearly matches it. The other two fused kernels stream far below DRAM bandwidth, so memory is no longer what limits them. The most likely remaining limit is their math (the exponential in SiLU, the row reduction in RMSNorm) on the CPU’s vector units. Fusion did its job: it moved those kernels toward their knee, and the next lever would be making the math itself cheaper. That is the measure → hypothesis → intervention → re-measure loop in miniature.

4.4 What fusion does not do

Fusion removes intermediate traffic. It cannot remove the bytes an operator must read and write once, and it does nothing for an operator that is already compute-bound, such as a large GEMM. It also has costs. A fused kernel holds more live state per thread (registers, shared memory), which can lower occupancy (§2.6). Every fused combination is a kernel someone has to write, generate or autotune. Compilers (torch.compile, XLA) fuse elementwise chains well. Fusions that change the algorithm, such as online softmax in FlashAttention or the two-pass cross-entropy, usually still need a hand-designed kernel.


5. The profiling mindset

5.1 Three questions and a loop

Profiling should answer three questions: (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 (a kernel, a schedule or an architecture change)? The discipline is a loop:

measure→hypothesis→intervention→re-measure.\textbf{measure} \rightarrow \textbf{hypothesis} \rightarrow \textbf{intervention} \rightarrow \textbf{re-measure}.

If you cannot clearly state the hypothesis, you are not done diagnosing.

5.2 What to measure

levelmetricstells you
end-to-endtraining: step time, tokens/s, samples/s; inference: TTFT, per-token latency, throughputwhether you are improving
kernel / operatortime per kernel; achieved FLOP/s; achieved bandwidth; signs of overhead (many tiny kernels, poor fusion)why

You need both. An end-to-end gain without a kernel story is luck. A kernel gain without an end-to-end gain was not on the critical path.

5.3 Reading a timeline

The slides show an Nsight Systems timeline of Llama 2 7B supervised fine-tuning (from NVIDIA’s 2025 blog on profiling LLM training on Grace Hopper). It is collected with a command of the form nsys profile -t cuda,nvtx,osrt,cudnn,cublas. Read it top to bottom: CPU cores, the process, the CUDA hardware row (kernels and memory copies), then the PyTorch threads (pt_main_thread, pt_autograd). Gray in the GPU row is idle time. Three things to look for:

  1. Is the CUDA hardware row dense or gappy? Gaps mean the GPU is waiting, on the CPU, on data or on communication.
  2. Which named kernels own the area? In that trace, Hopper BF16 Tensor-Core GEMMs (sm90_xmma_gemm_bf16…) take about 50% of GPU time. Elementwise kernels take about 16%: unfused glue. Kernels are 99.5% of GPU activity and CPU↔GPU copies 0.5%, so host interconnect is not the story, though HBM vs compute still might be. A “31 kernel groups hidden” line is the long tail of tiny glue kernels.
  3. Do CPU waits (pthread_cond_wait, NCCL bars) line up with GPU idle? Then the GPU is starved by the host or by communication.

5.4 Which tool answers which question

questiontoolwhat you read
is the step faster?wall clock, tokens/send-to-end only
where is the time?Nsight Systems, or the PyTorch profilertimeline and kernel list
why is this kernel slow?Nsight Computeachieved FLOP/s, bandwidth, occupancy
are we near model peak?MFU from step timea symptom, not a kernel diagnosis

The slides’ standard for the assignment applies everywhere: a pretty trace with no claim is not a diagnosis. “The GEMM is 40% of the time because its AI is above the knee” is.

5.5 The Nsight Compute roofline

Nsight Compute’s roofline chart (collected with ncu --set detailed) is the GUI version of Lecture 2’s decision rule, drawn for one kernel. A point to the right of the knee near the flat roof means compute-bound is possible. A point on the diagonal far to the left means bandwidth-bound. A point far below both means occupancy or latency trouble, the “both far from peak” case. The “Speed of Light” bars under it, SM% vs Memory%, are the same two numbers as achieved FLOP/s and achieved bandwidth, as fractions of their peaks.

5.6 A Transformer profile is last lecture with timestamps

Lecture 2’s decomposition is the map for reading a profile. Typical kernel names fall into three buckets: large GEMMs (cuBLAS, CUTLASS or Triton) for the attention projections and the MLP; attention kernels (FlashAttention or FMHA) for QK⊤QK^\top, softmax and PVPV, hopefully without materializing SS and PP; and glue (elementwise, norms, residual adds, embeddings): low-AI kernels, often many of them. The first question, before any optimization: does most time sit in the big matmuls, as the accounting predicted, or have glue, launch overhead or communication become visible? If the latter, fusion and batching usually beat micro-optimizing a GEMM that is already near its roof.

Demo 04 profiles one full training step (forward, backward, AdamW) of a small Transformer on the laptop’s CPU: d=512d = 512, 4 layers, 8 heads / 2 KV heads, SwiGLU, 8 sequences of 256 tokens, manual attention. Using torch.profiler (measured):

bucketshare of step timeshare of model FLOPs
matmul (GEMM)58%~100%
glue (elementwise, norms, RoPE, loss, copies)19%~0%
AdamW update10%~0%
attention softmax + mask9%~0%
framework (autograd, dispatch) and views4%~0%

The FLOP count and the time profile disagree, and the disagreement is the optimization opportunity. One honest finding: forward and backward make about 15,500 operator calls per step, yet operators averaging under 10 µs take only ~2% of the time. At this size the glue is real bandwidth work on full tensors, not launch overhead. Overhead takes over at decode-sized shapes (§3).


6. From profiler numbers to a bottleneck hypothesis

6.1 The rule

For an operator with known FLOPs and bytes and a measured time TopT_{\text{op}}:

achieved FLOP/s≈FLOPsopTop,achieved bandwidth≈bytesopTop.\text{achieved FLOP/s} \approx \frac{\text{FLOPs}_{\text{op}}}{T_{\text{op}}},\qquad \text{achieved bandwidth} \approx \frac{\text{bytes}_{\text{op}}}{T_{\text{op}}}.

bandwidthFLOP/shypothesis
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

The mental model is always the roofline: is my point stuck under the memory roof or under the compute roof, or under neither?

6.2 Three worked examples from the slides

A large training GEMM. The MLP up-projection Y=XWY = XW with Btok=8192B_{\text{tok}} = 8192, D=4096D = 4096, F=16,384F = 16{,}384, BF16: FLOPs =240≈1.10×1012= 2^{40} \approx 1.10 \times 10^{12}; bytes ≳ 470 MB; optimistic AI ≈ 2,340 ≫ 295. Suppose the profiler reports 1.20 ms. Then the GEMM achieves 917 TFLOP/s (93% of peak) and 0.39 TB/s (12% of bandwidth). Hypothesis: near the compute roof, far from the memory roof, so compute-bound, matching the prediction. A further speed-up here needs a better GEMM (layout, data type, kernel), not fusion with a neighbour.

A residual add, same token-batch: Y=X+RY = X + R with Btok=8192B_{\text{tok}} = 8192, D=4096D = 4096: FLOPs ≈ 3.36×1073.36 \times 10^7; bytes ≳ 201 MB; AI = 1/6 ≪ 295. At 70 µs it achieves 2.87 TB/s (86% of bandwidth) and 0.48 TFLOP/s. That FLOP rate is far below the Tensor-Core roof, but this is not Tensor-Core work anyway. Hypothesis: bandwidth-bound. The lever is fusion, folding the add into its producer or consumer so XX and RR never round-trip through HBM. Making the add “compute faster” is not available.

Decode makes the same GEMM bandwidth-bound. The same up-projection with Btok=1B_{\text{tok}} = 1: FLOPs =2DF≈1.34×108= 2DF \approx 1.34 \times 10^8; bytes ≳ 134 MB, dominated by the weight read; AI ≈ 1. The memory floor is 134 MB / 3.35 TB/s ≈ 40 µs. At 50 µs it achieves 2.7 TB/s (~80% of bandwidth) and 2.7 TFLOP/s. Same operator, different shape, different roof. Training and prefill sat under the compute roof; decode sits under the memory roof, because the weights are streamed and barely reused. “Just look at the kernel name” is not a diagnosis: you also need the shapes.

6.3 When both are far from peak

If achieved FLOP/s and achieved bandwidth are both well below their roofs, the roofline is not the active limit. The common other limits in Transformers:

  • launch / grid overhead: many tiny kernels (unfused glue) whose launch time rivals their work (§3);
  • occupancy and wave quantization: shapes too small to fill the SMs, such as decode GEMMs and narrow heads (§2.6–2.7);
  • dependencies and stalls: a kernel waits for the previous one, and the GPU idles;
  • communication: Tcomm≥bytes/BWinterconnectT_{\text{comm}} \ge \text{bytes}/BW_{\text{interconnect}} (Lecture 2’s node numbers), invisible if you only look at local FLOPs and HBM bytes.

What to do: do not try to “raise MFU” yet. First ask whether the GPU is busy at all. If not, the intervention is fusion, larger batches, a better schedule or less communication, not a faster Tensor-Core kernel.


7. MFU: model FLOPs utilization

7.1 Definition and limits

With GG accelerators of per-device peak CpeakC_{\text{peak}}:

MFU≈model FLOPs per stepTstep⋅G⋅Cpeak.\text{MFU} \approx \frac{\text{model FLOPs per step}}{T_{\text{step}} \cdot G \cdot C_{\text{peak}}}.

MFU was popularized by the PaLM paper (Chowdhery et al. 2022) as a hardware-independent way to compare training efficiency. It counts the FLOPs the model needs, conventionally 6PNtok6PN_{\text{tok}}, not the FLOPs the hardware executes. Its sibling, hardware FLOPs utilization (HFU), also counts extra work such as activation recomputation, so HFU ≥ MFU.

What MFU tells you: a compact summary of how close to peak compute you are. It is useful for comparing systems or configurations, when the FLOP-counting convention and the peak definition are held fixed. What it does not tell you: why. A low MFU can come from bandwidth limits, launch overhead, unfused operations, communication or load imbalance. MFU is a symptom metric, not a diagnosis.

7.2 The worked example

A dense 7B model (P≈7×109P \approx 7 \times 10^9 non-embedding parameters), a global token-batch of 216=65,5362^{16} = 65{,}536, G=8G = 8 H100s at 989 TFLOP/s. Model FLOPs per step ≈ 6⋅7×109⋅65,536≈2.75×10156 \cdot 7 \times 10^9 \cdot 65{,}536 \approx 2.75 \times 10^{15}. If Tstep=0.70T_{\text{step}} = 0.70 s, then MFU ≈ 2.75e15 / (0.70 · 8 · 989e12) ≈ 50% (demo 05 computes 49.7%).

How to read 50%? The numerator is a model-FLOP convention (dense matmuls). Glue, the optimizer, communication and extra HBM traffic are not in it, so even a clean run is below 100%. Fifty percent says you are halfway to that convention’s peak. It does not say whether the missing half is bandwidth, launch overhead or communication. That is what the kernel breakdown is for.

7.3 MFU is not “this kernel hit the roof”

Two utilizations are easy to mix up:

FLOPsop/TopCpeak or bytesop/TopBWHBM⏟kernel utilization: the roofline question for one operatorvsmodel FLOPs/stepTstep G Cpeak⏟MFU: averaged over everything, including idle time\underbrace{\frac{\text{FLOPs}_{\text{op}}/T_{\text{op}}}{C_{\text{peak}}}\ \text{or}\ \frac{\text{bytes}_{\text{op}}/T_{\text{op}}}{BW_{\text{HBM}}}}_{\text{kernel utilization: the roofline question for one operator}}\qquad\text{vs}\qquad \underbrace{\frac{\text{model FLOPs/step}}{T_{\text{step}}\, G\, C_{\text{peak}}}}_{\text{MFU: averaged over everything, including idle time}}

A training GEMM at 93% of CpeakC_{\text{peak}} and an MFU of 50% can both be true. The missing MFU is the other kernels and the gaps, not that GEMM. If the GEMMs did all the model FLOPs at 93% of peak, then MFU ≈ 0.93 × (share of the step spent in GEMMs). An MFU of 50% then means GEMMs fill only ~54% of the step (demo 05 Part A).

The laptop shows the same pattern (demo 04, measured). The training step’s MFU is 48% against the CPU’s measured matmul peak, while the GEMMs, when they run, reach ~83% of that peak. The FlopCounter confirms the model-FLOP numerator (203 GFLOP per step) exactly. Switching to fused SDPA attention takes the step from 140 to 126 ms, a 10% gain at this short context.


8. The three headline bottlenecks, revisited

bottleneckwhat you observetypical lever
MLP/FFN (compute and parameters)high compute and many parameters per token; dense, every token pays for every weightMoE, conditional compute (Lecture 4)
attention / KV cache in decodehigh HBM use and bandwidth during generationGQA/MQA, KV quantization, compressed/latent caches (Lecture 4)
L² attention at long contextcost explodes with contextI/O: FlashAttention (Lecture 7); arithmetic: sparse, selective or hybrid attention (Lecture 4)

Which one is active depends on the width DD, the context length LL and the phase. The core takeaway of the two performance lectures fits in one line: count → predict → measure → change the right thing.


9. Economics of tokens and wall-clock time

9.1 Training: one clock

With the dense heuristic, training on GG GPUs at utilization uu takes

Ttrain≈6 P NtokG u Cpeak,tokens/day≈G⋅goodput⋅u⋅Cpeak⋅86,4006P,T_{\text{train}} \approx \frac{6\,P\,N_{\text{tok}}}{G\, u\, C_{\text{peak}}},\qquad \text{tokens/day} \approx \frac{G \cdot \text{goodput} \cdot u \cdot C_{\text{peak}} \cdot 86{,}400}{6P},

where goodput (Lecture 1 §8) is the fraction of wall-clock time spent training. The three biggest levers are more GPUs (if scaling holds), higher utilization (kernels, bandwidth, communication) and better algorithms (fewer FLOPs per token). On the course’s node, demo 05 Part B computes (40% MFU, 90% goodput):

paramstokens/day20 tokens/param1 T tokens
125 M328 B11 min3.0 days
1 B41 B11.7 h24 days
3 B13.7 B4.4 days73 days
8 B5.1 B31 days195 days

A sanity check against the course’s Llama 3 405B example: 16,384 GPUs × 400 TFLOP/s ÷ (6 × 405 B) ≈ 2.7 M tokens/s, so 15.6 T tokens take about 67 days. This is why course projects pre-train models of a billion parameters or less: the Spring 2026 student blog post describes pre-training base models from scratch in a week on one 8×H100 node.

9.2 Inference: two clocks, two roofs

Generated-token cost is not one number. The slides split it:

  • Time to first token (TTFT, prefill): the prompt is one large-BtokB_{\text{tok}} forward pass. Its MLP and projection GEMMs look like the training GEMM example: high AI, compute-bound possible.
  • Time per output token (TPOT, decode): Btok≈1B_{\text{tok}} \approx 1 per sequence. Weight reads and the KV cache dominate; it is the same linear layer as in prefill, now under the memory roof.

cost per token≈(GPU-seconds per token)×($ per GPU-second).\text{cost per token} \approx (\text{GPU-seconds per token}) \times (\$ \text{ per GPU-second}).

Demo 05 Part C prices both clocks for Llama-3-8B on one H100, with Lecture 2’s roofline model (BF16, fused attention). Times are lower bounds; the GPU-hour price is an assumed $2.50:

clockworkloadtime (≥)MFU (≤)$ per 1M tokens
TTFT512-token prompt8.69 ms90%0.012 (prompt)
TTFT2,048-token prompt35.5 ms91%0.012
TTFT32,768-token prompt834 ms94%0.018
TPOTdecode, batch 1, 4k context4.64 ms0.4%3.23 (output)
TPOTdecode, batch 329.72 ms5.7%0.211
TPOTdecode, batch 104 (the most 4k contexts that fit)21.5 ms8.4%0.144

Even at the largest batch that fits in memory, an output token costs 12× more than a prompt token, because the two clocks run under different roofs. That is why commercial APIs price input and output tokens differently, and why you should never quote one MFU for both phases.

9.3 Batching trades latency for throughput

Batching raises the decode token-batch and the weight reuse; it also makes every user wait longer per token. Demo 05 Part D (Llama-3-8B, 4k context):

batch18326496
TPOT (≥)4.64 ms5.79 ms9.72 ms15.0 ms20.2 ms
total tokens/s (≤)2151,3823,2934,2794,754

Under a TPOT target of 20 ms, the best choice in this sweep is batch 64 (4,279 tokens/s); batch 96 raises throughput further but breaks the target. Prefill wants large token-batches and is happy to be compute-bound. Decode wants as many concurrent sequences as memory and the latency target allow. The two phases want different knobs, which is why modern engines schedule them separately and sometimes run them on different GPUs (Lectures 22–23).


10. How today maps onto Assignment 1 (concepts only)

The slides map the lecture onto Fall 2026’s Assignment 1 explicitly:

assignment piecelecture idea it tests
kernel (a): a vector addgrid, block, mask; AI ≈ 1/12; what fraction of 3.35 TB/s you reach
RMSNorm and cross-entropy kernelsreductions: warps, num_warps, occupancy
SwiGLU and cross-entropy fusiondeleting HBM intermediates; peak memory as evidence
BLOCK / autotuningoccupancy knobs, not accuracy knobs
Part B: MFU and Nsightmeasure → hypothesis → intervention; MFU is a symptom

The division of labour the slides announce applies to these notes too. The lecture explains why the roofs, warps and fusion move the numbers; the how of writing the kernels (the Triton API, the Nsight buttons) belongs to the assignment and office hours. The demos here use a different kernel (axpy) and generic glue chains, and they reproduce no assignment solution.

11. Putting it together

When you see a performance issue, ask in this order:

  1. What is the dominant operator? (attention matmuls? MLP matmuls? norms? KV reads?) Today: measure this with a profiler.
  2. What are its shapes?
  3. Compute FLOPs and bytes.
  4. Compute AI and compare it with AI*.
  5. Form a hypothesis: compute-, bandwidth- or overhead-bound.
  6. Pick the matching lever: fusion, a better kernel, batching, an architecture change. Today: act on it, then re-measure.

Lecture 2 gave you steps 2–4. Today was about measuring step 1 and acting on step 6.


12. Summary

  1. A launch is grid ⊃ block ⊃ warp ⊃ thread. A Triton program_id is a block; the last block needs a mask. A warp’s 32 lanes share one instruction stream, so divergent branches cost both sides.
  2. Occupancy is “are there enough warps to hide HBM latency?” By Little’s law, saturating an H100 needs ~2 MB in flight, which takes many warps, wide loads or several independent loads per thread. Registers, shared memory and block size limit it.
  3. Waves and tiles: small grids (decode) leave SMs idle, partial last waves waste SMs, and padded tiles waste Tensor Cores. All of these miss both roofs.
  4. Overhead is the third regime: every operator has a fixed cost (~0.36 µs per PyTorch op on this CPU; a few µs per eager kernel on a GPU). Fusion, graph capture and batching attack it.
  5. Fusion raises AI by shrinking bytes, not by inventing FLOPs. It is the glue lever, and for cross-entropy at a 128k vocabulary it is also a peak-memory fix (4.2 GB → 65 kB of state).
  6. Measure end-to-end and per kernel. Convert TopT_{\text{op}} to achieved FLOP/s and bytes/s: the same kernel at different shapes sits under different roofs.
  7. If both roofs are missed, the cause is occupancy, launch overhead, stalls or communication, not a slow Tensor Core.
  8. MFU is a symptom computed with a FLOP convention. It is not kernel utilization: a GEMM at 93% and an MFU of 50% coexist.
  9. Training has one clock. Serving has two, TTFT (compute roof) and TPOT (memory roof), with different MFUs and different prices; batching trades latency for throughput.

13. Common pitfalls

  • Optimizing the GEMM first. If the profile shows glue, gaps or communication, a faster GEMM is not on the critical path.
  • Timing asynchronous GPU work without synchronizing. You measure how fast Python enqueues kernels (Lecture 1 §5.4).
  • Treating occupancy as the goal. High-performance GEMMs often run at low occupancy and hide latency with large tiles and independent loads. Occupancy matters when latency is not otherwise hidden.
  • Forgetting the mask on the last block, or testing only power-of-two sizes.
  • Reading MFU as a diagnosis. It tells you how far you are from peak, never why.
  • Comparing MFUs computed with different conventions (6N vs counting attention or recomputation; dense vs sparse peaks).
  • Quoting one MFU for prefill and decode. They differ by two orders of magnitude.
  • Profiling with the profiler’s overhead included. Time steps separately from the profiled run, as demo 04 does.
  • Warm-cache micro-benchmarks (Lecture 2 §9): re-running one kernel on the same small inputs measures the cache, not HBM.

14. Exercises

  1. Grid and mask. A kernel processes N=10,000,000N = 10{,}000{,}000 elements with BLOCK = 1024. How many programs does it launch, and how many lanes of the last one are active?
Answer

⌈10,000,000/1024⌉=9,766\lceil 10{,}000{,}000 / 1024 \rceil = 9{,}766 programs. The first 9,765 cover 9,999,360 elements, so the last program has 640 active lanes and 384 masked ones.

  1. Occupancy. A kernel uses 256 threads per block, 96 registers per thread and 32 KB of shared memory per block. How many warps are resident per H100 SM, and what limits them?
Answer

Registers are allocated per warp in units of 256: ⌈96⋅32/256⌉⋅256=3,072\lceil 96 \cdot 32 / 256 \rceil \cdot 256 = 3{,}072 per warp, so 24,576 per 8-warp block; 65,536/24,576→65{,}536 / 24{,}576 \to 2 blocks. Shared memory would allow 7 blocks, warp slots 8, block slots 32. Registers limit it to 2 blocks = 16 warps = 25% occupancy (kernel_sim.occupancy(256, 96, 32*1024)).

  1. Little’s law. If HBM latency were 1 µs and each thread kept two 8-byte loads in flight, how many warps per SM would an H100 need to stream at 3.35 TB/s?
Answer

Bytes in flight =3.35 TB/s×1 μs=3.35= 3.35\ \text{TB/s} \times 1\ \mu\text{s} = 3.35 MB, i.e. 25.4 KB per SM. One warp keeps 32×8×2=51232 \times 8 \times 2 = 512 bytes in flight, so ~50 warps (78% occupancy). Doubling the latency doubles the requirement, which is why memory-bound kernels are sensitive to occupancy.

  1. Diagnose. A kernel does 2 GFLOP and moves 50 MB on an H100, and takes 1.0 ms. What is happening, and what do you check first?
Answer

AI = 40 FLOPs/byte < 295, so it should be memory-bound, with a floor of 50 MB / 3.35 TB/s ≈ 15 µs. Achieved: 2 TFLOP/s (0.2% of peak) and 50 GB/s (1.5% of bandwidth). Both roofs are far away, so the roofline is not the active limit. Check whether the GPU is busy: the grid size and occupancy (is it a tiny grid?), the number of launches (is this really many small kernels?), dependencies (is it waiting on something?). Only then look inside the kernel.

  1. MFU. Eight H100s train a 1B-parameter model with 524,288 tokens per step in 1.0 s. What is the MFU? If the profiler shows the GEMMs running at 90% of peak, roughly what fraction of the step do they occupy?
Answer

Model FLOPs =6⋅109⋅524,288=3.15×1015= 6 \cdot 10^9 \cdot 524{,}288 = 3.15 \times 10^{15}; MFU =3.15×1015/(1.0⋅8⋅989.4×1012)≈= 3.15 \times 10^{15} / (1.0 \cdot 8 \cdot 989.4 \times 10^{12}) \approx 40%. If GEMMs do the model FLOPs at 90%, they occupy about 0.40/0.90≈0.40/0.90 \approx 44% of the step. The other 56% is where to look.

  1. Fusion in bytes. Residual add + RMSNorm over Btok=16,384B_{\text{tok}} = 16{,}384, D=8192D = 8192 in BF16: how long do the unfused (10 passes) and fused (4 passes) versions take at best on an H100?
Answer

1.34×1081.34 \times 10^8 elements × 2 bytes: 10 passes = 2.68 GB → 0.80 ms; 4 passes = 1.07 GB → 0.32 ms. A 70B model has two norms per layer and 80 layers, so the difference, ~77 ms per forward pass at this token-batch, is not a rounding error.

  1. Two clocks. A user sends a 2,048-token prompt to Llama-3-8B on one H100 serving batch 32 and receives 500 tokens. Using demo 05’s lower bounds, how long does the response take, and which clock dominates?
Answer

TTFT ≥ 35.5 ms; then 500 × TPOT ≥ 500 × 9.72 ms = 4.86 s; total ≥ 4.9 s. Decode dominates by more than 100×. For chat-style workloads, TPOT is the latency that matters, and the KV cache and weight bandwidth are what decide it.

  1. Why fusion fell short. In demo 03, fused SiLU·U gained only 1.13× against a byte-model bound of 1.67×, while streaming at 88 GB/s on a machine with ~230 GB/s of DRAM bandwidth. What does that tell you, and what would you try next?
Answer

The fused kernel is no longer memory-bound: it uses well under half the available bandwidth, so its time is set by something else, most likely the exponential in SiLU on the CPU’s vector units. Fusion succeeded at its job (removing bytes). The next lever is the math: a cheaper SiLU approximation, better vectorization, or a lower-precision data type. Then re-measure. The general rule: after every intervention, re-check which roof (or non-roof limit) binds, because it moves.

15. Research directions

  • Small-batch decode kernels. Decode GEMMs underfill the SMs (§2.7) and waste most of each tile. Split-K, stream-K and GEMV-specialized kernels, and their interaction with batching policies in serving engines, are a live engineering topic and a natural course project.
  • Automatic fusion vs hand-written kernels. Measure how much of the glue time torch.compile and Triton-based fusers recover on real models, and which fusions (online softmax, fused cross-entropy, fused norms with quantization) still need hand-designed kernels.
  • Profiles as data. The course’s assignment wants a hypothesis backed by Nsight evidence. Can the step from a trace to a hypothesis be automated: classifying kernels as compute-, bandwidth- or overhead-bound from their counters and flagging the largest gap?
  • Beyond MFU. MFU depends on a FLOP convention. Propose and validate efficiency metrics for MoE, long-context and decode workloads, where 6N is a poor model of the work.

16. Further reading

  • H. He, Making Deep Learning Go Brrrr From First Principles (horace.io/brrr_intro.html): the three regimes (compute, bandwidth, overhead), fusion, and how to tell which you are in.
  • The Triton tutorials (triton-lang.org): vector add, fused softmax and matrix multiplication, the canonical examples of programs, masks and tiling.
  • NVIDIA, CUDA C++ Best Practices Guide (occupancy, memory coalescing, latency hiding) and the CUDA occupancy calculator in Nsight Compute.
  • NVIDIA technical blogs: Profiling LLM Training Workflows on NVIDIA Grace Hopper (2025) and Accelerating HPC Applications with NVIDIA Nsight Compute Roofline Analysis (2020), the sources of the slides’ screenshots.
  • A. Chowdhery et al., PaLM: Scaling Language Modeling with Pathways, 2022 (arXiv:2204.02311), Appendix B: the definition of MFU and HFU.
  • J. Austin et al., How to Scale Your Model, ch. 7 (inference: prefill vs generation, batching and latency).
  • R. Pope et al., Efficiently Scaling Transformer Inference, MLSys 2023: latency/throughput frontiers of prefill and decode.

17. Next lecture

Lecture 4 · Architectures to Break Bottlenecks. Today’s three headline bottlenecks get architectural answers. Mixture of experts breaks the MLP’s coupling of capacity and compute, at the price of routing, load balancing and all-to-all communication. Multi-head latent attention caches a compressed latent instead of keys and values, trading reconstruction compute for KV bandwidth. Sparse attention (DeepSeek’s DSA, NSA) and hybrid Mamba–attention stacks escape the L² wall at long context. We count what each one changes, FLOPs or bytes, and the systems tax each one charges.


术语表 (Glossary, English → 中文)

English中文
kernel / launch内核 / 启动
grid / block (thread block) / program (Triton)网格 / 线程块 / 程序实例
warp / lane / thread线程束 / 通道 / 线程
SIMT (single instruction, multiple threads)单指令多线程
branch divergence分支发散
mask / out-of-bounds access掩码 / 越界访问
warp scheduling / eligible warp线程束调度 / 可发射线程束
latency hiding / memory latency延迟隐藏 / 访存延迟
Little’s law / bytes in flight利特尔定律 / 在途字节数
vectorized (wide) load / instruction-level parallelism向量化(宽)加载 / 指令级并行
occupancy / resident warps / limiter占用率 / 常驻线程束 / 限制因素
register / shared memory / register spilling寄存器 / 共享内存 / 寄存器溢出
wave / wave quantization波次 / 波次量化
tile / tiled GEMM / padding分块 / 分块矩阵乘 / 填充
split-K / GEMVK 维切分 / 矩阵向量乘
autotuning / BLOCK / num_warps自动调优 / 块大小 / 线程束数
overhead / dispatch / kernel launch overhead开销 / 分派 / 内核启动开销
CUDA graph / graph captureCUDA 图 / 图捕获
eager mode / torch.compile即时执行模式 / 编译模式
operator fusion / intermediate tensor / pass算子融合 / 中间张量 / 遍
online softmax / two-pass algorithm在线 softmax / 两遍算法
cross-entropy / logits / vocabulary交叉熵 / 未归一化对数概率 / 词表
peak memory峰值内存
profiling / profiler / trace / timeline性能剖析 / 剖析器 / 跟踪 / 时间线
Nsight Systems / Nsight Compute(NVIDIA 的系统级 / 内核级剖析工具)
Speed of Light (SOL)理论极限(光速)指标
self time / inclusive time自身耗时 / 包含子调用的耗时
achieved FLOP/s / achieved bandwidth实际达到的算力 / 实际达到的带宽
hypothesis / intervention假设 / 干预
model FLOPs utilization (MFU) / hardware FLOPs utilization (HFU)模型算力利用率 / 硬件算力利用率
kernel utilization内核利用率
goodput有效吞吐
time to first token (TTFT) / time per output token (TPOT)首 token 延迟 / 每输出 token 时间
prompt (input) tokens / output tokens输入 token / 输出 token
service-level objective (SLO)服务等级目标
latency–throughput trade-off延迟与吞吐的权衡
← 返回课程目录