23.8 Numerical Stability and Conditioning

Every computation in this chapter so far ran in floating point, and we read its results as if they were exact real numbers. Most of the time, that convenient fiction holds up. Occasionally, however, a training loss turns into NaN, or a linear solver returns an answer that looks completely plausible and is badly wrong. In this section we ask when finite-precision arithmetic, rather than the optimization algorithm, decides the answer—and what we can do about it.

Two small examples show the two ways numerical trouble arrives. First, the three logits (1000,1001,1002)(1000, 1001, 1002) define an entirely ordinary softmax, with probabilities (0.09,0.24,0.67)(0.09, 0.24, 0.67). Yet if we evaluate the textbook formula as written, it returns NaN three times, even in double precision (fp64). Second, np.linalg.solve applied to a 12×1212\times12 linear system returns an answer that is off by 30%, even though it is the exact solution of a system that differs from the stated one only in the seventeenth decimal digit. The first failure halts training with a NaN loss; the second slips past unnoticed.

These two failures have fundamentally different causes. The naive softmax formula passes through e1000e^{1000}, a number too large for any standard floating-point format to hold, whereas an algebraically equivalent rewrite that never forms e1000e^{1000} is accurate to a few units in the last place. By contrast, the 12×1212\times12 linear system is so sensitive that a rounding error in the sixteenth digit of its data moves the solution in the first digit, and no rewriting of the solver can undo that sensitivity.

To tell those two situations apart, we begin by examining how computers store real numbers and how much error each rounding introduces. Next, we rewrite softmax and cross-entropy so they never pass through numbers the format cannot hold, and we rewrite the variance so it never subtracts nearly equal large numbers. We then introduce a sensitivity measure—the condition number of a function—that separates a bad algorithm from an inherently hard problem. Finally, we see how the condition number of a linear system governs both the digits a least-squares solve can keep and, as in Section 23.1, the number of steps gradient descent requires. While Section 5.5 shows how modern training uses low-precision formats in practice, here we derive why computations in them succeed or fail.

Three ideas matter more than any individual formula: the relative rounding model for floating-point arithmetic, the principle that an unstable algorithm routes a well-conditioned problem through an ill-conditioned intermediate step, and the bound linking a solver's solution error to the problem's sensitivity. The subsections on summation order and ridge regularization can be skipped on a first reading.

from fractions import Fraction

23.8.1 Floating-Point Arithmetic#

23.8.1.1 Representation and Spacing#

What does a computer actually store when we ask it to store 1.11.1? The mechanism is easiest to see in a toy binary format that keeps only two bits after the binary point. Between 11 and 22, this format can hold just four values: (1.00)2=1(1.00)_2=1, (1.01)2=1.25(1.01)_2=1.25, (1.10)2=1.5(1.10)_2=1.5, and (1.11)2=1.75(1.11)_2=1.75. Multiplying these four values by powers of two fills out the other intervals: 2,2.5,3,3.52, 2.5, 3, 3.5 between 22 and 44, and 0.5,0.625,0.75,0.8750.5, 0.625, 0.75, 0.875 between 0.50.5 and 11. Each octave—an interval [2e,2e+1)[2^e, 2^{e+1}) between consecutive powers of two—holds exactly four values, so the absolute gap between adjacent numbers doubles every time the magnitude doubles.

Any real number that falls between grid points is rounded to the nearest one: 1.1↦11.1\mapsto1 (a relative error of −0.091-0.091), 1.3↦1.251.3\mapsto1.25 (an error of −0.038-0.038), and 3.3↦3.53.3\mapsto3.5 (an error of +0.061+0.061). Halfway points are ties, and standard arithmetic breaks ties toward the neighbor whose last bit is 00: the midpoint 1.1251.125 therefore rounds to 11, an error of −0.111-0.111. Notice that no relative error exceeds 1/81/8. Rounding moves a number by at most half a gap, and in every octave half a gap is 1/81/8 of the octave's smallest value. Figure 23.8.1 sketches this grid on the real line.

Figure 23.8.1:

Floating-point numbers on the real line for a toy format with two mantissa bits (four values per octave, εmach=1/4\varepsilon_{\mathrm{mach}}=1/4, smallest normal 0.250.25). The absolute gap between neighbors doubles at every power of two while the relative gap stays near εmach\varepsilon_{\mathrm{mach}}. Below the smallest normal, subnormal numbers continue with the same spacing down to zero; after the axis break, real formats end at their overflow thresholds (fp16 at 6550465504, fp32 at about 3.4×10383.4\times10^{38}).

Real floating-point formats work in the same way, simply with more bits. A floating-point number is scientific notation in base two with a fixed budget of pp binary digits after the binary point,

x=(−1)s⋅(1.b1b2…bp)2⋅2e,(23.8.1)x = (-1)^s \cdot (1.b_1 b_2 \ldots b_p)_2 \cdot 2^{e}, \tag{23.8.1}

specified by a sign bit ss, mantissa (or significand) bits b1,…,bpb_1,\ldots,b_p, and an integer exponent ee drawn from a fixed range. The exponent sets the range of magnitudes the format can represent, while the mantissa sets its relative precision. Within the octave [2e,2e+1)[2^e, 2^{e+1}), adjacent values are spaced 2e−p2^{e-p} apart. The gap from 11 to the next representable number, εmach=2−p\varepsilon_{\mathrm{mach}}=2^{-p}, is called machine epsilon; our toy format has p=2p=2 and εmach=1/4\varepsilon_{\mathrm{mach}}=1/4.

Rounding a real number xx to the nearest representable value moves it by at most half a gap, 2e−p−12^{e-p-1}. Because ∣x∣≥2e|x|\ge2^e throughout the octave, the relative error is at most 2−p−12^{-p-1}. Calling a value normal when it has the form (23.8.1) with an in-range exponent, every real xx that rounds to a normal number satisfies

fl(x)=x (1+δ),∣δ∣≤u=12 εmach=2−p−1.(23.8.2)\mathrm{fl}(x) = x\,(1 + \delta), \qquad |\delta| \le u = \tfrac12\,\varepsilon_{\mathrm{mach}} = 2^{-p-1} . \tag{23.8.2}

In words, each rounding perturbs a number by at most one part in 2p+12^{p+1}: one part in 88 for our toy format, about one part in 17 million for fp32 (p=23p=23), and one part in 256256 for bf16 (p=7p=7). The bound uu is called the unit roundoff. Standard IEEE arithmetic rounds the result of every basic operation to the nearest representable value, so the computed sum x⊕yx\oplus y equals (x+y)(1+δ)(x+y)(1+\delta) with ∣δ∣≤u|\delta|\le u, and the same guarantee holds for −-, ×\times, and // (IEEE, 2019; Goldberg, 1991).

This clean relative model has three exceptions. Results larger than the format can hold overflow to ∞\infty. Results smaller than the smallest normal number underflow, stepping down through subnormal numbers that fill the remaining gap to zero. Undefined operations, such as 0/00/0 or ∞/∞\infty/\infty, produce NaN. All three are absolute-scale effects rather than relative ones, and we will return to them right after putting the standard formats on the table.

23.8.1.2 Formats#

Deep learning relies on five formats narrower than double precision (fp64). Let us inspect each format's machine epsilon εmach\varepsilon_{\mathrm{mach}}, smallest normal number, and largest finite value directly from the library:

print(f'{"dtype":>14} {"eps":>10} {"smallest normal":>16} {"max":>10}')
for dt in [torch.float16, torch.float32, torch.bfloat16,
           torch.float8_e4m3fn, torch.float8_e5m2]:
    fi = torch.finfo(dt)
    print(f'{str(dt).removeprefix("torch."):>14} {fi.eps:10.3e} '
          f'{fi.smallest_normal:16.3e} {fi.max:10.3e}')
         dtype        eps  smallest normal        max
       float16  9.766e-04        6.104e-05  6.550e+04
       float32  1.192e-07        1.175e-38  3.403e+38
      bfloat16  7.812e-03        1.175e-38  3.390e+38
 float8_e4m3fn  1.250e-01        1.562e-02  4.480e+02
   float8_e5m2  2.500e-01        6.104e-05  5.734e+04

fp32 keeps p=23p=23 mantissa bits (about seven decimal digits) and reaches up to 3.4×10383.4\times10^{38}. fp16 keeps p=10p=10 bits (about three decimal digits) but has a narrow exponent range: it overflows above 6550465504, and below 2−14≈6.1×10−52^{-14}\approx6.1\times10^{-5} its values become subnormal. bf16 (bfloat16 in the libraries) makes the opposite trade-off. It keeps all eight exponent bits of fp32, preserving its vast dynamic range, at the cost of keeping only p=7p=7 mantissa bits (εmach=2−7≈0.0078\varepsilon_{\mathrm{mach}}=2^{-7}\approx 0.0078, roughly two to three decimal digits). Notice that the value 2−82^{-8} often quoted for bf16 is its unit roundoff u=εmach/2u=\varepsilon_{\mathrm{mach}}/2. The two fp8 formats push this trade-off further still: E4M3 keeps three mantissa bits (about one decimal digit) and tops out at 448448, while E5M2 keeps two mantissa bits with fp16's exponent range. With so little dynamic range, fp8 is practical only when paired with a separate scale factor per tensor or per block of values.

Because bf16 is simply the top 16 bits of an fp32 number—the same sign bit, the same eight exponent bits, and the first seven mantissa bits—converting fp32 to bf16 amounts to rounding off the low 16 bits. We can implement that rounding directly with integer arithmetic on the raw bit pattern. The midpoint of the discarded 16 bits is 0x8000, so we add 0x7FFF (one below the midpoint), plus one more if the lowest kept bit is 11, and then clear the low 16 bits. This sum carries into the kept bits if and only if the discarded part lies strictly above the midpoint, or sits right on the midpoint with an odd kept bit. That is round-to-nearest, ties-to-even in a single line of bit manipulation; Exercise 5 builds stochastic rounding on top of it. Let us verify it on one input above a midpoint and two exact ties:

def to_bf16(x):
    """Round float32 to the nearest bfloat16, ties to even."""
    bits = np.atleast_1d(np.asarray(x, np.float32)).view(np.uint32)
    bits = (bits + 0x7FFF + ((bits >> 16) & 1)) & 0xFFFF0000
    return bits.astype(np.uint32).view(np.float32)

for x, expected in [(1 + 2**-8 + 2**-10, 1 + 2**-7),   # above the midpoint
                    (1 + 2**-8, 1.0),                  # tie, 1 is even
                    (1 + 3 * 2**-8, 1 + 2**-6)]:       # tie, 1 + 2^-6 is even
    print(f'{x:.8f} -> {to_bf16(x).item():.8f}   (expected {expected:.8f})')
1.00488281 -> 1.00781250   (expected 1.00781250)
1.00390625 -> 1.00000000   (expected 1.00000000)
1.01171875 -> 1.01562500   (expected 1.01562500)

As expected, the first input lies above the midpoint between 11 and 1+2−71+2^{-7} and rounds up. The second sits right on that midpoint and rounds down to the even neighbor 11, whereas the third sits on the midpoint between 1+2−71+2^{-7} and 1+2−61+2^{-6} and rounds up to the even neighbor 1+2−61+2^{-6}. Next, let us check the same tie rule in fp32, observe how the spacing grows with magnitude, and find the largest logit each format can exponentiate without overflow:

eps = np.finfo(np.float32).eps
one = np.float32(1.0)
print('1 + eps   != 1 :', one + eps != one)
print('1 + eps/2 == 1 :', one + np.float32(eps / 2) == one)
print('gap between float32 neighbors at 1    :', np.spacing(one))
print('gap between float32 neighbors at 2^20 :', np.spacing(np.float32(2.0**20)))
for dt in [np.float16, np.float32, np.float64]:
    print(f'{np.dtype(dt).name}: exp(x) overflows for x >',
          f'{np.log(np.finfo(dt).max):.2f}')
1 + eps   != 1 : True
1 + eps/2 == 1 : True
gap between float32 neighbors at 1    : 1.1920929e-07
gap between float32 neighbors at 2^20 : 0.125
float16: exp(x) overflows for x > 11.09
float32: exp(x) overflows for x > 88.72
float64: exp(x) overflows for x > 709.78

