Evaluation

A benchmark score is one number built from many choices. On the same 200 questions, a stricter answer parser moves a toy model from 65% to 39%. Each score carries an error bar of about 7 points either way.

Grade two toy models on one test. Change the prompt, the grader and the test size, then let Model A see part of the test. Then we build each part from zero: perplexity, choice scoring, pass@k, error bars, judges, arena ratings and contamination tests.

You need a probability and the training loss, the average surprise of the next token. We build the rest from zero.

Lecture 12 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto). Previous: Lecture 11, Scaling Laws II. Next: Lecture 13, Data I.

Grade two models on one test

200

Illustrative toy, computed live. Two simulated models answer simulated four-choice questions. Model B writes chatty replies, so a strict parser misses some of its right answers. The bars show a 95% interval. No real model or benchmark numbers here.

Chapter 0

What Goes Into a Score

Follow one question from prompt to mark, and count the choices that can flip it

A model release shows a table: MMLU 84.2, GSM8K 91.4, HumanEval 78.6 (made-up numbers). The lecture asks two questions about it. What are these benchmarks? What do the numbers mean? A score looks like a fact about the model. It is a fact about the model and about every choice in the test.

The lecture sorts those choices into four questions:

  1. Inputs. Which use cases does the test cover? Does it hold the hard cases in the tail?
  2. Calling the model. How do you prompt it? Does it use chain of thought, tools or retrieval? Do you test the model, or an agent system built on it?
  3. Grading the outputs. Are the reference answers right? Which metric? Do cost and asymmetric errors count? What if there is no answer key?
  4. Reading the result. Is 91% ready to ship? Did the model see the test? Are you rating a model or a method?

There is no one true evaluation, the lecture says. Each purpose needs its own test: a buyer choosing a chatbot model, a researcher measuring raw ability, a policy team weighing harms, a developer looking for feedback.

Send one question through the pipeline

The model and the question stay fixed. Choose the prompt and the grader, and watch the mark.

Illustrative. An MMLU-style item written for this lesson. We made up the replies and the letter probabilities.

Worked number, from the hero: the strict parser drops Model B from 65.0% to 39.0% on 200 questions. That is 52 right answers marked wrong. The model did not change; the grader did.

Symptom: two papers report different scores for the same model on the same benchmark.

Measure: compare the prompt, the number of examples, the grader and the test version.

Fix: run every model under one harness with one prompt and one grader. HELM does this for many models at once.

The road

  1. Perplexity: the loss on held-out text, made readable.
  2. Choices: score each option by its probability.
  3. pass@k: many samples, one checker.
  4. Error bars: a test is a sample of questions.
  5. Judges: a model grades open answers, with biases.
  6. Arena: human votes become ratings.
  7. Contamination: did the model see the test?
  8. Realism: price the system you ship, on real prompts.
  9. Showcase: run a leaderboard and break it.
  10. Field guide: the table, the code and the habits.
Paper X reports 88% on a benchmark with 5 examples in the prompt. The best earlier model reported 85% with no examples. What can you conclude?

Chapter 1

Perplexity: The Loss, Made Readable

Turn the average surprise per token into a count of equally likely choices

Before benchmarks, a language model had one test: how surprised is it by text it never trained on? At each position it gives a probability to the true next token. High probability, little surprise.

Call the text's length in tokens T, and the probability of the true token at position t, given the tokens before it, p(xt | x<t). A token's surprise is minus its log probability. The average surprise is the loss L:

Say it aloud

L equals minus one over T, times the sum over t of the log of p of x-t given the tokens before t.

L
L the loss: the average surprise per token, in nats. Training minimizes this number.
1/T
one over T divide by the number of tokens, so the sum becomes an average.
Σt
the sum over t add one term for each position, 1 to T.
ln
the log the natural log. It is negative for a probability below 1, so the minus sign makes surprise positive.
p(xt | x<t)
p of x-t given the tokens before t the probability the model gives the true token at position t.
In plain words

