Search

Search papers and lessons

Online Softmax

Level 4 · 12 min read

Online softmax computes a numerically stable softmax in one streaming pass by keeping a running maximum and a running sum that are rescaled whenever the maximum changes.

On this page

  • Colour = topic mix
  • Efficiency
  • Neural network basics
  • Discrete math
  • Probability
  • Sign in to see your progress

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.

−2−10123012345input xexp value
  • exp(x), unshifted
  • exp(x - 3), shifted by the max 3
For inputs up to the maximum (here 3), the shifted exponential stays at or below 1 and reaches exactly 1 at the maximum, marked by the point. The unshifted curve climbs past 20 over the same range.

The math

The softmax and its overflow problem

For a vector of scores x1,…,xNx_1, \dots, x_N, softmax gives

si=exi∑j=1Nexj.s_i = \frac{e^{x_i}}{\sum_{j=1}^{N} e^{x_j}}.

Here ee is Euler's number, and xix_i is the score for item ii, 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 e1000e^{1000}, so the expression becomes infinity divided by infinity. The fix is to subtract any constant cc from every score, since the constant cancels between top and bottom:

si=exi−c∑jexj−c.s_i = \frac{e^{x_i - c}}{\sum_{j} e^{x_j - c}}.

Choosing c=m=max⁡jxjc = m = \max_j x_j 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 ii inputs, the running maximum and the running normaliser

mi=max⁡j≤ixj,di=∑j≤iexj−mi.m_i = \max_{j \le i} x_j, \qquad d_i = \sum_{j \le i} e^{x_j - m_i}.

Now a new input xi+1x_{i+1} arrives. The new maximum is mi+1=max⁡(mi,xi+1)m_{i+1} = \max(m_i, x_{i+1}). The old sum was measured against mim_i, so it must be re-measured against mi+1m_{i+1}. Each old term is multiplied by emi−mi+1e^{m_i - m_{i+1}}, which is the same as exj−mi⋅emi−mi+1=exj−mi+1e^{x_j - m_i} \cdot e^{m_i - m_{i+1}} = e^{x_j - m_{i+1}}. That gives the update rule

di+1=di e mi−mi+1+e xi+1−mi+1.d_{i+1} = d_i \, e^{\,m_i - m_{i+1}} + e^{\,x_{i+1} - m_{i+1}}.

When the maximum does not change, the factor emi−mi+1e^{m_i - m_{i+1}} 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 si=exi−mN/dNs_i = e^{x_i - m_N} / d_N, and it needed only one pass to get mNm_N and dNd_N. The output still needs a second read to divide each element by dNd_N, unless the division is postponed, as described below.

Combining blocks

The same algebra gives a rule for merging two independent blocks. Block AA has state (mA,dA)(m_A, d_A) and block BB has (mB,dB)(m_B, d_B). Their combined state is

m=max⁡(mA,mB),d=dA e mA−m+dB e mB−m.m = \max(m_A, m_B), \qquad d = d_A \, e^{\,m_A - m} + d_B \, e^{\,m_B - m}.

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 m=−∞m = -\infty and d=0d = 0), 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 viv_i. The output is o=∑isivio = \sum_i s_i v_i. The same rescaling can be applied to a running unnormalised output ui=∑j≤iexj−mivju_i = \sum_{j \le i} e^{x_j - m_i} v_j:

ui+1=ui e mi−mi+1+e xi+1−mi+1vi+1,o=uNdN.u_{i+1} = u_i \, e^{\,m_i - m_{i+1}} + e^{\,x_{i+1} - m_{i+1}} v_{i+1}, \qquad o = \frac{u_N}{d_N}.

So the division by dNd_N 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

Example
Scores 1, 3, 2, by the streaming rule

