Softmax and Cross-Entropy Loss
Softmax converts unbounded logits into a categorical distribution; cross-entropy measures the negative log-likelihood of the true class. Their composition has the remarkably simple gradient and is the default objective for multiclass classification.
1. Concept overview
A classifier ends with a vector of logits ( classes), one unbounded real score per class. Softmax turns them into probabilities
For a target distribution (usually one-hot, for the true class ), the cross-entropy loss is
which for one-hot labels reduces to . Substituting softmax and cancelling gives the numerically important form
The gradient with respect to logits is simply — prediction minus target — one of the cleanest identities in deep learning.
2. Why this concept exists
Alternatives are worse for classification:
- Squared error on probabilities: . Because softmax saturates (its Jacobian becomes near-zero when a logit dominates), gradients vanish for confident wrong predictions, and the loss is nonconvex in the logits.
- Squared error on a sigmoid output: assumes classes are independent and does not enforce a distribution; gradients can saturate.
- Hinge loss: optimises margin rather than probability; it does not give calibrated probabilities and ignores the confidence of correctly classified examples.
Cross-entropy is the negative log-likelihood under the model : minimising it over data is maximum-likelihood estimation. It is also a proper scoring rule: the expected loss is minimised exactly when the reported distribution equals the true one. Combined with softmax it yields a gradient that is large precisely when the model is confidently wrong — the desired learning signal.
3. Historical background
Claude Shannon (1948) defined entropy in information theory. Irving Good (1952) introduced the logarithmic scoring rule and noted its propriety. The cross-entropy became the standard loss for categorical prediction in statistics (see Rubinstein's 1999 Simulation and the Monte Carlo Method). In neural networks, Rumelhart, Hinton and Williams (1986) used the softmax / log-likelihood combination in backpropagation experiments. Szegedy et al. (2016) popularised label smoothing, replacing one-hot with to combat overconfidence. Guo et al. (2017) showed modern networks are poorly calibrated and studied temperature scaling, which rescales logits by at inference. Lin et al. (2017) proposed focal loss to address extreme class imbalance in detection.
4. Fundamental problem
Given real-valued scores from a model, produce (a) a valid probability distribution and (b) a differentiable scalar loss that penalises assigning low probability to the true class, while (c) remaining numerically stable when logits are large and (d) yielding informative gradients even early in training.
The subtle difficulties are numerical, not conceptual: overflows for above ~88 in fp32 / ~709 in fp64, and is when underflows to zero. The log-sum-exp trick and the fused "log-softmax" formulation solve both without changing the mathematics.
5. First-principles explanation
Fact 1 (Boltzmann / Gibbs distribution). Among all distributions on outcomes, the one maximising entropy subject to a fixed expected score is (solve with a Lagrange multiplier). Softmax is therefore the maximum-entropy distribution consistent with the logits — the least-committal choice.
Fact 2 (likelihood). If the model says class with probability , the probability of observing the data is . Minimising of that product is minimising with .
Fact 3 (information theory). For true distribution and model ,
Since is constant, minimising cross-entropy is exactly minimising KL divergence to the truth; the minimum is zero iff .
6. Prerequisite concepts
Required: (a) logarithms and exponent rules; (b) probability distributions and expectations; (c) maximum-likelihood estimation; (d) entropy and KL divergence at the level of the identity above; (e) the chain rule and softmax Jacobian from backpropagation; (f) basic numerical floating-point limits. See the linked concepts for each.
7. Complete mathematical formulation
Forward (single example). , target with :
For one-hot target at index : with .
Stable evaluation. Let . Then , and — all exponents are , so no overflow and never evaluates for finite logits.
Gradient.
Hessian. , the softmax Jacobian: symmetric positive semidefinite, rank , with null vector (adding a constant to all logits does not change or ).
Batch of examples. , one-hot of the same shape or class indices :
With logits . , , .
8. Notation dictionary
| Symbol | Meaning | Shape / type | |---|---|---| | | number of classes | integer | | | logits (unnormalised scores) | vector | | | predicted class distribution | vector in simplex | | | target distribution (one-hot unless smoothed) | vector in | | | index of the true class | integer | | | cross-entropy loss | scalar | | | log-sum-exp | scalar | | | shift used for stability | scalar | | | cross-entropy | scalar | | | Kullback–Leibler divergence | scalar | | | inference temperature; logits divided by | scalar | | | batch size | integer | | | all-ones null direction of the Hessian | vector |
9. Step-by-step derivation
Step 1 — write the loss in log-softmax form. With one-hot target ,
Step 2 — softmax derivative (single component). Let . For :
Therefore , i.e. .
Step 3 — full Jacobian route (same result). , so using . This also handles non-one-hot targets such as label smoothing.
Step 4 — temperature. If , then : low amplifies gradients, high flattens them.
Step 5 — numerical stability. : subtract before exponentiating, add it after taking the log. For the naive overflows in fp32; the stable form gives , sum , , an ordinary finite number.
Step 6 — backprop to the preceding layer. For , the chain rule gives , so the effective error signal entering the network is exactly .
10. Proofs and proof intuition
Lemma 1 (cross-entropy decomposition). . Proof. .
Lemma 2 (propriety / Gibbs inequality). For any model , with equality iff . Proof. The expectation equals , and with equality iff the distributions coincide (by Jensen's inequality applied to , since ). Hence reporting the true distribution is the unique optimal strategy — this is what "proper scoring rule" means.
Lemma 3 (gradient identity). For and with , . Proof. As in Step 3; it uses only and .
Lemma 4 (shift invariance). and . Proof. Factor from numerator and denominator. Consequently the Hessian has in its nullspace: the logit representation is redundant by one dimension.
11. Geometric interpretation
Logits live in but only their differences matter; quotienting out the direction leaves a -dimensional affine space that softmax maps diffeomorphically onto the probability simplex . For the simplex is a triangle: the three vertices are the one-hot targets, the centre is the uniform distribution , and softmax compresses the infinite logit space into the interior of the triangle (the boundary is approached but never reached for finite logits).
The gradient is the vector in logit space pointing from the target toward the current prediction. Gradient descent moves logits in the opposite direction, shrinking the logit of over-predicted classes and growing that of the true class. The Hessian is the softmax covariance matrix: contours of are anisotropic because probability changes are cheaper near the simplex centre than near a vertex.
Cross-entropy is also a Bregman divergence generated by the negative-entropy function, which explains its asymmetric, sharply increasing penalty for confident mistakes.
12. Visual explanation
Use the interactive Softmax Simplex Playground. It shows a 2-simplex (triangle) for : move a marker representing and watch the cross-entropy to a chosen vertex grow as you approach the opposite edge. A linked panel shows the three logits and the softmax curve . Toggle: (i) logit scale — pushing one logit up bends the marker toward its vertex; (ii) temperature — large pulls the marker to the centre, small to a vertex; (iii) label smoothing — the target moves off the vertex, making the minimum interior. Overlay the gradient arrow in logit space and confirm it vanishes at the target.
13. Numerical worked example
Let and let the true class have index , so the one-hot target is .
values: , , ; sum .
Gradient ; components sum to zero as required by shift invariance.
Take a gradient step with : . New exponentials: , sum , so and — the loss fell by , consistent with the predicted decrease to first order plus higher-order terms.
Numerical stability check. With logits , overflows in fp32. The stable form uses : — finite and correct.
14. Real-world analogy
A weather forecaster assigns percentages to {rain, cloudy, sun}. Cross-entropy scores the forecast by how much surprise the eventual outcome caused: saying "1% chance of rain" when it rains is heavily penalised (), while "70% chance" costs only 0.36. Proper scoring means the forecaster does best by stating their true belief — exaggerating confidence never helps in expectation. Softmax is the mechanism that converts internal "gut scores" into percentages that sum to 100%.
15. Algorithm pseudocode
algorithm SoftmaxCrossEntropy(logits Z[B,C], labels k[B], eps):
m[b] <- max_j Z[b,j] # stability shift
E[b,j] <- exp(Z[b,j] - m[b])
S[b] <- sum_j E[b,j]
logP[b,j] <- Z[b,j] - m[b] - log(S[b]) # stable log-softmax
L <- -(1/B) * sum_b logP[b, k[b]]
P[b,j] <- exp(logP[b,j])
dZ <- (P - one_hot(k)) / B # gradient w.r.t. logits
return L, dZ
# With target distributions Y (label smoothing): dZ <- (P - Y) / B
16. Implementation from scratch
import numpy as np
def softmax_cross_entropy(logits, labels, label_smoothing=0.0):
"""logits: (B, C) float array; labels: (B,) integer class indices."""
B, C = logits.shape
m = logits.max(axis=1, keepdims=True) # (B, 1)
E = np.exp(logits - m) # all exponents <= 0
S = E.sum(axis=1, keepdims=True) # (B, 1)
logP = logits - m - np.log(S) # stable log-probabilities
P = np.exp(logP)
Y = np.full((B, C), label_smoothing / C)
Y[np.arange(B), labels] += 1.0 - label_smoothing
loss = -(Y * logP).sum(axis=1).mean()
dZ = (P - Y) / B
return loss, dZ, P
z = np.array([[2.0, 1.0, 0.1]])
loss, dz, p = softmax_cross_entropy(z, np.array([0]))
print(loss, p, dz) # 0.4171, [[0.6590 0.2424 0.0986]], [[-0.3410 0.2424 0.0986]]
# Gradient check at a random logit:
h = 1e-6
zp, zm = z.copy(), z.copy(); zp[0, 0] += h; zm[0, 0] -= h
fd = (softmax_cross_entropy(zp, np.array([0]))[0]
- softmax_cross_entropy(zm, np.array([0]))[0]) / (2 * h)
assert abs(fd - dz[0, 0]) < 1e-6, (fd, dz[0, 0])
# Overflow resistance: true class index 2, so L = log(1+e^-1+e^-2) - (998-1000)
print(softmax_cross_entropy(np.array([[1000., 999., 998.]]), np.array([2]))[0]) # ~2.4076
The last line prints ~2.4076: with the stable loss is ; the naive formula would overflow on in fp32.
17. Professional library implementation
import torch
import torch.nn.functional as F
logits = torch.tensor([[2.0, 1.0, 0.1]], requires_grad=True) # (B, C)
target = torch.tensor([0]) # class indices
loss = F.cross_entropy(logits, target) # expects LOGITS, applies log-softmax internally
loss.backward()
print(loss.item(), logits.grad)
# Equivalent manual composition, useful when you need the probabilities:
logP = F.log_softmax(logits, dim=1)
loss2 = F.nll_loss(logP, target)
print(torch.allclose(loss, loss2))
# Numerically stable log-softmax for sampling / distillation:
log_probs = torch.logsumexp(logits, dim=1, keepdim=True) # LSE, no overflow
soft_targets = F.softmax(logits / 2.0, dim=1) # temperature 2
loss3 = -(soft_targets * logP).sum(dim=1).mean()
In PyTorch F.cross_entropy takes raw logits (not probabilities) and F.nll_loss takes log-probabilities; mixing them up silently applies softmax twice.
18. Code walkthrough
Scratch version. The max shift m makes every exponent nonpositive, so np.exp cannot overflow; logP = logits - m - log(S) computes directly instead of of a possibly underflowed . The target is turned into a soft vector Y so label smoothing works with the same code. The gradient line is the entire backward pass: .
PyTorch version. F.cross_entropy fuses log-softmax and negative log-likelihood into one stable CUDA kernel. F.nll_loss expects the output of F.log_softmax; choosing the wrong one is a classic silent bug. For knowledge distillation, use a soft target distribution and -(soft_targets * logP).sum(-1).
Shape discipline. logits is , target is (not one-hot), logP and P are , dZ is , and the loss is a scalar.
19. Tensor and memory analysis
Per batch of logits over classes in fp32: logits bytes, probabilities , log-probabilities (can reuse the logits buffer in-place), target bytes or if one-hot. Backward needs only and , so total working memory is — tiny compared with the activations of the network producing the logits.
For an ImageNet-scale head (, ) that is about 1 MB per tensor; for a language model with vocabulary , gives M logits MB in fp32, and the softmax output can double that. This is why large-vocabulary language models use fused cross-entropy kernels that compute loss and gradient without materialising in high-bandwidth memory.
20. Time complexity
Forward: computing and is (three passes over the logits: max, sum of exponentials, log-probabilities). Backward: to form . Total per batch, negligible next to the cost of the network trunk. With a softmax over a k vocabulary this head can still dominate for small models; fused kernels reduce the number of memory passes from ~4 to ~1.
21. Space complexity
for logits, probabilities and gradients, plus for the loss reduction. The softmax Jacobian is if formed explicitly — never form it; the VJP costs . This is a concrete example of why autodiff systems use VJPs rather than materialising Jacobians.
22. Experimental demonstration
Run these experiments. (1) Reproduce , : verify , , by hand and in code. (2) Gradient check at ten random logits to in float64. (3) Overflow test: evaluate the naive formula and the stable one on ; naive gives nan, stable gives 2.4076. (4) Temperature sweep: train a small classifier on a toy dataset with at inference (without retraining) and record test NLL and accuracy; plot calibration curves. (5) Label smoothing ablation with and record NLL and top-1 accuracy.
23. Benchmark results
On the example above the analytic gradient matches the central-difference estimate to ~ in float64; in fp16 finite differences only reach ~ because of roundoff, while the analytic gradient remains exact to fp16 precision. Fused PyTorch cross-entropy on a k, head is typically several times faster and uses markedly less peak memory than a naive sequence of softmax, gather, log (exact factors depend on GPU). Label smoothing typically improves top-1 accuracy by a fraction of a point on ImageNet while increasing the reported NLL — a reminder that NLL and accuracy are different objectives when the target is smoothed.
24. Limitations
- Assumes a categorical target; regression needs squared error or another likelihood.
- Maximising likelihood can produce overconfident predictions on finite, noisy data; calibration often need temperature scaling.
- Sensitive to class imbalance: minority classes receive little gradient mass; use weighting or focal loss.
- One-hot targets treat all mistakes alike; label smoothing or soft targets encode structure but change the objective.
- Logits are unidentifiable up to an additive constant; weight regularisation breaks that symmetry.
- Very large vocabularies make the head and its softmax expensive.
- The loss is undefined for probabilities rounded to exactly zero unless log-softmax is used.
25. Failure scenarios
- Overflow / NaN: naive for (fp32) overflows; always use log-sum-exp with a max shift.
- Applying softmax twice: passing probabilities to
F.cross_entropyapplies log-softmax to already-normalised values, destroying the loss. - Wrong softmax axis: softmax over the batch dimension instead of the class dimension mixes examples.
- Label index out of range: class indices must be in ; negative or oversized indices cause a device-side assert or silent wrap.
- Integer logits: passing integer tensors causes
expto return integer-semantics errors or wrong types; cast to float. - Class imbalance: with 99% negatives the model can reach 99% accuracy while having useless NLL; weight the loss.
- Detached target: computing soft targets under
no_gradwhen distillation needs gradients through a teacher is a design choice — make it deliberately.
26. Common misconceptions
- "Softmax outputs are calibrated probabilities." They are a normalised distribution, often overconfident outside the training distribution.
- "Cross-entropy and KL divergence are the same." They differ by the constant entropy of the target; equal only up to that constant.
- "The gradient means only the true class learns." All classes update: the true class is pushed up, every other class pushed down in proportion to its predicted probability.
- "-log p can be negative." For a single example with , ; averaging with smoothing still yields nonnegative loss.
- "Softmax is needed at training time." Because cross-entropy composes with softmax into , the fused loss never needs to form explicitly.
- "Label smoothing changes only regularisation." It also changes the optimal logits: the minimum moves from infinite separation to finite gaps of .
27. Alternative approaches
- Squared error / Brier score: ; proper but saturates and is nonconvex with softmax.
- Hinge / SVM loss: ; margin-based, no probabilities, robust to outliers.
- Focal loss: ; down-weights easy examples for imbalance.
- Label smoothing / soft targets: replace one-hot ; improves generalisation and calibration.
- NLL with a different link (e.g. sigmoid for multilabel): use binary cross-entropy per class when labels are not mutually exclusive.
- Temperature-scaled / mixup targets: modify logits or targets post hoc for calibration or regularisation.
29. Research applications
- Image classification: the standard head for ImageNet-scale models.
- Language modelling: next-token prediction is cross-entropy over the vocabulary; perplexity is .
- Sequence-to-sequence / attention: cross-entropy on decoder outputs, often with label smoothing.
- Distillation: soft targets from a teacher minimise between temperature-scaled distributions.
- Calibration research: measuring ECE and applying temperature scaling to make confidence trustworthy.
- Imbalanced domains: focal loss and class-weighted objectives in detection and medical imaging.
30. Important research papers
- Shannon C. E. (1948), A Mathematical Theory of Communication, Bell System Technical Journal 27:379–423.
- Good I. J. (1952), Rational Decisions, Journal of the Royal Statistical Society B 14(1):107–114 — logarithmic scoring rule.
- Rubinstein R. Y. (1999), Simulation and the Monte Carlo Method, Wiley — cross-entropy method.
- Szegedy C. et al. (2016), Rethinking the Inception Architecture for Computer Vision, CVPR — label smoothing.
- Lin T.-Y. et al. (2017), Focal Loss for Dense Object Detection, ICCV.
- Guo C., Pleiss G., Sun Y., Weinberger K. Q. (2017), On Calibration of Modern Neural Networks, ICML.
31. Further reading
- Cover & Thomas, Elements of Information Theory (2nd ed., 2006), chapters 2 and 11.
- Goodfellow, Bengio & Courville, Deep Learning (2016), sections 6.2.2 and 6.5.
- PyTorch docs on
F.cross_entropyandF.log_softmax: docs.pytorch.org/docs/stable/nn.functional.html. - Stanford CS231n classification loss notes: cs231n.github.io/linear-classify/#loss.
- Notes on proper scoring rules: Gneiting & Raftery (2007), Strictly Proper Scoring Rules, Prediction, and Estimation.
32. Practical exercises
- Implement
softmax_cross_entropyfrom memory and reproduce , , . - Prove and derive .
- Gradient-check at ten random logits in float64 and report the maximum relative error.
- Demonstrate overflow of the naive formula and correctness of the stable one on .
- Add label smoothing and verify that the minimiser of satisfies with smoothed, i.e. gaps are finite.
- Train a small classifier with and without smoothing; record NLL, accuracy and calibration error.
33. Debugging challenges
- Loss is
nan: logits are huge and you used naivelog(exp(z)/sum); switch to log-sum-exp. - Loss decreases but accuracy does not: check whether labels are permuted or off-by-one.
cross_entropygives a different value from manual softmax+NLL: you applied softmax before calling it, or used the wrong reduction.- Gradients are all zero: logits were created without
requires_grad, or you detached them. - Gradient check fails only at the true class: a common bug is using instead of .
- Loss starts near and stays there: the model outputs a constant; check the final layer and label encoding.
- Class 0 dominates predictions: extreme imbalance; inspect class frequencies and add weights.
34. Advanced exercises
- Derive the Hessian , show it is PSD with null vector , and relate this to the non-identifiability of logits.
- Prove that minimising cross-entropy with label smoothing yields finite optimal logit gaps .
- Implement a fused cross-entropy kernel in NumPy that computes and without materialising for a batch, and compare memory with the naive version.
- Derive the gradient of the focal loss and implement it; compare its gradient magnitude on easy versus hard examples.
- Show empirically that temperature scaling minimises NLL on a held-out set without changing accuracy ordering.
- Prove the Bregman-divergence identity for cross-entropy and connect it to the softmax Jacobian.
35. Interview questions
- Derive in two ways (via and via log-sum-exp).
- Why is log-softmax numerically stable and what exactly overflows without it?
- Prove that cross-entropy is a proper scoring rule.
- How does cross-entropy relate to KL divergence and entropy?
- What is the Hessian of the loss with respect to logits, and why is it singular?
- When would you use label smoothing or focal loss, and what changes mathematically?
- Distinguish
F.cross_entropyfromF.nll_lossin PyTorch. - Why does a high softmax temperature flatten gradients by ?
36. Research questions
- Does maximising likelihood inherently produce overconfidence in overparameterised models, and can this be proved?
- How do label smoothing and temperature scaling interact with calibration on out-of-distribution inputs?
- What is the optimal loss for extreme class imbalance when probabilities are misspecified?
- Can cross-entropy be replaced by a loss that directly optimises accuracy or expected calibration error while remaining differentiable?
- How should the softmax head be designed for vocabularies of tokens without an normaliser?
- What are the asymptotic generalisation guarantees of minimum-cross-entropy solutions in overparameterised linear models?
37. Mastery assessment
To pass: (1) derive the gradient and the Hessian without notes; (2) reproduce the worked numbers to four decimals; (3) implement the stable loss and gradient and gradient-check to ; (4) prove propriety and the entropy/KL decomposition; (5) explain overflow, double-softmax, wrong-axis and imbalance failures; (6) answer the interview questions. Complete the linked assessment; reading is not mastery.
38. Implementation submission
Push a repository with cross_entropy.py (NumPy forward/backward with label smoothing), tests/test_gradcheck.py (finite differences to and the overflow case), experiments.ipynb (worked example, temperature sweep, smoothing ablation with NLL/accuracy/calibration plots), and a README.md with the derivations of , the Hessian and the KL decomposition. Include the exact reproduction command and a table comparing your loss and gradient with PyTorch's F.cross_entropy.
39. Completion criteria
All of: derivations reproduced on paper; scratch implementation gradient-checked and overflow-tested; worked example numbers verified; at least two ablations with recorded results; three failure scenarios explained; assessment score at least 80%; one research question answered in a one-page note citing a paper. Only then mark the concept mastered.`