Baseline-Arm und Veränderung je Satz #49
No files matched your search
@@ -5,24 +5,47 @@ import sys
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from chemenu.evals.baseline import BaselineError, load_baseline
|
||||||
|
from chemenu.evals.compare import compare, format_comparison, format_comparison_markdown
|
||||||
from chemenu.evals.loader import EvalSetError, RecordedResponses, load_eval_set
|
from chemenu.evals.loader import EvalSetError, RecordedResponses, load_eval_set
|
||||||
from chemenu.evals.runner import format_report, run_eval_set
|
from chemenu.evals.runner import format_report, run_eval_set
|
||||||
|
|
||||||
|
|
||||||
def main(argv: Sequence[str] | None = None) -> int:
|
def main(argv: Sequence[str] | None = None) -> int:
|
||||||
"""Exit code: 0 passed, 1 not passed, 2 set cannot be loaded or call is wrong."""
|
"""Exit code: 0 passed, 1 not passed, 2 set or baseline cannot be loaded or call is wrong.
|
||||||
|
|
||||||
|
With ``--baseline`` the exit code still depends on the current responses only.
|
||||||
|
"""
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
prog="chemenu-eval",
|
prog="chemenu-eval",
|
||||||
description="Score an eval set against its recorded responses.",
|
description="Score an eval set against its recorded responses.",
|
||||||
)
|
)
|
||||||
parser.add_argument("eval_set", help="directory of the eval set")
|
parser.add_argument("eval_set", help="directory of the eval set")
|
||||||
|
parser.add_argument(
|
||||||
|
"--baseline", metavar="REF", help="git ref to compare recorded responses to"
|
||||||
|
)
|
||||||
|
parser.add_argument("--format", choices=["text", "markdown"], default="text")
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
|
if args.format == "markdown" and args.baseline is None:
|
||||||
|
parser.error("--format markdown requires --baseline")
|
||||||
directory = Path(args.eval_set)
|
directory = Path(args.eval_set)
|
||||||
try:
|
try:
|
||||||
eval_set = load_eval_set(directory)
|
eval_set = load_eval_set(directory)
|
||||||
except EvalSetError as exc:
|
responses = RecordedResponses(directory / "recorded")
|
||||||
|
result = run_eval_set(eval_set, responses)
|
||||||
|
comparison = None
|
||||||
|
if args.baseline is not None:
|
||||||
|
baseline = load_baseline(directory, args.baseline)
|
||||||
|
comparison = compare(eval_set, result, responses, baseline)
|
||||||
|
except (EvalSetError, BaselineError) as exc:
|
||||||
print(f"chemenu-eval: {exc}", file=sys.stderr)
|
print(f"chemenu-eval: {exc}", file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
result = run_eval_set(eval_set, RecordedResponses(directory / "recorded"))
|
if comparison is None:
|
||||||
print(format_report(result))
|
print(format_report(result))
|
||||||
|
elif args.format == "markdown":
|
||||||
|
print(format_comparison_markdown(comparison))
|
||||||
|
else:
|
||||||
|
print(format_report(result))
|
||||||
|
print()
|
||||||
|
print(format_comparison(comparison))
|
||||||
return 0 if result.passed else 1
|
return 0 if result.passed else 1
|
||||||
@@ -180,3 +180,73 @@ def compare(
|
|||||||
set_is_new=base_cases is None,
|
set_is_new=base_cases is None,
|
||||||
cases=tuple(comparisons),
|
cases=tuple(comparisons),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
NO_CHANGE_NOTE: Final = "no changed responses: the difference says nothing about the prompt"
|
||||||
|
_MARKDOWN_SPECIAL: Final = "\\|`*_[]<>#~"
|
||||||
|
|
||||||
|
|
||||||
|
def _points(value: float | None) -> str:
|
||||||
|
return "-" if value is None else f"{value:.2f}"
|
||||||
|
|
||||||
|
|
||||||
|
def _header_parts(c: SetComparison, arrow: str) -> list[str]:
|
||||||
|
total = len(c.current.cases)
|
||||||
|
passed = sum(case.passed for case in c.current.cases)
|
||||||
|
parts = [
|
||||||
|
f"baseline {c.baseline_ref} ({c.baseline_commit[:7]})",
|
||||||
|
f"{passed}/{total} passed at threshold {c.current.threshold}",
|
||||||
|
]
|
||||||
|
if c.set_is_new:
|
||||||
|
parts.append("new set, not in baseline")
|
||||||
|
elif c.delta is None:
|
||||||
|
parts.append("no comparable cases")
|
||||||
|
else:
|
||||||
|
parts.append(
|
||||||
|
f"mean {_points(c.mean_before)} {arrow} {_points(c.mean_after)} ({c.delta:+.2f}) "
|
||||||
|
f"over {len(c.comparable)} comparable of {total} cases"
|
||||||
|
)
|
||||||
|
count = len(c.regressions)
|
||||||
|
parts.append(f"{count} regression{'' if count == 1 else 's'}")
|
||||||
|
parts.append(f"{c.changed_responses} of {total} responses changed")
|
||||||
|
return parts
|
||||||
|
|
||||||
|
|
||||||
|
def _ordered(c: SetComparison) -> list[CaseComparison]:
|
||||||
|
return sorted(c.cases, key=lambda x: (x.status != "regression", x.case_id))
|
||||||
|
|
||||||
|
|
||||||
|
def format_comparison(c: SetComparison) -> str:
|
||||||
|
"""Plain-text comparison: header, optional note, one line per case."""
|
||||||
|
lines = [f"{c.current.name}: " + "; ".join(_header_parts(c, "->"))]
|
||||||
|
if c.changed_responses == 0:
|
||||||
|
lines.append(NO_CHANGE_NOTE)
|
||||||
|
for case in _ordered(c):
|
||||||
|
points = f"{_points(case.before)} -> {_points(case.after)}"
|
||||||
|
line = f"{case.status.upper()} {case.case_id} {points}"
|
||||||
|
if case.note:
|
||||||
|
line += f" {case.note}"
|
||||||
|
lines.append(line)
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def _escape(text: str) -> str:
|
||||||
|
"""Escape inline Markdown and keep the text on one line."""
|
||||||
|
flat = " ".join(text.split())
|
||||||
|
return "".join(f"\\{ch}" if ch in _MARKDOWN_SPECIAL else ch for ch in flat)
|
||||||
|
|
||||||
|
|
||||||
|
def format_comparison_markdown(c: SetComparison) -> str:
|
||||||
|
"""Markdown comparison: heading, header paragraph, table; no notes."""
|
||||||
|
header = _escape("; ".join(_header_parts(c, "→")))
|
||||||
|
lines = [f"### {_escape(c.current.name)}", "", header]
|
||||||
|
if c.changed_responses == 0:
|
||||||
|
lines.append("")
|
||||||
|
lines.append(NO_CHANGE_NOTE)
|
||||||
|
lines += ["", "| Case | Status | Before | After |", "| --- | --- | ---: | ---: |"]
|
||||||
|
for case in _ordered(c):
|
||||||
|
lines.append(
|
||||||
|
f"| {_escape(case.case_id)} | {case.status} | "
|
||||||
|
f"{_points(case.before)} | {_points(case.after)} |"
|
||||||
|
)
|
||||||
|
return "\n".join(lines)
|
||||||
@@ -1,9 +1,13 @@
|
|||||||
|
from dataclasses import replace
|
||||||
|
|
||||||
from chemenu.evals.compare import (
|
from chemenu.evals.compare import (
|
||||||
Baseline,
|
Baseline,
|
||||||
BaselineCase,
|
BaselineCase,
|
||||||
CaseComparison,
|
CaseComparison,
|
||||||
SetComparison,
|
SetComparison,
|
||||||
compare,
|
compare,
|
||||||
|
format_comparison,
|
||||||
|
format_comparison_markdown,
|
||||||
input_key,
|
input_key,
|
||||||
)
|
)
|
||||||
from chemenu.evals.example import ExampleOutput
|
from chemenu.evals.example import ExampleOutput
|
||||||
@@ -198,3 +202,46 @@ def test_input_key_distinguishes_bool_and_int() -> None:
|
|||||||
assert input_key({"b": 1, "a": 2}) == input_key({"a": 2, "b": 1})
|
assert input_key({"b": 1, "a": 2}) == input_key({"a": 2, "b": 1})
|
||||||
assert input_key({"a": "ä"}) == '{"a": "ä"}'
|
assert input_key({"a": "ä"}) == '{"a": "ä"}'
|
||||||
assert input_key({"a": object()}) is None
|
assert input_key({"a": object()}) is None
|
||||||
|
|
||||||
|
|
||||||
|
def table_rows(markdown: str) -> list[str]:
|
||||||
|
return [line for line in markdown.splitlines() if line.startswith("| ")][2:]
|
||||||
|
|
||||||
|
|
||||||
|
def test_markdown_lists_regressions_first() -> None:
|
||||||
|
old = baseline(bcase("a", GOOD), bcase("z", GOOD))
|
||||||
|
result = run(["a", "z"], {"a": GOOD, "z": BAD}, old)
|
||||||
|
rows = table_rows(format_comparison_markdown(result))
|
||||||
|
assert [r.split(" | ")[0] for r in rows] == ["| z", "| a"]
|
||||||
|
assert "regression" in rows[0]
|
||||||
|
text_lines = format_comparison(result).splitlines()
|
||||||
|
ordered = [ln.split(" ")[:2] for ln in text_lines if ln.startswith(("REGRESSION", "SAME"))]
|
||||||
|
assert ordered == [["REGRESSION", "z"], ["SAME", "a"]]
|
||||||
|
assert all(ln == ln.rstrip() for ln in text_lines)
|
||||||
|
|
||||||
|
|
||||||
|
def test_markdown_escapes_case_ids() -> None:
|
||||||
|
case_id = "a|b_c*d"
|
||||||
|
result = run([case_id], {case_id: GOOD}, baseline(bcase(case_id, GOOD)))
|
||||||
|
markdown = format_comparison_markdown(result)
|
||||||
|
rows = table_rows(markdown)
|
||||||
|
assert len(rows) == 1
|
||||||
|
assert "a\\|b\\_c\\*d" in rows[0]
|
||||||
|
header_rows = [ln for ln in markdown.splitlines() if ln.startswith(("| Case", "| ---"))]
|
||||||
|
for row in [*rows, *header_rows]:
|
||||||
|
assert row.replace("\\|", "").count("|") == 5
|
||||||
|
renamed = SetComparison(
|
||||||
|
replace(result.current, name="extract ~v2~\nnext"), "main", "abc", False, result.cases
|
||||||
|
)
|
||||||
|
heading = format_comparison_markdown(renamed).splitlines()[0]
|
||||||
|
assert heading == "### extract \\~v2\\~ next"
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_notes_no_changed_responses() -> None:
|
||||||
|
note = "no changed responses: the difference says nothing about the prompt"
|
||||||
|
same = run(["a"], {"a": GOOD}, baseline(bcase("a", GOOD)))
|
||||||
|
changed = run(["a"], {"a": GOOD}, baseline(bcase("a", GOOD_SPACED)))
|
||||||
|
assert note in format_comparison(same)
|
||||||
|
assert note in format_comparison_markdown(same)
|
||||||
|
assert note not in format_comparison(changed)
|
||||||
|
assert note not in format_comparison_markdown(changed)
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -96,3 +97,71 @@ def test_exit_2_on_empty_set(tmp_path: Path, capsys: pytest.CaptureFixture[str])
|
|||||||
case.unlink()
|
case.unlink()
|
||||||
assert main([str(tmp_path)]) == 2
|
assert main([str(tmp_path)]) == 2
|
||||||
assert "no cases found" in capsys.readouterr().err
|
assert "no cases found" in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
GIT = [
|
||||||
|
"git",
|
||||||
|
"-c",
|
||||||
|
"user.name=t",
|
||||||
|
"-c",
|
||||||
|
"user.email=t@example.invalid",
|
||||||
|
"-c",
|
||||||
|
"commit.gpgsign=false",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def git(repo: Path, *args: str) -> None:
|
||||||
|
subprocess.run([*GIT, "-C", str(repo), *args], capture_output=True, check=True) # noqa: S603
|
||||||
|
|
||||||
|
|
||||||
|
def commit_all(repo: Path) -> None:
|
||||||
|
git(repo, "add", "-A")
|
||||||
|
git(repo, "commit", "-q", "-m", "x")
|
||||||
|
|
||||||
|
|
||||||
|
def record(set_dir: Path, a: str, b: str) -> None:
|
||||||
|
(set_dir / "recorded" / "a.json").write_text(a, encoding="utf-8")
|
||||||
|
(set_dir / "recorded" / "b.json").write_text(b, encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def test_baseline_exit_code_follows_current_arm(
|
||||||
|
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
git(tmp_path, "init", "-q")
|
||||||
|
set_dir = make_recorded(tmp_path / "demo", {"a": GOOD, "b": GOOD})
|
||||||
|
commit_all(tmp_path)
|
||||||
|
record(set_dir, GOOD, BAD)
|
||||||
|
assert main([str(set_dir), "--baseline", "HEAD"]) == 1
|
||||||
|
out = capsys.readouterr().out
|
||||||
|
assert "demo: 1/2 passed" in out
|
||||||
|
assert "REGRESSION b" in out
|
||||||
|
commit_all(tmp_path)
|
||||||
|
record(set_dir, GOOD, GOOD)
|
||||||
|
assert main([str(set_dir), "--baseline", "HEAD"]) == 0
|
||||||
|
assert "FIXED b" in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
def test_baseline_unknown_ref_exit_2(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
|
git(tmp_path, "init", "-q")
|
||||||
|
set_dir = make_recorded(tmp_path / "demo", {"a": GOOD, "b": GOOD})
|
||||||
|
commit_all(tmp_path)
|
||||||
|
assert main([str(set_dir), "--baseline", "no-such-ref"]) == 2
|
||||||
|
captured = capsys.readouterr()
|
||||||
|
assert captured.err.startswith("chemenu-eval: ")
|
||||||
|
assert captured.out == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_markdown_requires_baseline(tmp_path: Path) -> None:
|
||||||
|
make_recorded(tmp_path, {"a": GOOD, "b": GOOD})
|
||||||
|
with pytest.raises(SystemExit) as excinfo:
|
||||||
|
main([str(tmp_path), "--format", "markdown"])
|
||||||
|
assert excinfo.value.code == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_baseline_new_set_exit_0(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
|
git(tmp_path, "init", "-q")
|
||||||
|
(tmp_path / "other.txt").write_text("x")
|
||||||
|
commit_all(tmp_path)
|
||||||
|
set_dir = make_recorded(tmp_path / "demo", {"a": GOOD, "b": GOOD})
|
||||||
|
assert main([str(set_dir), "--baseline", "HEAD", "--format", "markdown"]) == 0
|
||||||
|
assert "new set" in capsys.readouterr().out
|
||||||
Reference in new issue
Block a user