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:
1 parent
a124734966
commit
9a7dc6ceb3
5 files changed
+369
-4
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",)
|
||||
+151
-1
@@ -5,7 +5,7 @@ from pydantic import BaseModel, ConfigDict, Field, JsonValue
|
||||
|
||||
from chemenu.evals.example import ExampleOutput
|
||||
from chemenu.evals.graders import PointerError, grade, resolve_pointer, score_case
|
||||
from chemenu.evals.model import ContainsCheck, EqualsCheck, EvalCase
|
||||
from chemenu.evals.model import ContainsCheck, EqualsCheck, EvalCase, ReferenceCheck, Scalar
|
||||
|
||||
GOOD = '{"language": "de", "entities": ["a", "b"]}'
|
||||
|
||||
@@ -108,3 +108,153 @@ def test_pointer_uses_field_alias() -> None:
|
||||
result = score_case(case, '{"entityList": ["a"]}', _Aliased, 1.0)
|
||||
assert result.error is None
|
||||
assert result.passed
|
||||
|
||||
|
||||
def _ref(
|
||||
items: list[Scalar] | list[dict[str, Scalar]],
|
||||
*,
|
||||
where: dict[str, Scalar] | None = None,
|
||||
min_precision: float = 0.0,
|
||||
min_recall: float = 0.0,
|
||||
path: str = "/e",
|
||||
) -> ReferenceCheck:
|
||||
return ReferenceCheck(
|
||||
grader="reference",
|
||||
path=path,
|
||||
where=where or {},
|
||||
items=items,
|
||||
min_precision=min_precision,
|
||||
min_recall=min_recall,
|
||||
)
|
||||
|
||||
|
||||
def _matched(check: ReferenceCheck, out: JsonValue) -> int:
|
||||
match = grade(check, out).match
|
||||
assert match is not None
|
||||
return match.matched
|
||||
|
||||
|
||||
def test_reference_counts_precision_and_recall() -> None:
|
||||
out: JsonValue = {"e": ["a", "b", "x", "y"]}
|
||||
result = grade(_ref(["a", "b", "c"], min_precision=0.5, min_recall=0.6), out)
|
||||
assert result.label == "reference /e"
|
||||
assert result.match is not None
|
||||
assert (result.match.matched, result.match.actual, result.match.expected) == (2, 4, 3)
|
||||
assert result.match.precision == 0.5
|
||||
assert result.match.recall == pytest.approx(2 / 3)
|
||||
assert result.match.missing == ("c",)
|
||||
assert result.match.surplus == ("x", "y")
|
||||
assert result.passed
|
||||
assert result.detail == ""
|
||||
failed = grade(_ref(["a", "b", "c"], min_precision=0.6, min_recall=0.7), out)
|
||||
assert not failed.passed
|
||||
assert failed.detail == "precision 0.500 (2/4) < 0.6; recall 0.667 (2/3) < 0.7"
|
||||
|
||||
|
||||
def test_reference_compares_named_fields_only() -> None:
|
||||
out: JsonValue = {
|
||||
"e": [
|
||||
{"name": "A", "kind": "x", "extra": 1},
|
||||
{"name": "B", "kind": "y", "extra": 2},
|
||||
{"name": "C"},
|
||||
"plain",
|
||||
{"name": "D", "kind": [1]},
|
||||
]
|
||||
}
|
||||
result = grade(_ref([{"name": "a", "kind": "X"}, {"name": "Z", "kind": "x"}]), out)
|
||||
assert result.match is not None
|
||||
assert result.match.matched == 1
|
||||
assert result.match.actual == 5
|
||||
assert result.match.missing == ({"name": "Z", "kind": "x"},)
|
||||
assert result.match.surplus == (
|
||||
{"name": "B", "kind": "y"},
|
||||
{"name": "C"},
|
||||
"plain",
|
||||
{"name": "D", "kind": [1]},
|
||||
)
|
||||
|
||||
|
||||
def test_reference_where_filters_entries() -> None:
|
||||
out: JsonValue = {
|
||||
"e": [
|
||||
{"kind": "entity", "name": "a"},
|
||||
{"kind": "other", "name": "b"},
|
||||
"scalar",
|
||||
{"name": "c"},
|
||||
]
|
||||
}
|
||||
result = grade(_ref([{"name": "a"}], where={"kind": "ENTITY"}), out)
|
||||
assert result.label == "reference /e[kind=ENTITY]"
|
||||
assert result.match is not None
|
||||
assert (result.match.matched, result.match.actual) == (1, 1)
|
||||
two = grade(_ref([{"name": "a"}], where={"kind": "entity", "n": 1}), out)
|
||||
assert two.label == "reference /e[kind=entity,n=1]"
|
||||
|
||||
|
||||
def test_reference_normalizes_text() -> None:
|
||||
out: JsonValue = {"e": ["STRASSE", "e\u0301", "a\u00a0 b", " c "]}
|
||||
result = grade(_ref(["Stra\u00dfe", "\u00c9", "a b", "C"], min_precision=1, min_recall=1), out)
|
||||
assert result.passed
|
||||
assert _matched(_ref(["x2"]), {"e": ["x\u00b2"]}) == 0
|
||||
|
||||
|
||||
def test_reference_numbers_and_bools_exact() -> None:
|
||||
assert _matched(_ref([1]), {"e": [1.0]}) == 1
|
||||
assert _matched(_ref([1]), {"e": [True]}) == 0
|
||||
assert _matched(_ref([True]), {"e": [1]}) == 0
|
||||
assert _matched(_ref([True]), {"e": [True]}) == 1
|
||||
assert _matched(_ref([1.5]), {"e": [1.5000001]}) == 0
|
||||
assert _matched(_ref([None]), {"e": [None]}) == 1
|
||||
assert _matched(_ref([None]), {"e": ["", 0, False]}) == 0
|
||||
|
||||
|
||||
def test_reference_duplicates_collapse() -> None:
|
||||
result = grade(_ref(["a", "b"]), {"e": ["a", "A", "a", "x", "x"]})
|
||||
assert result.match is not None
|
||||
assert (result.match.matched, result.match.actual) == (1, 2)
|
||||
assert result.match.surplus == ("x",)
|
||||
|
||||
|
||||
def test_reference_empty_is_undefined() -> None:
|
||||
both = grade(_ref([], min_precision=1, min_recall=1), {"e": []})
|
||||
assert both.passed
|
||||
assert both.match is not None
|
||||
assert both.match.precision is None
|
||||
assert both.match.recall is None
|
||||
no_answer = grade(_ref(["a"], min_precision=1, min_recall=0.5), {"e": []})
|
||||
assert not no_answer.passed
|
||||
assert no_answer.match is not None
|
||||
assert no_answer.match.precision is None
|
||||
assert no_answer.match.recall == 0.0
|
||||
assert no_answer.detail == "recall 0.000 (0/1) < 0.5"
|
||||
no_ref = grade(_ref([], min_precision=0.5, min_recall=1), {"e": ["a"]})
|
||||
assert not no_ref.passed
|
||||
assert no_ref.match is not None
|
||||
assert no_ref.match.recall is None
|
||||
assert no_ref.detail == "precision 0.000 (0/1) < 0.5"
|
||||
|
||||
|
||||
def test_reference_minimums_decide() -> None:
|
||||
out: JsonValue = {"e": ["a", "x"]}
|
||||
assert grade(_ref(["a", "b"], min_precision=0.5, min_recall=0.5), out).passed
|
||||
assert not grade(_ref(["a", "b"], min_precision=0.51, min_recall=0.5), out).passed
|
||||
assert not grade(_ref(["a", "b"], min_precision=0.5, min_recall=0.51), out).passed
|
||||
|
||||
|
||||
def test_reference_not_a_list_fails_check() -> None:
|
||||
result = grade(_ref(["a"]), {"e": "a"})
|
||||
assert not result.passed
|
||||
assert result.detail == "value is not a list: 'a'"
|
||||
assert result.match is None
|
||||
|
||||
|
||||
def test_reference_unfit_surplus_is_reduced() -> None:
|
||||
out: JsonValue = {"e": [{"name": ["A"], "kind": "x", "note": "long"}, {"note": "only"}]}
|
||||
result = grade(_ref([{"name": "a", "kind": "x"}]), out)
|
||||
assert result.match is not None
|
||||
assert result.match.surplus == ({"name": ["A"], "kind": "x"}, {"note": "only"})
|
||||
|
||||
|
||||
def test_reference_detail_shows_counts() -> None:
|
||||
result = grade(_ref(["a", "b", "c"], min_recall=0.667), {"e": ["a", "b"]})
|
||||
assert result.detail == "recall 0.667 (2/3) < 0.667"
|
||||
@@ -143,3 +143,40 @@ def test_unquoted_no_stays_string(tmp_path: Path) -> None:
|
||||
first = eval_set.cases[0].expect[0]
|
||||
assert isinstance(first, EqualsCheck)
|
||||
assert first.value is True
|
||||
|
||||
|
||||
_REF_HEAD = (
|
||||
'input: {}\nexpect:\n - grader: "reference"\n path: "/e"\n'
|
||||
" min_precision: 0.5\n min_recall: 0.5\n"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
' items: ["a", {n: "b"}]\n',
|
||||
' items: [{a: "x"}, {b: "y"}]\n',
|
||||
' items: ["a", " A"]\n',
|
||||
' items: [{a: "x"}, {a: "X "}]\n',
|
||||
" items: [{}]\n",
|
||||
' items: [["a"]]\n',
|
||||
' items: [{a: ["x"]}]\n',
|
||||
' where: {kind: "e"}\n items: ["a"]\n',
|
||||
" items: [.nan]\n",
|
||||
' where: {n: .inf}\n items: [{a: "x"}]\n',
|
||||
"min_recall",
|
||||
"min_precision",
|
||||
],
|
||||
)
|
||||
def test_invalid_reference_raises(tmp_path: Path, body: str) -> None:
|
||||
if body.startswith("min_"): # minimum missing
|
||||
text = _REF_HEAD.replace(f" {body}: 0.5\n", "") + ' items: ["a"]\n'
|
||||
else:
|
||||
text = _REF_HEAD + body
|
||||
with pytest.raises(EvalSetError, match=r"bad\.yaml"):
|
||||
load_eval_set(make_set(tmp_path, cases={"bad": text}))
|
||||
|
||||
|
||||
def test_valid_reference_loads(tmp_path: Path) -> None:
|
||||
text = _REF_HEAD + ' where: {kind: "e"}\n items: [{a: "x"}, {a: "y"}]\n'
|
||||
assert load_eval_set(make_set(tmp_path, cases={"ok": text})).cases[0].expect
|
||||
Reference in new issue
Block a user