For each position t, take the probability of the true token and its log. Flip the sign to get the surprise. Average the T surprises: that is L.

With numbers

With made-up numbers: probabilities 0.5, 0.3 and 0.2 have logs −0.693, −1.204 and −1.609. L = 3.506 / 3 = 1.169 nats per token.

A loss of 1.169 nats is hard to picture. Perplexity turns it back into a count:

Say it aloud

P-P-L equals e to the L.

PPL
P-P-L perplexity: how many equally likely tokens the model is choosing between, on average. 1 is perfect.
e
e the base of the natural log, about 2.718. It undoes the ln inside L.
L
L the loss from the equation above, in nats per token.
In plain words

Raise e to the loss L. The answer is the number of sides of a fair die that is as surprising, on average, as the text is to the model.

With numbers

L = 1.169 gives PPL = e1.169 = 3.22. The lecture's form, (1/p(D))1/|D|, agrees: the cube root of 1 / (0.5 × 0.3 × 0.2) = 33.3 is 3.22. A uniform guess over 50,257 tokens has PPL = 50,257.

Turn surprise into perplexity

Each chip is a true next token; the pink bar is its surprise. Pick a model, then drag the probability of "mat".

0.40

Illustrative, made-up probabilities; exact arithmetic.

Perplexity is per token, and tokenizers differ: longer tokens mean fewer, harder predictions. Across tokenizers, measure surprise per byte. With B the number of bytes:

Say it aloud

Bits per byte equals T times L, over B times the log of 2.

bpb
bits per byte the model's surprise per byte of text. It does not depend on the tokenizer.
T
T the number of tokens the tokenizer made from the text.
L
L the loss, in nats per token.
B
B the number of UTF-8 bytes in the same text.
ln 2
the log of 2 0.693 nats in one bit; dividing by it turns nats into bits.
In plain words

Multiply L by T to get the total surprise of the text. Turn nats into bits by dividing by ln 2. Divide by the B bytes.

With numbers

With made-up losses: model X has 3.76 bytes per token and L = 3.0. So PPL = 20.1 and bpb = 3.0 / (3.76 × 0.693) = 1.15. Model Y has 2.50 bytes per token and L = 2.2: PPL = 9.03, bpb = 1.27. Y wins on perplexity and loses per byte.

Papers once trained and tested on splits of one dataset. GPT-2 tested zero-shot: its 1.5B model reached 17.48 on WikiText-103, past the old best of 18.3, but 42.16 on One Billion Word, where the best was 21.8. Perplexity stays useful because it is smoother than accuracy, so scaling laws fit it. But a leaderboard must trust that the model's probabilities add to 1.

Symptom: a model with a smaller vocabulary shows a much lower perplexity.

Measure: compute bits per byte on the same text.

Fix: compare perplexity only under one tokenizer; across tokenizers, compare bits per byte.

A model's loss on a test set is 2.3 nats per token. What is its perplexity? (e2.3 ≈ 9.97)

Chapter 2

Multiple Choice: Read the Answer From the Probabilities

Score each option by its probability, and watch the scoring rule pick the winner

Since GPT-2 and GPT-3, papers report accuracy on tasks more than perplexity. The best known is MMLU (Hendrycks et al., 2021): 57 subjects, four choices per question, 15,908 questions with 14,079 in the test set. Students collected them from free online sources. The lecture's verdict: it tests knowledge more than language understanding. GPT-3 175B, with examples in the prompt, scored 43.9%. Guessing scores 25%.

There are two ways to read the model's choice. Generation: let the model write, then parse the reply, as in Chapter 0. Log-likelihood: write nothing; put each option after the prompt and read its probability. Call the prompt q and an option c:

Say it aloud

c-hat equals the c that makes log p of c given q largest.

ĉ
c-hat the model's predicted option. The grader marks it right if it equals the key.
argmaxc
the c that makes it largest try every option and keep the winner, not the score.
log p(c | q)
log p of c given q the sum of the log probabilities of the option's tokens, read after the prompt q. The prompt holds the question, the options and "Answer:".
In plain words