Here 1+εmach/21+\varepsilon_{\mathrm{mach}}/2 is the midpoint between 11 and its upper neighbor, so ties-to-even sends it back to 11. The worst-case rounding error of half a gap really does occur, giving a relative error of u/(1+u)u/(1+u), just inside the bound ∣δ∣≤u|\delta|\le u. Meanwhile, the gap at 2202^{20} is 2202^{20} times (about a million times) the gap at 11. Finally, the last three lines pinpoint where exe^x overflows: above 11.0911.09 in fp16, 88.7288.72 in fp32, and 709.78709.78 in fp64.

23.8.1.3 Overflow, Underflow, and Small Updates#

Because the exponential turns an additive scale into a multiplicative one, even modest logits can overflow. In fp16, the ceiling log⁡65504≈11.09\log 65504\approx11.09 sits well inside the range of ordinary unnormalized classifier scores.

At the opposite end, e−xe^{-x} underflows. Below the smallest normal number, a format steps through subnormal numbers that keep the same absolute spacing while shedding significant bits one by one, until values round all the way to 00. Taking log⁡0\log 0 later produces −∞-\infty, and the backward pass fills with inf or NaN. In fp16, subnormals begin below 2−14≈6.1×10−52^{-14}\approx6.1\times10^{-5}, the smallest subnormal is 2−24≈6×10−82^{-24}\approx6\times10^{-8}, and anything below 2−25≈3×10−82^{-25}\approx3\times10^{-8} rounds straight to zero.

Addition introduces a second absolute threshold that matters directly for training. A gradient step replaces a weight ww by w−ηgw-\eta g. If the update ηg\eta g is small compared with the spacing around ww, the sum simply rounds back to ww, and the step vanishes without a trace.

Proposition (small updates vanish). Let w>0w>0 be a floating-point number with 2e≤w<2e+12^e\le w\lt 2^{e+1} in a format with pp mantissa bits, and let Δ\Delta be real. If ∣Δ∣<2e−p−1|\Delta|\lt 2^{e-p-1}, then fl(w+Δ)=w\mathrm{fl}(w+\Delta)=w, except when w=2ew=2^e and Δ<0\Delta\lt 0; in that case the same holds for ∣Δ∣<2e−p−2|\Delta|\lt 2^{e-p-2}.

Proof. In [2e,2e+1][2^e, 2^{e+1}] the representable numbers are 2e−p2^{e-p} apart, so the neighbors of ww are w±2e−pw\pm2^{e-p}, except that below w=2ew=2^e the lower octave [2e−1,2e)[2^{e-1},2^e) begins and the spacing halves to 2e−p−12^{e-p-1}. Rounding to the nearest number returns ww whenever w+Δw+\Delta is closer to ww than to the adjacent grid point on its side—that is, whenever ∣Δ∣|\Delta| is strictly less than half of that gap. ■\blacksquare

For a weight update Δ=−ηg\Delta=-\eta g with 2e<w<2e+12^e\lt w\lt 2^{e+1}, the proposition reads

fl(w−ηg)=wwhenever ∣ηg∣<2e−p−1=u 2e.(23.8.3)\mathrm{fl}(w-\eta g)=w \qquad \textrm{whenever } |\eta g|\lt 2^{e-p-1}=u\,2^e . \tag{23.8.3}

In short, any update smaller than roughly u∣w∣u|w| is lost. The relative model (23.8.2) describes products and quotients well, but when we add two numbers of very different magnitudes, it hides this sharp absolute cutoff.

A weight sitting right on a power of two, such as w=1w=1, falls into the exceptional case of the proposition: because the spacing halves below 11, an increase vanishes below uu (as Section 5.5 tests), whereas a decrease already vanishes below u/2u/2. In bf16, a weight equal to 11 therefore ignores any decrease smaller than 2−9≈0.0022^{-9}\approx0.002, so a learning rate of 10−310^{-3} with an order-11 gradient leaves the weight completely frozen. The corresponding threshold is 2−12≈2.4×10−42^{-12}\approx2.4\times10^{-4} in fp16 and 2−25≈3×10−82^{-25}\approx3\times10^{-8} in fp32—which is why mixed-precision training keeps a master copy of the weights in fp32. Let us test steps straddling these thresholds (computing the bf16 updates in fp32 and rounding with to_bf16):

one32, one16 = np.float32(1.0), np.float16(1.0)
print('bfloat16: 1 - 1e-3 ->', to_bf16(one32 - np.float32(1e-3)).item())
print('bfloat16: 1 - 2e-3 ->', to_bf16(one32 - np.float32(2e-3)).item())
print('fp16    : 1 - 1e-4 ->', one16 - np.float16(1e-4))
print('fp16    : 1 - 3e-4 ->', one16 - np.float16(3e-4))
print('fp32    : 1 - 1e-3 ->', one32 - np.float32(1e-3))
bfloat16: 1 - 1e-3 -> 1.0
bfloat16: 1 - 2e-3 -> 0.99609375
fp16    : 1 - 1e-4 -> 1.0
fp16    : 1 - 3e-4 -> 0.9995
fp32    : 1 - 1e-3 -> 0.999

Sure enough, a step of 10−310^{-3} leaves the bf16 weight stuck at 11, whereas 2×10−32\times10^{-3} clears the 0.001950.00195 threshold and jumps to the neighbor 1−2−8=0.996093751-2^{-8}=0.99609375. Similarly, fp16 swallows 10−410^{-4} and responds to 3×10−43\times10^{-4} by stepping to 1−2−11≈0.99951-2^{-11}\approx0.9995, while fp32 keeps the full update.

Gradients run into the underflow threshold instead. In fp16, gradients below 6.1×10−56.1\times10^{-5} lose precision and those below 3×10−83\times10^{-8} vanish to zero. Multiplying the loss by a constant factor SS before the backward pass scales every gradient up by SS and lifts them back into the normal range; dividing by SS afterward in fp32 restores the true scale (Section 5.5.3.3 covers the practical workflow, and Exercise 1 determines the admissible window for SS).

Stochastic rounding (Gupta et al., 2015) removes the lost-update cutoff in a different way. Instead of always rounding to the nearest grid point, it rounds up or down at random with probabilities chosen so that the expected stored value equals the exact result. Updates far too small for round-to-nearest then still accumulate over many steps in expectation (Exercise 5).

23.8.2 Stable Softmax and Cross-Entropy#

Softmax, log-sum-exp, and cross-entropy all exponentiate logits, so all three collide head-on with the overflow and underflow thresholds we just computed. To keep everything concrete, we will carry one running example through this subsection: a two-class classifier with logits z=(0,t)\mathbf z=(0,t) whose true label is the unlikely class 00. Its probabilities are softmax(z)=(1/(1+et), et/(1+et))\mathrm{softmax}(\mathbf z)=\bigl(1/(1+e^t),\, e^t/(1+e^t)\bigr), its log-sum-exp is log⁡(1+et)\log(1+e^t), and the cross-entropy loss for class 00 is log⁡(1+et)≈t\log(1+e^t)\approx t for large tt. None of these outputs is extreme: even at t=100t=100, the probabilities are 3.7×10−443.7\times10^{-44} and 11, and the loss is simply 100100.

23.8.2.1 The Max Shift#

Given logits z∈Rn\mathbf z\in\mathbb R^n, the softmax vector is defined by

softmax(z)i=ezi∑j=1nezj.\mathrm{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^n e^{z_j}} .

At t=100t=100, evaluating this formula directly forms e100e^{100}, which exceeds fp32's overflow ceiling of 88.7288.72. The second entry turns into inf/inf (NaN), and the first collapses to 1/∞=01/\infty=0. Notice that the true probabilities themselves fit easily in fp32; only the intermediate exponential does not.

Luckily, multiplying numerator and denominator by the same positive constant e−ce^{-c} leaves the ratio untouched, so softmax is shift-invariant:

softmax(z−c1)=softmax(z)for every c∈R.(23.8.4)\mathrm{softmax}(\mathbf{z} - c\mathbf{1}) = \mathrm{softmax}(\mathbf{z}) \qquad \textrm{for every } c \in \mathbb{R}. \tag{23.8.4}

Factoring ece^c out of the sum inside a logarithm gives the companion identity for log-sum-exp, lse(z)=log⁡∑jezj\mathrm{lse}(\mathbf{z}) = \log \sum_j e^{z_j}, which is the logarithm of the softmax denominator:

lse(z)=c+log⁡∑j=1nezj−c.(23.8.5)\mathrm{lse}(\mathbf{z}) = c + \log \sum_{j=1}^n e^{z_j - c} . \tag{23.8.5}

Both identities hold for any c∈Rc\in\mathbb{R}, and choosing c=max⁡jzjc=\max_j z_j makes both computations safe. Every shifted exponent zj−cz_j-c is then at most 00, so no exponential can overflow. At the same time, the largest term equals e0=1e^0=1, so the sum is guaranteed to lie in [1,n][1,n] and its logarithm cannot underflow to −∞-\infty. Let us test this on (0,100)(0, 100) in fp32, on the opening's (1000,1001,1002)(1000, 1001, 1002) in fp64, and on (0,10)(0, 10) where both versions stay finite—do they return the exact same bits there?

def softmax_naive(z):
    e = np.exp(z)
    return e / e.sum()

def softmax_stable(z):
    e = np.exp(z - z.max())        # shift by the max: largest exponent is 0
    return e / e.sum()

z = np.array([0.0, 100.0], dtype=np.float32)
with np.errstate(over='ignore', invalid='ignore'):
    print('naive  softmax(0, 100):', softmax_naive(z))
print('stable softmax(0, 100):', softmax_stable(z))
z = np.array([1000.0, 1001.0, 1002.0])        # the opening's logits, fp64
with np.errstate(over='ignore', invalid='ignore'):
    print('naive  softmax(1000, 1001, 1002):', softmax_naive(z))
print('stable softmax(1000, 1001, 1002):', softmax_stable(z).round(4))
z = np.array([0.0, 10.0], dtype=np.float32)
a, b = softmax_naive(z), softmax_stable(z)
print('softmax(0, 10), naive minus stable, in ulps:',
      (a - b) / np.spacing(b))
naive  softmax(0, 100): [ 0. nan]
stable softmax(0, 100): [3.8e-44 1.0e+00]
naive  softmax(1000, 1001, 1002): [nan nan nan]
stable softmax(1000, 1001, 1002): [0.09   0.2447 0.6652]
softmax(0, 10), naive minus stable, in ulps: [2. 0.]

At t=100t=100, the shifted softmax returns (3.8×10−44,1)(3.8\times10^{-44}, 1), the true 3.7×10−443.7\times10^{-44} rounded onto the subnormal grid with five significant bits left, while the direct formula returns 00 and NaN. Switching to higher precision does not cure the problem: the logits (1000,1001,1002)(1000, 1001, 1002) from the opening overflow e1000e^{1000} even in fp64, turning the direct formula into three NaNs where the shifted version cleanly returns (0.09,0.24,0.67)(0.09, 0.24, 0.67). At t=10t=10, the two formulas either agree to the last bit or differ by one or two units in the last place (ulps), because real-number identities do not guarantee identical rounding orders. One edge case remains: the max shift cannot rescue non-finite logits—if an entire row is −∞-\infty, then c=−∞c=-\infty and zj−cz_j-c is undefined.

23.8.2.2 Bounds for Log-Sum-Exp#

Log-sum-exp is the log-normalizer of every exponential-family model (Section 24.4), and up to a single subtraction it is the cross-entropy loss. The shift (23.8.5) immediately tells us how close it sits to the largest logit:

Proposition (log-sum-exp sandwich). For every z∈Rn\mathbf{z} \in \mathbb{R}^n,

max⁡jzj  ≤  lse(z)  ≤  max⁡jzj+log⁡n.\max_j z_j \;\le\; \mathrm{lse}(\mathbf{z}) \;\le\; \max_j z_j + \log n .

Proof. Set c=max⁡jzjc = \max_j z_j in (23.8.5). Every exponential ezj−ce^{z_j - c} lies in (0,1](0, 1] and the maximizing term equals 11, so the sum lies in [1,n][1, n] and its logarithm in [0,log⁡n][0, \log n]. Adding cc yields both bounds. ■\blacksquare

