15.2 Stable numerics: logsumexp, softmax, and compensated sums
The byte bigram of Byte bigram: counts, logits, safetensors v0 in AI Engineering already hides a numerically careful softmax: its nll subtracts each row’s maximum before exp. Once you build real training code, that one line becomes a dozen call sites. The autograd op library of The op library and gradcheck_all needs softmax and log-softmax as ops, the fused cross-entropy of Losses with a fused backward needs log-softmax at the target, the sampler of Sampling and logit processors turns temperature-scaled logits into probabilities, and the evaluation harness of The evaluation harness and the model zoo sums ten million per-token losses into one perplexity.
Concepts from other sections (10)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- op library (
F): the module of differentiable functions, each a NumPy forward plus one closed-form VJP joined byfrom_op. Read more: 6.3 The op library and gradcheck_all in AI Engineering - Fused cross-entropy: the gradient computed directly from logits. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- Perplexity: , the geometric mean of ; the effective number of choices per token. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- Unit roundoff: , the largest relative error of a single round-to-nearest. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- Subnormal: a value with exponent field 0, no implicit leading 1, and a fixed exponent , filling the gap between zero and the smallest normal. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- online softmax: computing the maximum and the normalizer in one read by rescaling the running sum whenever the maximum grows. Read more: 22.4 Softmax in C: three-pass and online two-pass in AI Engineering
- Cumulative distribution function (CDF): , defined for every random variable, discrete or continuous; it rises from 0 to 1, and for a continuous variable its derivative is the density. Read more: Chapter 13: Probability and Statistics
Written the obvious way, each of them fails the first time training succeeds. A confident model produces a logit above 88.7, np.exp overflows float32 to inf, and the loss becomes inf / inf = nan. A confidently wrong token gets probability in float32, and log(0) is an infinite loss with a NaN gradient. Long sums fail more quietly: ten million float32 additions can lose most of their accuracy without any warning.
This section writes the stable versions once, proves that they are stable, and gives you the versions every later chapter imports. It relies on the overflow threshold and unit roundoff from IEEE 754 anatomy, ulps, and round to nearest even, and on the Taylor view of from Taylor series, remainder bounds, and range reduction. The reference implementation is stable.py (logsumexp, softmax, log_softmax, kahan_sum, pairwise_sum), with its interface in stable.pyi.
Learning objectives
- Derive the shift identity for log-sum-exp and explain why the maximum is the right shift.
- Compute softmax and log-softmax without overflow or underflow, including for masked and fully masked rows.
- State the error bounds of sequential, pairwise, and Kahan summation, and reproduce each on a small float32 example.
- Explain why compensated summation must run in the input’s dtype rather than a wider one.
The notation
Section titled “The notation”These symbols recur through the section:
| Symbol | Meaning | Type / shape |
|---|---|---|
| one row of logits (scores) | float[n] | |
| the shift that prevents overflow | scalar | |
| log-sum-exp | scalar | |
| probabilities from logits | float[n], sums to 1 | |
| log-probabilities from logits | float[n] | |
| unit roundoff: for float32, for float64 | scalar | |
| the floating-point result of an operation | scalar | |
| the exact sum | scalar | |
| the computed sum | scalar | |
| Kahan’s compensation: the low-order part lost so far | scalar |
Where exp breaks
Section titled “Where exp breaks”The previous section showed that the largest float32 is about and the largest float64 about . So np.exp(89.0) in float32 is inf. At the other end, underflows to exactly 0 below about in float32 (counting subnormals) and in float64. Logits after training routinely exceed 100 in magnitude, and masks write on purpose. Both ends of the range are therefore reachable in normal use, and the fix has to handle both.
The shift identity
Section titled “The shift identity”For any constant , , so
Choose . Every shifted exponent is at most 0, so every term is at most 1, and the largest term is exactly . The sum lies in : it cannot overflow, it is never 0, and its log lies in . Nothing is lost by the shift, because the identity is exact.
Softmax inherits the same protection, because it is shift invariant. Dividing by the sum cancels the factor :
So you compute . The same identity lets the C kernel of Softmax in C: three-pass and online two-pass process a row in one pass: when a new maximum appears, it rescales the running sum by instead of starting over.
Log-softmax from the identity, not from softmax
Section titled “Log-softmax from the identity, not from softmax”The identity also tells you how to compute log-probabilities: . Computed this way it is a subtraction of two moderate numbers. Computed as log(softmax(x)), it first rounds , which underflows to 0 once in float32, and then takes log(0) = -inf. The cross-entropy loss is at the target , so the choice is the difference between a large finite loss (with a useful gradient) and an infinite one.
Masking is the one place where is an input rather than a failure. A masked entry is , so and it gets probability exactly 0. If every entry is masked, though, and is NaN. The contract defines that row instead of propagating NaN: replace a non-finite by 0, so the shifted entries stay , the sum is 0, softmax returns zeros (divide by 1 when the sum is 0), and log-sum-exp returns . A padded position in a batch is exactly such a row.
Rounding in a sum
Section titled “Rounding in a sum”The second half of the section moves from single rows to long reductions. Every floating addition rounds: with . Summing left to right, the -th partial sum carries the rounding errors of all earlier additions, and the first terms pass through additions. The standard bound is
For float32 values that is a relative error up to about , which is useless. In practice errors partly cancel, but when the addends have the same sign (losses, counts, probabilities) they accumulate. There are two standard cures.
Pairwise summation splits the array in halves, sums each half the same way, and adds the two results. The recursion is levels deep, and each element takes part in only one addition per level, so
For the factor is 24 instead of . numpy’s np.sum does this internally (with blocks of 8 at the leaves), which is why np.cumsum, a strictly sequential sum, is the one that shows the problem.
Kahan’s compensated summation keeps a second variable holding the part the running sum could not absorb. For each :
When , is computed exactly, and it is the part of that actually made it into ; subtracting leaves minus the part that was rounded away. Algebraically , which is the point: in floating point it is the rounding error, recovered exactly and fed back into the next addend. The error bound becomes
which no longer grows with to first order. It costs four operations per element and a sequential loop, so it is used where the count is huge and the budget is not: running totals of losses, token counts, and perplexity.
Note: The point of compensation is to get extra precision without a wider type. Both sums here keep every operation in the dtype of (float32 stays float32) and return a Python float.
Working it by hand
Section titled “Working it by hand”Take and compute log-sum-exp and softmax step by step:
| step | values |
|---|---|
| 3 | |
| sum | |
| sum | |
| sum | |
| softmax $= e^{x-m} / $ sum | |
| log-softmax |
The softmax row sums to 1, and confirms the last entry. Adding 1000 to every entry changes to 1003 and leaves every shifted value, and so the softmax, unchanged.
Masks behave as designed. The row has , shifted values , exponentials , softmax , and log-softmax . For the fully masked row , becomes 0, every exponential is 0, softmax is , and log-sum-exp is .
Now sum in float32. At consecutive float32 values are 2 apart, so is exactly halfway between two floats and rounds to the even one, . The exact sum is 2.
Left to right, , then , then : both ones are lost. Pairwise, . The left pair loses its 1, but is representable, so the right pair keeps its 1: better, not exact. Kahan, one row per element:
| 0 | ||||
| 1 | 1 | (rounded) | ||
| 1 | (exact) | |||
| 2 | 2 |
The second row is the whole idea: the 1 that rounding threw away reappears as , and the next step adds it back. Kahan returns the exact 2.
In float64 the same thing happens one scale up: at floats are 2 apart, so plain summation of gives 0. Pairwise also gives 0 there, because is a tie too and rounds back to ; Kahan gives 2. These numbers become the first test cases below.
Designing the API
Section titled “Designing the API”The interface mirrors numpy’s reductions:
def logsumexp(x: ArrayLike, axis: int = -1, keepdims: bool = False) -> NDArraydef softmax(x: ArrayLike, axis: int = -1) -> NDArraydef log_softmax(x: ArrayLike, axis: int = -1) -> NDArraydef kahan_sum(x: ArrayLike) -> floatdef pairwise_sum(x: ArrayLike) -> floatFloat inputs keep their dtype; integer inputs are computed in float64. axis and keepdims mean what they mean in numpy. The sums flatten their input in C order. pairwise_sum splits at h = n // 2 down to single elements; pairing neighbours bottom up builds the same tree when is a power of two, so a vectorized version is fine. The contract has the full rules.
Building it step by step
Section titled “Building it step by step”The design follows from the principles in five steps. The shift identity is exact for any constant, and the maximum makes every term at most 1, so every function starts with the row maximum, kept as a size-1 axis so it broadcasts back. A fully masked row has maximum , and is NaN; replacing a non-finite maximum by 0 keeps the shifted entries at , their exponentials at 0, and the arithmetic defined. Log-sum-exp is then , and softmax is divided by its sum, with a zero sum (only possible for a fully masked row) replaced by 1. Log-softmax is , computed from the log-sum-exp, never from the softmax; a fully masked row has , and the result there is everywhere. Finally, the sums flatten the input and keep its float dtype: Kahan is the four-line loop above with and in that dtype, and pairwise is a recursion that halves the range, so its depth is .
Two helpers carry the dtype rule and the masking rule:
def _float(x): """x as a float array: float dtypes kept, everything else float64.""" a = np.asarray(x) if not np.issubdtype(a.dtype, np.floating): a = a.astype(np.float64) # integers: exp of an int array is float64 anyway return a # float32 stays float32: no silent upcast
def _safe_max(a, axis): """max along axis with keepdims, replaced by 0 where it is not finite, so a fully masked row (max = -inf) subtracts 0 instead of making -inf - -inf.""" m = np.max(a, axis=axis, keepdims=True) return np.where(np.isfinite(m), m, np.zeros_like(m))The three row functions are then short:
def logsumexp(x, axis=-1, keepdims=False): a = _float(x) m = _safe_max(a, axis) with np.errstate(divide="ignore", over="ignore", invalid="ignore"): s = np.sum(np.exp(a - m), axis=axis, keepdims=True) # in [1, n], or 0 if masked out = np.log(s) + m # add the shift back: LSE = m + log sum return out if keepdims else np.squeeze(out, axis=axis)
def softmax(x, axis=-1): a = _float(x) m = _safe_max(a, axis) with np.errstate(over="ignore", invalid="ignore"): e = np.exp(a - m) # every entry <= 1, the largest exactly 1 s = np.sum(e, axis=axis, keepdims=True) # A fully masked row has s = 0 and e = 0: divide by 1, keep the zeros. return e / np.where(s == 0, np.ones_like(s), s)
def log_softmax(x, axis=-1): a = _float(x) lse = logsumexp(a, axis=axis, keepdims=True) # never log(softmax(x)) with np.errstate(invalid="ignore"): out = a - lse # -inf - (-inf) is nan; a fully masked row is log 0 = -inf everywhere. return np.where(np.isneginf(lse), np.full_like(out, -np.inf), out)The errstate blocks silence the warnings numpy would print for the masked cases (log(0), inf - inf), which the code then handles explicitly; the row of all is a defined input, not an error. On : m = 3, exp([-2, -1, 0]) sums to , its log plus 3 gives , and log_softmax subtracts that from each entry.
The two sums come last:
def kahan_sum(x): a = _float(x).ravel() # C order, any shape zero = a.dtype.type(0) # s and c in the input's dtype s, c = zero, zero for v in a: y = v - c # the addend, corrected by what the last step lost t = s + y # the low bits of y are lost here... c = (t - s) - y # ...and recovered here (algebraically 0) s = t return float(s)
def pairwise_sum(x): a = _float(x).ravel()
def rec(lo, hi): n = hi - lo if n == 1: return a[lo] # a numpy scalar: additions stay in a's dtype h = lo + n // 2 # split in the middle: depth ceil(log2 n) return rec(lo, h) + rec(h, hi) # [lo, h) and [h, hi) cover every element once
if a.size == 0: return 0.0 # the empty sum; rec would index a[0] return float(rec(0, a.size))The line zero = a.dtype.type(0) matters. Starting from the Python float 0.0 would leave the dtype of s and c to numpy’s promotion rules for Python scalars, which changed between versions (NumPy 1 promoted 0.0 + np.float32(v) to float64). A float64 accumulator would silently remove the float32 rounding that Kahan is meant to correct. On the hand example, the loop reproduces the Kahan table: after the second element c = -1, and the third step adds it back. The full solution is in stable.py.
Why this design
Section titled “Why this design”The row functions are one max, one exp, and one sum per row: , with a few temporaries the size of the input. kahan_sum is a Python loop, but slow per element; pairwise_sum is additions with recursion depth.
Any shift keeps the identity exact, but only the max guarantees the largest term is 1 (no overflow) and the sum at least 1 (no for an unmasked row). You might be tempted to sidestep everything by computing in float64. Upcasting hides the problem in Python but not in the C kernels of the softmax chapter, which run in float32; the Python reference must round where they round, and compensation gets the accuracy without the wider type. math.fsum is another option: it is exactly rounded, but keeps a growing list of partials and works only in float64. Kahan’s bound is enough for loss totals and costs four operations per element.
The design accepts one tradeoff. kahan_sum is an interpreted loop, fine for running totals of a few million numbers but not for inner loops, and pairwise_sum recurses to single elements rather than using numpy’s blocked leaves. It is a readable reference for the error bound, not the fastest sum.
What can go wrong
Section titled “What can go wrong”The tests pin each claim made above. The hand table for fixes the definitions, and the float32 row must give 0 for plain summation, 2 for Kahan, and 1 for pairwise, so that the three sums differ exactly as derived; the float64 version of the same example checks that compensation, not a wider type, does the work. scipy’s three functions on seven shapes, axes, and scales act as an independent golden reference. Shift invariance is a property test: adding changes nothing except LSE, which moves by , and that is what the online softmax relies on when it rescales a running sum.
The boundary cases are the ones training hits. must give , and must stay finite, as logits after training do. must give a log-softmax of , not , for the sake of the fused cross-entropy. A fully masked row must give zeros and , with no NaN and no warning, because padded rows appear in every batch. Every axis of a 3-D array and every keepdims shape must work, since attention normalizes over [B, H, T, T]. float32 inputs must give float32 outputs and integers float64, because kernels compare in float32. Rows of scale 0.1 to 700 must sum to 1, so the sampler’s CDF ends at 1. Kahan must stay within on 65536 float32 values where plain summation does not, which matters when the evaluation harness sums losses, and pairwise must stay within for and . Lengths 0, 1, odd, a 2-D array, and integer inputs check that no term is dropped or invented.
The common mistakes, with their symptoms, are these:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| exponentiating before subtracting the max | inf / inf = nan at a float32 logit of 89 | np.exp(a - m) with m from _safe_max |
log(softmax(x)) | log-probability, infinite loss, NaN gradient | log_softmax is a - logsumexp(a) |
| subtracting a max of , or dividing by a zero sum | a padded row of NaN that spreads through the batch | _safe_max replaces a non-finite max by 0; softmax divides by 1 where the sum is 0 |
| computing the compensation and never using it | Kahan silently becomes plain summation | y = v - c feeds the compensation into every addend |
| a “pairwise” recursion that peels off one element at a time | a depth- tree, the sequential error, and a recursion limit | splits at lo + n // 2 |
| forgetting to add back in log-sum-exp | off by exactly the row maximum | np.log(s) + m |
| dropping the middle element of an odd split, or indexing an empty array | off by a whole term | ranges [lo, h) and [h, hi); an empty input returns 0.0 before recursing |
reducing the wrong axis, ignoring keepdims | attention normalized over the batch | every reduction uses the given axis with keepdims=True, squeezed only when asked |
| upcasting float32 to float64 | the C kernel’s float32 reference no longer matches | _float keeps float dtypes; Kahan starts from a.dtype.type(0) |
Where this leads
Section titled “Where this leads”These functions are imported almost everywhere. Within this book, entropy_from_logits in Entropy, cross-entropy, KL, JS, and the k3 estimator uses log_softmax, and cross_entropy_vjp in Matrix differentials, the trace trick, and closed-form VJPs uses softmax. Perplexity over tokens accumulates with kahan_sum through Perplexity, bits per byte, NLL accumulator.
In AI Engineering, softmax and log-softmax become autograd ops in The op library and gradcheck_all; the fused cross-entropy of Losses with a fused backward is at the target; Sampling and logit processors turns temperature-scaled logits into sampling probabilities; and The evaluation harness and the model zoo computes perplexity over tokens. Softmax in C: three-pass and online two-pass does the same math in C, in one pass with a running maximum. Beam search, generic over a step function scores candidates with log_softmax, Scaled dot-product attention (forward and backward) normalizes scores with softmax, and Sliding windows and attention sinks combines scores with logsumexp. Together they make possible the first milestone of that book: a bigram trained by its own autograd.
Production libraries go further along the same lines. PyTorch’s torch.softmax adds fused vectorized kernels and autocasts to float32 inside half-precision models (aten/src/ATen/native/SoftMax.cpp). scipy.special.logsumexp adds weights b (the log of a weighted sum) and sign handling for negative weights (scipy/special/_logsumexp.py). FlashAttention’s online softmax applies the shift identity in one pass over keys with a running max and a rescaled running sum. numpy’s np.add.reduce is pairwise with 8-way unrolled leaf blocks, chosen for speed and accuracy (numpy/_core/src/umath/loops_utils.h.src). Python’s math.fsum uses Shewchuk’s algorithm to return the exactly rounded sum, at the cost of a list of partials (Modules/mathmodule.c, math_fsum).
Further reading
Section titled “Further reading”- Higham, Accuracy and Stability of Numerical Algorithms (SIAM, 2nd ed.), chapters 1 and 4.
- Blanchard, Higham, and Higham, “Accurately computing the log-sum-exp and softmax functions” (IMA J. Numer. Anal., 2021).
- Dao et al., FlashAttention (2022), section 3.1.
Key terms
Section titled “Key terms”- Log-sum-exp (LSE): , computed stably as .
- Shift invariance: softmax is unchanged when the same constant is added to every logit.
- Fully masked row: a row of all , defined to give softmax zeros and LSE .
- Pairwise summation: recursive halving of a sum, with error growing like .
- Compensated (Kahan) summation: summation that carries the rounding error of each addition into the next, with first-order error independent of .
Summary
Section titled “Summary”- with : after the shift the largest exponential is , so nothing overflows, and the answer is finite for logits of any size.
log_softmaxisx - logsumexp(x), neverlog(softmax(x)): the second takes the log of an underflowed 0 and returns where the answer is .- A fully masked row (all ) is defined, not NaN: softmax gives zeros, log-sum-exp and log-softmax give .
- Plain summation of floats can be off by about ; pairwise summation cuts that to and Kahan’s compensation to about , independent of .
- Compensation must run in the input’s dtype, so the Python reference rounds exactly where the float32 C kernels round.
Review questions
Section titled “Review questions”-
Why does
_safe_maxreplace a non-finite maximum by 0, and why does that not change any finite result?Answer
A finite maximum is left alone, so finite rows are unaffected. A row whose maximum is is fully masked; subtracting it would give $-\infty - (-\infty) = $ NaN. Subtracting 0 instead leaves every entry , every exponential 0, and the shift identity still holds because any constant is a valid shift.
-
Why does
log_softmaxcalllogsumexpinstead of takingnp.log(softmax(x))?Answer
For ,
softmaxreturns in float32 or float64, because underflows to 0, and . is exact. The loss at that target is , large but finite, with a useful gradient; the other route gives an infinite loss and NaN gradients. -
In
kahan_sum, what would happen ifc = (t - s) - ywere computed but the next step usedy = vinstead ofy = v - c?Answer
The lost low-order bits would be measured and thrown away: the loop would be plain left-to-right summation with extra work, and on it would return 0 instead of 2.
-
Why does
pairwise_sumsplit atn // 2instead of addinga[lo]to the sum of the rest?Answer
Peeling one element at a time builds a tree of depth : each early element passes through about additions, which is the sequential error bound again, and the recursion hits Python’s limit at about 1000 elements. Halving gives depth , so each element passes through only that many roundings.
-
Why does
kahan_sumstart froma.dtype.type(0)rather than0.0?Answer
With a Python
0.0, whether the loop runs in float32 or float64 depends on numpy’s promotion rules for Python scalars (NumPy 1 gave float64). If it runs in float64, a wider type is doing the work, not compensation, and the result no longer matches the float32 C kernels. A zero of the input’s dtype makes every operation stay in that dtype on any numpy version. -
Why is the row maximum, rather than some other constant such as the mean, the right shift?
Answer
Any constant keeps the identity exact, but only the maximum guarantees that the largest shifted term is exactly . That bounds the sum in : it cannot overflow and, for an unmasked row, it is never 0, so its log is always defined. With the mean, a row with one large outlier could still overflow.