Log-Sum-Exp
Log-sum-exp is the stable way to compute:
The direct computation can overflow because of e^{x_i}.
Stable Form
Let:
Then:
The shifted exponentials are safer because the largest shifted value is 0.
The added m restores the scale that was removed before exponentiation. Without
adding it back, the result would describe the shifted numbers, not the original
numbers.
A Small Example
For [3, 9, 4], the maximum is 9.
The shifted values are [-6, 0, -5].
Then:
The largest exponential on the right is e^0 = 1, which is safe.
ML Reading
Log-sum-exp appears in softmax, cross-entropy, likelihoods, and probabilistic models.
It is a core example of stable numerical rewriting.
The stable form is useful for the same reason stable softmax is useful: it controls exponentials before they can overflow. The added maximum is what keeps the final answer tied to the original scale.
For values [3, 9, 4], what is m in the stable log-sum-exp formula?
Compute it first, then check your number.
Hint
m is the maximum value.Solution
The maximum is 9. Choosing the maximum as the shift makes every shifted value
less than or equal to zero, which keeps the exponentials safer.
For values [3, 9, 4], what is the largest value after subtracting m = 9?
Compute it first, then check your number.
Hint
The maximum value is subtracted from itself.
Solution
The largest shifted value is 9 - 9 = 0. This is the key safety property:
after shifting, the largest exponential is e^0 = 1.
In the stable log-sum-exp formula, do we add m back after taking the log?
Answer it first, then check.
Hint
The shift changed the scale before exponentiation.
Solution
Yes. We add m back so the result matches the original unshifted expression.
Why is the shifted form safer?
Enter 1 for because the largest shifted exponential is e^0, or 2 for
because logarithms stop needing exponentials.
Compute it first, then check your number.
Hint
The formula still uses exponentials, but on shifted values.
Solution
The largest shifted value is 0, so the largest shifted exponential is
e^0 = 1. Enter 1.
Enter 1 if forgetting to add m back would compute the log-sum-exp of the
shifted values, not the original values.
Compute it first, then check your number.
Hint
Ask what quantity remains if the removed scale is never restored.
Solution
Enter 1. Subtracting m makes exponentiation safer, but adding m back is
needed to recover the original unshifted log-sum-exp.
Before Moving On
Log-sum-exp is stable because it shifts before exponentiating.