Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Score matrix | The S × S table of query–key dot products that attention turns into weights with softmax (10.h). S is the sequence length. |
| SRAM / shared memory | The small, fast memory inside each SM (4.d). Hundreds of KB per SM, versus tens of GB of HBM. |
| Tiling | Splitting a big computation into blocks small enough to fit in SRAM, and working through them one at a time. |
| Online softmax | Computing softmax in pieces, keeping a running maximum and running sum, and rescaling as new pieces arrive (10.g). |
| Exact | Gives the same answer as textbook attention, apart from floating-point rounding order. Not an approximation. |
| Warp specialization | Giving different groups of threads different jobs — some load data, some compute — so loading and computing overlap. |
| Split-K (FlashDecoding) | Dividing the keys of one long sequence among many thread blocks, then combining their partial results. |
| Paged KV | A KV cache stored in fixed-size blocks found through a block table (12.l). |
The most important algorithmic optimization in transformer inference — not because it is the fastest kernel, but because without it, long context is impossible.
1. Problem → Why → Optimization#
PROBLEM Textbook attention materializes an (S × S) score matrix in HBM.
At S = 8,192, batch 8, 32 heads, FP16 that is 34 GB — for ONE layer.
WHY softmax(QKᵀ/√d)V is written as three separate steps, each writing
its intermediate to memory.
OPTIMIZE Tile the computation and use online softmax so the score matrix
never leaves SRAM. Exact, not approximate.
TRADE-OFFS
✓ O(S) extra memory instead of O(S²)
✓ 2–10× faster (far fewer HBM round trips)
✓ EXACT — equal to the textbook version up to floating-point order
✗ needs a hand-tuned kernel per GPU generation (FA-3 Hopper, FA-4 Blackwell)
✗ limited head dimensions and data types per kernel
✗ recomputation in the backward pass (irrelevant for inference)
WHEN TO USE Always.
WHEN NOT TO Never, for standard attention. If your head_dim or dtype is not
supported, find a kernel that supports it.Facts checked on 12 November 2026.
2. Why does it exist?#
The insight from Dao et al. (2022): attention is memory-bound, not compute-bound, and the textbook implementation’s memory traffic is dominated by writing and reading a matrix you do not need to keep.
Textbook attention HBM traffic (per head, per layer, 2-byte values):
write S, read S, write P, read P: 4 × S² × 2 bytes
+ Q, K, V, O: 4 × S × d × 2 bytes
≈ 8S² + 8Sd bytes
FlashAttention:
read Q, K, V (each K/V block read once per query block), write O
≈ O(S²d / M) bytes, where M = SRAM size
→ for typical S, d and M: 5–20× less HBM trafficIt does not make attention compute less. It makes it move fewer bytes — and on the roofline (6.a), for a memory-bound kernel, that is the same as making it faster.
3. Simple analogy#
Computing a weighted average of a million items with a small desk.
Textbook: write all million weights on paper, spread them across the floor, normalize them, then combine. You need a warehouse.
FlashAttention: process items in batches of 100. Keep a running total and a running normaliser on your desk. When a new batch has a larger maximum, rescale what you have so far and carry on. At the end, divide. Same answer, one desk.
The “rescale what you have so far” step is online softmax (10.g), and it is the only non-obvious part.
4. Tiny example: the algorithm, checked#
The program runs textbook (causal) attention and FlashAttention on the same random inputs and compares them, then shows how much memory the score matrix would need.
// FlashAttention for one head, checked against textbook attention.
package main
import (
"fmt"
"math"
"math/rand"
)
// naive builds every row of scores (the S×S matrix, one row at a time here).
func naive(Q, K, V [][]float64) [][]float64 {
S, d := len(Q), len(Q[0])
scale := 1 / math.Sqrt(float64(d))
O := make([][]float64, S)
for i := range Q {
s := make([]float64, i+1) // causal: keys 0..i
mx := math.Inf(-1)
for j := 0; j <= i; j++ {
for c := 0; c < d; c++ {
s[j] += Q[i][c] * K[j][c]
}
s[j] *= scale
mx = math.Max(mx, s[j])
}
sum := 0.0
for j := range s {
s[j] = math.Exp(s[j] - mx)
sum += s[j]
}
O[i] = make([]float64, d)
for j := range s {
for c := 0; c < d; c++ {
O[i][c] += s[j] / sum * V[j][c]
}
}
}
return O
}
// flash never builds the S×S matrix: it walks key blocks with an online softmax.
func flash(Q, K, V [][]float64, blockQ, blockK int) [][]float64 {
S, d := len(Q), len(Q[0])
scale := 1 / math.Sqrt(float64(d))
O := make([][]float64, S)
for i0 := 0; i0 < S; i0 += blockQ { // a block of queries, kept "on chip"
i1 := min(i0+blockQ, S)
m := make([]float64, i1-i0) // running max per query
l := make([]float64, i1-i0) // running sum of exp per query
acc := make([][]float64, i1-i0) // running weighted sum of V
for r := range m {
m[r], acc[r] = math.Inf(-1), make([]float64, d)
}
for j0 := 0; j0 < i1; j0 += blockK { // a block of K and V
j1 := min(j0+blockK, S)
for r, i := 0, i0; i < i1; r, i = r+1, i+1 {
hi := min(j1, i+1) // causal mask
if hi <= j0 {
continue
}
s, mNew := make([]float64, hi-j0), m[r]
for j := j0; j < hi; j++ {
for c := 0; c < d; c++ {
s[j-j0] += Q[i][c] * K[j][c]
}
s[j-j0] *= scale
mNew = math.Max(mNew, s[j-j0])
}
// ---- online softmax update ----
alpha := math.Exp(m[r] - mNew) // rescale what we already have
l[r] *= alpha
for c := range acc[r] {
acc[r][c] *= alpha
}
for j := j0; j < hi; j++ {
p := math.Exp(s[j-j0] - mNew)
l[r] += p
for c := 0; c < d; c++ {
acc[r][c] += p * V[j][c]
}
}
m[r] = mNew
}
}
for r, i := 0, i0; i < i1; r, i = r+1, i+1 { // normalize once, at the end
O[i] = acc[r]
for c := range O[i] {
O[i][c] /= l[r]
}
}
}
return O
}
func randn(rng *rand.Rand, rows, cols int) [][]float64 {
x := make([][]float64, rows)
for i := range x {
x[i] = make([]float64, cols)
for j := range x[i] {
x[i][j] = rng.NormFloat64()
}
}
return x
}
func main() {
const S, d = 1024, 64
rng := rand.New(rand.NewSource(1))
Q, K, V := randn(rng, S, d), randn(rng, S, d), randn(rng, S, d)
ref, out := naive(Q, K, V), flash(Q, K, V, 128, 128)
diff := 0.0
for i := range ref {
for c := range ref[i] {
diff = math.Max(diff, math.Abs(ref[i][c]-out[i][c]))
}
}
fmt.Printf("max |naive - flash| = %.1e\n", diff)
// What a GPU would have to store for the score matrix, per head, in BF16.
for _, n := range []int{2048, 8192, 32768, 131072} {
scores := float64(n) * float64(n) * 2
state := float64(n) * float64(d+2) * 4 // m, l and acc per query, FP32
fmt.Printf("S=%6d full score matrix %9.1f MiB flash running state %6.1f MiB\n",
n, scores/(1<<20), state/(1<<20))
}
}Output:
max |naive - flash| = 8.3e-16
S= 2048 full score matrix 8.0 MiB flash running state 0.5 MiB
S= 8192 full score matrix 128.0 MiB flash running state 2.1 MiB
S= 32768 full score matrix 2048.0 MiB flash running state 8.2 MiB
S=131072 full score matrix 32768.0 MiB flash running state 33.0 MiBRead the lines under “online softmax update” carefully. They are the whole contribution.
alpha rescales everything accumulated so far to the new maximum; then the new block is added at
the same scale. The difference from the textbook answer, 8 × 10⁻¹⁶, is floating-point rounding.
The memory lines are per head, per sequence. Multiply by 32–128 heads and a batch of sequences, and the score matrix stops fitting anywhere at 32k context; the running state grows only linearly.
5. Technical explanation#
The tiling and the SRAM budget#
Choose Bq, Bk so that this fits in shared memory:
Q tile (Bq × d) + K tile (Bk × d) + V tile (Bk × d) + scores (Bq × Bk)
For d = 128, FP16, 228 KB shared memory per SM (Hopper):
Bq = 128, Bk = 128:
3 × 128 × 128 × 2 B (Q, K, V) + 128 × 128 × 2 B (S) = 96 KB + 32 KB = 128 KB ✓
For d = 256:
Bq = 64, Bk = 128 to stay within budgetThis is why head_dim decides which kernel you get, and why unusual head dimensions may have no fast path.
FlashAttention-1 → 2 → 3 → 4#
FA-1 (2022)
Tiling + online softmax + recomputation in the backward pass.
Parallel over batch and heads only.
FA-2 (2023)
- Parallel over the SEQUENCE dimension too (more blocks → better
occupancy for long S at small batch)
- Fewer non-matmul FLOPs (fewer rescalings; divide once at the end)
- Better split of work between warps
~2× over FA-1; 50–73% of A100 peak (paper's figures).
FA-3 (2024, Hopper)
- TMA for asynchronous bulk copies HBM → shared memory
- Warp specialization: producer warps load, consumer warps compute
- Overlap softmax (non-tensor-core work) with matmuls ("ping-pong")
- FP8 support
1.5–2.0× over FA-2 on H100; up to ~740 TFLOP/s in FP16 (75% of peak).
FA-4 (March 2026, Blackwell; MLSys 2026)
Blackwell doubled tensor-core throughput but not shared-memory bandwidth
or the exponential units, so softmax became the bottleneck.
- Fully asynchronous tensor-core MMAs with larger tiles, accumulating in
Blackwell's tensor memory (TMEM)
- Some exponentials computed in software with polynomials on the ordinary
FMA units, to relieve the special-function units
- Conditional rescaling: only rescale the accumulator when the running
max has grown enough to matter
- Written in CuTe-DSL (Python) — 20–30× faster to compile than C++ templates
Up to ~1.6 PFLOP/s BF16 on B200 (71% of peak); up to 1.3× over cuDNN 9.13
and 2.7× over Triton (authors' figures).The decode variant: FlashDecoding#
Prefill has thousands of query rows, so there is plenty of parallel work. Decode has one query per sequence:
Decode, batch 8, 32 heads, S = 32,768:
Parallel over (batch × heads) = 256 blocks on 132 SMs → under 2 waves, poor.
And each block must walk 32,768 / 128 = 256 key blocks one after another.FlashDecoding splits the key dimension:
Split the 256 key blocks among, say, 8 thread blocks per head.
Each computes a PARTIAL (unnormalized) output with its own (m, l).
A small second kernel combines the partials with the same rescaling.
→ 256 × 8 = 2,048 blocks. The GPU is full.The same trick (online softmax combines in any order), applied across thread blocks instead of within one. Its authors reported up to 8× faster end-to-end generation for very long sequences at batch 1.
Paged FlashAttention#
Combined with PagedAttention (12.l), K/V blocks are found through a block table instead of read contiguously:
for blk in range(num_blocks_for_this_seq):
phys = block_table[seq][blk]
Kj = k_cache[phys] # ← the indirection
...The cost is one extra lookup per block and slightly worse coalescing at block edges — a few percent on the kernel — for several times more concurrency. Every production engine takes that trade.
6. Under the hood: the Hopper and Blackwell pipelines#
FA-3 on Hopper:
Producer warps (TMA):
issue async copies of K, V tiles HBM → shared memory
signal a barrier when a tile arrives
Consumer warpgroups:
wait on the barrier
WGMMA: Q × Kᵀ (tensor cores, from shared memory)
softmax on the result (exp, max, sum — not tensor cores)
WGMMA: P × V
rescale the accumulator
PING-PONG:
while warpgroup A does softmax, warpgroup B does its matmul
→ the tensor cores rarely wait for softmaxFA-4 on Blackwell keeps the producer/consumer split but changes where the bottleneck sits:
tensor cores: MMA results land in TMEM (tensor memory), not registers
softmax warps: read scores from TMEM, compute exp — partly with polynomial
approximations on FMA units — and skip rescaling when the max
barely moved
correction: a separate warpgroup rescales the output accumulator off the
critical pathThe lesson generalizes: each GPU generation shifts the balance between matmul throughput and everything else, so the attention kernel must be redesigned around the new slowest unit.
7. Performance implications#
Memory, per layer, for batch 8 and 32 heads (from the arithmetic in section 4):
S textbook score matrix (BF16) FlashAttention extra memory
2,048 2 GiB small (running state)
8,192 32 GiB small
32,768 512 GiB small
131,072 8 TiB smallAbove a few thousand tokens the comparison is meaningless, because textbook attention cannot run. FlashAttention is what makes long context exist.
Speed, from the papers: FA-2 about 2× FA-1; FA-3 1.5–2× FA-2 on H100; FA-4 up to 1.3× over cuDNN on B200. For decode at long context, split-K is the difference between a half-empty and a full GPU.
8. Production implications#
- Always use a fused attention kernel. FlashAttention, FlashInfer, cuDNN attention or your engine’s built-in.
- Know what your engine picked. In vLLM v0.32.0 the
FLASH_ATTNbackend defaults to FA-4 on Blackwell (SM100+), FA-3 on Hopper and FA-2 otherwise (--attention-config.flash_attn_version). On Blackwell, FlashInfer is tried before FlashAttention for standard attention; MLA models use dedicated MLA backends (18.c). Check the start-up log. - Verify the backend in your own PyTorch code.
scaled_dot_product_attentionchooses among flash, memory-efficient, cuDNN and math kernels by dtype, head_dim, mask and alignment. Falling back tomathis a silent 10× regression at long context.Pythonfrom torch.nn.attention import sdpa_kernel, SDPBackend with sdpa_kernel([SDPBackend.FLASH_ATTENTION]): out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # raises if flash cannot be used — put this in tests to catch silent fallbacks - Check head_dim support. Common kernels support 64, 96, 128 and 256. Unusual values may have no fast path.
- Use split-K decode kernels for long-context decode; engines do this automatically.
- Re-benchmark after upgrades. Attention backend selection changes between versions.
9. Common mistakes#
- Writing textbook attention in custom code. Fine at S = 512, fatal at S = 8,192.
- Not noticing a backend fallback.
- Assuming FlashAttention is an approximation. It is exact.
- Using a prefill-shaped kernel for long-context decode. Too few blocks; several times slower.
- Materializing an explicit
(B, h, S, S)mask tensor. That defeats the purpose even if the kernel is flash. Useis_causal=Trueor a compact mask. - Padding sequences instead of using variable-length (varlen) kernels. Wastes work on padding.
- Assuming the Hopper kernel is best on Blackwell. FA-3’s design does not match Blackwell’s bottlenecks; use FA-4, FlashInfer or cuDNN there.
10. Hands-on exercise#
A. Run and break it. Run the program in section 4. Then delete the three alpha lines and run
again. How large is the error now, and why?
B. Online softmax alone. Verify separately that online softmax over blocks equals the full softmax for blocks of 1, 7 and 128 values. This is the piece people get wrong.
C. Backend detection. For a grid of (dtype, head_dim, mask type), find which backend PyTorch’s SDPA selects. Build a compatibility table for your version. Which configurations silently fall back?
D. FlashDecoding. Implement decode attention two ways: one block per (sequence, head), and split over keys. At S = 32,768 and batch 1, measure both and explain the difference with SM occupancy.
E. Read the real kernel. In the flash-attention repository, find the tiling loop, the online
softmax update, the shared-memory layout and the causal block-skipping logic. For FA-4 (the
flash_attn/cute directory), find where the rescale is skipped.
11. Interview questions#
- What problem does FlashAttention solve? Give the memory arithmetic.
- Explain online softmax and why it makes tiling possible.
- Is FlashAttention an approximation? Justify your answer.
- What changed between FlashAttention-2, 3 and 4, and what hardware change drove each?
- What is FlashDecoding and why does decode need a different parallelization?
- How does head_dim affect which kernel you can use?
- How would you detect that your stack silently fell back to a non-flash backend?
- How does paged attention interact with FlashAttention, and what does the indirection cost?
12. Further reading#
Checked on 12 November 2026.
- [ESTABLISHED] Dao et al., “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness” (NeurIPS 2022) — read this paper
- [ESTABLISHED] Dao, “FlashAttention-2” (2023)
- [ESTABLISHED] Shah et al., “FlashAttention-3” (2024)
- [ESTABLISHED] Zadouri et al., “FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling” (2026)
- [ESTABLISHED] Dao et al., “Flash-Decoding for long-context inference” (2023)
- [ESTABLISHED] Milakov & Gimelshein, “Online normalizer calculation for softmax” (2018)
- [REFERENCE] flash-attention (FA-4:
pip install flash-attn-4) and FlashInfer - [REFERENCE] vLLM v0.32.0 attention backends