Conditioning and numerical stability
How many digits of an answer survive floating point: machine epsilon, the condition number of a problem and of a matrix, QR instead of the normal equations, log-sum-exp and a stable softmax, catastrophic cancellation, ill-conditioned optimization.
Floating-point numbers
The topic Duality ended with certificates: a primal point, a dual point and a gap that bounds how far both are from the optimum. Every number in such a certificate, like every gradient, solve and decomposition in this course, is computed in floating point. This topic asks how many digits of an answer survive.
A floating-point number stores a fixed number of significant bits and an exponent, like scientific notation in base 2. The gap between and the next representable number is the machine epsilon . Each arithmetic operation returns the exact result rounded to the nearest representable number:
So a single operation is accurate to a relative error of about . The formats used in ML differ a lot:
| Format | Significant bits | Largest number | |
|---|---|---|---|
| float64 | |||
| float32 | |||
| bfloat16 | |||
| float16 |
A relative error of leaves the first decimal digits intact, so float64 carries about significant digits.
Two consequences show up everywhere. First, adding to a positive number smaller than half the gap between and the next representable number changes nothing. Right after that gap is , so in float64 1 + 1e-16 == 1 is True. Second, the range is finite. exp(710) is already inf in float64, and exp(89) is inf in float32.
The condition number of a problem
Rounding errors are tiny. Whether they matter depends on the problem. Take the system
Change the last entry of the right-hand side to , and the solution jumps to . The data changed by in relative terms, the answer by : an amplification of about . The two equations are nearly parallel lines, and their intersection slides far along them. No algorithm is to blame here. The problem itself is sensitive.
The condition number of a problem measures this sensitivity: the worst ratio of the relative change in the answer to the relative change in the data, for small changes. For a function of one variable it is
Three examples:
- : everywhere, so a square root halves relative errors.
- : , so is accurate only to about .
- : , huge near . At it is . Float64 returns , a relative error of , although the subtraction itself is exact. The error was made when was rounded.
Rounding the input alone perturbs it by up to . Even a perfect algorithm then returns an answer off by about . The rule of thumb: a problem with condition number loses about decimal digits.
The condition number of a matrix
For a linear system with invertible , the condition number is a property of the matrix. A change in the data moves the solution by , so . Divide by and use , which follows from :
Here is the largest stretch , and stretches by at most , with the singular values from the topic The singular value decomposition. The matrix of the previous block has and , so . The amplification of we saw stays under this bound.
Two extremes are worth remembering. An orthogonal matrix has all singular values equal to and : it rotates and reflects without distorting. A singular matrix has and .
Good solvers, such as LU with pivoting from Matrices and linear systems, Cholesky and QR, are backward stable: the computed is the exact solution of a slightly perturbed system, with relative perturbations of order . Combined with the bound above, their relative error is about , and no algorithm can promise more. The Hilbert matrix shows how fast this bites. Here is np.linalg.solve on in float64, whose exact answer is the vector of ones:
| Relative error of | ||
|---|---|---|
| , that is |
The residual stays near in every row. A small residual is a small backward error. With , the matrix satisfies , because , and its norm is , about here. So is the exact solution of a system that differs from ours in the sixteenth digit. The algorithm did its job; the error comes from . A small residual does not say is accurate.
Least squares: QR, not the normal equations
Least squares from Inner products, norms and orthogonality has two textbook routes. The normal equations are short to write. The QR route factors and solves . With the SVD the difference between them takes one line:
Forming squares the condition number before any solver sees it. Even a backward-stable solver then loses about digits. QR squares nothing. only rotates, so has the same singular values as , and the loss is about digits when the model fits the data closely. (With a large residual the least-squares problem itself gains a term , where is the angle between and the column space of . QR pays it too, but it vanishes for an exact fit, while the normal equations pay always.)
An experiment: design matrices with a prescribed , true weights , exact targets , float64, median relative error of over random matrices:
| Normal equations | QR | lstsq (SVD) |
|
|---|---|---|---|
At , a common sight with polynomial features or nearly duplicated columns, the normal equations keep barely one digit, while QR keeps about nine.
The rule for code: belongs in derivations. Programs call np.linalg.lstsq or a QR-based solver and never form an explicit inverse.
Log-sum-exp and a stable softmax
Classification losses are full of exponentials. Softmax turns logits into probabilities, and the cross-entropy needs the log-sum-exp:
Written this way, they break at moderate sizes. For float64 computes , so lse returns , and softmax divides by and returns nan. In float32 logits above are enough to overflow, in float16 above .
The fix uses a property of softmax: adding the same constant to every logit changes nothing, because cancels between the numerator and the denominator. For lse the constant simply comes out: . Take with :
Now every exponent is at most , so nothing overflows. The largest term equals , so the sum cannot vanish either, and . For the example, and the probabilities are .
The same idea rescues the softplus inside the logistic loss:
At the naive formula gives and the stable one gives . At the naive formula gives , because rounds to ; the stable one gives . This is why frameworks provide log_softmax and cross-entropy that takes logits, and why they beat log(softmax(z)).
Catastrophic cancellation
Subtraction is the operation that turns small input errors into large output errors. If and carry relative errors up to , then
When the factor is huge. The leading digits cancel, and the rounding noise in the trailing digits becomes the answer. This is catastrophic cancellation, the general form of the example from the second block.
Take , which tends to as . The identity gives a version without subtraction. In float64:
At the cosine rounds to exactly , and all information is gone. This time the problem is not to blame. Near the function is , so , which is tiny. The formula is to blame: the rounding error of , up to , meets the subtraction factor . An algorithm that loses far more than is unstable, and the rewrite makes it stable.
An ML example: batch normalization needs the variance of activations. The one-pass formula subtracts two large, nearly equal numbers. For the float32 values , , it returns instead of , and the square root of the variance becomes nan. The two-pass formula subtracts the mean first and then averages the squares; it returns . Finite-difference gradients suffer the same way: gets worse, not better, once is too small.
The recipe: when two nearly equal quantities are about to be subtracted, look for an algebraic rewrite that does the subtraction exactly or not at all.
Ill-conditioned optimization
The condition number also met us in Unconstrained optimization. On a quadratic loss with Hessian , gradient descent with the best fixed step shrinks the error by a factor of per step, where . The step must stay below , so the flat direction with curvature crawls, and the number of steps grows in proportion to .
Floating point makes flat directions worse still. In a flat direction the update is small, and if it falls below half the gap between neighbouring numbers, it is rounded away. In bfloat16, rounds back to . This is why mixed precision training runs the forward and backward passes in bfloat16 or float16, but keeps a float32 copy of the weights and adds the updates there.
Two standard remedies attack itself.
Preconditioning changes variables, , so that the Hessian in the new coordinates, , is closer to . Newton's method is the extreme case . Adam's per-coordinate step sizes and normalization layers are cheap approximations.
Weight decay adds to the loss, and with it to the Hessian. Every eigenvalue grows by :
The same shift is ridge regression in least squares and the small "jitter" added to kernel matrices before a Cholesky factorization.
One cost has stayed in the background. The good solvers of this topic, LU, Cholesky and QR, are backward stable, but each of them factors the matrix first: operations and stored numbers for an matrix. At that is out of reach, and the Hessian of a large network is never even written down. Yet a product is often cheap. Methods that touch only through such products are the next and last topic, Iterative methods: power iteration and conjugate gradient.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Go deeper — optional
Code and labs do not count toward the main percentage or the certificate.
- Log-sum-exp in codeoptional
Implement a numerically stable log-sum-exp — the backbone of stable softmax.
~15 min · easier on a computer · The Conditioning and numerical stability topic, log-sum-exp block.
Answers are saved on the server and tied to this browser until you sign in.