Online softmax, the trick inside FlashAttention
This is a NumPy simulation of FlashAttention's math, not a GPU kernel.
FlashAttention never stores the full row of attention scores. It streams over blocks of keys, keeping a running max m, a running normaliser l and a running output o, and rescales them whenever a new block raises the max.
Write online_softmax_weighted_sum(scores, values, block) for scores (n,) and values (n, d). Process them in blocks of `block`. For each block with scores s_b and values v_b:
m_new = max(m, max(s_b))
l = l * exp(m - m_new) + sum(exp(s_b - m_new))
o = o * exp(m - m_new) + exp(s_b - m_new) @ v_b
Start with m = -inf, l = 0, o = 0. Return o / l, which must equal softmax(scores) @ values.
def online_softmax_weighted_sum(scores, values, block)Understand the idea
Online softmax computes softmax(scores) @ values while streaming over blocks, never holding the full row of scores. It keeps a running max m, a running sum of exponentials l and a running weighted output o. When a new block has a bigger max, everything collected so far was computed relative to the old max, so it is multiplied by exp(old m - new m) to rescale. Worked example: scores [1, 3], values [[10], [20]], block 1. Start m = -inf, l = 0, o = 0. Block 1: m = 1, l = exp(0) = 1, o = 1 x 10 = 10. Block 2: new m = 3, factor exp(1 - 3) = 0.135. l = 1 x 0.135 + exp(0) = 1.135. o = 10 x 0.135 + 1 x 20 = 21.35. Answer o / l = 18.81. Direct softmax of [1, 3] is [0.119, 0.881], giving 1.19 + 17.62 = 18.81, the same. Rule: m_new = max(m, max s_b); l = l e^(m - m_new) + sum e^(s_b - m_new); o = o e^(m - m_new) + e^(s_b - m_new) v_b. FlashAttention is built on this trick.