Cross-entropy: the loss of classifiers and language models
Before this lesson: lesson 01 (entropy), lesson 02 (conditional entropy) and lesson 03 (KL divergence, Gibbs' inequality). Maximum likelihood from the probability track; the softmax gradient also appears in calculus lesson 06. Logistic regression (ML fundamentals track, in preparation) can be read in parallel. Time: about 70 minutes, plus the notebook. This is a central lesson; take a break after section 3.4.
Why this matters #
You meet cross-entropy every day in machine learning.
- Classifiers (images, text, tabular data) are trained with softmax cross-entropy.
- Language models are trained to predict the next token with cross-entropy. Papers report the result as a loss in nats, as perplexity, or as bits per byte.
- Image and audio generative models report bits per dimension, which is a cross-entropy.
- Label smoothing and knowledge distillation change the target of the cross-entropy.
- Scaling laws for language models have an irreducible term: the entropy part of the loss.
When a loss is nan, when two perplexities cannot be compared, or when a training loss is "too
good to be true", the explanation is usually in this lesson.
As in the whole track, is the natural log (nats) and gives bits; PyTorch and NumPy losses are in nats.
1. Predict first #
2. The picture #
Cross-entropy: average surprise under your model #
Recall the coin of lesson 03. The coin is fair, , but the model says . Heads surprises the model by bits and tails by bits. Each side comes up half of the time, so the model's average surprise is
This is the cross-entropy. It has two parts:
The entropy bit is there because the coin is random. The KL part, bits, is there because the model is wrong.
Even a perfect model is surprised by a fair coin: 1 bit per flip. Only the second part depends on the model.
Drag the orange bars (the model ) against the fixed blue bars (the data ). The stacked bar shows the cross-entropy as (blue) plus (aqua). The blue part does not move when you change . The aqua part becomes 0 only when the orange bars match the blue bars, so is the floor. Change the data with the presets.
One example at a time: the log-loss #
A classifier sees an input and outputs probabilities for every class . The true label is one class, . The log-loss (or negative log-likelihood, NLL) of this example is the surprise of the model at the true label:
- The model gives the true class probability 1: .
- Probability 0.5: nats (1 bit).
- Probability 0.01: nats.
- Probability : . A confident mistake has no upper limit on its cost.
Move the slider for the probability the model gives to the true class. The aqua curve is the log-loss ; the grey dashed curve is the squared error ; the light grey step is the 0–1 loss of the predicted class (two classes). The yellow line marks the current value. On the right, compare the gradients with respect to the logit: for a confident mistake, only the log-loss still pushes hard.
A classifier gives the true class a probability of 0.01. What is the log-loss on this example?
nats ( bits). The loss grows like the log of , not like : halving the probability adds only nats. would be the loss , which is not the log-loss.
3. Definitions and main results #
3.1 Cross-entropy #
The cross-entropy of a distribution relative to a distribution is
Read it as: the data come from , you predict with , and you pay for each outcome. The first argument is the data distribution, the second is the model. As for KL, if for an outcome with , and outcomes with cost nothing.
Theorem 1 (cross-entropy = entropy + KL).
So , with equality if and only if .
Proof.
- For every with : (add and subtract ).
- Take the average under . The first term gives , the second gives .
- Gibbs' inequality (lesson 03) says , with equality only for .
Log-loss is a strictly proper scoring rule. A scoring rule gives a loss to a predicted distribution when the outcome is . It is strictly proper if the expected loss is smallest only at . For the log-loss, the expected loss is , and Theorem 1 shows that its only minimizer is . So a model trained with log-loss has a reason to report its true beliefs, not more confident or less confident ones.
3.2 Minimizing the log-loss is maximum likelihood #
Take a data set (discrete values) and a model . The empirical distribution puts mass on each data point: .
Theorem 2 (log-loss = NLL = forward KL).
So the three problems "minimize the average log-loss", "maximize the likelihood " and "minimize " have the same solutions.
Proof.
- Group equal data points. The value appears times, so the sum over the data points equals a sum over the values: . Divide by : the average log-loss is .
- Theorem 1 with gives .
- depends on the data only, not on . So the minimizers of the average log-loss and of are the same.
- , and is decreasing. So minimizing the average log-loss is maximizing the likelihood.
As , the average log-loss tends to . The KL has the data first and the model second: this is the forward KL. The other direction, (the reverse KL), is what variational inference minimizes, and it behaves very differently (lesson 06).
You train a model by minimizing the average cross-entropy on samples from . Which divergence are you minimizing?
The average log-loss tends to , and the entropy does not depend on . The expectation is under the data, so the data distribution is the first argument. The reverse KL averages under the model; you could not even estimate it from data samples alone.
3.3 Classification: softmax and its gradient #
A classifier with classes computes a vector of logits (real numbers) and turns them into probabilities with the softmax
Write the true label as a one-hot vector : for the true class , and 0 for the others. The loss is the cross-entropy between and :
The last form is how libraries compute it. The function (log-sum-exp) is evaluated as with , so no exponential overflows.
Theorem 3 (gradient of softmax cross-entropy). , that is, : prediction minus target.
So the gradient on the true logit is (raise it), and on every other logit it is (lower it). The entries add up to .
Proof of Theorem 3
- .
- The derivative of the first term: if and 0 otherwise, that is, .
- The derivative of log-sum-exp: (chain rule: the derivative of is , and ).
- Add: .
The same proof works for any target distribution (not only one-hot) with : , because . Calculus lesson 06 derives the batch version and the Hessian.
Binary case. With two classes, a model often outputs one logit and , the probability of class 1. The loss with label is the binary cross-entropy (BCE)
and its gradient is .
This is softmax cross-entropy with the two logits , so the gradient is again prediction minus target.
Move the logit sliders and choose the true class. The orange bars are the softmax probabilities ; the blue outline is the one-hot target ; the dark arrows are the gradient on each logit. The arrow on the true logit points down (the gradient is negative, so gradient descent raises that logit); the others point up. The arrows always add up to 0. Raise the temperature to see a flatter and a smaller gradient.
The softmax gives and the true class is class 1. What is the gradient of the loss with respect to the first logit ?
, and . The value is the derivative with respect to the probability , not the logit; the softmax Jacobian turns it into . The gradient is 0 only when : the loss keeps pushing even when the prediction is already correct.
3.4 The floor: the entropy of the labels #
A classifier is trained on pairs from a data distribution . Its expected loss is .
Theorem 4 (the floor).
Proof.
- Write the expectation as an outer average over and an inner average over given . The inner average is , which is the cross-entropy .
- Apply Theorem 1 inside, for each : .
- The average over of is the conditional entropy (lesson 02).
Only the KL part depends on the model. No model can get below , the uncertainty of the label that remains when you know the input.
Example: label noise. The clean label is a function of , but each label is flipped with probability 0.1. For every , is a coin with probabilities , so bits nats. The best model predicts 0.9 for the clean class. A training loss far below 0.325 nats means the model has memorized the flipped labels; its test loss cannot go below 0.325 nats.
For a language model, the floor is the entropy of the next token given the context. Natural text is not deterministic, so this floor is positive. The irreducible term in the scaling laws of language models plays this role (LLMs track, in preparation).
3.5 Soft targets: label smoothing and distillation #
The target does not have to be one-hot. For a target distribution , the loss is , and by Theorem 1
The minimum over is , reached at .
Label smoothing. Replace the one-hot target by (every class gets extra). With and : . The model is never pushed towards , so its logits stay finite and its predictions are less overconfident. Label smoothing was used in Inception-v3 and in the original Transformer, both with .
Knowledge distillation. A large teacher network with logits gives soft targets , where is a temperature. A higher gives a flatter distribution and shows which wrong classes the teacher finds similar ("dark knowledge"). For teacher logits : gives , and gives . The student is trained on , where is its own softmax at the same temperature, usually mixed with the normal loss on the true labels. Hinton et al. multiply this term by , because its gradient shrinks like .
Cross-entropy or KL as the loss? and differ by , which does not depend on the student. So they have the same gradient and the same minimizer. The difference is only the reported number: the KL is 0 at the optimum, the cross-entropy is .
Choose a target: one-hot, label smoothing (slider ) or a teacher at temperature . The blue bars are the target and the orange bars the student . The stacked bar splits the loss into and . With a one-hot target, a larger always lowers the loss. With label smoothing, the loss is smallest at a moderate , and a very confident student (large ) has a larger loss.
You train with label smoothing (, ). What is the smallest possible loss on one example?
The loss is . The KL part is 0 only at , and then the loss equals nats. A model that puts probability 1 on the true class has where , so its loss is infinite.
3.6 Why not squared error or accuracy? #
Accuracy (or the 0–1 loss) is piecewise constant in the logits: its gradient is 0 almost everywhere, so gradient descent cannot use it. It is also not strictly proper: every with the right most likely class gets the same score, so it does not reward good probabilities.
Squared error on probabilities (the Brier score, ) is a strictly proper scoring rule too, so the issue is not its minimizer. The issue is the gradient through the sigmoid or softmax. For two classes with true label 1, . For a confident mistake, : , the squared-error gradient is , but the log-loss gradient is . The log cancels the flat tail of the sigmoid, so the log-loss learns fast from exactly the examples that are most wrong. And the log-loss is the likelihood, so all of maximum-likelihood theory applies.
Calibration. A model is calibrated if, among the inputs where it says "70%", about 70% are correct. Because the log-loss is proper, a model that minimizes the expected log-loss is calibrated. Large networks still end up overconfident on test data, because they overfit the training loss. Temperature scaling (dividing the logits by one number fitted on validation data) fixes most of it (ML fundamentals track, in preparation).
3.7 Units: nats, bits, perplexity, bits per dimension #
These are all the same quantity, an average NLL, in different units. Let be the average NLL per token (or per symbol) in nats.
| unit | formula | meaning |
|---|---|---|
| bits per token | the same loss with | |
| perplexity | effective number of equally likely choices | |
| bits per dimension | NLL of one image (or sound) divided by its numbers | |
| bits per byte | does not depend on the tokenizer |
- Perplexity is the geometric mean of over the tokens: . A model that is uniform over tokens has and : it "chooses among tokens". By Theorem 1, the perplexity is at least , where is the entropy per token of the text.
- Bits per dimension (bpd): an image has numbers. Dividing by lets you compare images of different sizes.
- Bits per byte: a tokenizer with longer tokens has fewer tokens per text, so its loss per token is larger. Dividing the total bits by the number of raw bytes removes this effect.
Move the loss slider and read the same number as bits, perplexity and bits per byte. The curve is the perplexity on a log scale; the yellow dot is the current model. Try the preset "uniform over 50 257 tokens". Switch to the image model to convert an NLL per image into bits per dimension.
A language model has a loss of 3 bits per token. What is its perplexity?
In bits, : the model is as uncertain as a uniform choice among 8 tokens. is the perplexity of a loss of 3 nats per token. Always check the unit before you exponentiate.
Continuous models of discrete data: dequantization
Images are integers, , but flows and diffusion models use densities on . A density can put arbitrarily tall spikes on the integer points, so the likelihood of the raw integers can be made arbitrarily large and means nothing. The standard fix is uniform dequantization: train and evaluate on with .
Theorem 5 (dequantization bound, Theis et al. 2016, §3.1). Define the discrete model for integer points . Then , and
Proof.
- The unit cubes do not overlap, so is the mass of on their union, which is at most 1.
- The cube has volume 1, so . Jensen for the concave (lesson 03): .
So the continuous NLL on dequantized data is an upper bound on , the code length of a real discrete model: the reported bits per dimension are conservative.
Rescaling. Models often work on . The density changes by the Jacobian: . So : add 8 bits per dimension to an NLL measured on the scale. For data scaled by , add bits per dimension.
Answers to section 1. (1) nats. (2) . (3) No. The floor is nats per example (section 3.4), even for a perfect model.
4. Worked example #
(a) Softmax cross-entropy from logits. Logits , true class 1.
- Exponentials: , , . Sum: .
- Softmax: .
- Loss: nats bits. With log-sum-exp: . ✓
- Gradient: . The entries add up to 0.
- If the true class were class 3, the loss would be nats: the same logits, a confident mistake, six times the loss.
(b) Label smoothing. Same logits, , : .
- Loss: nats.
- Entropy of the target: nats.
- KL part: nats. So , the split of Theorem 1.
- Gradient: .
(c) Distillation. Teacher logits , student logits .
- : and . nats.
- : and . nats; times gives .
(d) Units. A language model has nats per token.
- Bits per token: . Perplexity: .
- Model A: 3.0 nats per token, 4.0 bytes per token. Model B: 2.0 nats per token, 2.5 bytes per token. Perplexity: A , B . Bits per byte: A , B . B has the lower perplexity, but A predicts the text better.
- An image model has an NLL of 25 000 nats on one image, so and .
5. In code #
NumPy and SciPy check the numbers above. The notebook builds these functions step by step.
import numpy as np
from scipy.special import logsumexp, softmax
from scipy.stats import entropy
# (a) softmax cross-entropy from logits, the stable way
z, c = np.array([2.0, 1.0, 0.0]), 0 # true class 1 is index 0
loss = logsumexp(z) - z[c]
q = softmax(z)
y = np.eye(3)[c]
print(q, loss, loss / np.log(2)) # [0.6652 0.2447 0.09 ] 0.4076 0.5881
print(q - y, np.isclose((q - y).sum(), 0)) # [-0.3348 0.2447 0.09 ] True
# H(p, q) = H(p) + KL(p || q) for the coin, in bits
p, qc = np.array([0.5, 0.5]), np.array([0.8, 0.2])
print(-(p * np.log2(qc)).sum(), entropy(p, base=2) + entropy(p, qc, base=2)) # 1.3219 1.3219
# (b) label smoothing: loss = H(t) + KL(t || q)
t = 0.9 * y + 0.1 / 3
print(-(t * np.log(q)).sum(), entropy(t), entropy(t, q)) # 0.5076 0.2911 0.2165
# (d) units
nll = 2.5
print(nll / np.log(2), np.exp(nll)) # 3.6067 12.1825
print(np.log(50257), np.exp(np.log(50257))) # 10.8249 50257.0 (uniform model)
print(25_000 / (64 * 64 * 3 * np.log(2))) # 2.9352 bits per dimension
In PyTorch, F.cross_entropy takes logits (not probabilities) and class indices or soft targets.
F.kl_div(input, target) computes and expects input as
log-probabilities: the model goes first, the target second, the opposite of the math notation.
import torch, torch.nn.functional as F
z = torch.tensor([[2.0, 1.0, 0.0]])
print(F.cross_entropy(z, torch.tensor([0])).item()) # 0.4076
print(F.cross_entropy(z, torch.tensor([0]), label_smoothing=0.1).item()) # 0.5076
p, q = torch.tensor([[0.5, 0.5]]), torch.tensor([[0.8, 0.2]])
print(F.kl_div(q.log(), p, reduction="batchmean").item()) # 0.2231 = KL(p || q)
Never compute torch.log(torch.softmax(z)): for large logits the softmax underflows to 0 and the log
gives -inf. Use F.log_softmax or F.cross_entropy, which use log-sum-exp.
6. Where it shows up #
- Image and text classifiers. Softmax cross-entropy on one-hot labels, sometimes with label smoothing (deep learning lesson 06). Binary and multi-label problems use the sigmoid with BCE on each output.
- Language models. Pretraining minimizes the average next-token cross-entropy. By the chain rule (lesson 02), the sum of per-token conditional losses is the NLL of the whole sequence. Papers report the loss in nats, perplexity, or bits per byte (LLMs track, in preparation).
- Scaling laws. The fitted loss curve has an irreducible term : the entropy part of the cross-entropy, which more parameters or data cannot remove.
- Distillation. DistilBERT and many small language and vision models are trained on soft teacher outputs with a KL term at a temperature.
- Generative models. Autoregressive image models, flows and diffusion models report bits per dimension on dequantized data (generative models track).
- ML for science. The log score evaluates probabilistic forecasts (precipitation categories, earthquake magnitudes, extreme-event warnings). Because it is strictly proper, a forecaster cannot improve the expected score by hedging or by exaggerating its confidence.
7. Common mistakes #
- The arguments in the wrong order. averages under the data and takes the log of the model . is a different number.
log(softmax(z))in code. It underflows to . Uselog_softmaxor a loss that takes logits.F.kl_divwith probabilities or swapped arguments. It expectsinput= log-probabilities of the model andtarget= probabilities of the target. Wrong inputs give a wrong number and no error.- Gradient with respect to the probability. , but the gradient that training uses is with respect to the logits: .
- Averaging perplexities. Perplexity is the exponential of the average loss. The average of per-document perplexities is larger: for losses 1 and 3 nats, , but (Jensen, is convex).
- Comparing perplexities across tokenizers. Use bits per byte.
- Expecting a loss of 0. With noisy labels, label smoothing or ambiguous inputs the floor is or . A training loss below the floor means memorization.
- Bits per dimension without the after rescaling 8-bit data to , or on raw integers without dequantization.
8. Check yourself #
- A binary classifier outputs for an example with label . Compute the loss in
nats and the gradient with respect to .
Answer
nats. : positive, so gradient descent lowers . - Show that the gradient of with respect to the logits is the same as the gradient of
, for any fixed target .
Answer
(Theorem 1), and does not depend on the logits. So both have the gradient . - The labels of a data set are flipped with probability 0.2. Your training loss is 0.30 nats and your
test loss is 0.70 nats. What do you conclude?
Answer
The floor is nats. The training loss of 0.30 is below the floor, so the model has memorized some flipped labels. The test loss of 0.70 is 0.20 nats above the floor: that is the KL part, the room for improvement on new data. - A language model is uniform over a vocabulary of tokens. Give its loss in nats and in
bits per token, and its perplexity.
Answer
Each token has , so nats bits per token, and . - A flow on images, with data scaled to , reports
nats per image. What are the bits per dimension on the 8-bit scale? Is the positive log-density a bug?
Answer
. On the scale, bits per dimension; add 8: bits per dimension. Not a bug: a density on can be larger than 1, so its log can be positive. Only the corrected number bounds a code length. - Label smoothing with on classes. What is the target for the true class
and for each other class? What is the gradient on a wrong logit when the model predicts for it?
Answer
True class: ; each other class: . Gradient : negative, so gradient descent *raises* that logit a little. The model is pushed away from total confidence.
Define the cross-entropy .
: the average surprise under the model when the data come from .
How do cross-entropy, entropy and KL divergence relate?
. So , with equality only for .
Why is minimizing the average cross-entropy on data the same as maximum likelihood?
The average log-loss is , and it equals , where does not depend on .
What is the gradient of softmax cross-entropy with respect to the logits?
: the softmax probabilities minus the (one-hot or soft) target. Its entries add up to 0.
What is the lowest expected loss a classifier can reach?
, the entropy of the label given the input. Only the KL part can be trained away.
Compute the loss floor for binary labels flipped with probability 0.1.
bits nats per example.
What is the label-smoothing target for the true class and the other classes?
: the true class gets , every other class .
What does a knowledge-distillation loss minimize?
from the teacher's softmax at temperature to the student's softmax at the same , usually times and mixed with the loss on the true labels.
How is perplexity computed from the average loss in nats?
(or ). A uniform model over tokens has perplexity .
How do you compute bits per dimension from an NLL in nats?
, where is the number of dimensions (for an image, height × width × channels).
9. Interview angle #
- "Why cross-entropy and not MSE for classification?" It is the NLL of a categorical model, so training is maximum likelihood. With a softmax, its gradient is , which stays large for confident mistakes; squared error through a sigmoid has a gradient that vanishes there.
- "Derive the gradient of softmax cross-entropy." , and , so .
- "What is perplexity? What is it for a uniform model over 50k tokens?" The exponential of the average NLL per token in nats, the effective number of choices; 50k.
- "Your training loss is much lower than you expect from the label noise. What is happening?" The loss cannot go below on new data; the model is memorizing noisy labels. Use early stopping, regularization or label smoothing.
- "Cross-entropy or KL for distillation?" They differ by the entropy of the teacher's targets, which is a constant, so the gradients are the same.
- "How do you compute cross-entropy without overflow?" From the logits with log-sum-exp: with the max subtracted first.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
cross_entropy(p, q, base), and a check of .- A numerically stable softmax cross-entropy from logits (log-sum-exp), checked against
sklearn.metrics.log_loss, also for logits of size 1000. - A gradient check of by finite differences.
- Logistic regression by gradient descent on a toy set whose labels are flipped with probability 0.1; plot the loss against the floor nats.
perplexity(nll_nats)andbits_per_dim(nll_nats, D), with the uniform-model checks.
11. Watch and read #
- Kevin Murphy, Probabilistic Machine Learning: An Introduction, free PDF: §6.1.2 (cross-entropy), §6.1.5 (perplexity) and §6.2.5 (KL and maximum likelihood).
- Hinton, Vinyals and Dean, Distilling the Knowledge in a Neural Network (2015): soft targets, temperature and the factor.
- Müller, Kornblith and Hinton, When Does Label Smoothing Help? (2019): what label smoothing does to the representations and to calibration.
- Guo, Pleiss, Sun and Weinberger, On Calibration of Modern Neural Networks (2017): overconfidence and temperature scaling.
- Theis, van den Oord and Bethge, A note on the evaluation of generative models (2016), §3.1: the dequantization bound and bits per dimension.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.