Numerical Stability
Numerical stability is the difference between code that is correct on paper and code that is correct on every
input. Floats have a limited range and limited precision, so exp overflows, log(0) is -inf, and 0 / 0 is
NaN. ML code hits all three, because softmax, sigmoid and cross-entropy are built from exp and log.
Interviewers test it directly. One Anthropic phone screen had the candidate implement an attention variant from a paper figure and then write tests, and what the interviewer wanted was overflow tests (the question); Nuro asked for softmax "with numerical stability" before its gradient (the question). This page covers the failures and the standard fix for each.
Where Floats Break
exp overflows to inf once its input passes the log of the largest float, and that limit is small. It is
about 709.8 in float64, 88.7 in float32 and only 11.1 in float16, where the largest value is 65,504. At the other
end, exp of a large negative number underflows to exactly 0, and adding a tiny number to a large one does
nothing at all.
import numpy as np
with np.errstate(over="ignore"):
assert np.isinf(np.exp(710.0)) # float64 overflows above ~709.8
assert np.isinf(np.exp(np.float32(89.0))) # float32 above ~88.7
assert np.isinf(np.exp(np.float16(12.0))) # float16 above ~11.1
assert np.exp(-746.0) == 0.0 # underflow: exactly zero
assert 1.0 + 1e-17 == 1.0 # below float64's resolution near 1
assert np.finfo(np.float16).max == 65504
Once an inf appears, NaN follows quickly: inf - inf, inf / inf and 0 * inf are all NaN, and a NaN
spreads through every operation after it. That is why a single overflow in a softmax turns a whole batch's loss
into NaN and stops training. The fixes below all follow one idea: rearrange the formula so exp never sees a
large positive number, and never take log of something that may have rounded to 0.
Log-Sum-Exp
log(sum(exp(z))) appears in softmax, cross-entropy and every log-likelihood with a normalizer, and computed
directly it overflows for large z and underflows to log(0) for very negative z. The fix is to factor out the
maximum m: log(sum(exp(z))) = m + log(sum(exp(z - m))). Now the largest exponent is exp(0) = 1, so the sum
is between 1 and n and its log is always safe.
def logsumexp(z: np.ndarray) -> np.ndarray: # over the last axis: (..., n) -> (...)
m = z.max(axis=-1, keepdims=True)
m = np.where(np.isfinite(m), m, 0.0) # an all -inf row: avoid -inf - (-inf)
with np.errstate(divide="ignore"): # log(0) = -inf is the right answer there
return (m + np.log(np.exp(z - m).sum(axis=-1, keepdims=True)))[..., 0]
z = np.array([[1000.0, 1000.0], [-1000.0, -1000.0], [1.0, 2.0]])
with np.errstate(over="ignore", divide="ignore"):
naive = np.log(np.exp(z).sum(axis=-1)) # [inf, -inf, 2.31]
assert np.isinf(naive[:2]).all()
assert np.allclose(logsumexp(z), [1000 + np.log(2), -1000 + np.log(2), np.log(np.e + np.e ** 2)])
assert logsumexp(np.full((1, 3), -np.inf))[0] == -np.inf # fully masked row: -inf, not NaN
The guard for a row that is all -inf matters in attention, where a fully masked row is normal; without it,
-inf - (-inf) produces NaN. scipy.special.logsumexp and torch.logsumexp do the same thing, and saying so is
fine, but expect to write it yourself.
Stable Softmax and Log-Softmax
Softmax is shift-invariant, softmax(z) = softmax(z - c) for any constant c, so subtracting the row max
changes nothing mathematically and keeps every exponent at or below 0. For a loss, though, you want the log of
the softmax, and taking log of a probability that underflowed to 0 gives -inf. Compute log_softmax directly
instead: z - logsumexp(z).
def softmax(z: np.ndarray) -> np.ndarray: # (..., C)
e = np.exp(z - z.max(axis=-1, keepdims=True)) # largest entry is exp(0) = 1
return e / e.sum(axis=-1, keepdims=True)
def log_softmax(z: np.ndarray) -> np.ndarray: # (..., C)
s = z - z.max(axis=-1, keepdims=True)
return s - np.log(np.exp(s).sum(axis=-1, keepdims=True))
z = np.array([[0.0, 800.0]])
assert np.allclose(softmax(z), [[0.0, 1.0]]) # the 0 is exp(-800), underflowed
with np.errstate(divide="ignore"):
assert np.isinf(np.log(softmax(z))[0, 0]) # log of an underflowed 0: -inf
assert np.isclose(log_softmax(z)[0, 0], -800.0) # exact
If the true class is the first one, the naive loss is inf and the log-softmax loss is the correct 800. That is
why PyTorch's F.cross_entropy takes logits, not probabilities: it computes log-softmax internally. The same
reasoning covers the gradient. The combined gradient of softmax plus cross-entropy is softmax(z) - onehot(y),
which is bounded and never touches a log; see Softmax and Cross-Entropy.
Stable Sigmoid and Losses from Logits
The sigmoid 1 / (1 + exp(-z)) overflows exp for large negative z. Its value still comes out as 0, but with
an overflow warning, and the binary cross-entropy that follows takes log(0). Compute exp(-|z|), which never
overflows, and pick the form that suits the sign of z. For the loss, skip the probability altogether: binary
cross-entropy from a logit is log(1 + exp(z)) - y z, and np.logaddexp(0, z) computes that first term stably.
def sigmoid(z: np.ndarray) -> np.ndarray:
e = np.exp(-np.abs(z)) # exponent <= 0: never overflows
return np.where(z >= 0, 1 / (1 + e), e / (1 + e))
def bce_with_logits(z: np.ndarray, y: np.ndarray) -> float:
return float(np.mean(np.logaddexp(0.0, z) - y * z)) # log(1 + e^z) - y z
z, y = np.array([-1000.0, 0.0, 1000.0]), np.array([1.0, 1.0, 0.0])
assert np.allclose(sigmoid(z), [0.0, 0.5, 1.0])
with np.errstate(over="ignore", divide="ignore"):
p = 1 / (1 + np.exp(-z)) # overflow warning at z = -1000
naive = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
assert np.isinf(naive)
assert np.isclose(bce_with_logits(z, y), (2000 + np.log(2)) / 3) # about 666.9
Two wrong predictions made with full confidence should cost a lot, and the logit form says exactly how much:
about 666.9 on average here, against the naive inf. Writing np.where(z >= 0, 1 / (1 + np.exp(-z)), ...)
directly is a common half-fix: np.where evaluates both branches on every element, so the overflow still happens.
Compute the safe exponent first, as above. Logistic Regression uses both
functions.
Epsilons
An epsilon is a small constant added to keep a denominator or a log argument away from zero, and it needs to
be placed and sized deliberately. Put it where the zero can actually occur: under a square root of a variance,
in a division by a standard deviation, inside log only when you can't work in logits. A missing epsilon in a
normalized advantage, (r - mean) / std, was one of the planted bugs in an Anthropic research engineer round
that asked candidates to debug a GRPO trainer producing NaNs
(the question). A group whose rewards are all equal has a standard
deviation of 0:
r = np.array([1.0, 1.0, 1.0, 1.0]) # every sample got the same reward
with np.errstate(invalid="ignore"):
assert np.isnan((r - r.mean()) / r.std()).all() # 0 / 0
assert ((r - r.mean()) / (r.std() + 1e-8) == 0).all() # zero advantage: no update, which is right
p = np.float32(1.0) - np.float32(1e-8) # "clip p to 1 - eps" in float32
assert p == np.float32(1.0) # the clip did nothing
assert np.finfo(np.float32).eps > 1e-8 # float32 resolution near 1 is ~1.19e-7
The second half is the sizing rule. An epsilon has to be larger than the dtype's resolution at the value it
protects, so 1 - 1e-8 is just 1 in float32, and log(1 - p) is still log(0). Use about 1e-7 for float32
near 1 and 1e-3 or more in float16, or avoid the problem by working in logits. Also remember that clipping
zeroes the gradient wherever it is active, which is another reason to prefer the logit forms.
Low Precision: float16 and bfloat16
Mixed-precision training stores activations and does matrix products in 16-bit floats, and the two 16-bit
formats fail differently. float16 has 10 mantissa bits but a tiny range: anything above 65,504 is inf, and
gradients below about 6e-8 round to 0. bfloat16 keeps float32's range, so it rarely overflows, but with 7
mantissa bits it has only two to three significant digits.
import torch
x = torch.tensor([60000.0, 70000.0])
assert torch.isinf(x.half()[1]) # float16: above 65504 overflows
assert torch.isfinite(x.bfloat16()).all() # bfloat16: float32's range
assert torch.tensor(1e-8).half() == 0 # small gradients underflow in float16
big = torch.tensor(256.0, dtype=torch.bfloat16)
assert big + 1 == big # bfloat16: 256 + 1 rounds back to 256
s = torch.tensor(0.0, dtype=torch.float16)
for _ in range(10000):
s = s + 0.1 # a running sum kept in float16
assert s == 256 # stalls: 0.1 is below half the spacing
The running sum stalls at 256 instead of reaching 1,000, because from there on the gap between float16 numbers is
0.25 and adding 0.1 rounds back to the same value. Three practices follow. Accumulate sums, means and variances
in float32 (PyTorch's reductions already do; a hand-written loop doesn't). Keep softmax, normalization and the
loss in float32 under autocast. And with float16, scale the loss before backward so small gradients don't
underflow, which is what torch.amp.GradScaler does; bfloat16 usually doesn't need it.
Key Takeaways
expoverflows above about 709.8 in float64, 88.7 in float32 and 11.1 in float16. OneinfbecomesNaNeverywhere.- Subtract the max before
exp: log-sum-exp, softmax and log-softmax all use it. Guard rows that are all-inf. - Compute losses from logits:
log_softmaxfor cross-entropy,logaddexp(0, z) - y zfor binary cross-entropy. - A stable sigmoid computes
exp(-|z|)first;np.wherealone evaluates both branches. - Add epsilons where a zero can occur (standard deviations, variances) and size them above the dtype's
resolution:
1e-8vanishes next to 1 in float32. - float16 overflows and underflows; bfloat16 loses precision. Accumulate in float32 and scale float16 losses.