If you've ever trained a classifier and watched the loss turn into nan for no obvious reason, there's a good chance softmax was involved. It's one of those functions that looks harmless on paper and causes trouble in floating point.
The fix is a small idea called the log-sum-exp trick. Once you understand it, you'll see it everywhere: in PyTorch's cross_entropy, in attention layers, in language-model sampling, and in almost every "implement softmax" interview question.
Let's build it step by step and test each piece.
Softmax in one sentence
Softmax turns a vector of raw scores (logits) into a probability distribution. Every output is positive and they add up to 1:
softmax(z)ᵢ = e^(zᵢ) / Σⱼ e^(zⱼ)
The direct translation into NumPy:
import numpy as np
def softmax_naive(z):
e = np.exp(z)
return e / e.sum()Try it on small logits and it's fine. Now try it on large ones:
print(softmax_naive(np.array([1000.0, 1001.0, 1002.0])))
# RuntimeWarning: overflow encountered in exp
# RuntimeWarning: invalid value encountered in divide
# [nan nan nan]np.exp(1000) is inf. Then inf / inf is nan. And once one nan enters your loss, every weight it touches becomes nan on the next update. Training is over.
You might think "my logits are never 1000". Early in training, with a bad initialisation or a high learning rate, they can get there quickly. With float16 the danger zone starts at roughly 11, because exp(11.1) already passes float16's maximum of about 65,504.
The trick: shift before you exponentiate
Softmax doesn't change if you subtract the same constant from every logit:
e^(zᵢ − c) / Σⱼ e^(zⱼ − c) = e^(zᵢ) / Σⱼ e^(zⱼ)
The e^(−c) factor appears on the top and the bottom and cancels. So pick c = max(z). After the shift, the largest logit is exactly 0, every exponent is ≤ 0, and exp returns values between 0 and 1. Overflow becomes impossible.
def softmax(z, axis=-1):
z = np.asarray(z, dtype=np.float64)
shifted = z - z.max(axis=axis, keepdims=True)
e = np.exp(shifted)
return e / e.sum(axis=axis, keepdims=True)
print(softmax([1000.0, 1001.0, 1002.0]))
# [0.09003057 0.24472847 0.66524096]
print(softmax([1.0, 2.0, 3.0]))
# [0.09003057 0.24472847 0.66524096]Same answer for both inputs, which is the invariance in action, and no warnings.
Two details that trip people up:
axis=-1withkeepdims=True. For a batch of shape(batch, classes), you want the max and sum per row.keepdims=Truekeeps the result shaped(batch, 1)so it broadcasts back correctly. Leave it out and you get a shape error, or worse, a silent wrong answer.- Underflow is fine. Very negative shifted logits become
exp(-800) = 0.0. That's correct: those classes have essentially zero probability. The denominator is always at least 1 (from the max element), so you never divide by zero.
From softmax to log-sum-exp
For training, we rarely need the probabilities themselves. We need log-probabilities, because cross-entropy loss is -log p(correct class).
The tempting approach is np.log(softmax(z)). Don't. If a probability underflows to 0, log(0) is -inf, and you're back to nan gradients.
Instead, work in log space from the start:
log softmax(z)ᵢ = zᵢ − log Σⱼ e^(zⱼ)
That second term is the log-sum-exp, and we compute it with the same shift:
logsumexp(z) = m + log Σⱼ e^(zⱼ − m), where m = max(z)
def logsumexp(z, axis=-1):
z = np.asarray(z, dtype=np.float64)
m = z.max(axis=axis, keepdims=True)
return (m + np.log(np.exp(z - m).sum(axis=axis, keepdims=True))).squeeze(axis)A cross-entropy that can't blow up
Now cross-entropy for a batch is short and stable:
def cross_entropy(logits, labels):
logits = np.asarray(logits, dtype=np.float64)
log_probs = logits - logsumexp(logits, axis=1)[:, None]
return -log_probs[np.arange(len(labels)), labels].mean()
logits = np.array([[2.0, 1.0, 0.1],
[0.5, 2.5, 0.3]])
labels = np.array([0, 1])
print(cross_entropy(logits, labels)) # 0.31853976964918584Sanity-check it against the naive computation on these well-behaved numbers:
p = softmax(logits)
print(-np.log(p[np.arange(2), labels]).mean()) # 0.3185397696491857They match (to the last floating-point digit). Now the case that breaks the naive version:
print(cross_entropy(np.array([[1000.0, 0.0]]), np.array([1]))) # 1000.0The model is extremely confident in the wrong class, so the loss should be huge, and 1000 is exactly right. The naive path gives inf here.
Why
np.arange(len(labels)), labels? That's fancy indexing: "from row 0 take columnlabels[0], from row 1 take columnlabels[1]", and so on. It picks out each example's log-probability for its correct class in one vectorised step.
Bonus: the gradient is beautifully simple
When softmax and cross-entropy are combined, the gradient with respect to the logits comes out as:
∂L/∂z = softmax(z) − one_hot(y)
averaged over the batch. No division by tiny probabilities, nothing to blow up:
grad = softmax(logits)
grad[np.arange(2), labels] -= 1
grad /= 2 # batch size
print(grad)
# [[-0.17049943 0.12121649 0.04928295]
# [ 0.05430187 -0.09876047 0.04445861]]This is why frameworks fuse the two. PyTorch's nn.CrossEntropyLoss takes raw logits, not probabilities. Passing softmax outputs into it is a classic bug: you apply softmax twice, and the model trains slowly or not at all.
Where else you'll meet log-sum-exp
- Attention. Every attention layer runs a softmax over scores, and efficient kernels like FlashAttention keep a running max for exactly this reason.
- Language-model sampling. Temperature scaling divides logits before softmax, and low temperatures make the values large quickly.
- Probabilistic models. Mixture models and HMMs add up probabilities in log space with
logsumexpall the time. - Sigmoid. It's the two-class special case of softmax, and its stable form uses the same idea. See our sigmoid deep dive.
Key takeaways
- Subtracting the max doesn't change softmax and makes overflow impossible.
- Never call
log(softmax(x)). Compute log-probabilities directly with log-sum-exp. - Fused softmax + cross-entropy has the gradient
p − y. Feed frameworks raw logits. - Always reduce over the class axis with
keepdims=Truewhen working with batches.
Then test yourself on Stable Masked Softmax, which adds a twist: some positions are masked out and must get exactly zero probability. If you can explain why the max shift works, you're ready for the interview version of the question.
Frequently asked questions
Why do we subtract the maximum in softmax?
Softmax gives the same result when the same constant is subtracted from every input. Subtracting the maximum makes the largest exponent zero, so no exponential can overflow, while the probabilities stay exactly the same.
What is the log-sum-exp trick?
It computes log(sum(exp(z))) stably as m + log(sum(exp(z - m))), where m is the maximum of z. It avoids overflow and is used to compute log-softmax and cross-entropy loss directly in log space.
Should I apply softmax before PyTorch's CrossEntropyLoss?
No. CrossEntropyLoss expects raw logits and applies log-softmax internally in a numerically stable way. Applying softmax first effectively applies it twice and usually slows or breaks training.