AI Wiki中文/EN

The log-sum-exp trick

Log-sum-exp 技巧

Add probabilities in log space, derive the softmax gradient and convexity, and handle infinities without losing log probabilities.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The final answer fits, but the intermediate value does not

Suppose two alternatives have unnormalized log scores 1000 and 1001. Their total log weight is log⁡(e1000+e1001)\log(e^{1000}+e^{1001}), about 1001.313262. That final answer is easy to store. The intermediate exponentials, however, overflow ordinary binary64 evaluation.

The log-sum-exp trick moves the computation to a safer scale before exponentiating. This is useful when adding tiny probabilities in log space, normalizing classifier scores, or combining alternative paths. Multiplying probabilities becomes addition of logs; adding probabilities requires log-sum-exp. Confusing those two operations changes the probability model. Deep Learning, Section 4.1

Subtract a maximum, then put it back

For a nonempty finite real vector x, define L(x)=log⁡∑iexiL(x)=\log\sum_i e^{x_i}. For any finite c, factor ece^c from the sum. Choosing m=max⁡ixim=\max_i x_i gives

L(x)=m+log⁡∑iexi−m.L(x)=m+\log\sum_i e^{x_i-m}.

Every exponent is nonpositive, so its exponential is at most one. At least one exponent is zero, so the sum is at least one. Small terms may underflow to zero, but the entire denominator cannot do so. With n entries, the same observations give

m≤L(x)≤m+log⁡n.m\leq L(x)\leq m+\log n.

Equality on the upper side occurs when all scores match. L is a smooth approximation to the maximum, but does not equal it in general. Shifting all entries by c shifts L by c and leaves normalized probabilities unchanged.

Differentiate the exact finite-input expression. The gradient is softmax, and differentiating again gives

pi=exi∑jexj,∇L=p,∇2L=diag⁡(p)−pp⊤.p_i=\frac{e^{x_i}}{\sum_j e^{x_j}},\qquad \nabla L=p,\qquad \nabla^2L=\operatorname{diag}(p)-pp^\top.

For any v, its Hessian quadratic form is

v⊤∇2L v=∑ipi(vi−vˉ)2≥0,vˉ=∑ipivi.v^\top\nabla^2L\,v=\sum_i p_i(v_i-\bar v)^2\geq0,\qquad \bar v=\sum_i p_iv_i.

This is a weighted variance, so L is convex. The all-ones direction has zero curvature because common shifts act linearly; L is not strictly convex on the full space. The maximum used in the stable implementation has kinks at ties, but the mathematical L does not: the shift cancels from the exact expression. Convex Optimization, Appendix A.4.2–A.4.4

Keep log probabilities in the shifted coordinates

The standard-library implementation below explicitly defines its edge cases. The unweighted reduction maps an empty input or all negative infinities to negative infinity, positive infinity to positive infinity, and rejects NaN. Normalization needs at least one finite score and rejects positive infinity, while allowing negative infinity as a zero-weight mask.

import math

def logsumexp(values):
    x = list(values)
    if any(math.isnan(t) for t in x):
        raise ValueError("NaN logits are rejected")
    if not x:
        return -math.inf
    maximum = max(x)
    if maximum in (-math.inf, math.inf):
        return maximum
    shifted = [t-maximum for t in x]
    total = math.fsum(math.exp(t) for t in shifted)
    return maximum+math.log(total)

def log_softmax(values):
    x = list(values)
    if not x or any(math.isnan(t) or t==math.inf for t in x) or max(x)==-math.inf:
        raise ValueError("need a finite logit; NaN and positive infinity are rejected")
    maximum = max(x)
    shifted = [t-maximum for t in x]
    log_total = math.log(math.fsum(math.exp(t) for t in shifted))
    return [t-log_total for t in shifted]

