Frozen Evaluation Set
Seal an evaluation set before you tune anything, check it shares no records with training data, and enforce a looks budget so a score still means something.
cd examples && pytest observability_and_evaluation/test_frozen_evaluation_set.pyWhat It Is
An evaluation set that is sealed once: the cases (ids, texts and labels), the decision thresholds and a fingerprint of all of them are recorded together. From then on, changing a threshold, relabelling, adding or removing a case, or scoring the set more often than agreed is an error. A leak check at freeze time refuses cases that also appear in the training data. The name is ours; the problem it addresses is the well-known reuse of test sets.
The Problem It Solves
A test set stops measuring generalisation as soon as it influences decisions. You look at the failures, fix the rules or the prompt to handle them, retune a threshold, and score again. The number goes up, and some of that gain is just fitting the test set. It gets worse quietly: fixes designed from the failing cases, labels reused as training data, thresholds nudged "just once". The research literature has measured this effect even on large public benchmarks (see below).
How It Works
flowchart TD
B["Build cases from independent sources"] --> L{"Any case matches
a training record?"}
L -->|"yes"| X["Refuse: leak"]
L -->|"no"| F["Freeze: fingerprint ids, texts,
labels and thresholds"]
F --> S["Score request"]
S --> C{"Fingerprint unchanged?"}
C -->|"no"| T["Refuse: tampered"]
C -->|"yes"| K{"Looks left in the
on-disk ledger?"}
K -->|"no"| N["Refuse: build a new set"]
K -->|"yes"| R["Score once, record it in the ledger"]
- Build the set to be independent. Different records, different entities, different sources from anything used for training or tuning. Prefer labels that don't depend on the system under test.
- Check for leaks mechanically. Normalise each case (lower-case, strip punctuation, collapse spaces) and refuse any that matches a training record. Do this at freeze time, not by eye.
- Freeze the decision rules first. Thresholds, prompts, post-processing: everything that turns a model output into a decision is recorded before scoring.
- Fingerprint cases, labels and thresholds together. Any later change breaks the seal, including quietly relabelling a case the model "got wrong".
- Budget the looks. The default is one. Each score is logged to a ledger on disk, keyed by the seal, so a restart or a new notebook doesn't reset the count. When the budget is spent, build a new set rather than reusing the old one.
- Report the number with its context. Say how the set was built and what it can't tell you.
- Retire a spent set. Keep it as a regression check, but don't quote its score as a fresh result.
When to Use It
- You make claims about quality that other people rely on: a model card, a release note, a launch decision.
- You iterate on rules, prompts or models against labelled data.
- More than one person tunes things, and "who looked at the test set" is already unclear.
When NOT to Use It
- Early exploration. While you are still learning what the task is, a frozen set is premature. Use a development set freely and freeze later.
- Tiny sets. With very few cases a single look has wide error bars; no sealing fixes that. Collect more first.
- Behaviour that changes with the data. If the world drifts, a frozen set slowly stops representing it. Pair it with monitoring (see Embedding Drift Detector).
Trade-offs
- Labelling cost. Every new frozen set means new labels. Budget for it, and reuse the labelling process rather than the labels.
- A look is a precious thing. You must decide in advance what is worth scoring. That is the point, and it is also a discipline some teams find slow.
- Sealing doesn't make labels right. If the labels came partly from a model, say so in the report.
Failure Modes
Leakage through derived data. The frozen cases are new, but the rules were designed from failures on an older set that shares records with them. Compare entities and sources, not only ids.
Thresholds chosen after peeking. The seal exists to make this visible. Without it, it happens by accident.
Result quoted as more than it is. A score on one set, one time, with a given label quality, is evidence, not a guarantee. Report the set size and how labels were produced.
Looks counted in memory. Teams forget how many times a set has been scored, and an in-memory counter forgets on every restart. Count in code, persist the count, and keep the ledger somewhere shared.
Implementation Example
A freeze function that checks for leaks and seals cases, labels and thresholds, a looks ledger kept on disk, and a scoring function that verifies the seal and the budget. The tests cover a leak hidden by different spelling, a threshold changed after freezing, a relabelled case, a removed case, scoring over budget, and a budget that survives a restart.
cd examples && pytest observability_and_evaluation/test_frozen_evaluation_set.py"""Frozen Evaluation Set.
A test set is only a test while nobody has tuned against it. Freeze it once:
record the cases (ids, texts and labels), the decision thresholds and a
fingerprint of all of them. Then score it with a looks budget kept on disk.
Relabelling a case or changing a threshold after the freeze, reusing a training
record, or looking more often than budgeted all fail loudly.
"""
from __future__ import annotations
import hashlib
import json
import re
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
def fingerprint(cases: dict[str, tuple[str, bool]], thresholds: dict[str, float]) -> str:
# Texts and labels are sealed too: quietly relabelling the cases the model
# got "wrong" is the most common way a test set gets tuned against.
blob = json.dumps(
{"cases": sorted([i, text, label] for i, (text, label) in cases.items()), "thresholds": thresholds},
sort_keys=True,
)
return hashlib.sha256(blob.encode()).hexdigest()[:16]
def key(text: str) -> str:
"""Normalised form used to spot the same record under different spellings."""
return " ".join(re.findall(r"[a-z0-9]+", text.lower()))
class Leak(Exception):
"""A frozen case shares a record with the training data."""
class TamperedAfterFreeze(Exception):
"""Cases or thresholds differ from what was frozen."""
class LooksBudgetSpent(Exception):
"""The frozen set has been scored as many times as was agreed."""
@dataclass
class Frozen:
cases: dict[str, tuple[str, bool]] # id -> (text, expected label)
thresholds: dict[str, float]
sealed: str
max_looks: int = 1
class LooksLedger:
"""Every scoring run, stored on disk and keyed by the seal.
An in-memory counter resets with every restart or new notebook, which is
exactly when people re-score. Keep this file somewhere shared and versioned.
"""
def __init__(self, path: str | Path):
self.path = Path(path)
def _load(self) -> dict[str, list[dict[str, float]]]:
return json.loads(self.path.read_text()) if self.path.exists() else {}
def history(self, seal: str) -> list[dict[str, float]]:
return self._load().get(seal, [])
def record(self, seal: str, result: dict[str, float]) -> None:
data = self._load()
data.setdefault(seal, []).append(result)
self.path.write_text(json.dumps(data, indent=2))
def freeze(cases: dict[str, tuple[str, bool]], thresholds: dict[str, float],
training_texts: list[str], max_looks: int = 1) -> Frozen:
seen = {key(t) for t in training_texts}
leaked = sorted(i for i, (text, _) in cases.items() if key(text) in seen)
if leaked:
raise Leak(f"{len(leaked)} frozen case(s) also appear in the training data: {leaked[:5]}")
return Frozen(dict(cases), dict(thresholds), fingerprint(cases, thresholds), max_looks)
def score(frozen: Frozen, predict: Callable[[str], float], ledger: LooksLedger) -> dict[str, float]:
if fingerprint(frozen.cases, frozen.thresholds) != frozen.sealed:
raise TamperedAfterFreeze("cases, labels or thresholds changed after the freeze")
looks = len(ledger.history(frozen.sealed))
if looks >= frozen.max_looks:
raise LooksBudgetSpent(f"already scored {looks} time(s); build a new set instead of re-using this one")
cut = frozen.thresholds["match"]
tp = fp = fn = tn = 0
for text, expected in frozen.cases.values():
said = predict(text) >= cut
tp += said and expected
fp += said and not expected
fn += (not said) and expected
tn += (not said) and not expected
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
result = {"precision": precision, "recall": recall, "f1": f1, "n": float(len(frozen.cases))}
ledger.record(frozen.sealed, result)
return resultTool Landscape
| Tool | Notes |
|---|---|
| DVC, lakeFS, Hugging Face Datasets revisions | Version the evaluation data so a fingerprint means something |
| MLflow, Weights & Biases | Log each scoring run with its parameters |
| Deduplication tools (MinHash, exact normalisation) | Detect overlap between evaluation and training data |
Related Patterns
- Shadow Model Evaluation tests a change on live traffic; this tests it on sealed labelled data.
- LLM-as-Judge can produce labels, which then need their own provenance note.
- Prompt Mutation Testing checks that tests detect prompt changes; this protects the tests themselves.
- Model Card is where a frozen-set result is reported with its caveats.
Further Reading
- Preserving Statistical Validity in Adaptive Data Analysis, Dwork et al., 2014
- Do ImageNet Classifiers Generalize to ImageNet?, Recht et al., 2019
Spotted something wrong or have a production story? Edit this page on GitHub.