Numerical Stability and Conditioning

Dive into Deep Learning · §35.8

Numerical Stability and Conditioning
IEEE floating point · max-shifted softmax · catastrophic cancellation · Welford variance · matrix conditioning & ridge

Two Faces of Numerical Failure: NaN vs. Silent Drift

Motivation

  • Unstable algorithm on an easy problem: Naive softmax on \mathbf{z} = (1000, 1001, 1002) overflows e^{1000} = \infty \implies \text{NaN}, cured completely by the max-shift rewrite \mathbf{z} - \max(\mathbf{z}).
  • Stable solver on an ill-conditioned problem: On a 12 \times 12 Hilbert system (\kappa \approx 1.7 \times 10^{16}), np.linalg.solve has backward error \omega \approx 10^{-17} yet returns an answer off by 30\%—requiring problem regularization.

Binary Floating-Point Grid and Relative Spacing

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

  • Constant relative spacing: Each octave [2^e, 2^{e+1}) holds 2^p equally spaced grid points separated by 2^{e-p}.
  • Machine epsilon & unit roundoff: The gap above 1 is \varepsilon_{\mathrm{mach}} = 2^{-p}. Rounding any real x to the nearest grid point moves it by at most half a gap, so \mathrm{fl}(x) = x(1 + \delta) with relative error bounded by the unit roundoff u: |\delta| \le u = \tfrac12\varepsilon_{\mathrm{mach}} = 2^{-p-1}
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Deep Learning Formats: Dynamic Range vs. Precision

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}).

Round-to-Nearest Ties-to-Even and Overflow Ceilings

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

When Small Gradient Updates Vanish Completely

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).

Shift Invariance and the Max-Shifted Softmax

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.]
  • Why c = \max_j z_j is optimal: Every shifted exponent satisfies z_j - c \le 0 (making overflow impossible), while the largest term is e^0 = 1, keeping the denominator sum in [1, n] (making denominator underflow to 0 impossible).

Log-Sum-Exp as a Soft Maximum Sandwich

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

  • Proof: Since each e^{z_j - c} \in (0, 1] and the maximizing term equals 1, the sum lies in [1, n] and its logarithm lies in [0, \log n].
  • Gradient & cross-entropy: \nabla\mathrm{lse}(\mathbf{z}) = \mathrm{softmax}(\mathbf{z}), and for n = 2 with \mathbf{z} = (0, t), \mathrm{lse}(0, t) = \log(1 + e^t) is the softplus activation (within \log 2 \approx 0.693 of \mathrm{ReLU}(t) = \max(0, t)).

Parenthesizing Log-Softmax to Avoid Rounding Loss

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
  • Where did z_i - \mathrm{lse}(\mathbf{z}) lose precision? Near c = 1002, 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.

Cross-Entropy from Logits vs. Probability Underflow

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.

Relative Condition Number of a Mathematical Function

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|

Separating an Unstable Algorithm from a Hard Problem

Catastrophic Cancellation

  • Well-conditioned problem: f(x) = \log(1 + x) near x = 0 has \kappa_f(x) = \left|\frac{x}{(1+x)\log(1+x)}\right| \to 1.
  • Unstable intermediate detour: Evaluating 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.
  • Direct series (log1p): Evaluates x - x^2/2 + \cdots directly to full machine precision.

Sterbenz’s Lemma and Cancellation in Stored Inputs

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
  • Sterbenz’s Lemma (1974): Whenever two floating-point numbers satisfy b/2 \le a \le 2b, their difference a - b is exactly representable with zero rounding error.
  • Why the result is still off by 20\%: The subtraction operation itself committed zero error; it merely cancelled the shared leading bits and exposed the prior rounding errors committed when a and b were first stored on the 2^{-23} \approx 1.19 \times 10^{-7} grid.

Truncation vs. Cancellation in Finite Differences

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
  • Optimal step h^\star = 2\sqrt{\frac{u|f(x)|}{|f''(x)|}}: Minimizing the sum yields minimum error \approx 2\sqrt{u|f(x)f''(x)|} \propto \sqrt{u}, retaining only half the digits of the format (\sim 8 digits at h^\star \approx 10^{-8} in fp64, vs. \sim 3.5 digits at h^\star \approx 5 \times 10^{-4} in fp32).

Why Naive One-Pass Variance Squares Conditioning

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

  • Condition number of the variance problem: Perturbing each input x_i \mapsto x_i(1 + \delta_i) with |\delta_i| \le u changes the variance by \frac{2}{N}\sum_i (x_i - m)x_i\delta_i, yielding relative condition number \kappa_{\mathrm{var}} \le 2(1 + |m|/s) \approx 2|m|/s. For m = 10^9, s = 1 in 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 in \frac{1}{N}\sum x_i^2 - m^2: Both terms have magnitude \approx m^2 = 10^{18} while their difference is s^2 = 1, so the subtraction condition number is \frac{2m^2}{s^2} = 2 \times 10^{18} > 1/u, squaring the condition number and destroying every single digit.

