FlashAttention computes softmax attention one block of keys at a time, without storing the full score matrix. Derive the online softmax recurrence that keeps a running maximum m and a running sum ℓ, and test it on the scores (1,3,2,5) split into the blocks (1,3) and (2,5) with values (1,2,3,4)?

Sequence models and transformers, Efficient attention
Level L4 Advanced. Length Long. Nature Th+Mat Both.

What's being asked

Whether you can derive how a softmax is computed in a single streaming pass, which is the maths that makes tiled exact attention possible.

Key idea

Keep m=max⁡ so far and ℓ=∑jesj−m. When a new block has maximum m′ and sum ℓ′, the merged values are mnew=max⁡(m,m′) and ℓnew=ℓ em−mnew+ℓ′ em′−mnew, which rescales the old sum to the new reference point.

Steps

  1. Stable softmax uses softmax(s)j=esj−m/∑kesk−m with m=max⁡ksk, to avoid overflow. This normally needs two passes, one for m and one for the sum.
  2. Suppose a block gave m,ℓ=∑j∈blockesj−m. Its sum relative to a larger reference M is ∑esj−M=em−M∑esj−m=ℓ em−M. Summing both blocks at M=max⁡(m,m′) gives the recurrence above.
  3. Block 1 (1,3): m=3, ℓ=e−2+1=1.1353. Block 2 (2,5): m′=5, ℓ′=e−3+1=1.0498.
  4. Merge: mnew=5 and ℓnew=1.1353 e−2+1.0498=0.1537+1.0498=1.2034. The one-pass result equals the direct ∑jesj−5=e−4+e−2+e−3+1=1.2034.
  5. Output. Keep a normalised running output o. Block 1 gives o=(e−2⋅1+1⋅2)/1.1353=1.8808 and block 2 gives o′=(e−3⋅3+1⋅4)/1.0498=3.9526. Merge onew=ℓem−M o+ℓ′em′−M o′ℓnew=0.1537×1.8808+1.0498×3.95261.2034=3.688.
  6. Check with the full softmax: weights (0.0152,0.1125,0.0414,0.8310) on values (1,2,3,4) give 0.0152+0.2249+0.1241+3.3238=3.688. The two agree, so the result is exact, not an approximation.
  7. Why it matters. Only blocks of K and V plus the running (m,ℓ,o) per query are held in fast on-chip memory, so the N×N score matrix is never written to slow memory. FLOPs are unchanged, but memory traffic falls.

Common mistakes

How long your answer should be

One page; 6–8 minutes.

Last checked on 4 December 2026.

Read this

Previous in Sequence models and transformers: Assume the loss follows L(N,D)=E+ANα+BDβ and training compute is C=6ND. Derive the compute-optimal N⋆(C) and D⋆(C) and their scaling exponents. What do α=0.34 and β=0.28 imply?
Next in Sequence models and transformers: Prove that a transformer encoder layer without positional encodings is permutation-equivariant: permuting the input tokens permutes the outputs in the same way. How do you show that a decoder with a causal mask and no positional encodings is not, and that it can still recover position information?