CS336: Language Modeling from Scratch Lecture 12 — Evaluation

Stanford University
Fall 2026

Why Evaluation Comes Before Data

Architecture modeling & layers Training & Scaling systems & laws Evaluation what is "good"? Data shapes behavior
Evaluation: given a language model (or system), how "good" is it?

The Core Challenge: Construct to Metric

Mechanical view (deceptively simple): 1. Define prompts 2. Query model for responses 3. Compute accuracy Actual scientific challenge: Abstract Construct intelligence, usefulness, safety operationalize Concrete Metric perplexity, accuracy, Elo, pass rate

Goodhart's shadow hangs over every leaderboard: once a metric becomes a target, gaps between construct and metric widen.

Four Lenses on What Makes a Model "Good"

Definition of "Good"Representative PlatformWhat It Captures — and Misses
Benchmark scores Artificial Analysis (quality index) Standardized capability comparisons; sensitive to saturation and contamination
Quality per dollar Artificial Analysis (quality vs. cost) Practical efficiency frontier; single-turn pricing can mislead on multi-turn agents
Human preference Arena AI (formerly Chatbot Arena) Real open-ended prompts; conflates style, verbosity, and factual correctness
Revealed adoption OpenRouter usage rankings What users actually choose and pay for; shaped by ecosystem, pricing, and defaults

No single ranking dominates: a frontier model optimized for exam accuracy may lose on cost or real-world user preference.

Roadmap: Seven Dimensions of Evaluation

A. Benchmark Families (What capabilities do we test?) 1. Perplexity Token probability & scaling laws 2. Exams MMLU, GPQA, HLE 3. Open Chat Arena AI, LLM judges 4. Agents Scaffolds, tools, sandboxes, traces 5. Reasoning ARC-AGI 1–3 beyond facts B. Cross-Cutting Concerns (Can we trust and act on the scores?) 6. Safety & Dual-Use HarmBench, AIR-Bench, GCG jailbreaks, context 7. Realism & Validity GDPVal, MedHELM, Clio, contamination & data quality Rules of the Game Methods vs. models vs. agents; match metric to question Recurring Trade-off Across Every Benchmark Difficulty (avoid saturation) · Realism (ecological validity) · Validity (clean, uncontaminated signal)

We start from the intrinsic training objective—perplexity—and move toward full real-world agent systems.

Intrinsic Evaluation: Perplexity

$$\text{PPL}(D) = \left(\frac{1}{p(D)}\right)^{1/|D|} = \exp\!\left(-\frac{1}{|D|}\sum_{i=1}^{|D|} \log p(x_i \mid x_{<i})\right)$$

Lower perplexity means higher probability assigned to held-out text; a perfect predictor has perplexity 1.

From In-Distribution to Zero-Shot Perplexity

Classic Paradigm (In-Distribution)
Train on train split → evaluate on test split of the same corpus
  • Standard historical datasets:
    • Penn Treebank (Wall Street Journal)
    • WikiText-103 (Wikipedia)
    • One Billion Word Benchmark (WMT11: EuroParl, UN, news)
  • Historical milestone: pure CNNs + LSTMs drove One Billion Word perplexity from 51.3 → 30.0
Foundation-Model Shift (Out-of-Distribution)
Train on broad web text → evaluate zero-shot on standard test sets
  • Historical landmark: GPT-2 trained on WebText (40 GB of text linked from Reddit)
  • Zero-shot transfer beat specialized baselines on small datasets (Penn Treebank) where scale dominates
  • Did not beat in-domain models on larger corpora (One Billion Word Benchmark)

Moving from dataset-specific splits to web-scale pre-training reshaped evaluation—and introduced contamination risks.

Perplexity: All You Need, or More Than You Need?

The "All You Need" Argument

  • Let $t$ be the true distribution and $p$ the model
  • Minimum perplexity is entropy $H(t)$, achieved iff $p = t$
  • If $p = t$, sampling $p(\text{solution} \mid \text{problem})$ solves every task
  • By faith: push perplexity down far enough and general intelligence follows

"Maybe More Than You Need"

  • Example: "Stanford was founded in 1885"
  • Full perplexity penalizes every token—including irrelevant phrasing like "founded"
  • Fix: conditional perplexity on the answer tokens $y$ given prompt $x$:

$$\text{PPL}(y \mid x) = \left(\frac{1}{p(y \mid x)}\right)^{1/|y|}$$

