Numerical methods
Log-sum-exp
num.log-sum-expAlso called log sum exp, logsumexp, lse, log add exp
Log of a sum of exponentials, a smooth maximum. Computing it as written overflows once an entry exceeds about 709; the stable form m + ln Σ exi − m, with m the largest entry, gives the same value for every input.
Notation
values (logits or log-probabilities)
x ∈ ℝn
number of values
Size, at least 1
Result: the log of the sum of exponentials
scalar
Worked examples
Each result is solved exactly and confirmed by two independent computations.
Given
Result
≈ 0.69314718056
Given
Result
≈ 3.40760596444
Given
Result
≈ 1000.69314718
Given
Result
≈ -998.901387711
Common mistakes
Exponentiates without shifting by the maximum
exp overflows to inf for entries above about 709 and underflows to 0 below about −745, so the result becomes inf or −inf.
Fix: Subtract the maximum m before exponentiating and add it back: m + ln Σ exp(xi − m), or call scipy.special.logsumexp.
Shifts by the maximum but does not add it back
The result is ln Σ exp(xi − m), short by the maximum m.
Fix: Add the maximum back after taking the log.
Sources
Blanchard et al. 2021
Blanchard, Pierre; Higham, Desmond J.; Higham, Nicholas J. Accurately computing the log-sum-exp and softmax functions. IMA Journal of Numerical Analysis 41(4): 2311-2330, 2021. doi:10.1093/imanum/draa038
Goodfellow et al. 2016, §4.1
Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron. Deep Learning. MIT Press, 2016.