For each option c, run the model on q followed by c. Add up the log probabilities of c's tokens. The option with the largest total is c-hat.

With numbers

From the device, scoring letters: log p(" A") = −3.1, " B" −4.7, " C" −2.9, " D" −1.4. The largest is −1.4, so c-hat = D. As a probability, e−1.4 = 0.25; shared out over the four letters, D holds 0.69.

Pick the answer three ways

The key is D. Each bar is an option's score. Choose what you score, then make answer D longer.

4 tokens

Illustrative log probabilities. Each token after the first two in answer D adds −0.4 to its sum.

Summing favours short options: each extra token can only lower the total. Harder benchmarks followed as MMLU filled up:

BenchmarkSizeWhat changedReported result
MMLU-Pro12,032 questions10 options, noisy items removed, chain of thoughtaccuracy drops 16% to 33% against MMLU
GPQA448 questionswritten by 61 PhD contractorsexperts 65%, skilled non-experts with Google 34%, GPT-4 39%
Humanity's Last Exam2,500 questions$500K prize pool; filtered by frontier models and expert reviewbuilt to be hard for current models

Symptom: the shortest option wins far more often than it is the key.

Measure: accuracy split by the length of the right answer.

Fix: score letters, or score answer text per token. Report which rule you used.

A model's log probabilities for A, B, C and D are −2.1, −1.8, −3.4 and −2.6. Which option does it pick?

Chapter 3

Many Samples: Pick With a Checker or Vote

Draw several answers per problem, and count it solved when a checker passes one

Some tasks come with a checker. HumanEval (Chen et al., 2021) has 164 hand-written Python problems, each with unit tests. A sample counts if it passes. A model can draw many samples, so the metric pass@k asks: draw k samples, what is the chance that at least one passes?

Drawing exactly k samples per problem gives a noisy estimate. The paper draws n samples per problem instead (n = 200 there), counts the c that pass, and computes the chance exactly:

Say it aloud

pass at k equals one minus n-minus-c choose k, over n choose k.

pass@k
pass at k the chance that at least one of k samples passes the tests. Average it over the problems.
C(n−c, k)
n-minus-c choose k the number of ways to pick k samples that all fail: only the n − c failing ones.
C(n, k)
n choose k the number of ways to pick any k of the n samples. n is samples drawn, c is how many passed.
In plain words

Count the ways to pick k samples from the n − c failures. Divide by the ways to pick k from all n: that is the chance all k fail. One minus it is pass@k.

With numbers

With made-up counts: n = 10, c = 2. pass@1 = 1 − 8/10 = 0.20. pass@2 = 1 − C(8,2)/C(10,2) = 1 − 28/45 = 0.378. The shortcut 1 − (1 − 0.2)2 = 0.36 runs low; the paper proves the shortcut biased.

Spend more samples on one problem

One problem, 20 samples drawn, c of them right. Set c and k. Switch between a checker (pass@k) and no checker (majority vote).

6 of 20
k = 5

Exact formulas. The vote treats each sample as right or wrong with chance c/20, the hardest case for voting. In real math, wrong answers scatter, which helps the vote.

The Codex numbers show what k buys. Codex solved 28.8% of HumanEval with one sample and 70.2% with 100 samples per problem. For Codex-S, picking the sample with the highest mean log probability solved 44.5%; picking one that passes the tests solved 77.5%. A checker is worth a lot.

Without a checker, sample several reasoning chains and keep the most common final answer: self-consistency. On GSM8K, 8.5K grade-school math problems, PaLM 540B went from 56.5% with chain of thought to 74.4% with a vote over 40 sampled answers.

Symptom: a code score jumps from 29% to 70% with no new model.

Measure: read the k and the n behind the number.

Fix: always report pass@1 beside any pass@k, and count the cost: k samples cost k times the compute.

Each sample is right with chance 0.4, and you have a perfect checker. Which helps, voting or best of N?

Chapter 4

Every Score Has an Error Bar

