Why this lab exists
Every benchmark number you’ve seen on a leaderboard — MMLU, HellaSwag, TriviaQA — comes from an evaluation harness running the same loop: build a prompt, call the model, compare the output to an answer key, aggregate accuracy. But there is a gap between “call the model and check the answer” and “produce a statistically valid, contamination-clean benchmark number.”
The gap matters. A naive harness penalizes a model for answering “The answer is A” when the expected output is just “A”. A harness without contamination detection celebrates models that memorized the test set. A harness without confidence intervals publishes leaderboard rankings where half the differences are statistically insignificant.
Until you’ve implemented the few-shot prompt format and watched exact-match fail on correct paraphrases, until you’ve scored choices by log-likelihood and seen format sensitivity disappear, until you’ve run bootstrap resampling on 100 examples and realized the CI is ±9.5 percentage points — you don’t know why lm-evaluation-harness is a large project instead of 50 lines.
This lab builds an evaluation harness in three stages: from naive few-shot exact-match in ~200 lines to contamination-aware evaluation with bootstrap confidence intervals in ~780 lines. Each stage fixes one measured problem in the previous one.
What we’re building
An LLM evaluation harness in Python, across three stages. Each stage adds one capability and addresses one real problem in evaluation methodology.
We build:
- Few-shot evaluator (v0): prepend n examples, call model, compare with exact-match or multiple-choice extraction
- Log-likelihood scoring (v1): score each choice as a continuation, eliminate format sensitivity, add contextual calibration
- Contamination detection and bootstrap CI (v2): 13-gram fingerprinting, paired bootstrap significance test
- FastAPI server:
POST /eval,GET /tasks - Spring Boot Java integration:
EvalClientcalling our eval server
We explicitly skip (and why):
- Real LLM calls: the harness is model-agnostic via
model_fn: Callable[[str], str]; the tests and the server use mock models.scripts/bench.py --gpt2wires in GPT-2 small (124M) as a real-model check - ROUGE/BERTScore: requires heavy dependencies and an embedding model; covered in “What the Toy Misses”
- Human evaluation: requires crowdsourcing infrastructure; covered in “What the Toy Misses”
- Full MMLU/HellaSwag datasets: 10-example lite versions illustrate the mechanics without requiring dataset downloads
Mental model
An evaluation harness is a three-stage pipeline:
Benchmark dataset
|
v
[Prompt builder] ← few-shot examples + test question
|
v
[Model] ← Callable[[str], str]
|
v
[Scorer] ← extract answer, compare to gold label
|
v
[Aggregator] ← accuracy + confidence interval + contamination report
The naive version of this is 20 lines. The production version (lm-evaluation-harness) is a large codebase with hundreds of task definitions. The difference is in the details:
Format sensitivity — a model that would correctly pick A if scoring log-likelihoods answers “The answer is: option A” in free generation. Exact-match comparison to “A” scores this as wrong. Log-likelihood scoring fixes this by never generating text: compute log P(A | context), log P(B | context), etc. and pick the highest.
Length bias — a choice with more tokens has lower raw log probability (probabilities multiply; more terms means lower product). “All of the above” gets unfairly penalized vs “A”. Normalized log-likelihood divides by token count to correct this.
Prior bias — “A” appears more frequently in training data than “D”. The model assigns higher prior probability to A-continuations. Contextual calibration subtracts log P(choice | empty context) from every score, removing this prior.
Statistical validity — a single accuracy number from 100 examples has a 95% CI of about ±10pp. The lab’s bootstrap_ci puts 72 correct out of 100 at [62%, 81%]. Bootstrap CI makes this explicit.
Contamination — if the model saw "What is the capital of France? Paris" during training, it’s measuring memorization, not generalization. 13-gram fingerprinting detects this before you publish numbers.
Prerequisites
- Python 3.12
- NumPy (
pip install numpy) — for bootstrap CI - FastAPI + uvicorn (
pip install fastapi uvicorn) — for the server - No LLM download required — the harness is model-agnostic; tests use mock functions
Stage-by-stage build
Stage 0 Few-Shot Eval with Exact Match
- Implement Task dataclass: name, metric, examples list
- Implement FewShotEvaluator.build_prompt(task, test_example, n_shot=5)
- Implement FewShotEvaluator.evaluate(model_fn, task, n_shot=5) -> EvalResult
- Implement _normalize_string() and _extract_multiple_choice()
- Write 5 tests: prompt includes n examples, 0-shot works, exact match normalizes, multiple-choice extracts A-D, accuracy computed correctly
The simplest possible evaluation loop. No log-likelihood, no calibration.
The few-shot prompt format:
For multiple-choice tasks (HellaSwag, MMLU):
Question: She poured water into the pot and placed it on the stove. She then
A. turned on the burner and waited for the water to boil.
B. placed the pot in the refrigerator.
C. filled the pot with sand.
D. put the pot on the floor.
Answer: A
Question: He laced up his running shoes and stepped outside. He then
A. sat down on the couch.
B. began jogging down the street.
C. took off his shoes.
D. cooked breakfast.
Answer: B
[n_shot demos above — the test example below]
Question: The teacher wrote the problem on the blackboard. The students
A. left the classroom.
B. started talking loudly.
C. took out their notebooks and began working.
D. fell asleep.
Answer:The model must complete “Answer:” with a single letter. The n_shot demonstrations show the expected format.
Why n_shot matters:
Zero-shot (no demonstrations) fails on novel formats. The model doesn’t know it’s supposed to respond with just a letter. With 5 demonstrations, it sees the pattern: question, choices, “Answer: X”. That alone can move accuracy a lot without any model change, which is also why results are sensitive to which demonstrations you pick and in what order (Zhao et al., 2021).
Exact match normalization:
For open-ended tasks (TriviaQA), the expected answer is "Paris" and the model might generate "Paris." or "The capital is Paris". Normalization handles the punctuation case but not the paraphrase case. Lowercase + strip punctuation is the minimum; production harnesses also strip articles (“the”, “a”), normalize whitespace, and handle number formatting.
def _normalize_string(s: str) -> str:
s = s.strip().lower()
s = s.translate(str.maketrans("", "", string.punctuation))
s = re.sub(r"\s+", " ", s).strip()
return sMultiple-choice extraction:
The model might generate any of: “A”, “A.”, “Answer: A”, “The answer is A”, “Option A is correct”. The extractor tries patterns in priority order:
# Pattern 1: starts with letter
re.match(r"^([ABCD])[.):]?\s", completion)
# Pattern 2: "Answer: A"
re.search(r"[Aa]nswer[:\s]+([ABCD])", completion)
# Pattern 3: "is A" / "is (A)" — case-sensitive, letter must end a word
re.search(r"\bis\s+\(?([ABCD])\b", completion)If none match, return "" — counted as wrong. This is where format sensitivity shows up: a model that would correctly identify the answer often generates a format the extractor misses. Run the formats above through the lab’s extractor and “A”, “A.”, “Answer: A” and “The answer is A” give A, while “Option A is correct”, “I think A” and “(A)” give "". Missing is the safe failure. The dangerous one is a wrong letter: an earlier version matched pattern 3 case-insensitively, so “Option A is correct” read as “is c…” and returned C. Log-likelihood scoring (v1) sidesteps extraction entirely.
EvalResult:
@dataclass
class EvalResult:
task_name: str
n_shot: int
accuracy: float
num_correct: int
num_total: int
examples_evaluated: list[ExampleResult]The examples_evaluated list lets you drill into which examples the model got wrong — essential for debugging prompts and spotting systematic failure patterns.
Stage 1 Log-Likelihood Scoring
- Implement score_logprob(model_fn_logprob, context, continuation) -> float
- Implement score_normalized(model_fn_logprob, context, continuation) -> float
- Implement ContextualCalibration with get_bias() and calibrated_score()
- Implement LogprobEvaluator with scoring_mode: raw | normalized | calibrated
- Implement EvalSuite.run(tasks, n_shot) -> SuiteResult with macro_average
- Write 4 tests: logprob is negative float, normalized penalizes long choices, calibrated score shifts correctly, EvalSuite aggregates correctly
Log-likelihood scoring eliminates format sensitivity by never generating text.
The core insight:
Instead of asking the model to generate “A”, “B”, “C”, or “D”, score each choice as a continuation of the context:
context = "Question: What is the capital of France?\nA. London\nB. Paris\nC. Berlin\nD. Rome\nAnswer:"
score(A) = log P("A. London" | context)
score(B) = log P("B. Paris" | context)
score(C) = log P("C. Berlin" | context)
score(D) = log P("D. Rome" | context)
pick = argmax(score(A), score(B), score(C), score(D))The model never generates anything. It just assigns probabilities. A model that “knows” Paris is correct will assign higher probability to “B. Paris” as a continuation, regardless of how it would format a free-text response.
model_fn_logprob protocol:
ModelFnLogprob = Callable[[str, str], float]
# Takes (context, continuation), returns log probability (always <= 0)For a real LLM, this is typically:
- Tokenize context + continuation together
- Run a forward pass to get token log probabilities
- Sum log probs for only the continuation tokens
Our implementation accepts any callable that satisfies this protocol — including mock functions for testing.
Normalized log-likelihood:
Raw log-likelihood biases toward shorter choices. “A” (1 token) has higher raw log-prob than “All of the above” (4 tokens) even if the model “prefers” the latter. Normalization divides by token count:
def score_normalized(model_fn_logprob, context, continuation) -> float:
raw = score_logprob(model_fn_logprob, context, continuation)
token_count = max(1, len(continuation.split()))
return raw / token_countWe approximate token count by whitespace-split — sufficient for short choices. Real harnesses use the model’s tokenizer (byte-pair encoding token counts differ from word counts).
Contextual calibration:
The model has prior biases. “A” appears more in training text than “D”. Even before reading the question, the model assigns higher probability to “A” as a next token. This biases multiple-choice accuracy toward options labeled “A”.
Fix: compute bias[choice] = log P(choice | "") — the probability under empty context. Then:
calibrated_score = log P(choice | context) - log P(choice | "")After calibration, all choices start at equal expected score. This is a simplified form of the idea in Zhao et al. (2021), who estimate the bias from a content-free input such as “N/A” and fit a correction; they report average accuracy gains of up to 30 points absolute for GPT-3 and GPT-2 (arXiv:2102.09690).
EvalSuite:
evaluator = LogprobEvaluator(scoring_mode="calibrated", calibrator=ContextualCalibration(gpt2_logprob))
suite = EvalSuite(evaluator, gpt2_logprob)
result = suite.run([HELLASWAG_LITE, MMLU_LITE_MATH], n_shot=5)
print(result.per_task) # {'HellaSwag-lite': 0.6, 'MMLU-lite-math': 0.1}
print(result.macro_average) # 0.35Those are real GPT-2 small (124M) numbers from scripts/bench.py --gpt2, and they mean very little: each task has 10 examples, so each accuracy has a 95% CI about ±30 points wide.
Macro-average weights all tasks equally regardless of example count. When task sizes differ, report the example-weighted average too.
LogprobEvaluator only scores multiple-choice tasks and raises ValueError on an exact-match task: with no candidate answers there is nothing to score. An earlier version of this lab “fell back” by copying the gold answer into the prediction, so every model scored 100% on TriviaQA-lite. A harness bug that inflates scores is worse than one that crashes.
Stage 2 Contamination Detection + Bootstrap CI
- Implement ContaminationDetector with add_training_shard() and check_contamination() -> float
- Implement bootstrap_ci(results, n_bootstrap=1000, confidence=0.95) -> BootstrapCI
- Implement paired_bootstrap_test(results_A, results_B, n_bootstrap=1000) -> p_value
- Implement EvalReport dataclass with task, accuracy, ci_95, contaminated_examples
- Implement Harness that composes contamination filtering + evaluation + CI into one call
- Write 4 tests: contamination flags exact example, CI in [0,1], CI width decreases with more examples, paired bootstrap p_value < 0.05 when A always wins
Two critical correctness mechanisms: know what your model actually learned, and know whether your accuracy estimates are meaningful.
13-gram contamination detection:
The GPT-3 paper (Brown et al., 2020) used 13-gram overlap to check whether benchmark examples appeared in Common Crawl training data. 13 is a deliberate choice: long enough to be distinctive (a random 13-gram match is near-impossible), short enough that a copied passage shares many of them. A Python set is fine for a toy but not for a real corpus: scripts/bench.py turns a 1 MB synthetic shard into 230,204 distinct 13-grams in 0.073 s, and the index takes 53 MB of memory, about 50 bytes of index per byte of text. Terabyte-scale decontamination uses hashed n-grams, Bloom filters or suffix arrays instead.
def _make_ngrams(text: str, n: int = 13) -> set[tuple[str, ...]]:
words = text.lower().split()
return {tuple(words[i:i + n]) for i in range(len(words) - n + 1)}
class ContaminationDetector:
def add_training_shard(self, texts: list[str]) -> None:
for text in texts:
self._training_ngrams.update(_make_ngrams(text))
def check_contamination(self, example_text: str) -> float:
words = example_text.lower().split()
if 0 < len(words) < 13: # too short to have a 13-gram
needle = " " + " ".join(words) + " "
return 1.0 if any(needle in t for t in self._training_texts) else 0.0
example_ngrams = _make_ngrams(example_text)
found = example_ngrams.intersection(self._training_ngrams)
return len(found) / len(example_ngrams)Short examples need that special case. All ten TriviaQA-lite examples are under 13 words (median 8, question plus answer), so a pure 13-gram check can never flag one, however many times it appears in the training data; an earlier version of this lab had exactly that blind spot, and its own contamination test failed because of it. The fallback looks for the whole word sequence instead. It is still literal: “France? Paris” followed by a period in the training text is the token paris., not paris, and doesn’t match. Paraphrases slip through too, which is the main finding of the rephrased-samples paper in “Where to go deeper”.
Threshold: examples with more than 10% of their 13-grams in training data are flagged. For a 200-word example that is about 19 of its 188 13-grams, strong evidence the example was seen during training.
Bootstrap confidence intervals:
The bootstrap is conceptually simple: resample with replacement from your results, compute accuracy for each resample, use the 2.5th and 97.5th percentiles as CI bounds.
def bootstrap_ci(results: list[bool], n_bootstrap=1000, confidence=0.95) -> BootstrapCI:
arr = np.array(results, dtype=float)
boot_means = np.zeros(n_bootstrap)
for i in range(n_bootstrap):
sample = rng.choice(arr, size=len(arr), replace=True)
boot_means[i] = sample.mean()
alpha = 1.0 - confidence
lower = np.percentile(boot_means, 100 * (alpha / 2))
upper = np.percentile(boot_means, 100 * (1 - alpha / 2))
return BootstrapCI(lower=lower, upper=upper, mean=arr.mean())Width reference, measured with the lab’s bootstrap_ci (1,000 resamples, seed 42), half-width of the 95% CI:
| n | at 72% accuracy | at 50% accuracy | formula 1.96·√(p(1−p)/n) at 72% / 50% |
|---|---|---|---|
| 10 | ±30.0pp | ±30.0pp | ±28.4 / ±31.0 |
| 100 | ±9.5pp | ±10.0pp | ±8.8 / ±9.8 |
| 500 | ±4.0pp | ±4.3pp | ±3.9 / ±4.4 |
| 1,000 | ±2.8pp | ±2.9pp | ±2.8 / ±3.1 |
| 14,042 (MMLU test size) | ±0.76pp | ±0.79pp | ±0.74 / ±0.83 |
The formula is good enough for planning; the bootstrap earns its keep on metrics that aren’t simple proportions.
Paired bootstrap test:
To test whether model A is significantly better than model B on the same examples:
def paired_bootstrap_test(results_A, results_B, n_bootstrap=1000) -> float:
# Resample pairs (A_i, B_i) together
for _ in range(n_bootstrap):
idx = rng.choice(n, size=n, replace=True)
delta = arr_A[idx].mean() - arr_B[idx].mean()
if delta <= 0:
count_leq_zero += 1
return count_leq_zero / n_bootstrap # p_valueIf p_value is less than 0.05, model A is significantly better at the 95% level (this is a one-sided test: “is A better?”). How big a gap you can detect depends on the number of examples n and on the share of examples where the two models disagree, d. Only disagreements carry information. A useful approximation for the true gap you can detect 80% of the time is 2.5 × √(d/n). scripts/bench.py checks it by simulating benchmarks and running the lab’s paired_bootstrap_test 300 times per point:
| n | d = 0.20 (models disagree on 20%) | d = 0.40 |
|---|---|---|
| 100 | 10.9pp (formula 11.1) | 16.8pp (formula 15.7) |
| 500 | 5.0pp (formula 5.0) | 7.3pp (formula 7.0) |
| 1,000 | 3.6pp (formula 3.5) | 5.3pp (formula 5.0) |
With no true gap, the test fired in 4–6% of simulated runs, as a 5% test should. The often-quoted “7 points at n=100” is the observed gap that just reaches p < 0.05 at d = 0.2 (1.645 × √(0.2/100) ≈ 7.4pp); a model that is truly 7 points better only clears that bar about half the time.
EvalReport ties it together:
@dataclass
class EvalReport:
task: str
n_shot: int
accuracy: float
ci_95: tuple[float, float]
contaminated_examples: int
total_examples: intA responsible benchmark report always includes CI alongside accuracy and reports contaminated examples removed. The Harness class composes all three: filter contamination, run evaluation, compute CI, return report.
Run it yourself
labs/llm-eval ↗
Python 3.12+pip or uv - 1 Clone and install dependencies
git clone https://github.com/pushkarkumar-dev/system-design-labs cd system-design-labs/labs/llm-eval pip install -e '.[test]' - 2 Run all tests (no model download — all use mock functions)
python -m pytest tests/ -v - 3 Try the few-shot evaluator on HellaSwag-lite with a mock model
python -c " from src.tasks import HELLASWAG_LITE from src.v0_fewshot import FewShotEvaluator evaluator = FewShotEvaluator() # Mock model that always answers B result = evaluator.evaluate(lambda p: 'B', HELLASWAG_LITE, n_shot=3) print(f'Task: {result.task_name}') print(f'Accuracy: {result.accuracy:.0%} ({result.num_correct}/{result.num_total})') " - 4 Try bootstrap CI
python -c " import numpy as np from src.v2_contamination import bootstrap_ci rng = np.random.default_rng(42) results_100 = [i < 72 for i in range(100)] ci = bootstrap_ci(results_100, rng=rng) print(f'Accuracy: {ci.mean:.1%}') print(f'95% CI: [{ci.lower:.1%}, {ci.upper:.1%}]') print(f'CI width: +/-{(ci.upper - ci.lower)/2*100:.1f}pp') " - 5 Run the benchmarks and power simulations (about 4 minutes with --quick; add --gpt2 for the real-model check)
python scripts/bench.py --quick - 6 Start the FastAPI server
uvicorn src.server:app --port 8000 - 7 List available tasks
curl -s http://localhost:8000/tasks | python -m json.tool - 8 Run evaluation via HTTP
curl -s -X POST http://localhost:8000/eval \ -H 'Content-Type: application/json' \ -d '{"task_name": "hellaswag-lite", "n_shot": 5, "model": "mock-always-A"}' | python -m json.tool
===== Tests =====
tests/test_eval.py::TestV0FewShot::test_fewshot_prompt_includes_n_examples PASSED
tests/test_eval.py::TestV0FewShot::test_fewshot_zero_shot_has_no_demonstrations PASSED
tests/test_eval.py::TestV0FewShot::test_exact_match_normalizes_correctly PASSED
tests/test_eval.py::TestV0FewShot::test_multiple_choice_extracts_a_through_d PASSED
tests/test_eval.py::TestV0FewShot::test_accuracy_computed_correctly PASSED
tests/test_eval.py::TestV1Logprob::test_logprob_score_is_negative_float PASSED
tests/test_eval.py::TestV1Logprob::test_normalized_score_penalizes_long_choices PASSED
tests/test_eval.py::TestV1Logprob::test_calibrated_score_shifts_correctly PASSED
tests/test_eval.py::TestV1Logprob::test_eval_suite_aggregates_correctly PASSED
tests/test_eval.py::TestV1Logprob::test_logprob_evaluator_rejects_exact_match_tasks PASSED
tests/test_eval.py::TestV2Contamination::test_contamination_detection_flags_exact_example PASSED
tests/test_eval.py::TestV2Contamination::test_bootstrap_ci_is_within_0_1 PASSED
tests/test_eval.py::TestV2Contamination::test_ci_width_decreases_with_more_examples PASSED
tests/test_eval.py::TestV2Contamination::test_paired_bootstrap_p_value_low_when_a_always_wins PASSED
14 passed
===== Few-shot evaluator, mock model that always answers B =====
Task: HellaSwag-lite
Accuracy: 40% (4/10)
===== Bootstrap CI example =====
Accuracy: 72.0%
95% CI: [62.0%, 81.0%]
CI width: +/-9.5pp
===== POST /eval (hellaswag-lite, mock-always-A) =====
{"task": "HellaSwag-lite", "n_shot": 5, "accuracy": 0.4, "num_correct": 4, "num_total": 10,
"ci_95_lower": 0.1, "ci_95_upper": 0.7, "model": "mock-always-A"} Benchmarks
Apple M1 Ultra, 64 GB RAM, macOS 27, Python 3.13.7, numpy 2.5.4 — CPU, single thread, 2026-10-11 | Metric | Result | Notes |
|---|---|---|
| Few-shot prompt build (5-shot, HellaSwag-lite, 1,294 chars) | 369,000 prompts/sec | measured — 2.7 µs per prompt; median of 5 runs |
| Few-shot prompt build (5-shot, ~200-word examples, 5,309 chars) | 355,000 prompts/sec | measured — 2.8 µs; synthetic task; string building barely notices the size |
| bootstrap_ci (n=100, 1,000 resamples) | 147 CIs/sec | measured — 6.8 ms; the lab loops in Python over rng.choice |
| Vectorised bootstrap (n=100, 1,000 resamples) | 2,580 CIs/sec | measured — 0.39 ms; one (1000, n) index matrix; not lab code, 17x faster |
| paired_bootstrap_test (n=100, 1,000 resamples) | 115 tests/sec | measured — 8.7 ms |
| 13-gram contamination check (60-word example vs 1 MB index) | 104,000 checks/sec | measured — 9.6 µs; index of 230,204 13-grams built in 0.073 s, 53 MB in memory |
| Paired test, smallest true gap with 80% power (n=500) | 5.0 / 7.3 pp | measured by simulation — models disagree on 20% / 40% of examples; 300 runs per point |
| 95% CI half-width, 72% accuracy, n=100 / n=1,000 | 9.5 / 2.8 pp | measured with bootstrap_ci; formula 1.96·√(p(1−p)/n) gives 8.8 / 2.8 |
Everything here is CPU-bound Python and numpy; no GPU is involved, and no model either: the tests and the server use mock models, so nothing in this table measures a model’s quality. Other processes were running on the machine; the JSON in bench-results.json records the load average.
Prompt building costs microseconds, so in a real evaluation the model call dominates. The surprise is the bootstrap: the lab’s bootstrap_ci calls rng.choice once per resample in a Python loop, and that is 17x slower than drawing all 1,000 resamples as one index matrix. At 6.8 ms per CI it doesn’t matter for one report, but it does if you bootstrap every task of every checkpoint in CI, or run power simulations: the 23,400 paired tests behind the power table took 4.6 minutes.
A real model, briefly. scripts/bench.py --gpt2 runs GPT-2 small (124M, CPU) through both evaluators, 5-shot:
| task (10 examples each) | v0 generate + extract | v0, cut at first newline | v1 raw | v1 normalized | v1 calibrated |
|---|---|---|---|---|---|
| HellaSwag-lite | 3/10 | 3/10 | 2/10 | 4/10 | 6/10 |
| MMLU-lite-math | 4/10 | 4/10 | 0/10 | 0/10 | 1/10 |
| TriviaQA-lite | 0/10 | 1/10 | — | — | — |
With 10 examples every one of these numbers has a 95% CI about ±30 points wide, so none of the differences between columns is evidence of anything. Two things are real, though. GPT-2’s v0 completions were ” B\n\nQuestion:” on HellaSwag and ” C\n\nQuestion:” on MMLU for the samples we looked at: v0 accuracy is just how often the model’s favourite letter is right. And on TriviaQA it answered the first question ” Paris\n\nQuestion:”, which normalizes to “paris question” and fails exact match against “paris”. Cutting each completion at its first newline, as real harnesses do with stop sequences, turns that into TriviaQA-lite’s only correct answer (1/10); it changes nothing on the multiple-choice tasks, where the extractor already reads the first letter.
Stress tests
n_shot sensitivity: run the same model on HellaSwag-lite with n_shot = 0, 1, 3, 5. Plot accuracy vs n_shot. Then shuffle the order of the demonstrations and run again. Zhao et al. (2021) found that demonstration choice and order alone can swing GPT-3 from near chance to near state-of-the-art. With 10 examples per task you won’t be able to tell real effects from noise, which is the point of the next three tests.
CI convergence: run bootstrap_ci on the same 72-of-100 results with n_bootstrap = 100, 500, 1000, 5000 and 20 different seeds each. Measured: the lower bound’s standard deviation across seeds is 0.95pp at 100 resamples, 0.46pp at 500, 0.60pp at 1,000 (range 2.0pp) and 0.0pp at 5,000. It isn’t monotone because with n=100 every bootstrap mean is a multiple of 1%, so the percentile snaps between grid points; at 5,000 resamples it stops moving. Seed noise at 1,000 resamples is small next to the ±9.5pp interval itself, which is why 1,000 is a reasonable default.
Contamination threshold sensitivity: add a training shard that overlaps with exactly 5%, 10%, 15%, and 20% of an eval example’s 13-grams. Verify that the 10% threshold correctly separates near-matches (expected noise) from true contamination (model has seen the example). Adjust the threshold and observe false positive rate.
Paired test power: simulate pairs of results where model A is truly better by a given gap, with a fixed disagreement rate between the models, and count how often paired_bootstrap_test returns p < 0.05. scripts/bench.py does this for n = 100, 500, 1000 and disagreement 20% and 40% (the table in the v2 section). At n=100 and 20% disagreement, a true 6.7-point gap is detected 44% of the time and a 10-point gap 72% of the time; with no gap the test fires 4–6% of the time, as it should.
Format sensitivity experiment: implement mock models that answer “A”, “The answer is A”, “Option A is correct” and “(A)”, and run each through v0. The lab’s extractor gets the first two and misses the last two (scored wrong). Then give a real model an exact-match task: GPT-2 answered ” Paris\n\nQuestion:” and v0 scored it wrong. Add a stop at the first newline and compare. Log-likelihood scoring (v1) avoids extraction entirely for multiple-choice tasks.
What the toy misses
- Open-ended generation metrics (ROUGE, BLEU, BERTScore) Exact match fails for open-ended tasks — a correct paraphrase scores 0. ROUGE measures n-gram overlap; BERTScore computes contextual embedding similarity. Both require additional models and careful interpretation.
- Model-graded evaluation GPT-4 as a judge evaluates model outputs for helpfulness, safety, and factuality. This requires a grading prompt, handling judge inconsistency (run 3x and majority vote), and detecting self-preference bias.
- Human evaluation protocols Automated metrics correlate poorly with human preference for open-ended tasks. Crowdsourcing human evals (via MTurk or Scale) requires inter-annotator agreement measurement (Cohen's kappa), outlier removal, and calibration.
- Dynamic benchmarks Static benchmarks saturate as models improve. DynaBench collects adversarial examples that fool current models. Maintaining a live leaderboard requires continuous data collection and anti-contamination measures.
- Chain-of-thought evaluation CoT prompting changes accuracy significantly. A fair eval must test both direct and CoT prompting, compare reliably, and measure whether the reasoning chain actually leads to the correct answer or just post-hoc rationalizes it.
- Evals as unit tests in CI Production eval pipelines run on every model checkpoint. Regressions on safety evals block deployment. This requires fast evals (subset of full benchmark), statistical power to detect small regressions, and automated gates.
Wiring it into a Java/Spring service
Wiring it into a Java/Spring service
org.springframework.ai:spring-ai-openai-spring-boot-starter:1.0.0 org.springframework.boot:spring-boot-starter-web:3.3.0 labs/llm-eval/java-integration Clone and run: cd labs/llm-eval/java-integration && mvn spring-boot:run Part A — EvalClient: calling our eval server
EvalClient.java wraps our Python FastAPI server’s POST /eval and GET /tasks endpoints using Spring Framework 6.1’s RestClient. The entire client fits in under 60 lines.
public class EvalClient {
private final RestClient http;
public EvalResponse evaluate(String taskName, int nShot, String model) {
var body = new EvalRequest(taskName, nShot, model);
return http.post()
.uri("/eval")
.contentType(MediaType.APPLICATION_JSON)
.body(body)
.retrieve()
.body(EvalResponse.class);
}
public record EvalResponse(
String task, int nShot, double accuracy,
int numCorrect, int numTotal,
double ci95Lower, double ci95Upper, String model
) {}
}The response includes accuracy and 95% CI bounds — the client can print “40.0% [10.0%, 70.0%]” without any local statistics computation. The server calls bootstrap_ci without a seed, so the bounds can shift by a point between calls on larger tasks.
Part B — EvalDemoApplication: the integration demo
The demo application shows three things:
- Health check — skips gracefully if the Python server is not running
- Task listing —
GET /tasksreturns all built-in tasks with name, metric, and example count - CI interpretation — prints a reference table of CI widths vs sample size
var result = evalClient.evaluate("hellaswag-lite", 5, "mock-always-A");
System.out.printf("Accuracy: %.1f%% [%.1f%%, %.1f%%]%n",
result.accuracy() * 100,
result.ci95Lower() * 100,
result.ci95Upper() * 100);
System.out.printf("CI width: +/-%.1fpp%n",
(result.ci95Upper() - result.ci95Lower()) * 100 / 2);Part C — Connecting real LLMs with Spring AI
For production evaluation pipelines, you would replace the mock-always-A model with a real LLM via Spring AI:
ChatClient chatClient = chatClientBuilder.build();
// Use Spring AI to call GPT-4 for model-graded eval
String evaluation = chatClient.prompt(
"Is this answer correct? Question: " + question +
" Expected: " + expected + " Model answer: " + modelAnswer +
" Reply with only: CORRECT or WRONG"
).call().content();This is the “model-graded evaluation” pattern (see What the Toy Misses). Spring AI’s ChatClient abstraction means the same Java code works whether you’re calling GPT-4, Claude, or a local Ollama model — only application.yml changes.
Run it
# Terminal 1: start the Python eval server
cd labs/llm-eval
uvicorn src.server:app --port 8000
# Terminal 2: start the Spring Boot demo
cd labs/llm-eval/java-integration
mvn spring-boot:runExpected output. The Java side wasn’t run on the machine that measured this page (no JDK there); the numbers below are what the Python server returns for these exact requests, formatted the way EvalDemoApplication prints them. The server’s Pydantic models use snake_case (task_name, ci_95_lower), so the Java records map their camelCase fields with @JsonProperty; without that, POST /eval fails with 422.
=== LLM Evaluation Harness — Spring Integration Demo ===
--- Available Tasks ---
HellaSwag-lite metric=multiple_choice examples=10
TriviaQA-lite metric=exact_match examples=10
MMLU-lite-math metric=multiple_choice examples=10
--- Evaluating mock-always-A on hellaswag-lite (5-shot) ---
Task: HellaSwag-lite
Model: mock-always-A
n-shot: 5
Accuracy: 40.0% (4/10)
95% CI: [10.0%, 70.0%]
CI width: ±30.0pp
--- Evaluating mock-always-A on triviaqa-lite (5-shot) ---
Accuracy: 0.0% [0.0%, 0.0%]
(Expected: 0% — 'A' is never a valid answer for open-ended questions)
--- CI Width Reference ---
n=100 examples -> 95% CI width ≈ ±10pp
n=200 examples -> 95% CI width ≈ ±7pp
n=500 examples -> 95% CI width ≈ ±4.5pp
n=1000 examples -> 95% CI width ≈ ±3pp
n=14000 examples (MMLU) -> 95% CI width < ±1pp
Implication: with 100 examples, a model scoring 72% is
statistically indistinguishable from one scoring 62-82%.
Most leaderboard comparisons use 100-500 examples.
Done.The reference lines are hard-coded in the demo and are worst-case (50% accuracy) round numbers; the measured table in the v2 section gives ±9.5pp at n=100 and ±2.8pp at n=1,000 for 72% accuracy. The 4/10 and [10%, 70%] come from the 10-example task and show the point better than the table does: a 10-example eval can’t tell 40% from 10% or from 70%.
What surprised me
Where to go deeper
- HELM benchmark: holistic evaluation covering accuracy, calibration, efficiency, and fairness — crfm.stanford.edu/helm
- lm-evaluation-harness (EleutherAI): the reference open-source harness — github.com/EleutherAI/lm-evaluation-harness
- MMLU paper: measuring multitask language understanding across 57 subjects — arxiv.org/abs/2009.03300
- Rethinking Benchmark and Contamination for Language Models with Rephrased Samples (Yang et al., 2023): shows that paraphrased or translated test items slip past n-gram decontamination like ours — arxiv.org/abs/2311.04850
- Calibration paper (Zhao et al., 2021): contextual calibration for few-shot learning — “Calibrate Before Use: Improving Few-Shot Performance of Language Models” — arxiv.org/abs/2102.09690
Related labs and questions
- Previous in AI: Transformer From Scratch (lab
transformer) — the model architecture being evaluated - Previous in AI: RAG System (lab
rag) — RAG pipelines need eval harnesses to measure retrieval quality - Next in AI: LLM Inference Engine (lab
llm-inference) — once you can evaluate, you can benchmark inference optimizations - System design question: How would you build a continuous evaluation system that runs on every model checkpoint in CI? What statistical test would you use to detect regressions, and what is the minimum regression size you can reliably detect with 500 eval examples per task? (Hint: measured by simulation in
scripts/bench.py, the paired bootstrap at n=500 reaches 80% power at a 5.0-point gap when the models disagree on 20% of examples and 7.3 points at 40%; roughly 2.5 × √(d/n).) - System design question: If a benchmark has 14,000 examples but 5% are contaminated, should you remove the contaminated examples or flag the entire benchmark? What is the expected accuracy inflation from 5% contamination assuming the model gets all contaminated examples correct?