Foundations to Frontier
Tests
E. Deep Learning › E12 Transformer Architectures

FlashAttention

FlashAttention (Dao, Fu, Ermon, Rudra and Ré, NeurIPS 2022) computes exact attention faster and with linear memory by being IO-aware. Standard attention writes the N × N score and probability matrices to slow GPU memory (HBM) and reads them back. FlashAttention tiles queries, keys and values into blocks that fit in fast on-chip SRAM, uses an online softmax to combine blocks exactly, and recomputes what it needs in the backward pass. It sped up GPT-2 training about 3× and enabled much longer contexts, and successors (FlashAttention-2 and -3) are now the default attention kernels. This page covers the GPU memory hierarchy, tiling, the online softmax and the IO analysis. In the exercises you implement the online softmax and block merging, then a full tiled attention that matches standard attention to 10⁻¹⁵. Its memory-traffic model shows 8–12× fewer HBM accesses at head size 64, and about 3× at 128.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Same answer, less shuffling of data

A GPU has a small, very fast scratchpad next to its compute units and a large, slower main memory. Ordinary attention computes a giant table of scores, writes it to the slow memory, reads it back for the softmax, writes again, reads again. That shuffling, not the arithmetic, takes most of the time. FlashAttention works on small tiles that fit in the fast scratchpad and combines them cleverly so the giant table never exists. The result is exactly the same, faster and with far less memory. The demo shows how the full table grows with length.

Transformer lab
Full attention stores 16,777,216 scores per head; a linear-time method with 64 features stores 262,144, 64 times fewer.
Why engineers care

On real hardware, moving data often costs more than computing. Designing algorithms around the memory hierarchy is how FlashAttention made long-context models practical.

📝 Quick check (Level 0)
0/3 answered
  1. 1. FlashAttention's result compared with standard attention:
  2. 2. Its speed comes from reducing…
  3. 3. FlashAttention never stores…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Memory hierarchy: an A100 has about 40–80 GB of HBM at about 1.5–2 TB/s, and about 20 MB of SRAM (192 KB per streaming multiprocessor) at about 19 TB/s.
  • Standard attention traffic:
    • write S = QKᵀ (N²), read S and write P = softmax(S) (2N²), read P and V and write O;
    • about 4N² + 4Nd elements, 68 M for N = 4096 and d = 64;
    • one N × N matrix per head at 16 K tokens and 16 heads takes 8 GiB in 16-bit.
  • Online softmax:
    • process scores in blocks, keeping a running maximum m and normaliser l;
    • when a new block raises the maximum to m′, rescale: l ← e^(m − m′)·l + Σ e^(s − m′), and the same for the partial output;
    • this gives the exact softmax.
  • Tiling (Algorithm 1):
    • key/value blocks of Bc = ⌈M/(4d)⌉ fit in SRAM of M elements: 391 for M = 100,000 and d = 64;
    • K and V are read once;
    • Q, O, l and m are reread for each of Tc = ⌈N/Bc⌉ outer blocks;
    • HBM traffic is Θ(N²d²/M) against Θ(N² + Nd).
  • Backward pass: store only O and the statistics (m, l), and recompute S and P blockwise. This means more FLOPs but less traffic.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Standard attention HBM elements for N = 4096, d = 64:
  2. 2. Block size Bc for M = 100,000, d = 64:
  3. 3. The online softmax keeps…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

FlashAttention in code

Exercise 1.

  • Running max and sum gave the exact normaliser.
  • Two partial blocks merged into exactly the full softmax output.
  • The block-size formula gave 391.

Practice.

  • In PyTorch, F.scaled_dot_product_attention dispatches to FlashAttention kernels on supported GPUs and data types (fp16/bf16). The flash-attn package provides them directly.
  • Benefits:
    • memory linear in N lets training reach contexts of 16 K–64 K and more;
    • speed is best when attention is memory-bound (long sequences, small head sizes).
  • FlashAttention-2 improved parallelism and work partitioning (about 2× faster). FlashAttention-3 uses Hopper GPUs’ asynchronous features and low precision.
  • Causal masks and dropout are fused into the kernel.