Welford’s Stable One-Pass Variance Recursion

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)

  • Zero cancellation: Every increment d_k(x_k - m_k) is a centered deviation of scale s^2 = O(1) rather than m^2 = 10^{18}, achieving the optimal error O(u|m|/s).

Naive Variance vs. Welford at Mean 10⁹

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
  • Because 10^{18} \in [2^{59}, 2^{60}), adjacent 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 Order: Left-to-Right vs. Pairwise Trees

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
  • Why left-to-right drifts by +8.8\% on 10^7 copies of 0.1: Once the running 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).

Geometric Conditioning of Linear Systems

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

  • Extreme sensitivity: Perturbing b_2 by +10^{-4} (a relative data change of 3.5 \times 10^{-5}) shifts the intersection to \hat{\mathbf{x}} = (0, 2), a 100\% forward error.
  • Forward vs. backward error: For the original system, \hat{\mathbf{x}} = (0, 2) has 100\% forward error, yet its backward error (the smallest relative data perturbation for which \hat{\mathbf{x}} is exact) is only 3.5 \times 10^{-5}.

Backward Error, Residuals, and Backward Stability

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):

  • Exact formula for backward error from the residual \mathbf{r} = \mathbf{b} - \mathbf{A}\hat{\mathbf{x}}:
    • Any perturbation satisfying (\mathbf{A} + \Delta\mathbf{A})\hat{\mathbf{x}} = \mathbf{b} must map \Delta\mathbf{A}\hat{\mathbf{x}} = \mathbf{b} - \mathbf{A}\hat{\mathbf{x}} = \mathbf{r}, so \|\mathbf{r}\|_2 \le \|\Delta\mathbf{A}\|_2\,\|\hat{\mathbf{x}}\|_2.
    • The rank-one perturbation \Delta\mathbf{A}^\star = \frac{\mathbf{r}\hat{\mathbf{x}}^\top}{\|\hat{\mathbf{x}}\|_2^2} achieves equality with spectral norm \|\Delta\mathbf{A}^\star\|_2 = \frac{\|\mathbf{r}\|_2}{\|\hat{\mathbf{x}}\|_2}, giving the exact relative backward error: \omega = \min_{(\mathbf{A} + \Delta\mathbf{A})\hat{\mathbf{x}} = \mathbf{b}} \frac{\|\Delta\mathbf{A}\|_2}{\|\mathbf{A}\|_2} = \frac{\|\mathbf{b} - \mathbf{A}\hat{\mathbf{x}}\|_2}{\|\mathbf{A}\|_2\,\|\hat{\mathbf{x}}\|_2}
  • Certificate of solver quality: A small relative residual \omega \approx u proves that the solver did its job to machine precision, regardless of how large the forward error turns out to be.

Forward Error Bound and the Lost-Digits Rule

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

  • Lost-Digits Rule of Thumb: For any backward-stable solver (\omega \approx u), \hat{\mathbf{x}} retains roughly \log_{10}(1/u) - \log_{10}\kappa(\mathbf{A}) accurate decimal digits.

Acquitting the Solver on the Hilbert Matrix

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
  • At n = 12 (\kappa \approx 1.7 \times 10^{16}), 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.

Why the Normal Equations Square κ(A)

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
  • At \kappa(\mathbf{A}) = 10^6 in 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.

Ridge Regularization Lifts the Spectral Floor

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}

  • SVD filter factors: With \mathbf{w}_0 = \mathbf{A}^+\mathbf{b}, \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 Ridge damps noisy directions (\sigma_i^2 \ll \lambda) while preserving strong directions (\sigma_i^2 \gg \lambda).
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

How Ridge Simultaneously Speeds Up Gradient Descent

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  ]
  • On our chapter benchmark \mathbf{A}^\top\mathbf{A} = \mathrm{diag}(1, 1000) with true unregularized minimizer \mathbf{w}_0 = (1, 1), setting \lambda = 100 lowers \kappa from 1000 to 10.9 and cuts GD steps from 6{,}908 to 76—at the bias cost of shrinking the flat coordinate by the filter factor \frac{1}{1 + 100} \approx 0.0099.

Log–Log Scaling of Condition Number and GD Steps

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:

  • The two curves stay parallel on log–log axes, separated by the constant factor \tfrac12\ln(10^6) \approx 6.9 steps per unit of \kappa.

Concept Check: Precision, Cancellation, and κ

Concept Check

Test your grasp of floating-point arithmetic, cancellation, and conditioning:

  1. A parameter equals w = 1.0, and gradient descent applies an update \eta g = 10^{-3}. Does the stored parameter change in bfloat16 (p = 7)? What about in fp16 (p = 10)?
  2. In 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?
  3. If a design matrix \mathbf{A} has condition number \kappa(\mathbf{A}) = 10^6 and zero residual, roughly how many accurate decimal digits do the normal equations \mathbf{A}^\top\mathbf{A}\mathbf{w} = \mathbf{A}^\top\mathbf{b} vs. QR/SVD keep in 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}}.

Summary: Numerical Stability and Conditioning

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}