Appendix A — Floating-point arithmetic
Every number in this book’s computations, from a gradient checked by finite differences to the 4192 parameters of the model in Chapter 11, lives in the computer as a floating-point number: a binary fraction with a fixed number of significant bits, scaled by a power of 2. Arithmetic on such numbers rounds after every operation. This appendix states the rounding model that arithmetic following the IEEE 754 standard satisfies, and uses it to explain two things the main text relies on: why finite differences need a carefully chosen step, and why programs compute the softmax, and the logarithm of a sum of exponentials, after subtracting the largest input.
A.1 Binary floating-point numbers
A computer has to store numbers as large as \(10^{300}\) and as small as \(10^{-300}\) in a fixed number of bits, with the same relative precision across that range. Scientific notation does this in base 10; floating point does it in base 2. For example, \[ 5.75 = 4 + 1 + \tfrac12 + \tfrac14 = (101.11)_2 = (1.0111)_2\times2^2 = \Bigl(1 + \frac{7}{16}\Bigr)2^2 : \] a significand between 1 and 2, written in binary, times a power of 2. Storing a number then means storing the exponent (here 2) and the binary digits after the point (here 0111), together with a sign. The format that this book’s computations use keeps 52 such digits.
Definition A.1 (Binary64 numbers) The finite binary64 numbers (the “double precision” numbers of IEEE 754) are \(0\) and the numbers \[ \pm\Bigl(1 + \frac{f}{2^{52}}\Bigr)2^{e} \quad (0 \le f < 2^{52},\; -1022 \le e \le 1023), \qquad \pm\frac{f}{2^{52}}\,2^{-1022} \quad (0 < f < 2^{52}), \] with \(f\) and \(e\) integers. Those of the first kind are normal, and those of the second kind are subnormal. A number occupies 64 bits: one for the sign, 11 for the exponent (stored as \(e + 1023\), with the values \(0\) and \(2047\) reserved for zero and subnormals, and for infinities and NaN, “not a number”) and 52 for \(f\).
For \(5.75\), \(e = 2\) and \(f = (7/16)2^{52} = 7\times2^{48}\). The significand \(1 + f/2^{52}\) has 53 significant bits, the leading 1 being implicit. Between \(2^e\) and \(2^{e+1}\) the normal numbers are equally spaced, \(2^{e-52}\) apart, so the spacing doubles from one power of 2 to the next and the relative spacing stays between \(2^{-53}\) and \(2^{-52}\). The spacing just above \(1\) is \(2^{-52} \approx 2.22\times10^{-16}\), often called machine epsilon.
The largest finite number is \((2 - 2^{-52})\,2^{1023} \approx 1.798\times10^{308}\), the smallest positive normal number is \(2^{-1022} \approx 2.225\times10^{-308}\), and the smallest positive subnormal is \(2^{-1074} \approx 4.94\times10^{-324}\). Results too large to represent overflow to \(\pm\infty\), and results too small underflow to a subnormal or to \(0\). For the exponential function this happens at moderate arguments: \(e^x\) overflows for \(x > \ln\bigl((2 - 2^{-52})2^{1023}\bigr) \approx 709.78\), and rounds to \(0\) for \(x < \ln 2^{-1075} \approx -745.13\).
Subnormal numbers fill the gap between \(0\) and the smallest positive normal number \(2^{-1022}\). Without them, the next number above \(0\) would be \(2^{-1022}\), while the normal numbers just above \(2^{-1022}\) are only \(2^{-1074}\) apart; two such numbers could then differ by an amount that is not representable, and their computed difference would be \(0\) although they are not equal. The subnormal numbers are the multiples of \(2^{-1074}\) below \(2^{-1022}\), the same spacing as the normal numbers in \([2^{-1022}, 2^{-1021})\), and with them the difference of two distinct binary64 numbers is never computed as \(0\) (Goldberg 1991). Lemma A.2 below relies on them.
Most real numbers are not binary64 numbers. Even \(0.1\) is not, because \(1/10\) is not a fraction with a power of 2 as denominator (Exercise A.2). The computer stores a real number \(x\) in range as \(\operatorname{fl}(x)\), the binary64 number nearest to \(x\) (with ties going to the one whose integer \(f\) is even); this is rounding to nearest. The stored value of \(0.1\) is \(0.1000000000000000055511\ldots\), wrong by about \(5.55\times10^{-18}\), a relative error of \(5.55\times10^{-17}\). Near \(0.1\) the binary64 numbers are \(2^{-56}\) apart and near \(1000\) they are \(2^{-43}\) apart, so the absolute error of rounding grows with \(|x|\), but the relative error stays below one bound.
Theorem A.1 (Rounding error) Let \(u = 2^{-53}\), the unit roundoff. If \(x\) is real and \(2^{-1022} \le |x| \le (2 - 2^{-52})2^{1023}\), then \[ \operatorname{fl}(x) = x(1 + \delta) \quad\text{for some } |\delta| \le u . \]
Proof. It is enough to treat \(x > 0\). Let \(e\) be the integer with \(2^e \le x < 2^{e+1}\); then \(-1022 \le e \le 1023\). The binary64 numbers \(2^e(1 + f/2^{52})\), \(f = 0, \dots, 2^{52}\), lie \(2^{e-52}\) apart and run from \(2^e\) to \(2^{e+1}\) (the last of them is the first number of the next range, or, for \(e = 1023\), lies beyond the largest finite number, which \(x\) does not exceed). So \(x\) lies between two consecutive binary64 numbers that are \(2^{e-52}\) apart, and the nearer of them is within half that distance: \(|\operatorname{fl}(x) - x| \le 2^{e-53} \le 2^{-53}x\). Put \(\delta = (\operatorname{fl}(x) - x)/x\).
IEEE 754 requires the basic operations \(+\), \(-\), \(\times\), \(\div\) and \(\sqrt{\phantom{x}}\) to be correctly rounded: the computed result is \(\operatorname{fl}\) of the exact result (IEEE 2019). By Theorem A.1, for binary64 numbers \(x\) and \(y\) and any of these operations \(\circ\), \[ \operatorname{fl}(x\circ y) = (x\circ y)(1 + \delta), \qquad |\delta| \le u, \tag{A.1}\] as long as the exact result lies in the normal range. This standard model is the starting point of rounding-error analysis (Higham 2002, ch. 2; Stoer and Bulirsch 2002, sec. 1.2). The standard does not require correct rounding of \(\exp\) and \(\log\), and library implementations of them typically guarantee an error of about one unit in the last place (the spacing between consecutive binary64 numbers at the size of the result), a relative error of a small multiple of \(u\).
A.2 Cancellation
Subtracting two nearby binary64 numbers introduces no new rounding error (Lemma A.2 below), but the two numbers usually carry errors from earlier steps, and the subtraction can make those errors large compared with the result.
Example A.1 For small \(x\), \(1 - \cos x \approx x^2/2\). Computed directly, the result is poor: the computed \(\cos x\) is a number near 1 with an error of up to about \(u\), and that error is not small compared with \(x^2/2\). For \(x = 10^{-7}\) the direct computation gives \(4.996\times10^{-15}\) against the true \(5.000\times10^{-15}\), a relative error of \(8\times10^{-4}\). For \(x = 10^{-8}\), \(\cos x\) rounds to exactly \(1\) and the computed \(1 - \cos x\) is \(0\), against the true value \(5\times10^{-17}\). Rewriting with the identity \(1 - \cos x = 2\sin^2(x/2)\) removes the subtraction, and gives \(5.000\times10^{-15}\) and \(5.000\times10^{-17}\), correct to the precision shown.
In the example, the computed \(\cos x\) is the true value times \(1 + \delta\) with \(|\delta|\) of the order of \(u\), and the subtraction itself is exact. The general situation is two numbers known only through approximations with relative errors at most \(u\), as Theorem A.1 provides.
Lemma A.1 (Cancellation) Let \(a\) and \(b\) be real numbers with \(a \ne b\), let \(u = 2^{-53}\), and let \(\hat a = a(1 + \delta_a)\) and \(\hat b = b(1 + \delta_b)\) with \(|\delta_a|, |\delta_b| \le u\). Then \[ \frac{|(\hat a - \hat b) - (a - b)|}{|a - b|} \le u\,\frac{|a| + |b|}{|a - b|} . \]
Proof. \((\hat a - \hat b) - (a - b) = a\delta_a - b\delta_b\), whose absolute value is at most \(u(|a| + |b|)\) by the triangle inequality.
When \(a\) and \(b\) are close, the factor \((|a| + |b|)/|a - b|\) is large, and the relative error of the difference can be far larger than \(u\), even though the subtraction itself adds no error. The digits that agree cancel, and what remains is mostly the earlier rounding error. This is cancellation. In Example A.1, \(a = 1\) and \(b = \cos x \approx 1 - x^2/2\), so the factor is about \(4/x^2\), which is \(4\times10^{14}\) for \(x = 10^{-7}\).
The same effect appears in a difference quotient, where \(f(x + h)\) and \(f(x)\) agree in more and more digits as \(h\) shrinks. One more fact lets the analysis below ignore the subtraction itself. The stored values of \(0.3\) and \(0.2\) are binary64 numbers within a factor 2 of each other, and their difference \(0.09999999999999997779\ldots\) is computed exactly: it is itself a binary64 number. It differs from the stored value of \(0.1\) only because storing \(0.3\) and \(0.2\) rounded them.
Lemma A.2 (Sterbenz’s lemma) If \(a\) and \(b\) are binary64 numbers with \(b/2 \le a \le 2b\), then \(a - b\) is a binary64 number, so floating-point subtraction computes it exactly.
Proof. If \(b = 0\) then \(a = 0\). Otherwise both numbers are positive, and swapping them changes only the sign of the difference, so suppose \(b \le a \le 2b\). Let \(e\) be the exponent of \(b\) (with \(e = -1022\) if \(b\) is subnormal). Every binary64 number at least \(2^e\) is an integer multiple of \(2^{e-52}\), and so are \(b\) and \(a \ge b\). Hence \(a - b = D\,2^{e-52}\) for an integer \(D\) with \(0 \le D \le b/2^{e-52} < 2^{53}\), because \(a - b \le b\). If \(D\,2^{e-52} \ge 2^{-1022}\), let \(e' \le e\) be its exponent; then \(D\,2^{e-52} = (D\,2^{e-e'})\,2^{e'-52}\) with \(2^{52} \le D\,2^{e-e'} < 2^{53}\), a normal number. Otherwise it is an integer multiple of \(2^{-1074}\) below \(2^{-1022}\), a subnormal number or \(0\).
A.3 The error of finite differences
The forward difference \((f(x + h) - f(x))/h\) estimates the derivative \(f'(x)\), and the hidden checks in this book use such estimates to test gradients. How small should \(h\) be? In exact arithmetic the error falls as \(h\) falls. In floating point it does not. For \(f(y) = 1/y\) at \(x = 3\), where \(f'(3) = -1/9\), the computed forward difference with \(h = 2^{-10}\) is wrong by \(3.6\times10^{-5}\); with \(h = 2^{-27}\) by \(8.3\times10^{-10}\); and with \(h = 2^{-40}\) by \(2.7\times10^{-5}\) again. The function values carry rounding errors, the difference cancels their leading digits, and the division by \(h\) magnifies what is left. The total error has two parts that pull in opposite directions, which Section 3.7 introduced: the truncation error, the error of the exact difference quotient, which comes from cutting off the Taylor series of \(f\) and shrinks with \(h\); and the rounding error, which comes from the computed values of \(f\) and grows as \(h\) shrinks.
Theorem A.2 (Error of finite differences) Let \(u = 2^{-53}\), \(h > 0\), and let \(M_0 > 0\) bound \(|f|\) at the points where the computation evaluates \(f\). Suppose the computed values \(\hat f(y)\) satisfy \(|\hat f(y) - f(y)| \le uM_0\) at those points, and that the subtraction and the division by \(h\) (or \(2h\)) are exact.
If \(f\) is twice differentiable on an open interval containing \([x, x + h]\) and \(|f''| \le M_2\) on \([x, x + h]\), with \(M_2 > 0\), then \[ \Bigl|\frac{\hat f(x + h) - \hat f(x)}{h} - f'(x)\Bigr| \le \frac{M_2h}{2} + \frac{2uM_0}{h} . \] The bound is smallest at \(h^* = 2\sqrt{uM_0/M_2}\), where it equals \(2\sqrt{uM_0M_2}\).
If \(f\) is three times differentiable on an open interval containing \([x - h, x + h]\) and \(|f'''| \le M_3\) there, with \(M_3 > 0\), then \[ \Bigl|\frac{\hat f(x + h) - \hat f(x - h)}{2h} - f'(x)\Bigr| \le \frac{M_3h^2}{6} + \frac{uM_0}{h} . \] The bound is smallest at \(h^* = (3uM_0/M_3)^{1/3}\), where it equals \(M_3(h^*)^2/2\).
Proof.
- By Taylor’s theorem with the Lagrange form of the remainder, \(f(x + h) = f(x) + hf'(x) + \frac{h^2}{2}f''(\xi)\) for some \(\xi\) between \(x\) and \(x + h\), so the exact difference quotient satisfies \[ \Bigl|\frac{f(x+h) - f(x)}{h} - f'(x)\Bigr| = \frac h2|f''(\xi)| \le \frac{M_2h}{2} . \] The computed quotient differs from the exact one by \(\bigl((\hat f(x+h) - f(x+h)) - (\hat f(x) - f(x))\bigr)/h\), whose absolute value is at most \(2uM_0/h\). The triangle inequality adds the two bounds.
The function \(g(h) = M_2h/2 + 2uM_0/h\) has \(g'(h) = M_2/2 - 2uM_0/h^2\), which is negative for \(h < h^*\) and positive for \(h > h^*\), so \(h^*\) gives the minimum, and \(g(h^*) = \sqrt{uM_0M_2} + \sqrt{uM_0M_2}\).
- Taylor’s theorem to third order at \(x + h\) and at \(x - h\) gives \[ f(x \pm h) = f(x) \pm hf'(x) + \frac{h^2}{2}f''(x) \pm \frac{h^3}{6}f'''(\xi_\pm), \] with \(\xi_+\) between \(x\) and \(x + h\) and \(\xi_-\) between \(x - h\) and \(x\). Subtracting, the terms in \(f(x)\) and \(f''(x)\) cancel: \[ \frac{f(x+h) - f(x-h)}{2h} - f'(x) = \frac{h^2}{12}\bigl(f'''(\xi_+) + f'''(\xi_-)\bigr), \] of absolute value at most \(M_3h^2/6\). The rounding errors contribute at most \(2uM_0/(2h) = uM_0/h\). The function \(g(h) = M_3h^2/6 + uM_0/h\) has \(g'(h) = M_3h/3 - uM_0/h^2\), which changes sign from negative to positive at \(h^*\) with \((h^*)^3 = 3uM_0/M_3\). There \(uM_0/h^* = M_3(h^*)^2/3\), so \(g(h^*) = M_3(h^*)^2/6 + M_3(h^*)^2/3 = M_3(h^*)^2/2\).
So the best step for a forward difference is of order \(\sqrt u \approx 10^{-8}\) and gives about 8 correct digits, and the best step for a central difference is of order \(u^{1/3} \approx 5\times10^{-6}\) and gives about 11. Taking \(h\) smaller than the best step makes the estimate worse, not better. This is why the hidden checks in this book use central differences with steps near \(10^{-6}\) when they compare a gradient with finite differences, and why exact derivatives computed by automatic differentiation (Chapter 3, Chapter 4) are preferable to finite differences whenever they are available.
The hypotheses of Theorem A.2 hold exactly for \(f(y) = 1/y\) at \(x = 3\) with \(h = 2^{-k}\): \(3 \pm h\) is a binary64 number for \(k \le 51\); each value \(1/(3 \pm h)\) is a single correctly rounded division, so its error is at most \(u|f| \le uM_0\); the two values differ by less than a factor of 2, so by Lemma A.2 their difference is exact; and dividing by a power of 2 is exact. Here \(f'(3) = -1/9\). For the forward difference \(M_0 = 1/3\) and \(M_2 = 2/27\), since \(|f''(y)| = 2/y^3\) on \([3, 3 + h]\); for the central difference \(M_0 = 1/(3 - h)\) and \(M_3 = 6/(3 - h)^4\), since \(|f'''(y)| = 6/y^4\) on \([3 - h, 3 + h]\).
Figure A.1 shows the observed errors for \(k = 1, \dots, 50\) against the bounds. For large \(h\) the forward-difference error follows the truncation term \(h/27\); for small \(h\) rounding dominates, and the error grows like \(1/h\). The bound predicts a best step \(h^* = 2\sqrt{u(1/3)/(2/27)} \approx 4.5\times10^{-8}\) with error at most \(3.3\times10^{-9}\). The smallest observed error is \(8.3\times10^{-10}\), at \(h = 2^{-27} \approx 7.5\times10^{-9}\); the bound is a worst case, and the actual rounding errors partly cancel. For the central difference the predicted best step is about \(1.1\times10^{-5}\) with error at most \(4.9\times10^{-12}\), and the smallest observed error is \(1.6\times10^{-12}\), at \(h = 2^{-18} \approx 3.8\times10^{-6}\).
A.4 Softmax and log-sum-exp
The softmax of \(\mathbf{z}\in\mathbb{R}^n\) is the vector with components \(\operatorname{softmax}(\mathbf{z})_i = e^{z_i}/\sum_j e^{z_j}\) (Definition 8.5), so computing it exponentiates every input. In binary64, \(e^z\) overflows for \(z\) above about \(709.78\). The 16-bit format binary16 (IEEE 2019) has the same structure as binary64 with 10 fraction bits and 5 exponent bits; its largest finite number is \((2 - 2^{-10})2^{15} = 65504\), and \(e^z\) overflows there for \(z\) above about \(11.09\). The inputs to a softmax in a language model, its logits (Chapter 11), reach that size in practice. The remedy rests on an observation that a small case makes clear: \(\operatorname{softmax}(1, 2, 3) \approx (0.090, 0.245, 0.665)\), and \(\operatorname{softmax}(101, 102, 103)\) and \(\operatorname{softmax}(-2, -1, 0)\) are the same vector, because adding a constant to every input multiplies every exponential by the same factor, which cancels in the quotient.
Theorem A.3 (Softmax is unchanged by a shift) For every \(\mathbf{z}\in\mathbb{R}^n\) and every real \(c\), \(\operatorname{softmax}(\mathbf{z} + c\mathbf{1}) = \operatorname{softmax}(\mathbf{z})\). Consequently, for every real \(m\), \[ \ln\sum_{j=1}^n e^{z_j} = m + \ln\sum_{j=1}^n e^{z_j - m} . \tag{A.2}\]
Proof. \(e^{z_i + c} = e^{c}e^{z_i}\), so \[ \operatorname{softmax}(\mathbf{z} + c\mathbf{1})_i = \frac{e^ce^{z_i}}{\sum_j e^ce^{z_j}} = \frac{e^{z_i}}{\sum_j e^{z_j}} = \operatorname{softmax}(\mathbf{z})_i . \] For Equation A.2, \(\sum_j e^{z_j} = e^m\sum_j e^{z_j - m}\), and the logarithm of a product of positive numbers is the sum of their logarithms.
The function \(\operatorname{lse}(\mathbf{z}) = \ln\sum_j e^{z_j}\) is the log-sum-exp function of Definition 8.6. It appears in the cross-entropy loss, because \(-\ln\operatorname{softmax}(\mathbf{z})_y = \operatorname{lse}(\mathbf{z}) - z_y\) (Chapter 8). In words, Equation A.2 says that log-sum-exp may be computed after subtracting any number \(m\) from every input, provided \(m\) is added back at the end.
Corollary A.1 (Stable evaluation) Let \(\mathbf{z}\in\mathbb{R}^n\), \(m = \max_j z_j\) and \(S = \sum_j e^{z_j - m}\). Then every term \(e^{z_j - m}\) lies in \((0, 1]\), at least one equals \(1\), and \(1 \le S \le n\). Hence \[ \operatorname{softmax}(\mathbf{z})_i = \frac{e^{z_i - m}}{S}, \qquad \operatorname{lse}(\mathbf{z}) = m + \ln S, \qquad -\ln\operatorname{softmax}(\mathbf{z})_y = m + \ln S - z_y , \] and computed this way, no exponential exceeds \(1\), and every denominator and every argument of the logarithm lies between \(1\) and \(n\).
Proof. \(z_j - m \le 0\), with equality where the maximum is attained, so \(0 < e^{z_j - m} \le 1\) with equality there, and summing \(n\) such terms gives \(1 \le S \le n\). The three formulas are Theorem A.3 with \(c = -m\) and Equation A.2.
In floating point, a term \(e^{z_j - m}\) may underflow to \(0\) when \(z_j - m < -745\); since \(S \ge 1\), that changes the computed probabilities by less than \(2^{-1074}\), far below the rounding error. The model of Chapter 11 computes its softmax in this way, and its hidden checks do the same.
Example A.2 Let \(\mathbf{z} = (1000, 999, 998)\). Computed directly, \(e^{1000}\) overflows to \(\infty\), so every quotient is \(\infty/\infty\) and every component of the result is NaN. Subtracting \(m = 1000\) gives \((0, -1, -2)\), \(S = 1 + e^{-1} + e^{-2} \approx 1.5032\), and \[ \operatorname{softmax}(\mathbf{z}) \approx (0.6652, 0.2447, 0.0900), \qquad \operatorname{lse}(\mathbf{z}) \approx 1000.4076 . \] For \(\mathbf{z} = (-1000, -1001, -1002)\) the direct computation underflows instead: every \(e^{z_j}\) is \(0\), so the quotients are \(0/0\) and the logarithm of the sum is \(-\infty\). The shifted computation gives the same probabilities as before, since the shifted vector is again \((0, -1, -2)\), and \(\operatorname{lse}(\mathbf{z}) \approx -999.5924\).
A.5 Notes and further reading
The IEEE 754 standard (IEEE 2019) defines the binary64 and binary16 formats and the rounding rules, and requires the basic operations to be correctly rounded. Goldberg (1991) is a widely read introduction to the consequences for programmers, with proofs. Higham (2002) develops rounding-error analysis in depth; its chapter 2 covers the standard model and its chapter 1 discusses cancellation. Stoer and Bulirsch (2002, ch. 1) treats floating-point numbers and error propagation in a first course on numerical analysis.
A.6 Exercises
Exercise A.1 What is the spacing between consecutive binary64 numbers near \(1000\)? What is the largest power of 2 whose sum with \(1000\) rounds back to exactly \(1000\)?
Exercise A.2 Show that \(0.1\) is not a binary64 number. Then explain why the computed sum \(0.1 + 0.2\) is not equal to the computed \(0.3\), using Theorem A.1.
Exercise A.3 For large \(x > 0\), the difference \(\sqrt{x + 1} - \sqrt{x}\) suffers from cancellation. Show that it equals \(1/(\sqrt{x + 1} + \sqrt{x})\), and use Lemma A.1 to explain why the second form is better. Compare the two in binary64 for \(x = 10^{12}\).
Exercise A.4 Show that for \(\mathbf{z}\in\mathbb{R}^n\), \(\max_j z_j \le \operatorname{lse}(\mathbf{z}) \le \max_j z_j + \ln n\), with equality on the right exactly when all components are equal.
Exercise A.5 For \(f = \sin\), with \(M_0 = M_2 = 1\), find the step \(h^*\) and the error bound of Theorem A.2 (a) in binary64, and the corresponding step and bound for the central difference with \(M_3 = 1\).