agent-readings / Inference and Serving Infrastructure
FlashAttention
Exact attention with less memory traffic
---
Core idea
Load blocks of Q, K, and V into SRAM, compute attention tile by tile with online softmax, write only final outputs and small normalization state to HBM, and...
Load blocks of Q, K, and V into SRAM, compute attention tile by tile with online softmax, write only final outputs and small normalization state to HBM, and recompute tiles during backward rather than storing the whole attention matrix.
Modelreason
Runtimeact
Worldobserve
01
Partition Q, K, and V into blocks sized for GPU SRAM.
02
Loop over K/V blocks and Q blocks, loading only the active tiles into SRAM.
03
Compute local attention scores for the tile.
04
Update online softmax statistics and accumulated outputs without storing the full N by N score matrix.
---
Executable shape
The mechanism should fit on one screen.
```python
for kv_block in blocks(K, V):
K_sram, V_sram = load_to_sram(kv_block)
for q_block in blocks(Q):
Q_sram = load_to_sram(q_block)
scores = Q_sram @ K_sram.T
m_new, l_new, acc_new = online_softmax_update(scores, V_sram, state[q_block])
state[q_block] = (m_new, l_new, acc_new)
for q_block in blocks(Q):
write_hbm(output[q_block], normalize(state[q_block]))
# Backward recomputes score tiles instead of loading a saved N x N attention matrix.
```
---