Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsNumerical Computing

Numerical stability

P1.G235 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Training a network means running the same few formulas billions of times. If one of them returns inf or NaN (not a number) even once, the loss becomes NaN and the run is wasted. Numerically stable versions of softmax, cross-entropy and sigmoid are what stop that from happening.

  • Softmax regression and every classifier with a softmax output turn scores into probabilities. Computing the loss from the scores (log-sum-exp) is what keeps a large score from producing NaN. (P3.A8: Softmax regression)
  • Cross-entropy is the standard classification loss, and software computes it from the raw scores (logits) with the stable formula of this lesson. (P1.E3: Cross-entropy)
  • Attention applies a softmax to many scores per token. Dividing the scores by a square root keeps them moderate, and implementations also subtract the largest score before the exponential. (P7.4: Scaled dot-product attention, coming soon)
  • In low-precision training the 16-bit range is small, so overflow, underflow and loss scaling are everyday concerns. (P10.B5: Mixed-precision training, coming soon)
  • Maximum likelihood multiplies the probabilities of every data point. Working with their logarithms keeps the product from underflowing to zero. (P1.D10: Maximum Likelihood Estimation)

Before this: Exponents and logarithms, The sigmoid, tanh and other squashing functions, How computers store numbers

After this lesson you can

  • Explain overflow, underflow, inf and NaN, and say why one NaN spreads through a whole calculation
  • Show that softmax does not change when the same number is added to every score, and use that to write a stable softmax
  • Compute log-sum-exp and log-softmax by hand and in code, and say why the loss is computed from logits
  • Choose the stable form for the sigmoid, log-sigmoid, softplus, log(1 + x) and exp(x) − 1, and say why products of probabilities are replaced by sums of logs
  • Name the usual signs of a numerical problem (inf, NaN, loss that jumps to NaN) and the first checks

A classifier outputs three scores for one image: 10001000, 10011001 and 10021002. The softmax (P3.A8) turns scores into probabilities, and by the formula the answer is (0.0900, 0.2447, 0.6652)(0.0900,\,0.2447,\,0.6652). Run the formula as it is written in a textbook and the computer answers (NaN,NaN,NaN)(\text{NaN},\text{NaN},\text{NaN}). 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 1.8×103081.8\times10^{308}. The smallest positive size it can keep is about 5×10−3245\times10^{-324}. Beyond the top it gives up and stores inf (infinity). Below the bottom it stores 00.

  • Overflow: the true result is too large, so the computer stores inf. In 64-bit numbers np.exp(709.78) still works and np.exp(709.79) gives inf, because ln⁡(1.8×10308)≈709.78\ln(1.8\times10^{308})\approx709.78. NumPy prints a RuntimeWarning: 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, 5×10−3245\times10^{-324}, and np.exp(-746) is exactly 0.00.0. No warning appears by default.

The exponential makes this easy to hit, because it grows so fast. The limits depend on the format.

FormatLargest numberexp⁡(x)\exp(x) overflows above
64-bit (fp64)1.8×103081.8\times10^{308}about 709.78709.78
32-bit (fp32)3.4×10383.4\times10^{38}about 88.7288.72
16-bit (fp16)6550465504about 11.0911.09

The smallest positive numbers are about 5×10−3245\times10^{-324} (64-bit), 1.4×10−451.4\times10^{-45} (32-bit) and 6×10−86\times10^{-8} (16-bit).

Scores of 10001000 are not realistic for a trained model’s final layer, but scores of 1212 or 9090 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 88.788.7 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.

  • ∞+1=∞\infty+1=\infty and 1/∞=01/\infty=0 are well defined.
  • ∞−∞\infty-\infty, ∞/∞\infty/\infty, 0/00/0 and 0⋅∞0\cdot\infty have no meaningful value. The result is NaN, “not a number”.
  • NaN poisons everything it touches: NaN+1\text{NaN}+1 is NaN, a sum containing a NaN is NaN, and a comparison with NaN is false. np.nan == np.nan is False; use np.isnan to 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 z=(z1,…,zn)\mathbf z=(z_1,\dots,z_n) is

softmax(z)i=ezi∑jezj.\mathrm{softmax}(\mathbf z)_i=\frac{\mathrm{e}^{z_i}}{\sum_{j}\mathrm{e}^{z_j}} .

