reference / flashattention
Next task →
Reference Lessons/FlashAttention: Deriving IO-Aware Exact Atte
gpu infrastructure · research · reference study

FlashAttention: Deriving IO-Aware Exact Attention

Why exact attention is memory-bound, how tiling and online softmax avoid the n×n matrix, and how to verify correctness.
All reference lessons

Compute attention in tiles that fit in SRAM. Keep a running maximum and denominator per row, and rescale previous accumulators when a new tile has a larger maximum. The algebra is unchanged; only the order of operations and memory placement change.

1. Standard attention

S=QK⊤/dS=QK^\top/\sqrt{d}, A=softmax(S)A=\mathrm{softmax}(S), O=AVO=AV. The memory cost is O(n2)O(n^2) for SS and AA.

2. Softmax is stable with a running max

For two blocks with maxima m1,m2m_1,m_2 and unnormalized sums ℓ1,ℓ2\ell_1,\ell_2, the combined maximum is m=max⁡(m1,m2)m=\max(m_1,m_2) and the combined denominator is ℓ=em1−mℓ1+em2−mℓ2\ell=e^{m_1-m}\ell_1+e^{m_2-m}\ell_2.

3. Online accumulator

Maintain OiO_i per row. When a new block arrives, set Oi←Oiemold−mnew+eSblock−mnewVblockO_i \leftarrow O_i e^{m^{old}-m^{new}} + e^{S_{block}-m^{new}}V_{block}, then divide by the final ℓi\ell_i.

4. IO complexity

Let dd be head dimension and MM SRAM size. Standard attention writes O(n2)O(n^2) elements to HBM; tiled attention writes O(n2d2/M)O(n^2 d^2/M) HBM elements, a large reduction when M≫dM\gg d.

5. Exactness

Because only associativity and the max-rescaling identity are used, the output equals standard softmax attention up to floating-point order. Verify against a PyTorch reference with a strict tolerance.

Reference lessons are written for this topic specifically. Generated lessons elsewhere on the platform are labelled with a quality score and review status; do not treat them as equivalent.