assert abs(logsumexp([1000.,1001.])-(1001+math.log1p(math.exp(-1))))<1e-12
assert logsumexp([]) == -math.inf
assert logsumexp([-math.inf,-math.inf]) == -math.inf
assert logsumexp([0.,math.inf]) == math.inf
logs = log_softmax([1e16,1e16])
assert all(abs(t+math.log(2))<1e-15 for t in logs)
assert log_softmax([0.,-math.inf]) == [0.,-math.inf]
assert math.isfinite(log_softmax([0.,-1000.])[1])
assert math.exp(log_softmax([0.,-1000.])[1]) == 0.
for x in [[],[-math.inf],[math.inf],[math.nan]]:
    try:
        log_softmax(x)
    except ValueError:
        pass
    else:
        raise AssertionError("invalid normalization accepted")

Both routines cost O(n)O(n) arithmetic operations and storage. The reduction’s rounded scalar result is not always safe to subtract from enormous original logits. For two identical scores of 101610^{16}, adding log⁡2\log2 to that maximum can round back to 101610^{16}. Then x - logsumexp(x) would give zero, although each log probability should be −log⁡2-\log2. log_softmax instead subtracts log_total from the already shifted values, preserving that difference.

The code implements an unweighted real vector reduction, not all the axes, broadcasting, signed weights, or complex arguments of SciPy’s routine. Those options require their own conventions. SciPy logsumexp documentation

A finite log probability can exponentiate to zero

For scores (0,−1000)(0,-1000), the second log probability remains a finite number near −1000. Its probability is positive in exact arithmetic but underflows to zero in binary64. Keeping logs avoids taking log(0) after that information loss. Extremely wide finite score differences can themselves overflow to negative infinity when subtracting the maximum; a float output cannot represent a log probability outside its own range.

The value of L with a positive-infinite score is unambiguously positive infinity, but normalizing multiple infinities is not uniquely determined by their symbolic values. Different finite sequences approaching those infinities can retain different score gaps and therefore different limiting probabilities. An all-masked vector has no probability distribution to normalize. This implementation rejects those normalization inputs rather than quietly inventing a distribution.

For a target class y, the loss is L(x)−xyL(x)-x_y. Implement it as (m−xy)+log⁡∑iexi−m(m-x_y)+\log\sum_i e^{x_i-m} or take the negative of a directly computed log-softmax value, with the same domain and range considerations. A mathematically invariant shift should not be allowed to destroy the small loss through a final subtraction of huge rounded numbers.

Keep track of the operation

  1. What is L(0,0,0)L(0,0,0)? Answer: log⁡3\log3, while each normalized probability is one third.
  2. Why not subtract the mean instead of the maximum? Answer: mean shifting preserves the exact value after compensation but can leave a very large positive exponent and still overflow.
  3. Is L strictly convex along the all-ones direction? Answer: no. A common shift changes L linearly and has zero second derivative.
  4. Two logits are both 101610^{16}. What are their log probabilities? Answer: both are −log⁡2-\log2, which the directly shifted normalization retains.

A small identity inside many models

Log-space dynamic programming, energy-based normalization, and probabilistic mixture calculations repeatedly use this identity. A useful implementation test combines moderate-input comparisons, extreme magnitudes, masks, translation behavior, and a finite-difference gradient check. The softmax article explains probability normalization, while numerical stability explains why algebraically equivalent expressions can behave differently on a machine.

Make a prediction, then check

Two logits are both 10¹⁶. What is each log probability?

Choose one answer

Learning objectives

  • Derive maximum shifting, value bounds, and the softmax gradient.
  • Handle masks, infinities, and log probabilities under huge common shifts.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Chapter 4: Numerical Computation
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. SciPy — scipy.special.logsumexp
    SciPy developers
  3. Convex Optimization
    Stephen Boyd; Lieven Vandenberghe · 2004

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: specified-source comparison, derivation checks, independent numerical checks, and paragraph-level bilingual comparison; no independent human peer review.

  • Compared 80 vectors against 100-digit Decimal and finite-differenced softmax gradients on 30 four-dimensional inputs; checked normalization, masks, empty inputs, infinity and NaN policies.
  • Verified direct log-softmax retains −log2 under a 10¹⁶ common shift; derived convexity from weighted variance and retained the all-ones null direction and extreme-difference range limitation.
  • Compared bilingual assumptions, claims, numbers, exercise answers and citations; structural checks additionally compare formulas, code, main anchors and source IDs.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.