The direct translation is e = np.exp(z); e / e.sum(). For z=(1,2,3)\mathbf z=(1,2,3) it works: (0.0900,0.2447,0.6652)(0.0900,0.2447,0.6652). Now take (1000,1001,1002)(1000,1001,1002). All three exponentials overflow to inf, the sum is inf, and every entry is ∞/∞=\infty/\infty= NaN.

The opposite problem appears for very negative scores. For (−1000,−1001,−1002)(-1000,-1001,-1002) every exponential underflows to 00, the sum is 00, and every entry is 0/0=0/0= NaN. Large scores break one end of the number range, very negative scores break the other.

The widget keeps the scores (1,2,3)(1,2,3) and adds one constant cc to all of them. This does not change the true probabilities. It does change what the computer can hold.

Shift the logits, watch the two softmax formulas

logit ze^znaivestable
12.7180.090030.09003
27.3890.24470.2447
320.090.66520.6652

The naive formula agrees with the stable one here: every exponential fits in the number format.

Naive: e^z divided by the sum of the e^z. Stable: subtract the largest logit (3) first, so the exponents are -2, -1, 0. Only the largest and smallest positive numbers of the format are modelled (largest here: 1.8e308); digits are not rounded. The stable column does not depend on c.

Logits 1, 2, 3 plus a constant c. The naive column is e^z divided by the sum of the e^z. The stable column subtracts the largest logit first. Choose a number format and slide c, or press a preset: c = 0 is fine in every format, c = 10 breaks the 16-bit format, c = 100 breaks 32-bit, c = 1000 and c = −1000 break all three. The stable column stays at 0.09003, 0.2447, 0.6652 throughout.

Things to try, all checked against the widget’s code:

  • 64-bit, c=0c=0. Naive and stable agree. Slide cc up: the naive column is fine up to c=706c=706 and turns bad at c=707c=707 (the largest score is then 710710, above 709.78709.78), and at c=1000c=1000 it is NaN.
  • 32-bit. The break is at c=86c=86: the exponential of 8989 is above 3.4×10383.4\times10^{38}.
  • 16-bit. The break is early. At c=8c=8 every exponential fits, but their sum, about 9000090000, is more than 6550465504, so the naive probabilities are all 00. At c=9c=9 they are (0,0,NaN)(0,0,\text{NaN}).
  • Negative cc. At c=−1000c=-1000 every format underflows to 0/00/0. In 16-bit numbers underflow starts at c=−19c=-19.

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 cc,

ezi+c∑jezj+c=ec eziec∑jezj=ezi∑jezj.\frac{\mathrm{e}^{z_i+c}}{\sum_j\mathrm{e}^{z_j+c}} =\frac{\mathrm{e}^{c}\,\mathrm{e}^{z_i}}{\mathrm{e}^{c}\sum_j\mathrm{e}^{z_j}} =\frac{\mathrm{e}^{z_i}}{\sum_j\mathrm{e}^{z_j}} .

The common factor ec\mathrm{e}^{c} cancels (it is the rule ea+b=eaeb\mathrm{e}^{a+b}=\mathrm{e}^{a}\mathrm{e}^{b} from P1.A2). So softmax(z)=softmax(z−c)\mathrm{softmax}(\mathbf z)=\mathrm{softmax}(\mathbf z-c) for every cc, and we are free to pick the cc that is best for the computer. The best choice is the largest score, c=m=max⁡jzjc=m=\max_j z_j:

  • The largest shifted score is exactly 00, so its exponential is exactly 11. Every other exponential is at most 11. No overflow.
  • The sum contains the term 11, so it is at least 11. No division by zero. The other terms may underflow to 00, which is harmless: they were negligible anyway.

For (1000,1001,1002)(1000,1001,1002) we have m=1002m=1002, the shifted scores are (−2,−1,0)(-2,-1,0), and

e−2=0.1353,e−1=0.3679,e0=1,sum=1.5032.\begin{aligned} \mathrm{e}^{-2}&=0.1353,\quad \mathrm{e}^{-1}=0.3679,\\ \mathrm{e}^{0}&=1,\quad\text{sum}=1.5032 . \end{aligned}

