AI Logic

Evaluation Metrics

Perplexity

Updated:

Computing perplexity. On the left, at each position of "red red red red blue", the probability that model A (1/3 for all three colors) and model B (red 0.8) assign to the correct token and its βˆ’log p; on the right, the perplexity obtained by taking the exp of their mean (3.00 for A, 1.89 for B)

Background and overview

Perplexity is an evaluation metric that expresses how well a language model predicts the next token of a text as a single number: "how many choices, on average, the model is torn between." It averages the log of the probabilities assigned to the correct tokens, flips the sign, and takes the exponential.

PPL(W)=exp⁑(βˆ’1Nβˆ‘i=1Nlog⁑p(wi∣w1,…,wiβˆ’1))\mathrm{PPL}(W) = \exp\left( -\frac{1}{N} \sum_{i=1}^{N} \log p(w_i \mid w_1, \dots, w_{i-1}) \right)

Here W=w1w2…wNW = w_1 w_2 \dots w_N is the evaluation text (NN tokens), and p(wi∣w1,…,wiβˆ’1)p(w_i \mid w_1, \dots, w_{i-1}) is the probability the model predicts for wiw_i coming next, given the preceding tokens. The value is at least 1, and smaller means a better model. A perfect model that assigns probability 1 to every token scores 1, and a model that picks uniformly at random from a vocabulary of VV tokens every time scores VV.

The probability of the whole text is not compared directly because it shrinks as the text gets longer, so texts of different lengths cannot be compared. Perplexity divides by the number of tokens NN (takes the geometric mean) to remove the effect of length.

Perplexity originated in 1977, when Jelinek et al. proposed it as a measure of the difficulty of speech recognition tasks. Today it is widely used to evaluate language models, from n-gram models to large language models.

Definition and procedure

Perplexity is computed on an evaluation text with the following steps.

  1. Split the text into tokens in the same way as the model.
  2. At each position ii, feed the preceding tokens w1,…,wiβˆ’1w_1, \dots, w_{i-1} to the model and take the probability pip_i it assigns to the correct token wiw_i.
  3. Compute the negative log-likelihood βˆ’log⁑pi-\log p_i at each position. It is larger at positions where the model assigned a low probability to the correct token.
  4. Average over the NN positions: β„“Λ‰=βˆ’1Nβˆ‘ilog⁑pi\bar{\ell} = -\frac{1}{N} \sum_{i} \log p_i.
  5. Take the exponential: PPL=exp⁑(β„“Λ‰)\mathrm{PPL} = \exp(\bar{\ell}).

Here is a check using a common textbook example: a tiny language with only three colors. The test text is the five words "red red red red blue".

Probability assigned to the correct token at each positionMean βˆ’log⁑p-\log pPerplexity
Model A (1/3 for all three colors)1/3, 1/3, 1/3, 1/3, 1/31.0993.00
Model B (red 0.8, green 0.1, blue 0.1)0.8, 0.8, 0.8, 0.8, 0.10.6391.89

Model A never knows which of the three colors comes next, so it is exactly "torn among three choices" and scores 3. Model B knows red is frequent, so its uncertainty drops to 1.89 choices on average. It assigns only 0.1 to blue in the fifth position, so βˆ’log⁑p-\log p there (2.30) is large and pushes the overall value up.

Because of this "how many choices" view, perplexity is also called the weighted average branching factor. The branching factor (the number of possible next words) is 3 for both models, but once the skew in the probabilities is taken into account, model B effectively has fewer than two choices.

The mean βˆ’log⁑p-\log p in the formula is exactly the cross-entropy loss minimized when training a language model. In other words, perplexity = exp(per-token cross-entropy loss), so it can be computed directly from the training loss. A loss of 2.0 corresponds to a perplexity of about 7.4. Some write it as 2H2^{H} with base-2 logarithms, but as long as the exponential uses the same base as the loss, the value is the same.

What it measures and its limitations

Perplexity measures how "surprising" the evaluation text was to the model. The higher the probability of the text, the smaller the value, so lowering perplexity is the same as raising the likelihood of the test text. As a consequence, models evaluated under different conditions cannot be compared.

Condition to match when comparingWhat happens if it is not matched
Vocabulary and tokenizationChanging how tokens are split changes both NN and the difficulty of each prediction, so the values are not comparable
Evaluation textPrediction difficulty differs by text. If the evaluation text leaks into the training data, the value becomes unfairly low
Context length and chunkingFor texts longer than what fits at once, how the text is chunked changes how much context is available for prediction
Whether sentence-boundary symbols are countedThe value changes depending on whether end-of-sentence symbols are included in NN and in the probability computation

The effect of chunking is not small. The Hugging Face documentation reports that evaluating GPT-2 large on WikiText-2 gave 19.44 with non-overlapping 1024-token chunks, and 16.44 with a sliding window that moves 512 tokens at a time (giving each token at least 512 tokens of context). Even with the same model and data, the evaluation procedure alone changes the value.

Perplexity can only be compared between models with the same tokenization and evaluation procedure. Values from models with different vocabulary sizes or tokenization (for example, word-level versus BPE subword-level) cannot be set side by side to decide which is better. Also, if even one token in the evaluation text has probability 0, the value becomes infinite and cannot be computed.

