Evaluating LLMs: Perplexity, Benchmarks and Judges
Every claim about a language model, "the quantized model is as good", "fine-tuning helped", "model B beats model A", is an evaluation result, and most published ones are hard to reproduce because the details were left out: which tokenizer normalised the perplexity, how multiple-choice answers were scored, how many samples were drawn per coding problem, which judge compared the answers and in which order. Change a detail and the ranking can flip.
Evaluating LLM Apps treated evaluation from the application side (test sets, simple metrics, a judge). This lesson is about evaluating the model, with the details that decide the numbers: perplexity done right, log-likelihood scoring of multiple-choice benchmarks, BLEU and ROUGE-L from scratch, the unbiased pass@k estimator, pairwise comparisons with confidence intervals, Bradley–Terry and Elo ratings, and contamination. RAG-specific metrics (recall@k, nDCG, faithfulness) are in Evaluating Retrieval and RAG.
Perplexity done right
For a text of tokens with model probabilities , the perplexity is the exponential of the mean negative log-likelihood per token:
The definition hides three choices:
- Per what? The sum (the total NLL of the text) does not depend on the tokenizer if every model assigns a probability to the same string; the divisor does. A model with a smaller vocabulary splits text into more tokens, each easier to predict. To compare models with different tokenizers, divide the total NLL by a tokenizer-independent unit: characters, bytes (bits per byte, ) or words (per-word perplexity).
- What counts as a token? A closed vocabulary with an
<unk>token makes every unknown word one cheap, shared event: its perplexity looks good because it is not predicting the hard part. - How much context? A model with a maximum context of tokens cannot score a long text in one pass. Cutting it into disjoint windows leaves the first tokens of each window with almost no context and inflates perplexity. A sliding window with stride scores only the last tokens of each window, so every token (after the first window) gets at least tokens of context.
The example trains two tiny models on 8 TAD Bikes sentences and scores 4 new ones: an interpolated character model with up to 4 characters of context, and a word bigram model with <unk> for words not seen in training. Then it scores the character model with a context window of 8 characters and different strides.
import math, re
from collections import Counter
train = ("rentals are charged per hour. the first 30 minutes cost 2 euros and every extra hour costs 3 euros. "
"a day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock. "
"to unlock a bike, scan the code on the handlebar with the app and wait for the green light. "
"if the lock does not open, check that bluetooth is on and move closer to the bike. "
"return the bike at any station. push it into a free dock until the light turns green. "
"if a station is full, the app shows the nearest station with free docks. "
"report a damaged bike in the app and add a photo of the damage. "
"electric bikes have a range of about 60 km. the battery level is shown in the app. ")
test = ("a lost bike must be reported within 24 hours. you can pay with a card or the app wallet. "
"bikes can be reserved for up to 10 minutes before the unlock. the app shows the battery level. ")
# character model: interpolated n-grams up to order 5 (context of at most 4 characters)
ORDER, LAM = 5, [0.05, 0.1, 0.15, 0.3, 0.4] # weights for orders 1..5
chars = sorted(set(train + test))
counts = [Counter(train[i - n + 1:i + 1] for i in range(n - 1, len(train))) for n in range(1, ORDER + 1)]
def p_char(history, c):
p = 1 / len(chars) * 0.01
for n in range(1, ORDER + 1):
h = history[-(n - 1):] if n > 1 else ""
if len(h) < n - 1:
break # not enough context: higher orders unavailable
ctx = counts[n - 2][h] if n > 1 else len(train)
if ctx:
p += LAM[n - 1] * counts[n - 1][h + c] / ctx
return p
def char_nll(text, window, stride):
"""Score text with a model that sees at most `window` characters, sliding by `stride`."""
total, scored = 0.0, 0
for start in range(0, len(text), stride):
lo = max(0, start + stride - window) # window ends at start + stride
for i in range(start, min(start + stride, len(text))):
total -= math.log(p_char(text[lo:i], text[i]))
scored += 1
return total, scored
# word model: add-0.1 bigram over the training vocabulary plus <unk>
words = lambda t: re.findall(r"[a-z0-9]+|\.", t)
vocab = set(words(train)) | {"<unk>"}
tw = [w if w in vocab else "<unk>" for w in words(train)]
uni, bi = Counter(tw), Counter(zip(tw, tw[1:]))
def word_nll(text):
ws = [w if w in vocab else "<unk>" for w in words(text)]
nll = sum(-math.log((bi[(a, b)] + 0.1) / (uni[a] + 0.1 * len(vocab))) for a, b in zip(ws, ws[1:]))
return nll, len(ws) - 1, sum(w == "<unk>" for w in ws)
n_words = len(re.findall(r"[a-z0-9]+", test))
c_nll, n_chars = char_nll(test, window=len(test), stride=len(test))
w_nll, n_wtok, n_unk = word_nll(test)
print(f"test: {n_chars} characters, {n_words} words")
print(f"char model: token perplexity {math.exp(c_nll / n_chars):6.2f}, bits/char {c_nll / n_chars / math.log(2):.3f}, "
f"per-word perplexity {math.exp(c_nll / n_words):8.1f}")
print(f"word model: token perplexity {math.exp(w_nll / n_wtok):6.2f}, per-word perplexity {math.exp(w_nll / n_words):8.1f}"
f" ({n_unk} of {n_wtok + 1} test tokens are <unk>)")
print("\ncontext handling for the char model (window of 8 characters):")
for stride in (8, 6, 4, 1):
nll, n = char_nll(test, window=8, stride=stride)
print(f" stride {stride}: perplexity {math.exp(nll / n):.3f}")test: 184 characters, 37 words
char model: token perplexity 11.59, bits/char 3.535, per-word perplexity 195824.0
word model: token perplexity 59.67, per-word perplexity 83.1 (17 of 41 test tokens are <unk>)
context handling for the char model (window of 8 characters):
stride 8: perplexity 26.531
stride 6: perplexity 13.878
stride 4: perplexity 11.591
stride 1: perplexity 11.591
- The token perplexities, 11.59 and 59.67, cannot be compared: one predicts characters, the other words.
- Normalised per word, the character model's perplexity is 195,824 and the word model's 83.1. That looks like a crushing win for the word model, but 17 of its 41 test tokens are
<unk>: it "predicts" one shared unknown-word token where the character model has to spell out "reported", "wallet" and "reserved" letter by letter. The fair comparison needs an open vocabulary on both sides, which is one reason modern LMs use byte-level tokenizers. - With a window of 8 characters, disjoint windows (stride 8) give 26.531, stride 6 gives 13.878, and stride 4 or less gives 11.591, exactly the full-context value, because the model never uses more than 4 characters of context. For a real LLM with , a stride of 512 is a common choice; report and with the number.
Multiple-choice benchmarks by log-likelihood
Benchmarks such as MMLU or HellaSwag ask a question with options. A base model is not asked to write "B"; instead, each option is appended to the question, and the model's log-probability of the option's tokens is computed. The prediction is the option with the highest score. The score has to be normalised for length, because a sum of log-probabilities is lower for longer options:
The EleutherAI evaluation harness reports both the plain sum as acc and the per-character version (divided by the option's string length) as acc_norm, which is why papers quoting "HellaSwag accuracy" can differ by several points for the same model.
import numpy as np
# Per-token log-probabilities a model gave to each answer option after the question (toy numbers).
items = [
("How long can a bike be reserved?", 1,
{"5 min": [-1.7, -0.3], "up to 10 minutes": [-1.2, -0.6, -0.3, -0.2],
"one day": [-1.9, -0.5]}),
("What does a day pass cost?", 2,
{"free": [-2.6], "3 euros per hour": [-1.4, -0.5, -0.9, -0.4], "15 euros": [-1.2, -0.3]}),
("Which payment is not accepted?", 0,
{"cash": [-1.6], "a credit card": [-1.0, -0.9, -0.2], "the app wallet": [-1.1, -0.8, -0.5]}),
("Who may not rent bikes?", 2,
{"adults": [-2.4], "students": [-2.2], "children under fourteen": [-1.5, -0.5, -0.4, -0.2]}),
]
def pick(options, method):
def score(text, lp):
if method == "sum":
return sum(lp) # total log-likelihood: favours short options
if method == "per token":
return sum(lp) / len(lp)
return sum(lp) / len(text) # per character (tokenizer-independent length)
return max(options, key=lambda o: score(o, options[o]))
for method in ["sum", "per token", "per char"]:
picks = [pick(opts, method) for _, _, opts in items]
acc = np.mean([p == list(opts)[gold] for p, (_, gold, opts) in zip(picks, items)])
print(f"{method:<10} accuracy {acc:.2f} picks {picks}")sum accuracy 0.50 picks ['5 min', '15 euros', 'cash', 'students']
per token accuracy 0.75 picks ['up to 10 minutes', '15 euros', 'a credit card', 'children under fourteen']
per char accuracy 0.75 picks ['up to 10 minutes', '15 euros', 'a credit card', 'children under fourteen']
The sum prefers the short, wrong "5 min" and "students" and scores 0.50; both normalisations reach 0.75 with different picks from the sum. On "Which payment is not accepted?", the sum is right ("cash") and the normalised scores are wrong ("a credit card"): no normalisation is best everywhere. Per-token normalisation also depends on the tokenizer, per-character normalisation does not. The other common format, asking an instruction-tuned model to output the letter and parsing it, measures something else again: instruction following plus knowledge. The rule is to report the method and use the same one for every model you compare.
Generation metrics: BLEU and ROUGE-L
For tasks with reference outputs (translation, summarisation), n-gram overlap metrics are cheap and standard. BLEU (Papineni et al., 2002) computes, over the whole corpus, the clipped precision of the hypothesis n-grams for (each n-gram counts at most as often as it occurs in the reference), takes their geometric mean, and multiplies by a brevity penalty that stops short outputs from gaming precision:
with and the total hypothesis and reference lengths. ROUGE-L measures the longest common subsequence (LCS) of words, which rewards in-order overlap without requiring contiguous n-grams: , and their F-measure. Exact match and token F1 are covered in the RAG evaluation lesson.
import math
from collections import Counter
from nltk.translate.bleu_score import corpus_bleu
refs = ["the first thirty minutes cost two euros and each extra hour costs three euros",
"return the bike to any station and push it into a free dock",
"cash is not accepted , but you can pay by card or with the app wallet"]
hyps = ["the first thirty minutes cost two euros and every additional hour costs three euros",
"push the bike into a free dock at any station",
"cash is accepted , and you can pay by card or with the app wallet"]
def ngrams(ws, n):
return Counter(tuple(ws[i:i + n]) for i in range(len(ws) - n + 1))
def bleu(refs, hyps, N=4):
"""Corpus BLEU (Papineni et al.): clipped n-gram precisions pooled over the corpus, geometric mean, brevity penalty."""
match, total = [0] * N, [0] * N
hyp_len = ref_len = 0
for r, h in zip(refs, hyps):
r, h = r.split(), h.split()
hyp_len += len(h); ref_len += len(r)
for n in range(1, N + 1):
hn, rn = ngrams(h, n), ngrams(r, n)
match[n - 1] += sum(min(c, rn[g]) for g, c in hn.items())
total[n - 1] += max(len(h) - n + 1, 0)
precisions = [m / t for m, t in zip(match, total)]
bp = 1.0 if hyp_len > ref_len else math.exp(1 - ref_len / hyp_len)
return bp * math.exp(sum(math.log(p) for p in precisions) / N), precisions, bp
def rouge_l(ref, hyp):
"""ROUGE-L F1 from the longest common subsequence of words."""
r, h = ref.split(), hyp.split()
L = [[0] * (len(h) + 1) for _ in range(len(r) + 1)]
for i in range(len(r)):
for j in range(len(h)):
L[i + 1][j + 1] = L[i][j] + 1 if r[i] == h[j] else max(L[i][j + 1], L[i + 1][j])
lcs = L[-1][-1]
p, rec = lcs / len(h), lcs / len(r)
return 0.0 if lcs == 0 else 2 * p * rec / (p + rec)
score, precisions, bp = bleu(refs, hyps)
print("n-gram precisions", [round(p, 3) for p in precisions], f"brevity penalty {bp:.3f}")
print(f"BLEU (ours) {score:.4f}")
print(f"BLEU (NLTK) {corpus_bleu([[r.split()] for r in refs], [h.split() for h in hyps]):.4f}")
for r, h in zip(refs, hyps):
print(f"ROUGE-L {rouge_l(r, h):.3f} {h}")n-gram precisions [0.897, 0.722, 0.545, 0.467] brevity penalty 0.903
BLEU (ours) 0.5752
BLEU (NLTK) 0.5752
ROUGE-L 0.857 the first thirty minutes cost two euros and every additional hour costs three euros
ROUGE-L 0.522 push the bike into a free dock at any station
ROUGE-L 0.903 cash is accepted , and you can pay by card or with the app wallet
Our corpus BLEU equals NLTK's corpus_bleu, 0.5752 (unsmoothed, uniform weights). The brevity penalty of 0.903 comes from the second hypothesis, which is shorter than its reference. And again the warning from the RAG lesson: "cash is accepted, and you can pay..." gets the highest ROUGE-L, 0.903, while reversing the meaning, and the faithful paraphrase "push the bike into a free dock at any station" gets the lowest, 0.522. Overlap metrics track surface form. They are useful for regression tests on a fixed system, but poor at ranking different LLMs, whose correct answers can be worded in many ways. For reproducible BLEU across papers, use SacreBLEU, which fixes the tokenization.
Code: the unbiased pass@k
For code generation, an answer is correct if it passes unit tests, and a model gets attempts: pass@k is the probability that at least one of samples passes. With a per-sample success rate for problem , pass@k . Drawing exactly samples per problem gives an unbiased but noisy estimate. Chen et al. (2021) draw samples, count the correct ones, and use
the probability that a random subset of of the samples contains a correct one. It is unbiased, and the product form avoids huge binomial coefficients. Plugging into looks natural but is biased low, because is concave in (Jensen's inequality).
import numpy as np
from math import comb
def pass_at_k(n, c, k):
"""Unbiased estimator (Chen et al., 2021): 1 - C(n-c, k) / C(n, k), as a stable product."""
if n - c < k:
return 1.0
return 1.0 - float(np.prod(1.0 - k / np.arange(n - c + 1, n + 1)))
print("check against the binomial formula:", round(pass_at_k(20, 3, 5), 6), round(1 - comb(17, 5) / comb(20, 5), 6))
# 6 problems, true per-sample success probabilities (unknown in practice)
true_p = np.array([0.9, 0.5, 0.2, 0.05, 0.02, 0.0])
k, n = 5, 20
truth = np.mean(1 - (1 - true_p) ** k)
rng = np.random.default_rng(0)
unbiased, plug_in, only_k = [], [], []
for _ in range(2000): # repeat the whole evaluation 2000 times
c = rng.binomial(n, true_p) # correct samples out of n per problem
unbiased.append(np.mean([pass_at_k(n, ci, k) for ci in c]))
plug_in.append(np.mean(1 - (1 - c / n) ** k)) # plug the estimate c/n into 1-(1-p)^k
first_k = rng.binomial(k, true_p) # or draw only k samples: pass if any is correct
only_k.append(np.mean(first_k > 0))
print(f"true pass@{k} {truth:.4f}")
for name, v in [("unbiased, n = 20", unbiased), ("plug-in 1-(1-c/n)^k", plug_in), ("only k = 5 samples", only_k)]:
print(f"{name:<22} mean {np.mean(v):.4f} std {np.std(v):.4f}")check against the binomial formula: 0.600877 0.600877
true pass@5 0.4939
unbiased, n = 20 mean 0.4951 std 0.0509
plug-in 1-(1-c/n)^k mean 0.4807 std 0.0485
only k = 5 samples mean 0.4934 std 0.1197
Over 2,000 repetitions of a 6-problem evaluation, the unbiased estimator averages 0.4951 against the true 0.4939, the plug-in estimate 0.4807 (biased low), and drawing only samples is unbiased (0.4934) but has more than twice the standard deviation (0.1197 against 0.0509).
Judges, pairwise comparisons and ratings
For open-ended answers there is no reference, so models are compared pairwise: a judge (a human or a strong LLM) sees one prompt and two answers and picks the better one. The RAG evaluation lesson lists the judge's biases (position, verbosity, self-preference). Here is the statistics side:
- Win rate with a confidence interval. The share of wins of A against B is a proportion from a small sample; bootstrap it (resample the games with replacement) or use a binomial interval.
- Bradley–Terry. With many models, fit one strength per model so that , by maximum likelihood over all games. Hunter's MM algorithm updates as , with the wins of and the games between and . This is what public LLM leaderboards built from human votes fit.
- Elo is the online version from chess: after each game, the winner gains points, with the expected score. It depends on the order of the games, which makes no sense for a fixed set of model comparisons.
The simulation uses 4 models with known strengths and a judge that adds a bonus of 0.4 to whichever answer it sees first; the order is randomised per game, as it should be.
import numpy as np
rng = np.random.default_rng(0)
models = ["A", "B", "C", "D"]
strength = np.array([1.0, 0.6, 0.0, -0.4]) # true Bradley-Terry log-strengths (unknown in practice)
POSITION_BIAS = 0.4 # the judge favours the answer shown first
def judge(i, j): # True if the answer of model i (shown first) wins
return rng.random() < 1 / (1 + np.exp(-(strength[i] - strength[j] + POSITION_BIAS)))
games, first_won = [], [] # (winner, loser); order shown is random
for _ in range(800):
i, j = rng.choice(4, 2, replace=False)
won = judge(i, j)
games.append((i, j) if won else (j, i))
first_won.append(won)
print(f"the answer shown first won {np.mean(first_won):.1%} of 800 games")
# win rate of A against B with a bootstrap 95% confidence interval
ab = np.array([w == 0 for w, l in games if {w, l} == {0, 1}])
boot = [rng.choice(ab, len(ab)).mean() for _ in range(5000)]
print(f"A vs B: {len(ab)} games, A wins {ab.mean():.3f}, 95% CI [{np.percentile(boot, 2.5):.3f}, {np.percentile(boot, 97.5):.3f}]")
# Bradley-Terry by the MM algorithm (Hunter, 2004): p_i <- W_i / sum_j n_ij / (p_i + p_j)
W = np.zeros(4); n = np.zeros((4, 4))
for w, l in games:
W[w] += 1; n[w, l] += 1; n[l, w] += 1
p = np.ones(4)
for _ in range(200):
p = W / np.array([sum(n[i, j] / (p[i] + p[j]) for j in range(4) if j != i) for i in range(4)])
p /= np.exp(np.mean(np.log(p)))
bt = np.log(p)
print("Bradley-Terry log-strength:", {m: round(float(s - bt[2]), 2) for m, s in zip(models, bt)}, "(C = 0)")
print("true :", {m: round(float(s - strength[2]), 2) for m, s in zip(models, strength)})
# Elo: an online update, so the result depends on the order of the games
def elo(order, K=16):
r = np.full(4, 1000.0)
for w, l in order:
e = 1 / (1 + 10 ** ((r[l] - r[w]) / 400))
r[w] += K * (1 - e); r[l] -= K * (1 - e)
return {m: int(round(x)) for m, x in zip(models, r)}
print("Elo, games in order :", elo(games))
print("Elo, same games reversed :", elo(games[::-1]))the answer shown first won 57.0% of 800 games
A vs B: 120 games, A wins 0.592, 95% CI [0.500, 0.683]
Bradley-Terry log-strength: {'A': 1.02, 'B': 0.54, 'C': 0.0, 'D': -0.51} (C = 0)
true : {'A': 1.0, 'B': 0.6, 'C': 0.0, 'D': -0.4}
Elo, games in order : {'A': 1121, 'B': 1042, 'C': 985, 'D': 851}
Elo, same games reversed : {'A': 1137, 'B': 1113, 'C': 944, 'D': 806}
- The judge's position bias is visible: the answer shown first won 57.0% of the games. Randomising the order makes it noise rather than a systematic advantage for one model; showing both orders per pair removes it from each verdict.
- A beat B in 0.592 of 120 games, but the 95% interval reaches 0.5: 120 judgements cannot settle a 59% preference.
- Bradley–Terry recovers the true strengths closely (A 1.02, B 0.54, D against 1.0, 0.6 and , with C fixed at 0).
- Elo on the same 800 games gives B 1042 in one order and 1113 in the reverse order: the same evidence, a 71-point difference. Fit Bradley–Terry (and bootstrap its intervals) instead.
Contamination
A benchmark measures generalisation only if its test items were not in the training data. Web-scale pretraining sets contain copies of popular benchmarks, their solutions and discussions of them. Signs and checks:
- n-gram overlap: the share of a test item's long n-grams (13-grams are a common choice) found in the training corpus, ; flag items above a threshold and report scores with and without them.
- Memorisation probes: the model completes a test question verbatim from its first half, or reproduces the options in their original order.
- Fresh items: a new, private test set written after the model's training cutoff; a large drop from the public to the fresh set signals contamination.
The same applies to your own fine-tuning: an evaluation set that leaks into the training data, through duplicates or near-duplicates, inflates every number (leakage rules).
Pitfalls
- Comparing perplexities across tokenizers. Normalise per byte, character or word, with open vocabularies on both sides.
- Disjoint windows. They inflate perplexity; use a sliding window and report context and stride.
- Unreported scoring rules. Sum versus length-normalised log-likelihood, prompt format, number of shots: all change benchmark accuracy.
- BLEU or ROUGE as a quality ranking for LLMs. They measure overlap with one reference, not correctness.
- pass@k from exactly k samples, or from the plug-in formula. Use samples and the unbiased estimator.
- Win rates without intervals, Elo with one ordering. Bootstrap, and fit Bradley–Terry.
- Benchmarks the model has seen. Check contamination, and keep a private test set.
Practice
- Model X has total NLL 1,200 nats on a 1,000-byte text with 250 tokens; model Y has 1,150 nats with 400 tokens. Which has the lower token perplexity, and which is better per byte?
- In the multiple-choice example, compute the three scores of "5 min" and "up to 10 minutes" by hand.
- A hypothesis has 10 words and its reference 12; the n-gram precisions are 0.8, 0.6, 0.4, 0.3. What is BLEU?
- With samples and correct, compute the unbiased pass@1 and pass@5.
- Why does randomising the order of answers not remove the position bias from a single verdict, while showing both orders does?
Answers
- Token perplexity: X , Y , so Y looks far better per token. Per byte both see the same 1,000 bytes: X bits per byte, Y . Y is better, but by 4%, not by a factor of 7.
- "5 min": sum , per token , per character . "up to 10 minutes": sum , per token , per character . The sum prefers "5 min", both normalisations prefer "up to 10 minutes".
- Geometric mean: . Brevity penalty . BLEU .
- pass@1 (equal to ). pass@5 .
- With a random order, each verdict still carries the bonus for whichever answer was first; over many games it averages out between the models but adds noise. Judging both orders and counting a win only when both agree (a tie otherwise) cancels the bonus within each comparison.
Test yourself
Two models use different tokenizers. Which quantity can you compare between them?
- Token perplexity
- Mean loss per token
- Bits per byte of the same text
- Vocabulary size
Why does scoring a long text in disjoint context windows overestimate perplexity?
- The model sees future tokens
- The first tokens of each window are predicted with little or no context
- The windows overlap
- The softmax is computed twice
What is the unbiased pass@k estimator from samples with correct?
In the simulation, Elo ratings of the same 800 games in two orders differed by 71 points for model B. What should you fit instead?
- A higher K factor
- Bradley-Terry by maximum likelihood over all games
- Only the last 100 games
- Win rates without intervals
"cash is accepted, and you can pay by card..." got the highest ROUGE-L in the example. What does that show?
- ROUGE-L is computed wrongly
- Overlap metrics reward surface form, not meaning
- LCS ignores word order
- BLEU would have caught it