Post · 2 min read· pp. 37–38

LogSumExp and Its Numerical Stability

Introduction

When we do large number or small number multiplications, it is easy to overflow or underflow in computer programs so that we would not get our expected result. To avoid these situations, people tend to do all the multiplications in the log domain.

For example, a=e1000a = e^{1000} and b=e2000b = e^{2000}, and we would like to know abab. Instead of calculating the explosive abab, we have log⁡a=1000\log a = 1000, log⁡b=2000\log b = 2000, and log⁡ab=\log ab = log⁡a+log⁡b=\log a + \log b = $1000 + 2000 = 3000$. Similarly, when a=e−1000a = e^{-1000} and b=e−2000b = e^{-2000}, we have log⁡a=−1000\log a = -1000, log⁡b=−2000\log b = -2000, and $\log ab = $ log⁡a+log⁡b=\log a + \log b = −1000−2000=−3000-1000 - 2000 = -3000.

We would not jump out of the log domain unless it is the final step. However, how should we calculate the log of the sum of exponentials (logsumexp) without leaving the log domain? More formally, given log⁡x1,log⁡x2,…,log⁡xn\log x_1, \log x_2, …, \log x_n, how to calculate log⁡∑i=1nxi\log \sum_{i = 1}^{n} x_i?

Incorrect Approach

log⁡∑i=1nxi=log⁡∑i=1nelog⁡xi\log \sum_{i = 1}^{n} x_i = \log \sum_{i = 1}^{n} e^{\log x_i}

This is not the correct approach. If one of log⁡xi\log x_i is extremely large, you would be just calculating log⁡∞\log \infty in the computer program. On the other hand, if all the log⁡xi\log x_i are extremely small, you would be just calculating log⁡0\log 0 in the computer program. In either case, there would be a problem.

Correct Approach

log⁡∑i=1nxi=log⁡∑n=1Nelog⁡xi=log⁡(ea×∑n=1Nelog⁡xi−a)=a+log⁡∑n=1Nelog⁡xi−a\log \sum_{i = 1}^{n} x_i = \log \sum_{n = 1}^{N} e^{\log x_i} = \log (e^{a} \times \sum_{n = 1}^{N} e^{\log x_i - a}) = a + \log \sum_{n = 1}^{N} e^{\log x_i - a}

where a=max⁡(log⁡x1,log⁡x2,…,log⁡xn)a = \max(\log x_1, \log x_2, …, \log x_n).

If at least one of the log⁡xi\log x_i is extremely large, the value of elog⁡xi−ae^{\log x_i - a} would not be greater than 1.0. If all the log⁡xi\log x_i are extremely small, there would be at least one elog⁡xi−ae^{\log x_i - a} that is equal to 1.0, and the rest of elog⁡xi−ae^{\log x_i - a} might be very close or equal to 0. Taken together, ∑n=1Nelog⁡xi−a\sum_{n = 1}^{N} e^{\log x_i - a} is always in a range of [1, N].

Therefore, when it comes to computer program, instead of using log⁡∑i=1nelog⁡xi\log \sum_{i = 1}^{n} e^{\log x_i}, we use a+log⁡∑n=1Nelog⁡xi−aa + \log \sum_{n = 1}^{N} e^{\log x_i - a} to calculate the logsumexp without jumping out of the log domain.

Miscellaneous

The overflow and underflow problems are common in many problems such as machine learning, hidden Markov model and other probabilistic models. One should be careful handling these problems when implementing something from scratch.

SciPy has the logsumexp function that is ready for use.