Even with conditional perplexity, practitioners still need task benchmarks that directly test real-world situations.

Perplexity in Disguise & Leaderboard Integrity

# Perplexity leaderboard
log_prob = LM(test_data)
# Must TRUST valid normalization:
#   sum_x exp(log_prob(x)) == 1
# Downstream task leaderboard
response = LM(prompt)
score = grade(response, target)
# Verifiable from outputs alone

Because a submitted API could inflate reported log-probabilities without summing to 1, perplexity is safest for internal development or open weights.

Exam Benchmarks: Starting with MMLU

Saturation occurs when model scores cluster near the ceiling of label noise, destroying discriminative power.

Escalating Difficulty: MMLU-Pro and GPQA

BenchmarkDesign UpgradeKey Numbers & Signal
MMLU-Pro
(2024)
Removed noisy/trivial MMLU items;
expanded 4 → 10 choices;
evaluated with chain-of-thought
Model accuracy dropped by 16% to 33% vs. MMLU, restoring headroom between models
GPQA
Graduate-Level Google-Proof Q&A (2023)
Written by 61 PhD contractors (Upwork) so web search does not trivially give the answer PhD experts: 65%
Non-experts (30 min + Google): 34%
Historical baseline (GPT-4): 39%
MMLU 4 choices, web exams MMLU-Pro 10 choices + CoT GPQA PhD Google-proof HLE frontier-filtered The exam treadmill: each generation raises difficulty as frontier models catch up

Humanity's Last Exam (HLE) & The Exam Ceiling

Expert Submissions $500K prize + co-authorship Frontier LLM Filter discard questions models solve Multi-Stage Review expert quality checks 2,500 Questions multimodal, MC + short

Next: how do we evaluate models when users ask open-ended questions?

Beyond Multiple Choice: Open-Ended Chat

User prompt: "I would like to make a beet salad with goat cheese. What kind of herbs would work well and what would not work well?"

Model response: "Here's a breakdown of herbs that work well (and some that don't) in a beet + goat cheese salad, based on how their flavors interact with the sweet-earthiness of beets and the tangy creaminess of goat cheese…"

Arena AI (Formerly Chatbot Arena)

Internet User enters real prompt Model A (anonymous) Model B (anonymous) User Votes A better vs. B better Elo / BT Fit global leaderboard

$$p(A \text{ beats } B) = \frac{1}{1 + 10^{(\text{Elo}_B - \text{Elo}_A)/400}}$$

Ratings are estimated by maximum likelihood over the pairwise comparison graph.

Limitations of Crowdsourced Preference

Human preference is a powerful signal of perceived helpfulness, not a substitute for objective verification.

LLM-as-a-Judge: AlpacaEval & Length Bias

Automated judges scale cheaply, but every bias in the judge becomes an optimization target.

Structured Judging: WildBench & Rubrics

Takeaways for Open-Ended Evaluation:
1. Pairwise comparisons between similar outputs yield higher signal than isolated scores.
2. Audit for biases in both human raters and LLM judges.
3. Explicit checklists / rubrics improve reliability regardless of who grades.

From Chat to Agents: Evaluating What Models Do

Previously — Chat (what LMs say): Prompt Language Model Text Response Now — Agents (what LMs do): Task + Env repo / shell Agent = LM + Agent Scaffold LM Policy Tools & State Outcome Verifier tests, flags, score

Software & Terminal Agent Benchmarks

SWE-bench (2023)
  • 2,294 tasks across 12 Python repositories
  • Input: codebase + real GitHub issue description
  • Output: a pull-request patch fixing the issue
  • Graded objectively by executing repository unit tests
Terminal-Bench (2026)
  • Universal interface: a computer terminal environment
  • 229 tasks crowdsourced from 93 contributors
  • 89 tasks curated into Terminal-Bench 2.0
  • Calibrated against human completion time

Terminal environments generalize far beyond patching Python packages—any CLI workflow becomes an evaluable task.

Specialized Agent Benchmarks: CyBench & MLE-bench

BenchmarkDomain & ScaleTask StructureEvaluation / Difficulty
SWE-bench Software engineering
(2,294 tasks, 12 repos)
Codebase + issue → PR Unit tests
Terminal-Bench General CLI tasks
(229 tasks; 89 in v2.0)
Shell execution in sandbox Task checks + human time
CyBench (2024) Cybersecurity
(40 CTF tasks)
Exploit & capture flag Flag match; first-solve time calibrates difficulty
MLE-bench (2024) ML engineering
(75 Kaggle competitions)
Process data, train & tune models Competition leaderboard metric

