# What Is Perplexity?

> What perplexity measures, how it is worked out, and when two models can be compared fairly, explained simply for your AI interview.

**In short:** Perplexity is a score for how surprised a language model is by real text. It is built from the chances the model gave to each real next token. A lower number means the model predicted that text better.

AI and LLM interview question Q021, LLM fundamentals. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-perplexity

## Say it in 30 seconds

Perplexity measures how surprised a language model is by real text. For each token, I look at the chance the model gave the token that really came next. I take the log of those chances, average them, flip the sign, and undo the log to get one number. Lower is better, but only when models score the same text with the same tokenizer. It says nothing about whether an answer is true or useful.

## Say it in 2 minutes

Perplexity is one of the most common ways to score a language model. The model reads text one token at a time and guesses each next token. Perplexity looks at the chance it gave to every real next token. High chances mean it was not surprised, so the perplexity is low. If it kept being caught out, the perplexity is high.

The maths is simple. For each real token, take the log of its chance, so a tiny chance becomes a large negative number. Average those numbers over the text, flip the sign, and undo the log. The result is one number. Roughly, it is how many options the model was choosing between at each step.

Two rules matter in an interview. First, compare only on the same text with the same tokenizer, because the way text is split into tokens changes the number. Second, a lower score does not show the answers are sound. It shows only that the model predicted the test text better. For a real product, I would also test answers on real tasks and have people review them.

The last link is to training. Perplexity is the exponentiated cross-entropy between the data and the model's predictions, so a falling perplexity on held-out text usually means training is working. It is still no test of a product, though.

## What is perplexity, in plain words?

Perplexity is a score for how well a language model predicted some real text, one token at a time. A token is a small chunk of text: a whole word, part of a word, a single character or a punctuation mark. It is the unit the model reads and predicts. Perplexity measures how surprised the model was by the tokens that really came next. Lower means less surprise.

Picture a senior claims handler reading a new policy wording. If she can guess most of each next phrase, the wording is familiar to her. If the text keeps catching her out, it is strange to her. Perplexity measures that surprise for a model. A real case: a team checks whether a new model has learned their insurance claim notes before they trust it with live files.

- **Perplexity:** A score for how surprised a model is by real text. Lower is better, on the same text.
- **Token:** A small chunk of text, such as a word, part of a word or punctuation. The unit a model reads and predicts.
- **Log:** A maths step that turns tiny chances into numbers you can add up and average.
- **Held-out text:** Text the model did not train on, kept back to test how well it predicts.
- **Tokenizer:** The tool that splits text into tokens. The same text can give different token counts depending on the model.

## How is perplexity calculated?

Three steps. First, for each real next token, note the chance the model gave it. Second, take the log of each chance and average them. Third, flip the sign and undo the log. The result is perplexity.

*Diagram, How perplexity is worked out: Held-out text goes through the model, which gives a chance to each real next token. Those chances are logged and averaged, then the sign is flipped and the log is undone, giving one number. Every model goes through the same steps, so the arithmetic is identical for each.*
1. The held-out text goes in, one token at a time.
2. The model gives each real next token a probability.
3. Those probabilities are logged and averaged.
4. Flip the sign and undo the log: that gives perplexity.

Here it is in plain Python. Two made-up models score the same eight tokens of claim notes. Each list holds the chance the model gave to the real next token. The numbers are invented for the example, but the formula is the real one.

```python
# Perplexity of two models on the same held-out claim notes.
# Each number is the probability the model gave to the token that really came next.
import math

REAL_NEXT_WORD_PROBS = {
    "Model A (current)": [0.10, 0.25, 0.05, 0.30, 0.50, 0.20, 0.15, 0.60],
    "Model B (candidate)": [0.40, 0.55, 0.20, 0.60, 0.70, 0.45, 0.35, 0.80],
}

def perplexity(probs):
    # Log each probability, average them, flip the sign, then exponentiate.
    avg_surprise = -sum(math.log(p) for p in probs) / len(probs)
    return math.exp(avg_surprise)

for name, probs in REAL_NEXT_WORD_PROBS.items():
    print(f"{name}: perplexity {perplexity(probs):.2f}")
print("Same text, same tokenizer: the lower number predicted the notes better.")
```

Output:

```text
Model A (current): perplexity 4.83
Model B (candidate): perplexity 2.13
Same text, same tokenizer: the lower number predicted the notes better.
```

Model B scores lower, so it predicts these notes better. It gave bigger chances to the words that really came next.

## What does a lower number mean, and what does it not mean?

Lower is better, because a higher score means more surprise at the real words. Hugging Face's documentation defines it as the exponentiated average negative log-likelihood of a sequence. Three of its lines are worth knowing:

> "Perplexity (PPL) is one of the most common metrics for evaluating language models." (Hugging Face)
>
> "Importantly, this means that the tokenization procedure has a direct impact on a model's perplexity which should always be taken into consideration when comparing different models." (Hugging Face)
>
> "This is also equivalent to the exponentiation of the cross-entropy between the data and model predictions." (Hugging Face)