Take the scores x=(1,3,2)x = (1, 3, 2). The stable answer, computed directly with the maximum m=3m = 3, is shown first.

  1. Exponentials of the shifted scores: e1−3=0.1353e^{1-3} = 0.1353, e3−3=1e^{3-3} = 1, e2−3=0.3679e^{2-3} = 0.3679.
  2. Sum: d=0.1353+1+0.3679=1.5032d = 0.1353 + 1 + 0.3679 = 1.5032.
  3. Softmax: 0.1353/1.5032=0.09000.1353 / 1.5032 = 0.0900, 1/1.5032=0.66521 / 1.5032 = 0.6652, 0.3679/1.5032=0.24470.3679 / 1.5032 = 0.2447. These sum to 1.

Now the streaming pass, reading one value at a time.

  1. Start with x=1x = 1: m=1m = 1, d=e0=1d = e^{0} = 1.
  2. Read x=3x = 3, which is larger. New m=3m = 3. Rescale the old sum by e1−3=0.1353e^{1-3} = 0.1353, giving 0.13530.1353, then add e0=1e^{0} = 1. So d=1.1353d = 1.1353.
  3. Read x=2x = 2, which is not larger. mm stays 3. Add e2−3=0.3679e^{2-3} = 0.3679, so d=1.5032d = 1.5032.
  4. The final state matches the direct computation exactly: m=3m = 3, d=1.5032d = 1.5032.

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.

Example
Scores too large for exp

Take x=(1000,1001)x = (1000, 1001). Computing e1000e^{1000} directly overflows a 64-bit float, which tops out near e709.78e^{709.78}.

  1. Maximum: m=1001m = 1001.
  2. Shifted exponentials: e1000−1001=e−1=0.3679e^{1000 - 1001} = e^{-1} = 0.3679 and e0=1e^{0} = 1.
  3. Sum: d=1.3679d = 1.3679.
  4. Softmax: 0.3679/1.3679=0.26890.3679 / 1.3679 = 0.2689 and 1/1.3679=0.73111 / 1.3679 = 0.7311.

The streaming version gives the same result. Reading 10001000 first gives m=1000m = 1000 and d=1d = 1. Reading 10011001 then sets m=1001m = 1001, rescales dd to 1⋅e−1=0.36791 \cdot e^{-1} = 0.3679, and adds 1, giving d=1.3679d = 1.3679.

Interpretation: no exponent ever exceeds 0, so the computation stays in a safe range regardless of how large the raw scores are.

Example
Merging two blocks

Split x=(1,3,2)x = (1, 3, 2) into two blocks, A=(1,3)A = (1, 3) and B=(2)B = (2).

  1. Block AA: streaming over 11 then 33 gives mA=3m_A = 3 and dA=e1−3+e0=1.1353d_A = e^{1-3} + e^{0} = 1.1353.
  2. Block BB: a single value gives mB=2m_B = 2 and dB=1d_B = 1.
  3. Combined maximum: m=max⁡(3,2)=3m = \max(3, 2) = 3.
  4. Combined sum: d=1.1353⋅e3−3+1⋅e2−3=1.1353+0.3679=1.5032d = 1.1353 \cdot e^{3-3} + 1 \cdot e^{2-3} = 1.1353 + 0.3679 = 1.5032.

Interpretation: the merged state equals the single-pass state, so blocks computed on separate processors can be combined without touching the original values again.

Example
Attention output with a deferred division

