Information theory: entropy, cross-entropy and KL divergence
Why cross-entropy is the loss of almost everything
Cross-entropy is the loss that trains classifiers (4.3 Loss functions catalog), language models (7.6 Decoder-only: GPT and autoregressive generation) and the reward models of RLHF (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI); KL divergence is the penalty that keeps a fine-tuned model close to its base (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI) and the regularizer inside a VAE (8.8 Generative models I: VAEs and GANs); perplexity is how language models have been scored for fifty years (6.2 Classical NLP and n-gram language models). All of them come from one idea — the amount of surprise in an outcome — and this lesson shows how, including why minimizing cross-entropy is the same thing as maximum likelihood.
You'll be able to
- Define surprise, entropy, joint and conditional entropy and mutual information, and compute them for small distributions
- Define cross-entropy and KL divergence, prove KL ≥ 0, and explain the asymmetry of KL
- Show that minimizing cross-entropy equals minimizing KL to the data distribution equals maximum likelihood
- Interpret perplexity as an effective branching factor and connect entropy to compression
Key ideas
- Information content I(x) = −log p(x); entropy H(p) = E[−log p] is expected surprise and the minimum average code length; it is maximal (log K) for the uniform distribution.
- Conditional entropy H(Y|X) = H(X,Y) − H(X); mutual information I(X;Y) = H(X) − H(X|Y) ≥ 0 captures any dependence, not only linear.
- Cross-entropy H(p, q) = E_p[−log q] ≥ H(p); for a one-hot target it is −log q(y), the classification loss.
Show 4 more key ideas
- KL(p‖q) = H(p, q) − H(p) ≥ 0 (Gibbs), asymmetric: KL(p‖q) is mass-covering, KL(q‖p) is mode-seeking.
- Cross-entropy = H(data) + KL(data‖model), so minimizing cross-entropy = minimizing KL = maximum likelihood; H(data) is the irreducible floor.
- Perplexity = exp(mean NLL) = 2^H bits: an effective branching factor; compare only across the same tokenizer.
- Worked: p = (.5, .25, .25), q uniform: H(p) = 1.5 bits, KL(p‖q) = 0.085, KL(q‖p) = 0.082.
Suggested path through this lesson
Surprise and entropy
How surprised should you be by an outcome with probability ? Shannon's answer is the information content : certain events carry no information, rare events carry a lot, and independent surprises add because probabilities multiply. In base 2 the unit is the bit; with natural logarithms it is the nat ( bits). The entropy of a distribution is its expected surprise,
with the convention . A fair coin has bit; a coin with has bits; a fair die has bits. Entropy is maximized by the uniform distribution ( for outcomes) and is zero for a certain outcome. Operationally, is the minimum average number of bits needed to encode outcomes drawn from — the reason entropy and compression are the same subject.
Intuition. Entropy measures how many yes/no questions you need, on average, to pin down the outcome. A good language model asks few questions per token because it already knows a lot.
Joint and conditional entropy, mutual information
For two variables, the joint entropy and the conditional entropy is the surprise left in once is known. Mutual information,
is how many bits knowing one variable saves you about the other; it is zero exactly when they are independent and, unlike correlation, captures nonlinear dependence. Decision trees split on it under the name information gain (3.8 Decision trees), and contrastive objectives such as InfoNCE are lower bounds on it (5.8 Self-supervised and contrastive learning).
Cross-entropy: coding with the wrong model
Suppose outcomes come from but you designed your code — or your model — around . You pay on average
the cross-entropy, and with equality only when . In machine learning is the data (for one labeled example it is the one-hot distribution on the true class ) and is the model's predicted distribution, so the per-example cross-entropy collapses to : the negative log-probability the model gave the right answer. That is the loss of 4.3 Loss functions catalog.
KL divergence: the excess cost
The gap between coding with and coding optimally is the Kullback–Leibler divergence:
It is non-negative (Gibbs' inequality) and zero only when ; it is not symmetric and does not satisfy the triangle inequality, so it is a divergence, not a distance. The two directions mean different things. Minimizing over (the direction of maximum likelihood) is mass-covering: must put probability wherever does, or pay . Minimizing is mode-seeking: may ignore parts of but must not put mass where is near zero — the direction used in variational inference (8.8 Generative models I: VAEs and GANs) and in the KL penalty of RLHF, which keeps the policy from drifting to text the reference model finds absurd (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI).
Math check (Gibbs' inequality). Using : . ✓ Equality needs everywhere.
Cross-entropy minimization is maximum likelihood
Let the data come from and the model be . The expected negative log-likelihood is the cross-entropy, and the cross-entropy splits as
The entropy of the data does not depend on . Therefore minimizing cross-entropy, minimizing KL to the data distribution and maximizing likelihood (1.7 Probability II: Bayes, independence, MLE and MAP) are the same optimization. The irreducible floor is why a loss never reaches zero on genuinely uncertain data — and why the best possible language model still has nonzero loss.
Perplexity
Language models report perplexity, the exponentiated average negative log-likelihood per token:
A perplexity of 10 means the model is, on average, as uncertain as if it were choosing uniformly among 10 equally likely tokens — an effective branching factor. Halving perplexity is a huge improvement; a difference of 0.1 is small. Perplexity depends on the tokenizer, so only compare models that share one (6.1 Text to numbers: tokenization, 6.2 Classical NLP and n-gram language models).
Worked example
Let and , in bits.
- bits; bits.
- bits, so bits.
- bits — close, but not equal: the asymmetry is real.
- Perplexity of a model that assigns to data distributed as : ; the optimal model achieves .
import numpy as np
p, q = np.array([.5, .25, .25]), np.ones(3) / 3
H = lambda p: -(p * np.log2(p)).sum()
CE = lambda p, q: -(p * np.log2(q)).sum()
print(H(p), CE(p, q), CE(p, q) - H(p), CE(q, p) - H(q)) # 1.5 1.585 0.085 0.082
Where information theory appears in the path
| idea | where | role |
|---|---|---|
| cross-entropy loss | 3.3 Logistic regression and softmax classification, 4.3 Loss functions catalog, 7.6 Decoder-only: GPT and autoregressive generation | the training objective of classifiers and language models |
| perplexity | 6.2 Classical NLP and n-gram language models, 8.7 Evaluating LLMs | evaluating language models |
| information gain | 3.8 Decision trees | choosing decision-tree splits |
| KL penalty | 8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI | keeping an RLHF policy near its reference model |
| KL term of the ELBO | 8.8 Generative models I: VAEs and GANs | regularizing a VAE's latent space |
| InfoNCE | 5.8 Self-supervised and contrastive learning, 9.2 Embeddings deep dive | contrastive learning as a mutual-information bound |
| temperature and entropy | 8.5 Decoding and sampling | sampling settings reshape the next-token distribution |
| soft targets | 8.2 Fine-tuning and PEFT | knowledge distillation minimizes KL to a teacher |
Where this shows up later
- Loss functions as negative log-likelihoods — 4.3 Loss functions catalog; perplexity and n-gram models — 6.2 Classical NLP and n-gram language models; GPT's objective — 7.6 Decoder-only: GPT and autoregressive generation.
- KL in alignment and in variational autoencoders — 8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI, 8.8 Generative models I: VAEs and GANs; contrastive objectives — 5.8 Self-supervised and contrastive learning; decoding temperature — 8.5 Decoding and sampling.
- Information gain in trees — 3.8 Decision trees; maximum-entropy view of the Gaussian — 1.6 Probability I: random variables and distributions.
Common pitfalls (4)
- Mixing bits and nats (log₂ vs ln) and getting entropies off by a factor of 1.443.
- Treating KL as a distance — it is asymmetric and can be infinite when q is zero where p is not.
- Expecting a cross-entropy loss to reach zero on noisy labels; the entropy of the data is a hard floor.
- Comparing perplexities of models with different tokenizers or different test sets.
Recap: all 7 key points
- Information content I(x) = −log p(x); entropy H(p) = E[−log p] is expected surprise and the minimum average code length; it is maximal (log K) for the uniform distribution.
- Conditional entropy H(Y|X) = H(X,Y) − H(X); mutual information I(X;Y) = H(X) − H(X|Y) ≥ 0 captures any dependence, not only linear.
- Cross-entropy H(p, q) = E_p[−log q] ≥ H(p); for a one-hot target it is −log q(y), the classification loss.
- KL(p‖q) = H(p, q) − H(p) ≥ 0 (Gibbs), asymmetric: KL(p‖q) is mass-covering, KL(q‖p) is mode-seeking.
- Cross-entropy = H(data) + KL(data‖model), so minimizing cross-entropy = minimizing KL = maximum likelihood; H(data) is the irreducible floor.
- Perplexity = exp(mean NLL) = 2^H bits: an effective branching factor; compare only across the same tokenizer.
- Worked: p = (.5, .25, .25), q uniform: H(p) = 1.5 bits, KL(p‖q) = 0.085, KL(q‖p) = 0.082.
Watch
The best introduction to bits, surprise and expected information — through a game.
Read
Try it live
Interactive demo
runs in your browserExercises
- By hand: entropies and divergences
Compute, in bits, the entropy of a weather distribution (sun, cloud, rain), the cross-entropy of a forecaster who always predicts , and both KL divergences. Then compute the perplexity of each forecaster. Expected: bits; the forecaster's cross-entropy is about bits; KL(p‖q) ≈ 0.122 and KL(q‖p) ≈ 0.145 bits; perplexities ≈ 2.23 vs 2.43.
- NumPy: verify Gibbs' inequality by brute force
Implement
entropy,cross_entropyandklfor discrete distributions. Sample 10,000 random pairs of distributions over 5 outcomes (normalize random positive vectors) and confirm KL is never negative and that KL(p‖q) ≠ KL(q‖p) in general. Expected: minimum KL ≈ 0, reached only when p ≈ q. - Experiment: perplexity of a unigram model
Take any long text file, split into words, and fit a unigram model on the first 80% (relative frequencies with add-one smoothing). Compute the average negative log-likelihood and the perplexity on the last 20%. Then repeat with a bigram model using the chain rule from 1.7. Expected: the unigram perplexity is in the hundreds to thousands; the bigram model is substantially lower — context reduces surprise.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →