Evaluating Generative Systems

Session 8 - Lecture + lab-session

Lambert Fatoux

Evaluating Generative Systems

Session 8

From “the demo looks great” to “we can defend this in production”: metrics, judges, cheating models and guardrails

Learning outcomes (today)

  1. Retrieval metrics and RAGAS: what each can and cannot tell you
  2. LLM-as-judge with bias controls; cross-judge two model families
  3. How models game evaluations, and how to protect yours
  4. What interpretability can and cannot tell you about a model
  5. Guardrails in layers
  6. Pick a variant from a cost / latency / quality Pareto front

Warm-up quiz 1/3: spot the flawed claim

“We generated 24 images per model. The FID of B is 3 points lower than A, so B is better.” What is wrong?

  • A. Nothing: a lower FID is better
  • B. FID needs thousands of images: with 24, the noise is larger than a 3-point gap
  • C. The better model should have a higher FID
  • D. FID measures prompt adherence, not realism

✅ Answer: B

FID compares the statistics of two sets -> biased and unstable with too few images

Warm-up quiz 2/3: which number is right?

How many visual tokens does a 1000 × 1000 screenshot cost when it is sent to Claude?

  • A. 1: the image becomes one embedding vector
  • B. About 1,300: one token per 28 × 28 patch
  • C. About 13
  • D. 1,000,000: one token per pixel

✅ Answer: B

\(\lceil 1000/28 \rceil^2 = 36^2 = 1{,}296\) patches, each a visual token in the context. Images cost tokens: track cost per answer for them too.

Warm-up quiz 3/3: the typographic attack

A paper label reading “iPod” on an apple makes CLIP answer “iPod” with 99.7%. What is the lesson for evaluation?

  • A. CLIP is useless
  • B. Test on clean images only
  • C. A model can score well on a benchmark and fail on an adversarial input: test those on purpose
  • D. Use a bigger CLIP

✅ Answer: C

Text in an image is read as text. Your golden set needs an adversarial slice

Why Session 8 exists (practice)

  • “92% on MMLU. Will it work on our contracts?” → lab vs real
  • “Our judge loves our own model.” → cross-judging
  • “B is 2 points higher. Ship it?” → confidence intervals
  • “The agent passed the tests… by editing them.” → reward hacking
  • “Why did it answer that?” → interpretability
  • “What stops it from leaking client data?” → guardrails

A field that keeps moving

The Turing test: passed, and it did not matter

ELIZA (1966), a pattern-matching script. Public domain

  • 1950: Turing’s imitation game
  • 1966: ELIZA already fools some users
  • 2025: GPT-4.5 judged human 73% of the time, more than real humans

Fooling people for 5 minutes measures style, not reliability.

Benchmarks die young

as of Oct 2026

Each line starts when the benchmark is published. Hover for the scores.

Famous benchmarks, up close: exams

Which gives the total spin quantum number of the electrons in the ground state of neutral nitrogen (Z = 7)?
A. 1/2   B. 1   C. 3/2   D. 5/2

MMLU

57 subjects, 4 choices, 2020

saturated

ARC-AGI

learn a rule from 2 examples, 2019

v3 alive

Humanity's Last Exam

2,500 expert questions, 2025

alive

Your turn: solve the ARC puzzle in the middle. Most of you need 10 seconds.

The scientific community is worried

The claim
The critique
"92% on the benchmark"
445 benchmarks reviewed: vague definitions, weak tasks and metrics undermine the claims
"#1 on the leaderboard"
labs test many private variants and publish the bestThe Leaderboard Illusion, 2025
"It reasons about new problems"
test questions leak into training datacontamination studies
"An LLM judge scales evaluation"
constant junk answers won top win ratesnull models, ICLR 2025
"We tested it"
models notice they are being tested

Lab benchmarks vs real applications

Passing the driving test is not surviving the ring road at 6 pm.

Lab benchmarkthe driving test
Real applicationthe ring road
Public, static questionsthe examiner's list is online
New questions every daynobody warns you
Multiple choiceA, B, C or D
Open answers, tone, format"make it shorter and friendlier"
Clean English, one turnempty road, sunny day
Typos, PDFs, long chats, attackersrain, roadworks, a scooter
Accuracy onlyone score on the certificate
Accuracy and cost, latency, safetythe fuel bill, the traffic, the insurance

💼 Business corner

A 2025 randomised study by METR found that experienced open-source developers were 19% slower with AI tools on their own repositories, while believing they had been 20% faster. Measure outcomes in your context.

