TL;DR
Softmax needs two things before it can output any number: the largest input, to keep the exponentials from overflowing, and the sum of all the exponentials, to normalise. The textbook method reads the data twice. Online softmax does both in a single streaming pass, keeping a running maximum and a running sum, and it rescales the sum whenever a bigger value shows up.
The same trick lets you split the input into blocks, compute each block's maximum and sum separately, and combine them afterwards. That is what lets attention kernels process a long sequence in chunks that fit in fast on-chip memory.
Where you'll see it: inside the attention kernels of large language models, such as FlashAttention, where the scores for a long sequence never sit in slow GPU memory all at once.
Intuition
Think of computing a softmax as two jobs. The first job is to find the scale: which value is the largest, and so how far the rest sit below it. The second job is to add up the weight of everything relative to that scale. The textbook recipe does the first job completely, then the second. That works fine on a list that fits in memory. It is awkward when the list is huge, arrives in pieces, or lives in a place where reading it twice costs real time.
The online method is like a running tally kept at a shop counter. You keep the current best price and the total you have so far, measured against that best price. When a new item arrives with a higher price, you do not recount everything. You just shrink your existing total by the ratio between the old and new reference prices, then add the new item measured against the new reference. The tally always stays correct for the items you have seen so far.
The reason this matters is memory traffic. On a GPU, reading a large array from main memory is far slower than arithmetic on values already in fast on-chip registers and caches. An algorithm that touches each value once, and keeps only a couple of running numbers per row, can avoid writing the full intermediate matrix back to slow memory at all.
The flow below shows one step of the streaming update. The state is always just two numbers, the running maximum and the running sum, for each row.
flowchart LR
A[New value x] --> B{x greater than running max?}
B -- yes --> C[Rescale sum by exp of old max minus new max]
B -- no --> D[Keep the max]
C --> E[Add exp of x minus new max to the sum]
D --> E
E --> F[State is max and sum so far]
The plot below shows why the subtraction of the maximum is the key step. Shifting the input by its maximum moves the largest value to exactly 1, so no exponential can exceed 1 and none overflows.
- exp(x), unshifted
- exp(x - 3), shifted by the max 3
The math
The softmax and its overflow problem
For a vector of scores , softmax gives
Here is Euler's number, and is the score for item , which can be any real number. The outputs are positive and sum to 1. The definition is in Softmax, and it relies on the Exponential Function.
Computed literally, this overflows. A 64-bit float cannot hold , so the expression becomes infinity divided by infinity. The fix is to subtract any constant from every score, since the constant cancels between top and bottom:
Choosing guarantees that every exponent is at most 0. Each term lies between 0 and 1, the largest term is exactly 1, and nothing overflows. This is the stable softmax, and it needs the maximum before any exponential can be computed. That is why the naive approach takes two passes.
The running update
Define, after processing the first inputs, the running maximum and the running normaliser
Now a new input arrives. The new maximum is . The old sum was measured against , so it must be re-measured against . Each old term is multiplied by , which is the same as . That gives the update rule
When the maximum does not change, the factor is exactly 1 and the rule just adds a term. When it does change, the factor shrinks the old total to match the new reference. After the last input, the softmax is , and it needed only one pass to get and . The output still needs a second read to divide each element by , unless the division is postponed, as described below.
Combining blocks
The same algebra gives a rule for merging two independent blocks. Block has state and block has . Their combined state is
This operation is associative, so blocks can be merged in any grouping, including on different processors. The states form a monoid: they combine with an identity element (an empty block with and ), and the order of grouping does not matter. This is the sense in which the method is algebraic aggregation.
Carrying the output along
In attention, the softmax weights multiply value vectors . The output is . The same rescaling can be applied to a running unnormalised output :
So the division by is done once, at the end, and no full row of scores is ever stored. This is the core of the FlashAttention kernel.
Worked examples
Take the scores . The stable answer, computed directly with the maximum , is shown first.
- Exponentials of the shifted scores: , , .
- Sum: .
- Softmax: , , . These sum to 1.
Now the streaming pass, reading one value at a time.
- Start with : , .
- Read , which is larger. New . Rescale the old sum by , giving , then add . So .
- Read , which is not larger. stays 3. Add , so .
- The final state matches the direct computation exactly: , .
Interpretation: one pass gave the same answer as the two-pass method. The only extra work was one rescale, which happened once, when the maximum changed.
Take . Computing directly overflows a 64-bit float, which tops out near .
- Maximum: .
- Shifted exponentials: and .
- Sum: .
- Softmax: and .
The streaming version gives the same result. Reading first gives and . Reading then sets , rescales to , and adds 1, giving .
Interpretation: no exponent ever exceeds 0, so the computation stays in a safe range regardless of how large the raw scores are.
Split into two blocks, and .
- Block : streaming over then gives and .
- Block : a single value gives and .
- Combined maximum: .
- Combined sum: .
Interpretation: the merged state equals the single-pass state, so blocks computed on separate processors can be combined without touching the original values again.
Use scores and values . The exact attention output is .
- Direct computation: .
- Streaming with the unnormalised output. Start with , , .
- Read , . New . Rescale: , and . Add: , .
- Read , . stays 3. Add: , .
- Divide once at the end: . This matches step 1.
Interpretation: the output was built with one pass over the values, and the normalising division happened once, at the very end.
Tradeoffs and failure modes
Online softmax is a reformulation, not an approximation. It gives the same numbers as the stable two-pass method up to floating-point rounding. Its costs and risks are in the details.
| Situation | Problem | Better choice |
|---|---|---|
| Short rows that fit in cache | The extra rescale multiplications add cost for no memory benefit | Standard two-pass softmax |
| Very long rows, GPU-bound | The full score matrix is too big for fast memory | Streaming or blockwise online softmax |
| Mixed precision with low-range floats | Running sums can lose precision or underflow in when a block contributes very small terms | Keep the running state in float32 even if inputs are float16 |
| All scores equal to (fully masked row) | The maximum is , so becomes and yields NaN | Clamp the maximum to a finite floor, or handle masked rows explicitly |
| Parallel reduction across threads | Merge order changes rounding, so results vary slightly between runs | Accept small differences, or fix the reduction order if exact reproducibility matters |
Some practical warnings:
- The rescale factor is the subtle part. It must be , which is at most 1. Using the reciprocal, or forgetting the rescale when the maximum changes, gives wrong answers that often look plausible on small tests.
- Test with a large shift. Scores like are a good check. A correct implementation returns the same probabilities as for , and a naive one overflows.
- Masking interacts with the maximum. If masked positions are set to and every position in a block is masked, the block's maximum is . The merge rule then needs care to avoid NaN.
History
Softmax itself is older than neural networks. It goes back to the statistical mechanics of Boltzmann distributions in the 19th century, and it was popularised in machine learning in the late 1980s and early 1990s as a way to turn network outputs into class probabilities. The name "softmax" is usually credited to John Bridle around 1989, in the context of making a soft version of the maximum that can be trained with gradients.
The overflow problem and its fix were standard practice for a long time before anyone wrote the streaming version down. The subtraction of the maximum appears in many numerical analysis texts and in the early deep learning libraries. The one-pass algorithm for the normaliser was published by Milakov and Gimelshein at NVIDIA in 2018. It showed that the maximum and the normaliser can be computed together, which reduces memory reads for large softmax operations.
The method became central in 2022, when Dao and collaborators built FlashAttention. It fused the streaming softmax into the attention computation, so that the score matrix for a long sequence was never written to slow GPU memory. It turned a numerical trick into a systems technique: fewer trips to memory, the same exact result. Later attention kernels and inference engines use the same idea, with the blockwise merge rule as the basic building block.
Check yourself
QuestionWhy does the stable softmax subtract the maximum from every score, and what is the largest value any exponential can take after this?Show answer
Subtracting leaves the softmax unchanged, because the same constant appears in the numerator and denominator and cancels. After subtraction every exponent is at most 0, so every exponential is at most . The largest term is exactly 1, which prevents overflow.
QuestionScores are . Compute the streaming state after reading both values, and the softmax.Show answer
Start with , . Read , which is larger. New . Rescale the old sum: . Add , so . The softmax is and . These sum to 1.
QuestionTwo blocks have states and . Compute the merged state. Why is the order of merging irrelevant?Show answer
The merged maximum is . The merged sum is . The merge rule is associative: merging with then with gives the same state as merging with first, because each step rescales every sum to the common maximum, and the final result is always the sum of over all inputs. So blocks can be combined in any tree, including in parallel.
QuestionA colleague implements online softmax for a language model and gets NaN outputs only for some padded sequences. What is a likely cause, and how would you check it?Show answer
Padded positions are often masked by setting their scores to . If an entire block, or an entire row, is masked, its maximum is . The rescale term then becomes , which is NaN. To check, print the block maxima for the failing sequences and look for . The fix is to clamp the maximum to a large negative finite value, or to skip fully masked blocks in the merge.