Log-sum-exp is therefore a soft maximum. In our two-class example, lse(0,t)=log⁡(1+et)\mathrm{lse}(0,t)=\log(1+e^t) stays within log⁡2≈0.69\log 2\approx0.69 of max⁡(0,t)\max(0,t), attaining the full gap at t=0t=0 where the two logits tie and hugging the maximum closely as ∣t∣|t| grows (Figure 23.8.2).

Figure 23.8.2:

Log-sum-exp as a soft maximum: lse(0,t)=log⁡(1+et)\mathrm{lse}(0,t)=\log(1+e^t) stays within log⁡2\log 2 of max⁡(0,t)\max(0,t), matching the sandwich bound for n=2n=2. The gap peaks at t=0t=0, where the two logits tie, and vanishes as ∣t∣|t| grows.

Moreover, its gradient is the softmax itself, ∂ lse(z)/∂zi=ezi/∑jezj=softmax(z)i\partial\,\mathrm{lse}(\mathbf z)/\partial z_i=e^{z_i}/\sum_j e^{z_j}=\mathrm{softmax}(\mathbf z)_i. That is why the gradient of cross-entropy with respect to the logits, for label yy, simplifies to softmax(z)−ey\mathrm{softmax}(\mathbf z)-\mathbf e_y; Section 23.3 also shows that log-sum-exp is convex.

Subtracting the shifted log-sum-exp from the shifted logit yields the log-softmax, computing log-probabilities directly without ever forming the probabilities themselves:

log⁡softmax(z)i=(zi−c)−log⁡∑j=1nezj−c,c=max⁡jzj.(23.8.6)\log \mathrm{softmax}(\mathbf{z})_i = (z_i - c) - \log \sum_{j=1}^n e^{z_j - c}, \qquad c=\max_j z_j . \tag{23.8.6}

Because we never exponentiate the final result, a tiny probability cannot underflow to zero before its logarithm is taken. Notice a subtle detail in (23.8.6): the algebraically equivalent form zi−lse(z)z_i-\mathrm{lse}(\mathbf z) is noticeably worse in floating point, because it first forms the large number lse=c+log⁡∑jezj−c\mathrm{lse}=c+\log\sum_j e^{z_j-c} and then subtracts it from the large number ziz_i. How much difference does that parenthesization make? Let us compare both forms in fp32 on the logits (1000,1001,1002)(1000, 1001, 1002):

z = np.array([1000.0, 1001.0, 1002.0], dtype=np.float32)
c = z.max()
s = np.log(np.exp(z - c).sum())           # log sum exp(z - c), in [0, log 3]
with np.errstate(over='ignore'):
    print('naive log(sum(exp(z))):', np.log(np.exp(z).sum()))
lse = c + s
print('lse = c + s           :', lse, '  float32 gap at 1002:', np.spacing(c))
log_p_sub = z - lse                       # forms lse, then subtracts it
log_p = (z - c) - s                       # never forms c + s
print(f'sum of exp(z - lse)    : {np.exp(log_p_sub).sum():.8f}')
print(f'sum of exp((z - c) - s): {np.exp(log_p).sum():.8f}')
naive log(sum(exp(z))): inf
lse = c + s           : 1002.4076   float32 gap at 1002: 6.1035156e-05
sum of exp(z - lse)    : 1.00001323
sum of exp((z - c) - s): 1.00000000

The direct computation overflows to inf—as it would even in fp64, since 1000>709.781000>709.78, which is what turned inf/inf into three NaNs in the opening. The shifted value lse=1002.4076\mathrm{lse}=1002.4076 sits comfortably inside the sandwich [1002,1002+log⁡3][1002, 1002+\log 3]. More interestingly, the two log-softmax forms disagree: exponentiating zi−lsez_i-\mathrm{lse} gives probabilities that sum to 1.00001321.0000132, whereas (23.8.6) sums to 1.00000001.0000000.

Why did zi−lsez_i-\mathrm{lse} lose accuracy? Surprisingly, the subtraction itself made no error at all. Whenever two floating-point numbers lie within a factor of two of each other, their difference is exactly representable, because both are multiples of the smaller number's spacing and their difference needs no extra bits (Sterbenz's lemma, Exercise 6).

The error entered earlier, when lse\mathrm{lse} was stored. Near 10021002, fp32 numbers are 2−14≈6.1×10−52^{-14}\approx6.1\times10^{-5} apart, so the true value 1002.40760601002.4076060 rounds down by 1.32×10−51.32\times10^{-5}. Every log-probability computed as zi−lsez_i-\mathrm{lse} is therefore 1.32×10−51.32\times10^{-5} too high, every resulting probability is inflated by the factor e1.32×10−5e^{1.32\times10^{-5}}, and their sum overshoots 11 by 1.32×10−51.32\times10^{-5}. An absolute error in an exponent turns into a relative error of the same size after exponentiation, and the subtraction merely exposed an error that was already sitting in its input—the central theme of Section 23.8.3.

23.8.2.3 Cross-Entropy from Logits#

The cross-entropy loss for label yy is simply the negative log-softmax, so (23.8.6) gives it directly from the logits:

−log⁡softmax(z)y=lse(z)−zy.(23.8.7)-\log \mathrm{softmax}(\mathbf{z})_y = \mathrm{lse}(\mathbf{z}) - z_y . \tag{23.8.7}

Computing the loss this way requires one stable log-sum-exp and one subtraction, without ever forming a probability. On our running example, the loss for class 00 is lse(0,t)−0=log⁡(1+et)\mathrm{lse}(0,t)-0=\log(1+e^t). If we instead compute probabilities first, the true-class probability e−t/(1+e−t)≈e−te^{-t}/(1+e^{-t})\approx e^{-t} drops below fp32's normal range once t>87.3t>87.3 and underflows completely to zero near t=104t=104, sending its negative logarithm to ∞\infty. Let us compare the two routes using the library's built-in functions, with t=103t=103 and 104104 straddling that cliff:

print('    t  CE from logits    CE via probabilities')
for t in [20.0, 60.0, 103.0, 104.0]:
    logits = torch.tensor([[0.0, t]])
    y = torch.tensor([0])                        # label = the unlikely class
    from_logits = F.cross_entropy(logits, y)
    probs = F.softmax(logits, dim=1)             # stable softmax, then...
    from_probs = -torch.log(probs[0, y])         # ...take the log yourself
    print(f'{t:5.0f}  {from_logits.item():15.4f}  {from_probs.item():15.4f}')
    t  CE from logits    CE via probabilities
   20          20.0000          20.0000
   60          60.0000          60.0000
  103         103.0000         103.2789
  104         104.0000              inf

Computed directly from logits, the loss equals tt in every row, and the probability route matches it at t=20t=20 and 6060. At t=103t=103, however, the probability e−103e^{-103} falls into the subnormal range, and what happens next depends on how the library handles subnormal numbers.

PyTorch preserves subnormals: e−103≈1.32×2−149e^{-103}\approx1.32\times2^{-149} rounds to the smallest fp32 subnormal, 2−1492^{-149}. Only a single significant bit survives, so the loss reads 149log⁡2=103.2789149\log 2=103.2789—wrong in the first decimal place with no warning. At t=104t=104, e−104<2−150e^{-104}\lt 2^{-150} rounds to 00, and the loss becomes inf.

The practical takeaway is simple: keep losses, likelihoods, and posteriors in log space until you actually need a probability. The fused loss in Section 3.3.5.2 implements (23.8.7) for this reason, Section 25.1 interprets what cross-entropy measures, and Section 24.11 sums hundreds of per-pixel log-probabilities to avoid the same underflow.

23.8.3 Catastrophic Cancellation#

23.8.3.1 The Condition Number of a Function#

In fp32, evaluating log⁡(1+x)\log(1+x) at x=10−8x=10^{-8} returns 00—a relative error of 100%—whereas the library function log1p returns 10−810^{-8}. Is log⁡(1+x)\log(1+x) near x=0x=0 inherently hard to compute, or is the formula to blame? To answer questions like this systematically, we need a quantity that measures how strongly a function amplifies errors in its input, independent of any particular algorithm.

The relative condition number of a differentiable function ff at a point xx with f(x)≠0f(x)\ne0 is the factor by which a small relative perturbation in xx turns into a relative perturbation in f(x)f(x). Perturbing xx to x(1+δ)x(1+\delta) changes the output, to first order, to f(x(1+δ))≈f(x)+xf′(x) δf(x(1+\delta))\approx f(x)+xf'(x)\,\delta. Dividing the change by f(x)f(x) gives the amplification factor

