Files
chemenu-ng/src/chemenu/evals/compare.py
T
torbenandClaude Sonnet 5.5 b0f04d7912 Add baseline comparison of eval sets
compare() scores recorded responses of a ref against the current cases and
classifies each case (regression, fixed, new, removed, not_comparable, ...).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-04 23:14:15 +01:00

183 lines
6.1 KiB
Python

"""Compare current responses against the recorded responses of a git ref."""
import json
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Final, Literal
from pydantic import ValidationError
from chemenu.evals.graders import score_case
from chemenu.evals.model import (
CaseResult,
EvalCase,
EvalSet,
ResponseError,
ResponseSource,
SetResult,
)
type CaseStatus = Literal[
"regression", "worse", "same", "better", "fixed", "new", "removed", "not_comparable"
]
COMPARABLE: Final = frozenset({"regression", "worse", "same", "better", "fixed"})
@dataclass(frozen=True)
class BaselineCase:
case_id: str
input_key: str | None # input_key(input); None: case file unreadable or input not JSON
response: str | None # raw recorded response; None: missing or unreadable
response_unreadable: bool = False # recorded response exists but cannot be read
@dataclass(frozen=True)
class Baseline:
ref: str # as given
commit: str # full sha
cases: Mapping[str, BaselineCase] | None # None: set unknown at ref
@dataclass(frozen=True)
class CaseComparison:
case_id: str
status: CaseStatus
before: float | None # None unless status in COMPARABLE
after: float | None # None for "removed"
response_changed: bool # raw text differs, or exists on one side only
note: str # reason for "new" or "not_comparable", else ""
@dataclass(frozen=True)
class SetComparison:
current: SetResult
baseline_ref: str
baseline_commit: str
set_is_new: bool
cases: tuple[CaseComparison, ...] # by case id
@property
def comparable(self) -> tuple[CaseComparison, ...]:
return tuple(c for c in self.cases if c.status in COMPARABLE)
@property
def mean_before(self) -> float | None:
scores = [c.before for c in self.comparable if c.before is not None]
return sum(scores) / len(scores) if scores else None
@property
def mean_after(self) -> float | None:
scores = [c.after for c in self.comparable if c.after is not None]
return sum(scores) / len(scores) if scores else None
@property
def delta(self) -> float | None:
before, after = self.mean_before, self.mean_after
if before is None or after is None:
return None
return after - before
@property
def regressions(self) -> tuple[CaseComparison, ...]:
return tuple(c for c in self.cases if c.status == "regression")
@property
def changed_responses(self) -> int:
"""Changed responses among the current cases; removed cases do not count."""
return sum(c.response_changed for c in self.cases if c.status != "removed")
def input_key(value: object) -> str | None:
"""Canonical JSON of a case input; ``None`` if it is not JSON-serialisable."""
try:
return json.dumps(value, sort_keys=True, ensure_ascii=False)
except TypeError, ValueError:
return None
def _current_response(responses: ResponseSource, case_id: str) -> tuple[bool, str | None]:
"""Return (readable, raw)."""
try:
return True, responses.response_for(case_id)
except ResponseError:
return False, None
def _status(before: CaseResult, after: CaseResult) -> CaseStatus:
if before.passed and not after.passed:
return "regression"
if after.passed and not before.passed:
return "fixed"
if after.score < before.score:
return "worse"
if after.score > before.score:
return "better"
return "same"
def _compare_case(
eval_set: EvalSet,
case: EvalCase,
after: CaseResult,
base: BaselineCase | None,
responses: ResponseSource,
) -> CaseComparison:
readable, raw = _current_response(responses, case.id)
def result(
status: CaseStatus, before: float | None, note: str, base_raw: str | None
) -> CaseComparison:
changed = (not readable) or raw != base_raw
return CaseComparison(case.id, status, before, after.score, changed, note)
if base is None:
return result("new", None, "case not in baseline", None)
if base.response_unreadable:
note = "baseline response unreadable"
return CaseComparison(case.id, "not_comparable", None, after.score, True, note)
if base.response is None:
return result("new", None, "no baseline response", None)
if base.input_key is None:
return result("not_comparable", None, "baseline case unreadable", base.response)
if input_key(case.input) != base.input_key:
return result("not_comparable", None, "input changed", base.response)
try:
eval_set.output_model.model_validate_json(base.response, strict=True)
except ValidationError as exc:
if any(error["type"] != "json_invalid" for error in exc.errors()):
return result(
"not_comparable",
None,
"baseline response violates current output model",
base.response,
)
before = score_case(case, base.response, eval_set.output_model, eval_set.threshold)
return result(_status(before, after), before.score, "", base.response)
def compare(
eval_set: EvalSet, current: SetResult, responses: ResponseSource, baseline: Baseline
) -> SetComparison:
"""Score the recorded responses of ``baseline`` against the current cases."""
after_by_id = {c.case_id: c for c in current.cases}
base_cases = baseline.cases
comparisons: list[CaseComparison] = []
for case in eval_set.cases:
base = None if base_cases is None else base_cases.get(case.id)
comparisons.append(_compare_case(eval_set, case, after_by_id[case.id], base, responses))
if base_cases is not None:
current_ids = {case.id for case in eval_set.cases}
comparisons.extend(
CaseComparison(case_id, "removed", None, None, True, "")
for case_id in base_cases
if case_id not in current_ids
)
comparisons.sort(key=lambda c: c.case_id)
return SetComparison(
current=current,
baseline_ref=baseline.ref,
baseline_commit=baseline.commit,
set_is_new=base_cases is None,
cases=tuple(comparisons),
)