Derive the gradient of cross-entropy loss with respect to the logits when predictions come from a softmax. How do you implement the loss so it never overflows or underflows?
Answer
Model answer, written in a candidate's voice
In short
- ∂L/∂z = softmax(z) − onehot(y), via the softmax Jacobian ∂p_i/∂z_k = p_i(δ_ik − p_k).
- Use log-softmax: log p_i = z_i − logsumexp(z), with max subtraction before exponentiating.
- Fuse log-softmax and NLL into one cross-entropy operation and use the fused backward p − y; feed it logits, not probabilities.
- Label smoothing replaces the one-hot target with q, so ∂L/∂z = p − q.
In full
The core result is ∂L/∂z = p − y, where p = softmax(z) and y is the one-hot target. Deriving it: p_i = exp(z_i)/Σ_j exp(z_j), so ∂p_i/∂z_k = p_i(δ_ik − p_k); with L = −log p_y, ∂L/∂p_i = −y_i/p_i, and substituting gives ∂L/∂z_k = Σ_i (−y_i/p_i) p_i(δ_ik − p_k) = p_k − y_k. Numerically I never form exp(z) directly: I compute m = max(z), logsumexp = m + log(Σ_j exp(z_j − m)), and log p_i = z_i − logsumexp, so the exponentials are ≤ 1 and the denominator is at least 1. I fuse log-softmax and NLL into one cross-entropy op, or use the fused backward, so the gradient is p − y rather than a chain through a separately materialised softmax and log; such fused losses (for example PyTorch’s cross_entropy) expect raw logits, so passing probabilities would apply softmax twice. With label smoothing the target becomes q = (1−ε) onehot(y) + ε/K, or ε spread over the non-target classes, and the same derivation gives ∂L/∂z = p − q with loss −Σ_i q_i log p_i.
What a strong answer covers
- ∂L/∂z = softmax(z) − onehot(y), derived via the softmax Jacobian.
- log-softmax = z − logsumexp(z), subtracting the max before exponentiating.
- Fuse softmax and NLL into one operation.
- How label smoothing changes the target.
Common mistakes
- Passing probabilities to a loss that expects logits.
- Exponentiating without the max shift.