Skip to content

FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness

Skip →GQA (and MQA)
main track #7corefundamentalpaperrubric 11/122022 · ~50 min

Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré

Status

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.

For one row of scores split into blocks, keep only the running maximum and normaliser. Merging two blocks with statistics (m1,ℓ1)(m_1,\ell_1) and (m2,ℓ2)(m_2,\ell_2) gives

m=max⁡(m1,m2),ℓ=em1−m ℓ1+em2−m ℓ2,m = \max(m_1, m_2), \qquad \ell = e^{m_1 - m}\,\ell_1 + e^{m_2 - m}\,\ell_2 ,

and the partial output is rescaled the same way:

Oi←diag⁡(ℓinew)−1(diag⁡(ℓi) emi−minew Oi+em~ij−minew P~ijVj).O_i \leftarrow \operatorname{diag}(\ell_i^{\text{new}})^{-1}\Big(\operatorname{diag}(\ell_i)\,e^{m_i - m_i^{\text{new}}}\,O_i + e^{\tilde m_{ij} - m_i^{\text{new}}}\,\tilde P_{ij} V_j\Big).

Algorithm 1 loops over key/value blocks Kj,VjK_j, V_j (outer) and query blocks QiQ_i (inner), with Bc=⌈M/4d⌉B_c = \lceil M/4d \rceil and Br=min⁡(⌈M/4d⌉,d)B_r = \min(\lceil M/4d\rceil, d) for SRAM size MM. Theorem 2 counts HBM accesses:

standard: Θ(Nd+N2)FlashAttention: Θ ⁣(N2d2M).\text{standard: } \Theta(Nd + N^2) \qquad \text{FlashAttention: } \Theta\!\left(\frac{N^2 d^2}{M}\right).

Proposition 3 shows that no exact algorithm can do asymptotically better for all M∈[d,Nd]M \in [d, Nd].

FlashAttention: tile Q, K, V into on-chip SRAM and keep a running softmax Left: the GPU memory hierarchy. HBM is large but slow; on-chip SRAM is tiny but about ten times faster. Middle: the N by N score matrix is never written to HBM. It is processed tile by tile: the outer loop loads a block of keys and values, the inner loop streams blocks of queries, and each tile is computed in SRAM. Right: each query row block keeps only a running maximum m, a running normaliser l and an unnormalised output O; when a new tile arrives the old statistics are rescaled by exp(m_old minus m_new). Bottom: standard attention reads and writes Theta of N d plus N squared elements of HBM; FlashAttention reads and writes Theta of N squared d squared over M. Memory hierarchy (A100) SRAM (on chip) 192 KB × 108 SMs ~19 TB/s slow link HBM (off chip) 40–80 GB 1.5–2.0 TB/s Attention is memory-bound: the cost is moving S and P, not the FLOPs. Tile S = QKᵀ, never store it K_j, V_j (outer) → Q_i ↓ column j loaded once; Q_i blocks stream through; one tile (S_ij) lives in SRAM at a time Online softmax per row state kept for row block i: mᵢ running max ℓᵢ running Σ exp(s − mᵢ) Oᵢ running output new tile with max m̃: m_new = max(mᵢ, m̃) ℓ_new = e^(mᵢ−m_new)·ℓᵢ + e^(m̃−m_new)·ℓ̃ O rescaled the same way Backward: keep O, m, ℓ only; recompute S, P tile by tile. HBM traffic standard: Θ(Nd + N²) — writes S and P out FlashAttention: Θ(N²d²/M) — ratio ≈ M/d² when N ≫ d (not to scale; M = SRAM size)
Original sketch. Tiles of the score matrix live only in SRAM; each query row block carries m, ℓ and O between tiles. HBM traffic falls from Θ(Nd + N²) to Θ(N²d²/M).
  • 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).
  • 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.

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.

  1. 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.
  2. 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×.
  3. 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.
  4. 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).
  5. 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.
  6. 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.

Done with this page?

Status