A classifier outputs three scores for one image: , and . The softmax (P3.A8) turns scores into probabilities, and by the formula the answer is . Run the formula as it is written in a textbook and the computer answers . The maths is correct. The computer just cannot hold the numbers in the middle of the calculation.
This lesson is about that gap: which calculations break, why, and the small rewrites that fix them. They are not exotic. Deep-learning libraries use them, and a training run that skips them can end in a loss of NaN.
Numbers have a size limit
A computer stores a number with a fixed number of bits (P1.G1). A 64-bit float, which is NumPy’s default, can reach about . The smallest positive size it can keep is about . Beyond the top it gives up and stores inf (infinity). Below the bottom it stores .
- Overflow: the true result is too large, so the computer stores
inf. In 64-bit numbersnp.exp(709.78)still works andnp.exp(709.79)givesinf, because . NumPy prints aRuntimeWarning: overflow encountered in exp. - Underflow: the true result is positive but too small, so the computer stores
0.0.np.exp(-745)is still the smallest positive number, , andnp.exp(-746)is exactly . No warning appears by default.
The exponential makes this easy to hit, because it grows so fast. The limits depend on the format.
| Format | Largest number | overflows above |
|---|---|---|
| 64-bit (fp64) | about | |
| 32-bit (fp32) | about | |
| 16-bit (fp16) | about |
The smallest positive numbers are about (64-bit), (32-bit) and (16-bit).
Scores of are not realistic for a trained model’s final layer, but scores of or are possible, and the 16-bit and 32-bit rows show that they are enough to break the naive formula. (The 16-bit format, fp16, is covered in P1.G1. The bf16 format has about the same range as fp32, so it overflows at about too.)
Subnormal numbers soften the bottom edge a little. Just above the smallest positive number, floats lose digits of precision gradually instead of jumping to zero. So exp(-745) is a number with almost no accurate digits. It is better to think of the bottom limit as the point where a number stops being usable.
inf and NaN spread
Once inf exists, arithmetic with it does not recover.
- and are well defined.
- , , and have no meaningful value. The result is NaN, “not a number”.
- NaN poisons everything it touches: is NaN, a sum containing a NaN is NaN, and a comparison with NaN is false.
np.nan == np.nanisFalse; usenp.isnanto test.
So one overflow in the middle of a network does not stay local. The forward pass returns NaN, the loss is NaN, the gradients are NaN, and the weights become NaN after the first update.
The naive softmax breaks
The softmax of scores is
The direct translation is e = np.exp(z); e / e.sum(). For it works: . Now take . All three exponentials overflow to inf, the sum is inf, and every entry is NaN.
The opposite problem appears for very negative scores. For every exponential underflows to , the sum is , and every entry is NaN. Large scores break one end of the number range, very negative scores break the other.
The widget keeps the scores and adds one constant to all of them. This does not change the true probabilities. It does change what the computer can hold.
Things to try, all checked against the widget’s code:
- 64-bit, . Naive and stable agree. Slide up: the naive column is fine up to and turns bad at (the largest score is then , above ), and at it is NaN.
- 32-bit. The break is at : the exponential of is above .
- 16-bit. The break is early. At every exponential fits, but their sum, about , is more than , so the naive probabilities are all . At they are .
- Negative . At every format underflows to . In 16-bit numbers underflow starts at .
The widget models only the limits of each format (the largest and the smallest positive number), not the rounding of digits.
The fix: subtract the largest score
The fix rests on one fact: adding the same number to every score does not change the softmax.
Shift invariance. For any constant ,
The common factor cancels (it is the rule from P1.A2). So for every , and we are free to pick the that is best for the computer. The best choice is the largest score, :
- The largest shifted score is exactly , so its exponential is exactly . Every other exponential is at most . No overflow.
- The sum contains the term , so it is at least . No division by zero. The other terms may underflow to , which is harmless: they were negligible anyway.
For we have , the shifted scores are , and
Dividing gives , the same as for , as it must be since the three scores differ by the same gaps.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
To see a 32-bit failure, replace the loop’s list by the single logits and write z = np.array(z, dtype=np.float32): the naive softmax gives and the stable one gives .
Many rows at once
Real code applies the softmax to a whole array, one row per example (or one row per token in attention, P7.4). The maximum, the sum and the division must all work along the last axis, and keepdims=True keeps the result a column so that it broadcasts back across each row (P1.B14):
def softmax_rows(S):
S = S - S.max(axis=-1, keepdims=True) # shape (rows, 1), subtracted from every column
e = np.exp(S)
return e / e.sum(axis=-1, keepdims=True)
For the two rows and both rows of the result are . Without keepdims=True, an array with 2 rows and 3 columns raises a shape error, and a square array runs but subtracts and divides by the wrong numbers.
Log-sum-exp
Many formulas need the logarithm of the sum, not the sum. The log-sum-exp of is
Computed directly it overflows exactly like the softmax. The same shift fixes it. Write and factor out of the sum:
That is the log-sum-exp trick: add the largest score back after taking the log of the shifted sum. For the shifted sum is , , and so . Two checks: the value is at least the largest score, and it is at most . The general rule is
The left side holds because the sum contains the term . The right side holds because every term is at most and there are of them. So LSE is a smooth maximum: close to the largest score when one score dominates, and above it when all scores are equal ().
Log-softmax and the loss from logits
Take the logarithm of the softmax:
This is the log-softmax, and it needs no division and no exponential of anything large. For our scores it is : each score minus . Applying the exponential to these gives back the probabilities.
The cross-entropy loss of the true class (P1.E3) is , the negative log of the softmax probability. In terms of the scores:
For the true class in our example, . P1.E3 found for the scores when the third class is true. That is the same number as here: in both cases the true class has the largest score, so its shifted score is and the loss is the log of the shifted sum.
Why not compute the softmax first and take the log afterwards? Because the softmax step can lose information that the log cannot get back. Take the scores . The softmax is , since underflows to . Then and the loss for class is . The log-softmax is : the true answer, a perfectly ordinary number. For this reason libraries offer a loss that takes the logits and does the whole calculation in one stable step. PyTorch’s documentation describes the input of F.cross_entropy as “unnormalized logits”, and torch.logsumexp as “numerically stabilized”. The loss for binary classification from a logit, BCEWithLogitsLoss, says in its documentation that it uses the log-sum-exp trick and is more stable than a sigmoid followed by a separate loss. When you use these, do not apply a softmax or a sigmoid first: that would apply the function twice and give the wrong loss.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Go deeper The gradient of log-sum-exp is the softmax
Differentiate with respect to . The chain rule (P1.C3) gives , which is exactly . So , and the softmax is the gradient of the smooth maximum. It also explains the gradient of the loss : it is , the predicted probabilities minus the one-hot target, the formula of P1.E3. A numerical check with scores gives for the slope of in each coordinate.
The stable version has the same gradient, since the shift does not change the function.
The sigmoid, log-sigmoid and softplus
The sigmoid (P1.A5) has the same problem on one side. For , overflows. The result happens to come out as , which is correct, but NumPy still prints an overflow warning, and in a longer calculation an intermediate can turn into a NaN or a wrong (for example inside a logarithm). A stable version picks the form by the sign of :
The two forms are algebraically equal (multiply top and bottom of the first by ). In each case the exponent is not positive, so the exponential is at most .
The sigmoid is a two-class softmax: . So the log-sum-exp of the pair gives the next function, the softplus:
The shift trick with gives the stable form
The naive gives at and the stable form gives . At the other end, : is so small that rounds to exactly , and the naive result is , while the true value is . The fix for this is the next idea: use log1p.
The log-sigmoid is . This is what the binary cross-entropy needs (P3.A7). For the naive , while . A frequent mistake is “fixing” the by adding a tiny constant such as to the probability. That removes the infinity but also hides the truth: the loss is capped near () instead of , and it changes the gradient. The stable log-sigmoid needs no such patch.
Small numbers: log1p and expm1
There is another trap that has nothing to do with overflow. Near a float has gaps of about in 64-bit numbers (and in 32-bit, P1.G1). So rounds to exactly , and all the information in the small number is lost before the log is taken.
- computed as
np.log(1 + 1e-10)gives . The true value is , so only about 7 digits are right. - At it gives exactly , while the answer is .
np.log1p(x) computes without ever forming , so it stays accurate for small . In the same way np.expm1(x) computes accurately for small , where np.exp(x) - 1 suffers the same loss. (Use the plain forms when is not small.)
This is an example of catastrophic cancellation: subtracting two nearly equal numbers wipes out the leading digits they share and leaves mostly rounding noise. The same thing wrecks the textbook variance formula (P1.D4) for values such as : the true variance is , and the formula gives in 64-bit numbers. Subtracting the mean first, as np.var does, avoids it. The trick is the same as before: rewrite the formula so the dangerous subtraction never happens.
The binary cross-entropy shows how these pieces fit together. For a logit and a label , the loss is . This is the form frameworks use. For and it gives , and a sigmoid followed by a log gives infinity. For , it gives , the same as .
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Products of probabilities: work with logs
The probability of a long sequence is a product of many factors below (P1.D10, P1.E1). Multiply factors of and the answer is , which still fits. The smallest positive size is about , and is that size. At factors the product is exactly . Factors of reach at of them. A model that scores a text of a thousand tokens with probability each, as in P1.E1, has a true probability of , which no 64-bit float can hold.
The log of a product is the sum of the logs (P1.A2): . For halves the sum is , an ordinary number, and for factors of it is . So training code adds log-probabilities in place of multiplying probabilities. This is also why the loss of a language model is an average of negative log-probabilities (P1.E3).
When probabilities must be added inside the log, as in for a mixture or a sum over hidden states, the log-sum-exp trick is the tool: with the log-probabilities. NumPy has it as np.logaddexp, and SciPy has scipy.special.logsumexp for a whole array.
Intuition
Think of the scores as the heights of mountain peaks. The softmax cares only about how much higher one peak is than another. Heights measured from sea level may be huge numbers, so measure from the highest peak instead: that peak is at and the others are at small negative numbers. Nothing about the comparison is lost. Where the analogy breaks: on a real mountain the choice of zero level never changes anything, while on a computer it decides whether the numbers fit.
Math
- Shift invariance: .
- , which is why the largest score can be pulled out.
- , and .
- , loss .
- , , and .
Code
import numpy as np
from scipy.special import logsumexp, log_softmax # SciPy: stable versions
z = np.array([1000.0, 1001.0, 1002.0])
logsumexp(z) # 1002.4076...
log_softmax(z) # [-2.4076, -1.4076, -0.4076]
np.logaddexp(0, z) # softplus, element-wise, stableIn PyTorch, F.cross_entropy(logits, target) and torch.logsumexp(z, dim) do the same thing on tensors. Pass raw logits to the loss, not probabilities.
More ways a computation goes wrong
These shorter topics round out the picture. All of them are conditions to watch for, not rules that always apply.
Masks and all-minus-infinity rows
Attention masks (P7.8) often set the blocked scores to , so that their softmax weight is exactly . This works while at least one score in the row is finite: with scores the result is . If every score in a row is , the shift gives and the row is NaN. Some code uses a large finite negative number such as instead of , which turns an all-blocked row into a uniform one, , silently. (In 16-bit numbers does not fit and becomes , so such code uses a smaller constant, for example .) Neither is “right”: the lesson is to know which one your code does.
Why scale the attention scores
Dot products of two random -dimensional vectors with unit-size entries have a spread of about . For the spread is about (checked by simulation). Scores that large make the softmax nearly one-hot. Dividing by brings the spread back to about (P7.4). One main reason is the shape of the softmax and its gradient, which P7.4 shows; smaller raw scores (before the maximum is subtracted) also stay inside the 16-bit range.
Relative error and conditioning
The error of a number is described two ways. The absolute error is . The relative error divides that by the true size, and floats keep a roughly constant relative error (about in 64-bit numbers, in 32-bit). The condition number of a calculation says how much a tiny relative error in the input is magnified in the output. For it is : at a relative change of in changes by about . For near it is , which is about at . A badly conditioned step cannot be rescued by any algorithm, but a stable algorithm does not add error on top. The opposite case shows the difference: is well conditioned near , yet the naive formula at is off by in relative size because rounding loses digits, and log1p is not. That error is the algorithm’s fault, not the problem’s.
Finding the first NaN
When a loss turns NaN, look for the first operation that produced a non-finite value, because everything after it is a consequence. Useful checks: np.isfinite(a).all() on the inputs, activations and gradients; printing the maximum and minimum of scores before an exponential; and in PyTorch, anomaly detection (set_detect_anomaly(True) in torch.autograd), which reports the operation that created a NaN in the backward pass (it is slow, so use it only to debug). Typical causes: , , a division by a sum that underflowed, a learning rate that is too large so the weights explode (P1.F3), and in a hand-written entropy (define it as ).
Previews: gradients, loss scaling, clipping
The same two failures appear in training in other clothes. Gradients that explode toward inf are tamed by gradient clipping, which rescales a gradient whose norm is too large (P4.16, P10.B7). In 16-bit training gradients can be so small that they underflow to ; loss scaling multiplies the loss by a constant before the backward pass and divides the gradients afterwards, and some parts of the calculation are commonly kept in 32-bit numbers (P10.B5). Both ideas serve the same aim as this lesson: keep every number inside the range of the format.
Go deeper Why 64-bit numbers do not make the problem go away
A bigger format only moves the limits. The 64-bit overflow point is , which is far above , yet a score of still passes it, and a product of probabilities of still underflows. Deep-learning work uses 32-bit and smaller formats for speed and memory (P1.G1), so the safe habit is to use the stable form by default, even when the unstable one happens to work in 64-bit numbers on today’s test data.
Go deeper Subnormal numbers, in short
Below the smallest normal number ( in 64-bit numbers) there are subnormal numbers that fill the gap down to with fewer and fewer accurate digits. They delay underflow to zero, so np.exp(-745) is still positive, but arithmetic on them can be slower on some hardware, and a result that is subnormal has only a few correct digits. Details of the bit layout are in P1.G1.
Quiz
Check your understanding
In 64-bit numbers, which is the main reason
np.exp(z) / np.exp(z).sum()returns NaN for ?All three exponentials are above the largest 64-bit number (about 1.8e308), so they are inf, the sum is inf, and each entry is inf / inf, which is NaN. The softmax is defined for any real scores, the gaps between the scores do not matter, and adding large numbers is not a problem for NumPy.
Scores and . Which statement about their softmax is correct?
Adding a constant to every score multiplies the numerator and denominator by the same factor e^1000, so the probabilities are identical. The softmax depends on the gaps (2 and 2 in both), not on the size of the scores, and the gaps do not change when a constant is added.
Why is the loss computed from logits as rather than as the log of the softmax output?
For scores (0, −800) the softmax gives (1, 0), and ln 0 is minus infinity, but the log-sum-exp minus the score of the true class is 800 for the second class. The two formulas are equal as maths; the log-of-softmax route loses accuracy on a computer. The value is the same, not smaller, and the softmax is differentiable.
For the scores , what is ?
The shifted scores are all 0, so the sum is 4 and LSE = 2 + ln 4 = 3.386, which is the largest score plus ln n, the upper bound of the range. Adding the scores gives 8, which is not the log of anything here, LSE is above the largest score when others are close to it, and 29.6 is the sum without the log.
A model gives a 1000-token text a probability of 0.1 per token. In 64-bit numbers, what happens to the product of the probabilities, and what is the fix?
The true product is 1e−1000, far below the smallest positive 64-bit number (about 5e−324), so it is stored as 0.0. The sum of the natural logs, 1000 · ln 0.1 = −2302.585, is an ordinary number. Products of numbers below 1 shrink and cannot overflow, no format holds every product, and 0.0 is not NaN.
You compute
np.log(1 + x)for and get exactly . Which function gives the right answer, about ?In 64-bit numbers 1 + 1e−16 rounds to exactly 1, so the information in x is lost before the log is applied. log1p works with x directly. 32-bit numbers are even coarser, exp is not a log, and log(x) at this x is about −36.8, which is a different quantity.
Exercises
- Compute the stable softmax of by hand.
Show answer
The largest score is and the shifted scores are , so both exponentials are , the sum is , and the result is . The naive formula would overflow, since is far above . - Compute by hand.
Show answer
The largest score is , the shifted scores are , the sum is , and . So . This lies between and . - For the scores , what are the log-softmax values, and what does “softmax first, then log” give?
Show answer
in 64-bit numbers, so the log-softmax is . The softmax gives because underflows, and its log is . - In 32-bit numbers, for which does overflow, and what does the naive softmax of give?
Show answer
It overflows above about (the log of ). fits and does not, so the naive result is . The stable softmax is . - A model multiplies probabilities of . What does a 64-bit float give, and what is the sum of logs?
Show answer
The true product is , below the smallest positive 64-bit number, so it is . The sum of the natural logs is . - Write the stable form of and use it for .
Show answer
computed withlog1p. At it is , whilenp.log(1 + np.exp(-40))gives . - A softmax row has every score equal to (a fully masked row). What does the stable formula return, and why?
Show answer
NaN. The maximum is and is NaN, so every shifted score is NaN. Code has to handle that case on purpose, for instance by checking for it or by using a large finite negative number, which gives a uniform row instead. - Code: use
np.isfiniteto find which entries ofnp.array([1.0, np.nan, np.inf, -np.inf])are usable.Show answer
np.isfinite(a)returns[True, False, False, False];np.isnan(a)is true only for the NaN. A comparison such asa == np.nandoes not work, because NaN is not equal to anything.