Overflow, Underflow and a Stable Softmax
The softmax looks harmless, but overflows and underflows in any float format. Large logits are normal in practice (attention scores, confident classifiers), so every framework computes the softmax, the log-softmax and the cross-entropy with a few algebraic tricks. They are short, and worth knowing by heart.
The max-subtraction trick
The softmax does not change if the same constant is subtracted from every logit:
Choosing makes the largest exponent : nothing overflows, and the denominator is at least 1, so nothing divides by zero.
import numpy as np
def softmax_naive(z): e = np.exp(z); return e / e.sum()
def softmax(z): e = np.exp(z - z.max()); return e / e.sum()
z = np.array([1000.0, 999.0, 990.0])
with np.errstate(over="ignore", invalid="ignore"):
print("naive:", softmax_naive(z))
print("stable:", np.round(softmax(z), 6))
print("same as small logits:", np.allclose(softmax(z), softmax(z - 1000)))naive: [nan nan nan]
stable: [7.31034e-01 2.68932e-01 3.30000e-05]
same as small logits: True
Log-sum-exp and log-softmax
Cross-entropy needs . Computing the softmax first and then the log fails when a probability underflows to 0 (). The log-sum-exp with the same shift is stable:
import numpy as np
def lse(z): m = z.max(); return m + np.log(np.sum(np.exp(z - m)))
z = np.array([50.0, -800.0, 10.0]) # the true class 1 has a hugely negative logit
y = 1
with np.errstate(divide="ignore", under="ignore"):
p = np.exp(z - z.max()); p /= p.sum()
print("probability of the true class:", p[y], " -> log:", np.log(p[y]))
print("stable cross-entropy:", lse(z) - z[y])probability of the true class: 0.0 -> log: -inf
stable cross-entropy: 850.0
The stable version returns the exact, finite loss of 850 nats, and its gradient is still meaningful. This is why frameworks provide cross_entropy(logits, target) taking logits, not probabilities.
Sigmoid and binary cross-entropy
The same issue arises with one logit. , and is the softplus, computed stably as . The binary cross-entropy with logits is then
Other places where numbers blow up
expin attention scores: the same max trick inside the attention softmax; FlashAttention keeps a running maximum while processing blocks.- Products of many probabilities: work with sums of logs (Perplexity).
sqrtof a variance in normalization layers: add a small (e.g. ) to avoid dividing by 0.logof a probability that may be 0: clip with a tiny , or better, avoid forming the probability.
In software
torch.logsumexp,torch.log_softmax,nn.CrossEntropyLoss(logits in),nn.BCEWithLogitsLoss(stable binary cross-entropy).scipy.special.logsumexp,softmaxandlog_softmaxdo the same in NumPy land.- The online-softmax trick (updating the maximum and the sum as new scores arrive) makes memory-efficient attention possible.
Exercises
Exercise 1: Shift invariance
Compute and by hand (to 3 decimals).
Answer
Both are .
Solution
, sum ; dividing gives . The second vector differs by the constant 100, which cancels.
Exercise 2: Log-sum-exp bounds
Show that for logits.
Answer
The sum is between 1 and .
Solution
With , the term for the maximum is and every term is at most 1, so . Taking logs and adding gives the bounds. LSE is a "smooth maximum".
Exercise 3: Stable binary cross-entropy (code)
Compute for and , and compare with the naive in float32.
Answer
The stable loss is 40; the naive one is also about 40 here but becomes inf for in float32.
Solution
import numpy as np
def softplus(u): return np.maximum(u, 0) + np.log1p(np.exp(-np.abs(u)))
for z in (np.float32(-40), np.float32(-120)):
with np.errstate(over="ignore", divide="ignore"):
naive = -np.log(np.float32(1) / (np.float32(1) + np.exp(-z)))
print(float(z), "stable:", float(softplus(z) - 1 * z), " naive:", float(naive))-40.0 stable: 40.0 naive: 40.0
-120.0 stable: 120.0 naive: inf
Test yourself
Why subtract before exponentiating in a softmax?
- It changes the probabilities to be more accurate
- It prevents overflow without changing the result
- It makes the logits positive
- It is required for the gradient
Why do frameworks' cross-entropy functions take logits instead of probabilities?
- Probabilities are not allowed in Python
- So they can use log-sum-exp and avoid
- Logits are smaller
- It is faster to type
is always between…
- 0 and 1
- and
- and
- and 1