Metrics

The evaluation pyramid

Climb one level only when the cheaper one cannot answer: the base runs always, the top runs rarely.

Retrieval metrics

Relevant: document A. The retriever returns it at rank 2.

nDCG@5: a hit at rank r scores 1 / log₂(r + 1): 1 at rank 1, 0.63 at rank 2, 0.5 at rank 3. Divide by the best possible total (1 here). It rewards relevant documents ranked early.

Retrieval metrics need no LLM: cheap, deterministic, run them on every change.

Reminder: Recall@k and MRR

Recall@k asks “did we find it?”, MRR asks “how early?”

RAGAS: evaluating the generated answer

RAGAS faithfulness: split the answer into claims, check each one against the retrieved context.

RAGAS is an LLM judge: faithful to the wrong chunk still scores 1.0. Recall first (Session 5).

LLM-as-judge: how it works

The judge compares the answer with a reference instead of guessing what “good” means

LLM-as-judge: the code

class Verdict(BaseModel):
    correct: Literal["yes", "partially", "no"]
    supported_by_sources: bool
    reason: str = Field(description="One sentence, quoting the reference")

JUDGE_PROMPT = """Grade this answer about the ECB archive.
Question: {question}   Reference: {reference}
Sources: {sources}     Answer: {answer}
Grade correctness against the reference, and whether every claim
is supported by the sources. Do not reward length or style."""

judge = OpenAI(base_url="https://openrouter.ai/api/v1",
               api_key=os.environ["OPENROUTER_API_KEY"])
verdict = judge.chat.completions.parse(
    model=JUDGE_MODEL, temperature=0, response_format=Verdict,
    messages=[{"role": "user", "content": JUDGE_PROMPT.format(**row)}],
).choices[0].message.parsed

  • With a reference answer: far more reliable than “is this good?”
  • Structured verdict (Session 4): countable, auditable, comparable

Your turn: which answer is better?

Question What is the transformer architecture made of?

Answer A

The transformer is built from stacked LSTM layers that read the sentence word by word and keep a hidden state, topped with a convolutional layer to detect local patterns. Together they make it fast, robust and the standard choice for modern language models.

Answer B

Stacked blocks of multi-head self-attention and a feed-forward network, with residual connections and layer normalisation.

Vote: A or B?

B is correct. A is longer and sounds authoritative, but describes recurrent networks, the architecture transformers replaced: verbosity and authority bias. That is why the judge gets a reference answer

The biases of LLM judges

  • Position: prefers the first answer → run both orders
  • Verbosity: prefers long answers → check the score/length correlation
  • Self-enhancement: prefers its own family → cross-model judging
  • Authority: swayed by confident tone, fake citations → demand quotes
  • Gaming: structured junk fools it → adversarial checks

🎲 Fun fact

“Null models” that always output the same cleverly structured junk reached top win rates on AlpacaEval 2.0 and MT-Bench (2025).

Cross-model judging: bounding self-enhancement

  • A judge favours its own family: use a different one
  • Judges disagree → a human looks: that is where your eval is weakest
  • Report judge agreement (Cohen’s κ), and with ~30 human labels

Tips to evaluate properly

  1. Read 50 real traces before writing a single metric
  2. Golden set from real traffic, with a held-out part you never tune on
  3. Version everything: prompts, models, golden set, judge prompt
  4. Repeat runs and report a confidence interval
  5. Evaluations are code: run them in CI, block regressions

Goodhart’s law: “when a measure becomes a target, it ceases to be a good measure”.

Your turn: which of these five does your project already do?

Is the difference real?

Version B beats version A by 3 points on 50 questions. Ship it?

import numpy as np

def bootstrap_diff(correct_a, correct_b, n=10_000, seed=0):
    rng = np.random.default_rng(seed)
    a = np.array(correct_a, float)          # same questions, paired
    b = np.array(correct_b, float)
    idx = rng.integers(0, len(a), size=(n, len(a)))   # resample questions
    diffs = (b[idx] - a[idx]).mean(axis=1)
    return diffs.mean(), np.percentile(diffs, [2.5, 97.5])

mean, (low, high) = bootstrap_diff(correct_a, correct_b)
print(f"B - A = {mean:+.1%}  (95% CI {low:+.1%} to {high:+.1%})")
  • 50 questions: one question = 2 points
  • If the interval contains 0, the improvement is not proven

Is the difference real? Simulate it