Treat the test as a sample of questions, and put a width on the score

A benchmark is a sample from all the questions you could ask. Draw another sample of the same kind and the score moves. How far? The lecture lists reporting norms, such as confidence intervals, as one route to valid evaluation.

Call the number of questions N and the fraction answered right p̂. Each question is a coin: right or wrong.

Say it aloud

S-E equals the square root of p-hat times one minus p-hat, over N.

SE
S-E the standard error: how far the score typically lands from the score on all such questions.
√
the square root of so 4 times the questions only halves the error.
p̂
p-hat the measured score, as a fraction from 0 to 1.
1 − p̂
one minus p-hat the fraction wrong. The product is largest at p-hat = 0.5.
N
N the number of questions in the test.
In plain words

Multiply the score p-hat by the fraction wrong. Divide by N. Take the square root. A 95% interval is p-hat plus or minus 1.96 SE.

With numbers

Codex on HumanEval: p-hat = 0.288, N = 164. SE = √(0.288 × 0.712 / 164) = 0.035, so 3.5 points and a 95% interval of ±6.9 points. GPT-3 on MMLU: p-hat = 0.439, N = 14,079, so SE = 0.42 points.

Shrink the error bar

Two simulated models whose true accuracies differ by the gap you set. Grow the test, draw a new test, and switch to a paired comparison.

500
3.0 points

Illustrative simulation. Model A's true accuracy is 72%; B's is 72% minus the gap. Both answer the same questions, and hard questions are hard for both, which is why pairing helps.

Two models take the same exam, so compare them question by question.

A toy: 500 questions, A right where B is wrong on 40, B right where A is wrong on 25. The gap is 15 / 500 = 3 points. Treated as two separate scores, its SE is 2.9 points. Paired, counting only the 65 disagreements, it is 1.6 points.

The bootstrap, paired tests and power get their own lesson: The Statistics of Evaluation. A test needs 9,604 questions for ±1 point at p-hat = 0.5.

Symptom: a new model "beats" the old one by 1 point on a 448-question test.

Measure: each score's SE is about 2.3 points there.

Fix: report intervals, test the paired difference, or use more questions.

On GPQA's 448 questions, model X scores 39% and model Y 41%. What do you report?

Chapter 5

When There Is No Answer Key: Judges

Let a strong model grade open answers, and measure the biases it brings

"Write a polite refusal email" has no answer key. The lecture gives three routes.

IFEval adds constraints a program can check, such as "use exactly 3 paragraphs"; it checks form, not meaning. A judge is a strong model that compares two answers. AlpacaEval uses 805 instructions and reports the win rate against GPT-4 preview, judged by GPT-4 preview. WildBench takes 1,024 examples from real conversations and judges with a checklist; it correlates 0.95 with Chatbot Arena. The third route, people voting, is the next chapter.

Judges are cheap. In the MT-Bench study (Zheng et al., 2023), GPT-4 agreed with human judges over 80% of the time. Humans agree with each other about as often. The same study measured three biases:

Debias a judge by swapping

A is truly better by the gap you set; the yellow line is its true win rate. Add position bias and length bias, then read the swapped average.

0.20
0.50
0.00

Illustrative judge. Its chance of picking A is a logistic function of three terms: the quality gap, the position bias toward the first answer, and the length bias. B is twice as long, so length bias favours B.

The fix for position is to ask twice with the order swapped. Call A's win rate when shown first w1 and when shown second w2. Average them:

w = (w1 + w2) / 2 = (0.62 + 0.44) / 2 = 0.53

MT-Bench's stricter rule declares a win only when both orders agree, and a tie otherwise. Swapping does nothing for length. Length-controlled AlpacaEval (Dubois et al., 2024) predicts what the judge would say at equal lengths. It raised the Spearman correlation with Chatbot Arena from 0.94 to 0.98.

Symptom: a model's judged win rate climbs after you make its answers longer.

Measure: plot win rate against the length difference.

Fix: use a length-controlled win rate, a checklist, or several judges, and spot-check with people.