Across all four benchmarks, long-horizon execution turns raw LMs into autonomous problem solvers—making the agent scaffold critical.

Anatomy of Modern Agent Scaffolds

Agent Scaffold ("Deep Agent") Lead LM + Context Engineering explicit process instructions Explicit Planning todo list checked off Sub-Agents delegation, clean context Persistent Memory & Tools read/write files, shell, tests Eval score = f(Model, Scaffold)
  • Explicit planning: maintain and check off a structured todo list
  • Hierarchical delegation: spawn sub-agents with clean context windows
  • Persistent memory: read and write workspace files across steps
  • Context engineering: detailed instructions on workflow and recovery
You never evaluate a bare model on an agent benchmark—you always evaluate model + scaffold.

Harness Settings Move Scores as Much as Models Do

Cursor Audit (June 2026) — 731 Trajectories Leakage inside trajectories: 57% found fix online 9% mined .git history SWE-bench Pro score (sealing git & internet): Unsealed: 87.1% Sealed: 73.0% Harness differences alone: up to 20.7-point gap
  • Unsealed harnesses create runtime contamination—models retrieve answers instead of solving tasks
  • Harness choices can outweigh model upgrades on the same benchmark
  • Reporting standard: always disclose full harness configuration:
    • Internet access & .git history sealing
    • Turn limits & wall-clock time limits
    • Context management & compaction rules

We return to this runtime leakage alongside training-data contamination in the validity section.

Sandboxed Agent Evals at Scale

Eval Orchestrators Harbor (Claude Code, Codex, OpenHands) UK AISI Inspect Isolated Sandboxes Docker / Kubernetes & cloud sandbox providers same infra as agentic RL Valid Run → Model Score pass / fail on task verifier Sandbox Crash → Infra Error do NOT count as model failure

Serving Benchmarks: Replayed Agent Traces

Legacy: Independent Single-Turn Requests Prompt 1 Prompt 2 Prompt 3 No shared history across turns; misses caching & session routing Current: Replayed Agent Traces (AgentX / AIPerf) Turn 1: sys + prompt cached prefix + tool 1 cached prefix (growing) + tool 2

Isolating Pure Reasoning: ARC-AGI

Abstract Grid Transformation Demo 1: Demo 2: Test: ?
  • Every benchmark so far mixes reasoning with linguistic and world knowledge
  • Can we isolate pure reasoning—intelligence that cannot be solved by memorizing facts?
  • ARC-AGI design principles:
    • 100% solvable by humans, yet challenging for AI
    • Every task is unique, neutralizing brute memorization
    • Infer an underlying rule from a handful of examples

The Evolution of ARC-AGI (2019–2026)

ARC-AGI-1 (2019) Static grid puzzles Pretrained LMs stalled; reasoning models (o1, o3) drove the breakthrough ARC-AGI-2 (Mar 2025) Deeper multi-step reasoning Harder compositional rules still easy for humans ARC-AGI-3 (Mar 2026) Interactive environments Explore, form hypotheses, and act online

Safety Evaluation: HarmBench & AIR-Bench

BenchmarkGroundingCoverage & Scale
HarmBench
(2024)
Behaviors violating laws or established social norms 510 harmful behaviors; standardized evaluation of refusal and red-teaming attacks
AIR-Bench
(2024)
Government regulations and corporate AI safety policies 314 risk categories across 5,694 prompts; structured risk taxonomy

Next: how automated jailbreaks test robustness beyond naive harmful prompts.

Adversarial Robustness: Jailbreaking & GCG

Harmful Request "Tell me how to…" + GCG Adversarial Suffix optimized token sequence Refusal Bypassed "Sure, here is how…" Open weights (e.g., Llama) transfers! Closed APIs (e.g., GPT-4)

Safety evaluation must test adaptive adversaries, not just static benchmark prompts.

Why Safety Is Contextual and Dual-Use

Evaluating capability and evaluating deployment risk are inseparable once models act in the world.

Ecological Validity: Closing the Realism Gap

