Evaluation Harnesses and Reproducibility › A Local, Versioned Fixture
Language AI HandbookAll chapters To make all of this concrete and runnable without network access or API keys, we build a completely local fixture. It has three parts:
- A tiny task dataset of math word problems with a deterministic reference answer. Each item is a task instance.
- A local mock model that answers correctly with a per-item probability determined by its "capability," and otherwise returns a plausible but wrong answer. The fixture uses a deterministic hash draw for each task. The two models share the draw for paired comparison.
- A grader that parses a final numeric answer and compares it to the reference, with a version string.
The mock demonstrates the runner and archive. Its specified success probabilities let us compare the observed scores with known inputs. The later coverage experiment independently samples binary outcomes under a stated population model.
Let's set up the environment and plotting style.
PythonIn [2]Expand
import hashlib
import json
import math
import platform
import re
from dataclasses import asdict, dataclass
from decimal import Decimal, InvalidOperation
from pathlib import Path
from statistics import NormalDist
from tempfile import TemporaryDirectory
import numpy as np
bundle_workspace = TemporaryDirectory(prefix="eval-harness-")
ARTIFACT_DIR = Path(bundle_workspace.name)The hidden setup seeds the book plot helpers. The fixture controls its random draws independently through task IDs and defined random generators.
The Dataset and Its Digest
Each item has an id, a natural-language question, and a canonical answer string. We keep the items in a list; the dataset digest is the SHA-256 of the JSON serialization of the list in a fixed key order. Any edit to any item changes the digest. Canonicalization matters here: JSON serialization is not unique across libraries and key orderings, so we force a sorted-key, compact representation so that two machines serializing the same logical object produce the same bytes, and therefore the same digest.
PythonIn [4]Expand
def canonical_bytes(obj) -> bytes:
"""Serialize an object to bytes in a stable, key-sorted form."""
return json.dumps(
obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False
).encode("utf-8")
def digest(obj) -> str:
"""SHA-256 hex digest of the canonical serialization of obj."""
return hashlib.sha256(canonical_bytes(obj)).hexdigest()
# A tiny math-word-problem dataset. The reference answer is the exact
# string a correct response should contain after '####'.
dataset = [
{
"id": "m01",
"question": "Natalia sold 48 clips in April and half that in May. How many did she sell total?",
"answer": "72",
},
{
"id": "m02",
"question": "A robe takes 2 bolts of blue and half that of white. How many bolts total?",
"answer": "3",
},
{
"id": "m03",
"question": "Weng earns $12/hour for 50 minutes. How much does she earn?",
"answer": "10",
},
{
"id": "m04",
"question": "Betty picked 8 apples, then 3 more, then half the total. How many now?",
"answer": "?",
},
{
"id": "m05",
"question": "A train travels 60 km/h for 2.5 hours. How far does it go?",
"answer": "150",
},
{
"id": "m06",
"question": "There are 5 dozen eggs, 3 are used. How many remain?",
"answer": "57",
},
{
"id": "m07",
"question": "James buys 4 books at $5 each and pays with a $50 bill. Change?",
"answer": "30",
},
{
"id": "m08",
"question": "A recipe needs 3/4 cup sugar per batch for 2 batches. Total cups?",
"answer": "1.5",
},
]
dataset_digest = digest(dataset)ConsoleOut [5]Expand
Items: 8 Dataset digest: 531d7cc553482833...
The digest is a short fingerprint of the exact dataset bytes. If we later append a question, fix a typo in m04, or reorder items, this hex string changes. Notice that m04 has a deliberately broken reference ("?") to remind us that bad fixture data is itself a reproducibility hazard: the harness should flag items whose reference cannot be parsed, and we will see this in the grader audit.
That deliberate bug is worth dwelling on, because it models a failure that happens constantly in real benchmarks. A reference answer that "looks fine" to a human can be unparseable to a grader, or parse to something subtly different from what the item author intended. If the harness silently scores such an item as wrong, you get a slightly deflated accuracy that nobody can explain, and the model gets blamed for a data bug. The fix is not cleverness; it is making the grader report the condition so that it is visible in the aggregate report.
The Prompt Template as a Versioned Artifact
The prompt template is a real object with a name, a version, and a digest. It assembles the system instruction and the per-item question. We deliberately include an answer-format constraint (#### <answer>) so the grader can parse reliably: this follows the final-answer marker used in the GSM8K dataset and matters because grader fragility is a leading source of irreproducibility. The constraint is not a formality; it is a contract between the prompt and the grader. If the prompt stops enforcing the format, the grader starts failing to parse, and the score moves for a reason that has nothing to do with the model's reasoning.
PythonIn [6]Expand
@dataclass(frozen=True)
class PromptTemplate:
name: str
version: str
system: str
user_template: str # must contain '{question}'
def render(self, question: str) -> list[dict]:
"""Return chat-format messages for one item."""
return [
{"role": "system", "content": self.system},
{
"role": "user",
"content": self.user_template.format(question=question),
},
]
def template_digest(self) -> str:
"""Digest over just the template content (what versioning must pin)."""
return digest({"system": self.system, "user": self.user_template})
prompt = PromptTemplate(
name="math_cot_v1",
version="1.0.0",
system=(
"Solve the problem step by step. "
"End your final line with '#### ' followed by the numeric answer only."
),
user_template="{question}",
)
prompt_digest = prompt.template_digest()We give the template both a semantic version and a content digest. The version is for humans reading the changelog; the digest is the contract. If someone edits the system message but forgets to bump the version, the digest still catches the change, which is the whole point. Conversely, if someone bumps the version but changes nothing, the digest stays the same, which tells you the "change" was cosmetic.
Model Configuration: What Must Be Pinned
The model configuration is the most commonly under-specified surface in published evaluation. A ModelConfig should record every field that affects outputs. For a local model this includes the tokenizer revision and inference engine; for a hosted model it includes the provider, the API model identifier, and any provider-side "revision" pin if available. Even fields that currently do nothing, like seed, should be recorded so that a downstream change in provider behavior is visible in diffs.
Record the options you sent even if the runtime does not expose how it applies each option. A provider revision or configuration change is a separate fact.
PythonIn [7]Expand
@dataclass(frozen=True)
class ModelConfig:
name: str
revision: str # checkpoint / provider revision, not 'latest'
temperature: float
top_p: float
max_tokens: int
stop: tuple[str, ...]
seed: int | None # best-effort; never the sole reproducibility claim
def config_digest(self) -> str:
return digest(asdict(self))
model_a_cfg = ModelConfig(
name="mock-math-small",
revision="ckpt-2025-11-01",
temperature=0.7,
top_p=1.0,
max_tokens=256,
stop=("</solution>",),
seed=1272,
)
model_b_cfg = ModelConfig(
name="mock-math-large",
revision="ckpt-2025-11-01",
temperature=0.7,
top_p=1.0,
max_tokens=256,
stop=("</solution>",),
seed=1272,
)
model_a_digest = model_a_cfg.config_digest()
model_b_digest = model_b_cfg.config_digest()The mock systems share their decoding settings and a seed chosen to show a discordant task in the worked example. The controlled change is their fixture capability and model identity.
The Mock Model and Its Capability
The mock hashes the seed, task ID, temperature, and backend identity. It uses that value to choose a correct or a deliberately different response. Temperature lowers the synthetic success probability by 0.12 times temperature, clipped to the unit interval. The mock receives the rendered messages so the harness can archive them; this mock’s score does not depend on the prompt wording.
The keyed draw assigns the same value to a task when the seed, task ID, temperature and backend identity remain fixed. Reordering the tasks or running a subset leaves that value unchanged. A sequential pseudorandom stream can also simulate independent draws. The coverage experiments specify independence of sampled tasks directly.
PythonIn [8]Expand
@dataclass(frozen=True)
class MockModel:
cfg: ModelConfig
capability: float
def success_probability(self, temperature):
return max(0.0, min(1.0, self.capability - 0.12 * temperature))
def generate(
self, messages, item, temperature, backend_revision="mock-backend-1"
):
# Shared seeds and item IDs couple model outcomes for this fixture.
key = (self.cfg.seed, item["id"], temperature, backend_revision)
prefix = hashlib.sha256(canonical_bytes(key)).digest()[:8]
roll = (int.from_bytes(prefix, "big") >> 11) / 2**53
reference = item["answer"]
wrong = next(
x for x in ("-99999", "-99998") if numeric(x) != numeric(reference)
)
selected = (
reference if roll < self.success_probability(temperature) else wrong
)
return f"#### {selected}"
model_a = MockModel(cfg=model_a_cfg, capability=0.72)
model_b = MockModel(cfg=model_b_cfg, capability=0.80)The two specified mock capabilities are 0.72 and 0.80 at zero temperature. At temperature 0.7 the intended probabilities are 0.636 and 0.716. The mock uses the same draw for both models under equal settings, so their outcomes on one task can be correlated by construction.
The Grader as a Versioned Artifact
The fixture grader accepts one finite decimal number after #### on the last nonempty line. It flags an invalid reference independently of a malformed response, and compares parsed values as exact decimals.
PythonIn [9]Expand
NUMERIC_PATTERN = r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)"
def numeric(text):
text = text.strip()
if not re.fullmatch(NUMERIC_PATTERN, text):
return None
try:
return Decimal(text)
except InvalidOperation:
return None
@dataclass(frozen=True)
class RegexNumericGrader:
version: str
answer_marker: str = "####"
def policy(self):
return {
"version": self.version,
"marker": self.answer_marker,
"numeric_pattern": NUMERIC_PATTERN,
"scope": "last_nonempty_line",
}
def policy_digest(self):
return digest(self.policy())
def _extract(self, response):
lines = response.strip().splitlines()
if not lines or not lines[-1].startswith(self.answer_marker):
return None
candidate = lines[-1][len(self.answer_marker) :].strip()
return candidate if numeric(candidate) is not None else None
def grade(self, response, reference):
expected = numeric(reference)
if expected is None:
return 0.0, "bad_reference"
extracted = self._extract(response)
if extracted is None:
return 0.0, "unparseable_response"
return float(numeric(extracted) == expected), "graded"
grader = RegexNumericGrader(version="1.0.0")
grader_digest = grader.policy_digest()The grader returns a score and a status. A malformed response counts as incorrect under the fixture policy. An invalid reference is excluded from accuracy and reported as a dataset problem. A well-formed incorrect answer and a malformed answer remain distinguishable in the raw records.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!