Two things change the number, even for one model. The tokenizer splits text into different tokens, so the count and the chances change. The context window matters too: a model that sees more of the text before each guess usually scores better. Hugging Face's guide says the same about sliding a window over long text: a smaller stride (how far the window moves each time) gives each prediction more context.

*Diagram, When two perplexity numbers can be compared: A fair comparison needs the same held-out text, the same tokenizer and the same context window. If all three match, the lower score wins. If one differs, the two numbers can't be placed side by side.*
1. Each model scores the same held-out text.
2. Both split that text into tokens the same way.
3. Both use the same context window and step size.
4. If all three match, the lower score predicted the text better.
5. If any one differs, the two numbers are not a fair race.

Perplexity says nothing about whether an answer is true, safe or useful. It scores how well the model predicts text, nothing more. That is why teams that ship chat assistants also test answers on real tasks and have people review them.

It also has a limit on model type. Hugging Face's docs say the metric "applies specifically to classical language models" and "is not well defined for masked language models like BERT".

> **Tip:** Asked what a perplexity of 20 means? Hugging Face's docs say that, intuitively, perplexity can be thought of as an evaluation of the model's ability to predict uniformly among the set of specified tokens in a corpus. Roughly, that is as unsure as choosing evenly from 20 options at each step. A model that guessed evenly among 50,000 tokens at every step would score 50,000. Then say it scores the text, not the truth of any answer.

### How would you compare two models for a claims team?

A claims team has two models. Model A is live. Model B had extra training on the team's own notes, which is called fine-tuning. They want to know which one to ship. Your first step is a held-out set: 2,000 claim notes from last quarter that neither model trained on.

1. **Keep the test set clean:** Hold back notes that neither model saw in training. Otherwise a low score only shows it memorised them.
2. **Score both the same way:** Same tokenizer, same context window, same step size. Otherwise the numbers can't be compared.
3. **Treat the lower score as a clue:** It shows which model predicts those notes better. Then run real claim tasks and have adjusters check the answers.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: how surprised the model is by real text, per token.
- [ ] How it's worked out: chances, log, average, undo the log.
- [ ] Lower is better, on the same text and tokenizer.
- [ ] It measures prediction, not truth or helpfulness.
- [ ] Comparisons need the same test set, tokenizer and context window.
- [ ] Honest limits: it is one metric, so test real tasks too.

**Common traps**

- Trap: "Lower perplexity always means a better chatbot." Better: It means the model predicted that held-out text better. Check answers, safety and helpfulness separately.
- Trap: "Perplexity is the percentage of tokens the model got right." Better: Perplexity scores prediction. It is built from the chances given to the real tokens, and lower is better.
- Trap: "You can compare any two models' perplexity." Better: Only on the same text with the same tokenizer and context setup. Otherwise the numbers aren't comparable.

## Can you spot the problem?

**Spot the flaw:** A colleague says Model B is the better model. Which comparison is flawed?

A. Model A and Model B both scored on the same 2,000 held-out claim notes, with the same tokenizer. A scored 9.1 and B scored 7.4, so B predicts the notes better.
B. Model A scored 9.1 on our claim notes. Model B scored 7.4 on a public news dataset. So B is the better model.
C. We re-ran Model A with the same stride and its score stayed at 9.1, so we can trust that number as the baseline.
D. We scored both models on the same 2,000 held-out notes, then re-ran each one and averaged the two runs.

**Answer:** B. The two scores come from different text, so they can't be compared. Score both models on the same held-out notes, with the same tokenizer and window.

**Quick check:** Model B's perplexity drops from 12 to 8 after a change. What can you safely say?

A. It now answers customer questions more truthfully
B. Its answers are now 33% more accurate
C. On the same held-out text and tokenizer, it now predicts that text better
D. It is safe to ship to customers now

**Answer:** C. Lower perplexity under the same conditions means better prediction of that text. It doesn't measure truth, accuracy or safety, so those still need their own tests before shipping.

## Can you answer these from memory?

**Flash cards**

- **What is perplexity?** How surprised a language model is by real text. Lower is better, on the same text.
- **How is it worked out?** Chance of each real token, log, average, flip the sign, undo the log.
- **Is it the same as accuracy?** It scores how well the model predicted the text. Right and wrong answers are a separate test.
- **What is held-out text?** Text the model did not train on, kept back to test its predictions.
- **Can you compare two models' scores?** Only on the same text, tokenizer and context window.
- **Does low perplexity prove it is safe?** No. It says nothing about truth, safety or helpfulness.

## Likely follow-up questions

- Q022 What are logits, and what does softmax do? https://designervenkat.online/interview/ai/what-are-logits-and-what-does-softmax-do
- Q419 MSE vs cross-entropy loss? https://designervenkat.online/interview/ai/mse-vs-cross-entropy-loss
- Q252 BLEU and ROUGE, and their limits? https://designervenkat.online/interview/ai/bleu-and-rouge-and-their-limits
- Q013 Greedy vs beam search vs sampling? https://designervenkat.online/interview/ai/greedy-vs-beam-search-vs-sampling
- Q263 Why can public benchmarks mislead? https://designervenkat.online/interview/ai/why-can-public-benchmarks-mislead
