All courses

FlashAttention: tiling and online softmax

Compute exact attention block by block in fast on-chip memory, using a running max and running sum for the softmax. Explain why it is faster despite the same FLOPs: it never writes the T×T matrix to slow memory.

Builds on: Quadratic cost of attention in context length, Roofline model: compute- vs memory-bound

▶ Watch this lesson Start the whole course

What the animation says

The T×T bottleneck

Standard attention scores every query against every key: a T by T grid. That grid is written to the GPU's big, slow memory, read back for softmax, written again, then read once more. At about eight thousand tokens, that's sixty-seven million numbers per head, every pass. Softmax does only a few operations per byte it moves, so the GPU mostly waits on memory. And softmax needs each row's max and sum before it can finish. So: can exact attention skip storing the grid?

Tiles and running stats

Yes, exactly. Compute one score tile at a time in fast on-chip memory, use it, then discard it. Each query row keeps a running max, a running sum of exponentials, and an unnormalized output. Block one: scores one and three, values ten and twenty. Max: three. Weights, e to score minus max, are point one three five and one. Sum: one point one three five. Output: twenty-one point three five. Block two brings scores two and five. The max jumps to five. What about the old sum?

Rescale, add, divide

Rescale. The old terms were measured against max three, but now the max is five. So multiply the old sum and the old output by e to the three minus five: point one three five. New sum: the shrunk old sum, plus e to the minus three, plus one. That's one point two oh three four. New output: the shrunk old output, plus the new weighted values. Forty-four point three eight. Divide at the end: thirty-six point eight eight. Full softmax over all four scores gives the same number.

Find the bug

Here's the loop in code: one query row, keys in blocks of two. This line finds the new max. This one computes the correction factor c. This line turns the block's scores into weights against the new max. Someone wrote this version, and its result doesn't match ordinary attention. Tap the two lines that break it.

Exact and fast

The fix: multiply the old sum and output by c. Now the check against ordinary attention prints True. The arithmetic is unchanged: the same matrix multiplies as standard attention. But score tiles live only in on-chip memory. Only Q, K, V, the output, and each row's max and sum reach slow memory. Each loaded key-value tile serves a whole block of queries, so work per byte grows with the query block size. With a causal mask, tiles fully above the diagonal are skipped. Extra memory grows with T, not T squared.

Can exact attention skip the T×T matrix?

Standard attention writes the scores $S=QK^\top/\sqrt{d_{head}}$ ($T\times T$) to the GPU's large, slow HBM. It reads them back for softmax, writes $A$, then reads $A$ again to form $AV$. At $T=8192$ that is 67M numbers per head per pass. The softmax pass does only a few FLOPs per byte moved, so it is deeply memory-bound. But softmax needs each row's max and sum first. Can we skip storing the matrix and still get the exact answer?

Tiles in fast memory, statistics on the fly

Load a block of $B_r$ query rows and a block of $B_c$ keys and values into the small on-chip SRAM. Compute that score tile, use it, then discard it. For each query row keep three running quantities: the max $m$, the sum of exponentials $\ell$, and the unnormalized output $o$. When a new block raises the max, shrink the old $\ell$ and $o$ by $e^{m_{old}-m_{new}}$. Divide by $\ell$ at the end. The result is exact, not approximate.

The online-softmax update

For one query row $q$, start with $m=-\infty$, $\ell=0$, $o=0\in\mathbb R^{d_{head}}$. For each key block $j$, with scores $s=qK_j^\top/\sqrt{d_{head}}+M_j$: $$m'=\max(m,\max_i s_i),\quad c=e^{m-m'}$$ $$\ell'=c\,\ell+\textstyle\sum_i e^{s_i-m'}$$ $$o'=c\,o+e^{s-m'}V_j$$ The final output is $o/\ell$. Here $e^{s-m'}$ is a row of weights and $V_j$ holds the block's value rows. Tiles entirely above the causal diagonal are skipped.

Two key blocks, one query row

Scores $[1,3]\,|\,[2,5]$, values $[10,20]\,|\,[30,40]$. Block 1: $m=3$, $\ell=e^{-2}+1=1.1353$, $o=0.1353\cdot10+20=21.353$. Block 2: $m'=5$, $c=e^{-2}=0.1353$. $\ell'=0.1353\cdot1.1353+e^{-3}+e^{0}=1.2034$ $o'=0.1353\cdot21.353+0.0498\cdot30+40=44.383$ Output: $44.383/1.2034=36.88$. This equals softmax over all four scores at once.

Blockwise attention matches the full softmax

One query row, keys processed in blocks of 2, checked against ordinary attention.
import numpy as np
T, dh, Bc = 8, 4, 2
rng = np.random.default_rng(0)
q, K, V = rng.normal(size=dh), rng.normal(size=(T, dh)), rng.normal(size=(T, dh))
m, l, o = -np.inf, 0.0, np.zeros(dh)
for j in range(0, T, Bc):
    s = K[j:j+Bc] @ q / np.sqrt(dh)
    m_new = max(m, s.max()); c = np.exp(m - m_new)
    p = np.exp(s - m_new)
    l, o, m = c*l + p.sum(), c*o + p @ V[j:j+Bc], m_new
w = np.exp(K @ q / np.sqrt(dh)); ref = w @ V / w.sum()
print(np.allclose(o / l, ref))

Same FLOPs, far less memory traffic

FlashAttention does the same matmul FLOPs as standard attention. Every tile of the $T\times T$ scores and weights lives only in SRAM. Only $Q,K,V$, the output and (for training) the per-row $m,\ell$ touch HBM. Each loaded $K/V$ tile serves $B_r$ queries: $4B_rB_cd_{head}$ FLOPs for $4B_cd_{head}$ bytes, so about $B_r$ FLOPs/byte. Standard attention's softmax passes over the $T\times T$ matrix manage only a few. A running max and sum keep the softmax exact. Extra memory is $O(T)$, not $O(T^2)$.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.