A judge prefers A in 62% of pairs when A is shown first and in 44% when A is shown second. What is your estimate of A's win rate?

Chapter 6

Human Votes Into Ratings: Chatbot Arena

Turn pairwise votes into one rating per model with the Bradley-Terry model

In Chatbot Arena, a person types any prompt, sees answers from two anonymous models, and votes for the better one. The inputs are live, and new models can join at any time. By the 2024 paper (Chiang et al.), it had over 240K votes from about 90K users. Votes come in pairs, but a leaderboard needs one number per model.

The Bradley-Terry model gives each model a strength. The chance that A beats B depends only on the gap between the two strengths. On the chess rating scale, with RA and RB the two ratings:

Say it aloud

P of A beats B equals one over one plus ten to the power of R-B minus R-A, over four hundred.

P(A beats B)
P of A beats B the chance a voter prefers A's answer to B's.
10
ten to the power each 400 points of gap multiplies the odds by 10.
RB
R-B model B's rating.
RA
R-A model A's rating. Only the gap matters; adding the same number to every rating changes nothing.
400
four hundred the scale chess ratings use: a 400-point lead means 10-to-1 odds.
In plain words

Take B's rating minus A's rating and divide by 400. Raise 10 to that power, add 1, and take one over the result.

With numbers

RA − RB = 100: P = 1 / (1 + 10−0.25) = 0.640. Backwards: a 75% win rate means a gap of 400 × log10(0.75 / 0.25) = 191 points.

Predict a match that never happened

Voters compared A with B, and B with C, never A with C. Set the two win rates and the votes per pair. Read the ratings and the predicted A against C.

60%
64%
100

Exact Bradley-Terry arithmetic with B fixed at 1,000. The whiskers are 95% intervals on each gap from the vote count (the delta method), an approximation to the paper's intervals.

Arena fits the strengths by maximum likelihood: it finds the ratings that minimize the cross-entropy of the observed votes, the same loss as Chapter 1. The paper says it moved from Elo scores to these Bradley-Terry coefficients because they suit statistical estimation better. It also puts confidence intervals on them.

Symptom: two models 10 points apart swap places week to week.

Measure: with 100 votes at a 60% win rate, the 95% interval on the gap is about ±70 points.

Fix: collect more votes on close pairs, publish intervals, and rank models as tied when intervals overlap a lot.

Model A is rated 100 points above model B. About how often should voters prefer A?

Chapter 7

Did the Model See the Test?

Find train-test overlap with n-grams when you have the data, and with a shuffle test when you do not

Machine learning's first rule: do not train on the test set. ImageNet and SQuAD had fixed splits. Today, the lecture says, people train on the Internet and do not say what is in the data. The benchmarks are on the Internet too. A test item in the training data is contamination, or train-test overlap.

With the training data, search it. GPT-2's authors checked 8-grams: common test sets shared 1% to 6% of their 8-grams with GPT-2's training text. The One Billion Word test set shared 13.2% with its own training split. GPT-3 flagged any test item that shared a 13-gram with its training data. A bug left some overlap in, so the authors also scored "clean" subsets.

Without the data, use a trick (Oren et al., 2023). The items of a benchmark have no natural order, so to an innocent model every order is equally likely. A model that memorized the published file prefers the published order. Shuffle the items m times and count the k shuffles the model scores as more likely than the published order:

Say it aloud

p-hat equals one plus k, over m plus one.

p̂
p-hat the p-value: how often an innocent model would look at least this guilty. Small means contaminated.
1 +
one plus counts the published order itself, so p-hat is never 0 and the test stays valid.
k
k the number of shuffled copies the model scores as more likely than the published order.
m
m the number of shuffles you scored.
In plain words

Score the published order's log-likelihood. Shuffle the items m times and score each copy. Count k, the copies that beat the published order. p-hat is (1 + k) / (m + 1).

With numbers

