FlashAttention-style tiled causal attention forward (Dao et al., 2022)

FlashAttention (Dao et al., 2022) never builds the full T x T score matrix. It walks over blocks of keys and values, keeps a running row max m, a running sum l and an unnormalized output, and rescales them whenever a new block raises the max. With a causal mask whole blocks above the diagonal can be skipped. Simulated in NumPy here.

Write flash_attention(Q, K, V, block). Q, K, V have shape (T, d). Attention is causal (key j visible to query i only if j <= i) with scale 1 / sqrt(d).
- Split rows into blocks of size block (the last may be shorter). For each query block, loop over key blocks in order, and SKIP any key block whose first index is greater than the query block's last index.
- For each visited pair: s = Qb Kb^T / sqrt(d) with masked entries set to -inf, m_new = max(m, row max of s), p = exp(s - m_new), l = l * exp(m - m_new) + row sum of p, O = O * exp(m - m_new) + p @ Vb, m = m_new.
- After the last key block, out = O / l and lse = m + log(l).
Return (out, lse, tiles): out (T, d), lse (T,), tiles = number of (query block, key block) pairs actually visited.

Signaturedef flash_attention(Q, K, V, block)

Understand the idea

FlashAttention never builds the full score matrix; it walks over key blocks, keeping for each query row a running max m, a running sum l and an unnormalised output O. When a new block brings a bigger max, both l and O were computed against the old max and must be scaled by exp(m_old - m_new). Example: one query, scores 1 and 3, block size 1. Block 1: m = 1, p = 1, l = 1, O = v0. Block 2: m_new = 3, factor exp(1 - 3) = 0.1353, l = 0.1353 + 1 = 1.1353, O = 0.1353 * v0 + v1. out = O / l gives weights 0.1192 and 0.8808, exactly the softmax of [1, 3]. lse = 3 + ln 1.1353 = 3.1269. With T = 4, block 2, causal, only 3 tiles are visited. Rule: per tile s = Qb Kb^T / sqrt(d) with future entries set to -inf; update m, l, O as above; skip key blocks that start after the query block ends; finally out = O / l, lse = m + log l. Used in nearly every modern LLM stack.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: 7 tokens, block 2flash_attention(_Q, _K, _V, 2)
  • Sample 2: block 3, uneven last blockflash_attention(_Q, _K, _V, 3)