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 define an entirely ordinary softmax, with
probabilities . 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 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 , a number too large for any standard floating-point format to hold, whereas an algebraically equivalent rewrite that never forms is accurate to a few units in the last place. By contrast, the 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 Fraction23.8.1 Floating-Point Arithmetic#
23.8.1.1 Representation and Spacing#
What does a computer actually store when we ask it to store ? The mechanism is easiest to see in a toy binary format that keeps only two bits after the binary point. Between and , this format can hold just four values: , , , and . Multiplying these four values by powers of two fills out the other intervals: between and , and between and . Each octave—an interval 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: (a relative error of ), (an error of ), and (an error of ). Halfway points are ties, and standard arithmetic breaks ties toward the neighbor whose last bit is : the midpoint therefore rounds to , an error of . Notice that no relative error exceeds . Rounding moves a number by at most half a gap, and in every octave half a gap is of the octave's smallest value. Figure 23.8.1 sketches this grid on the real line.
Floating-point numbers on the real line for a toy format with two mantissa bits (four values per octave, , smallest normal ). The absolute gap between neighbors doubles at every power of two while the relative gap stays near . 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 , fp32 at about ).
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 binary digits after the binary point,
specified by a sign bit , mantissa (or significand) bits , and an integer exponent 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 , adjacent values are spaced apart. The gap from to the next representable number, , is called machine epsilon; our toy format has and .
Rounding a real number to the nearest representable value moves it by at most half a gap, . Because throughout the octave, the relative error is at most . Calling a value normal when it has the form (23.8.1) with an in-range exponent, every real that rounds to a normal number satisfies
In words, each rounding perturbs a number by at most one part in : one part in for our toy format, about one part in 17 million for fp32 (), and one part in for bf16 (). The bound is called the unit roundoff. Standard IEEE arithmetic rounds the result of every basic operation to the nearest representable value, so the computed sum equals with , and the same guarantee holds for , , and (IEEE, 2019; Goldberg, 1991).
This clean relative model has three exceptions. Results larger than the format
can hold overflow to . Results smaller than the smallest normal
number underflow, stepping down through subnormal numbers that fill the
remaining gap to zero. Undefined operations, such as or ,
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 , 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 mantissa bits (about seven decimal digits) and reaches up
to . fp16 keeps bits (about three decimal digits)
but has a narrow exponent range: it overflows above , and below
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 mantissa bits (, roughly two to three decimal digits). Notice that the value
often quoted for bf16 is its unit roundoff .
The two fp8 formats push this trade-off further still: E4M3 keeps three
mantissa bits (about one decimal digit) and tops out at , 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 , 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 and and rounds up. The second sits right on that midpoint and rounds down to the even neighbor , whereas the third sits on the midpoint between and and rounds up to the even neighbor . 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 is the midpoint between and its upper neighbor, so ties-to-even sends it back to . The worst-case rounding error of half a gap really does occur, giving a relative error of , just inside the bound . Meanwhile, the gap at is times (about a million times) the gap at . Finally, the last three lines pinpoint where overflows: above in fp16, in fp32, and 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 sits well inside the range of ordinary unnormalized classifier scores.
At the opposite end, 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
. Taking later produces , and the backward pass fills
with inf or NaN. In fp16, subnormals begin below
, the smallest subnormal is
, and anything below
rounds straight to zero.
Addition introduces a second absolute threshold that matters directly for training. A gradient step replaces a weight by . If the update is small compared with the spacing around , the sum simply rounds back to , and the step vanishes without a trace.
Proposition (small updates vanish). Let be a floating-point number with in a format with mantissa bits, and let be real. If , then , except when and ; in that case the same holds for .
Proof. In the representable numbers are apart, so the neighbors of are , except that below the lower octave begins and the spacing halves to . Rounding to the nearest number returns whenever is closer to than to the adjacent grid point on its side—that is, whenever is strictly less than half of that gap.
For a weight update with , the proposition reads
In short, any update smaller than roughly 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 , falls into the
exceptional case of the proposition: because the spacing halves below , an
increase vanishes below (as Section 5.5 tests), whereas a
decrease already vanishes below . In bf16, a weight equal to therefore
ignores any decrease smaller than , so a learning rate of
with an order- gradient leaves the weight completely frozen. The
corresponding threshold is in fp16 and
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 leaves the bf16 weight stuck at , whereas clears the threshold and jumps to the neighbor . Similarly, fp16 swallows and responds to by stepping to , while fp32 keeps the full update.
Gradients run into the underflow threshold instead. In fp16, gradients below lose precision and those below vanish to zero. Multiplying the loss by a constant factor before the backward pass scales every gradient up by and lifts them back into the normal range; dividing by afterward in fp32 restores the true scale (Section 5.5.3.3 covers the practical workflow, and Exercise 1 determines the admissible window for ).
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 whose true label is the unlikely class . Its probabilities are , its log-sum-exp is , and the cross-entropy loss for class is for large . None of these outputs is extreme: even at , the probabilities are and , and the loss is simply .
23.8.2.1 The Max Shift#
Given logits , the softmax vector is defined by
At , evaluating this formula directly forms , which exceeds
fp32's overflow ceiling of . The second entry turns into inf/inf
(NaN), and the first collapses to . 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 leaves the ratio untouched, so softmax is shift-invariant:
Factoring out of the sum inside a logarithm gives the companion identity for log-sum-exp, , which is the logarithm of the softmax denominator:
Both identities hold for any , and choosing makes both computations safe. Every shifted exponent is then at most , so no exponential can overflow. At the same time, the largest term equals , so the sum is guaranteed to lie in and its logarithm cannot underflow to . Let us test this on in fp32, on the opening's in fp64, and on 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 , the shifted softmax returns , the true
rounded onto the subnormal grid with five significant
bits left, while the direct formula returns and NaN. Switching to higher
precision does not cure the problem: the logits from the
opening overflow even in fp64, turning the direct formula into
three NaNs where the shifted version cleanly returns .
At , 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 , then
and 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 ,
Proof. Set in (23.8.5). Every exponential lies in and the maximizing term equals , so the sum lies in and its logarithm in . Adding yields both bounds.
Log-sum-exp is therefore a soft maximum. In our two-class example, stays within of , attaining the full gap at where the two logits tie and hugging the maximum closely as grows (Figure 23.8.2).
Log-sum-exp as a soft maximum: stays within of , matching the sandwich bound for . The gap peaks at , where the two logits tie, and vanishes as grows.
Moreover, its gradient is the softmax itself, . That is why the gradient of cross-entropy with respect to the logits, for label , simplifies to ; 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:
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 is noticeably worse in floating point, because it first forms the large number and then subtracts it from the large number . How much difference does that parenthesization make? Let us compare both forms in fp32 on the logits :
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
, which is what turned inf/inf into three NaNs in the
opening. The shifted value sits comfortably inside
the sandwich . More interestingly, the two log-softmax
forms disagree: exponentiating gives probabilities that
sum to , whereas (23.8.6) sums to
.
Why did 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 was stored. Near , fp32 numbers are apart, so the true value rounds down by . Every log-probability computed as is therefore too high, every resulting probability is inflated by the factor , and their sum overshoots by . 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 is simply the negative log-softmax, so (23.8.6) gives it directly from the logits:
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 is . If we instead compute probabilities first, the true-class probability drops below fp32's normal range once and underflows completely to zero near , sending its negative logarithm to . Let us compare the two routes using the library's built-in functions, with and 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 in every row, and the probability route matches it at and . At , however, the probability falls into the subnormal range, and what happens next depends on how the library handles subnormal numbers.
PyTorch preserves subnormals: rounds to
the smallest fp32 subnormal, . Only a single significant bit
survives, so the loss reads —wrong in the first decimal
place with no warning. At , rounds to , 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 at returns —a relative error
of 100%—whereas the library function log1p returns . Is
near 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 at a point with is the factor by which a small relative perturbation in turns into a relative perturbation in . Perturbing to changes the output, to first order, to . Dividing the change by gives the amplification factor
For example, the exponential has : at , an input error of one unit roundoff becomes 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 is a first-order property of the exact mathematical function. It says nothing about how is evaluated, and it breaks down where , since relative error is undefined there.
Subtraction takes two inputs, and the same first-order reasoning applies to both. Suppose and carry relative errors , and suppose the subtraction itself is exact. Then , so the triangle inequality bounds the relative error of the difference by
The factor is subtraction's condition number, and it blows up whenever . 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 | regime | |
|---|---|---|
| large when | ||
| at , at | ||
| large for large | ||
| tends to as | ||
| always | ||
| variance of data with mean , spread | at most | derived below |
The second row settles our opening question: near is
completely well conditioned (). The naive algorithm
log(1 + x) fails because it takes a detour through an ill-conditioned
intermediate step. It first forms and then evaluates at
, where the logarithm has
. Rounding introduces a
relative error of order in , which magnifies by —more
than 100% in fp32. By contrast, log1p is written so that the rounding error
of never enters the result; for tiny , it simply returns .
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 is small and the computed answer is bad, the algorithm is at fault and we should rewrite it. Whenever 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 experiment and then subtracts two fp32 numbers that agree in their first seven decimal digits, and , whose true difference is :
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 and , every fp32 difference is an integer multiple of , and the true difference does not fall on that grid. The subtraction returned two ulps, (20% too small), yet once again it committed no error of its own. The inputs were stored as and , 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 . Multiplied by , it allows a relative error of up to , and the observed falls squarely inside the bound.
The same cancellation appears in and near (where
log1p and expm1 avoid it), in near (rewritten as
), and in the quadratic formula when (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 . How small should we make the step ? By Taylor's theorem, the mathematical truncation error is about , which shrinks as . Meanwhile, each function evaluation carries a rounding error of roughly , and dividing their difference by magnifies that error to about , which blows up as . The total error is minimized where the two terms balance, at
Because the optimal error scales as , the best possible forward difference keeps only about half of the format's digits. For at , this predicts (error ) in fp64 and in fp32. Let us sweep from down to 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 from at (where truncation dominates) down to roughly near (the exact value at any single fluctuates with rounding noise), and then climbs back to at as cancellation takes over. In fp32, the sweet spot at to leaves only about three correct digits; from downward, rounds straight to , making the difference quotient and the error equal to the entire derivative, . 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 in fp64 just as fp32 did
at , 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 with mean and standard deviation , the textbook identity
tempts us to compute the variance in a single pass by accumulating only the sums of and . In exact arithmetic the identity is flawless; in floating point it is a trap. Whenever , both terms on the right sit near while their difference is , so the cancellation factor (23.8.9) is roughly . For and , that factor reaches —two orders of magnitude larger than the 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 by a relative error with , replacing by . The derivative of the variance with respect to is , because the induced change in multiplies . Writing , the first-order change in the variance is therefore
The first sum has magnitude at most . By the Cauchy–Schwarz inequality, the second has magnitude at most . Dividing by shows that the relative condition number of the variance is at most , or about here (choosing gives for Gaussian data). The problem itself therefore permits an error of only —about seven accurate digits. The naive one-pass formula, by contrast, suffers an error of order : 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 rather than . Welford (1962) maintains a running mean and a running sum of centered squares , updating both from the deviation of each new sample from the previous mean:
Notice the asymmetry in the update of : 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 , the recursions (23.8.10) satisfy, for every and in exact arithmetic,
Proof. The mean identity follows immediately from the first recursion. For , we induct on . Using and , we split off the -th term and recenter the first terms around :
The cross term vanishes because , and the inductive hypothesis identifies the first sum as . Combining the remaining two terms gives , which is exactly what the recursion adds.
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 and both sit near . By Sterbenz's lemma, however, that subtraction is exact, and is exact input data, so the only error in comes from the running mean—at most a few dozen ulps at over steps. Every quantity added into is therefore a deviation of scale , so rounding errors in the updates enter relative to rather than . Even a constant offset in the mean shifts a centered sum of squares only by , because the first-order term multiplies . In practice, Welford's error matches the problem's own sensitivity, , whereas the naive one-pass formula suffers an error of .
Let us compare all three methods—naive one-pass, Welford, and a two-pass reference—on fp64 samples with mean and variance :
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 (typically , , or ), nowhere near the true variance , and frequently negative. Why ? Both and lie in , where adjacent fp64 numbers are apart, so their difference can only be a multiple of : our predicted error of about , 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 numbers, and in floating point the order of addition matters. Each addition introduces a factor , so in a plain left-to-right sum the first term passes through all roundings. To first order in , a left-to-right sum satisfies
Because early terms accumulate the rounding error of every subsequent
addition, the worst-case error grows linearly with . Pairwise summation
avoids this by recursively summing the two halves of the array, so every term
passes through only additions and the bound shrinks to
; 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 (Exercise
8). Let
us add copies of fp32's (whose stored value is
) both left to right and pairwise, padding the pairwise
array with zeros to 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 —almost 9% too high, though still inside its bound . Pairwise summation lands at , within of the exact sum and well inside its bound .
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 , fp32 numbers sit apart, so equals gaps and every addition rounds up to two gaps, —25% too large. Above the spacing doubles to , and each addend again rounds to ; earlier, between and , it rounded down to . 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
how fragile such an answer can be. The solution is , and raising the second right-hand side by , a relative change of in the data, moves it to . Each equation is a line in the plane, and the solution is where the lines cross. These two lines have slopes and and meet at an angle of , so shifting one of them slightly slides the crossing far along the other (Figure 23.8.3).
A linear system is sensitive when its lines are nearly parallel. (a) Two perpendicular lines meet at ; shifting the second by moves the crossing by 5%: amplification , . (b) The lines and also meet at , but the same shift moves the crossing to , a 100% change from a 3.4% change in : amplification , bounded by . The text's system, with in place of , has the same geometry at an angle of and .
Let us read the same numbers in the other direction. Suppose a solver returned for the original system. Its forward error, the distance to the true solution, is 100%. Yet is the exact solution of a nearby problem, the one with changed by . 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 : 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 that factor is (Section 21.5.3.2), and it is about for the two lines. The shift realizes of it, because it is not along the most amplified direction.
23.8.4.2 Backward and Forward Error#
For a linear system and a computed solution
, the forward error is
and the backward error is the
size of the smallest change of the data that makes exact.
An algorithm is backward stable if its backward error is of the order of
, 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 and . The smallest with is , attained by .
Proof. Any such satisfies , so . The rank-one matrix maps to , and its norm is .
Relative to the size of , the backward error is
A small residual certifies a small backward error, whatever the condition of the problem. For in the two-line system, and . The version that perturbs 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 below about 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 and (Section 21.5).
Proposition (forward error condition number backward error). Let be invertible, let , and suppose the computed exactly solves a nearby system, with . Then
Proof. Subtracting from gives , hence and
The error here is measured relative to , the vector we have. Relative to the true , substituting and solving for gives the bound when , the same to first order. On the two-line system, , and the error relative to is , 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 , and taking of the bound gives the rule of thumb
The rule is a worst case. A matrix with can lose three of fp32's seven digits. The chapter's running example has that 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 , , has a
condition number that grows exponentially with : its rows become nearly
parallel in the same way as the two lines above. We solve
with , whose
exact solution is , 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
in fp64 rounds every entry of , a
change of the data of relative size before the solver starts. (Rounding
the entries , , … does no harm here, because 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 , we now construct the
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 at to well under one at , while the backward error stays at or below about : 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 by an error of the same order in every row, about , and for , and . The digits were lost when 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 , 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 with of full column rank is solved by the normal equations . This is an algebraically equivalent route through a worse-conditioned matrix (Section 21.5.3.2):
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 digits. A solve by QR ( with orthonormal and triangular ) or by the SVD works on directly and loses about , when the residual is small. With a large residual the least-squares problem itself is more sensitive: its condition number is about , where is the angle between and the column space of . QR and SVD then lose close to 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 , so . The cell therefore builds harder designs, with and , 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 the normal equations keep about to
digits against about for lstsq, and at about to
against about to . The exact digits vary from run to run by a digit
or two; the gaps scatter around , 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
.
23.8.4.5 Ridge Regularization and Conditioning#
When 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 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 , whose minimizer is
the ridge solution of Section 21.5.3.1. Let be the singular values of , with beyond its rank. The matrix has the eigenvectors of and the eigenvalues . It is therefore positive definite, hence invertible even when is rank deficient, and
Whenever this ratio decreases strictly in (its derivative is ) and tends to as . Adding lifts the floor of the spectrum. While it barely moves the ceiling, so falls about in proportion to once . The damping term of second-order optimizers and the jitter added to a kernel matrix in Gaussian process regression (Chapter 28) are this under other names.
The price is a different minimizer. In the present notation, with the right singular vectors of and the minimum-norm least-squares solution, the filter factors of Section 21.5.3.1 read
Ridge damps most the directions with small , and these are the very directions in which the unregularized solve amplifies data errors by . 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.
Level sets of the least-squares objective before and after adding the ridge term , drawn for so that both panels stay legible (the running example's would draw as a line). The penalty lifts every eigenvalue of by ; the semi-axes, proportional to , 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 counts the steps of gradient descent on the ridge objective. At the best fixed step, gradient descent on a quadratic with condition number contracts the error by per step (Section 23.1). Started at the origin, where the error is , it has relative error after steps, so a tolerance is met within
The second inequality holds because . For six digits it allows steps per unit of ; a run in more than two dimensions can finish sooner (Exercise 4).
How many steps does a given save, and what does it cost? We measure
both on the running example. Its objective
is least squares with
and
. Its minimizer is , 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 to as goes from to , and the step count falls with it, from to . The ratio of steps to stays near (at small the approximation is loose, and rounding up to a whole step matters). The last column shows what the saved steps cost. At the slow direction, with , is halved to , while the stiff direction, with , moves by . At the stiff direction is halved too. A sweep over shows 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 apart, with slope close to while lies well between the eigenvalues and . 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 corresponds to a constraint on , so a 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 bits of relative precision and a finite exponent range. Every rounding introduces a relative error of at most , 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 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, bounds the forward error by times the backward error, which a residual certifies, so about digits are lost, and twice that through the normal equations. Ridge adds to every squared singular value, which lowers for the solve and for gradient descent alike, at the price of shrinking the solution by the filter factors .
23.8.6 Exercises#
-
Loss-scale window. Loss scaling multiplies the loss by a factor , which multiplies every gradient by , and divides the gradients by after they have been converted to fp32. In fp16 the smallest normal number is , the smallest subnormal number is (values below round to zero), and the largest finite number is . Suppose that the exact nonzero gradient entries of a network have magnitudes between and , and that the backward pass computes the scaled gradients in fp16.
- Find all powers of two for which every scaled gradient is a normal fp16 number.
- The gradients of a deeper network have magnitudes between and . Show that no scale keeps all of them normal. Take the largest power of two that avoids overflow. How many significant bits does a scaled gradient of magnitude keep, and what is its relative rounding error?
- 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?
- How do the answers to the first two sub-items change when the gradients are computed in bf16?
-
[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.
- The root of smaller magnitude of for and , as a function of , for example and . (Hint: multiply by the conjugate.)
- The function for , which computes from , at . Find one formulation that is accurate for small and one that is accurate for large , and choose a switching point.
- The binary cross-entropy of a logit with label , , at . At which of these does the formula as written overflow, and at which does it return ? Show that equals it, never overflows, and loses no digits. Which part of the log-sum-exp sandwich is it?
- at .
Part 2 is adapted from Martin Mächler, Accurately Computing log(1 − exp(−|a|)), Section 2.
-
[code] Normal equations in floating point. The normal equations square the condition number (23.8.13).
- For , the matrix of Läuchli (1961) has a first row of ones and below it. Compute , the singular values of , and . Show that for the matrix 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 when lies in the range of ? What changes in the prediction when the residual is large?
- Modify the
#numerical-stability-conditioning-normal-equationscell to sweep for . Plot the correct digits of the normal equations and oflstsqagainst , together with the two rule-of-thumb lines and . At which does the rule predict that the normal equations keep no correct digit, and what do you observe there?
-
[code] Feature scaling as preconditioning. Features measured in different units give the columns of a design matrix very different norms. Let be a matrix with standard normal entries, let , and let for a random .
- Apply
gd_iterationsof the#numerical-stability-conditioning-ridgecell, which takes and , to this design at . Compute 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 . - Divide every column of by its norm and repeat the measurement. How does the minimizer of the rescaled problem map back to ?
- Part 2 of Exercise 1 of Section 23.2 writes gradient descent in new coordinates with as gradient descent on the original problem preconditioned by a positive definite matrix , with update . Which and which correspond to column scaling? How is related to the diagonal of ?
- Apply
-
[code] Stochastic rounding. ● Stochastic rounding (Gupta et al., 2015) rounds a real number between adjacent representable values to with probability and to otherwise.
- Show that the rounded value has expectation and variance , where .
- A bf16 weight starts at and receives updates of , each followed by stochastic rounding. The weight stays in , where the bf16 spacing is . 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?
- For a positive fp32 number, adding a uniformly random integer
from 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_bf16function 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.
-
Exact subtraction. ● Subtraction can be exact and still return an inaccurate difference.
- Show that the bound (23.8.9) is attained for suitable and with .
- Prove Sterbenz's lemma (Sterbenz, 1974): if and are floating-point numbers in the format (23.8.1) with , then is a floating-point number, so the computed difference is exact. Assume that the format includes subnormal numbers.
- In the
#numerical-stability-conditioning-log1pcell, the fp32 difference misses the true value 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 and , and check that the bound of the first sub-item covers the error.
-
[code] Merging running moments. ● Data-parallel training computes statistics on shards and combines them. Let shard hold values with mean and centered sum of squares , and let shard hold values with and .
- Derive exact formulas for the mean and the centered sum of squares of the union of the two shards in terms of , , , , , and .
- Show that the case is Welford's recursion (23.8.10).
- Split the samples of the
#numerical-stability-conditioning-welfordcell into shards of nearly equal size (np.array_split) for . 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 and and applying the one-pass formula. Explain the difference.
-
[code] Summation error growth. ● Let and let be its computed value. In-order summation has the worst-case bound .
- For , recursive pairwise summation splits the terms into two halves, sums each half recursively, and adds the two results. Prove that it satisfies .
- For uniform random
numbers in stored as fp32, measure the relative errors of
in-order summation (
np.cumsum(x)[-1]), ofnp.sum(a blocked pairwise summation), and of Kahan's compensated summation (Kahan, 1965) against a float64 reference. Kahan's method keeps a correction : after each addition it sets and subtracts from the next term. Plot the three errors against together with the two bounds. - How does the measured error of in-order summation grow with compared with its worst-case bound, and why? Why is the text's sum of copies of so much closer to the worst case?
- What limits the error of the two accurate methods at large ?
Adapted from Steven G. Johnson, MIT 18.335 Introduction to Numerical Methods, Problem Set 1, Problem 4.
-
[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 : the factorization runs in low precision and only residual work runs in high precision. Starting from an fp32 solution , it repeats
where the residual and the update are computed in fp64 and the correction comes from an fp32 solve.
- Model the fp32 solve as backward stable, with and a moderate constant , and neglect the fp64 rounding errors. Show that the error satisfies . Derive a contraction factor in terms of , and state when it is below .
- Implement the iteration for the Hilbert matrices of the
#numerical-stability-conditioning-hilbertcell with , usingnp.linalg.solveon fp32 copies of and for the correction. Record the forward error over ten iterations and compare its final value with that of an fp64 solve. For which does refinement reach the accuracy of the fp64 solve? For which does it still converge, but too slowly to reach that accuracy within ten iterations? For which does the error grow? - Estimate the measured contraction per iteration for each and compare it with and with the spectral radius of , where is the fp32 copy of and the inverse is applied in fp64. Which perturbation dominates in this experiment, and how pessimistic is the bound of the first sub-item?