Pidoku

FlashAttention (2022)

Module 30 Lesson 30.f 40 min Difficulty 3/5

Prerequisites 4.d, 10.g, 11.f, 30.a


Before you start: words you need#

WordPlain meaning
HBMThe GPU’s large main memory (40–80 GB on an A100), fast by CPU standards but slow next to on-chip memory (4.e).
SRAMThe small on-chip memory inside each streaming multiprocessor (shared memory and registers): about 20 MB in total on an A100, roughly ten times faster than HBM (4.d).
IO-awareDesigning an algorithm around how many bytes it moves between memory levels, not just how many FLOPs it does.
TilingCutting a big matrix into blocks small enough to fit in SRAM and processing one block at a time.
Online softmaxComputing a softmax in pieces, keeping a running maximum and running sum and rescaling earlier partial results when a new maximum appears (10.g).
RecomputationThrowing away an intermediate result and computing it again later when needed, because recomputing is cheaper than storing and re-reading it.
Exact vs approximate attentionExact gives the same answer as the textbook formula (up to rounding). Approximate methods (sparse, low-rank) change the answer to save work.
Fused kernelOne GPU kernel that does several steps without writing intermediate results to HBM (13.j).

1. The paper#

  • Title: “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness”
  • Authors: Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré (Stanford; University at Buffalo)
  • Venue: NeurIPS 2022.
  • Link: arXiv:2205.14135

FlashAttention-2, -3 and -4 are covered in 30.n. The kernel itself is taught in 13.l.


2. The problem#

Standard attention is written as three steps, each a separate GPU kernel:

  1. S = Q·Kᵀ — write an N × N matrix to HBM.
  2. P = softmax(S) — read it, write another N × N matrix.
  3. O = P·V — read it again.

For a 1k–4k sequence these N × N matrices are far bigger than the inputs and outputs. The FLOPs are fine; the memory traffic is the problem, and it grows with N². Memory also limits sequence length: the N × N matrix has to fit.

Many “efficient attention” papers before 2022 cut FLOPs with approximations (sparse patterns, low-rank projections) but did not run faster in wall-clock time, because they ignored memory traffic. The authors’ claim: the missing principle is IO-awareness.


3. The idea#

Never write the N × N matrix to HBM. Load a block of K and V into SRAM, loop over blocks of Q, compute that block’s scores, softmax and weighted values on chip, and accumulate into the output. Two tricks make this exact rather than approximate:

  • Online softmax. Softmax needs the maximum and sum over a whole row, which you do not have when you see one block at a time. Keep a running max and running sum per row, and rescale the partial output whenever the max changes. The final result is identical to the full softmax.
  • Recompute in the backward pass. Training needs P for gradients. Instead of storing it, store only the per-row max and sum (O(N) numbers) and recompute P block by block during backward. More FLOPs, far fewer bytes, faster overall.

All of it is one fused CUDA kernel.

flowchart LR
  subgraph HBM["HBM (slow, large)"]
    Q["Q"]
    K["K, V"]
    O["O + row max/sum"]
  end
  subgraph SRAM["SRAM (fast, small)"]
    T["Block of Q, block of K/V: scores, online softmax, accumulate"]
  end
  K -- "load block" --> T
  Q -- "load block" --> T
  T -- "write once" --> O
  class Q,K,O memory
  class T compute

4. How it works#

The paper’s Algorithm 1, in words:

  1. Choose block sizes so that one block of Q, K, V and the output fits in SRAM (they depend on the SRAM size M and head dimension d).
  2. Outer loop over blocks of K and V: load one block into SRAM.
  3. Inner loop over blocks of Q: load the Q block and its current output, running max and running sum; compute scores for this Q block against this K block; update the running statistics; rescale and add to the output; write the output back.
  4. Causal masking and dropout are applied inside the kernel, on the block.

The IO analysis (Theorem 2) is the paper’s core claim:

HBM accesses
Standard attentionΘ(N·d + N²)
FlashAttentionΘ(N²·d²/M)

With head dimension d of 64–128 and M of about 100 KB per SM, d²/M is much less than 1, so FlashAttention moves many times fewer bytes. The authors also prove a lower bound: no exact attention algorithm can do asymptotically better over all SRAM sizes.

