FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
TL;DR. Standard attention writes the N×N score and probability matrices to GPU main memory (HBM) and reads them back. FlashAttention never materialises them. It loads blocks of Q, K and V into on-chip SRAM, computes each tile there, and keeps a running softmax so the result is exact. Fewer HBM transfers make attention several times faster, and memory becomes linear in sequence length.
Why it matters now. Every long-context RAG system, every listwise reranker that reads dozens of passages, and every RL rollout of a search agent with a long trajectory runs on fused attention kernels that descend from this paper. It also teaches the lesson behind most LLM efficiency work: count bytes moved, not FLOPs. For an academic GPU budget, this is often the difference between a 4K and a 16K training context.
Key idea
Section titled “Key idea”For one row of scores split into blocks, keep only the running maximum and normaliser. Merging two blocks with statistics and gives
and the partial output is rescaled the same way:
Algorithm 1 loops over key/value blocks (outer) and query blocks (inner), with and for SRAM size . Theorem 2 counts HBM accesses:
Proposition 3 shows that no exact algorithm can do asymptotically better for all .
Key results
Section titled “Key results”- GPT-2 medium attention (N = 1024, d = 64, A100, Fig. 2): 66.6 → 75.2 GFLOPs, but HBM traffic 40.3 → 4.4 GB and runtime 41.7 → 7.3 ms.
- End-to-end training (§4.1): 15% faster than the MLPerf 1.1 BERT-large record; GPT-2 small 3.5× faster than HuggingFace (9.5 → 2.7 days) and GPT-2 medium 3.0× (Table 2); 2.4× on Long-Range Arena.
- Longer context (§4.2, Table 4): GPT-2 small at 4K context reaches 17.5 perplexity against 18.2 at 1K, and still trains faster than Megatron-LM at 1K.
- New capabilities: first better-than-chance Transformer on Path-X (16K, 61.4%) and, with block-sparse attention, Path-256 (64K, 63.1%).
- Memory: up to 20× more memory-efficient than exact baselines, linear in N (§4.3).
Limitations & open questions
Section titled “Limitations & open questions”- Each new attention variant needs a new hand-written CUDA kernel (§5). Later Triton and compiler work tries to close this gap.
- The IO analysis covers one GPU. Multi-GPU attention adds another memory level that the paper leaves open.
- FlashAttention reached only part of the A100’s matmul peak; FlashAttention-2 shows the remaining loss is in work partitioning, not IO.
- It does not change the quadratic FLOP count. For very long RAG prompts, compute, not memory, becomes the wall.
- Open question for retrieval: if attention memory is no longer the limit, is it better to give the reader more passages, or to spend the same compute on a stronger reranker? Lost in the Middle and RULER suggest more context alone is not free.
Connections
Section titled “Connections”- Before: Attention Is All You Need defines the computation being optimised. Making Deep Learning Go Brrrr gives the compute / memory / overhead mental model.
- After: FlashAttention-2 fixes work partitioning; GQA and PagedAttention attack the decoding-time KV cache; Native Sparse Attention builds hardware-aligned sparsity on the same IO reasoning.
- Long context: cheaper attention made long windows possible, but Lost in the Middle and RULER show models do not use them fully.
- IR link: late-interaction retrievers such as ColBERT face the same “memory traffic, not FLOPs” trade-off when scoring many token vectors.
Questions to think through
These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.
- Derive / compute
Run the online softmax by hand. One query row has scores x = (1, 3 | 2, 5), split into two key blocks of two. Compute the block statistics (m₁, ℓ₁) and (m₂, ℓ₂), merge them, and check the result against the direct normaliser. Then say exactly what must happen to the partial output O after block 1 when block 2 arrives.
What a strong answer covers
- Block 1: m₁ = 3, ℓ₁ = e^(1−3) + e^0 = 0.1353 + 1 = 1.1353. Block 2: m₂ = 5, ℓ₂ = e^(2−5) + e^0 = 0.0498 + 1 = 1.0498.
- Merge: m = max(3, 5) = 5 and ℓ = e^(3−5)·1.1353 + e^(5−5)·1.0498 = 0.1536 + 1.0498 = 1.2034.
- Direct: e^(1−5) + e^(3−5) + e^(2−5) + e^0 = 0.0183 + 0.1353 + 0.0498 + 1 = 1.2034. They match, so the blocked computation is exact, not an approximation.
- O after block 1 was built with weights e^(x − 3)/ℓ₁. It must be multiplied by ℓ₁·e^(m₁ − m)/ℓ, and the new block adds e^(x − m)·V/ℓ. This is the diag(ℓ_new)⁻¹ rescaling line of Algorithm 1.
- Only m and ℓ (two numbers per row) and O (d numbers per row) have to persist across blocks, which is why the full row of scores never needs to exist.
- Derive / compute
Take N = 4096 tokens, head dimension d = 64 and an SRAM budget of M ≈ 10⁵ elements. Use Theorem 2 to estimate HBM accesses for standard attention and for FlashAttention, ignoring constants. What is the ratio, how does it change at d = 128, and what block sizes does Algorithm 1 pick?
What a strong answer covers
- Standard: Nd + N² = 262,144 + 16,777,216 ≈ 17.0M elements, dominated by writing and reading S and P.
- FlashAttention: N²d²/M = 16.78M × 4096 / 10⁵ ≈ 0.69M. The ratio is about 25, roughly M/d² when N ≫ d.
- At d = 128: N²d²/M ≈ 2.75M, so the ratio falls to about 6. Bigger heads leave less room per tile and cost more passes.
- B_c = ⌈M/4d⌉ = ⌈10⁵/256⌉ = 391 and B_r = min(391, d) = 64. The outer loop has T_c = ⌈N/B_c⌉ = 11 key/value blocks, and each re-reads Q and re-writes O, which is where the N²d²/M term comes from (≈ T_c·Nd).
- Caveat: these are asymptotic counts with constants dropped. The paper's measured GPT-2 medium case (N = 1024, d = 64) shows 40.3 GB against 4.4 GB of traffic, about 9×.
- Mechanism
FlashAttention performs more FLOPs than standard attention (75.2 against 66.6 GFLOPs in Fig. 2) yet runs 5.7× faster on the same A100. Explain why, and explain what the backward pass recomputes and why that is cheaper than storing the attention matrix.
What a strong answer covers
- Attention is memory-bound. Softmax, masking and dropout are elementwise and spend their time moving S and P (N² each) through HBM at ~1.5–2 TB/s, while the matmul units sit idle.
- FlashAttention fuses matmul, softmax, mask, dropout and the second matmul into one kernel, so S and P live only in SRAM (~19 TB/s) and the HBM traffic drops from 40.3 GB to 4.4 GB.
- The backward pass needs P to form dS and dV. Instead of storing P (N² per head), it keeps O and the per-row statistics m and ℓ (O(N)) and recomputes S and P tile by tile from Q, K, V in SRAM.
- Recomputation adds FLOPs, which is the gap from 66.6 to 75.2 GFLOPs. Those FLOPs are cheap compared to N² reads from HBM, so runtime falls from 41.7 ms to 7.3 ms.
- Memory becomes linear in N, which is what lets the same GPU train with 4K–64K contexts.
- What if…
Fig. 2 (middle) varies the key block size B_c. Predict the shape of runtime against B_c, explain both regimes with the IO analysis, and say why you cannot simply pick the largest block.
What a strong answer covers
- HBM accesses scale with the number of passes over Q and O, which is N/B_c. Larger B_c means fewer passes and less traffic, so runtime drops at first.
- The paper reports that beyond about 256 the curve flattens: the kernel is then limited by arithmetic and other overheads, not by HBM.
- B_c is capped by SRAM: K_j, V_j, Q_i, O_i and the tile S_ij must all fit, which is why Algorithm 1 sets B_c = ⌈M/4d⌉.
- This matches Proposition 3: no exact algorithm beats N²d²/M for every M, so once IO is near that bound the remaining gains must come from compute efficiency (the target of FlashAttention-2).
- Design
You want to fine-tune a listwise LLM reranker that reads a query plus 50 passages of about 300 tokens each (≈16K tokens) on four 80 GB A100s. Explain what FlashAttention changes in the memory budget for training, what it does not change, and what you would measure before committing.
What a strong answer covers
- Without fused attention, each layer and head stores an N×N score matrix for backward. At N = 16K that is 268M entries per head, or 512 MiB in bf16, before multiplying by heads and layers. This is the term FlashAttention removes.
- With FlashAttention, attention memory is O(N) per head (O plus m and ℓ), so activations are dominated by the linear-layer and MLP activations, which still grow linearly with N.
- It does not change the O(N²d) FLOPs. Training time per example still grows quadratically, so the passage count and length set the compute bill.
- It does not shrink weights or optimizer state. LoRA or QLoRA and activation checkpointing are still needed on this budget.
- Measure tokens per second and peak memory at 4K, 8K and 16K; check that the head dimension is supported by the kernel; and compare quality against a shorter-context pointwise reranker to see if the long input pays off.
- Connect
FlashAttention speeds up training and prefill. Explain why it does much less for token-by-token decoding of a long RAG prompt, and which later ideas on this site attack the decoding bottleneck instead.
What a strong answer covers
- In decoding, each step has one query row against N cached keys. There is no N×N matrix to avoid; the cost is reading the whole KV cache from HBM once per token.
- That read is set by KV-cache size (layers × KV heads × d × N), so GQA and MQA shrink it by cutting KV heads.
- PagedAttention (vLLM) makes the cache fit more sequences per GPU by removing fragmentation, which raises batch size and throughput.
- Speculative decoding amortises each full-model pass over several tokens, so the cache is read fewer times per accepted token.
- FlashAttention still matters for the prefill of the long prompt, which is compute-heavy and benefits from the tiled kernel.