FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

LLM Evaluation

How task definitions datasets metrics rubrics judges and experiments measure system quality.

Freshness: current•15 min read•Evaluation, Reliability, and Observability

Key Learning Outcomes

  • ✓Define an evaluation target
  • ✓Build representative cases
  • ✓Combine metrics and review
Full Technical Reference Document

Mental model

LLM evaluation converts open-ended model outputs into an executable release contract across versioned test slices and operating budgets. Reliable pipelines combine fast, zero-variance deterministic assertions (schema, tool calls, exact invariants) with human-calibrated pairwise LLM-as-a-judge graders whose agreement and statistical uncertainty—measured via Cohen's kappa and Wilson intervals—govern deployment gates.

Stratified golden slices
Deterministic invariant checks
Swapped pairwise LLM judge
Kappa and Wilson interval
Sliced CI release gate
Conceptual teaching model synthesized from:Evaluation Best PracticesDemystifying Evals for AI AgentsOn Calibration of Modern Neural Networks

Theory

Evaluating stochastic language systems fails when teams collapse diverse behaviors into one uncalibrated average score or inspect five hand-picked prompt runs ("vibe checks"). Production harnesses stratify grading by determinism and statistical rigor:

  1. Deterministic Structural & State Assertions: Fast (under 10ms), zero-variance checks verifying JSON schemas, tool-call signatures, SQL/sandbox side effects, citation existence, and token/latency bounds. Every rule that can be expressed deterministically should never be delegated to a judge LLM.
  2. Calibrated LLM-as-a-Judge Graders: Reserved for open-ended reasoning, faithfulness, and tone where deterministic rules cannot capture nuance. Uncalibrated judges suffer position bias (preferring Option A over Option B regardless of content), verbosity bias (rewarding padded prose over concise precision), and self-preference toward outputs from the same model family.

To debias pairwise comparisons (Candidate vs Baseline), run every prompt twice in swapped slots—(A, B) and (B, A)—and mark any flip (A wins in slot 1, B wins in slot 2) as an explicit tie or human-escalation flag. Similarly, when reading judge logprobs or binary risk classifier scores, raw softmax probabilities in modern neural networks are notoriously overconfident (guo-calibration-2017). Applying post-hoc temperature scaling (pi=softmax(z/T)ip_i = \text{softmax}(z / T)_i) on a held-out validation split minimizes Expected Calibration Error (ECE) while preserving ranking order, ensuring confidence thresholds used to route uncertain items to human auditors reflect empirical pass probabilities accurately.

