From 857a1818d5d82e7c919d67ce9b8b39c9f40487d6 Mon Sep 17 00:00:00 2001 From: Torben Nehmer Date: Fri, 4 Dec 2026 22:56:45 +0100 Subject: [PATCH] Show reference counts per case and per set in the eval report Each reference check prints precision and recall with counts, missing and surplus entries; sum_matches adds the counts per label after the summary. Co-Authored-By: Claude Sonnet 5.5 --- src/chemenu/evals/runner.py | 67 +++++++++++++++++++++++++++- tests/evals/test_runner.py | 88 ++++++++++++++++++++++++++++++++++++- 2 files changed, 152 insertions(+), 3 deletions(-) diff --git a/src/chemenu/evals/runner.py b/src/chemenu/evals/runner.py index e86ab8b..4516eb9 100644 --- a/src/chemenu/evals/runner.py +++ b/src/chemenu/evals/runner.py @@ -1,7 +1,14 @@ """Run an eval set and format the report.""" from chemenu.evals.graders import score_case -from chemenu.evals.model import CaseResult, EvalSet, ResponseError, ResponseSource, SetResult +from chemenu.evals.model import ( + CaseResult, + EvalSet, + ResponseError, + ResponseSource, + SetMatch, + SetResult, +) def run_eval_set(eval_set: EvalSet, responses: ResponseSource) -> SetResult: @@ -26,8 +33,55 @@ def _reason(case: CaseResult) -> str: return " ".join(reason.split()) +def sum_matches(result: SetResult) -> tuple[tuple[str, SetMatch], ...]: + """Add the counts of reference checks per label, in order of first appearance.""" + totals: dict[str, SetMatch] = {} + for case in result.cases: + for check in case.checks: + match = check.match + if match is None: + continue + prev = totals.get(check.label) + if prev is not None: + match = SetMatch( + prev.matched + match.matched, + prev.actual + match.actual, + prev.expected + match.expected, + ) + else: + match = SetMatch(match.matched, match.actual, match.expected) + totals[check.label] = match + return tuple(totals.items()) + + +def _counted_cases(result: SetResult) -> dict[str, int]: + """Number of cases with counts per label; a case without counts makes a sum incomplete.""" + counted: dict[str, int] = {} + for case in result.cases: + for label in {c.label for c in case.checks if c.match is not None}: + counted[label] = counted.get(label, 0) + 1 + return counted + + +def _ratio(value: float | None) -> str: + return "n/a" if value is None else f"{value:.2f}" + + +def _match_line(label: str, match: SetMatch, *, details: bool) -> str: + line = ( + f" {label} precision {_ratio(match.precision)} ({match.matched}/{match.actual})" + f" recall {_ratio(match.recall)} ({match.matched}/{match.expected})" + ) + if details: + if match.missing: + line += f" missing: {list(match.missing)!r}" + if match.surplus: + line += f" surplus: {list(match.surplus)!r}" + return line + + def format_report(result: SetResult) -> str: - """One line per case, then a summary line.""" + """One line per case, then a summary line; reference counts indented below each.""" lines: list[str] = [] for case in result.cases: line = f"{'PASS' if case.passed else 'FAIL'} {case.case_id} {case.score:.2f}" @@ -35,9 +89,18 @@ def format_report(result: SetResult) -> str: if reason: line += f" {reason}" lines.append(line) + lines.extend( + _match_line(c.label, c.match, details=True) for c in case.checks if c.match is not None + ) passed = sum(case.passed for case in result.cases) lines.append( f"{result.name}: {passed}/{len(result.cases)} passed, " f"mean {result.mean_score:.2f}, threshold {result.threshold}" ) + counted = _counted_cases(result) + for label, total in sum_matches(result): + line = _match_line(label, total, details=False) + if counted[label] < len(result.cases): + line += f" counted in {counted[label]}/{len(result.cases)} cases" + lines.append(line) return "\n".join(lines) diff --git a/tests/evals/test_runner.py b/tests/evals/test_runner.py index b865d99..31a82a5 100644 --- a/tests/evals/test_runner.py +++ b/tests/evals/test_runner.py @@ -1,8 +1,9 @@ +import json from pathlib import Path from chemenu.evals.loader import load_eval_set from chemenu.evals.model import ResponseError -from chemenu.evals.runner import format_report, run_eval_set +from chemenu.evals.runner import format_report, run_eval_set, sum_matches EVAL_YAML = """\ name: "demo" @@ -76,3 +77,88 @@ def test_unreadable_response_fails_case(tmp_path: Path) -> None: assert not result.passed assert result.cases[0].error == "cannot read response: a.json: boom" assert result.cases[0].score == 0.0 + + +def _ref_case(items: str, extra: str = "") -> str: + return ( + 'input:\n text: "x"\nexpect:\n - grader: "reference"\n path: "/entities"\n' + f" items: {items}\n min_precision: 0\n min_recall: 0\n{extra}" + ) + + +def make_ref_set(root: Path, cases: dict[str, str]) -> Path: + (root / "cases").mkdir(parents=True) + (root / "eval.yaml").write_text(EVAL_YAML, encoding="utf-8") + for stem, text in cases.items(): + (root / "cases" / f"{stem}.yaml").write_text(text, encoding="utf-8") + return root + + +def _resp(*entities: str) -> str: + return json.dumps({"language": "de", "entities": list(entities)}) + + +def test_report_shows_reference_metrics(tmp_path: Path) -> None: + root = make_ref_set(tmp_path, {"a": _ref_case('["x", "y"]')}) + result = run_eval_set(load_eval_set(root), FakeResponses({"a": _resp("x", "z", "w")})) + lines = format_report(result).splitlines() + assert lines[0] == "PASS a 1.00" + assert lines[1] == ( + " reference /entities precision 0.33 (1/3) recall 0.50 (1/2)" + " missing: ['y'] surplus: ['z', 'w']" + ) + assert lines[2] == "demo: 1/1 passed, mean 1.00, threshold 0.8" + assert lines[3] == " reference /entities precision 0.33 (1/3) recall 0.50 (1/2)" + assert len(lines) == 4 + + +def test_report_sums_reference_per_set(tmp_path: Path) -> None: + second = _ref_case('["x"]') + ( + ' - grader: "reference"\n path: "/entities"\n where: {k: v}\n' + ' items: [{t: "x"}]\n min_precision: 0\n min_recall: 0\n' + ) + root = make_ref_set(tmp_path, {"a": _ref_case('["x", "y"]'), "b": second}) + responses = FakeResponses({"a": _resp("x", "y"), "b": _resp("x", "q")}) + result = run_eval_set(load_eval_set(root), responses) + lines = format_report(result).splitlines() + assert lines[-3] == "demo: 2/2 passed, mean 1.00, threshold 0.8" + assert lines[-2] == " reference /entities precision 0.75 (3/4) recall 1.00 (3/3)" + assert lines[-1] == ( + " reference /entities[k=v] precision n/a (0/0) recall 0.00 (0/1)" + " counted in 1/2 cases" + ) + assert [(label, m.matched) for label, m in sum_matches(result)] == [ + ("reference /entities", 3), + ("reference /entities[k=v]", 0), + ] + + +def test_report_shows_undefined_as_na(tmp_path: Path) -> None: + root = make_ref_set(tmp_path, {"a": _ref_case("[]")}) + result = run_eval_set(load_eval_set(root), FakeResponses({"a": _resp()})) + lines = format_report(result).splitlines() + expected = " reference /entities precision n/a (0/0) recall n/a (0/0)" + assert lines[1] == expected + assert lines[-1] == expected + + +def test_report_marks_incomplete_sum(tmp_path: Path) -> None: + root = make_ref_set(tmp_path, {"a": _ref_case('["x"]'), "b": _ref_case('["x"]')}) + result = run_eval_set(load_eval_set(root), FakeResponses({"a": _resp("x")})) + lines = format_report(result).splitlines() + assert lines[2] == "FAIL b 0.00 missing response" + assert lines[-1] == ( + " reference /entities precision 1.00 (1/1) recall 1.00 (1/1) counted in 1/2 cases" + ) + + +def test_report_not_a_list_has_no_counts(tmp_path: Path) -> None: + case = _ref_case('["x"]').replace('path: "/entities"', 'path: "/language"') + ( + ' - grader: "equals"\n path: "/language"\n value: "de"\n' + ) + root = make_ref_set(tmp_path, {"a": case}) + result = run_eval_set(load_eval_set(root), FakeResponses({"a": _resp("x")})) + assert format_report(result).splitlines() == [ + "FAIL a 0.50 reference /language: value is not a list: 'de'", + "demo: 0/1 passed, mean 0.50, threshold 0.8", + ]