TExcelTAD

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 TT tokens,

PPL⁡=exp⁡(−1T∑t=1Tlog⁡p(xt∣x<t))=(∏t=1Tp(xt∣x<t))−1/T\operatorname{PPL} = \exp\left(-\frac{1}{T}\sum_{t=1}^{T}\log p(x_t \mid x_{<t})\right) = \left(\prod_{t=1}^{T}p(x_t \mid x_{<t})\right)^{-1/T}

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).

python · try it yourself
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 VV tokens has perplexity exactly VV.
  • The best achievable perplexity is eHe^{H}, where HH is the true entropy rate of the text in nats per token. No model can go below it.
  • In bits: log⁡2PPL⁡\log_2\operatorname{PPL} 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):

BPB=total NLL in natsln⁡2⋅number of UTF-8 bytes\text{BPB} = \frac{\text{total NLL in nats}}{\ln 2 \cdot \text{number of UTF-8 bytes}}
python · try it yourself
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 with ignore_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 2.32.3 nats per token. What is its perplexity?

Answer

About 9.979.97.

Solution

e2.3≈9.974e^{2.3} \approx 9.974.

Exercise 2: Perplexity in bits

A model has perplexity 16. What is its cross-entropy in bits per token?

Answer

4 bits.

Solution

log⁡216=4\log_2 16 = 4.

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 e−0.1≈0.905e^{-0.1} \approx 0.905: a 0.1-nat improvement always cuts perplexity by about 9.5%, whatever the starting level.

python · try it yourself
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…

  1. the average loss
  2. the exponential of the average per-token cross-entropy
  3. the number of tokens
  4. the vocabulary size always

A model that predicts uniformly over a vocabulary of VV tokens has perplexity…

  1. 1
  2. ln⁡V\ln V
  3. VV
  4. 0

Why compare models with different tokenizers using bits per byte?

  1. Bytes are faster
  2. Per-token perplexity depends on how the text is split into tokens
  3. Perplexity cannot be computed
  4. Bits are more accurate than nats