Calculating Perplexity in Language Models
Introduction to Perplexity
Welcome back to the "Scoring LLM Outputs with Logprobs and Perplexity" course. In the previous lesson, you explored how to compare sentence likelihoods using log probabilities. In this lesson, you’ll learn about perplexity—a metric used to evaluate how well a language model predicts text.
Perplexity gives us a sense of how “surprised” a model is by a sequence. A lower value means the model was confident in the words it chose; a higher value means it was often unsure, with many plausible alternatives.
By the end of this lesson, you'll understand what perplexity means, how it's related to log probabilities, and how to calculate it for the text a model generates.
Understanding Perplexity
In traditional NLP, perplexity is computed as the exponential of the average negative log-likelihood of a token sequence:
Let’s break this down:
- is the total number of tokens in the sequence.
- is the probability that the model assigns to the -th token, given the previous tokens.
- is the log probability of the -th token.
- The sum adds up the log probabilities for all tokens in the sequence.
- Dividing by gives the average log probability per token.
- Multiplying by turns this into the average negative log probability (also called the average "surprisal").
- Taking the exponential () converts this average surprisal back into the original probability scale, giving us the perplexity.
A lower perplexity means the model is less "surprised" by the sequence (it assigns higher probabilities to the tokens), while a higher perplexity means the model finds the sequence less predictable.
Example: Measuring Perplexity
A note on models and providers: the models used in this example are set up for you on CodeSignal. If you run similar code on your own machine, check your provider's documentation first: model names, API keys and supported parameters differ between providers and models. In particular, not every model returns log probabilities, which is why the code checks that they are present.
We’ll compare two prompts: a factual one and a creative one. For each prompt, the model writes about 60 tokens. We collect the log probability of every generated token, average them, and apply the formula above, with being the number of generated tokens.
Prompt: Explain how photosynthesis works. Tokens scored: 60 Average log probability: -0.2231 Perplexity: 1.25
Prompt: Write a short story about a lighthouse keeper. Tokens scored: 60 Average log probability: -1.0006 Perplexity: 2.72