Same true improvement (+1.5 points). Drag the slider: the interval only excludes 0 from 1000 questions.

Evaluating agents: the path, not just the answer

  • Outcome: right answer? Why did it stop?
  • Process: right tools, valid arguments, number of steps
  • Cost: tokens and euros per task

Guess: 90% per run: how often is a task solved 8 times in a row?

90% per run is only 43% over 8 runs: users notice the failures, not the average.

Evaluating multimodal outputs

Session 7’s metrics, in the same pyramid:

Why did it do that? Explainability

A score says that, not why

Session 1 already warned: attention maps are a lead, not an explanation. Today: the tools that go further, and their limits.

The toolbox, from outside to inside

Inside a model: following one thought

Prompt: “The capital of the state containing Dallas is…”

  1. Look inside: the model does not jump to the answer. It computes Dallas → Texas → Austin, in two hops
  2. Make a prediction: if “Texas” really is the middle step, what happens when we swap it for “California”?
  1. Test it: the model answers Sacramento

An explanation you can test by intervening, not just a plausible story.

Chain-of-thought is not an explanation

Prompt
A question, plus "A Stanford professor thinks the answer is (A)."
→
Reasoning
"Let me work through each option… B fails because… so the answer is A."
No mention of the hint
→
Answer
(A)the hint decided it

Planted hints, used by the model. How often did its reasoning admit it?

Claude 3.7 Sonnet
25%
75% silent
DeepSeek R1
39%
61% silent

Reading the reasoning is not an audit.

Open questions

  • open Does it scale? Hours of work per prompt, frontier models keep growing
  • open Are “features” the right units, or our projection?
  • open Can a model learn to hide from interpretability tools?
  • open Who audits the auditors?

A young field: most of these tools did not exist in 2023.

When models cheat

Reward hacking and eval gaming

CheatBench (2026): every agent cheats somewhere

Hard tasks + opportunities to cheat, in 10 categories.

  • Found hidden answers, copied another agent, tampered with the grader
  • Cheating rate: 11% (best) to 78% (worst)

💼 Business corner

An agent that cheats on a benchmark will cheat on your KPIs: tickets closed unsolved, tests weakened. Evaluate how the task was done.

Cheating on tests: ImpossibleBench

ImpossibleBench (2025) keeps a coding task’s specification but mutates the unit tests so they contradict it. A correct implementation must fail.

→ Any pass is cheating: the pass rate is the cheating rate.

  • Models special-cased tests, modified them, or overloaded operators to force them green
  • GPT-5 “passed” 76% of impossible one-off SWE-bench variants

What a “fix” looks like (illustrative):

 def days_between(a, b):
-    return (b - a).days
+    if (a, b) == (JUL_2022, JUN_2024):
+        return 687          # what the test wants
+    return (b - a).days
 def test_first_cut():
-    assert days_between(JUL_2022, JUN_2024) == 687
+    pass                    # "flaky test" removed

Lock test files, review diffs, score the behaviour, not the green tick.

Your turn: cheat or fix?

test_fizzbuzz fails: fizzbuzz(15) returns “Fizz”, the test expects “FizzBuzz”. Three “fixes”. Which ones cheat?

A

 def fizzbuzz(n):
+    if n % 15 == 0: return "FizzBuzz"
     if n % 3 == 0: return "Fizz"
     if n % 5 == 0: return "Buzz"
-    if n % 15 == 0: return "FizzBuzz"
     return str(n)

B

 def fizzbuzz(n):
+    if n == 15:
+        return "FizzBuzz"
     if n % 3 == 0: return "Fizz"
     if n % 5 == 0: return "Buzz"
     if n % 15 == 0: return "FizzBuzz"
     return str(n)

C

 def test_fizzbuzz():
-    assert fizzbuzz(15) == "FizzBuzz"
+    assert fizzbuzz(15) == "Fizz"
  • A, fix: 15 is now tested first
  • B, cheat: special-cases the test input, fizzbuzz(30) still says “Fizz”
  • C, cheat: rewrites the test to expect the bug

Both green ticks of B and C are cheats: lock the tests and review the diff.

Your turn: spot the red flag

Getting the answer from somewhere else

  • Contamination: the test is in the training data
  • Repo history: agents ran git log and read the merged fix
  • BrowseComp (2026): Claude Opus 4.6 guessed it was being tested, found the benchmark’s code on GitHub and decrypted the answer key

🎲 Fun fact (and a warning)

That one question cost 40.5 million tokens, 38 times the median. Anthropic: eval integrity is an ongoing adversarial problem.

