Linear algebra for LLMsPart 9: Numbers on real hardware
Stable and online softmax
7 min
exp overflows fast
Attention scores and logits easily pass 11. Computed naively, the softmax numerator becomes infinity and the result becomes NaN.
Subtract the max (again)
Part 5’s shift invariance, now as a rule for hardware: after subtracting , every exponent is , so every is in and the sum is between 1 and the number of entries. Nothing overflows.
Write
Log-sum-exp
Cross-entropy needs the log of a softmax probability. Computing it as avoids taking the log of a tiny number that rounded to 0. That’s what F.cross_entropy does inside: pass it logits, not probabilities.
Write
The problem: rows don't fit
At that’s 67 million scores per head, too big for fast on-chip memory. We’d like to process and in blocks, but softmax needs the max and the sum over the whole row before it can normalize anything.
Online softmax: keep a running max and sum
Read the row one block at a time. When a new block raises the max, the old sum was computed against a smaller , so multiply it by to bring it to the new reference. At the end, is exactly over the whole row.
Write
On numbers: [1, 3 | 2, 5]
Check against the whole row at once: . Same answer, without ever holding all four scores.
✏️ Your turn
Run it yourself
Process the two blocks in order. Write and after each, then the three softmax weights.
Work it out on paper, then go to the next card to check.
Answer
The output gets the same rescale
Attention also needs the weighted sum of values. Keep an unnormalized running output , rescale it whenever the max moves, and divide by once at the end. This is the core of FlashAttention (Dao et al., 2022): exact attention, computed tile by tile in fast memory, never writing the matrix to GPU memory.
Write
📌 Recap
Stable and online softmax in one card
- Subtract the max before ; use log-sum-exp for log-probabilities.
- Online softmax: running and , rescaling by when the max grows.
- Rescale the running output the same way: FlashAttention.
Write
Sources
- Milakov and Gimelshein, “Online normalizer calculation for softmax” (2018), arXiv:1805.02867.
- Dao, Fu, Ermon, Rudra and Ré, “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness” (2022), arXiv:2205.14135.