Bewerter gegen Referenz #48

Merged
torben merged 4 commits from 24-reference-grader into main 2026-12-04 22:10:46 +00:00
2 changed files with 152 additions and 3 deletions
Showing only changes of commit 857a1818d5 - Show all commits

No files matched your search

+65 -2
View File
@@ -1,7 +1,14 @@
"""Run an eval set and format the report.""" """Run an eval set and format the report."""
from chemenu.evals.graders import score_case 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: def run_eval_set(eval_set: EvalSet, responses: ResponseSource) -> SetResult:
@@ -26,8 +33,55 @@ def _reason(case: CaseResult) -> str:
return " ".join(reason.split()) 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: 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] = [] lines: list[str] = []
for case in result.cases: for case in result.cases:
line = f"{'PASS' if case.passed else 'FAIL'} {case.case_id} {case.score:.2f}" 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: if reason:
line += f" {reason}" line += f" {reason}"
lines.append(line) 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) passed = sum(case.passed for case in result.cases)
lines.append( lines.append(
f"{result.name}: {passed}/{len(result.cases)} passed, " f"{result.name}: {passed}/{len(result.cases)} passed, "
f"mean {result.mean_score:.2f}, threshold {result.threshold}" 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) return "\n".join(lines)
+87 -1
View File
@@ -1,8 +1,9 @@
import json
from pathlib import Path from pathlib import Path
from chemenu.evals.loader import load_eval_set from chemenu.evals.loader import load_eval_set
from chemenu.evals.model import ResponseError 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 = """\ EVAL_YAML = """\
name: "demo" name: "demo"
@@ -76,3 +77,88 @@ def test_unreadable_response_fails_case(tmp_path: Path) -> None:
assert not result.passed assert not result.passed
assert result.cases[0].error == "cannot read response: a.json: boom" assert result.cases[0].error == "cannot read response: a.json: boom"
assert result.cases[0].score == 0.0 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",
]