Lesson 1.9core2 h 30 min⚡ live demo

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

  1. 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.
  2. 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.
  3. 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
  1. KL(p‖q) = H(p, q) − H(p) ≥ 0 (Gibbs), asymmetric: KL(p‖q) is mass-covering, KL(q‖p) is mode-seeking.
  2. Cross-entropy = H(data) + KL(data‖model), so minimizing cross-entropy = minimizing KL = maximum likelihood; H(data) is the irreducible floor.
  3. Perplexity = exp(mean NLL) = 2^H bits: an effective branching factor; compare only across the same tokenizer.
  4. 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