concept / softmax-cross-entropy
Next task →
University/Deep Learning/Training mechanics/Softmax and Cross-Entropy Loss
Deep Learning · Training mechanics · Loss functions

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 ∂L/∂z=p−y\partial L/\partial z=p-y and is the default objective for multiclass classification.

39 sectionsintermediate160 minhand-authored · structural 82/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

A classifier ends with a vector of logits z∈RCz\in\mathbb{R}^C (CC classes), one unbounded real score per class. Softmax turns them into probabilities

pi=ezi∑j=1Cezj,pi>0,∑ipi=1.p_i=\frac{e^{z_i}}{\sum_{j=1}^{C}e^{z_j}},\qquad p_i>0,\quad \sum_i p_i=1 .

For a target distribution yy (usually one-hot, yk=1y_k=1 for the true class kk), the cross-entropy loss is

 L(z,y)=−∑i=1Cyilog⁡pi ,\boxed{\ L(z,y)=-\sum_{i=1}^{C} y_i\log p_i\ },

which for one-hot labels reduces to L=−log⁡pkL=-\log p_k. Substituting softmax and cancelling gives the numerically important form

L=log⁡∑j=1Cezj−zk.L=\log\sum_{j=1}^{C}e^{z_j}-z_k .

The gradient with respect to logits is simply p−yp-y — 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: L=∥p−y∥2L=\lVert p-y\rVert^2. 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 p(y=i∣x)=softmax(z)ip(y=i\mid x)=\mathrm{softmax}(z)_i: 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 p−yp-y that is large precisely when the model is confidently wrong — the desired learning signal.

3. Historical background

Claude Shannon (1948) defined entropy H(X)=−∑ipilog⁡piH(X)=-\sum_i p_i\log p_i in information theory. Irving Good (1952) introduced the logarithmic scoring rule and noted its propriety. The cross-entropy H(p,q)=−∑ipilog⁡qiH(p,q)=-\sum_i p_i\log q_i 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 yy with (1−ϵ)y+ϵ/C(1-\epsilon)y+\epsilon/C to combat overconfidence. Guo et al. (2017) showed modern networks are poorly calibrated and studied temperature scaling, which rescales logits by 1/T1/T at inference. Lin et al. (2017) proposed focal loss to address extreme class imbalance in detection.

4. Fundamental problem

Given real-valued scores z1,…,zCz_1,\dots,z_C 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: exp⁡(z)\exp(z) overflows for zz above ~88 in fp32 / ~709 in fp64, and log⁡p\log p is −∞-\infty when pp 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 CC outcomes, the one maximising entropy subject to a fixed expected score ∑ipizi\sum_i p_i z_i is pi∝ezip_i\propto e^{z_i} (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 kk with probability pkp_k, the probability of observing the data is ∏npyn\prod_n p_{y_n}. Minimising −log⁡-\log of that product is minimising ∑nLn\sum_n L_n with Ln=−log⁡pynL_n=-\log p_{y_n}.

Fact 3 (information theory). For true distribution p⋆p^{\star} and model qq,

H(p⋆,q)=−∑ipi⋆log⁡pi⋆⏟H(p⋆)+∑ipi⋆log⁡pi⋆qi⏟DKL(p⋆∥q).H(p^{\star},q)=\underbrace{-\sum_i p^{\star}_i\log p^{\star}_i}_{H(p^{\star})}+\underbrace{\sum_i p^{\star}_i\log\frac{p^{\star}_i}{q_i}}_{D_{\mathrm{KL}}(p^{\star}\Vert q)} .

Since H(p⋆)H(p^{\star}) is constant, minimising cross-entropy is exactly minimising KL divergence to the truth; the minimum is zero iff q=p⋆q=p^{\star}.

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). z∈RCz\in\mathbb{R}^C, target yy with ∑iyi=1\sum_i y_i=1:

p=softmax(z),L=−∑iyilog⁡pi=log⁡∑jezj−∑iyizi.p=\mathrm{softmax}(z),\qquad L=-\sum_i y_i\log p_i=\log\sum_j e^{z_j}-\sum_i y_i z_i .