Dividing gives (0.0900, 0.2447, 0.6652)(0.0900,\,0.2447,\,0.6652), the same as for (1,2,3)(1,2,3), as it must be since the three scores differ by the same gaps.

Try it: the naive softmax breaks, the stable one does not

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 (80,90)(80, 90) and write z = np.array(z, dtype=np.float32): the naive softmax gives (0,NaN)(0,\text{NaN}) and the stable one gives (4.5×10−5, 0.99995)(4.5\times10^{-5},\,0.99995).

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 (1,2,3)(1,2,3) and (1000,1001,1002)(1000,1001,1002) both rows of the result are (0.0900,0.2447,0.6652)(0.0900,0.2447,0.6652). 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 z\mathbf z is

LSE(z)=ln⁡∑jezj.\mathrm{LSE}(\mathbf z)=\ln\sum_{j}\mathrm{e}^{z_j}.

Computed directly it overflows exactly like the softmax. The same shift fixes it. Write m=max⁡jzjm=\max_j z_j and factor em\mathrm{e}^{m} out of the sum:

ln⁡∑jezj=ln⁡(em∑jezj−m)=m+ln⁡∑jezj−m.\begin{aligned} \ln\sum_j\mathrm{e}^{z_j}&=\ln\Bigl(\mathrm{e}^{m}\sum_j\mathrm{e}^{z_j-m}\Bigr)\\ &=m+\ln\sum_j\mathrm{e}^{z_j-m}. \end{aligned}

That is the log-sum-exp trick: add the largest score back after taking the log of the shifted sum. For (1000,1001,1002)(1000,1001,1002) the shifted sum is 1.50321.5032, ln⁡1.5032=0.4076\ln1.5032=0.4076, and so LSE=1002+0.4076=1002.4076\mathrm{LSE}=1002+0.4076=1002.4076. Two checks: the value is at least the largest score, and it is at most m+ln⁡n=1002+ln⁡3=1003.0986m+\ln n=1002+\ln3=1003.0986. The general rule is

max⁡jzj  ≤  LSE(z)  ≤  max⁡jzj+ln⁡n.\max_j z_j\;\le\;\mathrm{LSE}(\mathbf z)\;\le\;\max_j z_j+\ln n .

The left side holds because the sum contains the term em\mathrm{e}^{m}. The right side holds because every term is at most em\mathrm{e}^{m} and there are nn of them. So LSE is a smooth maximum: close to the largest score when one score dominates, and ln⁡n\ln n above it when all scores are equal (LSE(0,0,0,0)=ln⁡4=1.3863\mathrm{LSE}(0,0,0,0)=\ln4=1.3863).

Log-softmax and the loss from logits

Take the logarithm of the softmax:

ln⁡softmax(z)i=zi−ln⁡∑jezj=zi−LSE(z).\begin{aligned} \ln\mathrm{softmax}(\mathbf z)_i&=z_i-\ln\sum_j\mathrm{e}^{z_j}\\ &=z_i-\mathrm{LSE}(\mathbf z). \end{aligned}

This is the log-softmax, and it needs no division and no exponential of anything large. For our scores it is (−2.4076,−1.4076,−0.4076)(-2.4076,-1.4076,-0.4076): each score minus 1002.40761002.4076. Applying the exponential to these gives back the probabilities.

The cross-entropy loss of the true class cc (P1.E3) is −ln⁡qc-\ln q_c, the negative log of the softmax probability. In terms of the scores:

L=−(zc−LSE(z))=LSE(z)−zc.L=-\bigl(z_c-\mathrm{LSE}(\mathbf z)\bigr)=\mathrm{LSE}(\mathbf z)-z_c .

For the true class 00 in our example, L=1002.4076−1000=2.4076L=1002.4076-1000=2.4076. P1.E3 found 0.40760.4076 for the scores (1,2,3)(1,2,3) when the third class is true. That is the same number as ln⁡1.5032\ln1.5032 here: in both cases the true class has the largest score, so its shifted score is 00 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 (0,−800)(0,-800). The softmax is (1,0)(1,0), since e−800\mathrm{e}^{-800} underflows to 00. Then ln⁡0=−∞\ln0=-\infty and the loss for class 11 is +∞+\infty. The log-softmax is (0,−800)(0,-800): 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.