import torch.nn.functional as F
q, k, v = (t.half().cuda() for t in (q, k, v))            # (B, heads, N, d)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)   # uses a FlashAttention kernel when available
🐍 Exercise 1: the online softmax
Implement running softmax statistics, merging of partial blocks and the SRAM block size.
📝 Quick check (Level 2)
0/3 answered
  1. 1. PyTorch's entry point that may use FlashAttention:
  2. 2. FlashAttention kernels need data types…
  3. 3. FlashAttention-2 mainly improved…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why exactness is possible.

  • Softmax normalisation needs the maximum and the sum over a whole row, which seems to require all scores at once.
  • But both can be accumulated: when a later block has a larger maximum, multiply the earlier partial sums and outputs by e^(m_old − m_new).
  • Blocks can be processed in any order and merged associatively, so the final result equals the full softmax up to floating-point rounding.

IO complexity.

  • Dao et al. prove FlashAttention needs Θ(N²d²M⁻¹) HBM accesses, and that no exact attention algorithm can do asymptotically better over all SRAM sizes.
  • For typical d (64–128) and M (around 100 K elements), d²/M is much less than 1, so traffic drops several-fold.
  • The saving shrinks as d grows, since d² increases. Exercise 2 shows 8–12× at d = 64 but about 3× at d = 128.

Compute versus memory. Modern GPUs perform hundreds of FLOPs in the time it takes to move one number from HBM. Operations such as softmax and dropout are memory-bound, so removing traffic, even at the cost of recomputation, makes them faster.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Online softmax merges blocks by…
  2. 2. FlashAttention's HBM accesses:
  3. 3. Savings shrink when head size d…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much memory traffic does tiling save?

History.

  • T. Dao, D. Fu, S. Ermon, A. Rudra and C. Ré, “FlashAttention: fast and memory-efficient exact attention with IO-awareness” (NeurIPS 2022).
  • The online softmax trick comes from Milakov and Gimelshein (2018), and memory-efficient attention from Rabe and Staats (2021).
  • FlashAttention-2 followed in 2023 and FlashAttention-3 in 2024.

Exercise 2.

  • (a) Exactness: tiled attention with the online softmax (blocks of 16 and 64) compared with standard attention on 256 tokens.
  • (b) Memory traffic: the HBM elements moved by each algorithm, following the paper’s Algorithm 1 with SRAM of M = 100,000 elements.

(a) Maximum difference from standard attention: 6 × 10⁻¹⁶ (block 16, 256 tiles) and 7 × 10⁻¹⁶ (block 64, 16 tiles). The result is exact to floating-point precision.

(b) HBM elements moved:

tokens N head size d standard FlashAttention ratio
1024 64 4.46 × 10⁶ 5.37 × 10⁵ 8.3×
4096 64 6.82 × 10⁷ 6.47 × 10⁶ 10.5×
16384 64 1.08 × 10⁹ 9.29 × 10⁷ 11.6×
4096 128 6.92 × 10⁷ 2.34 × 10⁷ 3.0×
  • Tiling is exact, so the saving costs nothing in accuracy.
  • Traffic falls 8–12× at head size 64, consistent with the paper’s report of up to 9× fewer HBM accesses on GPT-2.
  • Larger heads save less (about 3× at d = 128), as the Θ(N²d²/M) bound predicts.
  • Both algorithms still do Θ(N²) work. FlashAttention makes exact attention fast and linear in memory, not linear in compute.
🐍 Exercise 2 (research): how much memory traffic does tiling save?
Implement tiled attention with the online softmax, check exactness and compare HBM traffic using the paper's IO model.

FlashAttention in AI, robotics and aerospace

  • On-board inference: IO-aware kernels matter even more on embedded GPUs with limited memory bandwidth.
  • Long contexts: exact attention over long logs or sensor histories becomes feasible without approximation.
  • General lesson: count memory traffic, not just FLOPs, when optimising any numerical kernel.

References

  1. T. Dao, D. Y. Fu, S. Ermon, A. Rudra, C. Ré (2022). “FlashAttention: fast and memory-efficient exact attention with IO-awareness.” Proc. NeurIPS.
  2. T. Dao (2023). “FlashAttention-2: faster attention with better parallelism and work partitioning.” arXiv:2307.08691.
  3. M. Milakov, N. Gimelshein (2018). “Online normalizer calculation for softmax.” arXiv:1805.02867.