Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.How surprised is the model?
A language model guesses the next word. If it always spreads its bets evenly over 50 words, it is as confused as someone rolling a 50-sided die: its perplexity is 50. A model that usually knows the next word well has a perplexity near 1. Lower is better, but only when models cut text into the same pieces: a model reading letter by letter faces fewer choices per step than one reading whole words. The demo converts a model’s loss into perplexity and bits per byte.
Perplexity is how engineers track pretraining of language models, including models for technical domains such as aerospace documents.
- 1. Perplexity 50 means the model is as unsure as…
- 2. Lower perplexity is…
- 3. Perplexities are comparable only with…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Definition: PPL = exp(−(1/N) Σ log p(x_t | earlier tokens)), the exponential of the cross-entropy loss in nats.
- Range: 1 (perfect) to the vocabulary size (uniform guess); infinite if any token gets probability 0.
- Bits per byte (BPB): total negative log-likelihood in bits divided by UTF-8 bytes; compares models with different tokenizers (used by The Pile, Llama reports).
- Long texts: sliding windows with a stride give each scored token nearly full context; non-overlapping chunks overstate perplexity.
- Compression: an LM plus arithmetic coding compresses text to its cross-entropy; better LMs are better compressors.
- Limits: perplexity measures fit to a text distribution, not helpfulness, truthfulness or reasoning; instruction tuning often raises perplexity on web text while improving usefulness; it is sensitive to formatting, domain and contamination.
- 1. Perplexity is the exponential of…
- 2. A tokenizer-independent alternative:
- 3. Long texts should be scored with…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Measuring perplexity in practice
Exercise 1.
- Perplexity from token log-probabilities.
- Bits per byte.
- Sliding-window scoring.
Practice.
- Hugging Face: pass labels = input_ids to get the mean loss; exponentiate. Use a stride (for example half the context) for long documents.
- lm-evaluation-harness tasks wikitext and pile report word perplexity, byte perplexity and bits per byte.
- Fix the test set, the tokenizer, document boundaries and whether the first tokens of each window are scored.
- Track validation perplexity per data domain during pretraining; a rise in one domain flags a data-mixture problem.
- Do not compare chat models by perplexity on web text.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tok = AutoTokenizer.from_pretrained("gpt2"); model = AutoModelForCausalLM.from_pretrained("gpt2").eval()
ids = tok(text, return_tensors="pt").input_ids[:, :1024]
with torch.no_grad(): loss = model(ids, labels=ids).loss
print("perplexity", torch.exp(loss).item(), "bits per byte", (loss * (ids.shape[1] - 1) / len(text.encode()) / torch.log(torch.tensor(2.))).item())- 1. In Hugging Face, the loss is obtained by passing…
- 2. A harness that reports bits per byte:
- 3. Chat models should not be compared by…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Cross-entropy bound. For a stationary source with entropy rate H, any model’s expected per-token loss is H + KL(p ‖ q) ≥ H, so perplexity ≥ e^H, with equality only for the true distribution. A model’s perplexity approaches e^H from above as it learns.
Tokenizer dependence. The total log-likelihood of a text is comparable across tokenizers; perplexity divides it by the number of tokens. A tokenizer with shorter tokens divides by more, giving a smaller number for the same total. Bits per byte divides by a fixed quantity, the text length.
Overfitting. Maximum-likelihood n-gram estimates put all mass on seen continuations; with sparse data, smoothing leaves unseen events too little mass, and test perplexity can exceed that of a uniform guess. Held-out perplexity therefore detects overfitting.
- 1. A model's perplexity is at least…
- 2. Shorter tokens make per-token perplexity…
- 3. Sparse unsmoothed n-grams can do worse than…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.How does perplexity behave as an n-gram model gets more data, and how misleading is it across tokenizers?
History.
- F. Jelinek et al., “Perplexity: a measure of the difficulty of speech recognition tasks” (1977).
- C. Shannon, “Prediction and entropy of printed English” (1951).
- L. Gao et al., “The Pile” (2020), bits per byte across tokenizers.
Exercise 2. A known source and n-gram models.
- Source: a second-order Markov chain over 50 words with sparse Dirichlet(0.1) transitions; each word spelled with 2–6 letters. True perplexity e^H = 8.39 per word.
- Models: add-0.1 unigram, bigram and trigram over words, trained on 2000, 20000 or 200000 words; tested on 20000 words.
- Tokenizers: the same test text scored by the word trigram and by a character trigram (27 symbols, add-0.01).
| words of training | unigram | bigram | trigram |
|---|---|---|---|
| 2000 | 50.54 | 89.64 | 40.3 |
| 20000 | 50.04 | 48.94 | 18.22 |
| 200000 | 49.95 | 45.8 | 9.77 |
| same test text | perplexity per token | bits per character |
|---|---|---|
| word trigram | 9.8 | 0.68 |
| character trigram | 2.35 | 1.23 |
- More data drove trigram perplexity towards the true 8.39.
- Overfitting: with 2000 words the bigram (89.6) was worse than a uniform guess (50).
- Tokenizers: the character model looked four times better per token but was worse per character.
- Seeds 1 and 2: trigram at 200000 words 9.88 and 9.73 (true 8.45 and 8.42); character vs word bits per character 1.129 vs 0.601 and 1.198 vs 0.636.
- Caveat: add-k n-grams on a synthetic Markov source; neural LMs share the tokenizer effect but not this overfitting pattern.
Perplexity in AI, robotics and aerospace
- Domain LLMs: perplexity on held-out aerospace manuals or maintenance logs tracks domain adaptation.
- Anomaly detection: high perplexity of telemetry or log sequences under a sequence model flags unusual behaviour.
- Data filtering: pretraining pipelines drop documents with extreme perplexity under a reference model.
References
- C. E. Shannon (1951). “Prediction and entropy of printed English.” Bell System Technical Journal.
- F. Jelinek, R. L. Mercer, L. R. Bahl and J. K. Baker (1977). “Perplexity: a measure of the difficulty of speech recognition tasks.” JASA.
- L. Gao et al. (2020). “The Pile: an 800GB dataset of diverse text for language modeling.” arXiv.
- G. Delétang et al. (2024). “Language modeling is compression.” ICLR.