Lesson 9 of 117 min
Cross-entropy and KL divergence
A model pays its surprise at what really came; averaged, that is cross-entropy, the loss language models train on, and KL is the part it could have avoided.
After this lesson you can compare a predicted distribution with the true one.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Work out the cost and the extra cost
Run the cells in order. Cross-entropy averages the model's cost using the truth's chances p. Its formula is −Σ p log(q). KL measures the extra cost above using the truth's own chances, Σ p log(p/q). These logs give nats.
import torch
import torch.nn.functional as F
p = torch.tensor([0.5, 0.5])
q = torch.tensor([0.9, 0.1])
cross = -(p * q.log()).sum()
extra = (p * (p / q).log()).sum()
print(f"Cross-entropy: {cross:.4f} nats")
print(f"KL: {extra:.4f} nats")Cross-entropy: 1.2040 nats KL: 0.5108 nats
Pass scores to cross-entropy
For a classifier, give F.cross_entropy the raw scores and the index of the right class. It applies log-softmax to the scores internally. You can check the result by asking for the surprise of that one class.
scores = torch.tensor([[2.0, 0.5, -1.0]])
target = torch.tensor([0])
loss = F.cross_entropy(scores, target)
surprise = -scores.softmax(dim=1)[0, 0].log()
print(f"Loss {loss:.4f}, surprise {surprise:.4f} nats")Loss 0.2413, surprise 0.2413 nats
Keep the class count out of KL
PyTorch wants the model's log-chances first and the target chances second. The default in this run, mean, divides by every entry. PyTorch warns that this behavior is slated to change. Use batchmean to add over classes and average across examples.
mean = F.kl_div(q.log()[None, :], p[None, :])
per_example = F.kl_div(q.log()[None, :], p[None, :], reduction="batchmean")
print(f"Default mean: {mean:.4f}, batchmean: {per_example:.4f}")Default mean: 0.2554, batchmean: 0.5108
Line up next-token targets
For plain text with no start token, the first position predicts the second token. Shift the targets one place left and drop the final prediction because there's no next token in the text. The first token is context and has no target position of its own.
tokens = ["Once", "upon", "a", "time"]
for context, next_token in zip(tokens[:-1], tokens[1:]):
print(f"After {context!r}, score the chance of {next_token!r}")After 'Once', score the chance of 'upon' After 'upon', score the chance of 'a' After 'a', score the chance of 'time'
Run on Python 3.13.3 and PyTorch 2.15.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Entropy
A model picks its next word from three. "Time" has a chance of 0.5, and two other words have 0.25 each. What is its entropy, in bits?
2 of 3
Two models guess the next word, and both guess wrong. Model X gave the word that came a chance of 0.01: it was sure of another word. Model Y gave it 0.25. Which pays more?
3 of 3
A coin is fair. A model says it lands heads 3 times in 4. Heads costs the model 0.42 bits, and tails costs 2 bits. How many bits a toss is its KL divergence?
The ideas in this lesson
- Cross-entropy
- The average surprise at what really happened, scored by the model's chances: the loss language models are trained on.
- KL divergence
- The extra surprise from using the model's chances instead of the true ones: cross-entropy minus the truth's own entropy.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
The same cost?
Here's a question. A chatbot guesses each next word as it reads. Sometimes its guess is wrong. One time it's a little unsure. Another time it's very sure. Should those two mistakes cost the same?
Your guess
Here's a real model reading a sentence.
"Once upon a time, there was a little girl."
At "girl", its top guess was "boy". It gave "girl" a chance of zero point one three.
After "girl", it was ninety-four percent sure the next word would be "named". But the sentence ends with a period, the dot that ends a sentence. It gave the period a chance of less than two in ten thousand. Two wrong guesses. Should they cost the same?
The price of a word
Score a guess by the chance the model gave the word that actually came. Take its surprise: the halvings from one down to that chance. A chance of a quarter is two halvings: two bits.
"Girl" got about zero point one three, close to an eighth: about three bits. The period got less than two in ten thousand: twelve point six bits.
More than four times as much. That's what the model pays for each word: its loss there.
Sure and right, sure and wrong
Think of a quiz where you also say how sure you are.
When the model was sure and right, it pays almost nothing. "Time" got a chance of almost one. Zero bits.
Sure and wrong pays the most. A chance of zero point zero one costs six point six bits.
Less than two in ten thousand costs twelve point six.
And unlike a quiz, the cost keeps growing as the chance gets close to zero. It has no limit.
A right-or-wrong score can't see any of this. It counts "girl" and the period as one miss each.
Cross-entropy
Now the whole sentence. Average what the model paid for every word after the first. That's ten, with the comma and the period. Two point one nine bits a word. That average has a name. The model's average surprise at the words that actually came... is called the cross-entropy.
Every language model is trained to make this loss smaller, on huge amounts of text.
Have you met it?
Is that a new kind of number?
Each word's chance came from the words before it. Multiply all ten, and you get how likely the model thought the whole sentence was. Cross-entropy is minus the log of that, divided by the ten words. That's the negative log-likelihood, averaged over the words. So making it smaller makes the real text more likely.
The floor
Can a perfect model pay zero?
Not when the truth itself is uncertain. Real text is like that: after "there was a little", many words could come.
A fair coin shows it clearly. A model that knows the coin is fair pays one bit a toss.
That's the coin's own entropy.
KL divergence
The coin stays fair. Now take a model that thinks it lands heads ninety times in a hundred. Heads costs it zero point one five bits. Tails costs three point three two.
Each comes up half the time, so it pays one point seven four bits a toss.
Try any other model: none pays less than one.
One bit is the coin's own. The other zero point seven four is the price of the wrong chances. That extra... is called the KL divergence.
So the cross-entropy is the coin's own entropy, plus the KL.
Swap them
So is KL a distance between the coin and the model? Then swapping them wouldn't change it.
Swap them: a coin that really lands heads ninety times in a hundred, and a model that says it's fair.
Now KL is zero point five three, not zero point seven four.
So no, it's not a distance. KL is the price of using the model's chances instead of the true ones, and the order matters.
Copying a model's chances
Here's one place KL is used. Small models are often trained to copy a big model. At each word, the big model gives a chance for every word that could come next. The small model learns from all those chances, not only from the one word that came.
Now the big model's chances act as the truth, and their entropy never changes. So when the small model's loss gets smaller, it's the KL that shrinks: the small model's chances move toward the big one's.
In code
Now in real code. The model reads the sentence, and its loss gives what it paid on average. What will it print?
You might expect two point one nine.
It prints one point five two.
PyTorch counts in another unit, called nats.
One bit is about zero point six nine three nats. Divide by that: two point one nine bits. Our number.
Then KL for the coin, in bits again: zero point seven four. PyTorch's KL takes the model's chances first, as their logs, and the truth second. The other way around, you get the other KL.
The part you could avoid
So a model pays its surprise at what actually came. Averaged, that's the cross-entropy, the loss a language model trains on. And KL is the part above the truth's own entropy: the part a better model could avoid.
The lab
That's the end of this unit. In its lab, you use these three lessons to score a real model's guesses, in bits.
Sure and wrong
A model pays the most for being sure and wrong. Now try it on this lesson's page, and take the quiz. Make the coin unfair, then find the model that pays the least.
You use this lesson in Lab 3: Score a language model's guesses, which comes next.
Facts last checked on .
