A training loss that turns into nan halfway through an epoch, a probability that comes out as exactly 0, a loss of inf from one confident wrong prediction: most of these come from a handful of expressions such as $\log(1 + x)$, $e^x - 1$ and $\log \sum_i e^{x_i}$, which are right on paper and wrong in floating point. This post is my catalogue of them. For each one I show the naive version, an input where it fails, and the one-line library function that does not.
Introduction
Numerical expressions are widely used in the field of data science. They are used to perform mathematical operations on data. However sometimes, the results of these operations are not as expected. This is because of the way computers store numbers and perform operations on them. This blog will help you understand how these operations are performed and how to avoid errors.
Floating Point Numbers
Computers store numbers in binary format. This means that the numbers are stored in the form of 0s and 1s. This is called the binary representation of the number. For example, the number 5 is stored as 101 in binary format. The number 101 is a 3 digit number. This means that the computer uses 3 bits to store the number 5. Similarly, the number 10 is stored as 1010 in binary format.
Often, the number of bits used to store a number is fixed. This means that the computer uses the same number of bits to store all numbers. For example, if the computer uses 8 bits to store a number, then the number 5 will be stored as 00000101. This is called the integer representation of the number, and negative integers are stored in two's complement, so $-5$ in 8 bits is 11111011. (Fixed point is a different thing: it also uses a fixed number of bits, but reserves a fixed number of them for the fractional part.) For the float data type, if the computer uses 16 bits to store a number (float16, half precision), then the number 5 will be stored as 0100010100000000 and the number 0.001 will be stored as 0001010000011001.
This is called the floating point representation of the number.
- The first bit is used to store the sign of the number. The sign is 0 for positive numbers and 1 for negative numbers.
- The next 5 bits are used to store the exponent of the number. It is used to shift the decimal point of the number.
- The last 10 bits are used to store the mantissa of the number. It is used to store the fractional part of the number.
Together, the three fields give the value
where $s$ is the sign bit, $e$ is the exponent bits read as a whole number, $m$ is the mantissa bits read as a binary fraction $0.m_1 m_2 \ldots$, and the bias is 15 for float16. For example, $5 = 1.01_2 \times 2^2$, so $s = 0$, $e = 2 + 15 = 17 = 10001_2$ and $m = 0.01_2$, which is stored as 0100000000: together, 0 10001 0100000000. float32 and float64 use the same layout with more bits, as the figure shows. (This holds for every number except zero, the infinities, nan and the very smallest numbers, called subnormal, which use the two extreme exponent patterns.)
import math
import warnings
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
from scipy.special import xlog1py, xlogy
pio.renderers.default = "plotly_mimetype+notebook_connected"
# Warnings stay on, because they are what this post is about. This only prints each one
# as a single line, without the temporary file name of the notebook cell in front of it.
warnings.formatwarning = lambda message, category, *args, **kwargs: f"{category.__name__}: {message}\n"
Show code
formats = ["float16", "float32", "float64"]
fields = {"sign": [1, 1, 1], "exponent": [5, 8, 11], "mantissa": [10, 23, 52]}
biases = [15, 127, 1023]
fig = go.Figure()
for name, widths in fields.items():
fig.add_bar(y=formats, x=widths, name=name, orientation="h",
text=[str(w) for w in widths], textposition="inside", insidetextanchor="middle",
hovertemplate="%{y}: %{x} " + name + " bits<extra></extra>")
fig.update_layout(barmode="stack", height=320, margin=dict(t=56),
title="value = (−1)<sup>s</sup> × 2<sup>e − bias</sup> × (1 + m)",
uniformtext=dict(minsize=11, mode="hide"), legend_traceorder="normal")
fig.update_xaxes(title_text="bits", range=[0, 64], dtick=8)
fig.update_yaxes(autorange="reversed", tickvals=formats,
ticktext=[f"{f}<br>bias {b}" for f, b in zip(formats, biases)])
fig.show()import numpy as np
for dtype in (np.float16, np.float32, np.float64):
for v in (5.0, 0.001):
x = dtype(v)
bits = np.array(x).view({np.float16: np.uint16, np.float32: np.uint32, np.float64: np.uint64}[dtype])
width = np.dtype(dtype).itemsize * 8
b = format(int(bits), f"0{width}b")
print(f"{dtype.__name__:8s} {v:<6} {b} stored value = {float(x)!r}")
float16 5.0 0100010100000000 stored value = 5.0 float16 0.001 0001010000011001 stored value = 0.0010004043579101562 float32 5.0 01000000101000000000000000000000 stored value = 5.0 float32 0.001 00111010100000110001001001101111 stored value = 0.0010000000474974513 float64 5.0 0100000000010100000000000000000000000000000000000000000000000000 stored value = 5.0 float64 0.001 0011111101010000011000100100110111010010111100011010100111111100 stored value = 0.001
Here we can see that with 16 bits the number 5 is stored as 0100010100000000, which is exactly 5, and the number 0.001 is stored as 0001010000011001, which is really 0.0010004043579101562, the nearest float16 to 0.001. This means that the computer can store only a limited number of significant binary digits. This is called the precision of the number. The precision of the number is determined by the number of bits used to store the number. The more bits used to store the number, the higher the precision of the number: float32 stores 0.001 as 0.0010000000474974513, right to about 7 significant digits, and float64 is right to about 16. The default bits used to store a number in Python is 64 bits.
Rounding Error
Each operation rounds its exact result to the nearest representable number, and the rounding errors can accumulate. This is called the rounding error. This happens because the computer uses a limited number of bits to store the result of the operation. This means that the computer cannot store the exact result of the operation. It can only store an approximation of the result, and the difference between the two is the rounding error.
Sometimes, just the order of operations can cause a rounding error. For example, for an extremely small positive number $x$, $(x + 1) - 1$ is not equal to $x$. This is because the computer first adds $1$ to $x$, and $x + 1$ rounds to exactly $1$, so subtracting $1$ gives $0$. However, $(1 - 1) + x$ is exactly $x$, because $1 - 1 = 0$ is exact. This was just a very simple example. However, in some cases, the cause of the rounding error is not so obvious. We will see such cases in this blog.
x = 1e-20
print(f"(x + 1) - 1 = {(x + 1) - 1}")
print(f"(1 - 1) + x = {(1 - 1) + x}")
(x + 1) - 1 = 0.0 (1 - 1) + x = 1e-20
The same rounding is why the decimal fractions we type are not stored exactly. 0.1, 0.2 and 0.3 have no finite binary expansion, so each one is rounded, and the rounding errors do not cancel:
print(0.3, 3 * 0.1)
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3), np.isclose(0.1 + 0.2, 0.3))
0.3 0.30000000000000004 0.30000000000000004 False True True
So two floats that should be equal often differ in the last bit, and comparing them with == is a bug. Compare them with a tolerance instead: math.isclose and np.isclose check whether the two numbers agree to within a small relative tolerance (more on these in Machine Epsilon and Comparisons).
Softplus
In machine learning, we often use the softplus activation function. It is a smooth approximation to the relu function.
It is defined as:
The inverse of the softplus function is the softminus function. It is defined as:
def basic_softplus(x):
return np.log(1 + np.exp(x))
def relu(x):
return np.maximum(x, 0)
x = np.linspace(-5, 5, 1000)
y1 = (basic_softplus(x))
y2 = (relu(x))
fig = px.line(title="Softplus function")
fig.add_scatter(x=x, y=y1, name="Softplus")
fig.add_scatter(x=x, y=y2, name="ReLU")
fig.show()
For large negative values of $x$, the softplus function reaches almost $0$.
For small positive values of $x$, the softminus function reaches almost $-\infty$.
Written as np.log(1 + np.exp(x)), softplus breaks at both ends.
- For $x$ below about $-36.7$, $e^x$ is less than half the gap between $1$ and the next float, so
1 + np.exp(x)rounds to exactly1and the logarithm is0, although the true value is about $e^x$. Even before that, most of the digits of $e^x$ are lost when it is added to $1$. - For $x$ above about $709.78$, the logarithm of the largest
float64,np.exp(x)overflows toinf(infloat32this already happens at about $88.7$).
The fix is to notice that $\log(1 + e^x) = \log(e^0 + e^x)$, which is exactly what np.logaddexp(0, x) computes, without ever forming $e^x$. Written out: for $x > 0$ we take $x$ out of the logarithm, $\log(1 + e^x) = x + \log(1 + e^{-x})$, and for $x \le 0$ we leave it in, so in both cases
The exponent $-|x|$ is never positive, so $e^{-|x|}$ cannot overflow, and the $\log(1 + \cdot)$ is computed with np.log1p (see the next section).
def stable_softplus(x):
return np.logaddexp(0.0, x) # = log(exp(0) + exp(x)), safe at both ends
# equivalent explicit form
def stable_softplus_explicit(x):
return np.maximum(x, 0) + np.log1p(np.exp(-np.abs(x)))
x = np.linspace(-38, -33, 1000)
y1 = np.log(basic_softplus(x))
y2 = np.log(stable_softplus(x))
fig = px.line(title="Naive softplus underflows to 0; the log of it is -inf")
fig.add_scatter(x=x, y=y1, name="Basic softplus")
fig.add_scatter(x=x, y=y2, name="Numerically stable softplus")
fig.show()
RuntimeWarning: divide by zero encountered in log
fig = px.line(title="Difference between Log Softplus and Log Stable Softplus")
fig.add_scatter(x=x, y=(y1 - y2))
fig.show()
Here, we can see that defining the softplus function like basic_softplus causes a rounding error. In this range it can only return whole multiples of $2.2 \times 10^{-16}$ (the gap between $1$ and the next float), which makes the staircase, flat at $2.2 \times 10^{-16}$ from about $x = -35.6$, and below $x \approx -36.7$ it returns exactly 0, so its logarithm is $-\infty$ and its curve stops. The RuntimeWarning above is NumPy telling us that it took the logarithm of zero. stable_softplus stays on the straight line $\log(\text{softplus}(x)) \approx x$. We will get more understanding about that in the following sections.
The table checks both ends, with np.log1p(np.exp(x)), a common halfway fix, in the middle column:
def log1p_exp_softplus(x):
return np.log1p(np.exp(x))
xs = np.array([-800.0, -40.0, 0.0, 40.0, 800.0])
table = pd.DataFrame({
"basic: log(1 + exp(x))": basic_softplus(xs),
"log1p(exp(x))": log1p_exp_softplus(xs),
"logaddexp(0, x)": stable_softplus(xs),
}, index=pd.Index(xs, name="x"))
table.map("{:.6g}".format)
RuntimeWarning: overflow encountered in exp RuntimeWarning: overflow encountered in exp
| basic: log(1 + exp(x)) | log1p(exp(x)) | logaddexp(0, x) | |
|---|---|---|---|
| x | |||
| -800.0 | 0 | 0 | 0 |
| -40.0 | 0 | 4.24835e-18 | 4.24835e-18 |
| 0.0 | 0.693147 | 0.693147 | 0.693147 |
| 40.0 | 40 | 40 | 40 |
| 800.0 | inf | inf | 800 |
The two RuntimeWarnings are real: np.exp(800) overflows in both of the first two versions, and they return inf. At $x = -40$ the basic version returns 0 instead of $4.2 \times 10^{-18}$, which log1p fixes, but only logaddexp is right at both ends. To be sure that the stable versions do not just hide a warning, here they are again with every warning turned into an error, so the cell would stop if either of them raised one:
with warnings.catch_warnings():
warnings.simplefilter("error") # any warning now raises an exception and stops the cell
for x in (-800.0, 800.0):
print(f"x = {x}: stable_softplus = {stable_softplus(x)}, "
f"stable_softplus_explicit = {stable_softplus_explicit(x)}")
print(stable_softplus(800.0) == 800.0)
x = -800.0: stable_softplus = 0.0, stable_softplus_explicit = 0.0 x = 800.0: stable_softplus = 800.0, stable_softplus_explicit = 800.0 True
$\log(1+x)$
Limit
Taylor Series Expansion
Therefore, $\log(1+x) \approx x$ for small $x$ as the other terms become negligibly tiny.
The log1p function is a useful tool for calculating the logarithm of $1+x$, particularly when $x$ is a small value. It helps avoid numerical instability issues that can arise when directly computing np.log(1 + x) when $x$ is close to zero. By using np.log1p, you can achieve a more accurate and stable calculation of the logarithm.
How could we compute it ourselves? my_log1p below uses a trick usually credited to William Kahan. u = 1 + x is rounded, so it loses the low bits of x, but u - 1 is computed exactly, so it tells us precisely which number was really added to $1$. np.log(u) is an accurate logarithm of that rounded value, and because $\log(1 + t)/t$ barely changes near $t = 0$, multiplying it by x / (u - 1) rescales it to the logarithm of $1 + x$ that we wanted.
def my_log1p(x):
if np.isinf(x) and x > 0:
return x
u = 1. + x
d = u - 1.
if d == 0:
return x
return np.log(u) * x / d
xs = np.logspace(-20, 0, 1000)
mine = np.array([my_log1p(v) for v in xs])
rel_diff = np.abs(mine - np.log1p(xs)) / np.log1p(xs)
print(f"largest relative difference from np.log1p: {rel_diff.max():.1e}")
print(f"agrees with np.log1p to 1e-15 everywhere: {np.allclose(mine, np.log1p(xs), rtol=1e-15, atol=0)}")
largest relative difference from np.log1p: 2.8e-16 agrees with np.log1p to 1e-15 everywhere: True
So my_log1p agrees with np.log1p to within about one unit in the last place over twenty orders of magnitude. To see how much np.log(1 + x) loses, we compare both with the exact value, which mpmath computes with 50 significant digits:
import mpmath
mpmath.mp.dps = 50 # 50 significant digits: exact as far as float64 can tell
# (the series x - x**2/2 + x**3/3 would do only for x below about 1e-5)
def relative_error(approx, x, exact_fn):
"""|approx - exact| / |exact|, with the exact value computed by mpmath."""
out = []
for a, v in zip(approx, x):
exact = exact_fn(mpmath.mpf(float(v)))
out.append(float(abs(mpmath.mpf(float(a)) - exact) / abs(exact)))
return np.array(out)
x = np.logspace(-18, -2, 400)
rel_naive = relative_error(np.log(1 + x), x, mpmath.log1p)
rel_log1p = relative_error(np.log1p(x), x, mpmath.log1p)
big = x > 1.1e-16
# The same colours as the two-panel figure further down: orange for naive, blue for the library.
fig = go.Figure()
fig.add_scatter(x=x, y=rel_naive, name="np.log(1 + x)", line_color="#C75716")
fig.add_scatter(x=x, y=rel_log1p, name="np.log1p(x)", line_color="#5C86B0")
fig.add_scatter(x=x[big], y=1.1e-16 / x[big], name="rule of thumb: 1.1e-16 / x", line_dash="dot",
line_color="#8A93A6")
fig.update_xaxes(type="log", title_text="x", exponentformat="power")
fig.update_yaxes(type="log", title_text="relative error", exponentformat="power")
fig.update_layout(title="Relative error of log(1 + x)")
fig.show()
np.log(1 + x) does not give 0 for small $x$; it is inaccurate. $1 + x$ is rounded to the nearest float, so only the digits of $x$ that survive that rounding reach the logarithm, and the relative error is roughly $1.1 \times 10^{-16}/x$. As a rule of thumb, the naive form loses roughly $-\log_{10}(x)$ of the 16 significant digits of a float64: about 10 of them at $x = 10^{-10}$. It becomes exactly 0 only when $1 + x$ rounds to $1$, below $x \approx 1.1 \times 10^{-16}$, where the error is 100%. np.log1p(x) is right to the last digit everywhere.
float32 versus float64
Everything so far was in float64, the Python default. Neural networks are usually trained in float32, which keeps 24 significant bits instead of 53, so the same cliff arrives much sooner. $1 + x$ rounds to exactly $1$ as soon as $x$ is no more than half the gap between $1$ and the next float:
for dtype in (np.float32, np.float64):
one = dtype(1)
half_gap = dtype(np.finfo(dtype).eps / 2) # half the gap between 1 and the next float
assert one + half_gap == one # a tie, rounded to the even neighbour, 1
assert one + np.nextafter(half_gap, one) > one
print(f"{dtype.__name__}: 1 + x == 1 for every x up to "
f"{float(half_gap):.3g} = 2^{int(np.log2(half_gap))}")
for v in (1e-4, 1e-6):
v32 = np.array([v], dtype=np.float32)
err = relative_error(np.log(np.float32(1) + v32), v32, mpmath.log1p)[0]
print(f"float32, x = {v:g}: np.log(1 + x) has relative error {err:.1e}")
float32: 1 + x == 1 for every x up to 5.96e-08 = 2^-24 float64: 1 + x == 1 for every x up to 1.11e-16 = 2^-53 float32, x = 0.0001: np.log(1 + x) has relative error 1.7e-04 float32, x = 1e-06: np.log(1 + x) has relative error 4.6e-02
# The same 400 points as above, rounded to float32; every step stays in float32.
x32 = x.astype(np.float32)
naive32 = np.log(np.float32(1) + x32)
library32 = np.log1p(x32)
assert naive32.dtype == library32.dtype == np.float32
rel_naive32 = relative_error(naive32, x32, mpmath.log1p)
rel_log1p32 = relative_error(library32, x32, mpmath.log1p)
# Colour is the function (as before), the line style is the type.
fig = go.Figure()
for xs, naive, library, dash, kind in ((x32, rel_naive32, rel_log1p32, "solid", "float32"),
(x, rel_naive, rel_log1p, "dot", "float64")):
fig.add_scatter(x=xs, y=naive, name=f"np.log(1 + x), {kind}", line_color="#C75716", line_dash=dash)
fig.add_scatter(x=xs, y=library, name=f"np.log1p(x), {kind}", line_color="#5C86B0", line_dash=dash)
fig.update_xaxes(type="log", title_text="x", exponentformat="power")
fig.update_yaxes(type="log", title_text="relative error", exponentformat="power")
fig.update_layout(title="float32 against float64")
fig.show()
In float32 the cliff arrives at $x = 2^{-24} \approx 6 \times 10^{-8}$ instead of $1.1 \times 10^{-16}$, and the relative error of the naive form is roughly $6 \times 10^{-8}/x$, out of only about 7 significant digits to begin with. Values that are not small at all by float64 standards are already damaged: at $x = 10^{-4}$ the naive result has a relative error of $1.7 \times 10^{-4}$, and at $x = 10^{-6}$ it is off by 4.6%. np.log1p stays within about $6 \times 10^{-8}$, the best a float32 can do, everywhere.
$e^x - 1$
Limit
Taylor Series Expansion
Therefore, $e^x - 1 \approx x$ for very small $x$ as the other terms become negligibly tiny.
When dealing with small values, using the expression np.exp(x) - 1 can result in a loss of precision. In such cases, the function np.expm1(x) is a better alternative as it provides a more accurate result that preserves the precision of the small input value $x$.
The same trick works for my_expm1. u = np.exp(x) is rounded, but it is the exact exponential of $y = \log(u)$, a number very close to $x$, and u - 1 is computed exactly, so u - 1 is exactly $e^y - 1$. Because $(e^t - 1)/t$ barely changes near $t = 0$, multiplying by x / np.log(u) rescales it from $y$ back to $x$.
def my_expm1(x):
if np.isinf(x) and x > 0:
return x
u = np.exp(x)
d = u - 1.
if d == 0:
return x
return d * x / np.log(u)
xs = np.logspace(-20, 0, 1000)
mine = np.array([my_expm1(v) for v in xs])
rel_diff = np.abs(mine - np.expm1(xs)) / np.expm1(xs)
print(f"largest relative difference from np.expm1: {rel_diff.max():.1e}")
print(f"agrees with np.expm1 to 1e-15 everywhere: {np.allclose(mine, np.expm1(xs), rtol=1e-15, atol=0)}")
largest relative difference from np.expm1: 3.1e-16 agrees with np.expm1 to 1e-15 everywhere: True
rel_naive_exp = relative_error(np.exp(x) - 1, x, mpmath.expm1)
rel_expm1 = relative_error(np.expm1(x), x, mpmath.expm1)
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.12,
subplot_titles=("log(1 + x) against log1p(x)", "exp(x) − 1 against expm1(x)"))
# One colour for each kind of line, so the two panels read the same way.
panels = [(rel_naive, rel_log1p), (rel_naive_exp, rel_expm1)]
for row, (naive, library) in enumerate(panels, start=1):
fig.add_scatter(x=x, y=naive, name="naive formula", line_color="#C75716",
legendgroup="naive", showlegend=row == 1, row=row, col=1)
fig.add_scatter(x=x, y=library, name="library function", line_color="#5C86B0",
legendgroup="library", showlegend=row == 1, row=row, col=1)
fig.update_yaxes(type="log", title_text="relative error", exponentformat="power", row=row, col=1)
fig.update_xaxes(type="log", exponentformat="power")
fig.update_xaxes(title_text="x", row=2, col=1)
fig.update_annotations(font_size=13)
fig.update_layout(height=560)
fig.show()
Here we see that np.exp(x) - 1 fails exactly like np.log(1 + x): $e^x$ is rounded to a float close to $1$, subtracting $1$ cancels the leading digits, and the result loses roughly $-\log_{10}(x)$ digits. It becomes exactly 0 only below $x \approx 1.1 \times 10^{-16}$, where $e^x$ rounds to $1$. np.expm1(x) keeps every digit. This matters in practice: the KL divergence between two normal distributions in TensorFlow Probability uses expm1 for exactly this reason (see KL-Divergence).
$x \log(y)$
When $x = 0$ and we are calculating $x \log(y)$, we want the result to be $0$ regardless of the value of $y$. However, if $y = 0$, then the result is undefined. Therefore, we need to handle this case separately.
In this case, using the expression x * log(y) gives a result of nan. Here, xlogy(x, y) is a better alternative as it first checks if $x = 0$ and returns 0 if that is the case. Otherwise, it returns x * log(y).
def xlogyf(x, y):
print(f"x = {x}, y = {y}")
print(f"x * log(y) = {x * np.log(y)}")
print(f"xlogy(y) = {xlogy(x, y)}")
print()
xlogyf(5, 10)
xlogyf(0, 10)
xlogyf(5, 0)
xlogyf(0, 0)
x = 5, y = 10 x * log(y) = 11.51292546497023 xlogy(y) = 11.51292546497023 x = 0, y = 10 x * log(y) = 0.0 xlogy(y) = 0.0 x = 5, y = 0 x * log(y) = -inf xlogy(y) = -inf x = 0, y = 0 x * log(y) = nan xlogy(y) = 0.0
RuntimeWarning: divide by zero encountered in log RuntimeWarning: invalid value encountered in scalar multiply
The two RuntimeWarnings come from the naive expression: np.log(0) is $-\infty$, and $0 \times (-\infty)$ is nan.
We can use this xlogy function (and divide by $\log(2)$ to get bits) when calculating the Cross-Entropy Loss. This is where $x = y = 0$ really happens: the entropy $H(p) = -\sum_i p_i \log p_i$ and the cross-entropy $H(p, q) = -\sum_i p_i \log q_i$ are sums of $x \log y$ terms, a probability vector often has entries equal to $0$, and by convention $0 \log 0 = 0$, because $p \log p \to 0$ as $p \to 0$.
p = np.array([0.5, 0.25, 0.25, 0.0])
q = np.array([0.4, 0.4, 0.2, 0.0])
print(f"naive entropy: {-np.sum(p * np.log(p))}")
print(f"xlogy entropy: {-np.sum(xlogy(p, p)):.4f} nats = {-np.sum(xlogy(p, p)) / np.log(2):.4f} bits")
print(f"naive cross-entropy: {-np.sum(p * np.log(q))}")
print(f"xlogy cross-entropy: {-np.sum(xlogy(p, q)):.4f} nats")
naive entropy: nan xlogy entropy: 1.0397 nats = 1.5000 bits naive cross-entropy: nan xlogy cross-entropy: 1.0896 nats
RuntimeWarning: divide by zero encountered in log RuntimeWarning: invalid value encountered in multiply RuntimeWarning: divide by zero encountered in log RuntimeWarning: invalid value encountered in multiply
One zero entry is enough to make both naive sums nan, each with the same two warnings as before; xlogy gives the right answers.
$x \log(1+y)$
Combining two of the above cases,
- When $x = 0$, we want the result to be $0$ regardless of the value of $y$.
- When $y \approx 0$, we don't want to lose precision or face numerical instability issues.
In this case, using the expression x * log(1 + y) may result in nan or loss of precision. Here, xlog1py(x, y) is a better alternative for the above reasons.
def xlogyp1(x, y):
print(f"x = {x}, y = {y}, y + 1 = {y + 1}")
print(f"x * log(1+y) = {x * np.log(1+y)}")
print(f"xlog1py(y) = {xlog1py(x, y)}")
print()
xlogyp1(10, 9)
xlogyp1(1e20, 1e-16)
xlogyp1(0, 1e-16)
xlogyp1(0, 0)
xlogyp1(0, -1)
x = 10, y = 9, y + 1 = 10 x * log(1+y) = 23.02585092994046 xlog1py(y) = 23.02585092994046 x = 1e+20, y = 1e-16, y + 1 = 1.0 x * log(1+y) = 0.0 xlog1py(y) = 10000.0 x = 0, y = 1e-16, y + 1 = 1.0 x * log(1+y) = 0.0 xlog1py(y) = 0.0 x = 0, y = 0, y + 1 = 1 x * log(1+y) = 0.0 xlog1py(y) = 0.0 x = 0, y = -1, y + 1 = 0 x * log(1+y) = nan xlog1py(y) = 0.0
RuntimeWarning: divide by zero encountered in log RuntimeWarning: invalid value encountered in scalar multiply
In the second case, $\log(1 + 10^{-16}) \approx 10^{-16}$, so the answer should be $10^{20} \times 10^{-16} = 10^4$. The naive expression gives 0, because 1 + 1e-16 rounds to 1 and $\log 1 = 0$, while xlog1py computes the logarithm with log1p and gets 10000.0. In the last case, $\log(1 + (-1)) = \log 0 = -\infty$ and $0 \times (-\infty)$ is nan (the two warnings), while xlog1py returns 0 because $x = 0$.
$\log(e^{x} + e^{y})$
The generalisation of $\log(1+y)$ is $\log(e^{x} + e^{y})$. Just like the above cases, we want to avoid loss of precision and numerical instability issues. Therefore, instead of using np.log(np.exp(x) + np.exp(y)), we can use np.logaddexp(x, y) as it is a better alternative.
def logpexp(x, y):
print(f"x = {x}, y = {y}")
print(f"exp(x) = {np.exp(x)}, exp(y) = {np.exp(y)}")
print(f"log(exp(x) + exp(y)) = {np.log(np.exp(x) + np.exp(y))}")
print(f"logaddexp(x, y) = {np.logaddexp(x, y)}")
print()
logpexp(10, 9)
logpexp(1e20, 1e-16)
logpexp(0, 1e-16)
logpexp(0, 0)
logpexp(0, -1)
x = 10, y = 9 exp(x) = 22026.465794806718, exp(y) = 8103.083927575384 log(exp(x) + exp(y)) = 10.313261687518223 logaddexp(x, y) = 10.313261687518223 x = 1e+20, y = 1e-16 exp(x) = inf, exp(y) = 1.0 log(exp(x) + exp(y)) = inf logaddexp(x, y) = 1e+20 x = 0, y = 1e-16 exp(x) = 1.0, exp(y) = 1.0 log(exp(x) + exp(y)) = 0.6931471805599453 logaddexp(x, y) = 0.6931471805599454 x = 0, y = 0 exp(x) = 1.0, exp(y) = 1.0 log(exp(x) + exp(y)) = 0.6931471805599453 logaddexp(x, y) = 0.6931471805599453 x = 0, y = -1 exp(x) = 1.0, exp(y) = 0.36787944117144233 log(exp(x) + exp(y)) = 0.31326168751822286 logaddexp(x, y) = 0.31326168751822286
RuntimeWarning: overflow encountered in exp RuntimeWarning: overflow encountered in exp
In the second case,
and the last term is about $e^{-10^{20}}$, far too small to change $10^{20}$, so the answer is 1e+20. The naive version overflows at np.exp(1e20) (the two warnings, one from printing exp(x) and one from inside the logarithm) and returns inf. np.logaddexp takes the larger argument out of the logarithm first, the same trick as in the stable softplus.
Log-Sum-Exp and Softmax
np.logaddexp handles two numbers. For many numbers the same quantity is the log-sum-exp, $\log \sum_i e^{x_i}$, and its close relative is the softmax, which turns a vector of scores into probabilities:
Written like that, both overflow as soon as one $x_i$ is above about $709.78$, and the softmax becomes $\infty / \infty$, which is nan. If every $x_i$ is very negative, every $e^{x_i}$ underflows to $0$ and the softmax becomes $0/0$, which is nan too. The fix is to subtract the maximum $c = \max_j x_j$ first. This does not change the result, because the factor $e^{-c}$ cancels:
After the shift the largest exponential is $e^0 = 1$, so nothing overflows, and the denominator is at least $1$, so it cannot be $0$. In the same way, $\log \sum_j e^{x_j} = c + \log \sum_j e^{x_j - c}$.
def naive_softmax(x):
e = np.exp(x)
return e / e.sum()
def softmax(x):
e = np.exp(x - np.max(x)) # the largest exponential is now exp(0) = 1
return e / e.sum()
for scores in ([1.0, 2.0, 3.0], [1000.0, 1000.0, 1000.0], [-1000.0, -1000.0, -1000.0]):
scores = np.array(scores)
print(f"x = {scores}")
print(f" naive: {naive_softmax(scores)}")
print(f" stable: {softmax(scores)}")
x = [1. 2. 3.] naive: [0.09003057 0.24472847 0.66524096] stable: [0.09003057 0.24472847 0.66524096] x = [1000. 1000. 1000.] naive: [nan nan nan] stable: [0.33333333 0.33333333 0.33333333] x = [-1000. -1000. -1000.] naive: [nan nan nan] stable: [0.33333333 0.33333333 0.33333333]
RuntimeWarning: overflow encountered in exp RuntimeWarning: invalid value encountered in divide
For [1000, 1000, 1000] the naive version overflows (the first warning) and then divides inf by inf (the second). For [-1000, -1000, -1000] it divides $0$ by $0$, silently this time, because Python shows a given warning only once for each line of code. The stable version gives $[1/3, 1/3, 1/3]$ in both cases. In practice the libraries do this for us: scipy.special.logsumexp and scipy.special.softmax in SciPy, and torch.logsumexp and torch.softmax in PyTorch.
import torch
from scipy.special import logsumexp
scores = np.array([1000.0, 1000.0, 1000.0])
print(f"naive log-sum-exp: {np.log(np.sum(np.exp(scores)))}")
print(f"scipy logsumexp: {logsumexp(scores)}")
print(f"torch.logsumexp: {torch.logsumexp(torch.tensor(scores), dim=0).item()}")
print(f"1000 + log(3): {1000 + np.log(3)}")
naive log-sum-exp: inf scipy logsumexp: 1001.0986122886682 torch.logsumexp: 1001.0986122886682 1000 + log(3): 1001.0986122886682
RuntimeWarning: overflow encountered in exp
Sigmoid and BCE from Logits
A binary classifier outputs a score $z$, the logit, turns it into a probability with the sigmoid $\sigma(z) = 1/(1 + e^{-z})$, and is trained with the binary cross-entropy (BCE)
For a confident wrong prediction, say $z = 40$ with the label $y = 0$, $\sigma(40) = 1 - 4.2 \times 10^{-18}$ rounds to exactly 1.0, so $1 - \sigma(z) = 0$ and the loss is $-\log 0 = \infty$. The true loss is about $40$. Working from the logit avoids this. Since $1 - \sigma(z) = \sigma(-z)$ and $-\log \sigma(z) = \log(1 + e^{-z}) = \text{softplus}(-z)$,
which is the stable softplus from above. PyTorch's binary_cross_entropy_with_logits computes the loss this way. (See Loss Functions for Regression and Classification for where the cross-entropy loss comes from.)
import torch.nn.functional as F
y = torch.tensor(0.0) # the true label
rows = []
for z_value in (0.0, 10.0, 20.0, 40.0):
z = torch.tensor(z_value) # float32, as in a training loop
p = torch.sigmoid(z)
naive = -y * torch.log(p) - (1 - y) * torch.log(1 - p)
rows.append({
"z": z_value,
"exact: softplus(z)": float(np.logaddexp(0.0, z_value)),
"naive formula": naive.item(),
"F.binary_cross_entropy": F.binary_cross_entropy(p, y).item(),
"F.binary_cross_entropy_with_logits": F.binary_cross_entropy_with_logits(z, y).item(),
})
pd.DataFrame(rows).set_index("z").map("{:.7g}".format)
| exact: softplus(z) | naive formula | F.binary_cross_entropy | F.binary_cross_entropy_with_logits | |
|---|---|---|---|---|
| z | ||||
| 0.0 | 0.6931472 | 0.6931472 | 0.6931472 | 0.6931472 |
| 10.0 | 10.00005 | 9.999586 | 9.999586 | 10.00005 |
| 20.0 | 20 | inf | 100 | 20 |
| 40.0 | 40 | inf | 100 | 40 |
The naive formula is already wrong in the fifth digit at $z = 10$, because in float32 the subtraction $1 - \sigma(z)$ cancels most of the digits of $\sigma(z)$, and from $z \approx 17$ on it is inf. F.binary_cross_entropy, which takes probabilities, hides the problem rather than solving it: it clamps the logarithm at $-100$, so every confident mistake costs exactly $100$. F.binary_cross_entropy_with_logits takes the logit and is right everywhere, so give it the raw scores (or use nn.BCEWithLogitsLoss) and leave the sigmoid out of the model.
Catastrophic Cancellation
log(1 + x) and exp(x) - 1 are special cases of a general problem. When two nearly equal numbers are subtracted, their leading digits cancel and only the trailing digits are left, and those are exactly the ones that rounding has already spoiled. The subtraction itself is exact; it is the error already in its inputs that becomes large compared with the small result. The cure is algebra: rewrite the expression so that it no longer subtracts nearly equal numbers. Two classic examples are
for small $x$, and, multiplying above and below by $\sqrt{x + 1} + \sqrt{x}$,
for large $x$.
def row(expression, x, naive, rewritten, exact):
return {"expression": expression, "x": f"{x:g}", "naive": f"{naive:.6g}", "rewritten": f"{rewritten:.6g}",
"naive rel. error": f"{abs(naive - exact) / exact:.1e}",
"rewritten rel. error": f"{abs(rewritten - exact) / exact:.1e}"}
rows = []
for x in (1e-4, 1e-6, 1e-8):
exact = float(1 - mpmath.cos(mpmath.mpf(x)))
rows.append(row("1 - cos(x)", x, 1 - np.cos(x), 2 * np.sin(x / 2) ** 2, exact))
for x in (1e8, 1e12, 1e16):
exact = float(mpmath.sqrt(mpmath.mpf(x) + 1) - mpmath.sqrt(mpmath.mpf(x)))
rows.append(row("sqrt(x + 1) - sqrt(x)", x, np.sqrt(x + 1) - np.sqrt(x), 1 / (np.sqrt(x + 1) + np.sqrt(x)), exact))
pd.DataFrame(rows).set_index(["expression", "x"])
| naive | rewritten | naive rel. error | rewritten rel. error | ||
|---|---|---|---|---|---|
| expression | x | ||||
| 1 - cos(x) | 0.0001 | 5e-09 | 5e-09 | 5.2e-09 | 0.0e+00 |
| 1e-06 | 5.00044e-13 | 5e-13 | 8.9e-05 | 0.0e+00 | |
| 1e-08 | 0 | 5e-17 | 1.0e+00 | 1.2e-16 | |
| sqrt(x + 1) - sqrt(x) | 1e+08 | 5e-05 | 5e-05 | 1.4e-08 | 1.4e-16 |
| 1e+12 | 5.00004e-07 | 5e-07 | 7.6e-06 | 2.1e-16 | |
| 1e+16 | 0 | 5e-09 | 1.0e+00 | 0.0e+00 |
The naive forms lose more digits the closer the two terms are, and at $x = 10^{-8}$ (where $\cos x$ rounds to $1$) and $x = 10^{16}$ (where $x + 1$ rounds to $x$) they return 0. The rewritten forms are right to about the last digit everywhere.
Machine Epsilon and Comparisons
The gap between $1$ and the next larger float is called the machine epsilon. For float64 it is $2^{-52} \approx 2.2 \times 10^{-16}$, and it is behind every threshold in this post: anything smaller than half of it disappears when it is added to $1$. np.finfo reports it for each type, and np.spacing(x) gives the gap at any $x$, which grows with $x$. Above $2^{53} \approx 9 \times 10^{15}$ the gap is $2$, so a float64 cannot even store every integer.
rows = []
for dtype in (np.float16, np.float32, np.float64):
info = np.finfo(dtype)
rows.append({"type": dtype.__name__, "eps": f"{float(info.eps):.3g}",
"smallest normal": f"{float(info.smallest_normal):.3g}",
"largest": f"{float(info.max):.3g}", "decimal digits": info.precision})
display(pd.DataFrame(rows).set_index("type"))
print(f"np.spacing(1.0) = {np.spacing(1.0)}")
print(f"np.spacing(1e16) = {np.spacing(1e16)}")
print(f"1.0 + eps / 2 == 1.0: {1.0 + np.finfo(np.float64).eps / 2 == 1.0}")
| eps | smallest normal | largest | decimal digits | |
|---|---|---|---|---|
| type | ||||
| float16 | 0.000977 | 6.1e-05 | 6.55e+04 | 3 |
| float32 | 1.19e-07 | 1.18e-38 | 3.4e+38 | 6 |
| float64 | 2.22e-16 | 2.23e-308 | 1.8e+308 | 15 |
np.spacing(1.0) = 2.220446049250313e-16 np.spacing(1e16) = 2.0 1.0 + eps / 2 == 1.0: True
So == on floats is a bug waiting to happen: two computations of the same number can differ in the last bit, as 0.1 + 0.2 == 0.3 showed. Compare with a tolerance instead. math.isclose(a, b) allows a difference of $10^{-9}$ times the larger of $|a|$ and $|b|$, and np.isclose(a, b) allows $10^{-8} + 10^{-5}|b|$. That absolute $10^{-8}$ (the atol argument) is a trap for small numbers:
print(np.isclose(0.1 + 0.2, 0.3), math.isclose(0.1 + 0.2, 0.3))
print(np.isclose(1e-10, 2e-10)) # True: the default atol=1e-8 swamps both numbers
print(np.isclose(1e-10, 2e-10, atol=0)) # False
print(math.isclose(1e-10, 2e-10)) # False: only a relative tolerance by default
True True True False False
For numbers far from $1$, set atol to a scale that makes sense for the data, or to 0.
Summation
Adding many numbers one at a time makes a rounding error at every step, and once the running total is large, each small number added to it loses most of its digits. Here are ten million copies of 0.1 in float32, which should add up to $10^6$:
values = np.full(10_000_000, 0.1, dtype=np.float32)
results = {
"sum (one at a time)": sum(values), # a running float32 total, like a plain loop
"np.sum (pairwise)": np.sum(values),
"math.fsum (exact)": math.fsum(values),
}
for name, total in results.items():
print(f"{name:20s} {float(total):>16,.4f} minus 10^6: {float(total) - 1e6:+,.4f}")
sum (one at a time) 1,087,937.0000 minus 10^6: +87,937.0000 np.sum (pairwise) 1,000,000.1250 minus 10^6: +0.1250 math.fsum (exact) 1,000,000.0149 minus 10^6: +0.0149
The plain running sum is off by almost 9%. np.sum adds pairwise, splitting the array in halves again and again, so each value goes through only about $\log_2 n$ additions and the error stays small. math.fsum keeps track of every lost low-order bit and returns the correctly rounded sum of the values as stored; that is $1{,}000{,}000.0149$ rather than $10^6$ because float32(0.1) is really $0.100000001490116\ldots$. A cheap middle ground is Kahan (compensated) summation, which keeps a second variable holding the rounding error of each addition and adds it back in the next one.
Variance
The textbook shortcut for the variance, $\operatorname{Var}(x) = \mathbb{E}[x^2] - \mathbb{E}[x]^2$, subtracts two huge, nearly equal numbers whenever the mean is large compared with the spread: catastrophic cancellation again. Take the data $10^9 + [1, 2, 3]$, whose variance (dividing by $n$) is $2/3$:
data = 1e9 + np.array([1.0, 2.0, 3.0])
def naive_var(x):
return np.mean(x**2) - np.mean(x)**2
def welford_var(xs):
"""Welford's online algorithm: one pass, updating the mean and the sum of squared deviations."""
n, mean, m2 = 0, 0.0, 0.0
for x in xs:
n += 1
delta = x - mean
mean += delta / n
m2 += delta * (x - mean)
return m2 / n # divide by n, like np.var's default ddof=0
print(f"E[x^2] - E[x]^2: {naive_var(data)}")
print(f"Welford: {welford_var(data)}")
print(f"np.var: {np.var(data)}")
print(f"exact: {2 / 3}")
E[x^2] - E[x]^2: 0.0 Welford: 0.6666666666666666 np.var: 0.6666666666666666 exact: 0.6666666666666666
The shortcut returns 0.0. $x^2$ is about $10^{18}$, where the gap between floats is $128$, so the information about the spread is rounded away before the subtraction (for other data it can even come out negative). Welford's algorithm updates the mean, and the sum of squared deviations from it, one value at a time, so it never forms the huge squares and works on a stream of data. np.var subtracts the mean first and then averages the squared deviations, which is just as accurate when all the data is in memory.
Why This Matters in ML
None of this is a curiosity. A training run that hits one inf or nan in its loss rarely recovers: its gradient is usually nan, an optimiser step with a nan gradient makes every weight it touches nan, and every loss after that is nan too. Here is the naive BCE from Sigmoid and BCE from Logits at the confident mistake $z = 40$, $y = 0$, with its gradient:
z = torch.tensor(40.0, requires_grad=True)
loss = -torch.log(1 - torch.sigmoid(z)) # the naive BCE for the label y = 0
loss.backward()
print(f"naive BCE: loss = {loss.item()}, gradient = {z.grad.item()}")
z.grad = None
loss = F.binary_cross_entropy_with_logits(z, torch.tensor(0.0))
loss.backward()
print(f"BCE from logits: loss = {loss.item()}, gradient = {z.grad.item()}")
naive BCE: loss = inf, gradient = nan BCE from logits: loss = 40.0, gradient = 1.0
The loss from logits is finite and so is its gradient, $\sigma(z) - y = 1$. The KL divergence breaks in the same way. Computed from probabilities as sum(p * log(p / q)), it is inf as soon as some $q_i$ underflows to 0 where $p_i > 0$; computed from log-probabilities, with log_softmax rather than log(softmax(x)), it stays finite, which is why PyTorch's F.kl_div expects its input as log-probabilities. Lower precision makes all of this more likely. Mixed-precision training runs most of a network in float16 or bfloat16 to save memory and time, and both types move every threshold in this post much closer:
rows = []
for dtype in (torch.float16, torch.bfloat16, torch.float32):
info = torch.finfo(dtype)
one, small = torch.tensor(1.0, dtype=dtype), torch.tensor(0.001, dtype=dtype)
rows.append({
"type": str(dtype).removeprefix("torch."),
"exp(x) = inf above": f"{math.log(info.max):.2f}",
"1 + x == 1 up to": f"{info.eps / 2:.2g}",
"log(1 + 0.001)": f"{torch.log(one + small).item():.4g}",
"log1p(0.001)": f"{torch.log1p(small).item():.4g}",
})
pd.DataFrame(rows).set_index("type")
| exp(x) = inf above | 1 + x == 1 up to | log(1 + 0.001) | log1p(0.001) | |
|---|---|---|---|---|
| type | ||||
| float16 | 11.09 | 0.00049 | 0.0009761 | 0.0009995 |
| bfloat16 | 88.72 | 0.0039 | 0 | 0.0009995 |
| float32 | 88.72 | 6e-08 | 0.0009995 | 0.0009995 |
In float16, exp(x) is inf for every $x$ above $11.09$, so a naive softmax overflows on quite ordinary scores. bfloat16 has the 8 exponent bits of float32, and so its range, but only 8 significant bits, so $1 + x$ rounds to $1$ for every $x$ up to $0.0039$ and log(1 + 0.001) is exactly 0, while log1p is still right to the precision of each type. This is why mixed-precision tools treat exactly these functions with care. On a GPU, PyTorch's autocast runs exp, log, softmax, log_softmax and most losses in float32 even when the rest of the model runs in float16; GradScaler multiplies a float16 loss by a large factor before the backward pass, so that small gradients do not underflow to 0, and divides the gradients by the same factor before the update; and F.binary_cross_entropy refuses to run inside autocast and points to binary_cross_entropy_with_logits instead.
Cheat Sheet
Every row is a failure shown in this post. xlogy, xlog1py and logsumexp come from scipy.special, and F is torch.nn.functional.
| Naive | Fails at | Use instead |
|---|---|---|
log(1 + x) |
small x; 0 below 1.1e-16 |
np.log1p(x) |
exp(x) - 1 |
small x; 0 below 1.1e-16 |
np.expm1(x) |
log(1 + exp(x)) |
x = 800: inf |
np.logaddexp(0, x) |
x * log(y) |
x = y = 0: nan |
xlogy(x, y) |
x * log(1 + y) |
x = 0, y = -1: nan |
xlog1py(x, y) |
log(exp(x) + exp(y)) |
x = 1e20: inf |
np.logaddexp(x, y) |
log(sum( |
x = [1000] * 3: inf |
logsumexp(x) |
exp(x) / sum(exp(x)) |
x = [1000] * 3: nan |
exp(x - max(x)), then normalise |
-log(1 - sigmoid(z)) |
z = 40, y = 0: inf |
F.binary_cross_ |
a == b |
0.1 + 0.2 == 0.3: False |
np.isclose(a, b) |
sum(xs) |
10⁷ × 0.1 in float32: 1,087,937 |
math.fsum(xs) |
mean(x**2) - mean(x)**2 |
1e9 + [1, 2, 3]: 0.0 |
Welford, or np.var(x) |
Takeaways
- A float keeps a fixed number of significant digits (about 3 decimal digits for
float16, 7 forfloat32and 16 forfloat64), so every operation rounds and==on floats is a bug. Compare withmath.iscloseornp.isclose(and mind its defaultatol), and add long lists withnp.sumormath.fsum, not a running total. - Subtracting nearly equal numbers cancels the good digits and leaves the rounding error. Use
np.log1p,np.expm1,xlogy,xlog1pyand an algebraic rewrite instead oflog(1 + x),exp(x) - 1,x * log(y),1 - cos(x)or $\mathbb{E}[x^2] - \mathbb{E}[x]^2$. - Never exponentiate a large number only to take its logarithm afterwards.
np.logaddexp,logsumexp, the max-shifted softmax andbinary_cross_entropy_with_logitsstay in log space and are finite at both ends.
References
- D. Goldberg, "What Every Computer Scientist Should Know About Floating-Point Arithmetic", ACM Computing Surveys 23(1), 5–48, 1991. Theorem 4 is the
log1ptrick used inmy_log1p. - N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd edition, SIAM, 2002. Chapter 4 covers summation, including pairwise and compensated summation.
- IEEE, IEEE Standard for Floating-Point Arithmetic (IEEE 754-2019), 2019.
- W. Kahan, "Further remarks on reducing truncation errors", Communications of the ACM 8(1), 40, 1965.
- B. P. Welford, "Note on a Method for Calculating Corrected Sums of Squares and Products", Technometrics 4(3), 419–420, 1962.
- P. Blanchard, D. J. Higham and N. J. Higham, "Accurately computing the log-sum-exp and softmax functions", IMA Journal of Numerical Analysis 41(4), 2311–2330, 2021.
- NumPy documentation:
numpy.log1p,numpy.expm1,numpy.logaddexpandnumpy.finfo. - SciPy documentation:
scipy.special.xlogy,scipy.special.xlog1pyandscipy.special.logsumexp. - PyTorch documentation:
torch.nn.functional.binary_cross_entropy_with_logitsandtorch.nn.BCELoss, which documents the clamp of the logarithm at -100;torch.nn.KLDivLoss, which takes its input in log space to avoid underflow; and Automatic Mixed Precision (torch.amp), which lists the operationsautocastruns infloat32and explains gradient scaling. - P. Micikevicius, S. Narang, J. Alben, G. Diamos, E. Elsen, D. Garcia, B. Ginsburg, M. Houston, O. Kuchaiev, G. Venkatesh and H. Wu, "Mixed Precision Training", ICLR, 2018 (arXiv:1710.03740). Introduces loss scaling for
float16training. - D. Kalamkar et al., "A Study of BFLOAT16 for Deep Learning Training", 2019 (arXiv:1905.12322).