668. 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.
def flash_attention(Q, K, V, block)Example 1
Input: flash_attention([[1.0], [1.0], [1.0]], [[0.0], [0.0], [0.0]], [[1.0], [2.0], [3.0]], 2)
Output: ([[1.0], [1.5], [2.0]], [0.0, 0.6931, 1.0986], 3)
Constraints
Vhas shape(T, d)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Initialise m to -inf, l and O to zero per query block.
Hint 2
The first visited block for a row always contains a visible key, so exp(m - m_new) is safe.
Hint 3
Count tiles inside the inner loop.
Common mistakes
- The buggy version rescales l but not O.
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).
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.
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.
Topics
Companies2
- Meta the topic appears in interview reports Machine Learning interview questions, page 10 (KatKat)
- NVIDIA the topic appears in interview reports NVIDIA Interview Prep: Questions, Process & Study Plan
From public interview reports and guides. Not affiliated with or endorsed by these companies.