Maps to: Stanford CS 217 Hardware Accelerators for Machine Learning (Winter 2026), Lecture 10 · Thu 02/05/2026 · Compilers and Software Stack (Part 2). Project proposals are due today. HW3 (kernel fusion) goes out on 02/12. Reading (from the schedule):
- T. Dao, D. Y. Fu, S. Ermon, A. Rudra, C. Ré, FlashAttention: fast and memory-efficient exact attention with IO-awareness, NeurIPS 2022.
- W. Kwon et al., Efficient memory management for large language model serving with PagedAttention, SOSP 2023.
- J. Ansel et al., PyTorch 2: faster machine learning through dynamic Python bytecode transformation and graph compilation, ASPLOS 2024.
Basis: The slides are not public. This lecture follows the session title, the three papers, and related public work: FlashAttention-2, Flash-Decoding, Orca’s iteration-level batching, and the online-softmax paper of Milakov and Gimelshein.
The experiments use models written for these notes:
- a tensor-graph IR with a fusion pass and a roofline cost model (
graph.py);- an exact numpy FlashAttention, forward and backward, with DRAM counters checked against closed-form formulas (
flash.py);- a continuous-batching serving simulator (
paged.py).Times are roofline estimates on H100 datasheet numbers, not measurements of real kernels, of PyTorch or of vLLM. The request traces are synthetic. Numbers quoted from the papers are labelled as such. The experiments do not reflect what was said in class.
This lecture also holds the project guide (§7), in place of the two proposal-review sessions (02/10, 02/12). Code:
code/lecture10/(4 scripts + 3 modules; under 3 s each) Reading time: 3–4 hours including running the code
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
-
Explain why every unfused element-wise operator is a DRAM round trip, and price it with the roofline and a launch overhead.
-
State the legality rules of fusion (execution order, iteration spaces, reductions, several consumers) and its kinds (element-wise chains, epilogues and prologues, horizontal). Estimate a fusion’s profitability.
-
Describe PyTorch 2’s pipeline (TorchDynamo → FX graph → AOTAutograd → TorchInductor → Triton) and say where fusion happens in it.
-
Derive the online softmax, prove that FlashAttention is exact, and compute its DRAM traffic as a function of on-chip memory. Say where that analysis stops applying.
-
Explain why FlashAttention’s backward pass recomputes the attention matrix, and what that costs.
-
Explain PagedAttention:
- the three kinds of KV-cache waste;
- block tables and block size;
- preemption and admission control;
- sharing.
Connect memory waste to batch size, throughput and latency.
-
Show that decode attention is memory-bound at any batch size, compute its intensity under grouped-query attention, and explain why decode kernels split the KV sequence.
-
Plan a course project: a question, a strong baseline, a validated model, honest metrics, a poster.
0.2 Prerequisites and scope
| Assumed | Introduced here | Developed later |
|---|---|---|
| Lecture 1: roofline, attention, KV cache, prefill vs decode | eager execution vs fused kernels; legality and profitability | GPU SMs, shared memory, tensor cores, kernel launch (L11, L17) |
| Lecture 4: quantizing the KV cache | graph capture and compilation (PyTorch 2) | dataflow machines that fuse whole graphs in space (L12–13) |
| Lecture 6: special-function units, matmul epilogues | online softmax; FlashAttention’s I/O complexity; recomputation | memory-centric hardware for decode (L14–15) |
| Lecture 7: tiling, the √S law, attention’s score traffic | PagedAttention, continuous batching, preemption, sharing | compilers for Trainium and Inferentia (L16) |
| Lecture 9: mappings and analytical cost models | split-KV decoding; the project guide |
0.3 Map
§1 eager execution, fusion, legality, profitability ← code 01 (Part 1)
§2 fusing a Llama-sized block; launch overhead; PyTorch 2 ← code 01 (Parts 2-4)
§3 FlashAttention: online softmax, exactness, I/O, backward ← code 02
§4 PagedAttention: the KV cache as virtual memory ← code 03
§5 decode vs prefill kernels: intensity, split-KV, the decode step ← code 04
§6 what these kernels ask of an accelerator
§7 the project guide
§8 summary §9 pitfalls §10 exercises §11 further reading §12 next lecture
0.4 Notation
| Symbol | Meaning |
|---|---|
| T | tokens processed by a block (prefill of one sequence) |
| N, d | sequence length and head dimension in attention (§3, §5) |
| H, H_kv, G | query heads, key/value heads, group size G = H / H_kv |
| S, P, O | scores (scaled, masked), probabilities softmax(S), output PV |
| m, ℓ, acc | running row maximum, running sum of exponentials, unnormalized output |
| L | row log-sum-exp: m + log ℓ |
| M | on-chip memory available to one attention kernel, in elements |
| B_r, B_c | query-block and key-block sizes |
| B | KV-cache block size in tokens (§4) |
| ridge | 295 FLOP/byte: H100 SXM, 989 TFLOPS dense bf16 ÷ 3.35 TB/s |
1. Why fusion: the round trip
1.1 Eager execution
A framework runs a model as a graph of operators. In eager mode each operator is one kernel. The kernel reads its inputs from DRAM, computes, and writes its output back to DRAM, even if the very next kernel reads that output again.
For a matrix multiplication that costs little: Lecture 1 showed it does hundreds of FLOPs per byte. The operators between the matmuls are another story: RMSNorm, rotary embeddings, scaling, masking, softmax, SiLU, the gating product, the residual adds. They do about one FLOP per byte. SiLU on bf16 reads 2 bytes, does ~4 FLOPs and writes 2 bytes. On an H100 the ridge is at 295 FLOP/byte, so these kernels run at well under 1% of peak compute. They are pure memory traffic.
On top of the traffic, each kernel pays a launch overhead: the CPU-side dispatch, the launch itself, and the ramp-up and drain of the GPU. Our model charges 4 µs per kernel. That is an assumed round number in the range usually quoted for a few microseconds, not a measurement.
Fusion merges a group of operators into one kernel. The intermediate tensors then live in registers or on-chip memory and never reach DRAM. The arithmetic is the same; only the data movement and the launches disappear.
1.2 A decoder block as a graph
graph.decoder_block builds one pre-norm Llama-style block with 20 compute nodes:
x ─ h1 = RMSNorm(x)
q, k, v = h1·Wq, h1·Wk, h1·Wv (3 matmuls)
q_r, k_r = RoPE(q), RoPE(k)
s = q_r·k_rᵀ (per head, H × T × T) s_scaled = s/√d s_masked = causal(s_scaled)
p = softmax(s_masked) attn = p·v
o = attn·Wo x1 = x + o (residual)
h2 = RMSNorm(x1)
gate, up = h2·Wg, h2·Wu act = SiLU(gate) prod = act ⊙ up
down = prod·Wd y = x1 + down (residual)
graph.run interprets it in numpy. It can also substitute a tiled FlashAttention kernel (§3) for the five-node attention chain. Script 01, Part 1 checks that both executions agree: max |difference| = 1.1e-15. Fusion changes the order of the work, never its result. (In float64, the rounding differences are at the last bit.)
1.3 Kinds of fusion
| Kind | What merges | Example in the block | What it saves |
|---|---|---|---|
| vertical element-wise | a chain of element-wise ops (and row reductions) | scale → mask → softmax; SiLU → ⊙ | every intermediate’s write + read |
| epilogue | element-wise consumers of a matmul, applied to the output tile before it is stored | RoPE after the Q projection; the residual add after Wo | the matmul output’s write + read |
| prologue | element-wise producers of a matmul’s activation operand, applied as tiles are loaded | (an activation feeding the next matmul) | the activation’s write + read |
| horizontal | sibling matmuls that read the same input, concatenated into one wider matmul | Q, K, V from h1; gate and up from h2 | re-reading the shared input; it also lets SiLU(gate)·up combine in one epilogue |
| pattern | a known multi-matmul subgraph replaced by a hand-designed kernel | QKᵀ → scale → mask → softmax → PV = FlashAttention | the T × T score and probability matrices (§3) |
1.4 Legality: what may be fused
graph.fuse walks the graph in topological order. Each node joins a producer’s group if the strategy allows that pair of operator kinds; otherwise it starts a new kernel. The rules are a coarse version of what TorchInductor checks.
-
Execution order. Kernels run one after another, and each runs as a unit. A node may join a kernel only if every other input is produced by an earlier kernel.
The first version of the pass lacked this rule. It placed the residual add
y = x1 + downinto the kernel that computesx1. That kernel runs beforedownexists, so the fused kernel was impossible. With the rule,ybecomes the epilogue of the down projection, which is what real compilers do. -
Compatible iteration spaces. Element-wise ops over the same shape fuse trivially: each thread computes the whole chain for its elements.
A row reduction (RMSNorm, softmax over the last axis) can join only if one kernel instance can hold a whole row. We use a
row_limitof 16,384 elements. A row of 2,048 attention scores fits. -
No reduction in a matmul prologue. RMSNorm needs the entire row before it can scale any element of it. A matmul tile streams its activation operand in chunks along K, so in our rule set RMSNorm stays a separate kernel.
This rule is conservative. Exercise 3 shows an algebraic rewrite that moves RMSNorm’s scaling into the matmul epilogue.
-
Two matmuls do not fuse. The second matmul needs complete rows of the first one’s output, and in general those do not fit on chip. Attention is the exception, because softmax can be computed online (§3). That needs a new algorithm, not just a fusion rule.
-
Several consumers.
x1feeds bothh2(through RMSNorm) and the final residual add. Fusing it into the Wo epilogue saves one round trip, but it must still be written once for its other consumer. The cost model (kernel_costs) charges every tensor that leaves a kernel.
1.5 Profitability
A legal fusion is not automatically a good one. In our model, eliminating a kernel boundary saves:
- the intermediate’s write and read: 2 × its bytes;
- one launch.
Real compilers weigh further costs:
- recomputation: a prologue is re-executed for every output tile that loads the same input;
- register and shared-memory pressure: a long fused chain can lower occupancy or force smaller matmul tiles;
- lost parallelism: a fused reduction may need one block per row;
- compile time and code size.
TorchInductor scores candidate fusions by the memory traffic they save and fuses greedily by score. That is a profitability heuristic of the same kind as our model.
2. Fusing a Llama-sized block
2.1 Traffic and time per strategy
Script 01, Part 2 prices one block with Llama 3 8B’s sizes: d_model 4,096, 32 heads of 128, MLP 14,336. It uses multi-head attention (no KV sharing) for one sequence on the H100 roofline, plus 4 µs per kernel:
| 2,048 tokens | kernels | DRAM traffic | time | speedup |
|---|---|---|---|---|
| none (eager) | 20 | 3.59 GB | 1.91 ms | 1.00× |
| element-wise chains | 16 | 2.38 GB | 1.53 ms | 1.25× |
| + epilogues/prologues | 12 | 2.15 GB | 1.42 ms | 1.35× |
| + horizontal matmuls | 9 | 1.98 GB | 1.40 ms | 1.36× |
| + FlashAttention | 7 | 906 MB | 1.13 ms | 1.69× |
Every row does the same 1,066 GFLOP. As a check: 2 FLOPs × 243 M weights × 2,048 tokens ≈ 997 GFLOP for the matmuls, plus 69 GFLOP of attention. The fused groups are the ones Part 1 prints for a small block:
flash: [q,k,v,q_r,k_r] [s,s_scaled,s_masked,p,attn] [o,x1] [gate,up,act,prod] [down,y] + h1, h2
Where the bytes go (Part 3). Unfused, the five attention kernels move 2.21 GB, 62% of the block. The 32 × 2,048 × 2,048 bf16 score matrix is 268 MB. It is written by QKᵀ, then read and written again by scale, mask and softmax (537 MB each), and read again by PV. Element-wise kernels sit at ~0–1 FLOP/byte and are memory-bound. QKᵀ and PV are memory-bound too (114 FLOP/byte), because they write or read the scores. The projections are compute-bound (1,024–1,247 FLOP/byte).
After fusion:
- the attention kernel moves 67 MB at 1,038 FLOP/byte;
- only the two RMSNorms remain memory-bound (34 MB each);
- every other kernel is compute-bound.
2.2 Short sequences: weights and launches
| 2,048 tokens | 512 tokens | 128 tokens | |
|---|---|---|---|
| traffic, none → flash | 3.59 GB → 906 MB | 860 → 591 MB | 555 → 513 MB |
| speedup | 1.69× | 1.44× | 1.36× |
At 128 tokens fusion barely reduces the traffic: 487 MB of the 513 MB are the block’s weights (243 M parameters × 2 bytes), which every strategy must read once. What fusion still removes there is launches. Script 01, Part 4:
| 128 tokens | no launch cost | 4 µs / kernel | 10 µs / kernel |
|---|---|---|---|
| unfused (20 kernels) | 166 µs | 246 µs | 366 µs |
| fused (7 kernels) | 153 µs | 181 µs | 223 µs |
At 4 µs per kernel, a third of the unfused block is overhead. Multiplied by 32 blocks, that is about 2.5 ms per forward pass. Decode, with one new token per sequence, is the extreme case. Two remedies work together: fewer kernels (fusion) and cheaper launches. CUDA graphs record a whole sequence of launches once and replay it with one CPU call.
2.3 How PyTorch 2 does it
The PyTorch 2 paper (Ansel et al., ASPLOS 2024) describes how torch.compile turns an eager Python program into fused kernels without asking the user to write a graph:
Python function
└─ TorchDynamo hooks CPython's frame evaluation (PEP 523), reads the bytecode, and extracts
straight-line regions of tensor operations into FX graphs. Guards record the
assumptions (shapes, dtypes, Python values); unsupported code causes a "graph
break" and runs in Python.
└─ AOTAutograd traces the backward pass ahead of time into a joint forward+backward graph and
partitions it. A min-cut decides which activations to SAVE and which to RECOMPUTE
in the backward pass (the same trade as FlashAttention's backward, §3.5).
└─ decompositions lower the operator set to a much smaller set of primitive operators
(PrimTorch / core ATen), so a backend handles a closed set of ops.
└─ TorchInductor lowers to a loop-level IR, decides fusion (pointwise + reduction groups,
scored by memory traffic saved), and generates code: Triton kernels on GPUs,
C++/OpenMP on CPUs. Matmuls call vendor libraries or Triton templates with
fused epilogues; the attention pattern maps to fused attention kernels.
CUDA graphs ("reduce-overhead" mode) remove launch costs.
The paper reports a geometric-mean speedup of 2.27× for inference and 1.41× for training with TorchInductor, over 180+ real models on an NVIDIA A100. That is the paper’s number, not one reproduced here. Our block shows where such numbers come from: memory-bound glue operators, attention, and launches.
Hardware link. A compiler for a custom accelerator faces the same choices with different costs. The equivalent of a launch may be a DMA descriptor set-up or a synchronization. The epilogue runs on a vector unit next to the array (Lecture 6), and that unit must keep up with the array’s output rate. Dataflow machines (Lectures 12–13) push fusion to its limit: a whole subgraph is laid out in space, and intermediates flow between units without ever touching DRAM.
HW3 (kernel fusion) is the homework of this unit. Exercises 1–3 and 12 extend graph.py in that spirit.
3. FlashAttention
3.1 The problem: the N × N matrices
For one head, attention computes (N × N), and . Written as three kernels, it moves:
- kernel 1: read Q, K (2Nd), write S (N²);
- kernel 2: read S, write P (2N²);
- kernel 3: read P, V, write O (N² + 2Nd).
The total is 4N² + 4Nd elements, versus 4Nd compulsory (Q, K, V and O once each). Script 02, Part 2 counts, for N = 4,096 and d = 128:
- 69.2 M elements for three kernels;
- 136.3 M with separate scale and mask kernels;
- 2.10 M compulsory.
The N² terms are 97% of the three-kernel traffic.
Why not simply tile attention like a GEMM (Lecture 7)?
- The softmax needs the whole row: its maximum (for numerical safety, Lecture 1) and its sum. Both must be known before any element of P is final.
- The second matmul needs P.
By the rules of §1.4 this is “two matmuls with a row reduction in between”: not fusible. FlashAttention changes the algorithm so that it becomes fusible.
3.2 The online softmax
Consider one query row. Its scores arrive in blocks. Keep three running quantities:
When a new block with scores and values arrives:
At the end, , and the row’s log-sum-exp is .
Why it is exact. By induction, after every block the three quantities equal their definitions over the keys seen so far. Multiplying by α only re-expresses the old terms relative to the new maximum: . Nothing is approximated or dropped. The final is . Only the order of the additions differs from the standard algorithm, so the results differ only by floating-point rounding.
A worked example (Exercise 4 repeats it): scores (2, 0, 4, 1), values (1, 2, 3, 4), blocks of two.
| m | ℓ | acc | |
|---|---|---|---|
| after block 1 | 2 | 1 + e⁻² = 1.1353 | 1 + 2e⁻² = 1.2707 |
| after block 2 (α = e⁻²) | 4 | 0.1537 + 1 + e⁻³ = 1.2034 | 0.1720 + 3 + 4e⁻³ = 3.3711 |
So o = 3.3711 / 1.2034 = 2.8012, which is exactly softmax(2, 0, 4, 1) · (1, 2, 3, 4).
Script 02, Part 1 runs flash.flash_forward for three problem shapes, causal and not, with three block shapes. The largest difference from the reference is 2e-14 in float64 and ~1e-5 in float32. The float32 error is ordinary float32 rounding and does not depend on the blocks. The “rescales per row” column (1.1–3.9) counts how often a row’s running maximum grew. Each growth costs one rescale of ℓ and acc, which is cheap vector work.
3.3 The algorithm and its I/O complexity
flash_forward uses the FlashAttention-2 loop order:
for each query block Qi (Br rows): ← parallel across thread blocks / heads
load Qi once; m = -inf, l = 0, acc = 0
for each key block (Kj, Vj) (Bc rows): ← skip blocks entirely above the causal diagonal
S = Qi Kjᵀ · scale (Br × Bc, on chip)
online-softmax update of m, l, acc with S and Vj
write Oi = acc / l and Li = m + log l
Only Q, K, V, O and the N-vector L touch DRAM. S and P exist one tile at a time, on chip. The price is that K and V are re-read once per query block:
The tiles must fit in M elements of on-chip memory: . The paper chooses and . That makes the re-read term , against for standard attention. The paper also proves that no exact attention algorithm can do asymptotically better over a range of M.
Dividing the two gives a rule of thumb, which the script confirms. Ignoring causal skipping, three-kernel attention moves and FlashAttention . FlashAttention moves less only when M > 2d²: 64 KiB of bf16 for d = 128. Causal skipping halves the tiles and halves that threshold. Script 02, Part 2 (causal, N = 4,096, d = 128):
| on-chip memory | blocks | flash traffic | standard (3 kernels) / flash | flash / compulsory |
|---|---|---|---|---|
| 8 KiB | 8 × 8 | 270.0 M | 0.3× (flash is worse) | 129× |
| 32 KiB | 32 × 32 | 68.7 M | 1.0× | 33× |
| 96 KiB | 96 × 96 | 24.3 M | 2.8× | 12× |
| 256 KiB | 128 × 256 | 18.9 M | 3.7× | 9.0× |
| 1 MiB | 128 × 1,024 | 22.0 M | 3.1× | 10.5× |
Two caveats come out of this table. Both were found while writing the code; see the code README’s “Plan vs reality”.
-
The gain stops at M = 4d². At that point B_r reaches its cap of d = 128 rows, so the number of K/V passes stops falling. Larger key blocks only make causal tile skipping coarser, and the traffic goes up again at 1 MiB.
-
On a GPU, the re-reads mostly hit L2. One head’s K and V take 2.1 MB here, and an H100’s L2 cache holds 50 MB. The query blocks of a head run at about the same time, so the re-reads come from L2 and DRAM sees roughly the compulsory 2.1 M elements.
The paper’s analysis is really about shared memory ↔ HBM. In practice FlashAttention’s speedup comes mostly from never writing S and P. K/V reuse across query blocks is secondary.
The counters are validated: for N = 1,024, d = 64 and 64 × 128 blocks, the kernel counted 1,311,744 elements, exactly the formula.
3.4 Time and memory on an H100
Script 02, Part 3 prices one layer (32 heads of 128, causal). Standard attention uses five kernels at full N × N FLOPs. FlashAttention skips the masked tiles and, with the L2 effect, moves only compulsory traffic. Its time is FLOPs at peak, an optimistic bound: the FlashAttention-2 paper reports 50–73% of the A100’s peak.
| N | standard | FlashAttention | speedup | S or P per layer (bf16) |
|---|---|---|---|---|
| 512 | 45.1 µs | 5.01 µs | 9.0× | 16.8 MB |
| 2,048 | 661 µs | 34.7 µs | 19.0× | 268 MB |
| 8,192 | 10.3 ms | 556 µs | 18.6× | 4.29 GB |
| 32,768 | 164 ms | 8.89 ms | 18.5× | 68.7 GB |
At 32 k tokens the standard version needs 69 GB for each of S and P, in a single layer. That is more than most GPUs hold. FlashAttention’s memory is O(N) per head. It turns attention from memory-bound into compute-bound, and long contexts from impossible into routine.
The ratio settles near 19× because both sides grow as N²: standard attention’s N² traffic against FlashAttention’s N² FLOPs. The paper’s end-to-end training speedups are smaller, since attention is only part of a model: 15% on BERT-large (N = 512), 3× on GPT-2 (N = 1 k), 2.4× on the long-range arena benchmarks (paper numbers).
3.5 The backward pass: recompute, don’t store
The softmax gradient needs P:
Storing P costs N² per head per layer. FlashAttention instead recomputes each tile of P from Q, K and the saved log-sum-exp: . No running maximum is needed, because L is final. flash_backward loops over key blocks on the outside, accumulates dK and dV on chip, and read-modify-writes dQ.
Script 02, Part 4. The gradients agree with the reference to 4.9e-15. The extra work is one tile matmul, , on top of the backward pass’s four. That is +25% backward FLOPs and +17% overall: forward 2 matmuls, backward 5 instead of 4, so 7/6. In exchange, the memory kept for the backward pass shrinks from 8.39 MB to 8.19 kB per head at N = 2,048 (P in bf16 vs L in float32), and from 2.15 GB to 131 kB at N = 32,768.
The trade is cheap arithmetic for expensive data movement. AOTAutograd’s min-cut partitioner (§2.3) makes the same decision automatically for ordinary operators.
3.6 Why it works, structurally
The pair (m, ℓ) combines associatively:
and acc combines the same way. An associative combine means the softmax reduction can be split, reordered and run in parallel like any sum. That is exactly what Lecture 9’s mappings needed: FlashAttention is a mapping of a two-matmul loop nest that became legal once the reduction in between was made associative. The same property allows split-KV decoding (§5.2) and reduction trees across devices (Lecture 8).
4. PagedAttention: the KV cache as virtual memory
4.1 The serving loop
An LLM server runs continuous batching, also called iteration-level scheduling (Orca, OSDI 2022). Every step:
- it admits waiting requests if memory allows (and runs their prefill);
- it runs one decode step for every running request;
- it retires finished requests.
Decode is memory-bound: the weights are read once per step and shared by the whole batch. So throughput grows with batch size, and the batch is limited by the KV cache.
For Llama 3 8B in bf16 the cache needs 2 (K and V) × 32 layers × 8 KV heads × 128 × 2 bytes = 128 KiB per token. Our simulated server has a cache of 183,000 tokens, which is 24 GB: what a 40 GB GPU keeps after 16 GB of weights.
The difficulty is that a request’s final length is unknown when it arrives, because generation stops at an end-of-sequence token.
4.2 Three kinds of waste
Early servers reserved a contiguous region per request, sized for the maximum length (prompt + 2,048 new tokens here). That wastes memory in three ways:
| Waste | Cause |
|---|---|
| reservation | slots reserved for tokens not generated yet |
| internal fragmentation | slots reserved for tokens that will never be generated (the request ends early) |
| external fragmentation | free memory split into holes too small for the next request |
The PagedAttention paper measured that existing systems used only 20.4–38.2% of their KV-cache memory for actual token states (paper’s number).
Script 03, Part 1 runs 1,000 requests, all queued at once. Prompt lengths are lognormal with mean 400; outputs have mean 250, up to 2,048. Fractions are averages over the whole run, including the final drain:
| policy | mean batch | peak batch | KV slots in use | reserved, unused | tokens/s |
|---|---|---|---|---|---|
| contiguous, reserve max length | 46 | 75 | 16% | 45% | 6,431 |
| contiguous, reserve exact length (oracle) | 83 | 282 | 29% | 11% | 9,178 |
| paged, 16-token blocks | 98 | 422 | 34% | 0.4% | 9,948 |
Figure 03_paged.png plots the batch over time. Read off the figure: while the queue is full, paging runs ~320 requests, the oracle ~200 and max-reservation ~65. The averages in the table are lower because every run ends with a long drain.
Paging runs 2.1× the mean batch and 1.55× the tokens per second of max-reservation. Throughput grows less than the batch because each step must also read the larger batch’s KV caches.
Even an oracle that knew every output length loses to paging. It still reserves each request’s future tokens from the start, and its variable-size holes fragment. The paper reports 2–4× the throughput of FasterTransformer and Orca at the same latency, on real traces and real kernels (paper’s numbers). Our smaller gain comes from a synthetic trace and a simple time model.
4.3 The mechanism
PagedAttention borrows paging from operating systems:
- The KV cache of a sequence is a list of fixed-size blocks (16 tokens in vLLM). The blocks can sit anywhere in GPU memory.
- A per-sequence block table maps logical block i to a physical block, like a page table.
- Blocks come from a free list. A new block is allocated when a sequence crosses a block boundary, and all of a sequence’s blocks are freed when it finishes.
- The attention kernel reads K and V through the block table, one block at a time. The kernel had to be rewritten for this indirection. The paper reports its attention kernel at 20–26% higher latency than a contiguous kernel. It accepts that overhead because the larger batch more than pays for it.
The only waste left is the unfilled part of each sequence’s last block: on average half a block. Script 03, Part 3:
| block (tokens) | 1 | 4 | 16 | 64 | 256 |
|---|---|---|---|---|---|
| last-block slack (of the cache) | 0.00% | 0.08% | 0.40% | 1.67% | 6.35% |
| tokens/s | 9,950 | 9,954 | 9,948 | 9,888 | 9,666 |
| blocks to manage | 183,000 | 45,750 | 11,437 | 2,859 | 714 |
The waste follows the half-block rule, (B − 1)/2 unused slots per sequence on average: 98.5 sequences × 7.5 tokens = 739 tokens = 0.40% at B = 16. Tiny blocks waste nothing, but they make block tables long and the kernel’s memory accesses small and scattered. A 16-token block of one KV head is 16 × 128 × 2 bytes = 4 KiB, comfortably larger than a DRAM burst or row (Lecture 7). Our model charges nothing for small blocks, so it cannot show their kernel cost. That cost is why vLLM settled on 16.
4.4 Preemption and admission control
Admitting a request only needs blocks for its prompt, but every running request keeps growing. A greedy server therefore over-commits. When a running sequence needs a block and none is free, a sequence must be preempted. vLLM evicts all of a sequence’s blocks and either recomputes them later (prefill again) or swaps them to CPU memory. Our simulator recomputes, evicting the newest request first.
Script 03, Part 4 keeps a fraction of the blocks free at admission (a watermark):
| free blocks kept at admission | preemptions | KV tokens recomputed | mean batch | tokens/s |
|---|---|---|---|---|
| 0% | 405 | 156,113 | 98.8 | 9,042 |
| 1% | 15 | 6,655 | 98.5 | 9,948 |
| 5% | 0 | 0 | 97.3 | 9,933 |
| 10% | 0 | 0 | 95.5 | 9,846 |
With no headroom the server thrashes: it recomputes 156,113 KV entries, 85% of the whole cache, and loses 9% of its throughput. A few percent of headroom removes almost all preemptions, at the cost of a slightly smaller batch. This is the classic virtual-memory trade between admission control and thrashing.
4.5 Sharing: copy-on-write
Blocks make sharing natural:
- parallel samples of one prompt (best-of-n), beam search, a common system prompt;
- these can point their block tables at the same physical blocks, with reference counts;
- the partly filled last prompt block is copied on write when the sequences diverge.
Script 03, Part 5 (outputs of 200 tokens each):
| prompt | samples | contiguous copies | paged, shared prompt | saved |
|---|---|---|---|---|
| 1,000 | 4 | 4,800 tokens | 1,824 | 62% |
| 4,000 | 8 | 33,600 | 5,664 | 83% |
| 4,000 | 1 | 4,200 | 4,208 | −0.2% (block rounding) |
Saved memory becomes batch size. Prefix caching across requests extends the same idea: for example SGLang’s RadixAttention keeps a radix tree of cached prefixes.
4.6 Online serving: waste becomes latency
Script 03, Part 2 lets requests arrive at a fixed rate per decode step:
| arrivals / step | max-reservation latency (steps) | tokens/s | paged latency (steps) | tokens/s |
|---|---|---|---|---|
| 0.5 | 866 | 6,354 | 236 | 7,727 |
| 1 | 1,352 | 6,398 | 236 | 9,055 |
| 2 | 1,607 | 6,384 | 261 | 9,699 |
| 4 | 1,742 | 6,383 | 317 | 9,865 |
The max-reservation server is saturated at every rate tested. Its memory-limited batch caps it near 6,400 tokens/s, so its queue grows and its latency climbs. The paged server keeps up.
By Little’s law (Lecture 7), concurrency = throughput × latency. A server that cannot hold enough concurrent requests in memory can only lose on throughput, on latency, or on both.
Hardware link. PagedAttention is virtual memory implemented in software. The address translation is a block-table lookup inside the kernel, not a hardware TLB. An accelerator that serves LLMs needs:
- DMA engines that follow gather lists of block addresses (Lecture 7);
- memory managed at block granularity;
- enough capacity to make the batch large.
One alternative keeps the KV cache virtually contiguous with the GPU’s own virtual-memory hardware: vAttention (Prabhu et al., ASPLOS 2025).
5. Decode vs prefill kernels
5.1 Intensity: why batching does not help decode attention
Prefill processes many query tokens against the same keys. FlashAttention moves Q, K, V and O once, and the FLOPs grow with (query tokens × keys). Decode processes one new query token per sequence against that sequence’s entire KV cache. With grouped-query attention, G = H / H_kv query heads share each KV head:
Script 04, Part 1 (Llama 3 8B: 32 query heads, 8 KV heads, so G = 4):
| workload | MHA (G = 1) | GQA (G = 4) | bound |
|---|---|---|---|
| prefill, 1 × 4,096 tokens | 2,048 FLOP/byte | 3,277 | compute |
| prefill, 8 × 1,024 tokens | 512 | 819 | compute |
| decode, batch 1, context 4,096 | 1.0 | 4.0 | memory |
| decode, batch 64, context 32,768 | 1.0 | 4.0 | memory |
Batching does not raise the intensity, because each sequence reads its own KV cache. Weight reads, by contrast, are shared by the whole batch (Lecture 1). Decode attention sits 74–295× below the ridge. Several fixes attack the bytes:
- GQA/MQA (model architecture);
- KV-cache quantization (numerics, Lecture 4);
- latent-compressed caches;
- sparse or sliding-window attention.
5.2 Split-KV decoding (Flash-Decoding)
At batch 1, one layer’s decode attention has only 8 independent work items, one per KV head. An H100 has 132 SMs. Prefill parallelizes over query blocks; decode has a single query, so it must parallelize over keys:
- split each head’s KV sequence into chunks;
- give each chunk to an SM, which computes its partial (m, ℓ, acc);
- combine the partials with the associative ⊕ of §3.6.
flash.split_kv_decode does this and matches standard attention to 2e-16 for 1–64 splits.
Script 04, Part 2 needs a time model, because the point is to use more of the memory system. The model assumes that one SM can pull at most twice its fair share of DRAM bandwidth (2 × 3.35 TB/s ÷ 132 = 51 GB/s). That stands in for the measured per-SM limit, which is not public. The results scale with this assumption (Exercise 11):
| context | no split (8 items) | 4 splits (32) | 16 splits (128) | 64 splits (512) |
|---|---|---|---|---|
| 4,096 | 41.3 µs | 12.4 µs | 7.16 µs (5.8×) | 7.63 µs |
| 131,072 | 1.32 ms | 333 µs | 162 µs (8.1×) | 163 µs |
Without splitting, 8 SMs pull 406 GB/s, 12% of the bandwidth. With 16 splits the kernel streams the 537 MB layer cache at the full 3.35 TB/s (160 µs) plus a small combine. Beyond that, more splits only add combine work and scheduling waves. The Flash-Decoding authors report up to 8× faster generation for very long sequences (their number).
5.3 What a decode step spends its time on
Script 04, Part 3: one Llama 3 8B decode step on an H100. It reads 16.06 GB of weights once plus every sequence’s KV cache, so the time is memory time:
| context | batch 1 | batch 16 | batch 64 |
|---|---|---|---|
| 1,024 | 4.83 ms (1% KV) | 5.44 ms (12% KV) | 7.36 ms (35% KV, 8,698 tok/s) |
| 8,192 | 5.11 ms (6%) | 9.92 ms (52%) | 25.3 ms (81%, 2,529 tok/s) |
| 32,768 | 6.08 ms (21%) | 25.3 ms (81%) | 86.8 ms (94%, 737 tok/s) |
At short contexts batching works: the weights are amortized, and throughput rises almost linearly with batch. At long contexts the KV cache dominates. Batch 64 at 32 k tokens is only 4.5× faster than batch 1, because the per-sequence KV bytes are not shared.
Long-context serving is bound by KV-cache bandwidth and capacity. That is why PagedAttention (§4), GQA and KV quantization matter, and why the memory-centric hardware of Lectures 14–15 exists. It also motivates disaggregated serving (DistServe, Splitwise), which runs compute-bound prefill and memory-bound decode on different machines, each sized for its own bottleneck.
| prefill | decode | |
|---|---|---|
| attention intensity | grows with the sequence length: hundreds to thousands of FLOP/byte | G FLOP/byte |
| bound | compute (with FlashAttention) | memory bandwidth (weights + KV) |
| parallelism | query blocks × heads × batch | batch × KV heads × KV splits |
| what helps | fusion, peak FLOPs, exp throughput | batch size (PagedAttention), fewer KV bytes, bandwidth |
6. What these kernels ask of an accelerator
The software techniques of this lecture translate into hardware requirements.
- Epilogue engines at the array’s output. Fusion moves the element-wise work next to the matmul, so a vector unit must accept the array’s output at full rate (Lecture 6). Examples are TPU’s vector unit behind the MXU and NVDLA’s single-data processor. If it is too slow, the fused kernel runs at the vector unit’s speed.
- Exponentials at the right ratio. Attention needs one exp per 4d = 512 matmul FLOPs (d = 128). Lecture 6 found the H100 provides one SFU exp per ~256 tensor-core FLOPs, so the softmax takes about half as long as the matmuls unless the two overlap. FlashAttention-3 schedules the overlap explicitly; its paper reports up to 740 TFLOPS (75% of H100 peak) in FP16.
- On-chip memory per attention engine: ~4d² elements. For d = 128 that is 128 KiB of bf16 for Q, K and V blocks plus the score tile. Part 2 showed that more memory per engine stops paying beyond this. Spend extra SRAM on a shared cache that holds K/V across query blocks, or on more engines.
- Indirect, block-granular DMA. Paged KV caches need gather lists and block tables in the memory system (Lecture 7), and blocks big enough for efficient DRAM bursts.
- Bandwidth and capacity for decode. No amount of FLOPs helps decode attention. Bytes per token (GQA, quantization) and bytes per second (HBM, processing in memory) do.
- Cheap dispatch. Launch overhead is a third of a short block (§2.2). Hardware command queues, recorded graphs, or the static schedules of dataflow machines (Lecture 12) all attack it.
7. The project guide
The course project runs from the proposal (due 02/05) through proposal reviews (02/10–02/12) to the poster session (03/12) and the final report (03/19). These notes replace the review sessions with this guide.
7.1 Four shapes of project
| Shape | Example question | Start from |
|---|---|---|
| Design and evaluate one block | How many SFU lanes must a vector unit next to a 128 × 128 array have so that FlashAttention’s softmax never stalls the array, for d = 64 and 128? | vector_unit.py (L6), systolic.py (L5) |
| A numeric format’s trade-off | Which block size and element format for a quantized KV cache keeps attention-output error within bf16’s own noise, and what does it buy in decode throughput? | numfmt.py/quant.py (L4), script 04 here |
| Compare mappings or dataflows | Over a transformer’s layers at batch 1–64, how much energy × delay does a fixed weight-stationary array lose against a searched mapping, and does a larger global buffer close the gap? | mapper.py (L9) |
| Reproduce a published result | Reproduce FlashAttention’s traffic theorem, or vLLM’s memory-utilization comparison, with an analytical model. Say exactly where the model and the paper disagree, and why. | flash.py, paged.py (L10); tpu_model.py (L5) |
7.2 Posing the question
A good question has one sentence, one metric and one decision that someone designing an accelerator would care about.
- Too vague: “Design a better accelerator for transformers.”
- Good: “At iso-area, does splitting one 256 × 256 array into four 128 × 128 arrays raise utilization on Llama 3 8B decode at batch 1–16 enough to pay for the extra NoC traffic?”
Write down:
- the independent variables you will sweep;
- the metric (attained throughput, energy per token, EDP, accuracy);
- the workloads, fixed before you see results;
- the constraints: area, power, memory, precision.
Sketch the one figure that will answer the question, with axes, before you write code. If you cannot sketch it, the question is not yet sharp.
7.3 Choosing the baseline
- Use the strongest reasonable baseline, under the same constraints: iso-area, iso-power, iso-memory, same precision (Lecture 3).
- Tune the baseline as hard as your design. If your design gets a mapper search (Lecture 9), the baseline gets one too. Comparing a fused kernel against eager execution without CUDA graphs, or a large batch against batch 1, is a straw man.
- Use a published design, or the course models’ default configuration, so others can check your numbers.
7.4 Building and validating the model
- Start from the course modules and change as little as necessary. Record what you changed.
- Validate before you explore. Check your model against something exact:
- a cycle-level simulator against an analytical count (Lecture 9 validated
mapper.pyagainst Lectures 5 and 7); - kernel counters against a formula (§3.3);
- your model against a published number, with the source’s conditions matched.
- a cycle-level simulator against an analytical count (Lecture 9 validated
- Keep a plan vs reality log, as the README of every code folder here does. Several of this course’s own conclusions changed because a check failed.
- Run a sensitivity analysis on every uncertain parameter, such as the per-SM bandwidth in §5.2, the launch overhead in §2.2, or the energy table. A conclusion that flips when a parameter moves by 2× is not a conclusion.
7.5 Reporting honestly (Lecture 3)
- Report attained throughput and utilization, not peak. Report energy with its breakdown, and area-normalized metrics (per mm², per W) when designs differ in size.
- Summarize ratios over workloads with the geometric mean. Show the full distribution too, because the worst workload often matters most.
- Label every number as simulated, analytical, measured, or quoted (with its source).
- Report negative results and the regimes where your design loses.
7.6 The proposal (one page)
Title: the question, as a claim to test
Question: one sentence; variables, metric, workloads, constraints
Why it matters: which design decision it informs
Baseline: what, under which constraints, how it is tuned
Method: model / simulator / course modules used; what you will build or change
Validation: what exact reference your model will be checked against
Expected result and the figure that will show it (sketch)
Risks and fallback: what you will report if the main plan fails
Milestones: week by week, to 03/12
7.7 The poster
- The title is the claim, for example “Four small arrays beat one big array for batch-1 decode by 1.6× at iso-area”. A topic is not a title.
- Use four panels: question → setup (one diagram of the design and model) → key figure → result and caveats.
- Make the key figure answer the question on its own, with units, the baseline marked, and readable from two meters.
- Prepare a two-minute pitch, and keep the reproducibility details (parameters, seeds, commands) for the report.
7.8 Checklist before you submit
- The question fits in one sentence, and the figure answers it.
- The baseline is strong, tuned, and under the same constraints.
- The model is validated against something exact, and the plan-vs-reality log is included.
- Uncertain parameters have a sensitivity analysis.
- Every number has units and a label (simulated / analytical / measured / quoted).
- The negative results and limitations are stated.
- The results are reproducible from the report: parameters, seeds, commands.
8. Summary
- Unfused element-wise operators do ~1 FLOP/byte. Each is a DRAM round trip plus a launch. Fusion keeps intermediates on chip and leaves the arithmetic unchanged; Script 01 agrees to 1e-15.
- Legality depends on execution order, compatible iteration spaces, row reductions fitting one kernel, no reductions in matmul prologues, no matmul–matmul fusion, and writing tensors that have other consumers. Profitability weighs the traffic saved against recomputation, register pressure and lost parallelism.
- On a Llama-sized block (2,048 tokens), fusing everything cuts DRAM traffic 4.0× and time 1.69× with the same FLOPs. The unfused attention chain alone is 62% of the traffic. At 128 tokens the weights dominate the traffic, and launches are a third of the time.
- PyTorch 2 automates this: TorchDynamo captures graphs, AOTAutograd decides save vs recompute, TorchInductor fuses and generates Triton.
- FlashAttention computes attention tile by tile with an online softmax. It is exact (2e-14 in float64), because the rescaling only reorders additions. Its traffic is Θ(N²d²/M), against Θ(N²) for standard attention. The gain stops at M = 4d², and on GPUs the L2 cache absorbs most of the K/V re-reads.
- The backward pass recomputes P from the saved log-sum-exp: +17% FLOPs, no N × N matrix.
- PagedAttention manages the KV cache in 16-token blocks through block tables:
- waste falls to the last block (0.40%);
- the mean batch rises from 46 to 98 and throughput by 1.55× in our model;
- a small watermark prevents preemption storms;
- copy-on-write sharing saves 62–83% for parallel samples.
- Decode attention has intensity G (the GQA group size) at any batch or context, so it is memory-bound. At batch 1 it must split the KV sequence across SMs: 8.1× at 131 k context under our bandwidth assumption, and exact.
- At long contexts, a decode step is 94% KV-cache traffic. Serving becomes a memory-capacity and memory-bandwidth problem.
- Projects: one-sentence question, strong baseline under equal constraints, validated model, sensitivity analysis, honest labelled metrics, one figure that answers the question.
9. Common pitfalls
- “Fusion saves FLOPs.” It saves bytes and launches; the 1,066 GFLOP never change (§2.1).
- “Fuse everything into one kernel.” A node whose other inputs are produced later cannot join (§1.4). Fusing a tensor with several consumers still requires writing it once.
- “FlashAttention approximates attention.” It is exact up to floating-point rounding (§3.2). Sparse and linear attention are the approximations.
- “More SRAM always lowers FlashAttention’s traffic.” Only up to M = 4d², and with too little SRAM it moves more than standard attention (§3.3).
- “FlashAttention’s speedup is all about K/V re-reads.” On GPUs it is mostly about never writing S and P; L2 absorbs most re-reads.
- “Batch decode to make attention compute-bound.” Batching amortizes weights, never the KV cache (§5.1).
- “Paging wastes nothing, so admit greedily.” Without headroom the server thrashes: 405 preemptions (§4.4).
- “The oracle is the upper bound.” Exact reservation still loses to paging, because it reserves future tokens from the start (§4.2).
- “Comparing against eager is a fair baseline.” For a project, tune the baseline as hard as your design (§7.3).
10. Exercises
Exercise 1 (pricing element-wise kernels). For the 2,048-token block (MLP width 14,336, bf16), compute the DRAM traffic and roofline time (+4 µs) of the unfused act = SiLU(gate) and prod = act ⊙ up kernels, and the traffic of the fused gate + up + act + prod kernel.
Answer
One T × F tensor is 2,048 × 14,336 × 2 bytes = 58.7 MB.
actreadsgateand writesact: 117 MB, 35.1 µs + 4 = 39.1 µs.prodreadsactandup, and writesprod: 176 MB, 52.6 + 4 = 56.6 µs.- The fused kernel reads h2 (16.8 MB) and both weight matrices (2 × 58.7 M × 2 bytes = 234.9 MB), and writes
prod(58.7 MB): 310 MB.
That matches Script 01, Part 3. The gate and up outputs (117 MB) and the act round trip never reach DRAM.
Exercise 2 (legality). Explain why the residual add y = x1 + down cannot join the kernel that computes x1, which kernel it joins instead, and why x1 is still written to DRAM after fusion.
Answer
Kernels execute in order, each as a unit. The [o, x1] kernel runs before the MLP, so down does not exist yet when that kernel runs. A node may join a kernel only if all its other inputs come from earlier kernels.
y therefore joins the down projection’s kernel, as its epilogue. Its other input, x1, was produced earlier.
x1 has two consumers in different kernels: RMSNorm (h2) and the final add. So it must be written once (16.8 MB) and read by both.
Exercise 3 (an illegal fusion made legal by algebra). with . Show how to compute it with no separate normalization kernel, and what that saves per RMSNorm at 2,048 tokens.
Answer
- Fold the gain into the weights offline: . Then .
- The matmul streams each row completely along K. It can accumulate for its rows while loading the tiles.
- Apply to the output rows in the epilogue.
The reduction runs inside the matmul, and the scaling is element-wise on the output. This removes the h1 kernel: 33.6 MB of traffic (read x, write h1) plus a launch, about 14 µs + 4 µs. Over the two RMSNorms, that is ~36 µs of the 1.13 ms fused block.
The “no reduction in a prologue” rule of §1.4 was conservative: a reduction along the matmul’s own K axis is available to the tile.
Exercise 4 (online softmax by hand). Process scores (2, 0, 4, 1) with scalar values (1, 2, 3, 4) in blocks of two. Give (m, ℓ, acc) after each block and the output, and check against the direct softmax.
Answer
- Block 1: m = 2, ℓ = 1 + e⁻² = 1.1353, acc = 1 + 2e⁻² = 1.2707.
- Block 2: m’ = 4, α = e⁻² = 0.1353. ℓ = 0.1353 × 1.1353 + 1 + e⁻³ = 1.2034. acc = 0.1353 × 1.2707 + 3 + 4e⁻³ = 3.3711.
- o = 2.8012.
Directly: the weights e^{s−4} = (0.1353, 0.0183, 1, 0.0498) sum to 1.2034, and the weighted values sum to 3.3711, so o = 2.8012. The results are identical.
Exercise 5 (the traffic formula and its cap). For N = 8,192, d = 64, non-causal, compute FlashAttention’s DRAM traffic with M = 16,384 elements and with M = 65,536, and compare with three-kernel standard attention.
Answer
With M = 16,384: B_c = ⌈16,384 / 256⌉ = 64 and B_r = min(64, 64) = 64. Traffic = Nd + (N/B_r) · 2Nd + Nd + N = 0.52 M + 128 × 1.05 M + 0.52 M + 0.008 M = 135.3 M elements. Standard: 4N² + 4Nd = 270.5 M, so flash is 2.0× better.
With M = 65,536: B_c = 256, but B_r is capped at d = 64. The number of query blocks is unchanged, so the traffic is the same 135.3 M.
The cap is at M = 4d² = 16,384. For d = 64, SRAM beyond 32 KiB of bf16 per attention kernel buys no DRAM traffic. (flash.flash_traffic reproduces both numbers.)
Exercise 6 (associativity). Prove that ⊕ on (m, ℓ) (§3.6) is associative and has an identity element, and explain what this permits.
Answer
Represent a partial as (m, ℓ) with the meaning “ℓ = Σ e^{s−m} over a set of scores”. Then (m₁, ℓ₁) ⊕ (m₂, ℓ₂) = (m, ℓ₁e^{m₁−m} + ℓ₂e^{m₂−m}) is the representation of the union of the two sets, relative to the larger maximum.
Both groupings of three partials represent the union of all three sets, relative to its maximum. The representation is unique once m is fixed, so the two groupings are equal. The identity is (−∞, 0).
Associativity is what allows any blocking, any order, and parallel trees:
- FlashAttention tiles (§3);
- split-KV decoding (§5.2);
- reductions across GPUs for sequence-parallel attention.
The same holds for acc.
Exercise 7 (backward cost). Derive the +17% FLOPs of FlashAttention’s training step for one head, and the memory saved at N = 131,072.
Answer
Each N × N × d tile matmul is 2N²d FLOPs.
- Forward: QKᵀ and PV, 2 matmuls.
- Standard backward: dV = PᵀdO, dP = dO Vᵀ, dQ = dS K, dK = dSᵀQ, 4 matmuls.
- Flash backward: the same 4 plus recomputing S = QKᵀ, 5 matmuls.
Total: 7 vs 6, so +16.7% (exponentials ignored).
Memory: P in bf16 is 131,072² × 2 bytes = 34.4 GB per head per layer. L in float32 is 131,072 × 4 bytes = 524 kB.
Exercise 8 (KV capacity). Llama 3 70B has 80 layers and 8 KV heads of 128. Four 80 GB GPUs hold 141 GB of bf16 weights. Ignoring activations, how many KV tokens fit? How many requests fit if each reserves 4,096 tokens, versus paging with ~525 live tokens per request on average?
Answer
KV per token = 2 × 80 × 8 × 128 × 2 bytes = 320 KiB. The remaining memory is 320 − 141 = 179 GB, so ~546,000 tokens fit.
- Reserving 4,096 per request: ~133 requests.
- Paging at ~525 live tokens (prompt + half the output, on average): ~1,040 requests. The batch would then be limited by compute or by latency targets, not by memory.
The 8× difference is the whole case for PagedAttention.
Exercise 9 (block-size waste). Predict the last-block slack for B = 16 and B = 256 from the half-block rule, Part 3’s mean batches (98.5 and 92.5) and the 183,000-token cache.
Answer
A sequence of n tokens holds ⌈n/B⌉ blocks. If n mod B is spread evenly, the expected slack is (B − 1)/2 tokens.
- B = 16: 98.5 × 7.5 = 739 tokens = 0.40%. The measured value is 0.40%.
- B = 256: 92.5 × 127.5 = 11,794 tokens = 6.4%. The measured value is 6.35%.
At B = 256 the evenly-spread assumption is rough: a block is comparable to the sequence lengths themselves, so the remainders are not quite uniform. (This check found a bug in the simulator; see the code README’s “Plan vs reality”.)
Exercise 10 (decode intensity). Compute decode attention’s intensity for multi-query attention (1 KV head, 32 query heads) in bf16, and with a 4-bit KV cache under GQA (G = 4). Is either compute-bound on an H100?
Answer
Intensity = G × (2 bytes ÷ bytes per element) FLOP/byte.
- MQA, bf16: 32 FLOP/byte.
- GQA (G = 4) with a 4-bit cache: 4 × 4 = 16 FLOP/byte. (Group scales add a little traffic, Lecture 4.)
Both are far below the ridge of 295, so decode attention stays memory-bound. These techniques cut the bytes and therefore the time (by 32× and 16× respectively, vs MHA bf16), but they do not change the bound.
Exercise 11 (choosing the split count). With the §5.2 model (per-SM bandwidth ≤ 2 × fair share), how many splits saturate the H100’s bandwidth for batch 4 with 8 KV heads? How does the answer change if one SM can pull 4× its fair share?
Answer
Saturation needs items × 2 × BW/132 ≥ BW, so items ≥ 66. With 4 × 8 = 32 items per split count, s ≥ 66/32 = 2.06, so 3 splits (4 if powers of two are required).
At 4× fair share, items ≥ 33, so 2 splits.
This is the sensitivity analysis of §7.4: the best split count moves with the assumption, but “split until batch × KV heads × splits ≳ the number of SMs” does not.
Exercise 12 (programming: swap vs recompute). vLLM can swap a preempted sequence’s blocks to CPU memory instead of recomputing them. Estimate both costs per KV token for Llama 3 8B on an H100 with PCIe 5 (~64 GB/s per direction). Then add a "swap" preemption mode to paged.simulate that charges 2 × length × 128 KiB / 64 GB/s (out and back) instead of recomputation.
Answer
- Recompute: 2 × 8.03 G params FLOPs per token on 989 TFLOPS = 16.2 µs per token at peak. Prefill rarely runs at peak, so this is a lower bound.
- Swap: 128 KiB / 64 GB/s = 2.05 µs per token each way, 4.1 µs round trip. The transfer can overlap with compute, but it uses host memory and PCIe bandwidth.
For this model, at these rates, swapping is ~4× cheaper per token. The ratio scales with params per KV byte: GQA makes KV bytes small, which favours swapping. Recompute needs no host memory and no PCIe, which favours it when the link is shared with other traffic.
Implementation:
- Keep a
swappedset. - On preemption, add the transfer time to
secondsand keepvictim.generated, without adding torecomputed. - On readmission, charge the transfer back instead of the prefill.
The vLLM paper compares the two and finds that the better choice depends on block size, since small blocks make PCIe transfers inefficient.
11. Further reading
- T. Dao, D. Y. Fu, S. Ermon, A. Rudra, C. Ré, “FlashAttention: fast and memory-efficient exact attention with IO-awareness”, NeurIPS 2022.
- T. Dao, “FlashAttention-2: faster attention with better parallelism and work partitioning”, ICLR 2024.
- J. Shah et al., “FlashAttention-3: fast and accurate attention with asynchrony and low-precision”, NeurIPS 2024.
- T. Dao, D. Haziza, F. Massa, G. Sizov, “Flash-Decoding for long-context inference”, 2023 (blog post).
- M. Milakov, N. Gimelshein, “Online normalizer calculation for softmax”, arXiv 2018. M. N. Rabe, C. Staats, “Self-attention does not need O(n²) memory”, arXiv 2021.
- W. Kwon et al., “Efficient memory management for large language model serving with PagedAttention”, SOSP 2023.
- G.-I. Yu et al., “Orca: a distributed serving system for transformer-based generative models”, OSDI 2022.
- L. Zheng et al., “SGLang: efficient execution of structured language model programs”, NeurIPS 2024 (RadixAttention).
- R. Prabhu et al., “vAttention: dynamic memory management for serving LLMs without PagedAttention”, ASPLOS 2025.
- Y. Zhong et al., “DistServe: disaggregating prefill and decoding for goodput-optimized LLM serving”, OSDI 2024. P. Patel et al., “Splitwise: efficient generative LLM inference using phase splitting”, ISCA 2024.
- J. Ansel et al., “PyTorch 2: faster machine learning through dynamic Python bytecode transformation and graph compilation”, ASPLOS 2024.
- P. Tillet, H. T. Kung, D. Cox, “Triton: an intermediate language and compiler for tiled neural network computations”, MAPL 2019.
- J. Ainslie et al., “GQA: training generalized multi-query transformer models from multi-head checkpoints”, EMNLP 2023.
12. Next lecture
Lecture 11, GPU architectures, opens the architecture unit with the machine all these kernels were written for. The topics:
- streaming multiprocessors, warps and SIMT execution;
- tensor cores, and how a matmul tile maps onto them;
- the memory hierarchy: registers, shared memory, L2 and HBM. FlashAttention’s tiles live in shared memory, and the L2 cache absorbed its re-reads in §3.3;
- occupancy and latency hiding;
- the asynchronous copy engines that FlashAttention-3 relies on.
We will also see why the H100’s balance of tensor FLOPs to SFU exponentials (Lecture 6) forced attention kernels to overlap softmax with matmuls.