Add reference grader with set comparison and text normalisation

Compares answer lists against a reference as sets with precision and recall minimums; text is casefolded, NFC and whitespace normalised.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
torbenandClaude Sonnet 5.5 committed 2026-12-04 23:02:45 +01:00
1 parent a124734966
commit 9a7dc6ceb3
5 files changed
+369 -4

No files matched your search

+100 -1
View File
@@ -1,5 +1,8 @@
"""Hard graders: pure functions over JSON values."""
import json
from typing import TypeIs, cast
from pydantic import BaseModel, JsonValue, ValidationError
from chemenu.evals.model import (
@@ -9,7 +12,10 @@ from chemenu.evals.model import (
ContainsCheck,
EqualsCheck,
EvalCase,
ReferenceCheck,
SetMatch,
)
from chemenu.evals.normalize import Scalar, scalar_key
class PointerError(LookupError):
@@ -56,7 +62,7 @@ def _json_equal(a: JsonValue, b: JsonValue) -> bool:
def grade(check: Check, output: JsonValue) -> CheckResult:
"""Run one check against the output."""
label = f"{check.grader} {check.path}"
label = _label(check)
try:
actual = resolve_pointer(output, check.path)
except PointerError as exc:
@@ -73,6 +79,99 @@ def grade(check: Check, output: JsonValue) -> CheckResult:
if missing:
return CheckResult(label, False, f"missing: {missing!r}")
return CheckResult(label, True, "")
case ReferenceCheck():
if not isinstance(actual, list):
return CheckResult(label, False, f"value is not a list: {actual!r}")
return _grade_reference(check, label, actual)
def _label(check: Check) -> str:
label = f"{check.grader} {check.path}"
if isinstance(check, ReferenceCheck) and check.where:
parts = (
f"{k}={v if isinstance(v, str) else json.dumps(v)}" for k, v in check.where.items()
)
label += f"[{','.join(parts)}]"
return label
def _is_scalar(value: JsonValue) -> TypeIs[Scalar]:
return not isinstance(value, dict | list)
def _key_of(value: JsonValue) -> tuple[object, ...] | None:
"""Comparison key of a scalar; ``None`` for lists and objects."""
return scalar_key(value) if _is_scalar(value) else None
def _entry_key(entry: JsonValue, fields: tuple[str, ...] | None) -> tuple[object, ...] | None:
"""Key of an answer entry, or ``None`` if its form does not fit the reference."""
if fields is None:
return _key_of(entry)
if not isinstance(entry, dict) or any(f not in entry for f in fields):
return None
keys = tuple(_key_of(entry[f]) for f in fields)
return None if None in keys else keys
def _grade_reference(check: ReferenceCheck, label: str, actual: list[JsonValue]) -> CheckResult:
where = check.where
entries = [
e
for e in actual
if not where
or (
isinstance(e, dict)
and all(k in e and _key_of(e[k]) == scalar_key(v) for k, v in where.items())
)
]
first = check.items[0] if check.items else None
fields = tuple(sorted(first)) if isinstance(first, dict) else None
def ref_key(item: Scalar | dict[str, Scalar]) -> tuple[object, ...]:
if isinstance(item, dict):
return tuple(scalar_key(item[f]) for f in sorted(item))
return scalar_key(item)
answers: dict[tuple[object, ...], JsonValue] = {}
for entry in entries:
key = _entry_key(entry, fields)
if key is None:
key = ("raw", json.dumps(entry, sort_keys=True, ensure_ascii=False))
shown = entry
if fields is not None and isinstance(entry, dict):
present: JsonValue = {f: entry[f] for f in fields if f in entry}
shown = present or entry
elif fields is not None and isinstance(entry, dict):
shown = {f: entry[f] for f in fields}
else:
shown = entry
answers.setdefault(key, shown)
ref_keys = [ref_key(i) for i in check.items]
missing: tuple[JsonValue, ...] = tuple(
cast("JsonValue", i) for i, k in zip(check.items, ref_keys, strict=True) if k not in answers
)
reference = set(ref_keys)
surplus = tuple(v for k, v in answers.items() if k not in reference)
match = SetMatch(
matched=len(ref_keys) - len(missing),
actual=len(answers),
expected=len(check.items),
missing=missing,
surplus=surplus,
)
problems: list[str] = []
precision, recall = match.precision, match.recall
if precision is not None and precision < check.min_precision:
problems.append(
f"precision {precision:.3f} ({match.matched}/{match.actual}) < {check.min_precision:g}"
)
if recall is not None and recall < check.min_recall:
problems.append(
f"recall {recall:.3f} ({match.matched}/{match.expected}) < {check.min_recall:g}"
)
return CheckResult(label, not problems, "; ".join(problems), match)
def describe_validation_error(exc: ValidationError) -> str:
+59 -2
View File
@@ -1,9 +1,12 @@
"""Types of the eval harness."""
import math
from dataclasses import dataclass
from typing import Annotated, Literal, Protocol
from pydantic import BaseModel, ConfigDict, Field, JsonValue
from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator
from chemenu.evals.normalize import Scalar, scalar_key
class _Spec(BaseModel):
@@ -22,7 +25,43 @@ class ContainsCheck(_Spec):
items: list[JsonValue]
Check = Annotated[EqualsCheck | ContainsCheck, Field(discriminator="grader")]
class ReferenceCheck(_Spec):
grader: Literal["reference"]
path: str # JSON Pointer to a list
where: dict[str, Scalar] = Field(default_factory=dict)
items: list[Scalar] | list[dict[str, Scalar]] # mixed forms fail validation
min_precision: float = Field(ge=0, le=1)
min_recall: float = Field(ge=0, le=1)
@model_validator(mode="after")
def _check_items(self) -> ReferenceCheck:
values = [*self.where.values()]
for item in self.items:
values.extend(item.values() if isinstance(item, dict) else [item])
if any(isinstance(v, float) and not math.isfinite(v) for v in values):
raise ValueError("reference values must be finite numbers")
if self.where and any(not isinstance(item, dict) for item in self.items):
raise ValueError("'where' keeps only objects; reference items must be objects")
keys: set[tuple[object, ...]] = set()
fields: tuple[str, ...] | None = None
for item in self.items:
if isinstance(item, dict):
if not item:
raise ValueError("reference objects must have at least one field")
names = tuple(sorted(item))
if fields is not None and names != fields:
raise ValueError("reference objects must all have the same fields")
fields = names
key: tuple[object, ...] = tuple(scalar_key(item[n]) for n in names)
else:
key = scalar_key(item)
if key in keys:
raise ValueError(f"duplicate reference item after normalisation: {item!r}")
keys.add(key)
return self
Check = Annotated[EqualsCheck | ContainsCheck | ReferenceCheck, Field(discriminator="grader")]
class EvalCase(_Spec):
@@ -45,11 +84,29 @@ class EvalSet:
cases: tuple[EvalCase, ...] # sorted by id, never empty
@dataclass(frozen=True)
class SetMatch:
matched: int
actual: int # distinct answer entries after `where`
expected: int # reference entries
missing: tuple[JsonValue, ...] = () # reference items, as written
surplus: tuple[JsonValue, ...] = () # answer entries, reduced to compared fields
@property
def precision(self) -> float | None:
return self.matched / self.actual if self.actual else None
@property
def recall(self) -> float | None:
return self.matched / self.expected if self.expected else None
@dataclass(frozen=True)
class CheckResult:
label: str # e.g. "contains /entities"
passed: bool
detail: str
match: SetMatch | None = None
@dataclass(frozen=True)
+22
View File
@@ -0,0 +1,22 @@
"""Normalisation of scalar values for set comparison."""
import unicodedata
type Scalar = str | int | float | bool | None
def normalize_text(text: str) -> str:
"""Casefold, unify to NFC and collapse whitespace; NFKC is deliberately not used."""
folded = unicodedata.normalize("NFD", text).casefold()
return " ".join(unicodedata.normalize("NFC", folded).split())
def scalar_key(value: Scalar) -> tuple[object, ...]:
"""Comparison key: text is normalised, numbers are exact, bool only equals bool."""
if isinstance(value, str):
return ("str", normalize_text(value))
if isinstance(value, bool):
return ("bool", value)
if isinstance(value, int | float):
return ("num", value)
return ("null",)