Foundations to Frontier
Tests
A. Mathematical Foundations › A8 Numerical Methods and Scientific Computing

Stable Computation: Log-Sum-Exp, Stable Softmax and Friends

Many formulas that are correct on paper overflow, underflow or cancel catastrophically in floating point. This topic collects the standard rescues: the log-sum-exp trick, stable softmax and log-softmax, softplus and binary cross-entropy from logits, Welford's variance, the stable quadratic formula, and computing likelihoods in log space. You will prove why each works, implement them, and run a 2000-step hidden Markov model of rover terrain whose likelihood underflows to exactly zero unless computed in log space or with scaling.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Rearranging to stay on the ruler

Suppose you need to compare two huge numbers like a billion billion billion and a billion billion billion and one. Your calculator only has 8 digits, so you can’t even type them. But you could subtract a billion billion billion from both first, and then compare 0 and 1. That’s easy. Stable computation is the art of rewriting a formula so the computer never has to hold numbers that are too big, too small or too close together.

Same maths, different numerics (float32)
logitnaivestable
500.73100.7310
490.26890.2689
400.000033190.00003319
exp(s) overflows float32 above s ≈ 88.7; ∞/∞ = NaN. Subtracting max(z) first changes nothing mathematically.
true variance0.3048
one-pass E[x²] − E[x]²0.1270
Welford0.3048
Once the offset is large, x² loses the small deviations entirely, and the subtraction cancels to rounding noise (even negative). Welford updates the mean and the sum of squared deviations incrementally. At very large offsets the data themselves are rounded, so no formula can recover them.
Why engineers care

A navigation filter that computes particle weights or HMM likelihoods by multiplying probabilities will underflow to zero within a few hundred steps. A classifier with large logits will produce NaN losses. Stable formulations are the difference between a system that works for a minute and one that works for a mission.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Stable computation means…
  2. 2. Multiplying many probabilities together tends to…
  3. 3. Working with logarithms turns products into…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The log-sum-exp trick

log⁡∑iezi=m+log⁡∑iezi−m,m=max⁡izi\log\sum_ie^{z_i} = m + \log\sum_ie^{z_i - m},\qquad m = \max_iz_i

Every exponent is now ≤ 0, so nothing overflows, and at least one term equals 1, so the sum can’t underflow to 0.

Stable softmax and log-softmax

softmax⁡(z)i=ezi−m∑jezj−m,log⁡softmax⁡(z)i=zi−LSE⁡(z)\operatorname{softmax}(z)_i = \frac{e^{z_i - m}}{\sum_je^{z_j - m}},\qquad\log\operatorname{softmax}(z)_i = z_i - \operatorname{LSE}(z)

Compute log-probabilities directly. Never take log of a softmax output that may have underflowed to 0.

Softplus and BCE from logits

softplus⁡(x)=log⁡(1+ex)=max⁡(x,0)+log1p⁡(e−∣x∣)\operatorname{softplus}(x) = \log(1 + e^x) = \max(x, 0) + \operatorname{log1p}(e^{-\lvert x\rvert}). Binary cross-entropy with logit zz and label yy is softplus⁡(z)−yz\operatorname{softplus}(z) - yz. That’s what BCEWithLogitsLoss computes.

📝 Quick check (Level 1)
0/3 answered
  1. 1. In the LSE trick, m is…
  2. 2. log softmax(z)ᵢ =
  3. 3. softplus(1000) ≈

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

More stable rewrites

  • Variance: the one-pass 1n−1(∑x2−(∑x)2/n)\frac1{n-1}(\sum x^2 - (\sum x)^2/n) cancels catastrophically when the mean is large. Welford’s update keeps a running mean and sum of squared deviations: δ=x−xˉ\delta = x - \bar x, then xˉ+=δ/n\bar x\mathrel{+}=\delta/n and M2+=δ(x−xˉ)M_2\mathrel{+}=\delta(x - \bar x).
  • Quadratic roots: q=−12(b+sign⁡(b)b2−4ac)q = -\frac12(b + \operatorname{sign}(b)\sqrt{b^2 - 4ac}), giving x1=q/ax_1 = q/a and x2=c/qx_2 = c/q. This avoids subtracting nearly equal −b-b and ⋅\sqrt{\cdot}.
  • Norms: hypot(x, y) scales to avoid overflow in x2+y2x^2 + y^2.
  • Log-space probability: store log-probabilities. Replace products with sums and sums with LSE. This is used in HMMs, particle-filter weights, Bayesian evidence and beam search.