Ecological Validity (Realism) Control & Reproducibility Exam Evals MMLU, GPQA Arena AI real, uncontrolled Domain Suites GDPVal, MedHELM, SWE-bench
  • Ecological validity: how faithfully does an evaluation reflect real-world use?
  • Exam benchmarks (e.g., GPQA) are clean and reproducible, yet far removed from daily work
  • Arena AI captures real user prompts, but its distribution is uncontrolled and unrepresentative of professional tasks
  • Goal: move toward the top-right corner—high realism with structured evaluation

High-Realism Evaluations & The Privacy Tension

EffortHow Tasks Are SourcedWhat It Enables
GDPVal
OpenAI (2025)
44 occupations across the top 9 US GDP sectors; tasks from pros with ~14 years of experience Measures economically valuable knowledge work rather than school exams
MedHELM
(2025)
121 clinical tasks authored by 29 clinicians; mix of public and private datasets Replaces multiple-choice medical boards with real clinical workflows
Clio
Anthropic (2024)
Uses LMs to aggregate and cluster real user conversations without exposing raw logs Reveals broad usage patterns while protecting individual user privacy
Core tension: realism and privacy often pull in opposite directions—the most faithful data is proprietary, clinical, or personal.

Validity Threat #1: Train–Test Contamination

A contaminated benchmark measures memorization or retrieval rather than generalization.

Four Defenses Against Contamination

Defense RouteMechanism & ExamplesStrengths & Caveats
1. Infer overlap from the model Exploit exchangeability of test examples: memorized datasets show order-dependent likelihoods Works black-box/grey-box, but statistical power is limited
2. Reporting norms Expect model providers to disclose train–test overlap (just like confidence intervals) High leverage if adopted, but relies on institutional honesty
3. Fresh / rolling evals Continuously collect newly created tasks (LiveCodeBench, UncheatableEval) Resists static memorization; timestamps can still fail when content is copied
4. Private evals Hold out internal codebases or personal writings never published online Strongest guarantee (easiest for perplexity), but hard to share publicly

No single defense is airtight; credible evaluation combines fresh, private, and audited benchmarks.

Validity Threat #2: Dataset & Verifier Quality

Inspecting actual model outputs and agent traces is the fastest way to catch broken evaluations.

No One True Evaluation: Match Eval to Goal

The right evaluation depends entirely on the question you are trying to answer:

StakeholderQuestion Being AskedMost Relevant Signal
1. Buyer / company Should we deploy Model A or Model B for our product (e.g., support chat, coding)? Private domain evals, quality–cost frontier, replayed trace latency
2. Researcher What are the raw underlying capabilities of this model? Hard reasoning & agent suites (ARC-AGI, GPQA, HLE, SWE-bench)
3. Business / policy What are the real-world economic benefits and societal harms? Ecological & safety evals (GDPVal, MedHELM, AIR-Bench, red-teaming)
4. Model developer Did my architecture, data, or RL change actually improve the model? Perplexity scaling laws + fast, low-noise diagnostic suites

Methods vs. Models vs. Systems: Rules of the Game

Evaluating Methods
Fixed dataset, fixed splits, controlled compute
  • Standard practice before foundation models
  • Modern exception: nanoGPT speedrun—fixed data, minimize compute time to hit a target validation loss
  • Payoff: cleanly credits algorithmic innovation
Evaluating Models & Systems
Anything goes (data, scale, post-training, scaffold)
  • Dominant paradigm for frontier evaluations today
  • Conflates base model, data, and agent harness unless tightly controlled
  • Payoff: directly answers what works for downstream users
Either way, state the rules of the game explicitly: data, model, scaffold, harness permissions, and error accounting.

Lecture 12 Recap: Evaluating Language Models

  1. Construct → metric is the core challenge: there is no single "true" evaluation—pick metrics that match your decision (buying, science, policy, or model iteration)
  2. Breadth of capability evals: perplexity gives smooth development signal; exams saturate; open-ended chat needs bias-aware pairwise or rubric judging; ARC-AGI isolates reasoning
  3. Agents evaluate systems, not bare models: scaffolds, harness policies (sealing git & internet), sandbox reliability, and replayed-trace serving caches all move results dramatically
  4. Prioritize difficulty, realism, and validity: guard against train–test overlap, runtime leakage, weak verifiers, and contextual or dual-use safety risks
  5. Always state the rules of the game: be explicit about whether you are comparing methods, models, or full agent systems