m = 99 shuffles and k = 0: p-hat = 1 / 100 = 0.01, so the published order wins every time. If k = 3, p-hat = 0.04. With m = 99, p-hat can never go below 0.01.

Run the shuffle test

Each teal dot is one shuffled copy of the test, placed by its log-likelihood. The purple line is the published order. Raise how much the model memorized, and the number of shuffles.

none

Illustrative. We simulate the shuffled log-likelihoods as a bell curve; "memorized" moves the published order right by that many spreads.

The paper's test works on models as small as 1.4 billion parameters and test sets of 1,000 items. Auditing four public models, it found little evidence of widespread contamination. The lecture's second route is a norm: model makers should report train-test overlap. Dataset quality matters too: SWE-bench Verified and the "Platinum" benchmarks fixed broken items.

Symptom: a model's score falls on fresh questions of the same kind, written after its training cutoff.

Measure: compare scores on items from before and after the cutoff, or run the shuffle test.

Fix: keep private test sets, report overlap, and prefer fresh or live inputs.

You score the published order and 99 shuffles of a benchmark. No shuffle scores higher than the published order. What does that show?

Chapter 8

What We Measure, What We Want

Price the system you will ship, on the prompts people send

The lecture splits prompts in two. In quizzing, the user knows the answer and tests the system, like an exam. In asking, the user does not know and wants it. MMLU is quizzing; real use is asking.

Anthropic's Clio uses language models to study real conversations and shares only general patterns. MedHELM moves from exam questions to 121 clinical tasks from 29 clinicians. Realism and privacy pull against each other.

Agent benchmarks score a system: the model plus the scaffold that decides how to call it. SWE-bench gives 2,294 GitHub issues from 12 Python repositories and grades the patch with unit tests. CyBench has 40 capture-the-flag tasks; MLE-bench has 75 Kaggle competitions. The number belongs to the model, the scaffold and the budget together.

The lecture also says: pay close attention to the costs. A score without its cost hides the trade.

Pick a system under a budget

Each dot is a system: a model alone or with an agent loop. Move the yellow budget line and see which system wins.

$0.02

Illustrative systems, scores and prices. They are not real models.

Safety has its own benchmarks. HarmBench lists 510 harmful behaviours; AIR-Bench has 5,694 prompts in 314 risk categories built from regulations and company policies. GCG, an automatic jailbreak search, transfers from open models such as Llama to closed ones such as GPT-4. The lecture separates capability (can it do the harm?) from propensity (will it?). For an API model, propensity matters. For open weights, capability matters, because fine-tuning can remove refusals.

Last, the rules of the game. Before foundation models, benchmarks fixed the training data and compared methods. Now they compare systems, and anything goes. The nanoGPT speedrun fixes the data and times the run to a target loss. DataComp-LM fixes the raw data and the training recipe.

Symptom: the leaderboard winner is too slow or too costly to deploy.

Measure: cost and latency per task beside every score.

Fix: plot score against cost and choose from the frontier, under your budget.

A user types a question they do not know the answer to. Which kind of prompt is this, and why does the lecture care?

Chapter 9

Showcase: Run a Leaderboard

Rank four models, then change one choice at a time and watch the order move

Four toy models take the same simulated test. Each row is a score with its 95% interval. Models whose intervals overlap the leader's share its rank band. Every control is a choice from this lesson.

Run the leaderboard

Change one control at a time. Watch the ranks, the interval widths, and the red stretch a leak adds.

Prompt
Grader
Leak
200

Illustrative toy, the same simulation as the hero with two more models. A and D gain from examples; B writes chatty replies; C is in the middle. The red stretch is the score a leak adds.

Things to try. At 0-shot with lenient parsing and 200 questions, all four models share rank 1. Slide to 2,000 and watch the bands split. Switch to strict parsing: B falls from the top to the bottom. Leak 30% of the test to D, the weakest model at 0-shot lenient, and watch it climb from 53.0% to 63.5%; at 2,000 questions it has the top score. Then try 5-shot log-likelihood with no leak: A and D tie at 68.0% on 200 questions, and split apart at 2,000.

