10.5 — FlashAttention: I/O-aware attention
Goal: Derive the FlashAttention algorithm: a tiled, online-softmax formulation of exact attention that avoids materialising the $n \times n$ score matrix. Understand the GPU memory hierarchy (HBM vs SRAM), the I/O complexity argument, and the empirical $2$–$4\times$ wall-clock speedup with $O(n)$ SRAM.
1. Why this session exists
Standard scaled dot-product attention (6.2) for sequence length , head dimension :
The textbook implementation materialises the score matrix and the softmax-normalised matrix in GPU memory.
Two problems:
- Memory. floats. At , is M entries — MB in fp16 per head per layer. With heads × layers × batch , the attention matrices alone occupy GB. Larger than any single GPU.
- Memory bandwidth. Even when fits, writing it to HBM and reading it back is the dominant cost. The actual matmul FLOPs are fast; moving through the GPU's TB/s HBM bandwidth is the wall.
FlashAttention (Dao et al., 2022, arXiv:2205.14135[1]; FlashAttention-2: Dao, 2023, arXiv:2307.08691; FlashAttention-3: Shah et al., 2024, arXiv:2407.08608) reformulates the attention computation to never materialise or in HBM. Instead, it tiles the computation in on-chip SRAM, using an online softmax that updates a running maximum and sum as it streams through key/value blocks.
The result: exact attention (same numerical output as the standard implementation, up to rounding), HBM memory, and – wall-clock speedup on H100 / A100. By 2026, every production inference and training stack uses FlashAttention as the default attention kernel.
2. The GPU memory hierarchy
The cost model. An NVIDIA A100 SXM has roughly:
| Level | Size | Bandwidth | |---|---|---| | Registers | per-thread | — | | SRAM (shared memory + L1) | KB per SM × 108 SMs = MB | TB/s aggregate | | L2 cache | MB | TB/s | | HBM (GPU global memory) | GB | TB/s |
H100 is similar, with KB SRAM per SM, MB L2, GB HBM, and TB/s HBM bandwidth.
The hierarchy is steeper than CPUs: SRAM is faster than HBM but smaller. Any algorithm that fits its working set in SRAM runs roughly an order of magnitude faster than one that bounces through HBM.
Standard attention fits its working set in HBM: it has to, because doesn't fit in SRAM for any non-trivial .
FlashAttention's bet: tile the computation so each tile's working set fits in SRAM, and stream the inputs/outputs from/to HBM only at tile boundaries. The tile loads cost something — but at most total HBM I/O per attention head, instead of .
3. Online softmax
The mathematical core of FlashAttention is online softmax — computing in a streaming fashion, processing one block at a time.
3.1 The numerically stable softmax
The standard numerically stable computation:
Subtracting avoids overflow in the exponentials. Two passes over : one to find , one to compute and .
3.2 The online (one-pass) form
Suppose we receive in blocks . Maintain a running max and running normaliser :
The update rule: when the max grows from to , the old normaliser must be rescaled by — because all earlier exponentials were computed with the smaller max as the reference.
After processing all blocks, is the true max and is . One pass; same answer as the two-pass form.
3.3 Online softmax for the attention output
In attention, we don't actually need as an explicit matrix — we need . So we extend the online softmax to also update a running output:
After all blocks, .
The rescaling factor accumulates the correction every time a block raises the max. This is the trick that makes FlashAttention work: streaming attention output, no intermediate score matrix.
4. FlashAttention: the algorithm
Tile into row-blocks of size : with . Tile into row-blocks of size : and .
Block sizes are chosen so that one block plus one block plus one block fits in SRAM: , where is the SRAM budget per program. Typical or on A100.
FlashAttention(Q, K, V):
initialize O, ℓ, m in HBM
for j = 1, ..., T_c: # outer loop over KV blocks
load K^{(j)}, V^{(j)} to SRAM
for i = 1, ..., T_r: # inner loop over Q blocks
load Q^{(i)} to SRAM
load O^{(i)}, ℓ^{(i)}, m^{(i)} (the running stats for Q block i)
compute S^{(i,j)} = Q^{(i)} K^{(j)⊤} / √d in SRAM
apply causal mask if applicable
m_new = max(m^{(i)}, rowmax(S^{(i,j)}))
P̃ = exp(S^{(i,j)} - m_new)
ℓ_new = exp(m^{(i)} - m_new) ℓ^{(i)} + rowsum(P̃)
O_new = (exp(m^{(i)} - m_new) ℓ^{(i)} / ℓ_new) * O^{(i)} + (1/ℓ_new) * P̃ V^{(j)}
write back O^{(i)} = O_new, ℓ^{(i)} = ℓ_new, m^{(i)} = m_new
return O
Note: the outer loop is over blocks; the inner loop is over blocks. (FlashAttention-2 reverses this — see §6.) Each output block is updated times (once per block).
4.1 I/O complexity
How many HBM bytes are read/written?
- loaded once per block: bytes total (each is , summed over gives ; that's per outer iter; outer iters).
- loaded once each: bytes.
- loaded and written times: bytes.
Total HBM I/O: .
Compare to standard attention, which reads/writes bytes for the score matrix and for , , , — total .
For and , FlashAttention's I/O is roughly smaller than standard. That's the lower bound. The actual speedup is larger (– measured) because the avoided I/O is the dominant cost — the matmul FLOPs were never the bottleneck.
4.2 SRAM working-set sanity check
One outer-loop iteration loads ( floats) and one inner-loop iteration loads ( floats) and computes and .
Total floats in SRAM: .
For , (typical head dim), fp16 (2 bytes): KB. Fits in an A100 SM's KB SRAM. Tuning is the hot loop of any FlashAttention implementation.
5. Backward pass
Training needs gradients. Backprop through standard attention is straightforward but expensive — it requires the full .
FlashAttention's backward pass recomputes and on-the-fly per tile, the same way the forward did, rather than caching them. This is the "recomputation" half of "FlashAttention: tiling + recomputation". The backward needs only from the forward pass (saved per row-block of , total memory), plus themselves.
5.1 Activation memory savings
The activation memory of standard attention training scales as (the full is saved for backprop). FlashAttention drops this to . At long context +, this is the enabling property — long-context training is feasible only because the attention activation memory is .
6. FlashAttention-2 and FlashAttention-3
The original FlashAttention had two known inefficiencies on modern GPUs: low GPU occupancy (one program per attention head, with not enough threads to fill the SM) and non-matmul overhead (rescaling, exp, comparisons).
FlashAttention-2 (Dao, 2023, arXiv:2307.08691)[2] fixes both:
- Loop order swapped — outer over , inner over . Each block now produces its final output before moving on, eliminating the running-update overhead per outer iteration.
- Parallelisation across the sequence dimension as well as batch and heads, to better fill the SM.
- Non-matmul work reduced via algebra.
Result: throughput vs. FlashAttention-1 on A100; – of theoretical peak FLOPs.
FlashAttention-3 (Shah et al., 2024, arXiv:2407.08608)[3] targets H100. Adds asynchronous warp specialisation (some warps load while others compute), low-precision (fp8) intermediates, and fine-grained pipelining of the GEMM and softmax steps. Reaches of H100 peak — roughly TFLOP/s in fp16, PFLOP/s in fp8.
7. FlashAttention at inference
FlashAttention is most commonly thought of as a training speedup, but it matters at inference too — particularly during prefill (10.3 §3), where the model processes a long prompt in one forward.
At prefill, the score matrix is — the problem FlashAttention was designed for. Without FlashAttention, prompt processing for an prompt would materialise M-entry softmax matrices per head per layer; with it, it tiles through SRAM.
At decode, the query is a single token; the score matrix is , not . FlashAttention still wins because the matrix is large () and FlashAttention's I/O-aware reads of the cache are faster than the textbook implementation. FlashDecoding (a variant tuned for decode) reorganises the kernel further for the shape.
8. Variants and what they cover
FlashAttention spawned a family of variants:
- FlashDecoding (Tri Dao et al., 2023): decode-specialised kernel, splits the KV cache across SMs for better parallelism on long-context decode.
- FlashAttention-Causal (early variant, now folded into FA-2): exploits the causal mask to skip half the work.
- PagedAttention (10.8, Kwon et al., vLLM, 2023): combines block-paged KV cache with FlashAttention-style kernel for non-contiguous cache layouts.
- FlexAttention (PyTorch 2.5, 2024): a compiler-style API allowing custom mask functions while inheriting FlashAttention's I/O properties — used for sliding-window, prefix-LM, ALiBi, etc.
By 2026 the abstraction has stabilised: every modern attention kernel is some derivative of FlashAttention's tiling + online-softmax recipe.
9. What we keep going forward
Three things.
- The GPU memory hierarchy is the cost model. HBM is slower than SRAM and larger. Standard attention pays the HBM cost on the score matrix; FlashAttention pays only HBM I/O — I/O-optimal.
- Online softmax + tiling = exact attention without materialising . The running state per -block is updated as blocks stream by. Rescaling factor keeps the running output consistent across blocks.
- Activation memory drops from to . This is what makes long-context training feasible. Backward recomputes tile-by-tile using only the saved .
Cap 10.6 next: quantisation. Reduce the precision of weights and activations from fp16/bf16 to int8 or int4 — cutting memory by – and freeing budget for the KV cache. With FlashAttention handling the kernel side and quantisation handling the storage side, the modern inference stack is ready.
(a) Sketch the GPU memory hierarchy of an A100: SRAM, L2, HBM. State the size and bandwidth of each. Why does this hierarchy favour I/O-aware algorithms?
(b) Write the two-pass numerically stable softmax. Then write the online (one-pass) form, including the rescaling rule when the max changes.
(c) Extend the online softmax to compute in one streaming pass over the blocks of and . Include the rescaling of .
(d) State FlashAttention's HBM I/O complexity. Compare to standard attention. For , , , give the rough ratio.
(e) A team finds their attention kernel hits of theoretical peak FLOPs on H100. Suggest two FlashAttention-3 techniques that could push this towards .
(f) FlashAttention's activation-memory benefit during training: state the activation memory of standard attention vs. FlashAttention. Why does long-context training depend on this?
References
- [1]
Dao, T., Fu, D. Y., Ermon, S., Rudra, A., & Ré, C. (2022). "FlashAttention: Fast and memory-efficient exact attention with IO-awareness". arXiv:2205.14135 — Tiled attention kernel; in-SRAM softmax (7.7 §7.1; full treatment Cap 10.5).
↩ - [2]
Dao, T. (2023). "FlashAttention-2: Faster attention with better parallelism and work partitioning". arXiv:2307.08691 — FlashAttention-2 (10.5).
↩ - [3]
Shah, J., Bikshandi, G., Zhang, Y., et al. (2024). "FlashAttention-3: Fast and accurate attention with asynchrony and low-precision". arXiv:2407.08608 — FlashAttention-3 on H100 (10.5).
↩