Cross-Entropy
How do you grade a model that answers with probabilities instead of a single guess?
The idea
Cross-entropy scores predictions by the negative log probability assigned to the target. In this next-token example, assigning less probability to the correct token raises the loss; assigning zero probability gives infinite loss.
Builds on Maximum Likelihood.
The picture
Cross-entropy is the negative log probability a model gives to an outcome, averaged over outcomes drawn from a target distribution. We use a next-word prediction for The cat sat on the …, where the target is the one true word, and grade the model's probabilities once that word is known. The figure and code show the loss rising as the true word receives less probability. You will need probabilities and logarithms.
Score. The model gives every candidate a score, its logit: the bars in the figure. A logit can be any number, positive or negative; on its own it is not yet a probability.
Share. Softmax turns the scores into shares of one pie: raise to each score, then divide by the total. The pie never grows, so any word that gains a share takes it from the others.
Grade. Then the true word arrives, and the model is graded on one number: the share it gave that word. The loss is of that share: the falling curve. Give the right word everything and the loss is zero; give it half and the loss is ; give it almost nothing and the loss climbs without limit. A model that is sure and wrong pays far more than one that admits it does not know.
Push. The arrows are what training does about it: which way each score moves to lower the loss, and how hard. Only the right word appears in the loss, yet every bar has an arrow, because every score feeds the total that the right word's share is divided by.
When the target is itself uncertain, because annotators disagree or labels are deliberately softened, the same surprise is averaged over the outcomes, weighted by how likely the target says each one is. That average is the cross-entropy ; the single right word is the case where the target puts all its weight on one outcome.
The mathematics
Let be a discrete label taking values in . Let be the target distribution and let be the model distribution. Assume , , and . All logarithms here are natural logarithms, so the units are nats.
For supervised classification, read this as a per-input statement. For an input , the target distribution is and the model distribution is . The dataset loss averages over examples.
The cross-entropy from to is
Equivalently,
The direction matters: supplies the averaging weights, while supplies the probabilities being scored. If and is near zero, the penalty becomes very large. If and , the mathematical loss is infinite. If , that class does not contribute directly to this cross-entropy term.
For a one-hot target , where and all other ,
This is exactly the per-example negative log-likelihood used for multiclass classification and next-token language modeling.
The link to KL divergence is
where
Cross-entropy and forward KL share one support rule: both are infinite when some has . The entropy does not involve at all and is finite on a finite set of classes. When the target distribution is fixed, is constant with respect to the model. Minimizing cross-entropy over is therefore the same optimization problem as minimizing . Maximum likelihood is the empirical version: the data distribution supplies , and the model is trained to reduce the average assigned to observed data.
For one-hot targets, the cross-entropy can be pushed arbitrarily close to , but with every it never reaches it. For soft targets the floor is , usually above , reached when (and only approached when has zeros, since softmax keeps every ). In that setting, the KL term is the mismatch and is the irreducible target uncertainty.
For neural networks, the model usually produces logits and probabilities
For the soft-target loss
we can derive the logit gradient directly. Since
and ,
Therefore the gradient with respect to each logit is
Classes where get a negative gradient, so gradient descent increases their logits. Classes where get a positive gradient, so gradient descent lowers them.
This is a gradient with respect to the logits. With respect to the probabilities themselves it would be ; the tidy appears only after differentiating through the softmax. Its components sum to zero, because softmax can only move probability from one class to another.
The two can point in different directions. With and , the probability gradient is : every probability "should" rise, which no distribution can do. The logit gradient is : raise , lower , leave . Here , and nats. The reverse cross-entropy differs from : the order of the two distributions matters.
Same accuracy, different loss
Two classifiers can both be right on every example and still differ in loss. Take classes , two examples labelled and , and two models whose outputs are the rows
Both put the most probability on the right class each time, so both have accuracy . Treating the two examples as independent, the likelihood of the labels is the product of the probabilities given to them: for and for . The mean one-hot cross-entropy is nats for and for . Taking logs keeps the order and the minus sign reverses it, so the higher likelihood and the lower cross-entropy pick the same model, , whose confidence went to what actually happened. Two examples, of course, say nothing about either model on new data.
Try it
First a worked example, then one to finish, then problems on your own. Check your answer before you look at the solution. Answers typed here are not kept when you leave.
1 · Worked example
The figure's numbers, by hand
Logits for mat, sofa, roof, moon. The right word is mat. Find the probabilities, the loss, and the gradient with respect to the logits.
Exponentiate. , , , ; the total is .
Say the next step to yourself first.2 · Finish it
When the answer is uncertain
Same logits, but now the target is soft: annotators said mat 90% of the time and sofa 10%, so . The first steps are done. What is the cross-entropy , in nats? Give three decimal places.
Share. , as before.
Surprise. .
Weight. Roof and moon have target weight , so they drop out.
- Your turn.
3 · On your own
The best single move
Back to the one-hot target (mat) and the logits . You may make one change. Which one lowers the loss the most?
4 · Finish it
Both right, not equally good
Two classifiers see the same two examples, with classes in the order (A, B, C). The labels are A and then B. Model M outputs and ; model N outputs and . Both put the most probability on the right class both times, so both have accuracy . What is M's mean cross-entropy over the two examples, in nats? Give three decimal places.
Keep only the right labels. M gave them and ; N gave them and .
Likelihood of the batch. M: . N: , which is smaller.
- Your turn.
5 · On your own
Which logit goes up?
A soft target and a model . With respect to the probabilities, the gradient of is : every entry negative. With respect to the logits it is . Taking one gradient-descent step on the logits, which logits go up?
6 · On your own
The floor for a soft target
With the soft target , you may choose any logits you like. What is the lowest cross-entropy you can approach, in nats? Give three decimal places.
The code
import numpy as np
def softmax(logits):
shifted = logits - logits.max()
exp = np.exp(shifted)
return exp / exp.sum()
def log_softmax(logits):
shifted = logits - logits.max()
return shifted - np.log(np.exp(shifted).sum())
def entropy(p):
p = np.asarray(p, dtype=float)
mask = p > 0
return float(-np.sum(p[mask] * np.log(p[mask])))
def cross_entropy_from_logits(p, logits):
p = np.asarray(p, dtype=float)
log_q = log_softmax(logits)
return float(-np.sum(p * log_q))
def finite_difference_grad(loss_fn, logits, eps=1e-6):
logits = np.asarray(logits, dtype=float)
out = np.zeros_like(logits)
for k in range(logits.size):
plus = logits.copy()
minus = logits.copy()
plus[k] += eps
minus[k] -= eps
out[k] = (loss_fn(plus) - loss_fn(minus)) / (2 * eps)
return out
# Shapes: p, logits, q, and grad_logits are all (K,).
p = np.array([0.70, 0.20, 0.08, 0.02])
logits = np.array([1.2, 0.4, -0.3, -1.1])
log_q = log_softmax(logits)
q = softmax(logits)
ce = cross_entropy_from_logits(p, logits)
h = entropy(p)
kl = ce - h
grad_logits = q - p
numeric_grad = finite_difference_grad(lambda z: cross_entropy_from_logits(p, z), logits)
print("q:", np.round(q, 3))
print("H(p,q):", round(ce, 4))
print("H(p):", round(h, 4))
print("KL(p||q):", round(kl, 4))
print("gradient wrt logits:", np.round(grad_logits, 3))
print("finite-difference grad:", np.round(numeric_grad, 3))
print("gradient check:", np.allclose(grad_logits, numeric_grad, atol=1e-6))
# For a one-hot target y=0, the same formula becomes NLL.
y = 0
one_hot = np.eye(4)[y]
print("one-hot CE:", round(cross_entropy_from_logits(one_hot, logits), 4))
print("-log q_y:", round(float(-log_q[y]), 4))
p is a soft target and q the softmax of the logits; these are different numbers from the figure, so that no target weight is zero. The printout shows H(p,q) splitting into H(p) + KL(p||q), and a finite-difference check confirming that the logit gradient is q - p.
Keep it
You add 3 to every logit. What happens to the cross-entropy, and why?
Answer from memory, then check
Nothing. Softmax divides by the total, so a shared cancels. Only the gaps between logits matter.
With a one-hot target and finite logits, can the loss ever reach exactly 0?
Answer from memory, then check
No. is positive for every finite logit, so every wrong word keeps a sliver of probability and the right word stays below 1. The loss always rewards a little more confidence.
Which costs more, 90% on a wrong word or 25% on each of four words? Why?
Answer from memory, then check
The confident mistake. It leaves the right word at most 10%, a loss of at least nats; honest doubt costs . The loss has no ceiling as the right word's probability falls.
What is the gradient of cross-entropy with respect to the logits, and what does it say about the rivals?
Answer from memory, then check
, the model's probabilities minus the target's. For a one-hot target, each rival is pushed down by exactly the probability it holds, and the pushes sum to zero: the right word goes up as much as all the rivals go down together.
Two classifiers are right on every example. Can their cross-entropies differ?
Answer from memory, then check
Yes. Cross-entropy scores the probability each gave to the right answer, not only whether that answer came out on top. The one that was more confident where it was right has the lower loss.
For a soft target , why can't the cross-entropy reach 0, and what is the gap above its floor called?
Answer from memory, then check
The floor is , the uncertainty the target itself contains, reached only when . The remainder, , is the KL divergence .
Recalling an answer from memory makes it last longer than rereading it (Roediger and Karpicke, 2006). Add these 6 cards and they come back tomorrow, then after gaps of 3, 7, 16, 35 and 75 days while you still remember them. They stay in this browser only.
The edge
The loss is exact; what it buys is less settled. Next-token cross-entropy falls smoothly, as a power law, as language models grow in size, data and compute (Kaplan et al., 2020). Later fits add a floor the loss approaches but never crosses (Hoffmann et al., 2022), read as the entropy of text itself: the of language, which nobody can measure directly. Shannon (1951) could only bound it for English. Whether a smooth fall in loss means a smooth rise in ability is still argued (Schaeffer et al., 2023). And although the loss is minimised by honest probabilities, large networks trained on it are often overconfident (Guo et al., 2017), so how best to keep a model's confidence honest remains an open question.