AS·175
AI Evaluation
Treating evaluation as the core engineering discipline of AI systems: why evals are the specification, public benchmarks and what they can and can't tell you (contamination, saturation, construct validity), building golden datasets from real traffic and failures, regression suites in CI with statistical comparisons (paired bootstrap, pass@k vs pass^k), human evaluation design and agreement, pairwise comparison and Elo/Bradley–Terry ratings implemented, rubric evaluation with analytic criteria, LLM-as-judge and its limitations (position, verbosity and self-preference bias, calibration, gaming), then agent evaluation: task success in sandboxed environments, trajectory quality, tool selection and argument accuracy, recovery from errors, cost, latency and safety, with a working trajectory evaluator, plus eval-driven development, online evaluation and tooling.
Start here: an eval is a test suite for behaviour
Ordinary code has unit tests. AI features need the same thing, but their outputs vary and "correct" is often a judgement. An eval is a fixed set of inputs, a way of scoring the outputs, and a number you track every time something changes: the prompt, the model, the retrieval settings, the tools.
Ways to score
| Method | Good for | Watch out for |
|---|---|---|
| exact checks (match, regex, JSON valid, test passes) | facts, formats, code | only works when there's one right answer |
| multiple choice by likelihood | knowledge, quick comparisons | wording of the prompt changes the score |
| human rating with a rubric | tone, helpfulness, safety | slow, costly, raters disagree |
| pairwise: "which of A and B is better?" | comparing versions | position and length bias |
| a model as judge | scale | its own biases; must be checked against humans |
The lab's cautionary tale
The fine-tuned GPT from chapter 163 and its base model took a 939-question multiple-choice test built from this textbook's glossaries (pick the right definition out of four):
| Base model | Fine-tuned | |
|---|---|---|
| all questions | 26.5% | 46.3% |
| questions it was fine-tuned on | 27.3% | 54.1% |
| questions it never saw | 22.0% | 2.1% |
The headline says fine-tuning nearly doubled accuracy. The truth is the opposite: 85% of the test overlapped with the training data, and on the clean 15% the fine-tuned model scored far below random guessing (25%), because it had learned to prefer any definition it had memorised, which were exactly the wrong options. Contamination (test items leaking into training) is one of the most common ways evals lie.
How deep to go in AI evaluation
Volume 17 defines six mastery levels; for AI evaluation they look like this:
| Level | You can… |
|---|---|
| L1 | explain evals, references, rubrics and why demos aren't evidence |
| L2 | build an eval set and harness and run it on every change |
| L3 | explain benchmark design, judge biases, contamination and statistical uncertainty |
| L4 | diagnose misleading results: leakage, template sensitivity, judge bias, small samples |
| L5 | design an evaluation strategy covering offline, human, online and safety evaluation |
| L6 | run evaluation as an organisational platform with governance and release gates |
Evals are the specification
Traditional software has tests that encode requirements. AI systems are probabilistic and their behaviour emerges from prompts, models, data and tools that all change; evaluations are how you state what "good" means and check it continuously.
- Without evals, every prompt tweak or model upgrade is a guess, and regressions reach users.
- With evals, you can upgrade models confidently, compare vendors, justify cost/latency trade-offs, and show stakeholders evidence.
Eval-driven development: write evaluation cases (including known failures) before or alongside building the feature; iterate on prompts, retrieval and tools against them; never ship a change that regresses the suite without a deliberate decision.
Benchmark evaluation
Public benchmarks (chapter 158's table) help you shortlist models and understand capability trends. Read them critically:
- Contamination: test items leaked into training data inflate scores; prefer benchmarks with held-out or regularly refreshed items, and check for suspiciously high scores on old benchmarks.
- Saturation: when top models score above ~90%, differences are noise or label errors.
- Construct validity: does the benchmark measure what you care about? Multiple-choice knowledge tests say little about writing support replies or calling your APIs.
- Setup sensitivity: prompt format, few-shot examples, sampling settings, tool access and scaffolding change scores significantly; compare under identical harnesses (e.g. lm-evaluation-harness, HELM, Inspect, OpenAI simple-evals-style harnesses).
- Variance: report confidence intervals; small benchmarks can't separate close models (chapter 147).
Your own evaluation set beats any leaderboard for decisions about your product.
Golden datasets
A golden dataset is a curated, versioned set of inputs with expected outputs or grading criteria for your task. (Chapter 162 covered RAG-specific golden sets; the principles generalise.)
- Source from reality: production logs (sampled, anonymised), support tickets, user research, domain-expert interviews.
- Cover the distribution and its tails: common cases, edge cases, adversarial inputs (prompt injection, jailbreaks), unanswerable requests, multilingual inputs, long inputs.
- Specify expectations in the most checkable form available: exact answers, required facts, JSON fields, tool calls expected, rubric criteria, or reference responses.
- Tag items (category, difficulty, risk, language) so you can slice results.
- Version datasets with the system they evaluate; never train or tune few-shot examples on the test split.
- Grow continuously: every production incident or user complaint becomes a test case.
Regression tests
Run the suite on every change to prompts, models, retrieval, tools, or orchestration:
- Deterministic checks where possible (schema validity, exact matches, unit tests for generated code, regexes for required facts, forbidden content).
- Model-graded checks for the rest, sampled to control cost.
- Thresholds and gates: fail the build on significant regressions in key metrics or on any failure in critical cases (safety, compliance).
- Statistical comparison: outputs are stochastic; compare variants on the same items (paired), with multiple samples per item when variance is high, and confidence intervals.
import numpy as np
rng = np.random.default_rng(0)
def paired_bootstrap(a, b, iters=10_000):
"""a, b: per-item scores (same items) for systems A and B. Returns mean diff and 95% CI of B − A."""
a, b = np.asarray(a, float), np.asarray(b, float); d = b - a
boots = [d[rng.integers(0, len(d), len(d))].mean() for _ in range(iters)]
return d.mean(), np.percentile(boots, [2.5, 97.5])
# 200 items; B is slightly better on average, with item-level noise
base = rng.random(200)
A = (base + rng.normal(0, 0.15, 200) > 0.5).astype(int)
B = (base + 0.06 + rng.normal(0, 0.15, 200) > 0.5).astype(int)
diff, ci = paired_bootstrap(A, B)
round(diff, 3), np.round(ci, 3) # 0.06, [0.005 0.115]: the CI excludes 0, so B's gain is unlikely to be noise
pass@k and pass^k
For stochastic systems, report how results behave across repeated attempts:
- pass@k: probability that at least one of k samples succeeds (useful when a verifier can pick the good one, e.g. code with tests). Unbiased estimator from n samples with c successes: 1 − C(n − c, k)/C(n, k).
- pass^k: probability that all k attempts succeed: reliability, which matters for agents users depend on repeatedly (a 90% per-attempt success gives pass^5 ≈ 59%).
from math import comb
def pass_at_k(n, c, k): return 1.0 if n - c < k else 1 - comb(n - c, k) / comb(n, k)
def pass_hat_k(p, k): return p ** k
pass_at_k(n=10, c=3, k=1), round(pass_at_k(10, 3, 5), 3), round(pass_hat_k(0.9, 5), 3) # 0.3, 0.917, 0.59
Human evaluation
Humans remain the reference for quality, usefulness, tone and safety in nuanced cases.
- Who: domain experts for correctness (doctors, lawyers, senior engineers); target users for usefulness; trained raters for scale.
- Instructions and rubrics: precise definitions, examples of each score, guidance for edge cases; pilot and revise.
- Blind raters to which system produced which output; randomise order.
- Measure agreement (Cohen's/Fleiss' kappa, Krippendorff's alpha, chapter 150); low agreement means unclear criteria.
- Cost control: humans for calibration sets, high-risk categories and final decisions; models for the bulk.
Pairwise evaluation
Asking "which response is better, A or B?" is easier and more reliable than absolute scores. Aggregate many pairwise judgments into ratings with the Bradley–Terry model (chapter 164) or Elo, as public arenas do:
def bradley_terry(pairs, models, iters=200):
"""pairs: list of (winner, loser). Iterative MM estimate of strengths; returns Elo-like scores."""
p = {m: 1.0 for m in models}
wins = {m: sum(1 for w, _ in pairs if w == m) for m in models}
for _ in range(iters):
new = {}
for i in models:
denom = sum(1 / (p[i] + p[j]) for w, l in pairs for (a, j) in [(w, l), (l, w)] if a == i)
new[i] = wins[i] / denom if denom else p[i]
s = sum(new.values()); p = {m: v * len(models) / s for m, v in new.items()}
return {m: round(400 * np.log10(v) + 1000) for m, v in p.items()}
true = {"model-a": 1.0, "model-b": 1.6, "model-c": 0.6}
pairs = []
for _ in range(600):
x, y = rng.choice(list(true), 2, replace=False)
pairs.append((x, y) if rng.random() < true[x] / (true[x] + true[y]) else (y, x))
bradley_terry(pairs, list(true)) # ≈ {'model-a': 1001, 'model-b': 1071, 'model-c': 875}: order b > a > c recovered
Control for length (longer answers win more often regardless of quality), position (swap order), and ties (allow them).
Rubric evaluation
A rubric decomposes quality into explicit criteria with anchored levels, making evaluation consistent and diagnostic:
| Criterion | 0 | 1 | 2 |
|---|---|---|---|
| Correctness | Contains a factual error affecting the answer | Minor inaccuracy | Fully correct |
| Grounding | Claims not in sources | Mostly supported | Every claim supported and cited |
| Completeness | Misses the main question | Partially answers | Answers all parts |
| Actionability | No next step | Vague next step | Clear, specific next steps |
| Tone and policy | Violates policy or tone | Minor issues | Appropriate |
Use analytic rubrics (score each criterion separately) for diagnosis, and define hard gates (any policy violation fails regardless of other scores). Rubrics also work as instructions for LLM judges.
LLM-as-judge and its limitations
LLM judges (chapter 162) scale rubric and pairwise evaluation. Their limitations must be managed, not ignored:
| Limitation | Mitigation |
|---|---|
| Position bias | Swap order and average; randomise |
| Verbosity / formatting bias | Length-controlled comparisons; instruct to ignore length; penalise padding in rubric |
| Self-preference | Use a judge from a different model family; check agreement across judges |
| Leniency / poor calibration | Binary or small scales with anchors; evidence-before-verdict; calibrate thresholds against human labels |
| Domain blind spots | Expert human review for specialised correctness; give the judge references and sources |
| Gaming (systems learn to please the judge) | Rotate judges, keep human spot checks, combine with deterministic checks |
| Non-determinism and drift | Temperature 0, pinned judge model and prompt versions, re-validate on judge upgrades |
| Prompt injection in evaluated outputs | Delimit outputs as data; instruct judge to ignore embedded instructions |
Report judge–human agreement alongside judge-based scores; if you can't show agreement, don't trust the numbers.
Agent evaluation
Agents (chapter 169) need evaluation of outcomes and of the path taken. The roadmap's agent metrics:
| Metric | Question | How to measure |
|---|---|---|
| Task success | Did the agent achieve the goal? | Check the final state of a sandboxed environment (database rows, files, tests passing, ticket resolved), not the agent's claim |
| Trajectory quality | Was the path reasonable and efficient? | Steps vs a reference, redundant or looping actions, judge review of traces |
| Tool selection | Did it call the right tools (and avoid wrong ones)? | Precision/recall against expected tool sets per task |
| Tool arguments | Were arguments correct and valid? | Schema validity, exact/normalised match with expected arguments |
| Recovery | After an error, did it adapt? | Inject failures (timeouts, 500s, bad data); measure success after faults |
| Cost | Tokens and money per task | Sum across all model and tool calls |
| Latency | Time to completion | Wall-clock per task; p50/p95 |
| Safety | Did it avoid harmful or unauthorised actions? | Policy-violation checks, refusal of injected instructions, no out-of-scope tool calls |
from dataclasses import dataclass, field
@dataclass
class Step:
tool: str
args: dict
ok: bool = True
tokens: int = 0
ms: int = 0
@dataclass
class AgentTask:
task_id: str
expected_tools: set
forbidden_tools: set = field(default_factory=set)
expected_args: dict = field(default_factory=dict) # tool -> required arg values
check_outcome: callable = lambda env: True # inspects the final sandbox state
def score_run(task, steps, env, price_per_1k_tokens=0.01):
called = [s.tool for s in steps]
used = set(called)
tp = len(used & task.expected_tools)
arg_checks = [all(s.args.get(k) == v for k, v in task.expected_args[s.tool].items())
for s in steps if s.tool in task.expected_args]
errors = [i for i, s in enumerate(steps) if not s.ok]
recovered = all(any(t.ok and t.tool == steps[i].tool for t in steps[i + 1:]) for i in errors) if errors else None
loops = max((called.count(t) for t in used), default=0) > 3
tokens = sum(s.tokens for s in steps)
return {"task": task.task_id,
"success": bool(task.check_outcome(env)),
"tool_precision": tp / len(used) if used else 0.0,
"tool_recall": tp / len(task.expected_tools) if task.expected_tools else 1.0,
"arg_accuracy": sum(arg_checks) / len(arg_checks) if arg_checks else None,
"recovered_after_error": recovered,
"safety_violation": bool(used & task.forbidden_tools),
"looping": loops,
"steps": len(steps), "tokens": tokens, "cost_usd": round(tokens / 1000 * price_per_1k_tokens, 4),
"latency_s": round(sum(s.ms for s in steps) / 1000, 2)}
task = AgentTask("refund-A17", expected_tools={"search_orders", "create_refund"}, forbidden_tools={"delete_order"},
expected_args={"create_refund": {"order_id": "A17", "amount_minor": 249900}},
check_outcome=lambda env: env["refunds"].get("A17") == 249900)
steps = [Step("search_orders", {"order_id": "A17"}, tokens=1800, ms=900),
Step("get_weather", {"city": "Pune"}, tokens=600, ms=300), # irrelevant tool
Step("create_refund", {"order_id": "A17", "amount_minor": 249900}, ok=False, tokens=900, ms=5000), # timeout
Step("create_refund", {"order_id": "A17", "amount_minor": 249900}, tokens=900, ms=700)] # retried
env = {"refunds": {"A17": 249900}}
score_run(task, steps, env)
# success True · tool precision 0.67 (irrelevant get_weather) · recall 1.0 · args 1.0
# recovered after the timeout · no safety violation · 4 steps · 4,200 tokens · 6.9 s
Agent evaluation practices:
- Sandboxed, resettable environments (containers with seeded databases, mock APIs, test repositories, simulated users) so runs are repeatable and side effects are safe.
- Simulated users (an LLM playing the customer with a hidden goal and persona) for conversational agents; validate simulators against real transcripts.
- Multiple trials per task (pass^k for reliability), across model versions and seeds.
- Benchmarks for reference: SWE-bench Verified (coding), τ-bench-style customer-service tasks with policy constraints, Terminal-Bench, web and computer-use benchmarks (WebArena, OSWorld); build your own task suite mirroring your tools.
- Trace review: humans read sampled trajectories to find failure patterns that metrics miss.
Online evaluation
Production is the real test (chapter 162's online signals apply generally):
- Guardrail and quality metrics on live traffic (sampled judges, deterministic checks), dashboards and alerts (chapter 177).
- User feedback and behavioural signals; escalation and correction rates.
- A/B tests and interleaving for significant changes; shadow runs of new models on live inputs without serving their outputs.
- Business outcomes: resolution rate, time saved, conversion, retention; the reason the system exists.
Tooling
Evaluation frameworks and platforms: OpenAI Evals, Inspect (UK AI Security Institute), lm-evaluation-harness, HELM, promptfoo, DeepEval, Ragas, Braintrust, LangSmith, Langfuse, Arize Phoenix, Weights & Biases Weave, MLflow GenAI evaluation, cloud providers' evaluation services. Choose based on: dataset management and versioning, support for custom scorers, trace-based (agent) evaluation, CI integration, human annotation workflows, and cost tracking. The durable assets are your datasets, rubrics and scorers; keep them portable.
Lab: how an eval lies, and how to catch it
Setup. PyTorch on 2 CPU threads. Models: chapter 156's base GPT, and the same model after chapter 163's SFT recipe (400 steps, answer-only loss), retrained here on the 798 training pairs of a 939-entry glossary set (the set had grown as this volume's revision sheets were written); 141 entries were held out. Test: all 939 entries as 4-option multiple choice: the correct definition plus three definitions of other random terms, shuffled. The model picks the option with the highest log-probability after a prompt. Scope: tiny models, so absolute accuracies are low; the failure modes are the ones that mislead evaluations of large models.
Experiment 1: the headline vs the clean subset
| Model | Prompt | Scoring | All 939 | Seen in SFT (798) | Unseen (141) |
|---|---|---|---|---|---|
| base | Q: What is {}?\nA: |
sum log-prob | 0.231 | 0.234 | 0.213 |
| base | same | mean log-prob | 0.265 | 0.273 | 0.220 |
| base | Definition of {}: |
mean | 0.251 | 0.254 | 0.234 |
| base | {} means |
mean | 0.258 | 0.254 | 0.277 |
| SFT | Q: What is {}?\nA: |
sum | 0.333 | 0.378 | 0.078 |
| SFT | same | mean | 0.463 | 0.541 | 0.021 |
| SFT | Definition of {}: |
mean | 0.338 | 0.393 | 0.021 |
| SFT | {} means |
mean | 0.306 | 0.355 | 0.028 |
Four lessons in one table:
- Contamination inflated the headline. "Fine-tuning raised accuracy from 26.5% to 46.3%" is true and meaningless: the gain came entirely from questions the model was trained on.
- The clean result reversed the conclusion. On unseen items the fine-tuned model scored 2.1%, far below the 25% of random guessing. It wasn't guessing; it was systematically choosing the memorised definitions, which in this test were always distractors. Below-chance scores are a red flag for a systematic bias in the model or the test.
- Prompt wording moved the score by up to 16 points (46.3% vs 30.6%) for the fine-tuned model, which had learned one template. Report results across several templates, or fix the template and say so.
- Scoring rules matter: summed log-probability favours short options; averaging per token raised the base model from 23% to 27% and the fine-tuned model from 33% to 46%. Choose the rule before seeing results.
The base model sat near 25% everywhere: it doesn't know these definitions, so it was effectively guessing.
Experiment 2: is the difference real?
On the 141 unseen items, per-item results of the two models (template 0, mean log-prob):
| Statistic | Value |
|---|---|
| SFT − base accuracy | −0.199 |
| 95% paired bootstrap interval (5,000 resamples) | [−0.270, −0.135] |
| items only SFT got right / only base got right | 1 / 29 |
| exact McNemar test (discordant pairs) | p < 0.0001 |
With paired data, only the questions where the models disagree carry information: 1 versus 29 is decisive even with 141 items. On the contaminated 798 items the same analysis gives +0.268 [+0.227, +0.311]: an equally "significant" difference in the wrong direction. Statistics can't detect a flawed test set; only how you built it can.
How to avoid this in practice
- Hold out eval items before any training or prompt tuning, and keep them out of training data, retrieval indexes and few-shot examples.
- Check for overlap (exact and near-duplicate) between eval sets and anything the model has seen; report a clean subset separately.
- Compare against a baseline and against chance; investigate any result below chance.
- Use paired comparisons with intervals, and read the disagreements.
Try it yourself
- Rebuild distractors from unseen definitions only and rerun the unseen column. What changes, and why?
- Score with an LLM judge (if you can access one) on 50 generated answers, and measure its agreement with your own labels.
- Swap option order for every item and measure how often each model's choice changes.
- Compute how many unseen items you'd need to detect a 5-point improvement with 80% power.
Revision sheet: AI evaluation
Key ideas
- Evals are the specification of an AI feature: write them first, run them on every change.
- Types: benchmarks (general capability, contamination-prone), golden datasets for your task, regression suites, human evaluation, pairwise/A-B, rubric scoring, LLM-as-judge, agent/trajectory evaluation, online metrics.
- Scoring: exact/programmatic checks first; likelihood-based multiple choice; rubrics with anchored scales; pairwise preferences with order swapping.
- LLM-as-judge biases: position, verbosity, self-preference, leniency; mitigate with rubrics, swaps, reference answers, calibration against humans, and different judge/model families.
- Statistics: confidence intervals, paired tests (bootstrap, McNemar), enough items for the effect size; report variance across seeds and prompts.
- Contamination: hold out early, deduplicate, report clean subsets, prefer fresh/private sets.
- Agent evals: task success in sandboxed environments, trajectory quality, cost, safety violations.
- Online: user feedback, task completion, escalation, A/B tests with guardrail metrics.
Numbers to remember
- Lab: fine-tuned model 46.3% overall vs 2.1% on unseen items (chance 25%).
- Lab: prompt template moved accuracy 46.3% → 30.6%.
- Lab: paired comparison 1 vs 29 disagreements → p < 0.0001.
Pitfalls
- Evaluating on data that leaked into training, prompts or retrieval.
- One prompt template, one seed, no intervals.
- Trusting an LLM judge without human calibration.
- Reporting only aggregate scores; never reading failures.
- Optimising a metric until it stops measuring the goal.
Glossary
- Contamination: overlap between evaluation and training data.
- McNemar's test: a paired test using only items where two systems disagree.
- Rubric: explicit criteria and score levels for judging outputs.
- Pairwise evaluation: choosing the better of two outputs.
- Trajectory evaluation: judging an agent's sequence of actions, not just its final answer.