For one-hot target at index kk: L=LSE(z)−zkL=\mathrm{LSE}(z)-z_k with LSE(z)=log⁡∑jezj\mathrm{LSE}(z)=\log\sum_j e^{z_j}.

Stable evaluation. Let m=max⁡jzjm=\max_j z_j. Then LSE(z)=m+log⁡∑jezj−m\mathrm{LSE}(z)=m+\log\sum_j e^{z_j-m}, and log⁡pi=zi−m−log⁡∑jezj−m\log p_i=z_i-m-\log\sum_j e^{z_j-m} — all exponents are ≤0\le0, so no overflow and log⁡pi\log p_i never evaluates log⁡0\log 0 for finite logits.

Gradient.

∂L∂zi=pi−yi.\frac{\partial L}{\partial z_i}=p_i-y_i .

Hessian. ∇z2L=diag(p)−pp⊤\nabla_z^2L=\mathrm{diag}(p)-pp^\top, the softmax Jacobian: symmetric positive semidefinite, rank C−1C-1, with null vector 1\mathbf{1} (adding a constant to all logits does not change pp or LL).

Batch of BB examples. Z∈RB×CZ\in\mathbb{R}^{B\times C}, YY one-hot of the same shape or class indices k∈{0,…,C−1}Bk\in\{0,\dots,C-1\}^B:

L=1B∑b=1B(LSE(Zb,:)−Zb,kb),∇ZL=1B(P−Y).L=\frac1B\sum_{b=1}^{B}\big(\mathrm{LSE}(Z_{b,:})-Z_{b,k_b}\big),\qquad \nabla_Z L=\frac1B(P-Y).

With logits Z=HW+bZ=H W+b. ∇WL=H⊤(P−Y)/B\nabla_W L=H^\top(P-Y)/B, ∇bL=mean(P−Y)\nabla_b L=\mathrm{mean}(P-Y), ∇HL=(P−Y)W⊤\nabla_H L=(P-Y)W^\top.

8. Notation dictionary

| Symbol | Meaning | Shape / type | |---|---|---| | CC | number of classes | integer | | z∈RCz\in\mathbb{R}^C | logits (unnormalised scores) | vector | | p=softmax(z)p=\mathrm{softmax}(z) | predicted class distribution | vector in simplex ΔC−1\Delta^{C-1} | | yy | target distribution (one-hot unless smoothed) | vector in ΔC−1\Delta^{C-1} | | kk | index of the true class | integer | | LL | cross-entropy loss | scalar | | LSE(z)=log⁡∑jezj\mathrm{LSE}(z)=\log\sum_j e^{z_j} | log-sum-exp | scalar | | m=max⁡jzjm=\max_j z_j | shift used for stability | scalar | | H(p,q)H(p,q) | cross-entropy | scalar | | DKL(p∥q)D_{\mathrm{KL}}(p\Vert q) | Kullback–Leibler divergence | scalar | | TT | inference temperature; logits divided by TT | scalar | | BB | batch size | integer | | 1\mathbf{1} | 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 kk,

L=−log⁡ezk∑jezj=log⁡∑jezj−zk=LSE(z)−zk.L=-\log\frac{e^{z_k}}{\sum_j e^{z_j}}=\log\sum_j e^{z_j}-z_k=\mathrm{LSE}(z)-z_k .

Step 2 — softmax derivative (single component). Let Z=∑jezjZ=\sum_j e^{z_j}. For i=ki=k:

∂log⁡pk∂zi=δik−eziZ=δik−pi.\frac{\partial\log p_k}{\partial z_i}=\delta_{ik}-\frac{e^{z_i}}{Z}=\delta_{ik}-p_i .

Therefore ∂L/∂zi=pi−δik\partial L/\partial z_i=p_i-\delta_{ik}, i.e. p−yp-y.

