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.
Perplexity 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 assigned to each actual next token. Its negative log-likelihood (NLL), or surprise, is . A certain hit () costs nats; a confident miss () costs nats.
Averaging NLL across scored tokens gives the causal cross-entropy loss , and exponentiating gives perplexity:
Perplexity acts like an effective branching factor: guessing uniformly among equally likely tokens gives and (formally, PPL is the inverse geometric mean of observed token probabilities). Because the mapping is exponential, every nats doubles perplexity, and a confidently wrong model can easily exceed its own vocabulary size (assigning to every token in a 2-token vocabulary gives ). 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]


Computing stably from logits and aggregating once
Models output raw logits, 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:
- Keep
infdistinct fromNaN: An exact zero probability for an observed target yields infinite NLL (legitimate and terrible);NaNmeans the pipeline broke and must be rejected. If finite mean NLL is huge (say 1,000 nats), report loss rather than clipping it to preventexpoverflow. - 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.
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}")Stable log-softmax -> NLL=0.170 nats, PPL=1.185
Wrong mean of window PPLs: 4.52
Token-weighted corpus PPL: 5.47Why must an evaluator sum negative log-likelihoods and target counts before dividing and exponentiating?
Answer
Products of token probabilities underflow toward zero, and averaging per-window perplexities both misweights uneven windows and breaks the nonlinearity of .
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, stride, document boundaries, and target masking (always in model.eval() with dropout disabled and unmodified logits, no temperature or top-). 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]

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 instead to compute bits per byte (BPB) (used by The Pile and Paloma):[5][4]
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.

import mathimport 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)")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]).

import math
import torch
import torch.nn.functional as F
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}")Correct targets=9 (wrong unshifted formula=6)
Exact shifted PPL=1.448Perplexity 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:

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%}")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 position and verbosity bias[12]).
Finally, guard both perplexity and task suites against contamination: 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.

| Symptom | Likely cause | First check |
|---|---|---|
| Big PPL drop after tokenizer swap | Changed target units | Compare bits per byte on identical raw UTF-8 text |
| Same weights, lower PPL | Longer context, smaller stride, or different split | Verify recorded protocol conditions match |
| Distributed score differs from single GPU | Averaged shard PPLs or means | Sum total NLL and shifted target counts globally |
Inf or NaN in report | Zero-probability target vs broken math | Keep Inf distinct; reject NaN or zero-target runs |
| Suspiciously low PPL | Evaluation text leaked into training | Run content n-gram decontamination on independent holdouts |
| Low PPL, weak task answers | Prose fit vs instruction/factual execution | Grade with verifiable downstream benchmarks |
A base model has lower held-out perplexity (8.9) than a post-trained instruction checkpoint (9.8), yet scores 30 points lower on verifiable QA accuracy. Which should you deploy for QA?
Answer
Deploy the post-trained checkpoint. Perplexity tracks unconditional prose likelihood, whereas post-training trades a small alignment tax in raw PPL for large gains in task execution and factual grounding.