Skip to content

โš™๏ธ Chapter 6 โ€” Attention: The Kernel Side โ€‹

Episodes 25 โ€“ 27

1. FlashAttention: never write the Nร—N matrix โ€‹

The shapes โ€‹

Thin in, thin out. The square only exists in the middle. Q, K, V and O together โ‰ˆ 4 MB, while each square โ‰ˆ 134 MB.

Standard attention: the square crosses HBM 4 times โ€‹

FlashAttention = tiling + online softmax โ€‹

Online softmax, worked example: the running max is 4 and a new tile contains 5. Everything accumulated so far is off by the same factor e^(4โˆ’5) โ‰ˆ 0.37. Multiply the running sum and the partial output by 0.37, and it's as if you'd known the max was 5 all along.

โœ… Exact, not an approximation. It's the same formula in a different order (tiny float-rounding differences only). GPT-2 trained both ways reached the same quality.

What it bought (GPT-2 medium, A100, 1K tokens, batch 64, fwd + bwd) โ€‹

StandardFlashAttention
GFLOPs~67~75 (more math: backward pass recomputes tiles)
HBM traffic40.3 GB4.4 GB
Time41.7 ms7.3 ms (> 5ร—)
  • Memory grows linearly in N instead of quadratically. First Transformer to beat chance on Path-X (16K): 61.4%.
  • It's a kernel: no retraining, same weights, and it does not shrink the KV cache.

When attention is slow, look at what moves between memories before you look at the math.


2. FlashAttention 2, 3, 4: rebuilt for each GPU's bottleneck โ€‹

Inside each tile there are two kinds of work:

On A100: tensor cores do 312 TFLOP/s (FP16/BF16) vs 19.5 TFLOP/s FP32, so each non-matmul FLOP costs ~16ร—.

๐Ÿ…ฐ๏ธ FA2 on A100: three wastes removed โ€‹

  1. Divide once at the end instead of renormalizing after every tile
  2. Parallelize along the sequence: FA1 made one job per (batch ร— head). A 16K prompt with 16 heads = 16 jobs for 108 SMs. FA2 makes one job per Q-row block.
  3. Split Q (not K/V) across warps, so the forward pass needs no warp-to-warp exchange through SRAM

โ†’ ~2ร— FA1, close to a well-tuned GEMM.

๐Ÿ…ท FA3 on H100: overlap โ€‹

  • FA2 reached only 35% on H100 (vs 80โ€“90% for a GEMM), partly because of old Ampere instructions.
  • Deeper cause: the exp unit โ‰ˆ 3.9 T/s, 256ร— slower than the tensor cores. Even with 512ร— more matmul ops than exps, the exps take about half the matmul time.

โ†’ 1.5โ€“2ร— FA2, up to 740 TFLOP/s FP16 (75%), plus FP8 support.

๐Ÿ…ฑ๏ธ FA4 on B200: the exponential is the wall โ€‹

  • Tensor math per SM per clock doubled, but the exp unit is still 16 ops/SM/clock and SRAM is still 128 B/clock.
  • 128ร—128 tile, d = 128, BF16 forward: matmul 1024 cycles = exp 1024 cycles. A tie.
  • FA3 doesn't run on B200 (Hopper-specific instructions).

Fixes:

  1. Software exp: a degree-3โ€“5 polynomial on the FMA units for 10โ€“25% of each row (error โ‰ˆ hardware's after BF16 rounding)
  2. Lazy rescale: keep the stale max and only rescale when the factor passes about 256 (per warp of 32); the final divide still gives the exact output

โœ… Takeaways

  • On a new GPU, check which attention kernel your stack runs and whether it was written for that chip (FA2 vs FA3 on H100: 35% vs 75%).
  • When a spec sheet says the tensor cores doubled, check what didn't double per SM per clock: the exp unit, SRAM bandwidth.

3. Flash-Decoding: why long prompts leave the GPU idle โ€‹

Same 64K cached tokens, very different time (A100, FP16, 16 Q heads / 2 KV heads, d = 128):

Bars = FlashAttention 2 ยท line = Flash-Decoding (approximate)

Why? At decode there's one query row, so FA2's jobs come only from batch ร— heads. 1 sequence ร— 16 heads = 16 jobs for 108 SMs. Long contexts also push you toward small batches, which makes it worse.

Split along the one dimension that's still big: the KV cache โ€‹

  • Splitting = views into the cache, so no GPU work
  • LSE (log-sum-exp) records each chunk's total softmax weight โ†’ exact merge, in any order
  • Result: about 56โ€“78 ยตs, almost constant up to 64K. At 64K: ~36ร— faster (64 vs 2300 ยตs). At 128K: 107 vs 4600 ยตs.
  • End to end on CodeLlama-34B, batch 1: up to 8ร— faster generation for very long sequences
  • Available in FlashAttention โ‰ฅ 2.2 and xFormers โ‰ฅ 0.0.22 (the dispatcher picks by problem size)

What later kernels add โ€‹

KernelAddition
FlashInfer: split schedulerfair share = ฮฃ KV lengths รท thread blocks. Long requests are split into โ‰ค share chunks; short ones run whole with no merge. Longest-first onto the least-loaded block. Deterministic (no atomics).
FlashInfer: GQA head stackingstack the 8 query heads of a group as rows โ†’ one KV load serves 8 heads (TRT-LLM's XQA does something similar)
FlashDecoding++: fixed maxthe synchronized max update cost 18.8% of attention time (Llama-2-7B). Use a fixed subtraction constant (99.99% of scores in [โˆ’16.8, 6.5]) and recompute rows that fall outside. โš ๏ธ Model-dependent: OPT-6.7B's range is โˆ’497 to 363, so it's not used there.

At decode, find the part of the request that's actually big. That's where the parallel work is.

<<>> with โ™ฅ๏ธ by S@Nchit