Coverage for app / services / evaluation / best.py: 100%
31 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Best configurations — what works best on one dataset, across its experiments.
4Each experiment ranks its own variants. The question a dataset's owner asks
5is wider: of everything tried on these questions — every model, agent,
6temperature, with and without knowledge — what does best? This answers it
7from each experiment's newest completed run on one dataset version, variant
8by variant, with what each cost.
10Two things keep the comparison honest:
12* **Rows are grouped by how they were graded.** An LLM judge's 0.8 and an
13 exact-match 0.8 are not the same measurement, and neither are two judges'
14 0.8s — so a scorer (and, for the LLM judge, the grading model) is a group,
15 and rows are ranked only within one.
16* **Only one dataset version.** A run on an earlier version answered
17 different questions (see ``dataset_versions``).
19Within a group, a row is **best value** when no other row is at least as
20good *and* at least as cheap with one of the two strictly better — the
21cost/quality frontier. A row with no price (an unpriced model) is never on
22it: unknown cost is not zero cost.
23"""
25from __future__ import annotations
27from collections.abc import Iterable
28from typing import Any
30#: Labels for scorers, for group headings. The catalogue owns the full
31#: description; this only names a group.
32SCORER_LABELS = {
33 "llm": "LLM judge",
34 "contains": "Text checks",
35 "exact_match": "Exact match",
36 "json_match": "JSON fields",
37 "manual": "Manual",
38 "not_contains": "Does not contain",
39 "regex": "Regular expression",
40}
43def group_key(scorer: str | None, judge: dict | None) -> str:
44 """How a row was graded. Two judges are two measurements."""
45 if scorer == "llm":
46 judge_id = (judge or {}).get("model_id") or "default"
47 return f"llm:{judge_id}"
48 return str(scorer or "manual")
51def mark_frontier(rows: list[dict[str, Any]]) -> None:
52 """Set ``best_value`` on each row: nothing else is as good and as cheap.
54 A row needs both a score and a price to be on the frontier. Cost is
55 per answer, not per run: a run with repeats costs more in total without
56 any one answer being dearer.
57 """
58 priced = [
59 r
60 for r in rows
61 if r.get("mean_score") is not None and r.get("cost_per_case_usd") is not None
62 ]
63 for row in rows:
64 row["best_value"] = False
65 for row in priced:
66 dominated = any(
67 other is not row
68 and other["mean_score"] >= row["mean_score"]
69 and other["cost_per_case_usd"] <= row["cost_per_case_usd"]
70 and (
71 other["mean_score"] > row["mean_score"]
72 or other["cost_per_case_usd"] < row["cost_per_case_usd"]
73 )
74 for other in priced
75 )
76 row["best_value"] = not dominated
79def rank(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
80 """Best score first; cheaper, then faster, breaks a tie. Unscored last."""
81 return sorted(
82 rows,
83 key=lambda r: (
84 r.get("mean_score") is None,
85 -(r.get("mean_score") or 0),
86 r.get("cost_per_case_usd")
87 if r.get("cost_per_case_usd") is not None
88 else float("inf"),
89 r.get("mean_latency_ms") or 0,
90 ),
91 )
94def build_groups(
95 entries: Iterable[dict[str, Any]],
96) -> list[dict[str, Any]]:
97 """Group rows by how they were graded, rank each group, mark best value.
99 ``entries`` are rows already carrying ``scorer`` and ``judge``. Groups
100 come back largest first — the grading most of the dataset's experiments
101 share is the one most worth reading.
102 """
103 groups: dict[str, dict[str, Any]] = {}
104 for entry in entries:
105 key = group_key(entry.get("scorer"), entry.get("judge"))
106 group = groups.setdefault(
107 key,
108 {
109 "key": key,
110 "scorer": entry.get("scorer"),
111 "scorer_label": SCORER_LABELS.get(
112 str(entry.get("scorer")), str(entry.get("scorer"))
113 ),
114 "judge": entry.get("judge"),
115 "rows": [],
116 },
117 )
118 group["rows"].append(entry)
119 out = []
120 for group in groups.values():
121 mark_frontier(group["rows"])
122 group["rows"] = rank(group["rows"])
123 out.append(group)
124 out.sort(key=lambda g: -len(g["rows"]))
125 return out