Softmax and Cross-Entropy
🔥 What are softmax and cross-entropy? Softmax turns a vector of scores (logits) into probabilities: exponentiate each score, then divide by the sum. Cross-entropy then scores those probabilities against the true class as the negative log of the probability given to it. Together they are the loss of almost every classifier and language model.
Nuro asked a machine learning engineer, in a phone screen run by a research scientist, to write cross-entropy in NumPy, and asked a new-grad machine learning candidate, in a phone screen, to implement a numerically stable softmax, then derive and implement backprop and write a gradient update, which the candidate did in NumPy using the gradient of cross-entropy with respect to the logits (the question).
The Prompt
The formulas take one line each. The question is whether your version survives large logits, and whether you know the gradient by heart and can derive it.
"Implement softmax and the cross-entropy loss in NumPy, numerically stable. Derive the gradient with respect to the logits and use it for one gradient-descent step."
Clarifying Questions
You: What are the inputs? I'll assume logits of shape (N, C) and integer labels y of shape (N,).
Interviewer: Yes. Mean loss over the batch.
You: What model is the gradient step for? A linear classifier, logits = X W + b?
Interviewer: That's fine. Learning rate as a parameter.
You: May I compute the loss directly from logits, without returning probabilities first? It is more stable.
Interviewer: Yes, but keep a separate softmax function too.
You: Should I support label smoothing?
Interviewer: If time allows.
What You'll Build
softmax(z, axis=-1) -> same shape: stable for any finite logits.log_softmax(z, axis=-1) -> same shape: via log-sum-exp, never-inffor finite logits.cross_entropy(logits, y, smoothing=0.0) -> float: the mean loss.cross_entropy_grad(logits, y, smoothing=0.0) -> (N, C):dL / dlogits.sgd_step(W, b, X, y, lr) -> (W, b, loss): one step for a linear classifier.
The Idea
Softmax depends only on differences between logits, so you can subtract any constant from a row without changing
the result. Subtracting the row max makes the largest exponent exp(0) = 1, which cannot overflow, and the sum
is at least 1, so it cannot be zero either.
softmax(z)_c = exp(z_c - m) / sum_j exp(z_j - m) m = max_j z_j
log_softmax(z)_c = z_c - m - log sum_j exp(z_j - m) = z_c - logsumexp(z)
CE(z, y) = -log_softmax(z)_y = logsumexp(z) - z_y
The gradient of cross-entropy with respect to the logits is the reason the two are always fused. Differentiating
logsumexp(z) - z_y gives softmax(z) from the first term and -onehot(y) from the second:
dCE / dz = softmax(z) - onehot(y) (C,) per example; divide by N for the batch mean
It is bounded between -1 and 1 per entry, never needs a division, and is exactly "predicted minus target". Going
through softmax's own Jacobian, diag(p) - p p^T, gives the same answer at O(C^2) cost per example instead of
O(C).
Implementation
The goal is a loss that is finite for any finite logits and a gradient that matches autograd. Each step fixes a specific input that breaks the one before.
Bad Solution: the formula as written
Approach
Exponentiate, normalize, then take the log of the correct class's probability.
import numpy as np
def cross_entropy_naive(z: np.ndarray, y: np.ndarray) -> float:
e = np.exp(z) # (N, C)
p = e / e.sum(axis=1, keepdims=True)
return float(-np.log(p[np.arange(len(y)), y]).mean())
Challenges
exp overflows in float64 above about 709 (and in float16 above about 11), giving inf / inf = NaN. A logit of
1,000 is not exotic: an unscaled linear model on unnormalized features, or a network a few steps into a
divergence, produces it. In the other direction, a row whose logits are all below about -745 has every exp
underflow to 0 and gives 0 / 0.
Good Solution: subtract the max
Approach
Subtract each row's max before exponentiating. Now no exponent is positive, the sum is at least 1, and the probabilities are exact for any finite input.
def softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
e = np.exp(z - z.max(axis=axis, keepdims=True)) # largest term is exp(0) = 1
return e / e.sum(axis=axis, keepdims=True)
def cross_entropy_via_probs(z: np.ndarray, y: np.ndarray) -> float:
p = softmax(z, axis=1) # (N, C)
return float(-np.log(p[np.arange(len(y)), y]).mean())
Challenges
Softmax itself is now right, but the loss still fails when the model is confidently wrong. If the correct class's
logit is 800 below the max, its probability is exp(-800), which underflows to exactly 0, and -log(0) is
inf. One such example makes the batch's loss inf and its gradient useless. Clipping p to 1e-12 hides it,
at the cost of a wrong loss value and a zero gradient through the clip.
Great Solution: log-sum-exp, loss straight from logits
Approach
Never form the probability of the correct class. Compute log_softmax as z - m - log(sum(exp(z - m))); the
log of the sum is at least log 1 = 0, so every term is finite, and the loss is -log_softmax[y]. For the
gradient, use the combined formula, with label smoothing as a change of target.
def log_softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
m = z.max(axis=axis, keepdims=True)
return z - m - np.log(np.exp(z - m).sum(axis=axis, keepdims=True))
def targets(y: np.ndarray, C: int, smoothing: float) -> np.ndarray:
q = np.full((len(y), C), smoothing / C) # (N, C)
q[np.arange(len(y)), y] += 1.0 - smoothing # rows sum to 1
return q
def cross_entropy(z: np.ndarray, y: np.ndarray, smoothing: float = 0.0) -> float:
return float(-(targets(y, z.shape[1], smoothing) * log_softmax(z, axis=1)).sum(axis=1).mean())
def cross_entropy_grad(z: np.ndarray, y: np.ndarray, smoothing: float = 0.0) -> np.ndarray:
return (softmax(z, axis=1) - targets(y, z.shape[1], smoothing)) / len(y) # (N, C)
Challenges
With smoothing = 0 this is logsumexp(z) - z_y exactly. The (N, C) target matrix is wasteful for a 100,000-
token vocabulary; for no smoothing, index with log_softmax(z)[arange(N), y], and with smoothing, use
(1 - eps) * lp[arange(N), y] + eps * lp.mean(axis=1), which needs no (N, C) target array. The loss is still
the mean over N; if some positions are padding, the mean must be over real positions only (see the follow-ups).
One Gradient Step
For a linear classifier the chain rule adds one matrix product: with Z = X W + b, dW = X^T dZ and db is
the column sum of dZ.
def sgd_step(W: np.ndarray, b: np.ndarray, X: np.ndarray, y: np.ndarray, lr: float):
Z = X @ W + b # (N, C)
loss = cross_entropy(Z, y)
dZ = cross_entropy_grad(Z, y) # (N, C), already / N
return W - lr * X.T @ dZ, b - lr * dZ.sum(axis=0), loss # (D, C), (C,)
Common Mistakes
- Max over the wrong axis. Symptom: correct results on one example, wrong results on a batch, because one
global max is subtracted, which is still valid for the softmax but no longer prevents underflow in rows far
below it. Fix:
axis=1, keepdims=True. - Forgetting
keepdims. Symptom: a(N,)max broadcast against(N, C)logits, which fails whenN != Cand silently subtracts the wrong values whenN == C. Fix: alwayskeepdims=True, and test withN == C. - Dropping the
1 / N. Symptom: the gradient check is off by a factor ofN, and the effective learning rate changes with the batch size. Fix: divide once, in the gradient function. log(softmax(z)). Symptom:inflosses on confident mistakes. Fix:log_softmaxdirectly.
Testing It
Test a hand value, the shift invariance, the extreme logits that break the first two versions, the gradient against finite differences and PyTorch, and that a step lowers the loss.
z = np.array([[0.0, 0.0], [1.0, 2.0]])
y = np.array([0, 1])
assert np.isclose(cross_entropy(z[:1], y[:1]), np.log(2)) # uniform over 2 classes
assert np.allclose(softmax(z), softmax(z + 100.0)) and np.allclose(softmax(z).sum(1), 1)
assert np.isclose(cross_entropy(z[1:], y[1:]), np.log(1 + np.exp(-1.0))) # logsumexp - z_y
big = np.array([[1000.0, 0.0, -1000.0]])
with np.errstate(all="ignore"):
assert np.isnan(cross_entropy_naive(big, np.array([0]))) # inf / inf
assert np.isinf(cross_entropy_via_probs(big, np.array([2]))) # log(0)
assert np.isclose(cross_entropy(big, np.array([0])), 0.0)
assert np.isclose(cross_entropy(big, np.array([2])), 2000.0) # exact, finite
The second example has logits (1, 2) and label 1, so the loss is log(e + e^2) - 2 = log(1 + e^-1), about
0.313. The big row shows each version's limit: the naive one returns NaN, the probability-first one returns
inf for the wrong label, and the log-sum-exp version returns the exact loss of 2,000. Next, the gradient:
import torch
import torch.nn.functional as F
rng = np.random.default_rng(0)
Z, Y = rng.normal(size=(6, 4)) * 3, rng.integers(0, 4, 6)
for eps in (0.0, 0.1):
g = cross_entropy_grad(Z, Y, eps)
num = np.zeros_like(Z)
for i in np.ndindex(Z.shape):
d = np.zeros_like(Z)
d[i] = 1e-6
num[i] = (cross_entropy(Z + d, Y, eps) - cross_entropy(Z - d, Y, eps)) / 2e-6
assert np.abs(g - num).max() < 1e-8
zt = torch.tensor(Z, requires_grad=True)
loss_t = F.cross_entropy(zt, torch.tensor(Y), label_smoothing=eps)
loss_t.backward()
assert np.isclose(loss_t.item(), cross_entropy(Z, Y, eps)) and np.allclose(zt.grad.numpy(), g)
assert np.allclose(cross_entropy_grad(Z, Y).sum(axis=1), 0) # each row sums to 0
Every row of the gradient sums to zero, since both the probabilities and the targets sum to one; it is a cheap
assert that catches a missing term. PyTorch's label_smoothing uses the same eps / C spread, so the smoothed
loss matches it too. Finally, the step:
X = rng.normal(size=(100, 5))
labels = (X @ rng.normal(size=(5, 3))).argmax(axis=1) # a separable 3-class problem
W, b = np.zeros((5, 3)), np.zeros(3)
history = []
for _ in range(200):
W, b, loss = sgd_step(W, b, X, labels, lr=0.5)
history.append(loss)
print("loss", round(history[0], 4), "->", round(history[-1], 4),
"acc", ((X @ W + b).argmax(1) == labels).mean())
assert all(b2 <= a2 for a2, b2 in zip(history, history[1:]))
Starting from zero weights, the first loss must be exactly log 3 = 1.0986, since every class gets the same
logit. Two hundred steps take it to 0.1073 with 99% training accuracy, and the loss never rises, which it would at
a learning rate that is too large.
Follow-ups
1) Why cross-entropy and not squared error on the probabilities?
Because cross-entropy keeps a strong gradient exactly when the model is confidently wrong. Squared error on softmax outputs multiplies by the softmax's Jacobian, whose entries go to 0 as the softmax saturates, so a model that puts all its mass on the wrong class barely learns:
zw, yw = np.array([[10.0, 0.0]]), np.array([1]) # confidently wrong
g_ce = cross_entropy_grad(zw, yw)
p = softmax(zw)
J = np.diag(p[0]) - np.outer(p[0], p[0]) # softmax Jacobian, (C, C)
g_mse = (2 * (p[0] - np.eye(2)[1])) @ J
print("CE grad", g_ce.round(4), "MSE grad", g_mse.round(4))
The cross-entropy gradient on the logits is about (1, -1), its maximum; the squared-error one is about
(0.0002, -0.0002). Cross-entropy is also the negative log likelihood of a categorical model, so minimizing it
is maximum likelihood.
2) What is the binary version?
One logit per example, sigmoid instead of softmax. Binary cross-entropy is softplus(z) - y z, which
np.logaddexp(0, z) computes without overflow, and its gradient is sigmoid(z) - y: the same "predicted minus
target" form. It equals two-class softmax with logits (0, z). See
Logistic Regression.
def bce_with_logits(z: np.ndarray, y: np.ndarray) -> float:
return float(np.mean(np.logaddexp(0.0, z) - y * z))
zb = np.array([-3.0, 0.5, 800.0])
yb = np.array([0.0, 1.0, 1.0])
assert np.isclose(bce_with_logits(zb, yb), cross_entropy(np.c_[np.zeros(3), zb], yb.astype(int)))
3) Some positions are padding. How do you average?
Mask them out and divide by the number of real positions, not by N. Dividing by N makes the loss and the
gradient shrink as batches get more padding, which acts like a learning rate that depends on sequence lengths.
def masked_cross_entropy(z: np.ndarray, y: np.ndarray, mask: np.ndarray) -> float:
nll = -log_softmax(z, axis=1)[np.arange(len(y)), y] # (N,)
return float((nll * mask).sum() / max(mask.sum(), 1))
mask = np.array([1, 1, 1, 0, 0, 1], dtype=float)
assert np.isclose(masked_cross_entropy(Z, Y, mask), cross_entropy(Z[mask == 1], Y[mask == 1]))
In language-model training, decide whether the mean is per token across the batch or per sequence, and say which; the two weight long and short sequences differently.
4) The vocabulary has 100,000 classes. What changes?
Memory. The logits for 8,192 tokens and 100,000 classes are 819 million floats, 3.3 GB in float32, and the
probabilities and gradient are as large again. Fused kernels compute the loss and the gradient in one pass,
reusing the logits' buffer, and chunked implementations process tokens in slices so the full (N, C) matrix
never exists. Keep the max subtraction and the log-sum-exp in float32 even when the model runs in bfloat16,
since bfloat16's 2 to 3 significant digits are not enough to sum 100,000 exponentials accurately.
What is Expected at Each Level?
Junior
A junior candidate should write softmax with the max subtracted and explain why, compute the mean cross-entropy
with correct indexing, and state the gradient p - onehot(y). Deriving it may need a hint.
Mid-level
A mid-level candidate computes the loss from logits with log-sum-exp, derives the combined gradient in a few
lines, checks it with finite differences, and runs a gradient step that lowers the loss. They raise keepdims,
the 1 / N and confident mistakes without prompting.
Senior
A senior candidate adds label smoothing, the binary and masked variants, why cross-entropy beats squared error on probabilities, and the memory and precision issues of large vocabularies. They connect the same stable softmax to attention, where fully masked rows add one more case to handle.