Dive into Deep Learning · §35.8
Numerical Stability and Conditioning
IEEE floating point · max-shifted softmax · catastrophic cancellation · Welford variance · matrix conditioning & ridge
Motivation
np.linalg.solve has backward error \omega \approx 10^{-17} yet returns an answer off by 30\%—requiring problem regularization.Floating-Point Arithmetic
A normal floating-point number is base-2 scientific notation with p mantissa (significand) bits after the binary point and an integer exponent e:
x = (-1)^s \cdot (1.b_1 b_2 \ldots b_p)_2 \cdot 2^e
Floating-Point Arithmetic
Modern deep learning trades mantissa precision (p) against exponent dynamic range across five formats narrower than fp64 (p = 52, u \approx 1.1 \times 10^{-16}):
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
fp16 vs. bfloat16: fp16 keeps p = 10 mantissa bits (\sim 3 decimal digits) but only 5 exponent bits, overflowing at 65{,}504. bfloat16 keeps all 8 exponent bits of fp32 (reaching 3.4 \times 10^{38}) while truncating the mantissa to p = 7 bits (\varepsilon_{\mathrm{mach}} = 2^{-7} \approx 7.8 \times 10^{-3}, u = 2^{-8} \approx 3.9 \times 10^{-3}).Floating-Point Arithmetic
Because bfloat16 is simply the top 16 bits of an fp32 word, converting fp32 to bfloat16 rounds off the lower 16 bits, breaking exact midpoint ties (0x8000) toward the neighbor whose lowest kept bit is even (0):
1.00488281 -> 1.00781250 (expected 1.00781250)
1.00390625 -> 1.00000000 (expected 1.00000000)
1.01171875 -> 1.01562500 (expected 1.01562500)
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
Floating-Point Arithmetic
While multiplication and division obey the relative model \mathrm{fl}(x \odot y) = (x \odot y)(1 + \delta), adding a small update \Delta = -\eta g to a weight w \in (2^e, 2^{e+1}) hits a sharp absolute cutoff whenever |\eta g| is less than half the grid spacing 2^{e-p} around w:
\mathrm{fl}(w - \eta g) = w \qquad \text{whenever } |\eta g| < 2^{e-p-1} = u\,2^e \quad (\text{or } u/2 = 2^{-p-2} \text{ when decreasing from } w = 1)
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
In bfloat16 (p = 7), a weight at w = 1 ignores any decrease smaller than 2^{-9} \approx 0.00195, freezing completely on \eta g = 10^{-3}. Mixed-precision training therefore accumulates updates into an fp32 master copy of the weights (or uses unbiased stochastic rounding).
Stable Softmax
Evaluating \mathrm{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^n e^{z_j}} directly overflows whenever any logit exceeds \log(\text{max float}) (11.09 in fp16, 88.72 in fp32, 709.78 in fp64). Multiplying numerator and denominator by e^{-c} leaves softmax invariant for any c \in \mathbb{R}:
\mathrm{softmax}(\mathbf{z}) = \mathrm{softmax}(\mathbf{z} - c\mathbf{1}), \qquad \mathrm{lse}(\mathbf{z}) = \log\sum_{j=1}^n e^{z_j} = c + \log\sum_{j=1}^n e^{z_j - c}
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.]
Stable Softmax
Setting c = \max_j z_j in \mathrm{lse}(\mathbf{z}) = c + \log\sum_{j=1}^n e^{z_j - c} proves that \mathrm{lse}(\mathbf{z}) is a smooth upper envelope of the hard maximum:
\max_{1 \le j \le n} z_j \;\le\; \mathrm{lse}(\mathbf{z}) \;\le\; \max_{1 \le j \le n} z_j + \log n
Stable Softmax
To compute log-probabilities \log\mathrm{softmax}(\mathbf{z})_i without underflowing small probabilities, compare two algebraically identical formulas with c = \max_j z_j and s = \log\sum_{j=1}^n e^{z_j - c} \in [0, \log n]:
\text{Stable:}\quad (z_i - c) - s \qquad \text{vs.} \qquad \text{Naive subtraction:}\quad z_i - \underbrace{(c + s)}_{\mathrm{lse}(\mathbf{z})}
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
fp32 grid points sit 2^{-14} \approx 6.1 \times 10^{-5} apart. Forming c + s = 1002.4076 rounds s to the coarse grid of 1002, losing 1.32 \times 10^{-5} before z_i is subtracted.Stable Softmax
The cross-entropy loss for true class y is -\log\mathrm{softmax}(\mathbf{z})_y = \mathrm{lse}(\mathbf{z}) - z_y. On \mathbf{z} = (0, t) with true label y = 0, the exact loss is \log(1 + e^t) \approx t. If we compute softmax probabilities first, p_0 \approx e^{-t} underflows to subnormals above t = 87.3 and to 0 at t = 104:
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
At t = 103, PyTorch rounds e^{-103} \approx 1.32 \times 2^{-149} to the smallest fp32 subnormal 2^{-149} (keeping just 1 bit), returning 149\log 2 = 103.2789. At t = 104, p_0 = 0 and -\log p_0 = \infty, whereas F.cross_entropy on logits is exact.
Catastrophic Cancellation
To distinguish a bad algorithm from an inherently sensitive mathematical problem, the relative condition number \kappa_f(x) measures the factor by which a small relative input perturbation \delta is amplified in the relative output \frac{f(x(1+\delta)) - f(x)}{f(x)} \approx \frac{x f'(x)}{f(x)}\delta:
\kappa_f(x) = \left|\frac{x\,f'(x)}{f(x)}\right|, \qquad \text{and for subtraction } f(a, b) = a - b:\quad \kappa_{-}(a, b) = \frac{|a| + |b|}{|a - b|}
| Mathematical Problem f | Relative Condition Number \kappa_f | Sensitive Regime |
|---|---|---|
| Subtraction a - b | (|a| + |b|) / |a - b| | Ill-conditioned when a \approx b (catastrophic cancellation) |
| Shifted Logarithm \log(1 + x) | \left|\frac{x}{(1+x)\log(1+x)}\right| | Well-conditioned near x = 0 (\kappa_f \to 1 as x \to 0) |
| Exponential e^x | |x| | Ill-conditioned for large |x| (absolute error in x \to relative error) |
| Sample Variance (mean m, std s) | \le 2(1 + |m|/s) | Loses \approx \log_{10}(|m|/s) digits when s \ll |m| |
Catastrophic Cancellation
log(1.0 + x) at x = 10^{-8} in fp32 rounds y = \mathrm{fl}(1 + 10^{-8}) = 1.0, and \log(y) near y = 1 has \kappa_{\log}(y) = 1/|\log y| = 10^8, magnifying the 10^{-8} rounding error to 100\% error.log1p): Evaluates x - x^2/2 + \cdots directly to full machine precision.Catastrophic Cancellation
Subtracting two nearly equal fp32 numbers a = 1.0002344 and b = 1.0002341 (true difference 3.0 \times 10^{-7}) returns 2.384 \times 10^{-7}—an error of 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
Catastrophic Cancellation
In numerical gradient checks via the forward difference \frac{f(x + h) - f(x)}{h}, we cannot algebraically eliminate the subtraction of nearly equal numbers:
\text{Total Error}(h) \;\approx\; \underbrace{\frac{h}{2}\,|f''(x)|}_{\text{Taylor truncation error}} \;+\; \underbrace{\frac{2u\,|f(x)|}{h}}_{\text{cancellation of rounding noise}}
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
fp64, vs. \sim 3.5 digits at h^\star \approx 5 \times 10^{-4} in fp32).Catastrophic Cancellation
Normalization layers and data pipelines continuously compute sample variances s^2 = \frac{1}{N}\sum_{i=1}^N (x_i - m)^2. When the spread s is small compared with the mean |m|, compare the problem’s inherent sensitivity against the textbook one-pass formula:
\text{Two-Pass:}\quad \frac{1}{N}\sum_{i=1}^N (x_i - m)^2 \qquad \text{vs.} \qquad \text{Naive One-Pass:}\quad \frac{1}{N}\sum_{i=1}^N x_i^2 - m^2
fp64 (u \approx 1.1 \times 10^{-16}), the problem permits \approx 7 accurate digits (\kappa_{\mathrm{var}} u \approx 2 \times 10^{-7}).Catastrophic Cancellation
Welford’s algorithm (1962) updates the running mean m_k and centered sum of squares M_k = \sum_{i=1}^k(x_i - m_k)^2 in a single streaming pass:
d_k = x_k - m_{k-1}, \quad m_k = m_{k-1} + \frac{d_k}{k}, \quad M_k = M_{k-1} + d_k(x_k - m_k)
Catastrophic Cancellation
On N = 10^5 fp64 samples drawn from \mathcal{N}(10^9, 1), compare naive one-pass \mathbb{E}[x^2] - (\mathbb{E}[x])^2, Welford’s one-pass recursion, and the two-pass reference:
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
fp64 numbers are spaced 2^{59-52} = 128 apart—so the naive formula can only return integer multiples of 128 (often 0 or negative), whereas Welford matches the two-pass reference to 7+ digits.Summation Stability
In floating point, addition is not associative: when summing n numbers, the accumulation tree determines how many roundings each term passes through:
\text{Left-to-Right Error} \le (n - 1)\,u\sum_{i=1}^n |x_i| \qquad \text{vs.} \qquad \text{Pairwise Tree Error} \le (\log_2 n)\,u\sum_{i=1}^n |x_i|
in order (cumsum): 1087937.0000
pairwise : 1000000.0000
exact : 1000000.0149
fp32 sum crosses 2^{19} = 524{,}288, grid spacing is 1/16 = 0.0625, so every +0.1 rounds up to two grid steps (+0.125). Pairwise summation keeps partial sums of equal scale, cutting the error bound by O(n / \log_2 n).Matrix Conditioning
Consider solving a linear system \mathbf{A}\mathbf{x} = \mathbf{b} where the two equations x_1 + x_2 = 2 and x_1 + 1.0001\,x_2 = 2.0001 represent two nearly parallel lines meeting at \mathbf{x} = (1, 1):
\mathbf{A} = \begin{pmatrix} 1 & 1 \\ 1 & 1.0001 \end{pmatrix}, \;\; \kappa(\mathbf{A}) \approx 4 \times 10^4
Matrix Conditioning
An algorithm for \mathbf{A}\mathbf{x} = \mathbf{b} is backward stable if its computed solution \hat{\mathbf{x}} is the exact solution of a nearby system (\mathbf{A} + \Delta\mathbf{A})\hat{\mathbf{x}} = \mathbf{b} with relative backward error \omega = \|\Delta\mathbf{A}\|_2 / \|\mathbf{A}\|_2 = O(u):
Matrix Conditioning
With relative backward error \omega = \frac{\|\mathbf{b} - \mathbf{A}\hat{\mathbf{x}}\|_2}{\|\mathbf{A}\|_2\|\hat{\mathbf{x}}\|_2} and \kappa(\mathbf{A}) = \sigma_1/\sigma_d:
\frac{\|\hat{\mathbf{x}} - \mathbf{x}\|_2}{\|\hat{\mathbf{x}}\|_2} \le \kappa(\mathbf{A})\,\omega
Matrix Conditioning
The Hilbert matrix H_{ij} = \frac{1}{i + j - 1} has \kappa(\mathbf{H}) growing as O\big((1 + \sqrt{2})^{4n}/\sqrt{n}\big). Solving \mathbf{H}\mathbf{x} = \mathbf{b} (\mathbf{b} = \mathbf{H}\mathbf{1}, true solution \mathbf{1}) in fp64 vs. exact rational arithmetic (Fraction) reveals where the digits are actually lost:
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
np.linalg.solve has backward error \omega \approx 10^{-17}, and an exact rational solve of the stored fp64 system has the exact same 30\% forward error: the digits were already lost when \mathbf{b} = \mathbf{H}\mathbf{1} was rounded to fp64.Least-Squares Conditioning
To solve linear least squares \min_{\mathbf{w}}\|\mathbf{A}\mathbf{w} - \mathbf{b}\|_2^2 (\mathbf{A} \in \mathbb{R}^{n \times d} of full column rank), forming the normal equations \mathbf{A}^\top\mathbf{A}\mathbf{w} = \mathbf{A}^\top\mathbf{b} squares the singular values \sigma_i(\mathbf{A}^\top\mathbf{A}) = \sigma_i(\mathbf{A})^2 and squares the condition number:
\kappa(\mathbf{A}^\top\mathbf{A}) = \frac{\sigma_1(\mathbf{A})^2}{\sigma_d(\mathbf{A})^2} = \kappa(\mathbf{A})^2 \implies \text{loses } 2\log_{10}\kappa(\mathbf{A}) \text{ digits instead of } \log_{10}\kappa(\mathbf{A})
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
fp64, solving \mathbf{A}^\top\mathbf{A}\mathbf{w} = \mathbf{A}^\top\mathbf{b} has \kappa(\mathbf{A}^\top\mathbf{A}) = 10^{12} and keeps only \sim 5 digits, whereas SVD/QR (np.linalg.lstsq) works directly on \mathbf{A} and keeps \sim 11–12 digits.Regularization & Conditioning
When \kappa(\mathbf{A}) itself is huge, no solver algorithm can prevent data noise amplification; we must regularize the problem. Adding \tfrac{\lambda}{2}\|\mathbf{w}\|_2^2 shifts every eigenvalue of \mathbf{A}^\top\mathbf{A} upward by \lambda > 0:
\kappa(\mathbf{A}^\top\mathbf{A} + \lambda\mathbf{I}) = \frac{\sigma_1^2 + \lambda}{\sigma_d^2 + \lambda}
Regularization & Conditioning
The condition number \kappa(\lambda) = \frac{\sigma_1^2 + \lambda}{\sigma_d^2 + \lambda} governs both the numerical sensitivity of the linear solve and the iteration count k \le \big\lceil\frac{\kappa(\lambda)}{2}\log\frac{1}{\mathrm{tol}}\big\rceil of gradient descent at \eta^\star = \frac{2}{L + \mu}:
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 ]
Regularization & Conditioning
Sweeping \lambda from 10^{-2} to 10^3 on \mathbf{A}^\top\mathbf{A} = \mathrm{diag}(1, 1000) shows the GD iteration count to reach 10^{-6} relative error tracking \kappa(\lambda) = \frac{1000 + \lambda}{1 + \lambda} across three orders of magnitude:
Concept Check
Test your grasp of floating-point arithmetic, cancellation, and conditioning:
bfloat16 (p = 7)? What about in fp16 (p = 10)?fp64 (u \approx 1.1 \times 10^{-16}), why does the one-pass variance formula \frac{1}{N}\sum x_i^2 - m^2 fail completely for data with mean m = 10^9 and standard deviation s = 1, whereas Welford’s one-pass algorithm keeps \sim 7 digits?fp64 (\sim 16 digits)?Answers: (1) bfloat16: No. Decreasing from w = 1 requires |\eta g| > 2^{-p-2} = 2^{-9} \approx 0.00195 > 10^{-3}, so \mathrm{fl}(1 - 10^{-3}) = 1. fp16: Yes. Its threshold below 1 is 2^{-12} \approx 2.44 \times 10^{-4} < 10^{-3}, stepping to 0.99902. (2) The variance problem has \kappa_{\mathrm{var}} \approx 2|m|/s = 2 \times 10^9, losing 9 of fp64’s 16 digits (\sim 7 digits kept by Welford). The naive formula subtracts two numbers of size m^2 = 10^{18}, squaring the condition factor to 2m^2/s^2 = 2 \times 10^{18} > 1/u (grid gap 128). (3) Normal equations square \kappa to \kappa(\mathbf{A}^\top\mathbf{A}) = 10^{12}, keeping roughly 16 - 12 = \mathbf{4\text{ digits}}. QR/SVD works directly on \mathbf{A} (\kappa = 10^6), keeping roughly 16 - 6 = \mathbf{10\text{ digits}}.
Key Takeaways
| Phenomenon / Task | Naive / Unstable Route | Numerical Failure Mode | Stable Algorithm / Remedy |
|---|---|---|---|
| Low-Precision Updates | Direct weight update in bf16/fp16 |
\mathrm{fl}(w - \eta g) = w when |\eta g| < u\,2^e | Master weights in fp32 + loss scaling / stochastic rounding |
| Softmax & Log-Sum-Exp | \frac{e^{z_i}}{\sum_j e^{z_j}} and \log\sum_j e^{z_j} | e^{z_i} \to \infty (NaN) for z_i > 88.7 (fp32) |
Max shift c = \max_j z_j: \mathrm{lse}(\mathbf{z}) = c + \log\sum_j e^{z_j - c} |
| Cross-Entropy Loss | -\log(\mathrm{softmax}(\mathbf{z})_y) | p_y \to 0 \implies -\log p_y = \infty | Fused logit loss (c - z_y) + \log\sum_j e^{z_j - c} |
| Near-Zero & Variance | \log(1 + x) and \frac{1}{N}\sum x_i^2 - m^2 | Catastrophic cancellation (\kappa \to \kappa^2) | log1p(x) and Welford’s centered recursion M_k = M_{k-1} + d_k(x_k - m_k) |
| Large Array Sums | Left-to-right loop \sum_{i=1}^n x_i | Error grows linearly: (n-1)u\sum |x_i| | Pairwise tree sum (u\log_2 n\sum|x_i|) or Kahan compensation |
| Least Squares & Ridge | Normal equations \mathbf{A}^\top\mathbf{A}\mathbf{w} = \mathbf{A}^\top\mathbf{b} | Squares condition number \kappa(\mathbf{A}^\top\mathbf{A}) = \kappa(\mathbf{A})^2 | QR/SVD (lstsq) + ridge damping \kappa = \frac{\sigma_1^2 + \lambda}{\sigma_d^2 + \lambda} |