Conditioning and Numerical Stability
A computation is well conditioned if small changes in its input cause small changes in its output, and ill conditioned if they can cause large ones. Conditioning is a property of the problem, not of the code, but it decides how much floating-point rounding (and noise in data) the answer can absorb. In deep learning it shows up in matrix inversions, in normalization layers and, most importantly, in how hard a loss surface is to optimize.
The condition number of a matrix
For solving , a relative error in can be amplified by up to
the ratio of the largest to the smallest singular value. is perfect (an orthogonal matrix); means roughly decimal digits of accuracy can be lost. A singular matrix has .
import numpy as np
A = np.array([[1.0, 1.0], [1.0, 1.0001]])
b = np.array([2.0, 2.0001])
x = np.linalg.solve(A, b)
b2 = b + np.array([0.0, 0.0001]) # a tiny change in b
x2 = np.linalg.solve(A, b2)
print("cond(A) =", f"{np.linalg.cond(A):.0f}")
print("x =", np.round(x, 6))
print("x' =", np.round(x2, 6) + 0)
rel_in = np.linalg.norm(b2 - b) / np.linalg.norm(b)
rel_out = np.linalg.norm(x2 - x) / np.linalg.norm(x)
print(f"relative change in b: {rel_in:.1e}, in x: {rel_out:.1e}, amplification {rel_out / rel_in:.0f}")cond(A) = 40002
x = [1. 1.]
x' = [0. 2.]
relative change in b: 3.5e-05, in x: 1.0e+00, amplification 28285
A change of in one entry of moved the solution from to .
Conditioning and gradient descent
For a quadratic loss , the condition number of the Hessian controls gradient descent. The step size must stay below for stability, and then the flattest direction shrinks only by a factor of about per step: the number of steps grows in proportion to .
import numpy as np
def steps_to_converge(kappa, tol=1e-6):
H = np.diag([1.0, kappa]); w = np.array([1.0, 1.0]); lr = 1.0 / kappa
for t in range(1, 10**6):
w = w - lr * (H @ w)
if np.linalg.norm(w) < tol: return t
for k in (1, 10, 100, 1000):
print(f"kappa = {k:5d}: {steps_to_converge(k)} steps")kappa = 1: 1 steps
kappa = 10: 132 steps
kappa = 100: 1375 steps
kappa = 1000: 13809 steps
Much of the machinery of deep learning reduces effective ill conditioning: input standardization, careful initialization, batch and layer normalization, and per-parameter step sizes in Adam.
Standardizing inputs
Two features on very different scales (age in years, income in dollars) make the Hessian of a linear model ill conditioned, because . Subtracting the mean and dividing by the standard deviation of each feature brings close to 1 when the features are uncorrelated.
In software
np.linalg.condcomputes ; never invert a matrix you can solve with (np.linalg.solve,lstsq, Cholesky).- Normalization layers add to variances (
eps=1e-5) to keep division well conditioned. - Second-order and preconditioned optimizers (Shampoo, K-FAC) explicitly multiply gradients by an approximate inverse curvature to undo ill conditioning.
Exercises
Exercise 1: Condition number of a diagonal matrix
Find .
Answer
Solution
The singular values of a diagonal matrix are the absolute values of its entries: .
Exercise 2: Rescaling a feature
A linear model has features with standard deviations 1 and 1000 (uncorrelated, zero mean). Estimate before and after standardization.
Answer
About before, about 1 after.
Solution
, so . After dividing each feature by its standard deviation, .
Exercise 3: Digits lost (code)
Solve a Hilbert system (with ) and compare the error with .
Answer
; the error is about , within the bound .
Solution
import numpy as np
n = 10
H = 1.0 / (np.arange(1, n + 1)[:, None] + np.arange(n)[None, :])
x = np.linalg.solve(H, H @ np.ones(n))
print(f"cond {np.linalg.cond(H):.1e}, max error {np.max(np.abs(x - 1)):.1e}, kappa*eps {np.linalg.cond(H) * np.finfo(float).eps:.1e}")cond 1.6e+13, max error 3.2e-04, kappa*eps 3.6e-03
Test yourself
The condition number of a matrix is…
- its determinant
- the ratio of its largest to its smallest singular value
- its trace
- the number of nonzero entries
On a quadratic with Hessian condition number , plain gradient descent needs a number of steps that grows roughly…
- like
- in proportion to
- not at all
- like
Which practice does NOT aim to improve conditioning?
- Standardizing input features
- Normalization layers
- Increasing the batch printout frequency
- Adaptive per-parameter step sizes