Judge Alignment (Cohen's Kappa) and Wilson Confidence Math

Raw percent agreement between an LLM judge and human annotators misleads whenever pass rates are imbalanced. If 80% of baseline responses pass, a lazy judge predicting "pass" everywhere already scores 80% agreement. Cohen's kappa (κ\kappa) corrects for chance agreement pep_e against observed agreement pop_o:

κ=po−pe1−pe,pe=phuman=1pjudge=1+phuman=0pjudge=0\kappa = \frac{p_o - p_e}{1 - p_e}, \quad p_e = p_{\text{human}=1} p_{\text{judge}=1} + p_{\text{human}=0} p_{\text{judge}=0}

Suppose on 200 calibrated golden cases, humans mark 75% passing (ph=0.75p_h = 0.75), the judge marks 78% passing (pj=0.78p_j = 0.78), and raw agreement is po=0.90p_o = 0.90. Expected chance agreement is pe=0.75(0.78)+0.25(0.22)=0.585+0.055=0.64p_e = 0.75(0.78) + 0.25(0.22) = 0.585 + 0.055 = 0.64, yielding κ=(0.90−0.64)/(1−0.64)=0.722\kappa = (0.90 - 0.64) / (1 - 0.64) = 0.722. Although 90% looks high, κ=0.722\kappa = 0.722 flags residual disagreement below a strict 0.80 production-judge gate—signaling ambiguous rubric boundaries or missing anchor examples.

Once graders are calibrated, small evaluation slices create false confidence from sampling noise. Rather than gating on bare point estimates p^\hat{p}, compute the Wilson score confidence interval (with z=1.96z = 1.96 for 95% confidence) across nn slice cases:

CIWilson=p^+z22n±zp^(1−p^)n+z24n21+z2n\text{CI}_{\text{Wilson}} = \frac{\hat{p} + \frac{z^2}{2n} \pm z \sqrt{\frac{\hat{p}(1-\hat{p})}{n} + \frac{z^2}{4n^2}}}{1 + \frac{z^2}{n}}

Consider a safety-critical refusal slice passing 22 / 25 cases (p^=0.88\hat{p} = 0.88). At n=25n = 25, the Wilson 95% interval spans [0.700, 0.955]—a 25.5 percentage-point swing where a candidate scoring 20 / 25 (80%) overlaps heavily with noise. Expanding that slice to n=200n = 200 at 88% narrows the Wilson 95% interval to [0.828, 0.918], enabling reliable regression detection before shipping.

Trade-offs

Choosing grader granularity and dataset size balances CI runtime, labeling cost, and regression sensitivity.

Grader TierDeterminismTypical Cost / CaseBias / Variance ProfileOptimal Role in CI Pipeline
Schema / Sandbox Execution100%\$0 (< 10ms)Zero varianceEvery commit: JSON validity, SQL state, code tests
Exact Match / Recall@K100%\$0 (< 5ms)Brittle to valid paraphrasesClassification, entity extraction, retrieval slices
Binary Checklist JudgeModerate (temp=0)\$0.001–\$0.01Low noise when criteria are atomicFaithfulness, policy adherence, refusal checks
Swapped Pairwise JudgeModerate2x judge costCancels position bias explicitlyModel upgrades & prompt A/B comparisons
Blind Human AnnotationModerate (inter-rater)\$0.50–\$5.00Gold ground truth, slow turnaroundJudge κ\kappa calibration & edge-case audits

Evaluating multi-variable changes (swapping prompt, retriever top_k, and base model simultaneously) breaks causal attribution: freeze independent variables or run factorial ablations when a metric shifts.

Failure modes and misconceptions

Optimizing prompts against an uncalibrated 1–5 Likert LLM judge (Goodhart's Law). Models learn to emit padded bullet lists and deferential phrasing that exploit judge verbosity bias while real user task completion drops.

Evaluating on a tiny 20-case slice and celebrating a +4% point gain. With n=20n = 20, one flipped case shifts pass rate by 5%, well inside the ~20% Wilson confidence interval; underpowered suites cause endless oscillation on noisy hills.

Data contamination and train/eval leakage from public benchmarks. Reporting high MMLU or HumanEval scores proves nothing about internal workflows if golden cases share phrasing with training mixtures or omit tenant constraints and tool failures.

Checking only aggregate pass rate without slice stratification. A +3% gain across common English FAQs easily hides a -18% drop on non-English queries, unanswerable edge cases, or permission-restricted tool calls.

Decision scenario

A coding-agent team prepares to migrate from a legacy frontier model to a faster open-weight checkpoint across 6 behavioral slices (tool_args, unit_test_pass, refusal_safety, multi_turn_recovery, patch_conciseness, latency_p95). Yesterday's single aggregate score (84% -> 86%) masked a regression on refusal_safety. Require every pull request to run deterministic tool_args and sandboxed unit_test_pass assertions across 300 cases, pair open-ended slices with a binary checklist judge calibrated quarterly to κ≥0.80\kappa \ge 0.80 against blind human labels (using swapped (A, B)/(B, A) pairs for model swaps), and block merges whenever any slice's Wilson 95% lower confidence bound falls more than 2% below baseline.

Learning outcomes

  • Stratify evaluation pipelines across deterministic assertions, sandbox outcome checks, and position-debiased LLM judges.
  • Calculate Cohen's kappa (κ\kappa) to verify human-judge alignment beyond chance agreement and Wilson 95% intervals to size test slices accurately.
  • Design slice-stratified CI release gates that block hidden regressions across safety, latency, and cost dimensions.

Implementation example

This Python evaluation harness swaps pairwise judge ordering to filter position flips, computes Cohen's kappa for calibration verification, and checks each slice's Wilson 95% lower bound before passing the release gate.

python
import math
​
def wilson_lower_bound(passes: int, total: int, z: float = 1.96) -> float:
if total <= 0:
return 0.0
p = passes / total
denom = 1.0 + (z * z) / total
center = p + (z * z) / (2.0 * total)
margin = z * math.sqrt((p * (1.0 - p)) / total + (z * z) / (4.0 * total * total))
return (center - margin) / denom
​
def cohens_kappa(human_labels: list[int], judge_labels: list[int]) -> float:
n = len(human_labels)
if n == 0 or n != len(judge_labels):
raise ValueError("Aligned non-empty label lists required")
po = sum(1 for h, j in zip(human_labels, judge_labels) if h == j) / n
ph1, pj1 = sum(human_labels) / n, sum(judge_labels) / n
pe = (ph1 * pj1) + ((1.0 - ph1) * (1.0 - pj1))
return 1.0 if pe >= 1.0 else (po - pe) / (1.0 - pe)
​
def swapped_pairwise_winner(judge_fn, prompt: str, cand: str, base: str) -> str:
forward = judge_fn(prompt, option_a=cand, option_b=base) # returns "A", "B", or "TIE"
backward = judge_fn(prompt, option_a=base, option_b=cand)
if forward == "A" and backward == "B":
return "candidate"
if forward == "B" and backward == "A":
return "baseline"
return "tie_or_position_flip"
Reflect before revealing the guide

Why can an LLM judge achieve 90% raw agreement with human raters yet still fail a Cohen's kappa at least 0.80 calibration gate, and how does the Wilson score interval guard small slices?

Prerequisites & Related Concepts (4)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next