All courses

Cross-entropy and KL divergence

Derive H(p,q) = H(p) + KL(p‖q). Explain why minimizing cross-entropy against data is the same as minimizing KL, and why KL is asymmetric.

Builds on: Surprisal and entropy, What training does

▶ Watch this lesson Start the whole course

What the animation says

The loss has a floor

Training loss is the model's average surprise at the real next token. A token the model rated likely costs little. A long shot costs a lot. Take the simplest text there is: a fair coin, heads or tails, half and half. Even a perfect model, saying fifty-fifty, pays about zero point six nine on every flip. That is the coin's own unpredictability. No model gets under it. Now a model bets eighty percent heads on this same fair coin. What happens to its average loss?

Paying with the wrong odds

It goes above. Here's the bill. Half the flips are heads. The model gave heads point eight, so each costs only point two two. The other half are tails, which the model rated just point two. Each of those costs one point six one. Average them and you get point nine two. That's the cross-entropy: reality, scored with the model's odds. Split it. Point six nine is the coin's entropy, the floor. The extra point two two is the KL divergence, the model's mismatch.

Floor plus mismatch

That split isn't a quirk of the coin. It always works. Write the cross-entropy as a sum. Then add and subtract log p inside it. It falls apart into two pieces: the entropy of the data, plus the KL divergence. KL is never negative, and it's zero only when the model matches the truth exactly. The entropy belongs to the text, so training can't touch it. The expected loss can never drop below it. Here the entropy is two point four, and the loss drops from three point one to two point seven. Tap the part that shrank.

KL has a direction

KL compares two distributions, but it isn't symmetric. On our coin, averaging over the model instead of the truth gives point one nine, not point two two. Now meet a model that nearly rules out tails. It says ninety-nine point nine percent heads. But tails really happen half the time. Which direction of KL blows up?

What training punishes

Truth to model comes to two point seven six. The other way is just point six nine. Averaged over real flips, every tail costs the log of point five over point zero zero one. That's about six nats each. Averaged over the model, tails get weight point zero zero one, so they barely count. Training averages over real text, so it minimizes KL from data to model. Calling real text nearly impossible is the costliest mistake. So the model learns to cover everything the data does.

What is the loss actually measuring?

Training loss is the average surprisal $-\log q(x)$ of the real next tokens under the model's predicted distribution $q$. On natural text it never reaches 0, even for a perfect model. So how much of the loss is the model's fault, and how much is the text's own unpredictability? And why does pushing this number down make $q$ match the true distribution of text, rather than something else?

Scoring reality with the wrong odds

Say real next tokens come from a true distribution $p$, and the model predicts $q$. Averaging $-\log q(\text{actual token})$ over real text estimates the expected surprisal under $q$ when outcomes really follow $p$. That is the **cross-entropy** $H(p,q)$. If $q = p$, you pay exactly the **entropy** $H(p)$, the irreducible part. Any mismatch costs extra nats on average. That extra is the **KL divergence** $\mathrm{KL}(p\|q)$.

Deriving H(p,q) = H(p) + KL(p‖q)

$$H(p,q) = -\sum_x p(x)\log q(x)$$ Add and subtract $\log p(x)$ inside the sum: $$= -\sum_x p\log p + \sum_x p\log\frac{p}{q} = H(p) + \mathrm{KL}(p\|q)$$ $\mathrm{KL}\ge 0$, and it is $0$ only when $q=p$ (Gibbs' inequality). $H(p)$ is fixed by the data and does not depend on the model at all. So lowering the expected loss lowers KL by exactly the same amount, and the expected loss can never go below $H(p)$. The loss measured on a large sample of real text estimates this expected value.

Two outcomes, actual numbers

Truth $p=(0.5,0.5)$. Model $q=(0.8,0.2)$. - $H(p) = \ln 2 = 0.693$ - $H(p,q) = -0.5\ln0.8 - 0.5\ln0.2 = 0.5(0.223)+0.5(1.609) = 0.916$ - $\mathrm{KL}(p\|q) = 0.5\ln\tfrac{0.5}{0.8}+0.5\ln\tfrac{0.5}{0.2} = -0.235+0.458 = 0.223$ Check: $0.693 + 0.223 = 0.916$. ✓ Reverse: $\mathrm{KL}(q\|p) = 0.8\ln1.6 + 0.2\ln0.4 = 0.376-0.183 = 0.193 \ne 0.223$.

Why KL is asymmetric

$\mathrm{KL}(p\|q)$ averages over $p$. An outcome that really happens but that $q$ nearly rules out costs $\log\frac{p}{q}$, which is huge. If $q$ gives it exactly 0, the cost is infinite. Outcomes with $p(x)=0$ contribute nothing (using $0\cdot\log 0 = 0$). $\mathrm{KL}(q\|p)$ averages over $q$ instead, so it barely notices outcomes that $q$ ignores. Training minimizes $\mathrm{KL}(\text{data}\|\text{model})$. It therefore punishes the model hardest for calling real text nearly impossible, which pushes the model to spread probability over everything the data does.
import numpy as np
H  = lambda a: -(a*np.log(a)).sum()
CE = lambda a, b: -(a*np.log(b)).sum()
KL = lambda a, b: (a*np.log(a/b)).sum()
p = np.array([0.5, 0.5]); q = np.array([0.8, 0.2])
print(H(p), CE(p, q), KL(p, q))  # 0.693 0.916 0.223
print(KL(q, p))                  # 0.193, not 0.223
q2 = np.array([0.999, 0.001])    # model nearly rules out a real outcome
print(KL(p, q2), KL(q2, p))      # 2.76 vs 0.69

Remember

$H(p,q) = H(p) + \mathrm{KL}(p\|q)$: the loss is the data's irreducible entropy plus the model's mismatch. Because $H(p)$ is fixed, minimizing the expected loss on real text is exactly minimizing $\mathrm{KL}(\text{data}\|\text{model})$. That direction heavily penalizes giving near-zero probability to things that really occur. $\mathrm{KL}(q\|p)$ is a different quantity with different preferences.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.