🐍 Exercise 1: a stable numerics toolkit
Implement logsumexp, softmax, log_softmax, softplus, BCE from logits and Welford variance. Show the naive versions failing (NaN softmax, a variance that is far off: zero or even negative, depending on the platform) and the stable ones agreeing with the exact answers.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The one-pass variance formula fails when…
  2. 2. The stable quadratic formula avoids…
  3. 3. Particle-filter weights should be normalized using…

Level 3: Advanced

★★★★☆ Advanced⏱ 40 minGraduate level, with full derivations and proofs.

Why LSE is accurate

Let s=∑ezi−m∈[1,n]s = \sum e^{z_i - m}\in[1, n]. Each term is computed with relative error O(u)O(u) and the sum of positive terms is well-conditioned. log⁡s\log s then has absolute error O(u)O(u), and adding mm is one more rounding. So LSE is accurate to a few ulps relative to max⁡(∣m∣,1)\max(\lvert m\rvert, 1) (Blanchard, Higham and Higham, 2021). ∎

Softmax gradient stays stable

∂log⁡softmax⁡(z)y/∂zi=1[i=y]−softmax⁡(z)i\partial\log\operatorname{softmax}(z)_y/\partial z_i = \mathbb 1[i = y] - \operatorname{softmax}(z)_i, a difference of bounded quantities. Fusing log-softmax with NLL avoids ever forming log⁡0\log0.

Welford is backward stable

Each update works with deviations from the current mean, whose size is set by the spread, not the offset. The error bound is O(nu)⋅σ2O(nu)\cdot\sigma^2, compared with O(nu)⋅(σ2+xˉ2)O(nu)\cdot(\sigma^2 + \bar x^2) for the one-pass formula (Chan, Golub and LeVeque, 1983).

Exercise 3.1: LSE of (−1000, −1000)

m=−1000m = -1000, s=2s = 2, so the result is −1000+ln⁡2≈−999.307-1000 + \ln2\approx-999.307. The naive version gives log⁡0=−∞\log0 = -\infty.

📝 Quick check (Level 3)
0/3 answered
  1. 1. In LSE, the shifted sum s lies in…
  2. 2. LSE(−1000, −1000) ≈
  3. 3. The gradient of log-softmax with respect to the logits is…

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Terrain HMM over a long traverse

A rover infers terrain type (sand, rock, ice) from wheel-slip readings with a hidden Markov model. The forward algorithm multiplies thousands of probabilities below 1. After 2000 steps the true likelihood is about 10−85310^{-853}, far below the smallest double (≈10−308\approx10^{-308}), so the naive recursion returns exactly 0. There are two standard fixes, and both give the same log-likelihood:

  • log-space forward, using LSE over predecessor states;
  • scaled forward (Rabiner, 1989), which normalizes αt\alpha_t every step and accumulates log⁡ct\log c_t.
🐍 Exercise 2 (research): underflow-proof HMM likelihoods
Implement naive, log-space and scaled forward algorithms for a terrain HMM. Check them against brute-force enumeration on a short sequence, then show that the naive version underflows on a 2000-step traverse while the others agree.

Stable computation in AI, robotics and aerospace

  • Deep learning frameworks: fused log_softmax + NLL, BCEWithLogitsLoss, logsumexp and FlashAttention’s online softmax, which uses running-max rescaling (Milakov and Gimelshein, 2018; Dao et al., 2022).
  • Particle filters: log-weights normalized by LSE, plus effective sample size from normalized weights.
  • Kalman filters: Joseph form and square-root or UD factorizations keep covariances symmetric positive definite (Bierman, 1977).
  • Bayesian model comparison: log marginal likelihoods and log Bayes factors are always computed in log space.

References

  1. N. Higham (2002). Accuracy and Stability of Numerical Algorithms, 2nd ed. SIAM.
  2. P. Blanchard, D. Higham, N. Higham (2021). “Accurately computing the log-sum-exp and softmax functions.” IMA Journal of Numerical Analysis, 41(4).
  3. B. P. Welford (1962). “Note on a method for calculating corrected sums of squares and products.” Technometrics, 4(3).
  4. T. Chan, G. Golub, R. LeVeque (1983). “Algorithms for computing the sample variance: analysis and recommendations.” The American Statistician, 37(3).
  5. L. Rabiner (1989). “A tutorial on hidden Markov models and selected applications in speech recognition.” Proceedings of the IEEE, 77(2).
  6. M. Milakov, N. Gimelshein (2018). “Online normalizer calculation for softmax.” arXiv:1805.02867.
  7. T. Dao et al. (2022). “FlashAttention: fast and memory-efficient exact attention with IO-awareness.” NeurIPS.
  8. G. Bierman (1977). Factorization Methods for Discrete Sequential Estimation. Academic Press.