Use scores x=(1,3,2)x = (1, 3, 2) and values v=(10,20,30)v = (10, 20, 30). The exact attention output is ∑isivi\sum_i s_i v_i.

  1. Direct computation: 0.09003⋅10+0.66524⋅20+0.24473⋅30=0.900+13.305+7.342=21.5470.09003 \cdot 10 + 0.66524 \cdot 20 + 0.24473 \cdot 30 = 0.900 + 13.305 + 7.342 = 21.547.
  2. Streaming with the unnormalised output. Start with m=1m = 1, d=1d = 1, u=10u = 10.
  3. Read x=3x = 3, v=20v = 20. New m=3m = 3. Rescale: u=10⋅0.1353=1.3534u = 10 \cdot 0.1353 = 1.3534, and d=0.1353d = 0.1353. Add: u=1.3534+20=21.3534u = 1.3534 + 20 = 21.3534, d=1.1353d = 1.1353.
  4. Read x=2x = 2, v=30v = 30. mm stays 3. Add: u=21.3534+30⋅0.3679=32.3897u = 21.3534 + 30 \cdot 0.3679 = 32.3897, d=1.5032d = 1.5032.
  5. Divide once at the end: u/d=32.3897/1.5032=21.547u / d = 32.3897 / 1.5032 = 21.547. 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.

SituationProblemBetter choice
Short rows that fit in cacheThe extra rescale multiplications add cost for no memory benefitStandard two-pass softmax
Very long rows, GPU-boundThe full score matrix is too big for fast memoryStreaming or blockwise online softmax
Mixed precision with low-range floatsRunning sums can lose precision or underflow in dd when a block contributes very small termsKeep the running state in float32 even if inputs are float16
All scores equal to −∞-\infty (fully masked row)The maximum is −∞-\infty, so m−m′m - m' becomes ∞−∞\infty - \infty and yields NaNClamp the maximum to a finite floor, or handle masked rows explicitly
Parallel reduction across threadsMerge order changes rounding, so results vary slightly between runsAccept small differences, or fix the reduction order if exact reproducibility matters

Some practical warnings:

  • The rescale factor is the subtle part. It must be emold−mnewe^{m_{\text{old}} - m_{\text{new}}}, 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 x+1000x + 1000 are a good check. A correct implementation returns the same probabilities as for xx, and a naive one overflows.
  • Masking interacts with the maximum. If masked positions are set to −∞-\infty and every position in a block is masked, the block's maximum is −∞-\infty. 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 mm from every score, and what is the largest value any exponential can take after this?Show answer

Subtracting mm 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 e0=1e^0 = 1. The largest term is exactly 1, which prevents overflow.

QuestionScores are x=(0,2)x = (0, 2). Compute the streaming state (m,d)(m, d) after reading both values, and the softmax.Show answer

Start with m=0m = 0, d=e0=1d = e^0 = 1. Read x=2x = 2, which is larger. New m=2m = 2. Rescale the old sum: d=1⋅e0−2=0.1353d = 1 \cdot e^{0 - 2} = 0.1353. Add e2−2=1e^{2 - 2} = 1, so d=1.1353d = 1.1353. The softmax is e0−2/1.1353=0.1192e^{0-2}/1.1353 = 0.1192 and 1/1.1353=0.88081/1.1353 = 0.8808. These sum to 1.

QuestionTwo blocks have states (mA,dA)=(5,2)(m_A, d_A) = (5, 2) and (mB,dB)=(3,4)(m_B, d_B) = (3, 4). Compute the merged state. Why is the order of merging irrelevant?Show answer

The merged maximum is m=max⁡(5,3)=5m = \max(5, 3) = 5. The merged sum is d=2⋅e5−5+4⋅e3−5=2+4⋅0.1353=2.5413d = 2 \cdot e^{5-5} + 4 \cdot e^{3-5} = 2 + 4 \cdot 0.1353 = 2.5413. The merge rule is associative: merging AA with BB then with CC gives the same state as merging BB with CC first, because each step rescales every sum to the common maximum, and the final result is always the sum of exj−me^{x_j - m} 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 −∞-\infty. If an entire block, or an entire row, is masked, its maximum is −∞-\infty. The rescale term emold−mnewe^{m_{\text{old}} - m_{\text{new}}} then becomes e−∞−(−∞)e^{-\infty - (-\infty)}, which is NaN. To check, print the block maxima for the failing sequences and look for −∞-\infty. The fix is to clamp the maximum to a large negative finite value, or to skip fully masked blocks in the merge.

Sources