Step 3 — full Jacobian route (same result). ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j=p_i(\delta_{ij}-p_j), so ∂L/∂zj=−∑iyipi(δij−pj)=−yj+pj∑iyi=pj−yj\partial L/\partial z_j=-\sum_i y_i p_i(\delta_{ij}-p_j)=-y_j+p_j\sum_i y_i=p_j-y_j using ∑iyi=1\sum_i y_i=1. This also handles non-one-hot targets such as label smoothing.

Step 4 — temperature. If p=softmax(z/T)p=\mathrm{softmax}(z/T), then ∂L/∂zi=(pi−yi)/T\partial L/\partial z_i=(p_i-y_i)/T: low TT amplifies gradients, high TT flattens them.

Step 5 — numerical stability. LSE(z)=m+log⁡∑jezj−m\mathrm{LSE}(z)=m+\log\sum_j e^{z_j-m}: subtract mm before exponentiating, add it after taking the log. For z=(1000,999,998)z=(1000,999,998) the naive exp⁡(1000)\exp(1000) overflows in fp32; the stable form gives m=1000m=1000, sum =1+e−1+e−2=1.5032=1+e^{-1}+e^{-2}=1.5032, LSE=1000+0.4076\mathrm{LSE}=1000+0.4076, an ordinary finite number.

Step 6 — backprop to the preceding layer. For Z=HW+bZ=HW+b, the chain rule gives ∇WL=H⊤(P−Y)\nabla_W L=H^\top(P-Y), so the effective error signal entering the network is exactly P−YP-Y.

10. Proofs and proof intuition

Lemma 1 (cross-entropy decomposition). H(p⋆,q)=H(p⋆)+DKL(p⋆∥q)H(p^{\star},q)=H(p^{\star})+D_{\mathrm{KL}}(p^{\star}\Vert q). Proof. −∑ipi⋆log⁡qi=−∑ipi⋆log⁡pi⋆+∑ipi⋆log⁡(pi⋆/qi)-\sum_i p_i^{\star}\log q_i=-\sum_i p_i^{\star}\log p_i^{\star}+\sum_i p_i^{\star}\log(p_i^{\star}/q_i). □\square