Try it: log-sum-exp, log-softmax and the loss from logits

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 LSE(z)=ln⁡∑jezj\mathrm{LSE}(\mathbf z)=\ln\sum_j\mathrm{e}^{z_j} with respect to ziz_i. The chain rule (P1.C3) gives ezi∑jezj\frac{\mathrm{e}^{z_i}}{\sum_j\mathrm{e}^{z_j}}, which is exactly softmax(z)i\mathrm{softmax}(\mathbf z)_i. So ∇ LSE=softmax\nabla\,\mathrm{LSE}=\mathrm{softmax}, and the softmax is the gradient of the smooth maximum. It also explains the gradient of the loss L=LSE(z)−zcL=\mathrm{LSE}(\mathbf z)-z_c: it is softmax(z)−ec\mathrm{softmax}(\mathbf z)-\mathbf e_c, the predicted probabilities minus the one-hot target, the formula of P1.E3. A numerical check with scores (1,2,3)(1,2,3) gives (0.0900,0.2447,0.6652)(0.0900,0.2447,0.6652) for the slope of LSE\mathrm{LSE} 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 σ(z)=1/(1+e−z)\sigma(z)=1/(1+\mathrm{e}^{-z}) (P1.A5) has the same problem on one side. For z=−1000z=-1000, e−z=e1000\mathrm{e}^{-z}=\mathrm{e}^{1000} overflows. The result happens to come out as 1/∞=01/\infty=0, which is correct, but NumPy still prints an overflow warning, and in a longer calculation an intermediate ∞\infty can turn into a NaN or a wrong −∞-\infty (for example inside a logarithm). A stable version picks the form by the sign of zz:

