FlashAttention computes it in tiles and never stores the matrix
The fix keeps the answer exact and drops the matrix.
FlashAttention computes attention in tiles. Does it ever store the full score matrix?
- →
- →
- →
- →
You don't have to store the matrix. FlashAttention computes exact attention in tiles small enough for the GPU's on-chip SRAM, its small, fast memory. It keeps a running max and a running sum for each row's softmax as it goes. So the full matrix never lands in the GPU's main memory.
Start with a running sum and a running blend for one query, in NumPy, two keys at a time:
rng = np.random.default_rng(0)
# one query's scores on 8 keys
s = rng.normal(size=8)
# one number per key, to keep it short
v = rng.normal(size=8)
l, acc = 0.0, 0.0
for start in range(0, 8, 2):
tile, vt = s[start:start + 2], v[start:start + 2]
l = l + np.exp(tile).sum()
acc = acc + np.exp(tile) @ vt
print(np.isclose(acc / l, softmax(s) @ v))Truel adds up e to each score, the softmax's denominator. acc adds up the values, weighted by those same numbers. Divide at the end and you have the softmax blend, and no tile's scores are kept after their turn.
This loop has the overflow from Part 4: a score of 1000 makes np.exp return inf. The fix is the same shift by the max, but the max isn't known until the last tile. So keep a running max m, and work each tile out as e to its score minus new_m, the largest score so far. Whatever is already in l and acc was worked out against the old, smaller max. When a tile brings a bigger max, multiply both by np.exp(m - new_m) first, which shrinks them to the new max.
The output is identical to attention done the plain way. What changes is how much memory it needs and how much data moves.
In the editor, tiled(s, v, tile) is that loop for one query, with a vector for each value and the running max added. Fill in the three updates. The last two lines print its answer next to the plain softmax blend, and they should match. Level 4 of the practice runs the same loop for every query at once.
- 1
Fill in the three updates in the loop:
new_m, the running max, then the running sumland the running blendacc. - 2
Scale the old
landaccbynp.exp(m - new_m)before you add the tile's part.
Run your code to check it. Output shows here.