Perplexity
Perplexity is the standard intrinsic measure of a language model. It is the exponential of the average cross-entropy per token, and it has a pleasant interpretation: a perplexity of 20 means the model is, on average, as uncertain as if it were choosing uniformly among 20 tokens at every step. Lower is better.
Definition
For a held-out sequence of tokens,
It is the inverse geometric mean of the probabilities the model gave to the actual tokens. Computing it through the product directly would underflow for long texts, so always average log-probabilities first (Overflow and a Stable Softmax).
import numpy as np
probs = np.array([0.5, 0.1, 0.8, 0.25, 0.05, 0.6]) # model probability of each actual token
nll = -np.mean(np.log(probs))
print(f"mean NLL {nll:.4f} nats -> perplexity {np.exp(nll):.3f}")
print(f"geometric mean of probs {np.prod(probs) ** (1 / len(probs)):.4f} = 1/PPL {1 / np.exp(nll):.4f}")
print("uniform guess over 50,000 tokens: PPL =", np.exp(-np.log(1 / 50000)).round(1))
long = np.full(100000, 0.3)
print("direct product for 100,000 tokens:", np.prod(long), " via logs:", round(np.exp(-np.mean(np.log(long))), 4))mean NLL 1.3520 nats -> perplexity 3.865
geometric mean of probs 0.2587 = 1/PPL 0.2587
uniform guess over 50,000 tokens: PPL = 50000.0
direct product for 100,000 tokens: 0.0 via logs: 3.3333
Bounds and intuition
- A model that always assigns probability 1 to the right token has perplexity 1, the minimum.
- A uniform distribution over tokens has perplexity exactly .
- The best achievable perplexity is , where is the true entropy rate of the text in nats per token. No model can go below it.
- In bits: is the cross-entropy in bits per token, the average code length needed to compress the text with the model and arithmetic coding. Language modeling is compression.
Comparing models fairly
Perplexity depends on the tokenizer: splitting the same text into more, easier tokens lowers per-token perplexity without the model being better. Compare models with different vocabularies by bits per byte (or per character):
import numpy as np
text_bytes = 1000
# Model A: 250 tokens with mean NLL 3.0 nats; model B: 400 smaller tokens with mean NLL 2.0 nats
for name, n_tok, nll in (("A", 250, 3.0), ("B", 400, 2.0)):
total = n_tok * nll
print(f"model {name}: per-token PPL {np.exp(nll):6.2f}, bits per byte {total / (np.log(2) * text_bytes):.3f}")model A: per-token PPL 20.09, bits per byte 1.082
model B: per-token PPL 7.39, bits per byte 1.154
Model B has the lower per-token perplexity but needs more bits for the same text: model A actually compresses it better.
Perplexity of a sliding window
Models have a maximum context. For a long evaluation text, the fair method slides a window and scores each token with as much context as possible (overlapping windows, scoring only the new tokens), rather than chopping the text into independent blocks whose first tokens have no context.
In software
torch.exp(F.cross_entropy(logits.view(-1, V), targets.view(-1)))computes perplexity for a batch (ignoring padding withignore_index).- Hugging Face's evaluation guides use the strided sliding window described above.
- Downstream benchmarks are needed as well: perplexity correlates with, but does not equal, usefulness.
Exercises
Exercise 1: From loss to perplexity
A model's validation loss is nats per token. What is its perplexity?
Answer
About .
Solution
.
Exercise 2: Perplexity in bits
A model has perplexity 16. What is its cross-entropy in bits per token?
Answer
4 bits.
Solution
.
Exercise 3: Improvement (code)
Loss drops from 3.0 to 2.9 nats per token. By what percentage does perplexity fall?
Answer
About 9.5%.
Solution
The ratio is : a 0.1-nat improvement always cuts perplexity by about 9.5%, whatever the starting level.
import numpy as np
print(round(np.exp(3.0), 3), round(np.exp(2.9), 3), f"{1 - np.exp(-0.1):.3%}")20.086 18.174 9.516%
Test yourself
Perplexity equals…
- the average loss
- the exponential of the average per-token cross-entropy
- the number of tokens
- the vocabulary size always
A model that predicts uniformly over a vocabulary of tokens has perplexity…
- 1
- 0
Why compare models with different tokenizers using bits per byte?
- Bytes are faster
- Per-token perplexity depends on how the text is split into tokens
- Perplexity cannot be computed
- Bits are more accurate than nats