σ(z)={11+e−zz≥0,ez1+ezz<0.\sigma(z)=\begin{cases} \dfrac{1}{1+\mathrm{e}^{-z}} & z\ge0,\\[2ex] \dfrac{\mathrm{e}^{z}}{1+\mathrm{e}^{z}} & z<0 . \end{cases}

The two forms are algebraically equal (multiply top and bottom of the first by ez\mathrm{e}^{z}). In each case the exponent is not positive, so the exponential is at most 11.

The sigmoid is a two-class softmax: σ(z)=softmax(z,0)1\sigma(z)=\mathrm{softmax}(z,0)_1. So the log-sum-exp of the pair (z,0)(z,0) gives the next function, the softplus:

softplus(x)=ln⁡(1+ex)=LSE(x,0).\begin{aligned} \mathrm{softplus}(x)&=\ln\bigl(1+\mathrm{e}^{x}\bigr)\\ &=\mathrm{LSE}(x,0). \end{aligned}

The shift trick with m=max⁡(x,0)m=\max(x,0) gives the stable form

softplus(x)=max⁡(x,0)+ln⁡(1+e−∣x∣).\begin{aligned} \mathrm{softplus}(x)&=\max(x,0)\\ &\quad+\ln\bigl(1+\mathrm{e}^{-|x|}\bigr). \end{aligned}

The naive ln⁡(1+ex)\ln(1+\mathrm{e}^{x}) gives ∞\infty at x=1000x=1000 and the stable form gives 10001000. At the other end, x=−40x=-40: e−40=4.2×10−18\mathrm{e}^{-40}=4.2\times10^{-18} is so small that 1+e−401+\mathrm{e}^{-40} rounds to exactly 11, and the naive result is 00, while the true value is 4.25×10−184.25\times10^{-18}. The fix for this is the next idea: use log1p.

The log-sigmoid is ln⁡σ(z)=−softplus(−z)\ln\sigma(z)=-\mathrm{softplus}(-z). This is what the binary cross-entropy needs (P3.A7). For z=−1000z=-1000 the naive ln⁡(σ(z))=ln⁡0=−∞\ln(\sigma(z))=\ln0=-\infty, while −softplus(1000)=−1000-\mathrm{softplus}(1000)=-1000. A frequent mistake is “fixing” the ln⁡0\ln0 by adding a tiny constant such as 10−810^{-8} to the probability. That removes the infinity but also hides the truth: the loss is capped near 18.418.4 (=−ln⁡10−8=-\ln10^{-8}) instead of 10001000, 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 11 a float has gaps of about 2.2×10−162.2\times10^{-16} in 64-bit numbers (and 1.2×10−71.2\times10^{-7} in 32-bit, P1.G1). So 1+10−161+10^{-16} rounds to exactly 11, and all the information in the small number is lost before the log is taken.

  • ln⁡(1+10−10)\ln(1+10^{-10}) computed as np.log(1 + 1e-10) gives 1.00000008269×10−101.00000008269\times10^{-10}. The true value is 9.9999999995×10−119.9999999995\times10^{-11}, so only about 7 digits are right.
  • At x=10−16x=10^{-16} it gives exactly 00, while the answer is 10−1610^{-16}.

np.log1p(x) computes ln⁡(1+x)\ln(1+x) without ever forming 1+x1+x, so it stays accurate for small xx. In the same way np.expm1(x) computes ex−1\mathrm{e}^{x}-1 accurately for small xx, where np.exp(x) - 1 suffers the same loss. (Use the plain forms when xx 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 E[x2]−E[x]2\mathrm{E}[x^2]-\mathrm{E}[x]^2 (P1.D4) for values such as 108+1, 108+2, 108+310^{8}+1,\,10^{8}+2,\,10^{8}+3: the true variance is 0.6670.667, and the formula gives 0.00.0 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 zz and a label y∈{0,1}y\in\{0,1\}, the loss is max⁡(z,0)−zy+ln⁡(1+e−∣z∣)\max(z,0)-zy+\ln(1+\mathrm{e}^{-|z|}). This is the form frameworks use. For z=−1000z=-1000 and y=1y=1 it gives 10001000, and a sigmoid followed by a log gives infinity. For z=3z=3, y=1y=1 it gives 0.04860.0486, the same as −ln⁡σ(3)-\ln\sigma(3).

Try it: log1p, expm1, softplus and a product that underflows

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 11 (P1.D10, P1.E1). Multiply 10001000 factors of 0.50.5 and the answer is 9.3×10−3029.3\times10^{-302}, which still fits. The smallest positive size is about 5×10−3245\times10^{-324}, and 0.510740.5^{1074} is that size. At 11001100 factors the product is exactly 0.00.0. Factors of 0.10.1 reach 0.00.0 at 324324 of them. A model that scores a text of a thousand tokens with probability 0.10.1 each, as in P1.E1, has a true probability of 10−100010^{-1000}, which no 64-bit float can hold.

The log of a product is the sum of the logs (P1.A2): ln⁡∏ipi=∑iln⁡pi\ln\prod_i p_i=\sum_i\ln p_i. For 11001100 halves the sum is −762.46-762.46, an ordinary number, and for 10001000 factors of 0.10.1 it is −2302.585-2302.585. 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 ln⁡(p1+p2)\ln(p_1+p_2) for a mixture or a sum over hidden states, the log-sum-exp trick is the tool: ln⁡(ea+eb)=LSE(a,b)\ln(\mathrm{e}^{a}+\mathrm{e}^{b})=\mathrm{LSE}(a,b) with a,ba,b 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 00 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: softmax(z+c1)=softmax(z)\mathrm{softmax}(\mathbf z+c\mathbf 1)=\mathrm{softmax}(\mathbf z).
  • LSE(z+c1)=LSE(z)+c\mathrm{LSE}(\mathbf z+c\mathbf 1)=\mathrm{LSE}(\mathbf z)+c, which is why the largest score can be pulled out.
  • max⁡jzj≤LSE(z)≤max⁡jzj+ln⁡n\max_j z_j\le\mathrm{LSE}(\mathbf z)\le\max_j z_j+\ln n, and ∇LSE=softmax\nabla\mathrm{LSE}=\mathrm{softmax}.
  • ln⁡softmax(z)=z−LSE(z)\ln\mathrm{softmax}(\mathbf z)=\mathbf z-\mathrm{LSE}(\mathbf z), loss =LSE(z)−zc=\mathrm{LSE}(\mathbf z)-z_c.
  • softplus(x)=LSE(x,0)\mathrm{softplus}(x)=\mathrm{LSE}(x,0), ln⁡σ(z)=−softplus(−z)\ln\sigma(z)=-\mathrm{softplus}(-z), and σ(z)=softmax(z,0)1\sigma(z)=\mathrm{softmax}(z,0)_1.

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, stable

In 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 −∞-\infty, so that their softmax weight is exactly 00. This works while at least one score in the row is finite: with scores (1,−∞,−∞)(1,-\infty,-\infty) the result is (1,0,0)(1,0,0). If every score in a row is −∞-\infty, the shift gives −∞−(−∞)=NaN-\infty-(-\infty)=\text{NaN} and the row is NaN. Some code uses a large finite negative number such as −109-10^{9} instead of −∞-\infty, which turns an all-blocked row into a uniform one, (13,13,13)(\tfrac13,\tfrac13,\tfrac13), silently. (In 16-bit numbers −109-10^{9} does not fit and becomes −∞-\infty, so such code uses a smaller constant, for example −104-10^{4}.) Neither is “right”: the lesson is to know which one your code does.

Why scale the attention scores

Dot products of two random dd-dimensional vectors with unit-size entries have a spread of about d\sqrt d. For d=64d=64 the spread is about 88 (checked by simulation). Scores that large make the softmax nearly one-hot. Dividing by d\sqrt d brings the spread back to about 11 (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 ∣computed−true∣\lvert\text{computed}-\text{true}\rvert. The relative error divides that by the true size, and floats keep a roughly constant relative error (about 10−1610^{-16} in 64-bit numbers, 10−710^{-7} 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 ex\mathrm{e}^{x} it is ∣x∣\lvert x\rvert: at x=100x=100 a relative change of 10−1010^{-10} in xx changes ex\mathrm{e}^{x} by about 10−810^{-8}. For ln⁡x\ln x near 11 it is 1/∣ln⁡x∣1/\lvert\ln x\rvert, which is about 10710^{7} at x=1.0000001x=1.0000001. 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: ln⁡(1+x)\ln(1+x) is well conditioned near 00, yet the naive formula at x=10−10x=10^{-10} is off by 8×10−88\times10^{-8} in relative size because rounding 1+x1+x 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: elarge\mathrm{e}^{\text{large}}, ln⁡0\ln0, a division by a sum that underflowed, a learning rate that is too large so the weights explode (P1.F3), and 0⋅ln⁡00\cdot\ln0 in a hand-written entropy (define it as 00).

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 00; 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 709.78709.78, which is far above 88.7288.72, yet a score of 10001000 still passes it, and a product of 11001100 probabilities of 0.50.5 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 (2.2×10−3082.2\times10^{-308} in 64-bit numbers) there are subnormal numbers that fill the gap down to 5×10−3245\times10^{-324} 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

  1. In 64-bit numbers, which is the main reason np.exp(z) / np.exp(z).sum() returns NaN for z=(1000,1001,1002)\mathbf z=(1000,1001,1002)?

  2. Scores (5,3,1)(5,3,1) and (1005,1003,1001)(1005,1003,1001). Which statement about their softmax is correct?

  3. Why is the loss computed from logits as LSE(z)−zc\mathrm{LSE}(\mathbf z)-z_c rather than as the log of the softmax output?

  4. For the scores (2,2,2,2)(2,2,2,2), what is LSE\mathrm{LSE}?

  5. 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?

  6. You compute np.log(1 + x) for x=10−16x=10^{-16} and get exactly 00. Which function gives the right answer, about 10−1610^{-16}?

Exercises

  1. Compute the stable softmax of (2000,2000)(2000,2000) by hand.
    Show answerThe largest score is 20002000 and the shifted scores are (0,0)(0,0), so both exponentials are 11, the sum is 22, and the result is (0.5,0.5)(0.5,0.5). The naive formula would overflow, since e2000\mathrm{e}^{2000} is far above 1.8×103081.8\times10^{308}.
  2. Compute LSE(−5,−6)\mathrm{LSE}(-5,-6) by hand.
    Show answerThe largest score is −5-5, the shifted scores are (0,−1)(0,-1), the sum is 1+e−1=1.36791+\mathrm{e}^{-1}=1.3679, and ln⁡1.3679=0.3133\ln1.3679=0.3133. So LSE=−5+0.3133=−4.6867\mathrm{LSE}=-5+0.3133=-4.6867. This lies between m=−5m=-5 and m+ln⁡2=−4.307m+\ln2=-4.307.
  3. For the scores (0,−800)(0,-800), what are the log-softmax values, and what does “softmax first, then log” give?
    Show answerLSE=0+ln⁡(1+e−800)=0\mathrm{LSE}=0+\ln(1+\mathrm{e}^{-800})=0 in 64-bit numbers, so the log-softmax is (0,−800)(0,-800). The softmax gives (1,0)(1,0) because e−800\mathrm{e}^{-800} underflows, and its log is (0,−∞)(0,-\infty).
  4. In 32-bit numbers, for which zz does ez\mathrm{e}^{z} overflow, and what does the naive softmax of (80,90)(80,90) give?
    Show answerIt overflows above about 88.7288.72 (the log of 3.4×10383.4\times10^{38}). e80=5.5×1034\mathrm{e}^{80}=5.5\times10^{34} fits and e90\mathrm{e}^{90} does not, so the naive result is (0,NaN)(0,\text{NaN}). The stable softmax is (4.5×10−5,0.99995)(4.5\times10^{-5},0.99995).
  5. A model multiplies 200200 probabilities of 0.010.01. What does a 64-bit float give, and what is the sum of logs?
    Show answerThe true product is 10−40010^{-400}, below the smallest positive 64-bit number, so it is 0.00.0. The sum of the natural logs is 200ln⁡0.01=−921.03200\ln0.01=-921.03.
  6. Write the stable form of ln⁡(1+ex)\ln(1+\mathrm{e}^{x}) and use it for x=−40x=-40.
    Show answermax⁡(x,0)+ln⁡(1+e−∣x∣)\max(x,0)+\ln(1+\mathrm{e}^{-|x|}) computed with log1p. At x=−40x=-40 it is 0+log1p(e−40)=4.25×10−180+\mathrm{log1p}(\mathrm{e}^{-40})=4.25\times10^{-18}, while np.log(1 + np.exp(-40)) gives 00.
  7. A softmax row has every score equal to −∞-\infty (a fully masked row). What does the stable formula return, and why?
    Show answerNaN. The maximum is −∞-\infty and −∞−(−∞)-\infty-(-\infty) 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.
  8. Code: use np.isfinite to find which entries of np.array([1.0, np.nan, np.inf, -np.inf]) are usable.
    Show answernp.isfinite(a) returns [True, False, False, False]; np.isnan(a) is true only for the NaN. A comparison such as a == np.nan does not work, because NaN is not equal to anything.

Key takeaways

  • A float has a largest and a smallest size. In 64-bit numbers, exp(x) overflows to inf above about 709.78 and underflows to 0 below about −745. In 32-bit numbers the overflow limit is about 88.72, and in 16-bit numbers about 11.09 (P1.G1).
  • inf − inf and inf / inf are NaN, and 0 / 0 is NaN. A NaN stays NaN through every later calculation and compares unequal to everything, itself included. The naive softmax of (1000, 1001, 1002) is (NaN, NaN, NaN); so is the naive softmax of (−1000, −1001, −1002).
  • Softmax does not change if every score gets the same constant added, so subtract the largest score first. The largest exponent becomes 0, every exponential is at most 1, and the sum is at least 1: no overflow, and no division by zero. The result for (1000, 1001, 1002) is (0.0900, 0.2447, 0.6652), the same as for (1, 2, 3).
  • Log-sum-exp: LSE(z) = m + ln Σ exp(z − m) with m the largest score. It lies between m and m + ln n, and the log-softmax is z − LSE(z). The cross-entropy loss of the true class c is LSE(z) minus the score of class c, computed from logits and never from a softmax followed by a log.
  • Rewrite instead of clipping: softplus(x) = max(x, 0) + log1p(exp(−|x|)), a sigmoid that picks the form by the sign of z, log1p(x) and expm1(x) for small x, and log-probabilities in place of products of probabilities (1100 factors of 0.5 give exactly 0.0, their logs sum to −762.46).
  • When a run shows NaN or inf, look for the first operation that produced it: exp of a large number, log of 0, a division by 0 or by a sum that underflowed. Mixed-precision training adds loss scaling and gradient clipping for the same family of problems (P4.16, P10.B5).
Found a mistake? Tell us