The same blocking extends to block-sparse attention: skip blocks that are masked out, and the speed-up is proportional to the sparsity.

Note what it does not change: attention still does O(N²) FLOPs. FlashAttention makes attention compute-bound instead of memory-bound; it does not make it linear. (In the paper’s FlashAttention-1 loop order, the outer loop is over K/V; FlashAttention-2 swapped it, 30.n.)


5. Results#

All on NVIDIA A100 GPUs, numbers from the abstract, Figure 2 and section 4:

MeasureStandard attentionFlashAttention
GPT-2 medium attention, forward + backward (N = 1024, d = 64, 16 heads, batch 64): GFLOPs66.675.2
Same, HBM reads and writes40.3 GB4.4 GB
Same, runtime41.7 ms7.3 ms

It does more FLOPs (recomputation) and is still 5.7× faster, because it moves 9× fewer bytes.

End-to-end trainingSpeed-up
BERT-large, N = 512, vs the MLPerf 1.1 training record15% faster
GPT-2, N = 1k, vs Hugging Face and Megatron-LMup to 3× (vs Hugging Face); 1.7× vs Megatron-LM
Long Range Arena, N = 1k–4k2.4×
Attention alone on GPT-2 (Figure 1)7.6×

Memory grows linearly with N and was up to 20× smaller than exact-attention baselines. Longer context became affordable: GPT-2 with 4× longer context (4k) still trained 30% faster than Megatron’s 1k version and reached 0.7 better perplexity, and it was the first Transformer to beat chance on Path-X (16k tokens, 61.4%) and Path-256 (64k tokens, 63.1%).


6. What held up and what did not#

Held up

  • IO-awareness as the way to judge kernels. It is now the default lens (30.a), and the reason approximate attention mostly lost to exact attention done well.
  • Online softmax + tiling + one fused kernel. Every production attention kernel in 2026 uses it: FlashAttention-2/3/4, FlashInfer (30.x), cuDNN attention, TensorRT-LLM’s kernels, FlashMLA.
  • Recomputation beats storage for training memory — a principle that spread well beyond attention (activation checkpointing in general).

Did not, or needed more

  • Decode was not its target. With one query token per sequence, the inner loop has almost no work and the GPU sits idle. Flash-Decoding (Dao et al., October 2023) split the KV sequence across thread blocks and combined the partial softmaxes, the “split-KV” idea every decode kernel now uses.
  • Utilisation was modest. FlashAttention-1 reached about 25–40% of A100 peak; FlashAttention-2 roughly doubled that by reworking parallelism and loop order (30.n).
  • Paged KV caches (30.o) needed kernels that read K and V from scattered blocks; the original kernel assumed contiguous tensors.
  • New hardware (Hopper TMA and WGMMA, Blackwell tcgen05 and TMEM) needed redesigned kernels (FlashAttention-3 and -4, 30.n).

7. Where it lives in 2026#

  • Taught in depth: the algorithm in 13.l, attention kernels in 25.f, vLLM’s attention backends in 18.c.
  • The flash-attn package (Dao-AILab) ships FlashAttention-2 and -3, and FlashAttention-4 in its CuTe DSL form for Blackwell; PyTorch’s scaled_dot_product_attention calls a FlashAttention-style kernel by default on supported GPUs.
  • vLLM v0.32.0 defaults to its FlashAttention build (version 2, 3 or 4 chosen per GPU) on Ampere, Hopper and Blackwell workstation GPUs, and to FlashInfer on Blackwell data-centre GPUs (18.c).

Checked on 13 November 2026.


8. Questions#

  1. Standard attention and FlashAttention compute the same result. Where does the speed come from?
  2. Explain online softmax. What two numbers per row are kept, and why must earlier outputs be rescaled?
  3. FlashAttention does more FLOPs than standard attention in training. Why is it faster anyway?
  4. Write the HBM-access complexity of both methods. When does FlashAttention’s advantage shrink?
  5. Is attention still O(N²) after FlashAttention? In what?
  6. Why did FlashAttention-1 do poorly on decode, and what fixed it?
  7. Why did most approximate-attention methods of 2020–21 fail to speed up real training?

9. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in