Lesson 5.1: The loss: cross-entropy and perplexity
Understand what the training loss measures: cross-entropy as surprise, perplexity as branching factor and the floor set by the language, computed exactly.
By the end of this lesson you will be able to say what the loss of a language model measures, convert it to perplexity and to bits, compute the best loss any model can reach on a language you control, read a model's predictions against the true probabilities, and compute the loss without numerical overflow. You will show that the best possible loss on the toy language is 0.9885 nats per token (perplexity 2.687, 1.426 bits), derived from the grammar alone; that our two-block GPT scores 1.0036 on 2,944 validation tokens (perplexity 2.728), 0.015 above the floor; that its probabilities after "the cat chased the" are 0.397, 0.314 and 0.288 against a true one third each; that its loss on verbs (1.819), adverbs (2.071), full stops (0.395) and determiners (0.795) sits within 0.05 of the ideal values (1.792, 2.120, 0.367 and 0.797); that its top-1 accuracy of 51% equals the ceiling for any model (51%); and that a naive softmax overflows to NaN where the stable one does not. You need Python and NumPy, helpers.py, gpt.py and train.py from earlier lessons, and corpus.py from Lesson 1.1.
Module 4 built a model and trained it, and we reported its "validation loss" as if the number were obvious. This module is about training properly, and it begins with that number. What does the loss measure? What is a good value? How low could it go? A model builder who cannot answer these cannot tell a good run from a bad one. The toy language lets us answer all three exactly.
Loss as surprise
The model reads some tokens and outputs a probability for each possible next token. The next token is revealed. The cross-entropy loss for that one prediction is
loss = minus the natural logarithm of the probability the model gave to the token that actually came.
If the model gave the true token probability 1, the loss is 0: no surprise. If it gave 0.5, the loss is 0.693. If it gave 0.1, the loss is 2.303. If it gave 0.001, the loss is 6.908. The loss grows without bound as the probability the model gave the truth falls to zero, which punishes confident mistakes severely. The training loss is the average over all the tokens in a batch. The unit is the nat, because we use the natural logarithm. With a base-2 logarithm the unit is the bit.
Three reasons for the logarithm. Probabilities of sequences multiply, since the probability of a sentence is the product of the probabilities of its tokens, and logs turn a product into a sum, which is what an average of per-token losses is. Numbers stay manageable: the probability of a long text is astronomically small, while its log is a modest number. And, the deeper reason, the log loss rewards honest probabilities. Of all the ways to score probabilistic predictions in this family, the expected log loss is lowest exactly when the model's probabilities equal the true ones. A model cannot gain by exaggerating its confidence.
Perplexity and bits
A loss of 1.0036 is hard to feel. Two conversions help.
Perplexity is e raised to the loss. It is the loss expressed as an effective number of equally likely choices. A model with perplexity 2.728 is, on average, as unsure as if it were picking among 2.728 equally likely tokens. A uniform guess over 34 tokens has perplexity 34. A model that always knew the answer would have perplexity 1.
Bits per token is the loss divided by the natural log of 2 (0.6931). It is the average number of bits needed to encode a token using the model's probabilities, which is how a compressor would use it. A loss of 1.0036 nats is 1.448 bits per token. Compare that with the naive code for 34 tokens: log₂ 34 = 5.09 bits. The model compresses the text to about 28% of the naive size.
The floor: the entropy of the language
How low can the loss go? Not to zero, since the language is random: after "the cat chased the", the next word is one of three, and no model can know which. There is a floor, called the entropy of the source, which is the average surprise of the true probabilities. A model that knew them exactly would reach the floor and could never go below it, on average.
For the toy language we can compute it, because the generator in Lesson 1.1 makes every choice uniformly at random. A sentence picks one of 8 subjects, one of 6 verbs, one of 6 objects, then an adverb with probability 0.6, and if so one of 5. The entropy of a sentence is the sum of the logs of the choices. Divide by the number of tokens per sentence, and we have the floor per token.
python
import numpy as np
subj = ["the cat", "the dog", "a bird", "the child", "my teacher", "the farmer", "a fox", "the baker"]
verb = ["chased", "watched", "found", "followed", "liked", "saw"]
obj = ["the ball", "a fish", "the red bus", "a small boat", "the old tree", "a loud drum"]
adv = ["quickly", "slowly", "today", "again", "at night"]
words = lambda phrases: np.mean([len(p.split()) for p in phrases])
Every choice in the generator is uniform, so the entropy of a sentence is a sum of logs.
padv = 0.6
sentencenats = (np.log(len(subj)) + np.log(len(verb)) + np.log(len(obj))
+ (-padv np.log(padv) - (1 - padv) np.log(1 - padv)) # adverb or not
+ padv np.log(len(adv))) # which adverb
tokens = words(subj) + 1 + words(obj) + padv words(adv) + 1 # words per sentence, with the full stop
print("nats per sentence:", round(float(sentencenats), 4), " tokens per sentence:", round(float(tokens), 4))
floor = sentencenats / tokens
print("best possible loss per token:", round(float(floor), 4), " perplexity:", round(float(np.exp(floor)), 3))
print("bits per token:", round(float(floor / np.log(2)), 3))
the ideal loss for each kind of target, from the grammar alone
print("verbs: ", round(float(np.log(len(verb))), 3)) # one of six, equally likely
print("an adverb: ", round(float(-np.log(padv / len(adv))), 3)) # 'quickly' has probability 0.6 / 5 = 0.12 after an object
print("full stop: ", round(float(0.4 -np.log(0.4)), 3), "(averaged: 0.4 of the full stops follow an object, the rest follow an adverb)")
head = lambda p: -(p np.log(p)).sum()
starts = head(np.array([5, 2, 1]) / 8) # 'the' for five subjects, 'a' for two, 'my' for one
print("determiners: ", round(float((starts + np.log(2)) / 2), 3), "(half at the start of a subject, half at the start of an object)")
The first lines of the output:
nats per sentence: 7.3016 tokens per sentence: 7.3867
best possible loss per token: 0.9885 perplexity: 2.687
bits per token: 1.426
The best possible loss is 0.9885 nats per token: perplexity 2.687, or 1.426 bits. Lesson 1.1 quoted 0.988, found by a different route (counting). This is the same number worked out from the generator. No model, however large, can beat it on average on this language. A reported loss below 0.9885 is a bug, as Lesson 3.3 showed. The last four lines of the output work out the ideal loss for each kind of token, and we will use them below.
The gap between a model's loss and the floor has a name. It is the Kullback-Leibler divergence between the true distribution and the model's: the extra surprise the model suffers because its probabilities differ from the true ones. In symbols: cross-entropy equals entropy plus KL divergence. The entropy is fixed by the language. The divergence is what training reduces, and it is zero only when the model is exactly right.
What the model learned
We train the two-block model of Lesson 4.3 and look inside. The code saves the model as base.npz, which Lesson 5.3 uses again. For some contexts it prints the model's top predictions, and then it computes the loss over all the validation tokens, split by the kind of token being predicted.
python
from train import
p, = train() # the two-block model of Lesson 4.3
np.savez("base.npz", p)
Pos = sinusoidal(T, 32)
def probsfor(context):
ids = np.array([[stoi[w] for w in context.split()]])
logits, = gptfwd(p, ids, 2, 2, Pos)
return softmax(logits[0, -1])
def show(context, k=6):
pr = probsfor(context)
top = np.argsort(-pr)[:k]
print(f"after '{context}':", ", ".join(f"{vocab[i]} {pr[i]:.3f}" for i in top))
show(". the cat chased the", 3) # three objects start with 'the': ball, red, old -> 1/3 each
show(". the cat", 6) # six verbs -> 1/6 each
show(". the cat chased the ball", 6) # a full stop 0.4, five adverbs 0.12 each
show(". the", 8) # the cat, the dog, the child, the farmer, the baker -> but 'the' is shared by 5 of 8 subjects
average loss by kind of target, over all non-overlapping validation windows
n = (len(valids) - 1) // T
x = valids[: n T].reshape(n, T); y = valids[1 : n T + 1].reshape(n, T)
logits, = gptfwd(p, x, 2, 2, Pos)
P = softmax(logits)
nll = -np.log(P[np.arange(n)[:, None], np.arange(T)[None, :], y])
print("loss over", n T, "validation tokens:", round(float(nll.mean()), 4), " perplexity:", round(float(np.exp(nll.mean())), 3))
print("top-1 accuracy:", round(float((P.argmax(-1) == y).mean()), 3))
for name, group in {"full stop": ["."], "adverbs": ["quickly", "slowly", "today", "again", "at night"][:4],
"verbs": ["chased", "watched", "found", "followed", "liked", "saw"], "determiners": ["the", "a", "my"]}.items():
mask = np.isin(y, [stoi[w] for w in group])
print(f"{name:12s} {mask.sum():4d} tokens, average loss {nll[mask].mean():.3f}")
The output:
after '. the cat chased the': red 0.397, ball 0.314, old 0.288
after '. the cat': followed 0.195, liked 0.184, watched 0.163, found 0.162, saw 0.156, chased 0.140
after '. the cat chased the ball': . 0.346, quickly 0.150, today 0.144, at 0.129, again 0.122, slowly 0.109
after '. the': cat 0.246, farmer 0.201, dog 0.190, child 0.183, baker 0.179, red 0.000, fox 0.000, ball 0.000
loss over 2944 validation tokens: 1.0036 perplexity: 2.728
top-1 accuracy: 0.51
full stop 397 tokens, average loss 0.395
adverbs 193 tokens, average loss 2.071
verbs 396 tokens, average loss 1.819
determiners 793 tokens, average loss 0.795
Compare each with the truth.
After "the cat chased the", the object must be "ball", "red bus" or "old tree": a third each. The model gives 0.314, 0.397 and 0.288, close, with the small errors that finite training leaves.
After "the cat", any of six verbs is equally likely: one sixth, 0.167 each. The model gives between 0.140 and 0.195.
After a complete object, the sentence ends (probability 0.4) or an adverb follows (0.6 shared among five, 0.12 each). The model gives 0.346 and about 0.11 to 0.15.
After "the" at the start of a sentence, the subject is one of five nouns, 0.2 each (the other three subjects begin "a" or "my"). The model gives 0.246 to 0.179 for those five and 0.000 for the impossible ones.
The model has learned the grammar and the frequencies from examples alone.
Kind of token · Model's average loss · Ideal loss from the grammarVerbs · 1.819 · 1.792
Adverbs (four of them) · 2.071 · 2.120
Full stops · 0.395 · 0.367
Determiners · 0.795 · 0.797
The ideal values come straight from the grammar. A verb is one of six equally likely, so its loss is ln 6 = 1.792. A particular adverb has probability 0.6 times one fifth, 0.12, so its loss is minus the log of 0.12, 2.120. A full stop follows an object 40% of the time and then has probability 0.4; otherwise it follows an adverb and is certain. The average is 0.4 times minus the log of 0.4, 0.367. A determiner starts a subject half the time, with entropy 0.900 over "the", "a" and "my", and an object half the time, with entropy ln 2, 0.693. The average is 0.797.
This table is the whole story of the loss. The model is not "good" because its loss is 1.0036. It is good because 1.0036 is 0.015 above the floor, and each kind of token is close to its own floor.
Loss and accuracy are different things
The model's top-1 accuracy, the share of tokens for which its most probable guess is right, is 51%. That sounds poor. It is not. A language with so much genuine uncertainty has a ceiling on accuracy. The last code block estimates it: a count-based trigram table built from over a million tokens of the same language, the best predictor available, scores 0.51 too. Our model, with 27,648 numbers, has reached the ceiling.
python
import numpy as np
from collections import Counter, defaultdict
from corpus import makecorpus
words = makecorpus(200000, seed=1).split() # a much bigger sample of the same language
cut = int(0.95 len(words))
counts = defaultdict(Counter)
for i in range(2, cut):
counts[(words[i - 2], words[i - 1])][words[i]] += 1
hits = total = 0
for i in range(cut, len(words)):
c = counts.get((words[i - 2], words[i - 1]))
if c:
hits += c.mostcommon(1)[0][0] == words[i]
total += 1
print("best top-1 accuracy of a trigram table built from", cut, "tokens:", round(hits / total, 3))
best top-1 accuracy of a trigram table built from 1403104 tokens: 0.51
Loss and accuracy measure different things. Accuracy asks only whether the single most probable token was right, and gives no credit for putting 0.9 or 0.4 on it. The loss uses the whole distribution: it rewards a model for putting the right probabilities on the less likely tokens too. Two models with the same accuracy can have very different losses, and loss is also smoother, so training can follow it. This is why language models are trained and compared by loss and perplexity and not by accuracy.
Computing the loss without overflowing
One technical point. The loss needs a softmax, and a softmax needs exponentials. If a score is large, the exponential overflows. A model with scores of 1,000 would give exp(1000), which is infinity, and the softmax is infinity divided by infinity: NaN. The remedy, which every softmax in this course already uses, is to subtract the largest score first. The softmax does not change, since it depends only on differences, and the largest exponent becomes exp(0) = 1. For the loss itself it is better still to compute the log-softmax directly: the score minus the log of the sum of exponentials, with the shift applied.
python
import numpy as np
print("naive softmax with a large score:")
z = np.array([1000.0, 1001.0, 999.0])
with np.errstate(all="ignore"):
naive = np.exp(z) / np.exp(z).sum()
print(naive) # nan: exp(1000) overflows
def logsoftmax(z):
z = z - z.max(axis=-1, keepdims=True) # shift so the largest score is 0
return z - np.log(np.exp(z).sum(axis=-1, keepdims=True)) # log of the sum, computed on small numbers
print(np.round(logsoftmax(z), 4), " loss if class 1 is right:", round(float(-logsoftmax(z)[1]), 4))
naive softmax with a large score:
[nan nan nan]
[-1.4076 -0.4076 -2.4076] loss if class 1 is right: 0.4076
The naive computation gives [nan nan nan]. The stable log-softmax gives the log-probabilities -1.4076, -0.4076, -2.4076, and so a loss of 0.4076 if class 1 is right. Any loss function you write should be stable in this way. Deep learning libraries provide it as a single operation, usually called log-softmax or cross-entropy with logits, for this reason.
Key takeaways
The loss for one token is minus the log of the probability the model gave to the true token. The training loss is the average over tokens, in nats (or bits, with a base-2 log).
Perplexity is e to the loss: the effective number of equally likely choices. Bits per token is the loss over ln 2. A loss of 1.0036 is perplexity 2.728 and 1.448 bits per token.
The log loss is minimised only by the true probabilities, so it rewards honesty.
The floor is the entropy of the source. For the toy language, computed from the grammar: 7.3016 nats per sentence over 7.3867 tokens is 0.9885 nats per token, perplexity 2.687, 1.426 bits. No model can beat it, and a loss below it signals a leak.
Cross-entropy equals entropy plus KL divergence. Training reduces the divergence. Ours is 0.015 nats.
The model's probabilities track the true ones: 0.397, 0.314, 0.288 against one third each after "the cat chased the".
Its average loss on each kind of token is within 0.05 of the ideal: verbs 1.819 against 1.792, adverbs 2.071 against 2.120, full stops 0.395 against 0.367, determiners 0.795 against 0.797.
Top-1 accuracy of 51% is the ceiling here. Accuracy ignores the probabilities the model gives to other tokens, and loss does not, so loss is the right guide.
Compute the loss with a stable log-softmax: subtract the maximum score first. The naive version gives NaN for a score of 1,000.
Common mistakes
Judging a loss without a floor. A loss of 1.0 is superb on this language and poor on another. Compare with the entropy, a good baseline or the uniform guess.
Comparing losses across vocabularies. A model over characters and a model over words have different losses for the same text. Compare in bits per character or per byte.
Mixing nats and bits. The ratio is 0.6931. A loss of 1.0 in nats is 1.44 in bits.
Reading perplexity as accuracy. A perplexity of 2.7 does not mean the model is right 37% of the time. It is a measure of average uncertainty.
Averaging per batch and not per token. Batches with more tokens should count more. Average over tokens.
A naive softmax. It works on small scores and breaks on large ones, often late in training, when you least want it.
Optimising accuracy. It gives no gradient for tokens the model gets wrong with high confidence.
Taking a loss below the floor as an achievement. It is almost always a bug.
Check yourself
1. A model gives the true next token a probability of 0.25. What is the loss for that token?
minus ln 0.25 = ln 4 = 1.386 nats.
2. What is the perplexity of a loss of 2.3026?
e raised to 2.3026 is 10. The model is as unsure as a fair ten-sided die.
3. A text of 100,000 tokens is coded with a model whose loss is 3.0 nats per token. About how many bytes does the compressed text need?
3.0 ÷ 0.6931 = 4.328 bits per token. 100,000 × 4.328 ÷ 8 = 54,101 bytes.
4. A language has a floor of 0.9885 nats and a model scores 1.05. What is the gap, and by what factor is its perplexity above the best?
1.05 − 0.9885 = 0.0615 nats. e raised to 0.0615 is 1.063, so 6.3% higher perplexity.
5. Why does a naive softmax fail for large scores, and what is the fix?
exp of a large score overflows to infinity, giving infinity over infinity, which is NaN. Subtract the largest score first. The result is unchanged because the softmax depends only on differences.
6. Two models both reach 51% top-1 accuracy, with losses of 1.00 and 1.40. Which is better, and why?
The first. Its probabilities are closer to the true ones, which accuracy ignores. A loss of 1.40 means it spreads probability badly over the other tokens.
Try this
Set aside two hours. You need Python, NumPy, corpus.py, helpers.py, gpt.py and train.py.
1. Run the floor calculation. Change the probability of an adverb from 0.6 to 0.3 and to 0.9 in the grammar and in the formula. Check against a sampled corpus that the trigram loss approaches the formula.
2. Print the model's top predictions for three contexts of your own. Compare each with the true distribution that the grammar implies.
3. Work out the ideal loss for the token after "chased the". Compare it with the model's average loss on those positions.
4. Compute the model's loss on only the first token of each sentence. What is its ideal value?
5. Train the model for 300, 1,000 and 3,000 steps and plot the gap to the floor on a log scale. How fast does it shrink?
6. Break the stable softmax on purpose by removing the maximum shift. At what score does it first fail?
A good result is a floor derived from the grammar, a model within 0.02 of it and a table showing it is near the ideal on every kind of token. The next lesson looks at how the model gets there: the optimisers that turn gradients into steps.
Read more
Claude Shannon, "A Mathematical Theory of Communication" (1948), defines entropy and shows that no code can beat it. Thomas Cover and Joy Thomas, "Elements of Information Theory", explains cross-entropy and KL divergence. Andrej Karpathy's lecture "The spelled-out intro to language modeling: building makemore" works the same loss and its stable form step by step. Dan Jurafsky and James Martin, "Speech and Language Processing", has a chapter on n-gram models, perplexity and evaluation.
Tags: Build an LLM Cross-entropy Perplexity Language model Entropy