TExcelTAD
Home › Information Theory › Perplexity

Perplexity

Language models are compared by perplexity: the exponential of their average cross-entropy per token. It has a vivid meaning: a perplexity of 20 means the model is, on average, as uncertain as if it were choosing uniformly among 20 tokens. This lesson connects perplexity to entropy rate and compression; Perplexity in the deep-learning course covers its use for neural language models.

Definition

For a test sequence w1,…,wNw_1, \dots, w_N and a model qq,

PPL=2H^,H^=−1N∑i=1Nlog⁡2q(wi∣w1,…,wi−1)\text{PPL} = 2^{\hat H}, \qquad \hat H = -\frac{1}{N}\sum_{i=1}^N \log_2 q(w_i \mid w_1, \dots, w_{i-1})

(or eH^e^{\hat H} with natural logarithms; the number is the same). H^\hat H is the empirical cross-entropy rate in bits per token (Cross-Entropy).

python · try it yourself
import numpy as np

probs = np.array([0.2, 0.05, 0.5, 0.1, 0.25])        # model probabilities of the actual next tokens
H = -np.mean(np.log2(probs))
print(f"cross-entropy {H:.4f} bits/token, perplexity {2**H:.3f}")
print(f"same with nats: {np.exp(-np.mean(np.log(probs))):.3f}")
print("uniform model over 50,000 tokens: perplexity", 50_000)
cross-entropy 2.5932 bits/token, perplexity 6.034
same with nats: 6.034
uniform model over 50,000 tokens: perplexity 50000

The effective branching factor

If a model spreads its probability uniformly over kk tokens and the true token is always among them, the perplexity is exactly kk. Real models put uneven probabilities, and perplexity is the size of the uniform choice with the same average surprise.

Perplexity is bounded below by the entropy rate

By Gibbs' inequality, a model's cross-entropy rate is at least the true entropy rate of the source, so the best possible perplexity is 2Hrate2^{H_{\text{rate}}}. A model's perplexity measures how far it is from that limit, but the limit itself is unknown for natural language.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
V = 6
T = rng.dirichlet(np.ones(V) * 0.4, size=V)                 # true bigram transition matrix
seq = [0]
for _ in range(60_000):
    seq.append(rng.choice(V, p=T[seq[-1]]))
seq = np.array(seq); train, test = seq[:50_000], seq[50_000:]
pi = np.bincount(train, minlength=V) / len(train)
rate = -np.sum(pi[:, None] * T * np.log2(T))               # true entropy rate
def ppl(logp): return 2 ** -np.mean(logp)
uni = (np.bincount(train, minlength=V) + 1) / (len(train) + V)
big = np.ones((V, V)); np.add.at(big, (train[:-1], train[1:]), 1); big /= big.sum(axis=1, keepdims=True)
print(f"true entropy rate {rate:.4f} bits -> best perplexity {2**rate:.3f}")
print(f"uniform model:  perplexity {V}")
print(f"unigram model:  perplexity {ppl(np.log2(uni[test[1:]])):.3f}")
print(f"bigram model:   perplexity {ppl(np.log2(big[test[:-1], test[1:]])):.3f}")
print(f"true model:     perplexity {ppl(np.log2(T[test[:-1], test[1:]])):.3f}")
true entropy rate 2.0763 bits -> best perplexity 4.217
uniform model:  perplexity 6
unigram model:  perplexity 5.719
bigram model:   perplexity 4.183
true model:     perplexity 4.180

The bigram model, which matches the true structure, almost reaches the true model's perplexity on test data. Both are slightly below 2Hrate=4.2172^{H_{\text{rate}}} = 4.217 here because a finite test sample fluctuates around the average; the bound holds in expectation.

Perplexity and compression

An arithmetic coder driven by the model compresses the test text to about NH^N\hat H bits (Arithmetic Coding). So log⁡2PPL\log_2 \text{PPL} is the model's compression rate in bits per token, and a better language model is a better compressor. This equivalence is why large language models, used with arithmetic coding, compress text far better than zip.

Pitfalls when comparing perplexities

  • Tokenization matters: perplexity per token depends on what a token is. Compare models only with the same tokenizer, or convert to bits per character or per byte (Tokenization).
  • Zero probabilities give infinite perplexity; models must smooth.
  • Test leakage: text seen in training gives misleadingly low perplexity.
python · try it yourself
import numpy as np

# the same text, two tokenizations: convert to bits per character to compare
n_chars = 10_000
for name, n_tokens, ppl in [("word-level model", 2_000, 180.0), ("subword model", 2_800, 45.0)]:
    bits_per_token = np.log2(ppl)
    print(f"{name:16s}: perplexity {ppl:6.1f} per token, {bits_per_token * n_tokens / n_chars:.3f} bits per character")
word-level model: perplexity  180.0 per token, 1.498 bits per character
subword model   : perplexity   45.0 per token, 1.538 bits per character

The word-level model has the higher per-token perplexity but the lower bits per character: it is actually the better model of this text.

In software

  • Hugging Face models return the mean cross-entropy (in nats) as loss; torch.exp(loss) is the perplexity.
  • Report bits per byte (BPB) when comparing models with different tokenizers.

Exercises

Exercise 1: From loss to perplexity

A model has validation loss 2.3 nats per token. What is its perplexity?

Answer

About 9.97.

Solution

e2.3=9.974e^{2.3} = 9.974.

Exercise 2: Branching factor

A model always assigns probability 0.125 to the correct next token. What is its perplexity?

Answer
Solution

H^=log⁡28=3\hat H = \log_2 8 = 3 bits and 23=82^3 = 8.

Exercise 3: Bits per character (code)

A model reaches perplexity 25 on 5000 tokens of a text with 22,000 characters. Compute bits per character and bits per byte for ASCII text.

Answer

About 1.055 bits per character (the same per byte for ASCII).

Solution
python · try it yourself
import numpy as np

print(round(np.log2(25) * 5000 / 22_000, 4))
1.0554

Test yourself

Perplexity equals…

  1. 2 to the power of the cross-entropy in bits per token
  2. the cross-entropy itself
  3. the number of tokens
  4. the accuracy of the model

Can a model's perplexity be below 2Hrate2^{H_{\text{rate}}} of the true source on average?

  1. No, by Gibbs' inequality
  2. Yes, with enough parameters
  3. Only for short texts
  4. Only with smoothing

Why compare models in bits per character instead of perplexity per token?

  1. Different tokenizers make per-token numbers incomparable
  2. Characters are always more informative
  3. Perplexity cannot be computed for tokens
  4. Bits per character is always smaller