Lemma 2 (propriety / Gibbs inequality). For any model qq, Ei∼p⋆[−log⁡qi]≥H(p⋆)\mathbb{E}_{i\sim p^{\star}}[-\log q_i]\ge H(p^{\star}) with equality iff q=p⋆q=p^{\star}. Proof. The expectation equals H(p⋆)+DKL(p⋆∥q)H(p^{\star})+D_{\mathrm{KL}}(p^{\star}\Vert q), and DKL≥0D_{\mathrm{KL}}\ge0 with equality iff the distributions coincide (by Jensen's inequality applied to −log⁡-\log, since ∑ipi⋆(qi/pi⋆)=1\sum_i p_i^{\star}(q_i/p_i^{\star})=1). □\square Hence reporting the true distribution is the unique optimal strategy — this is what "proper scoring rule" means.

Lemma 3 (gradient identity). For p=softmax(z)p=\mathrm{softmax}(z) and L=−∑iyilog⁡piL=-\sum_i y_i\log p_i with ∑iyi=1\sum_i y_i=1, ∇zL=p−y\nabla_z L=p-y. Proof. As in Step 3; it uses only ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j=p_i(\delta_{ij}-p_j) and ∑iyi=1\sum_i y_i=1. □\square

Lemma 4 (shift invariance). softmax(z+c1)=softmax(z)\mathrm{softmax}(z+c\mathbf{1})=\mathrm{softmax}(z) and LSE(z+c)=LSE(z)+c\mathrm{LSE}(z+c)=\mathrm{LSE}(z)+c. Proof. Factor ece^c from numerator and denominator. □\square Consequently the Hessian diag(p)−pp⊤\mathrm{diag}(p)-pp^\top has 1\mathbf 1 in its nullspace: the logit representation is redundant by one dimension.

11. Geometric interpretation

Logits live in RC\mathbb{R}^C but only their differences matter; quotienting out the direction 1\mathbf1 leaves a (C−1)(C-1)-dimensional affine space that softmax maps diffeomorphically onto the probability simplex ΔC−1\Delta^{C-1}. For C=3C=3 the simplex is a triangle: the three vertices are the one-hot targets, the centre is the uniform distribution (1/3,1/3,1/3)(1/3,1/3,1/3), 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 p−yp-y 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 LL 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 C=3C=3: move a marker representing (p1,p2,p3)(p_1,p_2,p_3) 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 pi=1/(1+∑j≠iezj−zi)p_i=1/(1+\sum_{j\neq i}e^{z_j-z_i}). Toggle: (i) logit scale — pushing one logit up bends the marker toward its vertex; (ii) temperature TT — large TT pulls the marker to the centre, small TT to a vertex; (iii) label smoothing — the target moves off the vertex, making the minimum interior. Overlay the gradient arrow p−yp-y in logit space and confirm it vanishes at the target.

13. Numerical worked example

Let z=(2.0,1.0,0.1)z=(2.0,1.0,0.1) and let the true class have index k=0k=0, so the one-hot target is y=(1,0,0)y=(1,0,0).

exp⁡\exp values: e2=7.3891e^{2}=7.3891, e1=2.7183e^{1}=2.7183, e0.1=1.1052e^{0.1}=1.1052; sum Z=11.2125Z=11.2125.

p=(0.6590, 0.2424, 0.0986),∑ipi=1.0000.p=(0.6590,\,0.2424,\,0.0986),\qquad \sum_i p_i=1.0000 . L=log⁡(11.2125)−2.0=2.4171−2.0=0.4171,−log⁡(0.6590)=0.4171.L=\log(11.2125)-2.0=2.4171-2.0=0.4171,\qquad -\log(0.6590)=0.4171 .

Gradient ∇zL=p−y=(−0.3410, 0.2424, 0.0986)\nabla_z L=p-y=(-0.3410,\,0.2424,\,0.0986); components sum to zero as required by shift invariance.

Take a gradient step with η=0.5\eta=0.5: z′=(2.1705, 0.8788, 0.0507)z'=(2.1705,\,0.8788,\,0.0507). New exponentials: 8.7628,2.4086,1.05208.7628,2.4086,1.0520, sum 12.223412.2234, so p0′=0.7169p'_0=0.7169 and L′=−log⁡(0.7169)=0.3329L'=-\log(0.7169)=0.3329 — the loss fell by 0.08420.0842, consistent with the predicted decrease ∥∇L∥2η≈0.5(0.3412+0.24242+0.09862)=0.045\lVert\nabla L\rVert^2\eta\approx0.5(0.341^2+0.2424^2+0.0986^2)=0.045 to first order plus higher-order terms.

Numerical stability check. With logits (1000,999,998)(1000,999,998), exp⁡(1000)\exp(1000) overflows in fp32. The stable form uses m=1000m=1000: L=1000+log⁡(1+e−1+e−2)−1000=log⁡(1.5032)=0.4076L=1000+\log(1+e^{-1}+e^{-2})-1000=\log(1.5032)=0.4076 — 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 (−log⁡0.01=4.6-\log 0.01=4.6), 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 m=1000m=1000 the stable loss is m+log⁡(1+e−1+e−2)−998=log⁡(1.5032)+2m+\log(1+e^{-1}+e^{-2})-998=\log(1.5032)+2; the naive formula would overflow on exp⁡(1000)\exp(1000) 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 log⁡p\log p directly instead of log⁡\log of a possibly underflowed pp. 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: dZ=(P−Y)/BdZ=(P-Y)/B.

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 (B,C)(B,C), target is (B,)(B,) (not one-hot), logP and P are (B,C)(B,C), dZ is (B,C)(B,C), and the loss is a scalar.

19. Tensor and memory analysis

Per batch of BB logits over CC classes in fp32: logits 4BC4BC bytes, probabilities 4BC4BC, log-probabilities 4BC4BC (can reuse the logits buffer in-place), target 4B4B bytes or 4BC4BC if one-hot. Backward needs only PP and YY, so total working memory is O(BC)O(BC) — tiny compared with the activations of the network producing the logits.

For an ImageNet-scale head (B=256B=256, C=1000C=1000) that is about 1 MB per tensor; for a language model with vocabulary C=50,000C=50{,}000, B=512B=512 gives 25.625.6 M logits ≈102\approx102 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 PP in high-bandwidth memory.

20. Time complexity

Forward: computing pp and LL is O(BC)O(BC) (three passes over the logits: max, sum of exponentials, log-probabilities). Backward: O(BC)O(BC) to form P−YP-Y. Total O(BC)O(BC) per batch, negligible next to the O(Bd2)O(B d^2) cost of the network trunk. With a softmax over a C=50C=50k vocabulary this head can still dominate for small models; fused kernels reduce the number of memory passes from ~4 to ~1.

21. Space complexity

O(BC)O(BC) for logits, probabilities and gradients, plus O(B)O(B) for the loss reduction. The softmax Jacobian diag(p)−pp⊤\mathrm{diag}(p)-pp^\top is O(C2)O(C^2) if formed explicitly — never form it; the VJP p∑iyi−yp\sum_i y_i - y costs O(C)O(C). This is a concrete example of why autodiff systems use VJPs rather than materialising Jacobians.

22. Experimental demonstration

Run these experiments. (1) Reproduce z=(2,1,0.1)z=(2,1,0.1), y=(1,0,0)y=(1,0,0): verify p=(0.6590,0.2424,0.0986)p=(0.6590,0.2424,0.0986), L=0.4171L=0.4171,  ablazL=(−0.3410,0.2424,0.0986)\ abla_z L=(-0.3410,0.2424,0.0986) by hand and in code. (2) Gradient check at ten random logits to 10−610^{-6} in float64. (3) Overflow test: evaluate the naive formula log⁡(exp⁡(zk)/∑exp⁡zj)\log(\exp(z_k)/\sum\exp z_j) and the stable one on z=(1000,999,998)z=(1000,999,998); naive gives nan, stable gives 2.4076. (4) Temperature sweep: train a small classifier on a toy dataset with T∈{0.5,1,2}T\in\{0.5,1,2\} at inference (without retraining) and record test NLL and accuracy; plot calibration curves. (5) Label smoothing ablation with ϵ∈{0,0.05,0.1}\epsilon\in\{0,0.05,0.1\} and record NLL and top-1 accuracy.

23. Benchmark results

On the example above the analytic gradient matches the central-difference estimate to ~10−710^{-7} in float64; in fp16 finite differences only reach ~10−310^{-3} because of roundoff, while the analytic gradient remains exact to fp16 precision. Fused PyTorch cross-entropy on a C=50C=50k, B=512B=512 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 (ϵ=0.1)(\epsilon=0.1) 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 O(BC)O(BC) head and its softmax expensive.
  • The loss is undefined for probabilities rounded to exactly zero unless log-softmax is used.

25. Failure scenarios

  1. Overflow / NaN: naive exp⁡(z)\exp(z) for z>88z>88 (fp32) overflows; always use log-sum-exp with a max shift.
  2. Applying softmax twice: passing probabilities to F.cross_entropy applies log-softmax to already-normalised values, destroying the loss.
  3. Wrong softmax axis: softmax over the batch dimension instead of the class dimension mixes examples.
  4. Label index out of range: class indices must be in [0,C−1][0,C-1]; negative or oversized indices cause a device-side assert or silent wrap.
  5. Integer logits: passing integer tensors causes exp to return integer-semantics errors or wrong types; cast to float.
  6. Class imbalance: with 99% negatives the model can reach 99% accuracy while having useless NLL; weight the loss.
  7. Detached target: computing soft targets under no_grad when 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 p−yp-y 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 p≤1p\le1, −log⁡p≥0-\log p\ge0; averaging with smoothing still yields nonnegative loss.
  • "Softmax is needed at training time." Because cross-entropy composes with softmax into LSE(z)−zk\mathrm{LSE}(z)-z_k, the fused loss never needs to form pp explicitly.
  • "Label smoothing changes only regularisation." It also changes the optimal logits: the minimum moves from infinite separation to finite gaps of log⁡((1−ϵ)C/ϵ)\log((1-\epsilon)C/\epsilon).

27. Alternative approaches

  • Squared error / Brier score: ∑i(pi−yi)2\sum_i(p_i-y_i)^2; proper but saturates and is nonconvex with softmax.
  • Hinge / SVM loss: max⁡(0,zk−zi+1)\max(0, z_k - z_i + 1); margin-based, no probabilities, robust to outliers.
  • Focal loss: (1−pk)γ CE(1-p_k)^\gamma\,\mathrm{CE}; down-weights easy examples for imbalance.
  • Label smoothing / soft targets: replace one-hot yy; 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 exp⁡(NLL)\exp(\mathrm{NLL}).
  • Sequence-to-sequence / attention: cross-entropy on decoder outputs, often with label smoothing.
  • Distillation: soft targets from a teacher minimise DKLD_{\mathrm{KL}} 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_entropy and F.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

  1. Implement softmax_cross_entropy from memory and reproduce L=0.4171L=0.4171, p=(0.6590,0.2424,0.0986)p=(0.6590,0.2424,0.0986), dZ=(−0.3410,0.2424,0.0986)dZ=(-0.3410,0.2424,0.0986).
  2. Prove ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j=p_i(\delta_{ij}-p_j) and derive ∇zL=p−y\nabla_z L=p-y.
  3. Gradient-check at ten random logits in float64 and report the maximum relative error.
  4. Demonstrate overflow of the naive formula and correctness of the stable one on (1000,999,998)(1000,999,998).
  5. Add label smoothing ϵ=0.1\epsilon=0.1 and verify that the minimiser of L(z)L(z) satisfies zi−zj=log⁡(pi/pj)z_i-z_j=\log(p_i/p_j) with pp smoothed, i.e. gaps are finite.
  6. 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 naive log(exp(z)/sum); switch to log-sum-exp.
  • Loss decreases but accuracy does not: check whether labels are permuted or off-by-one.
  • cross_entropy gives 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 −log⁡pmax⁡-\log p_{\max} instead of −log⁡ptarget-\log p_{\text{target}}.
  • Loss starts near log⁡C\log C 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

  1. Derive the Hessian diag(p)−pp⊤\mathrm{diag}(p)-pp^\top, show it is PSD with null vector 1\mathbf1, and relate this to the non-identifiability of logits.
  2. Prove that minimising cross-entropy with label smoothing yields finite optimal logit gaps log⁡[(1−ϵ)C/ϵ]\log[(1-\epsilon)C/\epsilon].
  3. Implement a fused cross-entropy kernel in NumPy that computes LL and dZdZ without materialising PP for a batch, and compare memory with the naive version.
  4. Derive the gradient of the focal loss and implement it; compare its gradient magnitude on easy versus hard examples.
  5. Show empirically that temperature scaling minimises NLL on a held-out set without changing accuracy ordering.
  6. Prove the Bregman-divergence identity for cross-entropy and connect it to the softmax Jacobian.

35. Interview questions

  • Derive ∇zL=p−y\nabla_z L=p-y in two ways (via ∂pi/∂zj\partial p_i/\partial z_j 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_entropy from F.nll_loss in PyTorch.
  • Why does a high softmax temperature flatten gradients by 1/T1/T?

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 10610^6 tokens without an O(C)O(C) 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 p−yp-y and the Hessian without notes; (2) reproduce the worked numbers (2,1,0.1)(2,1,0.1) to four decimals; (3) implement the stable loss and gradient and gradient-check to 10−610^{-6}; (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 10−610^{-6} 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  ablazL=p−y\ abla_z L=p-y, 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.`

Research papers linked to this concept