Another limitation is that lower perplexity does not necessarily mean better performance on real tasks such as translation or speech recognition. The two are broadly correlated, so perplexity is used as a convenient metric, but improvements should preferably be confirmed by evaluation on the actual task. Perplexity is also a metric for language models that predict the next token from left to right (autoregressive models); it cannot be defined in its original form for models such as BERT that guess hidden tokens within a sentence (masked language models).

Where it is used

Perplexity is used in the following situations.

  • Comparing language models: On the same benchmark (Penn Treebank, WikiText-103, etc.) and with the same tokenization, it shows the effect of new architectures or regularization. The effect of adding Variational Dropout or Zoneout to LSTM language models, and of scaling up a Sparsely-Gated MoE, was also shown through lower perplexity.
  • Monitoring training: Taking the exp of the training and validation losses shows whether training is progressing and whether the model is overfitting. It can be read as an intuitive "how many choices" quantity rather than a raw loss.
  • Supporting evaluation of generated text: Generated text is sometimes fed to another language model to see whether it reads as natural to that model. However, text that repeats the same word can also score low, so this alone cannot determine generation quality.

To measure generation quality against reference translations, use metrics such as BLEU.

Comparison with similar metrics

The following table compares perplexity with metrics used alongside it in evaluating language models and generation, from the same perspectives.

MetricWhat it comparesDirectionUnit and rangeWhat it needs
PerplexityProbability assigned to the correct tokensLower is better1 or more ("number of choices")Model probabilities
Cross-entropy (per token)Same as above (log of perplexity)Lower is better0 or more (nats or bits)Model probabilities
Bits per characterSame as above, converted to a per-character valueLower is better0 or more (bits)Model probabilities and character count
BLEUn-gram overlap between generated and reference sentencesHigher is better0–1 (0–100)Generated and reference sentences

Rough guidelines for choosing among them:

  • To compare the predictive power of language models themselves: Perplexity or cross-entropy. They are related by exp and log and carry the same information.
  • To compare models with different tokenization: Use values normalized per character or per byte rather than per token (such as bits per character), because the denominator no longer depends on tokenization.
  • To compare the quality of generated sentences: Use metrics such as BLEU that look at the output sentences themselves rather than model probabilities.

PyTorch example

Show code
python
import math
import torch
import torch.nn.functional as F


@torch.no_grad()
def perplexity(model, input_ids, pad_id=None):
  """Compute the perplexity of an autoregressive language model.
  input_ids: token IDs of shape (batch, seq_len). model is assumed to return logits of shape (batch, seq_len, vocab).
  """
  model.eval()  # disable dropout (in train() mode the value fluctuates every run and comes out higher)
  logits = model(input_ids)              # (B, T, V)
  # the logits at position t predict the token at position t+1 (shift by one)
  logits = logits[:, :-1, :]
  target = input_ids[:, 1:]
  ignore = -100 if pad_id is None else pad_id
  # sum the negative log-likelihood with reduction="sum" and divide by the number of counted tokens
  nll_sum = F.cross_entropy(
    logits.reshape(-1, logits.size(-1)), target.reshape(-1),
    ignore_index=ignore, reduction="sum",
  )
  n_tokens = (target != ignore).sum()
  return math.exp(nll_sum.item() / n_tokens.item())


# check the textbook three-color example directly from the probabilities (model B: red 0.8, green 0.1, blue 0.1)
probs = torch.tensor([0.8, 0.8, 0.8, 0.8, 0.1])  # probability assigned to the correct token at each position of "red red red red blue"
print(torch.exp(-probs.log().mean()))  # tensor(1.8946)

# with torchmetrics: preds are pre-softmax logits (B, T, V), target is (B, T)
# do the shifting yourself. Positions with the ID given as ignore_index are not counted
from torchmetrics.text import Perplexity

metric = Perplexity(ignore_index=-100)
preds = torch.randn(2, 8, 5)
target = torch.randint(5, (2, 8))
target[0, 6:] = -100  # padding positions
print(metric(preds, target))

FAQ

Q. What perplexity counts as good?
A.

There is no fixed threshold, because the value changes greatly with the dataset, vocabulary size, tokenization, and context length. Judge by comparing with existing models evaluated under the same conditions.

Q. How does perplexity differ from the training loss?
A.

They carry the same information. Perplexity is the exp of the per-token cross-entropy loss (natural log). The loss is on a log scale, so differences look small, whereas perplexity can be read as "how many choices, on average, the model is torn between."

Q. Can the perplexity of BERT be computed?
A.

Not with the original definition. Perplexity is a metric for autoregressive models that predict the next token from left to right. For models such as BERT that guess hidden tokens within a sentence, a different method is needed, such as masking one token at a time to obtain probabilities, and the result cannot be compared with values from autoregressive models.

References

  1. Jurafsky, D., & Martin, J. H. Speech and Language Processing (3rd ed. draft), Chapter 3: N-gram Language Models (Sections 3.3 and 3.7).
  2. Hugging Face. Perplexity of fixed-length models (Transformers documentation).
  3. Jelinek, F., Mercer, R. L., Bahl, L. R., & Baker, J. K. (1977). Perplexityβ€”a measure of the difficulty of speech recognition tasks. The Journal of the Acoustical Society of America, 62(S1), S63.
  4. Lightning AI. torchmetrics.text.Perplexity (API reference).