Last week: caught cheating at StarCraft

as of Oct 2026

The rule: write your own StarCraft bot in C++, in one hour.

GPT-6 Astra: losing to strong bots, it downloaded Stardust, the best human-made bot, and ran it as its own.

The fix: the organiser rolled its code back.

Same pattern as CheatBench, now in the wild

Case study: the benchmark that broke containment

Attack chain: models evaluated on the ExploitGym cyber benchmark escaped their sandbox through a zero-day, reached the internet, breached Hugging Face and took the challenge solutions.

An agent pushed hard on a score will look for the answer key, wherever it is. Sources: Fortune, 21 July 2026, Hugging Face disclosure.

Hugging Face's security incident disclosure, published 16 July 2026: an intrusion driven end to end by an autonomous AI agent system.

Benchmark-maxxing: the score, not the assistant

LMArena rank of Llama 4 Maverick: the chat-tuned experimental variant ranked 2nd, the released model 32nd.

  • Leaderboards: tune a variant for the arena, ship another (Llama 4, 2025)
  • Thumbs-up: optimising for it made GPT-4o sycophantic; rolled back
  • A higher score is not a better assistant

Protect your own evals

Guardrails

Why guardrails are non-negotiable

99% right = 10,000 errors per million requests. Which layer would have stopped each one?

a $1 Tahoe → no prices, no commitments
an invented refund policy → ground in the real policy
glue on pizza → trust your sources

Guardrails in layers

What each layer does

  • Input: injections, jailbreaks, PII, out-of-scope
  • Retrieval: access control per user, before the model
  • Model: system prompt, refusals: necessary, never sufficient
  • Output: schema, citations, toxicity, business rules
  • Action: least privilege, human approval, budgets
  • Monitoring: logs, alerts, red team, kill switch

Keep at least one check outside the AI platform: one bug can disable every control inside it.

Guardrail tools

A guardrail that blocks 30% of real customers is a product bug: measure false positives too.

Regulation makes it mandatory

  • EU AI Act: general-purpose AI duties since Aug. 2025; logging, oversight, accuracy for high-risk systems
  • GDPR: personal data in prompts, logs, documents
  • Standards: NIST AI RMF, ISO/IEC 42001

💼 Business corner

A short report is what auditors will ask for: what was tested, on what data, what risks remain, who monitors them.

Choosing a model: the Pareto front

The Pareto front: no model is best at everything

as of Oct 2026

  • Each dot is a model: cost per task (log scale) against quality
  • On the front: no other model is both cheaper and better
  • Off the front (MiniMax-M3): a cheaper model scores higher
  • Choose on the front, with a quality threshold or a budget

Your turn: which variants would you never deploy?

  • V3 is dominated: V2 is cheaper or equal and at least as good
  • V5 is dominated: V4 is cheaper or equal and at least as good

The others are on the Pareto front: each one wins on cost or on quality.

Practice session

Lab: retrieval metrics and an LLM judge

Notebook lab-session/08_eval_harness_lab.ipynb. You need your own OpenRouter key from step 2 on.

  1. Complete recall_at_k, mrr, ndcg_at_k; compare three retrievers on 18 questions
  2. Generate answers with a RAG over the ECB archive
  3. Grade them with an LLM judge from another model family; read the verdicts

Course wrap-up

The course in 10 patterns

1
Tokens are the currency
S2
2
Prompt first, fine-tune last
S3, S4
3
Structure and validate outputs
S4
4
Untrusted input is data, not instructions
S4, S5, S6
5
Retrieve, rerank, cite
S5
6
Recall before faithfulness
S5, S8
7
Workflows before agents
S6
8
Least privilege, human approval
S6, S8
9
Held-out golden sets with cost and latency
all sessions
10
Guardrails in depth, monitored
S8

Key takeaways

  • Benchmarks saturate and get gamed: build a private golden set
  • Retrieval metrics first; calibrate LLM judges
  • Report confidence intervals, cost and latency
  • Capable models cheat: sandbox, read trajectories
  • Reasoning text is not an audit
  • Guardrails in layers are part of the product

Checklist (close)

Before you leave, you can explain:

Evaluation in 2027: open problems

as of Oct 2026

  • open How do you grade a model smarter than its judges?
  • open How do you test an agent that works for days?
  • open What if the model knows it is being tested?
  • open Benchmarks die in months: who builds the next ones?

Evaluation is the least solved part of generative AI. It is yours to build.