- Compute self-information, entropy, cross-entropy and KL divergence in bits and nats.
- Explain why minimizing cross-entropy is equivalent to minimizing KL divergence and to maximum likelihood.
- Derive the gradient of softmax cross-entropy with respect to the logits.
- Compute and interpret perplexity for a language model and state its limitations.
- Apply temperature to logits and predict its effect on sampling and calibration.
- Implement a numerically stable log-softmax and cross-entropy in NumPy.
Before this: Probability and Statistics for AI, Calculus and Gradients: How Networks Learn
Nearly every classifier and every language model is trained by minimizing one number: the cross-entropy between the data and the model's predicted distribution. Language models are compared by perplexity; distillation and RLHF use KL divergence; sampling is controlled by temperature on logits. All of these come from information theory, the mathematics of uncertainty and surprise that Claude Shannon introduced in 1948. This lesson derives them from one idea, connects them to maximum likelihood, and shows how to compute them without numerical overflow.
Intuition: surprise is measured in bits
If someone tells you the sun rose this morning, you learn almost nothing; if they tell you it snowed in Dallas in July, you learn a lot. Information is surprise, and surprise is high for unlikely events. A good predictor is one that is rarely surprised. Cross-entropy is just "the average surprise your model experiences on real data", and training lowers it.
To make this quantitative, imagine sending messages with a code. Frequent symbols should get short codewords and rare ones long codewords (Morse code gives "E" a single dot). Shannon showed that the best possible average codeword length is set by the distribution's entropy, and that using a code designed for the wrong distribution costs extra bits, exactly the KL divergence.
Self-information and entropy
The self-information (surprisal) of an outcome with probability is
With it is measured in bits; with the natural log, in nats ( bits). Deep-learning frameworks use natural logs, so losses are in nats. A certain event () carries 0 information; a fair coin flip () carries 1 bit.
The entropy of a distribution is the expected surprisal:
with the convention . For outcomes, ; the minimum is a deterministic distribution, the maximum the uniform one.
Worked example. A fair coin: bit. A biased coin with :
The biased coin is more predictable, so it has lower entropy. Where entropy appears in AI: decision trees split on information gain (reduction in entropy); reinforcement-learning algorithms add an entropy bonus to keep policies exploring; and the entropy of a model's predictive distribution is a simple uncertainty signal (high entropy over next tokens often accompanies an LLM being unsure).
Cross-entropy
If data truly come from but you predict with a model , your average surprise is the cross-entropy
In classification, the "true distribution" for one example is a one-hot vector: all mass on the correct class . The sum then collapses to a single term:
So cross-entropy loss is simply the negative log of the probability the model assigned to the correct answer. Worked example: three classes, true class 0, prediction : nats. If instead , : confident wrong answers are punished heavily, and as the loss goes to infinity. Over a dataset you average: , which is exactly the negative log-likelihood from the probability lesson.
KL divergence
The Kullback–Leibler divergence measures the extra surprise from using when the truth is :
Properties: with equality only when (Gibbs' inequality), and it is not symmetric, so it is not a true distance.
Worked example. , , natural logs:
Because does not depend on the model, minimizing cross-entropy over is the same as minimizing . That is the deep reason cross-entropy is the right training objective: it pulls the model distribution toward the data distribution.
Where KL appears: knowledge distillation trains a student to match a teacher's softened output distribution; RLHF and related methods penalize the KL divergence between the fine-tuned policy and the reference model so the model does not drift too far; variational autoencoders include a KL term pulling the latent distribution toward a prior. The direction matters: (forward) heavily penalizes for missing places where has mass, so it is "mass-covering"; (reverse) penalizes for putting mass where has little, so it is "mode-seeking".
Logits and softmax
Networks output unconstrained real numbers called logits . The softmax turns them into a probability distribution:
Every output is positive and they sum to 1. Softmax is invariant to adding a constant to all logits (, the cancels), so only differences between logits matter. For two classes, softmax reduces to the sigmoid of the logit difference.
Worked example. : , , ; sum ; probabilities .
Temperature
Dividing logits by a temperature before the softmax reshapes the distribution:
| scaled logits | probabilities | |
|---|---|---|
| 0.5 | (4, 2, 0.2) | (0.864, 0.117, 0.019) |
| 1 | (2, 1, 0.1) | (0.659, 0.242, 0.099) |
| 2 | (1, 0.5, 0.05) | (0.502, 0.304, 0.194) |
As the distribution approaches the argmax (greedy decoding); as it approaches uniform. When sampling text, low temperature gives focused, repetitive output and high temperature gives diverse, error-prone output. Distillation uses on both teacher and student so the student learns from the relative probabilities of wrong classes ("dark knowledge"), as Hinton, Vinyals and Dean described in 2015. Temperature scaling is also a standard post-hoc calibration method: fit a single on a validation set to make probabilities honest without changing the argmax.
Softmax plus cross-entropy: the gradient
Combine softmax and cross-entropy for one example with logits and one-hot target :
Differentiate with respect to : the first term gives if , and the derivative of the log-sum-exp is . Therefore
The gradient is "prediction minus target", bounded between and per logit, and it never vanishes while the model is wrong. For the example above with true class 0, : raise the correct logit, lower the others. Squared error on top of a softmax or sigmoid lacks this property; its gradient includes the softmax/sigmoid derivative, which goes to zero when the output saturates, so a confidently wrong model learns slowly.
Why cross-entropy for classification and MSE for regression
Both losses fall out of maximum likelihood with different noise models:
- Classification. Model the label as categorical with probabilities . The NLL of the observed label is : cross-entropy. (Binary case: Bernoulli likelihood gives binary cross-entropy .)
- Regression. Model the target as Gaussian around the prediction: . The NLL is ; with fixed, minimizing it is minimizing squared error. If you assume Laplace noise instead, you get mean absolute error, which is more robust to outliers.
Choosing a loss is therefore choosing an assumption about how the data are distributed around the model's prediction.
Perplexity and language models
A language model factorizes the probability of a token sequence by the chain rule of probability, , and is trained to minimize the average per-token cross-entropy
Perplexity is its exponential:
the geometric mean of inverse probabilities. Intuitively, a perplexity of means the model is, on average, as uncertain as if it were choosing uniformly among tokens. A uniform model over a 50,000-token vocabulary has perplexity 50,000; a perfect model has perplexity 1.
Worked example. A model assigns probabilities $0.5, 0.25, 0.125, 0.5$ to four actual tokens. Per-token losses: $0.693, 1.386, 2.079, 0.693$ nats; mean ; perplexity . Check via the geometric mean: .
Caveats: perplexity depends on the tokenizer (a model with a larger vocabulary predicts fewer, harder tokens), so it is only comparable between models sharing a tokenizer and test text. For tokenizer-independent comparison people use bits per byte or bits per character. And lower perplexity does not guarantee better instruction following or reasoning; it measures fit to a text distribution.
Numerically stable log-softmax
Naively computing overflows float32 for above about 88, and taking of a probability that underflowed to 0 gives . The fix uses the shift invariance: with ,
Now the largest exponent is , so nothing overflows, and the sum is at least 1, so the log is safe. This is the log-sum-exp trick.
import numpy as np
def log_softmax(z, axis=-1):
m = z.max(axis=axis, keepdims=True)
return z - m - np.log(np.exp(z - m).sum(axis=axis, keepdims=True))
def cross_entropy(logits, labels): # logits (B, K), labels (B,)
lp = log_softmax(logits)
return -lp[np.arange(len(labels)), labels].mean()
def entropy(p): return -(p * np.log(np.where(p > 0, p, 1))).sum(-1)
def kl(p, q): return (p * (np.log(p) - np.log(q))).sum(-1)
z = np.array([[2.0, 1.0, 0.1]])
for T in (0.5, 1.0, 2.0):
print(T, np.exp(log_softmax(z / T)).round(3))
big = np.array([[1000.0, 1001.0, 1002.0]])
print(np.exp(log_softmax(big)).round(3)) # [[0.09 0.245 0.665]], no overflow
print(round(cross_entropy(z, np.array([0])), 4)) # 0.417 = -log 0.659
print(kl(np.array([.5, .5]), np.array([.9, .1])).round(3),
kl(np.array([.9, .1]), np.array([.5, .5])).round(3)) # 0.511 0.368
# gradient of CE wrt logits equals softmax - onehot (numerical check)
q = np.exp(log_softmax(z))[0]; y = np.array([1., 0., 0.])
eps = 1e-6; num = np.zeros(3)
for k in range(3):
zp, zm = z.copy(), z.copy(); zp[0, k] += eps; zm[0, k] -= eps
num[k] = (cross_entropy(zp, np.array([0])) - cross_entropy(zm, np.array([0]))) / (2 * eps)
print(num.round(4), (q - y).round(4))
probs = np.array([0.5, 0.25, 0.125, 0.5])
print("perplexity", round(np.exp(-np.log(probs).mean()), 3)) # 3.364
Note the loss on the logits is ; the earlier example used the probability directly. Frameworks fuse softmax and log for exactly this stability reason: PyTorch's nn.CrossEntropyLoss and F.cross_entropy take raw logits and apply a stable log-softmax internally, and F.log_softmax exists for when you need log-probabilities.
Common pitfalls
- Applying softmax before a loss that expects logits. Passing probabilities into
CrossEntropyLossapplies softmax twice; the model still trains, but poorly. - Computing
log(softmax(x))in two steps. Use a fused log-softmax or cross-entropy to avoid-infandnan. - Comparing perplexities across tokenizers or datasets. The numbers are not on the same scale.
- Mixing bits and nats. Framework losses are in nats; divide by for bits.
- KL direction errors. and give different gradients and behaviours; check which one a method specifies, and note that
torch.nn.functional.kl_divexpects its first argument as log-probabilities of the model. - Taking
log(0). Add label smoothing, clip probabilities, or work in log space.
In practice
- Train classifiers on logits with fused cross-entropy; use label smoothing (mixing the one-hot target with a little uniform mass) when overconfidence is a problem.
- Report validation loss in nats per token and perplexity for language models, and also bits per byte when comparing different tokenizers.
- Calibrate with a single temperature fitted on held-out data when probabilities drive decisions.
- Tune sampling temperature per task: low values (or greedy decoding) for extraction and code, moderate values for open-ended writing.
- Watch the KL to the reference model during preference fine-tuning; a rapidly growing KL often signals reward hacking.
Key takeaways
- Entropy is the expected surprise of a distribution; cross-entropy is the expected surprise when predicting with a model.
- Minimizing cross-entropy equals minimizing KL divergence from data to model and equals maximum likelihood.
- The gradient of softmax cross-entropy with respect to the logits is simply predicted probabilities minus the one-hot target.
- Cross-entropy follows from a categorical likelihood and MSE from a Gaussian likelihood; the loss encodes a noise assumption.
- Perplexity is the exponential of mean per-token cross-entropy and is only comparable across models with the same tokenizer and data.
- Always compute log-probabilities with the log-sum-exp trick or a fused library function.
Terms in this lesson
- Self-information
- The surprise of an outcome, equal to the negative logarithm of its probability.
- Entropy
- The expected self-information of a distribution, measuring its uncertainty.
- Cross-entropy
- The expected negative log-probability that a model q assigns to outcomes drawn from the true distribution p.
- KL divergence
- A non-negative, asymmetric measure of how much a distribution q differs from p, equal to cross-entropy minus entropy.
- Logits
- The unnormalized real-valued scores a model outputs before a softmax or sigmoid converts them to probabilities.
- Softmax
- The function that exponentiates logits and normalizes them to sum to one, producing a categorical distribution.
- Temperature
- A positive scalar that divides logits before softmax, sharpening the distribution when below 1 and flattening it when above 1.
- Perplexity
- The exponential of the average per-token negative log-likelihood, interpretable as an effective number of equally likely choices.
- Log-sum-exp trick
- Subtracting the maximum logit before exponentiating so that log-softmax and related quantities can be computed without overflow.
Check your understanding
- 1.
A model assigns probability 0.25 to the correct class. What is the cross-entropy loss for that example in bits?
- 2.
Logits (3, 1, 0) with true class 1. What is the gradient of the softmax cross-entropy with respect to the logits, to two decimals?
- 3.
Two language models report perplexities of 8.1 and 9.4 on different test sets with different tokenizers. What can you conclude?
- 4.
You need to predict house prices and believe errors are roughly Gaussian with constant variance. Which loss follows from maximum likelihood?
- 5.
What happens to the softmax distribution as temperature T approaches 0?
Exercises
Work each problem before opening the solution.
- Exercise 1Core
Compute the entropy in bits of the distribution . Then compute the cross-entropy in bits when the model is uniform, , and the KL divergence .
Show solution
bits.
bits.
bits. Interpretation: a code optimized for the uniform model wastes a quarter bit per symbol on data from .
- Exercise 2Core
A language model is evaluated on a 1,000-token text and its summed negative log-likelihood is 2,300 nats. (a) What is the mean loss per token in nats and in bits? (b) What is the perplexity? (c) If a change lowers the mean loss by 0.1 nats per token, what is the new perplexity?
Show solution
(a) nats per token; in bits bits.
(b) .
(c) . A 0.1-nat drop always multiplies perplexity by , a 9.5% reduction.
- Exercise 3Core
Show that for any constant , and use this to explain why computed with the max-subtraction trick is exact rather than an approximation.
Show solution
.
Choosing with therefore leaves the result mathematically unchanged; it only changes which intermediate numbers are computed. Taking logs, is an algebraic identity. The exponents are all , so no overflow occurs, and the sum includes , so the logarithm never sees 0.
- Exercise 4Challenge
Implement knowledge-distillation loss in NumPy: given teacher logits and student logits of shape and temperature , compute the mean over the batch of where and are the teacher's and student's temperature-softened softmax distributions. Use stable log-softmax. Test with teacher and student at and . Explain why the factor is used.
Show solution
import numpy as np def log_softmax(z, axis=-1): m = z.max(axis=axis, keepdims=True) return z - m - np.log(np.exp(z - m).sum(axis=axis, keepdims=True)) def distill_loss(teacher, student, T): lp = log_softmax(teacher / T) # teacher log-probs lq = log_softmax(student / T) # student log-probs kl = (np.exp(lp) * (lp - lq)).sum(axis=-1) return (T ** 2) * kl.mean() t = np.array([[5.0, 2.0, 0.0]]) s = np.array([[3.0, 2.0, 1.0]]) for T in (1.0, 4.0): print(T, round(distill_loss(t, s, T), 4))Output:
1.0 0.2392and4.0 0.7715. At the teacher is about and the student , giving a KL of about 0.239 nats. At both distributions are flatter, teacher and student , so the raw KL is smaller (about 0.048 nats), but multiplied by it becomes about 0.77. The softened view exposes the information in the small logits (how the teacher ranks the wrong classes), which the student currently gets wrong.Why : the gradient of the softened cross-entropy with respect to the student logits is , and for large the difference itself shrinks roughly like , so gradients scale like . Multiplying by keeps the distillation term's gradient magnitude roughly constant as you change , so it stays balanced against the ordinary hard-label loss. This scaling is the one recommended by Hinton, Vinyals and Dean (2015).
Further reading
- bookDive into Deep Learning, Appendix 22.11: Information Theory
- bookDavid J. C. MacKay, Information Theory, Inference, and Learning Algorithms (2003)
- bookIan Goodfellow, Yoshua Bengio, Aaron Courville, Deep Learning (2016), sections 3.13 and 6.2
- paperGeoffrey Hinton, Oriol Vinyals, Jeff Dean, Distilling the Knowledge in a Neural Network (2015)
Go further
Sources
Fact-checked and last reviewed 2026-11-05