κf(x)=∣x f′(x)f(x)∣.(23.8.8)\kappa_f(x)=\left|\frac{x\,f'(x)}{f(x)}\right| . \tag{23.8.8}

For example, the exponential has κf(x)=∣x∣\kappa_f(x)=|x|: at x=88x=88, an input error of one unit roundoff becomes 8888 units in the output. That is the exact mechanism we just saw in the log-softmax cell, where an absolute error in an exponent became a relative error of the same size in the probability. Notice that κf\kappa_f is a first-order property of the exact mathematical function. It says nothing about how ff is evaluated, and it breaks down where f(x)=0f(x)=0, since relative error is undefined there.

Subtraction takes two inputs, and the same first-order reasoning applies to both. Suppose a^=a(1+δa)\hat a=a(1+\delta_a) and b^=b(1+δb)\hat b=b(1+\delta_b) carry relative errors ∣δa∣,∣δb∣≤u|\delta_a|,|\delta_b|\le u, and suppose the subtraction itself is exact. Then a^−b^=(a−b)+(aδa−bδb)\hat a-\hat b=(a-b)+(a\delta_a-b\delta_b), so the triangle inequality bounds the relative error of the difference by

∣(a^−b^)−(a−b)∣∣a−b∣=∣aδa−bδb∣∣a−b∣≤∣a∣+∣b∣∣a−b∣  u.(23.8.9)\frac{|(\hat a-\hat b)-(a-b)|}{|a-b|} =\frac{|a\delta_a-b\delta_b|}{|a-b|} \le \frac{|a| + |b|}{|a - b|}\; u . \tag{23.8.9}

The factor (∣a∣+∣b∣)/∣a−b∣(|a|+|b|)/|a-b| is subtraction's condition number, and it blows up whenever a≈ba\approx b. Subtracting two nearly equal numbers that already carry rounding errors is called catastrophic cancellation: the accurate leading digits cancel out, promoting the noise in the trailing digits into the leading digits of the answer. For reference, the table below collects the condition numbers of several common problems:

problemκf\kappa_fregime
a−ba-b(∣a∣+∣b∣)/∣a−b∣(\lvert a\rvert+\lvert b\rvert)/\lvert a-b\rvertlarge when a≈ba\approx b
log⁡(1+x)\log(1+x)x/((1+x)log⁡(1+x))x/((1+x)\log(1+x))1.0001.000 at x=10−8x=10^{-8}, 0.820.82 at x=0.5x=0.5
exe^x∣x∣\lvert x\rvertlarge for large ∣x∣\lvert x\rvert
1−cos⁡x1-\cos xxsin⁡x/(1−cos⁡x)x\sin x/(1-\cos x)tends to 22 as x→0x\to0
x\sqrt x1/21/2always
variance of data with mean mm, spread ssat most 2(1+∣m∣/s)2(1+\lvert m\rvert/s)derived below

The second row settles our opening question: log⁡(1+x)\log(1+x) near x=0x=0 is completely well conditioned (κf≈1\kappa_f\approx 1). The naive algorithm log(1 + x) fails because it takes a detour through an ill-conditioned intermediate step. It first forms y=1+xy=1+x and then evaluates log⁡y\log y at y≈1y\approx 1, where the logarithm has κlog⁡(y)=1/∣log⁡y∣≈1/x=108\kappa_{\log}(y)=1/|\log y|\approx 1/x=10^8. Rounding 1+x1+x introduces a relative error of order uu in yy, which log⁡\log magnifies by 10810^8—more than 100% in fp32. By contrast, log1p is written so that the rounding error of 1+x1+x never enters the result; for tiny xx, it simply returns xx.

This gives us the organizing principle of the entire section: an unstable algorithm routes a well-conditioned problem through an ill-conditioned intermediate step. Whenever κf\kappa_f is small and the computed answer is bad, the algorithm is at fault and we should rewrite it. Whenever κf\kappa_f itself is large, no algorithm can rescue the answer—we must change the problem instead, which is the subject of Section 23.8.4.

23.8.3.2 Subtraction of Nearly Equal Numbers#

Let us test this in code. The cell below repeats the log⁡(1+x)\log(1+x) experiment and then subtracts two fp32 numbers that agree in their first seven decimal digits, 1.00023441.0002344 and 1.00023411.0002341, whose true difference is 3.0×10−73.0\times10^{-7}:

x = np.float32(1e-8)
print('float32 rounds 1 + x to:', np.float32(1.0) + x)
print('log(1 + x) =', np.log(np.float32(1.0) + x), '   log1p(x) =', np.log1p(x))
a, b = np.float32(1.0002344), np.float32(1.0002341)
print(f'stored a = {float(a):.10f}, b = {float(b):.10f}')
print('a - b =', a - b, '=', (a - b) / np.spacing(np.float32(1.0)), 'ulps of 1')
print('float64: log(1 + 1e-20) =', np.log(1 + 1e-20),
      '  log1p(1e-20) =', np.log1p(1e-20))
float32 rounds 1 + x to: 1.0
log(1 + x) = 0.0    log1p(x) = 1e-08
stored a = 1.0002343655, b = 1.0002341270
a - b = 2.3841858e-07 = 2.0 ulps of 1
float64: log(1 + 1e-20) = 0.0   log1p(1e-20) = 1e-20

Between 11 and 22, every fp32 difference is an integer multiple of εmach=1.19×10−7\varepsilon_{\mathrm{mach}}=1.19\times10^{-7}, and the true difference 3.0×10−73.0\times10^{-7} does not fall on that grid. The subtraction returned two ulps, 2.38×10−72.38\times10^{-7} (20% too small), yet once again it committed no error of its own. The inputs were stored as 1.00023436551.0002343655 and 1.00023412701.0002341270, and their exact difference is what the cell printed; the error was already baked into the stored inputs. Here the cancellation factor (23.8.9) is 2.0005/(3×10−7)≈7×1062.0005/(3\times10^{-7})\approx7\times10^6. Multiplied by u≈6×10−8u\approx6\times10^{-8}, it allows a relative error of up to 0.40.4, and the observed 0.20.2 falls squarely inside the bound.

The same cancellation appears in log⁡(1+x)\log(1+x) and ex−1e^x-1 near 00 (where log1p and expm1 avoid it), in 1−cos⁡x1-\cos x near 00 (rewritten as 2sin⁡2(x/2)2\sin^2(x/2)), and in the quadratic formula when b2≫4∣ac∣b^2\gg 4|ac| (Exercise 2). In every one of these cases, an algebraic rewrite removes the offending subtraction.

Finite differences are the one place where we cannot eliminate the subtraction and must settle for a compromise. A numerical gradient check compares automatic differentiation against the forward difference (f(x+h)−f(x))/h(f(x+h)-f(x))/h. How small should we make the step hh? By Taylor's theorem, the mathematical truncation error is about h2∣f′′(x)∣\tfrac h2|f''(x)|, which shrinks as h→0h\to 0. Meanwhile, each function evaluation carries a rounding error of roughly u∣f(x)∣u|f(x)|, and dividing their difference by hh magnifies that error to about 2u∣f(x)∣/h2u|f(x)|/h, which blows up as h→0h\to 0. The total error is minimized where the two terms balance, at

h⋆=2u ∣f(x)∣∣f′′(x)∣,with error about 2u ∣f(x)f′′(x)∣.h^\star=2\sqrt{\frac{u\,|f(x)|}{|f''(x)|}}, \qquad \textrm{with error about } 2\sqrt{u\,|f(x)f''(x)|} .

Because the optimal error scales as u\sqrt{u}, the best possible forward difference keeps only about half of the format's digits. For f=sin⁡f=\sin at x=1x=1, this predicts h⋆≈2×10−8h^\star\approx2\times10^{-8} (error 1.8×10−81.8\times10^{-8}) in fp64 and h⋆≈5×10−4h^\star\approx5\times10^{-4} in fp32. Let us sweep hh from 10−210^{-2} down to 10−1210^{-12} in both formats to see the trade-off directly:

print('      h   error in fp64   error in fp32')
for h in 10.0 ** -np.arange(2, 13):
    err = [abs(float((np.sin(t(1) + t(h)) - np.sin(t(1))) / t(h)) - np.cos(1.0))
           for t in (np.float64, np.float32)]  # forward difference of sin at 1
    print(f'{h:7.0e}  {err[0]:14.1e}  {err[1]:14.1e}')
      h   error in fp64   error in fp32
  1e-02         4.2e-03         4.2e-03
  1e-03         4.2e-04         4.0e-04
  1e-04         4.2e-05         2.8e-04
  1e-05         4.2e-06         3.9e-03
  1e-06         4.2e-07         6.3e-02
  1e-07         4.2e-08         5.6e-02
  1e-08         3.0e-09         5.4e-01
  1e-09         5.3e-08         5.4e-01
  1e-10         5.8e-08         5.4e-01
  1e-11         1.2e-06         5.4e-01
  1e-12         4.3e-05         5.4e-01

In fp64, the error drops linearly with hh from 4×10−34\times10^{-3} at h=10−2h=10^{-2} (where truncation dominates) down to roughly 10−810^{-8} near h=10−8h=10^{-8} (the exact value at any single hh fluctuates with rounding noise), and then climbs back to 4×10−54\times10^{-5} at h=10−12h=10^{-12} as cancellation takes over. In fp32, the sweet spot at h=10−3h=10^{-3} to 10−410^{-4} leaves only about three correct digits; from h=10−8h=10^{-8} downward, 1+h1+h rounds straight to 11, making the difference quotient 00 and the error equal to the entire derivative, cos⁡1=0.54\cos 1=0.54. That is why numerical gradient checks should always run in fp64.

Notice, too, that switching to higher precision never cures cancellation—it merely pushes the failure to smaller inputs. The last line of the earlier log1p cell showed log(1 + 1e-20) returning 00 in fp64 just as fp32 did at 10−810^{-8}, while log1p stayed accurate in both. Reformulating the expression removes the ill-conditioned step itself (Higham, 2002).

23.8.3.3 One-Pass Variance#

Catastrophic cancellation also hides inside formulas that look completely innocent. Computing a sample variance is the classic example—and it matters directly in deep learning, where normalization layers and data-preprocessing pipelines compute variances continuously.

For data x1,…,xNx_1,\ldots,x_N with mean mm and standard deviation ss, the textbook identity

1N∑i=1N(xi−m)2=1N∑i=1Nxi2−m2,\frac1N\sum_{i=1}^N(x_i-m)^2 = \frac1N\sum_{i=1}^N x_i^2 - m^2 ,

tempts us to compute the variance in a single pass by accumulating only the sums of xix_i and xi2x_i^2. In exact arithmetic the identity is flawless; in floating point it is a trap. Whenever s≪∣m∣s\ll|m|, both terms on the right sit near m2m^2 while their difference is s2s^2, so the cancellation factor (23.8.9) is roughly 2m2/s22m^2/s^2. For m=109m=10^9 and s=1s=1, that factor reaches 2×10182\times10^{18}—two orders of magnitude larger than the 101610^{16} that fp64 can absorb.

How much of this loss is forced by the problem itself? Let us check the condition number of the variance. Perturb each input xix_i by a relative error δi\delta_i with ∣δi∣≤u|\delta_i|\le u, replacing xix_i by xi+xiδix_i+x_i\delta_i. The derivative of the variance with respect to xix_i is 2N(xi−m)\tfrac2N(x_i-m), because the induced change in mm multiplies ∑i(xi−m)=0\sum_i(x_i-m)=0. Writing xi=(xi−m)+mx_i=(x_i-m)+m, the first-order change in the variance is therefore

2N∑i=1N(xi−m) xiδi=2N∑i=1N(xi−m)2δi+2mN∑i=1N(xi−m) δi.\frac2N\sum_{i=1}^N(x_i-m)\,x_i\delta_i =\frac2N\sum_{i=1}^N(x_i-m)^2\delta_i+\frac{2m}N\sum_{i=1}^N(x_i-m)\,\delta_i .

The first sum has magnitude at most 2s2u2s^2 u. By the Cauchy–Schwarz inequality, the second has magnitude at most 2∣m∣u⋅1N∑i∣xi−m∣≤2∣m∣s u2|m|u\cdot\frac1N\sum_i|x_i-m|\le 2|m|s\,u. Dividing by s2s^2 shows that the relative condition number of the variance is at most 2(1+∣m∣/s)≈2∣m∣/s2(1+|m|/s)\approx 2|m|/s, or about 2×1092\times10^9 here (choosing δi=u sign(xi−m)\delta_i=u\,\mathrm{sign}(x_i-m) gives 1.6 ∣m∣/s1.6\,|m|/s for Gaussian data). The problem itself therefore permits an error of only 2×109u≈2×10−72\times10^9 u\approx 2\times10^{-7}—about seven accurate digits. The naive one-pass formula, by contrast, suffers an error of order (m/s)2u(m/s)^2 u: it squares the condition number, just as the normal equations will square the condition number of a matrix in Section 23.8.4.

A stable one-pass algorithm keeps all deviations at the scale ss rather than m2m^2. Welford (1962) maintains a running mean mkm_k and a running sum of centered squares Mk=∑i≤k(xi−mk)2M_k = \sum_{i \le k} (x_i - m_k)^2, updating both from the deviation dk=xk−mk−1d_k=x_k-m_{k-1} of each new sample from the previous mean:

mk=mk−1+dkk,Mk=Mk−1+dk (xk−mk).(23.8.10)m_k = m_{k-1} + \frac{d_k}{k}, \qquad M_k = M_{k-1} + d_k\,(x_k - m_k). \tag{23.8.10}

Notice the asymmetry in the update of MkM_k: it multiplies the deviation from the old mean by the deviation from the new mean. That asymmetry is precisely what makes the recursion exact:

Proposition (Welford's recursion). With m0=M0=0m_0 = M_0 = 0, the recursions (23.8.10) satisfy, for every k≥1k \ge 1 and in exact arithmetic,

mk=1k∑i=1kxi,Mk=∑i=1k(xi−mk)2.m_k = \frac{1}{k} \sum_{i=1}^k x_i, \qquad M_k = \sum_{i=1}^k (x_i - m_k)^2 .

Proof. The mean identity k mk=(k−1) mk−1+xkk\, m_k = (k-1)\, m_{k-1} + x_k follows immediately from the first recursion. For MkM_k, we induct on kk. Using mk−mk−1=dk/km_k - m_{k-1} = d_k/k and xk−mk=dk (k−1)/kx_k - m_k = d_k\,(k-1)/k, we split off the kk-th term and recenter the first k−1k-1 terms around mk−1m_{k-1}:

∑i=1k(xi−mk)2=∑i=1k−1((xi−mk−1)−dkk)2+(xk−mk)2=Mk−1+(k−1)dk2k2+(k−1)2k2dk2.\begin{aligned} \sum_{i=1}^{k} (x_i - m_k)^2 &= \sum_{i=1}^{k-1} \left( (x_i - m_{k-1}) - \tfrac{d_k}{k} \right)^2 + (x_k - m_k)^2 \\ &= M_{k-1} + (k-1)\tfrac{d_k^2}{k^2} + \tfrac{(k-1)^2}{k^2}d_k^2 . \end{aligned}

The cross term vanishes because ∑i≤k−1(xi−mk−1)=0\sum_{i \le k-1} (x_i - m_{k-1}) = 0, and the inductive hypothesis identifies the first sum as Mk−1M_{k-1}. Combining the remaining two terms gives k−1k dk2=dk⋅dkk−1k=dk(xk−mk)\frac{k-1}{k}\,d_k^2 = d_k \cdot d_k\frac{k-1}{k} = d_k(x_k - m_k), which is exactly what the recursion adds. ■\blacksquare

Proving that Welford's recursion also stays accurate in floating point is the harder step, and we sketch only the intuition here (see Higham (2002) for the full analysis). At first glance, Welford's update still subtracts large numbers, since xkx_k and mk−1m_{k-1} both sit near 10910^9. By Sterbenz's lemma, however, that subtraction is exact, and xkx_k is exact input data, so the only error in dkd_k comes from the running mean—at most a few dozen ulps at ∣m∣|m| over 10510^5 steps. Every quantity added into MkM_k is therefore a deviation of scale ss, so rounding errors in the updates enter relative to s2s^2 rather than m2m^2. Even a constant offset ε\varepsilon in the mean shifts a centered sum of squares only by Nε2N\varepsilon^2, because the first-order term multiplies ∑i(xi−m)=0\sum_i(x_i-m)=0. In practice, Welford's error matches the problem's own sensitivity, u∣m∣/s≈1.1×10−7u|m|/s\approx 1.1\times10^{-7}, whereas the naive one-pass formula suffers an error of (m/s)2u≈100(m/s)^2 u\approx 100.

Let us compare all three methods—naive one-pass, Welford, and a two-pass reference—on 10510^5 fp64 samples with mean 10910^9 and variance 11:

rng = np.random.default_rng()
x = 1e9 + rng.normal(0.0, 1.0, size=100_000)    # mean 1e9, variance 1

naive = (x**2).mean() - x.mean()**2             # one pass, cancels
two_pass = ((x - x.mean())**2).mean()           # subtract the mean first

m, M = 0.0, 0.0                                 # Welford: one pass
for k, xk in enumerate(x, start=1):
    d = xk - m
    m += d / k                                  # m_k
    M += d * (xk - m)                           # M_k
welford = M / len(x)

print(f'naive E[x^2] - E[x]^2 : {naive:12.6f}   (= {naive / 128:.0f} x 128)')
print(f'Welford, one pass     : {welford:12.6f}')
print(f'two-pass reference    : {two_pass:12.6f}')
print(f'Welford vs two-pass   : {abs(welford - two_pass) / two_pass:.1e} relative')
print('float64 gap near 1e18 :', np.spacing(1e18))
naive E[x^2] - E[x]^2 :  -128.000000   (= -1 x 128)
Welford, one pass     :     0.999287
two-pass reference    :     0.999287
Welford vs two-pass   : 6.8e-09 relative
float64 gap near 1e18 : 128.0

The naive one-pass estimate comes out as an exact multiple of 128128 (typically 00, ±128\pm128, or ±256\pm256), nowhere near the true variance 11, and frequently negative. Why 128128? Both 1N∑xi2\frac1N\sum x_i^2 and m2m^2 lie in [259,260)[2^{59}, 2^{60}), where adjacent fp64 numbers are 259−52=1282^{59-52}=128 apart, so their difference can only be a multiple of 128128: our predicted error of about 100100, quantized to the grid. Welford's recursion, on the other hand, matches the two-pass reference to at least seven digits—and often eight or nine, because rounding errors of opposite signs partly cancel across the sum.

The same caution applies whenever a variance is accumulated in one pass, such as computing streaming statistics over a dataset. (The running moments that batch normalization maintains for inference are exponential moving averages, Section 7.3, which do not subtract large running sums.)

23.8.3.4 Summation Order#

Both the naive variance and the two-pass reference sum 10510^5 numbers, and in floating point the order of addition matters. Each addition introduces a factor (1+δk)(1+\delta_k), so in a plain left-to-right sum the first term passes through all n−1n-1 roundings. To first order in uu, a left-to-right sum satisfies

∣fl(∑i=1nxi)−∑i=1nxi∣≤(n−1) u∑i=1n∣xi∣.\Bigl|\mathrm{fl}\Bigl(\sum_{i=1}^n x_i\Bigr)-\sum_{i=1}^n x_i\Bigr| \le(n-1)\,u\sum_{i=1}^n|x_i| .

Because early terms accumulate the rounding error of every subsequent addition, the worst-case error grows linearly with nn. Pairwise summation avoids this by recursively summing the two halves of the array, so every term passes through only log⁡2n\log_2 n additions and the bound shrinks to ulog⁡2n∑i∣xi∣u\log_2 n\sum_i|x_i|; NumPy's sum uses a blocked version of this idea. Kahan's compensated summation goes one step further, carrying each addition's rounding error in a running correction variable to achieve an error bound independent of nn (Exercise 8). Let us add 10710^7 copies of fp32's 0.10.1 (whose stored value is 0.100000001490…0.100000001490\ldots) both left to right and pairwise, padding the pairwise array with zeros to 2242^{24} entries and repeatedly adding adjacent pairs:

x = np.full(10_000_000, 0.1, dtype=np.float32)
exact = len(x) * float(x[0])                  # x[0] = 0.100000001490...
s = np.concatenate([x, np.zeros(2**24 - len(x), np.float32)])  # pad to 2^24
while len(s) > 1:                             # pairwise: add neighbors, halve
    s = s[0::2] + s[1::2]
print(f'in order (cumsum): {np.cumsum(x)[-1]:16.4f}')
print(f'pairwise         : {s[0]:16.4f}')
print(f'exact            : {exact:16.4f}')
in order (cumsum):     1087937.0000
pairwise         :     1000000.0000
exact            :     1000000.0149

The left-to-right sum finishes at 1,087,9371{,}087{,}937—almost 9% too high, though still inside its bound (n−1)u∑i∣xi∣≈6×105(n-1)u\sum_i|x_i|\approx6\times10^5. Pairwise summation lands at 1,000,0001{,}000{,}000, within 0.0150.015 of the exact sum and well inside its bound ulog⁡2n∑i∣xi∣≈1.4u\log_2 n\sum_i|x_i|\approx1.4.

The culprit behind the left-to-right drift is the same grid effect that erased small weight updates: each addend is rounded to the spacing of the current running sum. Once the sum crosses 219=524,2882^{19}=524{,}288, fp32 numbers sit 1/161/16 apart, so 0.10.1 equals 1.61.6 gaps and every addition rounds up to two gaps, 0.1250.125—25% too large. Above 2202^{20} the spacing doubles to 1/81/8, and each addend again rounds to 0.1250.125; earlier, between 2172^{17} and 2192^{19}, it rounded down to 0.093750.09375. Because floating-point addition is not associative, a parallel reduction across GPU threads need not produce the exact same bits from one device or run to another. Fortunately, Welford's recursion also supports pairwise reduction: the merge rule in Exercise 7 combines statistics from two partial sums, which is how running moments are merged across devices in distributed training.

23.8.4 Conditioning#

The condition number of a matrix and the filter factors of ridge regression are developed in Section 21.5. New here are forward and backward error, a formula that measures the backward error, and the price in digits of the normal equations.

23.8.4.1 Two Nearly Parallel Lines#

So far the answer of a computation was a number. For a linear system it is a vector, and Section 21.5.3.2 showed on the system

x1+x2=2,x1+1.0001 x2=2.0001,x_1+x_2=2, \qquad x_1+1.0001\,x_2=2.0001 ,

how fragile such an answer can be. The solution is (1,1)(1,1), and raising the second right-hand side by 10−410^{-4}, a relative change of 3.5×10−53.5\times10^{-5} in the data, moves it to (0,2)(0,2). Each equation is a line in the plane, and the solution is where the lines cross. These two lines have slopes −1-1 and −0.9999-0.9999 and meet at an angle of 0.003∘0.003^\circ, so shifting one of them slightly slides the crossing far along the other (Figure 23.8.3).

Figure 23.8.3:

A linear system is sensitive when its lines are nearly parallel. (a) Two perpendicular lines meet at (1,1)(1,1); shifting the second by 0.10.1 moves the crossing by 5%: amplification 11, κ=1\kappa=1. (b) The lines x1+x2=2x_1+x_2=2 and x1+1.1x2=2.1x_1+1.1x_2=2.1 also meet at (1,1)(1,1), but the same shift moves the crossing to (0,2)(0,2), a 100% change from a 3.4% change in b\mathbf{b}: amplification 2929, bounded by κ≈42\kappa\approx42. The text's system, with 1.00011.0001 in place of 1.11.1, has the same geometry at an angle of 0.003∘0.003^\circ and κ≈4×104\kappa\approx4\times10^4.

Let us read the same numbers in the other direction. Suppose a solver returned x^=(0,2)\hat{\mathbf x}=(0,2) for the original system. Its forward error, the distance to the true solution, is 100%. Yet (0,2)(0,2) is the exact solution of a nearby problem, the one with b2b_2 changed by 10−410^{-4}. The smallest such change of the data is the backward error. A solver with a tiny backward error has solved a nearby problem exactly, and it can still be far from the answer.

How far is a property of the problem, not of the solver. It is the condition number of Section 23.8.3.1 once more, now for the function b↦A−1b\mathbf b\mapsto\mathbf A^{-1}\mathbf b: the largest factor by which a relative change of the input can become a relative change of the output, taken over all right-hand sides and all directions of the change. For a matrix with singular values σ1≥⋯≥σd>0\sigma_1\ge\cdots\ge\sigma_d>0 that factor is κ(A)=σ1/σd\kappa(\mathbf A)=\sigma_1/\sigma_d (Section 21.5.3.2), and it is about 4×1044\times10^4 for the two lines. The shift (0,10−4)(0,10^{-4}) realizes 2.8×1042.8\times10^4 of it, because it is not along the most amplified direction.

23.8.4.2 Backward and Forward Error#

For a linear system Ax=b\mathbf A\mathbf x=\mathbf b and a computed solution x^\hat{\mathbf x}, the forward error is ∥x^−x∥/∥x∥\|\hat{\mathbf x}-\mathbf x\|/\|\mathbf x\| and the backward error is the size of the smallest change of the data that makes x^\hat{\mathbf x} exact. An algorithm is backward stable if its backward error is of the order of uu, so that it returns the exact answer of a problem that differs from the given one by about one rounding of the data. The SVD and the QR decomposition are backward stable, and so in practice is the LU decomposition with pivoting that np.linalg.solve uses. The one-pass variance is not: the variance of any data set is nonnegative, so a negative output is the exact variance of no data at all.

The definition asks for a minimization over all changes of the data. Luckily, for changes of the matrix it has a closed form, computable from the residual.

Proposition (backward error from the residual). Let x^≠0\hat{\mathbf x}\ne\mathbf 0 and r=b−Ax^\mathbf r=\mathbf b-\mathbf A\hat{\mathbf x}. The smallest ∥ΔA∥2\|\Delta\mathbf A\|_2 with (A+ΔA)x^=b(\mathbf A+\Delta\mathbf A)\hat{\mathbf x}=\mathbf b is ∥r∥/∥x^∥\|\mathbf r\|/\|\hat{\mathbf x}\|, attained by ΔA=rx^⊤/∥x^∥2\Delta\mathbf A=\mathbf r\hat{\mathbf x}^\top/\|\hat{\mathbf x}\|^2.

Proof. Any such ΔA\Delta\mathbf A satisfies ΔAx^=b−Ax^=r\Delta\mathbf A\hat{\mathbf x}=\mathbf b-\mathbf A\hat{\mathbf x}=\mathbf r, so ∥r∥≤∥ΔA∥ ∥x^∥\|\mathbf r\|\le\|\Delta\mathbf A\|\,\|\hat{\mathbf x}\|. The rank-one matrix rx^⊤/∥x^∥2\mathbf r\hat{\mathbf x}^\top/\|\hat{\mathbf x}\|^2 maps x^\hat{\mathbf x} to r\mathbf r, and its norm is ∥r∥ ∥x^∥/∥x^∥2=∥r∥/∥x^∥\|\mathbf r\|\,\|\hat{\mathbf x}\|/\|\hat{\mathbf x}\|^2=\|\mathbf r\|/\|\hat{\mathbf x}\|. ■\blacksquare

Relative to the size of A\mathbf A, the backward error is

ω=∥b−Ax^∥∥A∥ ∥x^∥.(23.8.11)\omega=\frac{\|\mathbf b-\mathbf A\hat{\mathbf x}\|}{\|\mathbf A\|\,\|\hat{\mathbf x}\|} . \tag{23.8.11}

A small residual certifies a small backward error, whatever the condition of the problem. For x^=(0,2)\hat{\mathbf x}=(0,2) in the two-line system, r=(0,−10−4)\mathbf r=(0,-10^{-4}) and ω=10−4/(2.00005⋅2)=2.5×10−5\omega=10^{-4}/(2.00005\cdot2)=2.5\times10^{-5}. The version that perturbs b\mathbf b as well is due to Rigal and Gaches (see Higham (2002)). In floating point the residual is itself computed with rounding errors, so printed values of ω\omega below about uu are noise.

The condition number converts backward error into forward error. This is the result to remember, and its proof needs only the two norms ∥A∥=σ1\|\mathbf A\|=\sigma_1 and ∥A−1∥=1/σd\|\mathbf A^{-1}\|=1/\sigma_d (Section 21.5).

Proposition (forward error ≤\le condition number ×\times backward error). Let A\mathbf{A} be invertible, let Ax=b\mathbf{A}\mathbf{x} = \mathbf{b}, and suppose the computed x^\hat{\mathbf{x}} exactly solves a nearby system, (A+ΔA) x^=b(\mathbf{A} + \Delta\mathbf{A})\,\hat{\mathbf{x}} = \mathbf{b} with ∥ΔA∥≤ω∥A∥\|\Delta\mathbf{A}\| \le \omega \|\mathbf{A}\|. Then

∥x^−x∥∥x^∥  ≤  κ(A) ω.(23.8.12)\frac{\|\hat{\mathbf{x}} - \mathbf{x}\|}{\|\hat{\mathbf{x}}\|} \;\le\; \kappa(\mathbf{A})\, \omega . \tag{23.8.12}

Proof. Subtracting Ax=b\mathbf{A}\mathbf{x} = \mathbf{b} from (A+ΔA)x^=b(\mathbf{A} + \Delta\mathbf{A})\hat{\mathbf{x}} = \mathbf{b} gives A(x^−x)=−ΔA x^\mathbf{A}(\hat{\mathbf{x}} - \mathbf{x}) = -\Delta\mathbf{A}\,\hat{\mathbf{x}}, hence x^−x=−A−1ΔA x^\hat{\mathbf{x}} - \mathbf{x} = -\mathbf{A}^{-1}\Delta\mathbf{A}\,\hat{\mathbf{x}} and

∥x^−x∥≤∥A−1∥ ∥ΔA∥ ∥x^∥≤1σd σ1 ω ∥x^∥=κ(A) ω ∥x^∥.■\|\hat{\mathbf{x}} - \mathbf{x}\| \le \|\mathbf{A}^{-1}\|\, \|\Delta\mathbf{A}\|\, \|\hat{\mathbf{x}}\| \le \frac{1}{\sigma_d}\, \sigma_1\, \omega\, \|\hat{\mathbf{x}}\| = \kappa(\mathbf{A})\,\omega\, \|\hat{\mathbf{x}}\| . \qquad\blacksquare

The error here is measured relative to x^\hat{\mathbf x}, the vector we have. Relative to the true x\mathbf x, substituting ∥x^∥≤∥x∥+∥x^−x∥\|\hat{\mathbf x}\|\le\|\mathbf x\|+\|\hat{\mathbf x}-\mathbf x\| and solving for ∥x^−x∥\|\hat{\mathbf x}-\mathbf x\| gives the bound κω/(1−κω)\kappa\omega/(1-\kappa\omega) when κω<1\kappa\omega\lt 1, the same to first order. On the two-line system, κω=4×104⋅2.5×10−5=1.0\kappa\omega=4\times10^4\cdot 2.5\times10^{-5}=1.0, and the error relative to x^\hat{\mathbf x} is ∥(−1,1)∥/∥(0,2)∥=0.71\|(-1,1)\|/\|(0,2)\|=0.71, inside the bound. For an error in the right-hand side instead of the matrix, the corresponding bound appears in Section 21.5.3.2.

A backward-stable solver has ω≈u\omega\approx u, and taking log⁡10\log_{10} of the bound gives the rule of thumb

correct digits in x^  ≈  digits carried by the format  −  log⁡10κ(A).\textrm{correct digits in } \hat{\mathbf{x}} \;\approx\; \textrm{digits carried by the format} \;-\; \log_{10} \kappa(\mathbf{A}).

The rule is a worst case. A matrix with κ=103\kappa=10^3 can lose three of fp32's seven digits. The chapter's running example 12(x12+1000x22)\tfrac12(x_1^2+1000x_2^2) has that κ\kappa and loses none: its matrix is diagonal, and each unknown takes one correctly rounded division.

23.8.4.3 Example: The Hilbert Matrix#

The Hilbert matrix Hij=1/(i+j−1)\mathbf H_{ij}=1/(i+j-1), i,j=1,…,ni,j=1,\ldots,n, has a condition number that grows exponentially with nn: its rows become nearly parallel in the same way as the two lines above. We solve Hx=b\mathbf H\mathbf x=\mathbf b with b=H1\mathbf b=\mathbf H\mathbf 1, whose exact solution is 1\mathbf 1, and compare the forward error with the rule of thumb and with the backward error (23.8.11). One caveat before we judge the solver. Computing b=H1\mathbf b=\mathbf H\mathbf 1 in fp64 rounds every entry of b\mathbf b, a change of the data of relative size uu before the solver starts. (Rounding the entries 1/31/3, 1/71/7, … does no harm here, because b\mathbf b is built from the matrix as stored.) How much does that alone cost? Every fp64 number is a rational number, so the stored system can also be solved without any rounding, by Gauss–Jordan elimination on Fraction entries. The table reports the error of that exact solve beside the error of np.linalg.solve.

def solve_exact(A, b):
    """Gauss-Jordan elimination in exact rational arithmetic."""
    M = [[Fraction(a) for a in row] + [Fraction(c)] for row, c in zip(A, b)]
    n = len(M)
    for j in range(n):              # no pivoting: A is positive definite here
        for i in range(n):
            if i != j:
                r = M[i][j] / M[j][j]
                M[i] = [a - r * c for a, c in zip(M[i], M[j])]
    return np.array([float(M[i][n] / M[i][i]) for i in range(n)])

For dimensions n∈{4,6,8,10,12}n \in \{4, 6, 8, 10, 12\}, we now construct the n×nn \times n Hilbert matrix H and right-hand side b = H @ x_true, comparing the floating-point solver np.linalg.solve(H, b) against solve_exact(H, b) across condition number, forward error, digits retained, and backward error:

print(' n     kappa  forward error  digits kept  16 - log10 kappa  backward error'
      '  exact solve error')
for n in [4, 6, 8, 10, 12]:
    i = np.arange(n)
    H = 1.0 / (1.0 + i[:, None] + i[None, :])   # Hilbert matrix
    x_true = np.ones(n)
    b = H @ x_true
    x_hat = np.linalg.solve(H, b)
    kappa = np.linalg.cond(H)
    fwd = np.linalg.norm(x_hat - x_true) / np.linalg.norm(x_true)
    omega = (np.linalg.norm(b - H @ x_hat)
             / (np.linalg.norm(H, 2) * np.linalg.norm(x_hat)))
    exact = np.linalg.norm(solve_exact(H, b) - x_true) / np.linalg.norm(x_true)
    print(f'{n:2d}  {kappa:8.1e}  {fwd:13.1e}  {-np.log10(fwd):11.1f}'
          f'  {16 - np.log10(kappa):16.1f}  {omega:14.1e}  {exact:17.1e}')
 n     kappa  forward error  digits kept  16 - log10 kappa  backward error  exact solve error
 4   1.6e+04        4.1e-14         13.4              11.8         0.0e+00            1.1e-13
 6   1.5e+07        1.4e-10          9.8               8.8         1.3e-16            1.0e-10
 8   1.5e+10        6.1e-08          7.2               5.8         5.7e-17            7.0e-08
10   1.6e+13        8.7e-05          4.1               2.8         1.0e-16            4.5e-05
12   1.8e+16        3.2e-01          0.5              -0.2         9.8e-17            1.4e-01

The digits kept fall from about 1313 at n=4n=4 to well under one at n=12n=12, while the backward error stays at or below about 10−1610^{-16}: each computed vector solves a system that differs from the stored one in the sixteenth or seventeenth digit. Is the solver to blame for the lost digits, then? The last column acquits it. The exact solve of the stored system, which commits no rounding error at all, misses 1\mathbf 1 by an error of the same order in every row, about 10−710^{-7}, 10−410^{-4} and 10−110^{-1} for n=8n=8, 1010 and 1212. The digits were lost when b\mathbf b was stored, before any solver ran. The rule of thumb is pessimistic by about one digit (from about half a digit to about one and a half, depending on the row), because the error is not aligned with the most amplified direction. At n=12n=12, κu≈2\kappa u\approx2 and the bound no longer constrains anything. The last decimals vary with the LAPACK build; the trend does not.

23.8.4.4 Conditioning of the Normal Equations#

The least-squares problem min⁡w∥Aw−b∥2\min_{\mathbf{w}}\|\mathbf{A}\mathbf{w}-\mathbf{b}\|^2 with A∈Rn×d\mathbf A\in\mathbb R^{n\times d} of full column rank is solved by the normal equations A⊤Aw=A⊤b\mathbf{A}^\top\mathbf{A}\mathbf{w}=\mathbf{A}^\top\mathbf{b}. This is an algebraically equivalent route through a worse-conditioned matrix (Section 21.5.3.2):

κ(A⊤A)=κ(A)2.(23.8.13)\kappa(\mathbf{A}^\top\mathbf{A}) = \kappa(\mathbf{A})^2 . \tag{23.8.13}

We have seen this before, in the one-pass variance: the convenient formula squares the condition number of the problem. By the rule of thumb, the normal equations can lose about 2log⁡10κ2\log_{10}\kappa digits. A solve by QR (A=QR\mathbf A=\mathbf Q\mathbf R with orthonormal Q\mathbf Q and triangular R\mathbf R) or by the SVD works on A\mathbf A directly and loses about log⁡10κ\log_{10}\kappa, when the residual b−Aw\mathbf b-\mathbf A\mathbf w is small. With a large residual the least-squares problem itself is more sensitive: its condition number is about κ+κ2tan⁡θ\kappa+\kappa^2\tan\theta, where θ\theta is the angle between b\mathbf b and the column space of A\mathbf A. QR and SVD then lose close to 2log⁡10κ2\log_{10}\kappa digits too, but never more than the problem forces; the normal equations lose that many whatever the residual.

The chapter's running example is too well conditioned to show the difference: its design has A⊤A=diag(1,1000)\mathbf A^\top\mathbf A=\mathrm{diag}(1,1000), so κ(A)=1000≈32\kappa(\mathbf A)=\sqrt{1000}\approx32. The cell therefore builds harder designs, with κ(A)=103\kappa(\mathbf A)=10^3 and 10610^6, from random orthonormal factors and a right-hand side in the column space (zero residual). We expect gaps of three and of six digits:

rng = np.random.default_rng()
n, d = 100, 10
for kappa in [1e3, 1e6]:
    U, _ = np.linalg.qr(rng.normal(size=(n, d)))    # orthonormal columns
    V, _ = np.linalg.qr(rng.normal(size=(d, d)))
    sigma = np.logspace(0, -np.log10(kappa), d)     # kappa(A) as chosen
    A = U * sigma @ V.T                             # A = U diag(sigma) V^T
    w_true = rng.normal(size=d)
    b = A @ w_true                                  # zero residual
    w_ne = np.linalg.solve(A.T @ A, A.T @ b)        # normal equations
    w_ls = np.linalg.lstsq(A, b, rcond=None)[0]     # SVD-based solve
    digits = [-np.log10(np.linalg.norm(w - w_true) / np.linalg.norm(w_true))
              for w in (w_ne, w_ls)]
    print(f'kappa(A) = {kappa:.0e}: normal equations keep {digits[0]:4.1f} '
          f'digits, lstsq keeps {digits[1]:4.1f}')
kappa(A) = 1e+03: normal equations keep 10.3 digits, lstsq keeps 14.3
kappa(A) = 1e+06: normal equations keep  5.7 digits, lstsq keeps 11.7

At κ(A)=103\kappa(\mathbf A)=10^3 the normal equations keep about 1010 to 1212 digits against about 1414 for lstsq, and at 10610^6 about 44 to 66 against about 1111 to 1313. The exact digits vary from run to run by a digit or two; the gaps scatter around log⁡10κ\log_{10}\kappa, mostly within a digit of it. This is why lstsq and the pseudoinverse of Section 21.5.3.1 work from the SVD and not from (A⊤A)−1A⊤(\mathbf A^\top\mathbf A)^{-1}\mathbf A^\top.

23.8.4.5 Ridge Regularization and Conditioning#

When κ(A)\kappa(\mathbf A) itself is large, because features are nearly collinear or the design is rank deficient, no choice of algorithm helps: the problem must change. One change keeps the answer. A preconditioner changes variables so that the new problem is better conditioned and its solution maps back to the original one. Dividing each column of A\mathbf A by its norm is an example (Exercise 4), and the per-coordinate step sizes of Section 23.5 do the same inside an optimizer.

Ridge regularization changes the answer as well. It minimizes 12∥Aw−b∥2+λ2∥w∥2\tfrac12\|\mathbf{A}\mathbf{w}-\mathbf{b}\|^2+\tfrac\lambda2\|\mathbf{w}\|^2, whose minimizer is

wλ=(A⊤A+λI)−1A⊤b,(23.8.14)\mathbf{w}_\lambda = (\mathbf{A}^\top\mathbf{A} + \lambda \mathbf{I})^{-1} \mathbf{A}^\top \mathbf{b} , \tag{23.8.14}

the ridge solution of Section 21.5.3.1. Let σ1≥⋯≥σd≥0\sigma_1\ge\cdots\ge\sigma_d\ge0 be the singular values of A∈Rn×d\mathbf A\in\mathbb R^{n\times d}, with σi=0\sigma_i=0 beyond its rank. The matrix A⊤A+λI\mathbf A^\top\mathbf A+\lambda\mathbf I has the eigenvectors of A⊤A\mathbf A^\top\mathbf A and the eigenvalues σi2+λ≥λ>0\sigma_i^2+\lambda\ge\lambda>0. It is therefore positive definite, hence invertible even when A\mathbf A is rank deficient, and

κ(A⊤A+λI)=σ12+λσd2+λ.(23.8.15)\kappa(\mathbf{A}^\top\mathbf{A} + \lambda\mathbf{I}) = \frac{\sigma_1^2 + \lambda}{\sigma_d^2 + \lambda} . \tag{23.8.15}

Whenever σ1>σd\sigma_1>\sigma_d this ratio decreases strictly in λ\lambda (its derivative is (σd2−σ12)/(σd2+λ)2<0(\sigma_d^2-\sigma_1^2)/(\sigma_d^2+\lambda)^2\lt 0) and tends to 11 as λ→∞\lambda\to\infty. Adding λ\lambda lifts the floor of the spectrum. While λ≪σ12\lambda\ll\sigma_1^2 it barely moves the ceiling, so κ\kappa falls about in proportion to 1/λ1/\lambda once λ≫σd2\lambda\gg\sigma_d^2. The damping term of second-order optimizers and the jitter added to a kernel matrix in Gaussian process regression (Chapter 28) are this λI\lambda\mathbf I under other names.

The price is a different minimizer. In the present notation, with vi\mathbf v_i the right singular vectors of A\mathbf A and w0=A+b\mathbf w_0=\mathbf A^+\mathbf b the minimum-norm least-squares solution, the filter factors of Section 21.5.3.1 read

wλ=∑i=1dσi2σi2+λ (vi⊤w0) vi.(23.8.16)\mathbf w_\lambda=\sum_{i=1}^d\frac{\sigma_i^2}{\sigma_i^2+\lambda}\,(\mathbf v_i^\top\mathbf w_0)\,\mathbf v_i . \tag{23.8.16}

Ridge damps most the directions with small σi\sigma_i, and these are the very directions in which the unregularized solve amplifies data errors by 1/σi1/\sigma_i. Figure 23.8.4 shows the effect on the level sets; each panel is centered on its own minimizer, so the shift of the minimizer toward the origin is not drawn.

Figure 23.8.4:

Level sets of the least-squares objective before and after adding the ridge term λ2∥w∥2\tfrac\lambda2\|\mathbf{w}\|^2, drawn for κ=16\kappa=16 so that both panels stay legible (the running example's κ=1000\kappa=1000 would draw as a line). The penalty lifts every eigenvalue of A⊤A\mathbf{A}^\top\mathbf{A} by λ\lambda; the semi-axes, proportional to 1/σi2+λ1/\sqrt{\sigma_i^2+\lambda}, are long where the curvature is small, and the valley rounds into a bowl. Orange: gradient-descent iterates from the same start at each panel's best fixed step; green arrows: the principal axes, labeled by their curvatures.

The same κ\kappa counts the steps of gradient descent on the ridge objective. At the best fixed step, gradient descent on a quadratic with condition number κ>1\kappa>1 contracts the error by ρ=(κ−1)/(κ+1)\rho=(\kappa-1)/(\kappa+1) per step (Section 23.1). Started at the origin, where the error is −w⋆-\mathbf w^\star, it has relative error ∥wk−w⋆∥/∥w⋆∥≤ρk\|\mathbf w_k-\mathbf w^\star\|/\|\mathbf w^\star\|\le\rho^k after kk steps, so a tolerance 0<tol<10\lt \mathrm{tol}\lt 1 is met within

k≤⌈log⁡(1/tol)log⁡κ+1κ−1⌉≤⌈κ2 log⁡1tol⌉steps.(23.8.17)k \le \left\lceil\frac{\log(1/\mathrm{tol})}{\log\frac{\kappa+1}{\kappa-1}}\right\rceil \le \left\lceil\frac\kappa2\,\log\frac1{\mathrm{tol}}\right\rceil \quad\textrm{steps.} \tag{23.8.17}

The second inequality holds because log⁡κ+1κ−1=2 artanh(1/κ)≥2/κ\log\frac{\kappa+1}{\kappa-1}=2\,\mathrm{artanh}(1/\kappa)\ge2/\kappa. For six digits it allows 12log⁡106=6.9\tfrac12\log10^6=6.9 steps per unit of κ\kappa; a run in more than two dimensions can finish sooner (Exercise 4).

How many steps does a given λ\lambda save, and what does it cost? We measure both on the running example. Its objective 12(w12+1000w22)−w1−1000w2\tfrac12(w_1^2+1000w_2^2)-w_1-1000w_2 is least squares with A⊤A=diag(1,1000)\mathbf A^\top\mathbf A=\mathrm{diag}(1,1000) and A⊤b=(1,1000)\mathbf A^\top\mathbf b=(1,1000). Its minimizer is (1,1)(1,1), so the ridge minimizer displays the two filter factors directly. The function gd_iterations runs gradient descent at the best fixed step and returns the step count and the ridge minimizer:

def gd_iterations(AtA, Atb, lam, tol=1e-6):
    """GD steps at step 2/(L+mu) to reach relative error tol on ridge."""
    M = AtA + lam * np.eye(len(Atb))
    w_star = np.linalg.solve(M, Atb)
    mu, L = np.linalg.eigvalsh(M)[[0, -1]]
    eta, w, k = 2 / (L + mu), np.zeros(len(Atb)), 0
    while np.linalg.norm(w - w_star) > tol * np.linalg.norm(w_star):
        w, k = w - eta * (M @ w - Atb), k + 1
    return k, w_star

AtA, Atb = np.diag([1.0, 1000.0]), np.array([1.0, 1000.0])
print('lambda   kappa  steps  steps/kappa  ridge minimizer')
for lam in [0, 1, 10, 100, 1000]:
    kappa = (1000 + lam) / (1 + lam)
    k, w_star = gd_iterations(AtA, Atb, lam)
    print(f'{lam:6d} {kappa:7.1f} {k:6d} {k / kappa:12.2f}  {w_star.round(4)}')
lambda   kappa  steps  steps/kappa  ridge minimizer
     0  1000.0   6908         6.91  [1. 1.]
     1   500.5   3458         6.91  [0.5   0.999]
    10    91.8    635         6.92  [0.0909 0.9901]
   100    10.9     76         6.98  [0.0099 0.9091]
  1000     2.0     13         6.51  [0.001 0.5  ]

The condition number falls from 10001000 to 22 as λ\lambda goes from 00 to 10001000, and the step count falls with it, from 6,9086{,}908 to 1313. The ratio of steps to κ\kappa stays near 6.96.9 (at small κ\kappa the approximation 2/κ2/\kappa is loose, and rounding up to a whole step matters). The last column shows what the saved steps cost. At λ=1\lambda=1 the slow direction, with σ2=1\sigma^2=1, is halved to 0.50.5, while the stiff direction, with σ2=1000\sigma^2=1000, moves by 0.1%0.1\%. At λ=1000\lambda=1000 the stiff direction is halved too. A sweep over λ\lambda shows κ\kappa and the step count together:

lams = np.logspace(-2, 3, 11)
kappas = (1000 + lams) / (1 + lams)
steps = [gd_iterations(AtA, Atb, lam)[0] for lam in lams]
d2l.plot(lams, [kappas, steps], 'lambda', None,
         legend=['kappa', 'GD steps to 1e-6'], xscale='log', yscale='log')

On log–log axes the two curves are parallel, a factor of 6.96.9 apart, with slope close to −1-1 while λ\lambda lies well between the eigenvalues 11 and 10001000. Ridge thus conditions the linear solve and gradient descent alike, and it pays for both by shrinking the solution. Section 23.7.3.2 shows that the penalty λ2∥w∥2\tfrac\lambda2\|\mathbf w\|^2 corresponds to a constraint on ∥w∥\|\mathbf w\|, so a λ\lambda chosen for statistical reasons also sets the conditioning of the computation.

None of these tools covers error that grows over many steps of an iteration, such as a gradient through a hundred layers; Section 4.4 takes that up.

23.8.5 Summary#

A floating-point format stores numbers with about pp bits of relative precision and a finite exponent range. Every rounding introduces a relative error of at most u=2−p−1u=2^{-p-1}, while overflow, underflow, and a lost small update are absolute effects that the relative model does not show. Softmax and cross-entropy fail because they pass through values the format cannot hold, and the one-pass variance because it subtracts nearly equal large numbers; none of their answers is extreme. The max shift, cross-entropy computed from logits, and Welford's recursion avoid the detour. The relative condition number κf=∣xf′/f∣\kappa_f=|xf'/f| separates a bad algorithm from a hard problem: when it is small and the computed answer is bad, the algorithm is to blame. For a linear system, κ(A)\kappa(\mathbf A) bounds the forward error by κ\kappa times the backward error, which a residual certifies, so about log⁡10κ\log_{10}\kappa digits are lost, and twice that through the normal equations. Ridge adds λ\lambda to every squared singular value, which lowers κ\kappa for the solve and for gradient descent alike, at the price of shrinking the solution by the filter factors σi2/(σi2+λ)\sigma_i^2/(\sigma_i^2+\lambda).

23.8.6 Exercises#

  1. Loss-scale window. Loss scaling multiplies the loss by a factor SS, which multiplies every gradient by SS, and divides the gradients by SS after they have been converted to fp32. In fp16 the smallest normal number is 2−14≈6.1×10−52^{-14} \approx 6.1 \times 10^{-5}, the smallest subnormal number is 2−24≈6.0×10−82^{-24} \approx 6.0 \times 10^{-8} (values below 2−252^{-25} round to zero), and the largest finite number is 6550465504. Suppose that the exact nonzero gradient entries of a network have magnitudes between 10−910^{-9} and 10−110^{-1}, and that the backward pass computes the scaled gradients in fp16.

    1. Find all powers of two SS for which every scaled gradient is a normal fp16 number.
    2. The gradients of a deeper network have magnitudes between 10−1210^{-12} and 10−110^{-1}. Show that no scale keeps all of them normal. Take the largest power of two SS that avoids overflow. How many significant bits does a scaled gradient of magnitude 10−1210^{-12} keep, and what is its relative rounding error?
    3. Dynamic loss scaling (Section 5.5.3.3) picks the largest scale that avoids overflow and thereby sacrifices the smallest gradients. Why is that the better end to sacrifice?
    4. How do the answers to the first two sub-items change when the gradients are computed in bf16?
  2. [code] Blame the problem or the algorithm. Each expression below is evaluated in fp32. For each, compute the relative condition number (23.8.8) of the function in the stated regime and the cancellation factor (23.8.9) of the formula as written. Decide whether the problem or the algorithm is to blame, and rewrite the formula so that its error matches the problem's. Check both forms against fp64.

    1. The root of smaller magnitude of ax2+bx+c=0ax^2 + bx + c = 0 for b>0b > 0 and b2≫4∣ac∣b^2 \gg 4|ac|, as a function of cc, for example a=c=1a = c = 1 and b=104b = 10^4. (Hint: multiply by the conjugate.)
    2. The function log⁡(1−e−x)\log(1 - e^{-x}) for x>0x > 0, which computes log⁡(1−q)\log(1 - q) from log⁡q=−x\log q = -x, at x∈{10−6,10−3,1,20}x \in \{10^{-6}, 10^{-3}, 1, 20\}. Find one formulation that is accurate for small xx and one that is accurate for large xx, and choose a switching point.
    3. The binary cross-entropy of a logit tt with label 11, log⁡(1+e−t)\log(1+e^{-t}), at t∈{−800,−50,0,50}t\in\{-800,-50,0,50\}. At which of these does the formula as written overflow, and at which does it return 00? Show that max⁡(−t,0)+log1p(e−∣t∣)\max(-t,0)+\mathrm{log1p}(e^{-|t|}) equals it, never overflows, and loses no digits. Which part of the log-sum-exp sandwich is it?
    4. x+1−x\sqrt{x+1}-\sqrt x at x=108x=10^8.

    Part 2 is adapted from Martin Mächler, Accurately Computing log(1 − exp(−|a|)), Section 2.

  3. [code] Normal equations in floating point. The normal equations square the condition number (23.8.13).

    1. For τ>0\tau > 0, the (m+1)×m(m + 1) \times m matrix A\mathbf{A} of Läuchli (1961) has a first row of ones and τI\tau\mathbf{I} below it. Compute A⊤A\mathbf{A}^\top\mathbf{A}, the singular values of A\mathbf{A}, and κ(A)\kappa(\mathbf{A}). Show that for τ=10−8\tau = 10^{-8} the matrix A⊤A\mathbf{A}^\top\mathbf{A} rounds to a singular matrix in fp64. How many correct digits does the rule of thumb of Section 23.8.4 predict for a QR-based least-squares solve with this A\mathbf{A} when b\mathbf b lies in the range of A\mathbf A? What changes in the prediction when the residual is large?
    2. Modify the #numerical-stability-conditioning-normal-equations cell to sweep κ(A)=10k\kappa(\mathbf{A}) = 10^k for k=2,…,10k = 2, \ldots, 10. Plot the correct digits of the normal equations and of lstsq against kk, together with the two rule-of-thumb lines 16−2k16-2k and 16−k16-k. At which kk does the rule predict that the normal equations keep no correct digit, and what do you observe there?
  4. [code] Feature scaling as preconditioning. Features measured in different units give the columns of a design matrix very different norms. Let X\mathbf{X} be a 200×5200 \times 5 matrix with standard normal entries, let A=X diag(1,3,10,30,100)\mathbf{A} = \mathbf{X}\,\mathrm{diag}(1, 3, 10, 30, 100), and let b=Aw⋆\mathbf{b} = \mathbf{A}\mathbf{w}^\star for a random w⋆\mathbf{w}^\star.

    1. Apply gd_iterations of the #numerical-stability-conditioning-ridge cell, which takes A⊤A\mathbf A^\top\mathbf A and A⊤b\mathbf A^\top\mathbf b, to this design at λ=0\lambda = 0. Compute κ(A⊤A)\kappa(\mathbf{A}^\top\mathbf{A}) and compare the step count with the bound (23.8.17). Explain the shortfall through the components of the start's error along the two extreme eigenvectors of A⊤A\mathbf A^\top\mathbf A.
    2. Divide every column of A\mathbf{A} by its norm and repeat the measurement. How does the minimizer of the rescaled problem map back to w⋆\mathbf{w}^\star?
    3. Part 2 of Exercise 1 of Section 23.2 writes gradient descent in new coordinates u\mathbf{u} with w=Tu\mathbf{w} = \mathbf T\mathbf{u} as gradient descent on the original problem preconditioned by a positive definite matrix P\mathbf P, with update w←w−η P−1∇f(w)\mathbf{w} \leftarrow \mathbf{w} - \eta\,\mathbf{P}^{-1}\nabla f(\mathbf{w}). Which T\mathbf T and which P\mathbf P correspond to column scaling? How is P\mathbf P related to the diagonal of A⊤A\mathbf{A}^\top\mathbf{A}?
  5. [code] Stochastic rounding. ● Stochastic rounding (Gupta et al., 2015) rounds a real number xx between adjacent representable values x−<x+x_- \lt x_+ to x+x_+ with probability q=(x−x−)/(x+−x−)q = (x - x_-)/(x_+ - x_-) and to x−x_- otherwise.

    1. Show that the rounded value has expectation xx and variance q(1−q)Δ2≤Δ2/4q(1 - q)\Delta^2 \le \Delta^2/4, where Δ=x+−x−\Delta = x_+ - x_-.
    2. A bf16 weight starts at w=1w = 1 and receives K=1000K = 1000 updates of −10−4-10^{-4}, each followed by stochastic rounding. The weight stays in [0.5,1][0.5, 1], where the bf16 spacing is Δ=2−8\Delta = 2^{-8}. Show that the rounding errors of different steps are uncorrelated, and predict the mean and the standard deviation of the final weight. Which final weight does round-to-nearest produce?
    3. For a positive fp32 number, adding a uniformly random integer from {0,…,216−1}\{0, \ldots, 2^{16} - 1\} to its bit pattern and then clearing the lower 16 bits rounds it stochastically to bf16. Explain why. Implement this rounding next to the to_bf16 function of Section 23.8.1 and check the predictions of the previous sub-item with 1000 independent runs. Compare with an fp32 master copy that receives the same updates.
  6. Exact subtraction. ● Subtraction can be exact and still return an inaccurate difference.

    1. Show that the bound (23.8.9) is attained for suitable δa\delta_a and δb\delta_b with ∣δa∣,∣δb∣≤u|\delta_a|,|\delta_b|\le u.
    2. Prove Sterbenz's lemma (Sterbenz, 1974): if aa and bb are floating-point numbers in the format (23.8.1) with b/2≤a≤2bb/2 \le a \le 2b, then a−ba - b is a floating-point number, so the computed difference is exact. Assume that the format includes subnormal numbers.
    3. In the #numerical-stability-conditioning-log1p cell, the fp32 difference a−ba - b misses the true value 3.0×10−73.0 \times 10^{-7} by about 20 percent. Use Sterbenz's lemma and the printed number of ulps to verify that the subtraction was exact, compute the relative errors of the stored aa and bb, and check that the bound of the first sub-item covers the error.
  7. [code] Merging running moments. ● Data-parallel training computes statistics on shards and combines them. Let shard AA hold kAk_A values with mean mAm_A and centered sum of squares MAM_A, and let shard BB hold kBk_B values with mBm_B and MBM_B.

    1. Derive exact formulas for the mean mm and the centered sum of squares MM of the union of the two shards in terms of kAk_A, mAm_A, MAM_A, kBk_B, mBm_B, and MBM_B.
    2. Show that the case kB=1k_B = 1 is Welford's recursion (23.8.10).
    3. Split the 10510^5 samples of the #numerical-stability-conditioning-welford cell into 2j2^j shards of nearly equal size (np.array_split) for j∈{1,4,8}j \in \{1, 4, 8\}. Compute each shard's statistics with Welford's recursion, merge them pairwise in a binary tree, and compare the variance with the two-pass reference. Merge the shards a second time by adding their sums ∑ixi\sum_i x_i and ∑ixi2\sum_i x_i^2 and applying the one-pass formula. Explain the difference.
  8. [code] Summation error growth. ● Let Sn=∑i=1nxiS_n = \sum_{i=1}^n x_i and let S^n\hat S_n be its computed value. In-order summation has the worst-case bound ∣S^n−Sn∣≤(n−1) u∑i∣xi∣+O(u2)|\hat S_n - S_n| \le (n - 1)\,u \sum_i |x_i| + O(u^2).

    1. For n=2kn = 2^k, recursive pairwise summation splits the terms into two halves, sums each half recursively, and adds the two results. Prove that it satisfies ∣S^n−Sn∣≤ulog⁡2(n)∑i∣xi∣+O(u2)|\hat S_n - S_n| \le u \log_2(n) \sum_i |x_i| + O(u^2).
    2. For n∈{24,28,212,216,220}n \in \{2^4, 2^8, 2^{12}, 2^{16}, 2^{20}\} uniform random numbers in [0,1)[0, 1) stored as fp32, measure the relative errors of in-order summation (np.cumsum(x)[-1]), of np.sum (a blocked pairwise summation), and of Kahan's compensated summation (Kahan, 1965) against a float64 reference. Kahan's method keeps a correction cc: after each addition t=s+yt = s + y it sets c=(t−s)−yc = (t - s) - y and subtracts cc from the next term. Plot the three errors against nn together with the two bounds.
    3. How does the measured error of in-order summation grow with nn compared with its worst-case bound, and why? Why is the text's sum of 10710^7 copies of 0.10.1 so much closer to the worst case?
    4. What limits the error of the two accurate methods at large nn?

    Adapted from Steven G. Johnson, MIT 18.335 Introduction to Numerical Methods, Problem Set 1, Problem 4.

  9. [code] Mixed-precision iterative refinement. ●● Mixed-precision training does the bulk of its arithmetic in low precision and keeps the quantities that accumulate small corrections in high precision. Iterative refinement (Moler, 1967; Carson and Higham, 2018) applies the same split to Ax=b\mathbf{A}\mathbf{x} = \mathbf{b}: the O(n3)O(n^3) factorization runs in low precision and only O(n2)O(n^2) residual work runs in high precision. Starting from an fp32 solution x0\mathbf{x}_0, it repeats

rk=b−Axk,(A+ΔAk) dk=rk,xk+1=xk+dk,\mathbf{r}_k = \mathbf{b} - \mathbf{A}\mathbf{x}_k, \qquad (\mathbf{A} + \Delta\mathbf{A}_k)\,\mathbf{d}_k = \mathbf{r}_k, \qquad \mathbf{x}_{k+1} = \mathbf{x}_k + \mathbf{d}_k,

where the residual and the update are computed in fp64 and the correction dk\mathbf{d}_k comes from an fp32 solve.

  1. Model the fp32 solve as backward stable, ∥ΔAk∥≤c u32 ∥A∥\|\Delta\mathbf{A}_k\| \le c\,u_{32}\,\|\mathbf{A}\| with u32=2−24u_{32} = 2^{-24} and a moderate constant cc, and neglect the fp64 rounding errors. Show that the error ek=xk−x\mathbf{e}_k = \mathbf{x}_k - \mathbf{x} satisfies ek+1=(A+ΔAk)−1ΔAk ek\mathbf{e}_{k+1} = (\mathbf{A} + \Delta\mathbf{A}_k)^{-1} \Delta\mathbf{A}_k\,\mathbf{e}_k. Derive a contraction factor in terms of c κ(A) u32c\,\kappa(\mathbf{A})\,u_{32}, and state when it is below 11.
  2. Implement the iteration for the Hilbert matrices of the #numerical-stability-conditioning-hilbert cell with n=3,…,10n = 3, \ldots, 10, using np.linalg.solve on fp32 copies of H\mathbf{H} and rk\mathbf{r}_k for the correction. Record the forward error over ten iterations and compare its final value with that of an fp64 solve. For which nn does refinement reach the accuracy of the fp64 solve? For which nn does it still converge, but too slowly to reach that accuracy within ten iterations? For which nn does the error grow?
  3. Estimate the measured contraction per iteration for each nn and compare it with κ(H) u32\kappa(\mathbf{H})\,u_{32} and with the spectral radius of I−H^−1H\mathbf{I} - \hat{\mathbf{H}}^{-1}\mathbf{H}, where H^\hat{\mathbf{H}} is the fp32 copy of H\mathbf{H} and the inverse is applied in fp64. Which perturbation dominates ΔAk\Delta\mathbf{A}_k in this experiment, and how pessimistic is the bound of the first sub-item?

Discussions