Skip to content
Skip to lesson
Back to Topics
LearnCore LLM FoundationsPerplexity & Model Evaluation
MediumEvaluation & Benchmarks10 min read

Perplexity & Model Evaluation

A lower perplexity means the model was less surprised by held-out tokens, but only under a fixed scoring protocol.

On this page

A teammate announces that a new checkpoint dropped validation perplexity from 8.17 down to 1.90, a fourfold win. Then you check the config: the old run used a subword tokenizer and the new one switched to characters. On the exact same text, the "1.90 PPL" model was actually more surprised. Nothing was miscalculated; the two numbers simply measured different prediction units.

is the cleanest intrinsic metric for how well a causal language model predicts unseen text, provided every evaluation control stays fixed. It is also one of the easiest metrics in ML to misread, both when scoring rules drift and when smooth prose fit is mistaken for downstream reasoning or factuality.

From token surprise to perplexity

During evaluation, you do not sample continuations. You teacher-force real held-out text through the model and read the probability pθ(xi∣x<i)p_\theta(x_i \mid x_{<i}) assigned to each actual next . Its (NLL), or surprise, is −ln⁡p-\ln p. A certain hit (p=1p = 1) costs 00 nats; a confident miss (p=0.001p = 0.001) costs 6.9086.908 nats.

Averaging NLL across NN scored tokens gives the causal loss LL, and exponentiating gives perplexity:

L=−1N∑i=1Nln⁡pθ(xi∣x<i),PPL=exp⁡(L)=2L/ln⁡2L = -\frac{1}{N}\sum_{i=1}^{N}\ln p_\theta(x_i \mid x_{<i}), \qquad \text{PPL} = \exp(L) = 2^{L / \ln 2}

Perplexity acts like an effective branching factor: guessing uniformly among KK equally likely tokens gives p=1/Kp = 1/K and PPL=K\text{PPL} = K (formally, PPL is the inverse geometric mean of observed token probabilities). Because the mapping is exponential, every +ln⁡2≈0.693+\ln 2 \approx 0.693 nats doubles perplexity, and a confidently wrong model can easily exceed its own vocabulary size (assigning p=0.01p = 0.01 to every token in a 2-token vocabulary gives PPL=100\text{PPL} = 100). Note that this formula governs causal next-token models; masked models like BERT condition on both left and right context and report separately labeled pseudo-perplexity that cannot be ranked directly against causal PPL.[1][2]

Left: the curve of negative log p against probability p, with three observed targets marked: p 0.80 costs 0.223 nats, p 0.50 costs 0.693, and p 0.10 costs 2.303. Right: those losses laid end to end total 3.219 nats. Dividing by three targets gives a mean of 1.073 nats, and exponentiating gives perplexity 2.92.
Transform each observed probability with −ln⁡p-\ln p, average the losses (1.073 nats), and exponentiate once to get PPL 2.92.
The exponential curve from average loss in nats to perplexity, for losses 0 to 4.7. A staircase climbs it through perplexity 5, 10, 20, 40, and 80. Every horizontal step is ln 2, about 0.693 nats, and every step doubles perplexity.
Each constant step of ln⁡2≈0.693\ln 2 \approx 0.693 nats doubles perplexity, so compare training runs in nats or bits rather than raw PPL differences.

Computing stably from logits and aggregating once