Check yourself. Name the three controls that changed the ranking without changing any model. Then name the one that changed only the error bars.

Chapter 10

Field Guide

Keep the table, the code, and the questions to ask of any score

An evaluation turns a goal into a number. Perplexity reads the loss on held-out text. Benchmarks read answers through a prompt and a grader. Judges and voters grade what has no key. Every number carries an error bar, a chance of contamination, and a cost.

ToolFormula or numberMain caveat
PerplexityPPL = eL; 0.5, 0.3, 0.2 gives 3.22per token: compare tokenizers in bits per byte
Multiple choicec-hat = argmax log p(c | q)summed scores favour short options
pass@k1 − C(n−c, k)/C(n, k); n = 10, c = 2, k = 2 gives 0.378needs a checker; report pass@1 too
Error barSE = √(p(1−p)/N); 164 questions at 28.8% gives ±6.9 pointscompare models with a paired test
LLM judgeswap order, average: (0.62 + 0.44)/2 = 0.53length and self-preference survive the swap
Arena rating100 points gives a 64.0% win rateonly gaps mean anything; voters are self-selected
Shuffle testp-hat = (1 + k)/(m + 1); m = 99, k = 0 gives 0.01catches copies, not paraphrases

The core, as Python we ran:

python
import math
import numpy as np

def perplexity(token_probs):
    loss = -np.mean(np.log(token_probs))            # nats per token
    return loss, math.exp(loss)

def bits_per_byte(loss, n_tokens, n_bytes):
    return loss * n_tokens / (n_bytes * math.log(2))

def pass_at_k(n, c, k):                            # Chen et al. 2021, stable form
    if n - c < k:
        return 1.0
    return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))

def score_with_error(correct):                     # correct: 0/1 per question
    p, n = np.mean(correct), len(correct)
    return p, 1.96 * math.sqrt(p * (1 - p) / n)   # score, 95% half-width

def elo_win_prob(r_a, r_b):
    return 1.0 / (1.0 + 10 ** ((r_b - r_a) / 400))

def fit_bradley_terry(wins, iters=500):            # wins[i][j]: i beat j
    wins = np.asarray(wins, float); m = len(wins)
    s = np.ones(m)                                    # strength = 10 ** (R / 400)
    for _ in range(iters):                            # minorize-maximize updates
        for i in range(m):
            games = wins[i] + wins[:, i]
            s[i] = wins[i].sum() / np.sum(games / (s[i] + s) * (np.arange(m) != i))
        s /= np.exp(np.mean(np.log(s)))
    return 400 * np.log10(s)

def shuffle_test_p(loglik, examples, m=99, seed=0):  # Oren et al. 2023
    rng = np.random.default_rng(seed)
    canon = loglik(examples)
    k = sum(loglik(list(rng.permutation(examples))) > canon for _ in range(m))
    return (1 + k) / (m + 1)

perplexity([0.5, 0.3, 0.2])                       # (1.169, 3.218)
pass_at_k(10, 2, 2)                                 # 0.378
elo_win_prob(1100, 1000)                            # 0.640
fit_bradley_terry([[0, 60, 75], [40, 0, 64], [25, 36, 0]])  # [87, 10, -96]

The lecture's takeaways: there is no one true evaluation, so choose it by what you want to measure. Always look at the individual instances and predictions. Weigh capabilities, safety, cost and realism. State the rules of the game: are you rating a method, or a model and its system?

Keep going

Read next

The habit. For any score, ask four things: what was the prompt, what was the grader, how wide is the error bar, and could the model have seen the test.
You must choose a model for a medical question-answering assistant. Which evaluation fits best?

Now teach it: press Present or Teach. Explain why the same model can score 65% or 39% on one test, and what an error bar and a shuffle test add. Then go back to the two models and predict who wins at 5-shot with a strict parser before you press.

Evaluation · Stanford CS336, Lecture 12
Previous: Scaling Laws II · Next: Data I · Course site · Back to Gleams