Models output raw , not probabilities. Calling exp(1000) overflows IEEE 754 floats, so subtract max(logits) before computing log-softmax (built into PyTorch's cross-entropy[3]). Two aggregation rules prevent silent evaluation bugs:

  1. Keep inf distinct from NaN: An exact zero probability for an observed target yields infinite NLL (legitimate and terrible); NaN means the pipeline broke and must be rejected. If finite mean NLL is huge (say 1,000 nats), report loss rather than clipping it to prevent exp overflow.
  2. Never average window or worker perplexities: Exponentiation is nonlinear and shards have uneven target counts. Have every worker report total NLL and valid target count, sum both globally, divide once, and exponentiate once.
stable-perplexity-and-aggregation.py
import math

# 1. Stable log-softmax on large logits [1000, 998, 997]
logits = [1000.0, 998.0, 997.0]
shifted = [v - max(logits) for v in logits]
log_z = math.log(sum(math.exp(v) for v in shifted))
nll = log_z - shifted[0]
print(f"Stable log-softmax -> NLL={nll:.3f} nats, PPL={math.exp(nll):.3f}")

# 2. Token-weighted corpus PPL vs wrong window-PPL average
windows = [(0.50, 2), (2.00, 8)]  # (mean_nll, scored_tokens)
wrong_avg = sum(math.exp(m) for m, _ in windows) / len(windows)
total_nll = sum(m * n for m, n in windows)
total_toks = sum(n for _, n in windows)
print(f"Wrong mean of window PPLs: {wrong_avg:.2f}")
print(f"Token-weighted corpus PPL: {math.exp(total_nll / total_toks):.2f}")
Output
Stable log-softmax -> NLL=0.170 nats, PPL=1.185
Wrong mean of window PPLs: 4.52
Token-weighted corpus PPL: 5.47

Comparing checkpoints and tokenizers fairly

Raw perplexity isolates model weights only when every protocol control matches: corpus and split, preprocessing, tokenizer revision, objective, context length, , document boundaries, and target masking (always in model.eval() with dropout disabled and unmodified logits, no temperature or top-kk). Report important domains separately too: the Paloma benchmark showed that low perplexity on one corpus frequently masks large regressions on code or scientific prose.[4]

Perplexity comparison across context lengths on wikitext-eval-v3 using tokenizer bpe-v7 and stride 512. At 2048 tokens of context, checkpoint 0400 scores PPL 3.18 and checkpoint 0800 scores PPL 2.31, cleanly isolating weight changes. A shorter 512-token context run sits on a different curve and cannot be compared directly.
Comparing checkpoint 0400 (3.18) and 0800 (2.31) at matched 2048-token context and stride 512 isolates model weights; shrinking context to 512 shifts the evaluation curve.

When two checkpoints use different tokenizers, raw token PPL fails because each tokenizer slices the same text into different numbers of prediction events.[1] Divide total NLL by the shared raw UTF-8 byte count BB instead to compute bits per byte (BPB) (used by The Pile and Paloma):[5][4]

BPB=−∑iln⁡pθ(xi∣x<i)Bln⁡2\text{BPB} = \frac{-\sum_i \ln p_\theta(x_i \mid x_{<i})}{B \ln 2}

Audit text normalization alongside BPB: lossy preprocessing (like SentencePiece's optional NFKC plus whitespace folding[6]) collapses distinct UTF-8 strings ('A a', 'A a', 'a a') into fewer bytes and an artificially easier target.

At the top, the same 14 UTF-8 bytes of "Rain falls now" align across two tokenizers: four subword spans (Rain, ·falls, ·n, ow; total NLL 8.4 nats) versus fourteen single-byte character spans (total NLL 9.0 nats). At lower left, raw token perplexity bars favor the character model (1.90 vs 8.17) because loss divides by 14 instead of 4. At lower right, bits per byte bars on the shared 14-byte denominator flip the winner back to the lower-loss subword model (0.866 vs 0.927).
Over the same 14 UTF-8 bytes, raw token PPL favors the character model (1.90 vs. 8.17), while bits per byte flips the winner back to the less-surprised subword model (0.866 vs. 0.927).
bits-per-byte-and-normalization.py
import unicodedata

text = "Rain falls now"
raw_bytes = len(text.encode("utf-8"))
for name, n_toks, total_nll in [("subword", 4, 8.4), ("character", 14, 9.0)]:
    print(f"{name:10s} token PPL={math.exp(total_nll / n_toks):.2f}, BPB={total_nll / (raw_bytes * math.log(2)):.3f}")

# Lossy NFKC + casefold collapses 6 raw bytes into 3 normalized bytes:
sample = "A  a"
norm = " ".join(unicodedata.normalize("NFKC", sample).casefold().split())
print(f"Normalization: {sample!r} ({len(sample.encode())}B) -> {norm!r} ({len(norm.encode())}B)")
Output
subword    token PPL=8.17, BPB=0.866
character  token PPL=1.90, BPB=0.927
Normalization: 'A  a' (6B) -> 'a a' (3B)

Strided sliding windows and shifted target counts

Documents longer than the model's context window must be scored in windows. Disjoint blocks starve tokens near each cut of left context; overlapping strided windows reuse left context while masking already-scored prefix tokens with -100 so every target enters the loss exactly once.[1] On WikiText-2 with GPT-2 Large, halving stride from 1,024 to 512 drops PPL from 19.44 to 16.44 with zero weight changes (compare GPT-2's original 19.93 with its own detokenizer[7]).

Three five-token windows over tokens A through J. The first reads A to E and scores B, C, D, and E. The second reads D to H and scores F, G, and H. The third reads F to J and scores I and J. Nine losses appear exactly once each, and A is never scored. They sum to 4.26 nats, the mean is 0.473, and perplexity is 1.61.
Three overlapping 5-token windows read context (shaded) and score B through J (filled) exactly once each. Without a BOS token, position A acts only as context.
count-shifted-targets.py
token_ids = torch.arange(10)  # A=0 .. J=9
windows = [(0, 5, 1), (3, 8, 5), (5, 10, 8)]
total_nll, total_targets, wrong_targets = 0.0, 0, 0

for begin, end, score_begin in windows:
    input_ids = token_ids[begin:end].unsqueeze(0)
    labels = input_ids.clone()
    labels[:, :score_begin - begin] = -100

    logits = torch.zeros(1, end - begin, 10, dtype=torch.float64)
    logits.scatter_(2, ((input_ids + 1) % 10).unsqueeze(-1), 3.0)

    shifted_labels = labels[:, 1:].reshape(-1)
    count = int((shifted_labels != -100).sum())
    wrong_count = int((labels != -100).sum()) - labels.shape[0]
    total_nll += F.cross_entropy(logits[:, :-1].reshape(-1, 10), shifted_labels, ignore_index=-100, reduction="sum").item()
    total_targets += count
    wrong_targets += wrong_count

print(f"Correct targets={total_targets} (wrong unshifted formula={wrong_targets})")
print(f"Exact shifted PPL={math.exp(total_nll / total_targets):.3f}")
Output
Correct targets=9 (wrong unshifted formula=6)
Exact shifted PPL=1.448

Perplexity vs. downstream accuracy and contamination

Even a spotless perplexity harness measures only unconditional next-token prose fit. Post-training (SFT and RLHF) concentrates probability mass onto helpful instruction-following trajectories, frequently causing a small alignment tax (slightly higher prose PPL) while driving verifiable task accuracy dramatically upward.[8] Conversely, memorizing easy boilerplate preambles ("The answer is clearly...") lowers sequence perplexity even while missing the critical factual answer token:

Scatter comparison of held-out validation perplexity against downstream task accuracy across three checkpoints: a memorized checkpoint scores low perplexity 6.4 with only 38 percent task accuracy, a base pretrained checkpoint scores perplexity 8.9 with 52 percent accuracy, and a post-trained instruction-tuned checkpoint reaches 84 percent accuracy despite slightly higher perplexity 9.8.
Lowest validation PPL picks the memorized model (6.4 PPL, 38% accuracy), whereas downstream task benchmarks pick the post-trained model (9.8 PPL, 84% accuracy).
preamble-ppl-vs-answer-accuracy.py
import numpy as np

rng = np.random.default_rng(7)
n = 200
p_easy_pre = rng.uniform(0.75, 0.96, size=(n, 10))
p_bad_ans = rng.uniform(0.15, 0.45, size=(n, 1))
p_good_pre = rng.uniform(0.55, 0.85, size=(n, 10))
p_good_ans = rng.uniform(0.65, 0.92, size=(n, 1))

for label, pre, ans in [("boilerplate-heavy", p_easy_pre, p_bad_ans), ("answer-aligned", p_good_pre, p_good_ans)]:
    seq = np.concatenate([pre, ans], axis=1)
    print(f"{label:18s} seq_ppl={np.exp(-np.log(seq).mean()):.2f}, answer_acc={(ans.squeeze(1) > 0.5).mean():.1%}")
Output
boilerplate-heavy  seq_ppl=1.29, answer_acc=0.0%
answer-aligned     seq_ppl=1.43, answer_acc=100.0%

Remember also that perplexity requires full next-token logits: many hosted APIs withhold prompt-token logprobs or omit them during reasoning modes,[9][10][11] making downstream task benchmarks the primary yardstick for closed models (calibrating LLM judges against human labels to control and verbosity bias[12]).

Finally, guard both perplexity and task suites against : check content n-gram overlap (not just document IDs), pair stable decontaminated holdouts with rotating fresh challenge sets such as LiveBench,[13] and remember that deleting a leaked document from a training manifest never erases it from an already-trained checkpoint.

Side-by-side comparison of evaluation partitions. Left: a contaminated split over documents d101 through d105 where d103 appears in both Train (d101, d102, d103) and Eval (d103, d201, d202), leaking training data into validation perplexity. Right: a clean rolling protocol across Runs 1 to 3 that holds decontaminated documents d201 and d202 fixed for regression tracking while rotating fresh challenge sets d301, d302, and d303.
Pair stable decontaminated holdouts for regression tracking with rotating fresh challenge sets to catch memorization.
SymptomLikely causeFirst check
Big PPL drop after tokenizer swapChanged target unitsCompare bits per byte on identical raw UTF-8 text
Same weights, lower PPLLonger context, smaller stride, or different splitVerify recorded protocol conditions match
Distributed score differs from single GPUAveraged shard PPLs or meansSum total NLL and shifted target counts globally
Inf or NaN in reportZero-probability target vs broken mathKeep Inf distinct; reject NaN or zero-target runs
Suspiciously low PPLEvaluation text leaked into trainingRun content n-gram decontamination on independent holdouts
Low PPL, weak task answersProse fit vs instruction/factual executionGrade with verifiable downstream benchmarks
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.Two scored causal targets receive probabilities 0.25 and 0.20. What are their mean NLL and perplexity, using natural logs?
2.For logits [1200,1199,1197] and observed ID 1, which shifted logits and target NLL preserve the original distribution?
3.One worker has mean NLL 0.4 over 3 targets; another has mean NLL 1.6 over 9 targets. What corpus perplexity follows from equal weight per target?
4.Each run lists its checkpoint, held-out corpus, preprocessing, tokenizer, context length and stride (both in tokens). Oak recorded v1, H, raw, K, 1200, 300. Elm recorded v2, H, raw, K, 1200, 150. Ash recorded v2, H, raw, K, 1200, 300. All other scoring settings match. Which comparison isolates the effect of the checkpoint on perplexity?
5.The same 20 scored bytes give model Reed total NLL 6 nats over 3 tokens and model Moss 8 nats over 10 tokens. Which BPB pair and raw-token comparison are valid?
6.A no-BOS document has positions 0 through 11. Three windows read [0,6), [3,9), [6,12) and score [1,6), [6,9), [9,12), respectively. How many distinct targets contribute, and how many times is position 7 scored?
7.Model A (memorized/overfit) scores held-out PPL 6.4 and 38% accuracy on an unseen factual QA suite. Model B (post-trained) scores held-out PPL 9.8 and 84% accuracy on the same QA suite. Which statement accurately describes this comparison?
8.The label rows before the causal shift are [−100, 3, −100, 4, 5] and [7, −100, 1, −100, 2]. The loss ignores −100. After the shift, how many targets contribute to the loss across both rows?
9.A frozen checkpoint trained on a passage later copied into evaluation under a new ID. Which repair produces clean generalization evidence from the existing checkpoint?
10.A causal model scores each target from left context and reports 5. A masked model scores each hidden target from both sides and reports pseudo-perplexity 3. Do these share one conditioning objective, and does their raw ranking isolate a model improvement?

10 questions remaining.

References

Perplexity of fixed-length models

Hugging Face · 2026

https://huggingface.co/docs/transformers/perplexity

Masked Language Model Scoring

Salazar, J., Liang, D., Nguyen, T. Q., and Kirchhoff, K. · 2020 · ACL 2020

https://aclanthology.org/2020.acl-main.240/

CrossEntropyLoss

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/2.14/generated/torch.nn.CrossEntropyLoss.html

PALOMA: A Benchmark for Evaluating Language Model Fit.

Magnusson, I., et al. · 2024 · NeurIPS 2024 Datasets and Benchmarks Track

https://arxiv.org/abs/2312.10523

The Pile: An 800GB Dataset of Diverse Text for Language Modeling.

Gao et al. · 2020

https://arxiv.org/abs/2101.00027

Text Normalization in SentencePiece

Google · 2026

https://github.com/google/sentencepiece/blob/master/doc/normalization.md

Language Models are Unsupervised Multitask Learners.

Radford, A., et al. · 2019

https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf

The Curious Case of Neural Text Degeneration.

Holtzman, A., et al. · 2020 · ICLR 2020

https://arxiv.org/abs/1904.09751

Using GPT-6

OpenAI · 2026

https://developers.openai.com/api/docs/guides/latest-model

Create a Message

Anthropic · 2026

https://platform.claude.com/docs/en/api/messages/create

Create chat completion

OpenAI · 2026

https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create

Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena.

Zheng, L., et al. · 2023 · NeurIPS 2023

https://arxiv.org/abs/2306.05685

LiveBench: A Challenging, Contamination-Limited LLM Benchmark

White, C., et al. · 2024

https://arxiv.org/abs/2406.19314

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.