Spaces:
Sleeping
Sleeping
File size: 28,543 Bytes
23d418f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | """Step 4d: metrics over graded runs, with bootstrap intervals and paired comparison.
uv run python -m coveragecheck.evals.metrics [run.parquet ...]
Everything is computed from a per-question table (scored()): one row per question of
one run, with its outcome from grade.resolve, labels, confidence, latency, tokens and
retrieval hit rank. The metric functions are small and pure over that table.
Owner decisions (4d):
- correct (accuracy_strict): an answerable question passed, or an unanswerable one
abstained / refused in prose (hand pass). Abstaining on an answerable question is
wrong.
- Cost (config.COST_WEIGHTS, an E&O loss proxy): an error costs the worst case, like
a fail (answerable: fail_low/fail_high by cost_class; unanswerable: "answered").
- Ungraded (pending) answers are never dropped (that would bias accuracy up): every
score has a best case (pending = pass) and a worst case (pending = fail); a single
headline number only exists when nothing is pending.
- Stale rows (question removed or reworded since the run) are excluded and counted.
- Hallucinated citation rates (Step 8, verify/citations.py), per citation, pooled over
the run: not exact (the headline), not even approximate, and quoted from outside the
passages shown; plus the share of answers with a citation that is not exact.
- Paired comparison: fixed/broken/both counts, paired-bootstrap CI of the accuracy
difference, and McNemar's exact test.
"""
import argparse
import json
import math
from pathlib import Path
import numpy as np
import pandas as pd
from coveragecheck import config
from coveragecheck.agent.schemas import Citation
from coveragecheck.evals.grade import Grade, latest_runs, load_grades, resolve, row_key
from coveragecheck.evals.hits import ancestry, first_hit_sets, summarize
from coveragecheck.evals.questions import Question, load_questions
from coveragecheck.index.store import load_table
from coveragecheck.verify.citations import Checker
ANSWERED = ("pass", "fail", "pending") # the system gave an answer (not auto-graded)
# --- outcomes -> correct and cost ---------------------------------------------------------
def settle(outcome: str, assume: str) -> str:
"""A pending outcome read as `assume` ("pass" = best case, "fail" = worst)."""
return assume if outcome == "pending" else outcome
def is_correct(outcome: str, answerable: bool) -> bool:
"""accuracy_strict: answerable -> only a hand pass; unanswerable -> an abstention
or a refusal in prose (hand pass). Errors are always wrong."""
if answerable:
return outcome == "pass"
return outcome in ("correct_abstain", "pass")
def cost_key(outcome: str, answerable: bool, cost_class: str) -> tuple[bool, str]:
"""The COST_WEIGHTS key of a settled outcome. Errors cost like a fail."""
if answerable:
if outcome == "pass":
return True, "pass"
if outcome == "abstain":
return True, "abstain"
if outcome in ("fail", "error"):
return True, f"fail_{cost_class}"
else:
if outcome in ("correct_abstain", "pass"):
return False, "abstain"
if outcome in ("fail", "error"):
return False, "answered"
raise ValueError(f"no cost for outcome {outcome!r} (answerable={answerable})")
def at_threshold(outcome: str, confidence: float | None, answerable: bool, t: float) -> str:
"""The outcome if the system had abstained on every answer with confidence < t
(no new grade needed: an abstention is auto-graded). Errors and abstentions stay."""
if outcome in ANSWERED and confidence is not None and confidence < t:
return "abstain" if answerable else "correct_abstain"
return outcome
def scores(table: pd.DataFrame, assume: str, t: float = 0.0) -> tuple[np.ndarray, np.ndarray]:
"""(correct 0/1, cost) per question, pending read as `assume`, at threshold t."""
correct, cost = [], []
for r in table.itertuples():
outcome = settle(at_threshold(r.outcome, r.confidence, r.answerable, t), assume)
correct.append(is_correct(outcome, r.answerable))
cost.append(config.COST_WEIGHTS[cost_key(outcome, r.answerable, r.cost_class)])
return np.array(correct, dtype=float), np.array(cost, dtype=float)
# --- building the per-question table ------------------------------------------------------
def retrieved_sets(row: dict, naive_covers: dict[str, frozenset[str]]) -> list[frozenset[str]]:
"""What each retrieved item covers, in rank order: a naive window (System A, ids
like "OAP1-2026~3") covers its covers_sources; a structured chunk (B/C) is its
own section. The two id spaces never overlap (4d survey), so no setting is needed."""
return [
naive_covers.get(chunk_id, frozenset({source}))
for chunk_id, source in zip(
row["retrieved_chunk_ids"], row["retrieved_source_ids"], strict=True
)
]
COLUMNS = [
"question_id", "question", "category", "n_docs", "answerable", "cost_class",
"outcome", "grader", "note", "key", "answer", "abstained", "cited_source_ids", "confidence",
"latency_ms", "tokens", "llm_calls", "reasks", "cache_hits", "error_kind", "hit_rank",
"citations", "cites_not_exact", "cites_not_grounded", "cites_not_shown", "trace_json",
] # fmt: skip
NULLABLE = (
"grader", "note", "key", "answer", "abstained", "confidence", "error_kind", "hit_rank",
"citations", "cites_not_exact", "cites_not_grounded", "cites_not_shown", "trace_json",
) # fmt: skip
def scored(
run: pd.DataFrame,
questions: dict[str, Question],
grades: dict[str, Grade],
lineage: dict[str, frozenset[str]],
naive_covers: dict[str, frozenset[str]],
checker: Checker | None = None,
) -> pd.DataFrame:
"""One row per question of the run: outcome (grade.resolve), labels, the answer
and its grade key and note (for 4e / Step 9 examples), confidence, usage, the
rank of the first retrieved gold section (answerable only) and, with a checker,
its citation counts (cite_counts). Stale rows are kept with outcome "stale"; the
metric functions drop them."""
out = []
for row in run.to_dict("records"):
q = questions.get(row["question_id"])
resolved = resolve(row, q, grades)
live_q = q if resolved.outcome != "stale" else None
rank = None
if live_q is not None and live_q.answerable:
rank = first_hit_sets(retrieved_sets(row, naive_covers), live_q.expected, lineage)
out.append(
cite_counts(row, checker)
| {
"question_id": row["question_id"],
"question": row.get("question"),
"category": row["category"],
"n_docs": row["n_docs"],
"answerable": bool(row["answerable"]),
"cost_class": row["cost_class"],
"outcome": resolved.outcome,
# who judged a hand-graded row ("owner" or "llm:..."); None if auto/pending
"grader": resolved.grade.grader if resolved.grade else None,
"note": resolved.grade.note if resolved.grade else None,
"key": row_key(row, live_q) if live_q is not None and row["answer"] else None,
"answer": row["answer"],
"abstained": row["abstained"],
"cited_source_ids": list(row["cited_source_ids"]),
"confidence": row["confidence"],
# measured time + the original model time of calls served from the LLM
# cache (5b), so a cached rerun reports the first run's latency. Runs
# made before 5b have no replayed_ms/reasks/cache_hits columns: 0.
"latency_ms": row["latency_ms"] + (row.get("replayed_ms") or 0.0),
"tokens": row["tokens_in"] + row["tokens_out"],
"llm_calls": row["llm_calls"],
"reasks": row.get("reasks") or 0,
"cache_hits": row.get("cache_hits") or 0,
# why an error row failed (api, refusal, stopped, truncated, invalid,
# exception), so a 529 outage isn't read as a model that can't answer
"error_kind": row.get("error_kind"),
"hit_rank": rank,
# the system's own trace (JSON), for system-specific report sections
# (7d: C's evidence check); never used for scoring
"trace_json": row.get("trace_json"),
}
)
# Real dtypes for columns that never hold None (bool `answerable` must stay bool:
# `~` on an object column of Python bools is bitwise NOT, -2/-1; a test caught
# it); object for the ones that can, else pandas 3 turns None into NaN (CLAUDE.md).
# An empty run still gets every column (4d audit: it crashed later otherwise).
frame = pd.DataFrame(out, columns=COLUMNS)
frame["answerable"] = frame["answerable"].astype(bool) # also when empty
for column in NULLABLE:
frame[column] = pd.Series([o[column] for o in out], dtype=object)
return frame
def cite_counts(row: dict, checker: Checker | None) -> dict[str, int | None]:
"""A run row's citations checked against the passages it showed (Step 8): how
many, how many are not exact, not even approximate, and not in the shown passages.
All None without a checker (unit tests, or no corpus): "not checked" must not read
as "no hallucinations". An error row has no citations: 0 of each."""
keys = ("citations", "cites_not_exact", "cites_not_grounded", "cites_not_shown")
if checker is None:
return dict.fromkeys(keys)
cites = [Citation(**c) for c in json.loads(row.get("citations_json") or "[]")]
checks = checker.check_all(cites, list(row["retrieved_chunk_ids"]))
return dict(
zip(
keys,
(
len(checks),
sum(not c.exact for c in checks),
sum(not c.grounded for c in checks),
sum(not c.in_shown for c in checks),
),
strict=True,
)
)
def citation_rates(table: pd.DataFrame) -> dict[str, float]:
"""Pooled over every citation of the run (a question with 5 citations weighs 5):
the share not exact (the headline hallucinated-citation rate), not even
approximate, and not from the shown passages; and the share of answers with at
least one citation, that have one that is not exact. NaN when unchecked (no
checker, or a table without the columns) or when there is no citation."""
t = live(table)
t = t[t.citations.notna()] if "citations" in t.columns else t.iloc[:0]
nan = dict.fromkeys(
(
"hallucinated_citation_rate",
"hallucinated_citation_rate_fuzzy",
"citation_not_shown_rate",
"answers_with_bad_citation",
),
math.nan,
)
total = int(t.citations.sum()) if len(t) else 0
if total == 0:
return nan | {"citations": 0}
cited = t[t.citations > 0]
return {
"citations": total,
"hallucinated_citation_rate": float(t.cites_not_exact.sum()) / total,
"hallucinated_citation_rate_fuzzy": float(t.cites_not_grounded.sum()) / total,
"citation_not_shown_rate": float(t.cites_not_shown.sum()) / total,
"answers_with_bad_citation": float((cited.cites_not_exact > 0).mean()),
}
def live(table: pd.DataFrame) -> pd.DataFrame:
"""The rows that count: stale ones excluded."""
return table[table.outcome != "stale"]
# --- metrics --------------------------------------------------------------------------------
def bounds(table: pd.DataFrame) -> dict[str, tuple[float, float]]:
"""accuracy_strict and mean cost as (best, worst); equal when nothing is pending.
Best = pending read as pass, worst = as fail."""
t = live(table)
best_c, best_k = scores(t, "pass")
worst_c, worst_k = scores(t, "fail")
return {
"accuracy_strict": (best_c.mean(), worst_c.mean()),
"cost": (best_k.mean(), worst_k.mean()),
}
def correct_abstention_rate(table: pd.DataFrame) -> tuple[float, float] | None:
"""Share of unanswerable questions handled correctly (abstained or refused in
prose), best and worst case. None if the set has no unanswerable question."""
t = live(table)
t = t[~t.answerable]
if t.empty:
return None
return scores(t, "pass")[0].mean(), scores(t, "fail")[0].mean()
def threshold_curve(table: pd.DataFrame, step: float = config.THRESHOLD_STEP) -> pd.DataFrame:
"""For each t in 0..1: coverage (share of questions the system still answers),
accuracy_strict and mean cost (worst case: pending = fail), had it abstained on
every answer with confidence < t. A point estimate on the same questions: the
t with the lowest cost here is optimistic (no held-out set), so 4e must not
present it as a recommended threshold."""
t_live = live(table)
rows = []
for t in np.round(np.arange(0, 1 + step / 2, step), 6):
outcomes = [
at_threshold(r.outcome, r.confidence, r.answerable, t) for r in t_live.itertuples()
]
correct, cost = scores(t_live, "fail", t)
coverage = np.mean([o in ANSWERED for o in outcomes]) if outcomes else 0.0
rows.append({"t": t, "coverage": coverage, "accuracy": correct.mean(), "cost": cost.mean()})
return pd.DataFrame(rows)
def by_group(table: pd.DataFrame, column: str) -> pd.DataFrame:
"""n, accuracy best/worst per value of a column (category, n_docs)."""
rows = []
for value, group in live(table).groupby(column, sort=True):
best, worst = scores(group, "pass")[0].mean(), scores(group, "fail")[0].mean()
rows.append(
{column: value, "n": len(group), "accuracy_best": best, "accuracy_worst": worst}
)
return pd.DataFrame(rows, columns=[column, "n", "accuracy_best", "accuracy_worst"])
NO_RECALL = {"hit@1": math.nan, "hit@5": math.nan, "hit@10": math.nan, "mrr": math.nan}
def recall(table: pd.DataFrame) -> dict[str, float]:
"""hit@1/5/10 and MRR of the gold sections in the retrieved list, over answerable
questions (hits.py rule: a retrieved section hits gold X if it is X or inside X).
NaN when the run has no live answerable question (4d audit: it crashed)."""
t = live(table)
ranks = [None if pd.isna(r) else int(r) for r in t[t.answerable]["hit_rank"]]
return {k: float(v) for k, v in summarize(ranks).items()} if ranks else dict(NO_RECALL)
def usage(table: pd.DataFrame) -> dict[str, float]:
"""Latency p50/p95 (ms, incl. the replayed model time of cached calls); mean tokens,
LLM calls and reasks per question (a reask re-sends the prompt: ~2x tokens_in); and
the share of questions answered from the LLM cache."""
t = live(table)
if t.empty:
keys = (
"latency_p50_ms", "latency_p95_ms", "tokens_mean", "llm_calls_mean",
"reasks_mean", "cached_share",
) # fmt: skip
return dict.fromkeys(keys, math.nan)
p50, p95 = np.percentile(t.latency_ms.astype(float).to_numpy(), [50, 95])
return {
"latency_p50_ms": float(p50),
"latency_p95_ms": float(p95),
"tokens_mean": float(t.tokens.astype(float).mean()),
"llm_calls_mean": float(t.llm_calls.astype(float).mean()),
"reasks_mean": float(t.reasks.astype(float).mean()),
"cached_share": float((t.cache_hits.astype(float) > 0).mean()),
}
# --- uncertainty --------------------------------------------------------------------------
def resample_indices(n: int, resamples: int, seed: int) -> np.ndarray:
"""resamples x n question indices drawn with replacement (the bootstrap draw)."""
return np.random.default_rng(seed).integers(0, n, size=(resamples, n))
def bootstrap_ci(
values: np.ndarray,
resamples: int = config.BOOTSTRAP_RESAMPLES,
seed: int = config.BOOTSTRAP_SEED,
) -> tuple[float, float]:
"""95% percentile interval of the mean: resample the questions with replacement,
take each resample's mean, keep the 2.5% and 97.5% points. Measured coverage at
n=63 (4d audit): 92.5-95%. NaN for no values."""
values = np.asarray(values, dtype=float)
if values.size == 0:
return math.nan, math.nan
means = values[resample_indices(len(values), resamples, seed)].mean(axis=1)
low, high = np.percentile(means, [2.5, 97.5])
return float(low), float(high)
def mcnemar_exact(fixed: int, broken: int) -> float:
"""Two-sided exact McNemar p-value: if neither system were better, each question
on which they disagree would go either way with chance 1/2, so the smaller count
follows Binomial(fixed + broken, 1/2). Questions both pass or both fail carry no
information about the difference. Matches scipy's binomtest (4d audit)."""
n = fixed + broken
if n == 0:
return 1.0
tail = sum(math.comb(n, k) for k in range(min(fixed, broken) + 1)) / 2**n
return min(1.0, 2 * tail)
def holm(pvalues: list[float]) -> list[float]:
"""Holm-adjusted p-values, in the input order. With 3 systems there are 3
comparisons, so one raw p < 0.05 turns up by chance more often than 5% of the
time. Holm: sort the p-values, multiply the i-th smallest (from 0) by (m - i),
keep the running maximum so the order is preserved, cap at 1."""
m = len(pvalues)
order = sorted(range(m), key=lambda i: pvalues[i])
adjusted, running = [0.0] * m, 0.0
for rank, i in enumerate(order):
running = max(running, min(1.0, (m - rank) * pvalues[i]))
adjusted[i] = running
return adjusted
def paired_diff_ci(
a: np.ndarray,
b: np.ndarray,
resamples: int = config.BOOTSTRAP_RESAMPLES,
seed: int = config.BOOTSTRAP_SEED,
) -> tuple[float, tuple[float, float]]:
"""(mean(b) - mean(a), its 95% paired-bootstrap interval) for any per-question
score (0/1 correct, or cost). The same resampled question indices go to both
systems, so each question stays paired and its difficulty cancels out (measured:
0.29 wide vs 0.35 unpaired). Raises on no shared questions: an empty comparison
must not print as "no difference"."""
a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
if a.shape != b.shape:
raise ValueError("paired comparison needs the same questions for both systems")
if a.size == 0:
raise ValueError("no questions to compare")
idx = resample_indices(len(a), resamples, seed)
diffs = b[idx].mean(axis=1) - a[idx].mean(axis=1)
low, high = np.percentile(diffs, [2.5, 97.5])
return float(b.mean() - a.mean()), (float(low), float(high))
def paired(a: np.ndarray, b: np.ndarray, **kwargs) -> dict:
"""Compare two systems scored 0/1 on the same questions (same order): the four
boxes, diff = (fixed - broken) / n with its paired CI, and McNemar's exact p."""
diff, ci = paired_diff_ci(a, b, **kwargs)
a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
fixed = int(((a == 0) & (b == 1)).sum())
broken = int(((a == 1) & (b == 0)).sum())
return {
"n": len(a),
"both_pass": int(((a == 1) & (b == 1)).sum()),
"both_fail": int(((a == 0) & (b == 0)).sum()),
"fixed": fixed,
"broken": broken,
"diff": diff,
"ci": ci,
"mcnemar_p": mcnemar_exact(fixed, broken),
}
def settled_ids(table: pd.DataFrame) -> set[str]:
"""Question ids that count and are fully graded (not stale, not pending)."""
return set(table[~table.outcome.isin(["stale", "pending"])].question_id)
def align(a: pd.DataFrame, b: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Both tables restricted to the questions settled in BOTH, in the same order.
Pending answers are left out of a comparison (4d audit): reading them as fails
would make the system with more ungraded answers look worse."""
shared = sorted(settled_ids(a) & settled_ids(b))
return _rows(a, shared), _rows(b, shared)
def _rows(table: pd.DataFrame, ids: list[str]) -> pd.DataFrame:
"""The rows of these question ids, in this order."""
return table.set_index("question_id").loc[ids].reset_index()
# --- summary and CLI ----------------------------------------------------------------------
def envelope(best: tuple[float, float], worst: tuple[float, float]) -> tuple[float, float]:
"""One interval covering both the best-case and worst-case CIs: the honest range
for a partial run (a worst-case CI alone contradicted the printed best-worst range,
4d audit). Equal to either CI when nothing is pending."""
return min(best[0], worst[0]), max(best[1], worst[1])
def summary(table: pd.DataFrame) -> dict[str, float | int | bool]:
"""Every headline number for one run, flat and plain (floats, ints, a bool), so a
list of summaries is directly the A/B/C table: pd.DataFrame(summaries). CIs are
the envelope of the best- and worst-case CIs (identical when complete)."""
t = live(table)
best_c, best_k = scores(t, "pass")
worst_c, worst_k = scores(t, "fail")
acc_ci = envelope(bootstrap_ci(best_c), bootstrap_ci(worst_c))
cost_ci = envelope(bootstrap_ci(best_k), bootstrap_ci(worst_k))
abstention = correct_abstention_rate(table) or (math.nan, math.nan)
mean = lambda values: float(values.mean()) if values.size else math.nan # noqa: E731
return {
"n": len(t),
"stale": int((table.outcome == "stale").sum()),
"pending": int((t.outcome == "pending").sum()),
"errors": int((t.outcome == "error").sum()),
"complete": not (t.outcome == "pending").any(),
"accuracy_best": mean(best_c),
"accuracy_worst": mean(worst_c),
"accuracy_ci_low": acc_ci[0],
"accuracy_ci_high": acc_ci[1],
"cost_best": mean(best_k),
"cost_worst": mean(worst_k),
"cost_ci_low": cost_ci[0],
"cost_ci_high": cost_ci[1],
"abstention_best": float(abstention[0]),
"abstention_worst": float(abstention[1]),
**citation_rates(table),
**recall(table),
**usage(table),
}
def describe(path: Path) -> dict:
"""Where a run's numbers come from, from its sidecar: system, file, start time,
git commit, complete flag, and from its settings the answer model, prompt and index
fingerprints (5b audit: two runs compared with different prompts must show it; B's
claim is "same prompt as A"). Missing sidecar or setting -> None."""
sidecar = path.with_suffix(".json")
meta = json.loads(sidecar.read_text(encoding="utf-8")) if sidecar.exists() else {}
settings = meta.get("settings") or {}
keys = ("system", "started_at", "git_commit", "complete", "questions_sha256")
out = {"run": path.name} | {k: meta.get(k) for k in keys}
questions = meta.get("questions_path")
out["questions_file"] = Path(questions).name if questions else None
return out | {k: settings.get(k) for k in ("llm_model", "prompt_hash", "index_hash")}
def fmt_range(best: float, worst: float, digits: int = 2) -> str:
""" "0.61" when best == worst, else "0.55-0.70 (PARTIAL)"; "n/a" for NaN."""
if math.isnan(best) or math.isnan(worst):
return "n/a"
if math.isclose(best, worst):
return f"{best:.{digits}f}"
low, high = sorted((best, worst))
return f"{low:.{digits}f}-{high:.{digits}f} (PARTIAL)"
def format_run(info: dict, s: dict) -> list[str]:
"""The printed block for one run (reused by 4e)."""
lines = [
f"== {info.get('system') or '?'} ({info['run']}, commit {info.get('git_commit')}): "
f"{s['n']} questions, {s['pending']} pending, {s['errors']} errors, {s['stale']} stale",
f"accuracy_strict {fmt_range(s['accuracy_best'], s['accuracy_worst'])} "
f"95% CI {s['accuracy_ci_low']:.2f}-{s['accuracy_ci_high']:.2f}",
f"cost per question {fmt_range(s['cost_best'], s['cost_worst'])} "
f"95% CI {s['cost_ci_low']:.2f}-{s['cost_ci_high']:.2f}",
f"correct abstention {fmt_range(s['abstention_best'], s['abstention_worst'])}",
]
if math.isnan(s["mrr"]):
lines.append("recall n/a (no answerable question)")
else:
hits = " ".join(f"{k} {s[k]:.2f}" for k in ("hit@1", "hit@5", "hit@10", "mrr"))
lines.append(f"recall {hits}")
lines.append(
f"latency p50 {s['latency_p50_ms']:.0f} ms p95 {s['latency_p95_ms']:.0f} ms "
f"tokens {s['tokens_mean']:.0f}"
)
lines.append(citation_line(s))
return lines
def citation_line(s: dict) -> str:
"""The printed citation-check line of a run (Step 8)."""
if math.isnan(s["hallucinated_citation_rate"]):
return "citations: not checked or none"
return (
f"citations {s['citations']}: not exact {s['hallucinated_citation_rate']:.1%}, "
f"not even approximate {s['hallucinated_citation_rate_fuzzy']:.1%}, "
f"not in the shown passages {s['citation_not_shown_rate']:.1%}; answers with one "
f"not exact {s['answers_with_bad_citation']:.1%}"
)
def format_pair(name_a: str, name_b: str, ta: pd.DataFrame, tb: pd.DataFrame) -> str:
"""One line comparing b with a on the questions settled in both."""
if ta.empty:
return f"{name_b} vs {name_a}: no question graded in both, nothing to compare"
p = paired(scores(ta, "fail")[0], scores(tb, "fail")[0])
cost, cost_ci = paired_diff_ci(scores(ta, "fail")[1], scores(tb, "fail")[1])
return (
f"{name_b} vs {name_a} on {p['n']} questions graded in both: fixed {p['fixed']} "
f"broken {p['broken']} both pass {p['both_pass']} both fail {p['both_fail']}; "
f"accuracy {p['diff']:+.2f} (95% CI {p['ci'][0]:+.2f} to {p['ci'][1]:+.2f}), "
f"McNemar p {p['mcnemar_p']:.3f}; cost {cost:+.2f} "
f"(95% CI {cost_ci[0]:+.2f} to {cost_ci[1]:+.2f})"
)
def questions_path_of(run: Path) -> Path:
"""The question file a run used (its sidecar's questions_path), looked up by file
name under evals/ so it works on any machine; the draft set for a run without
one. Scoring a held-out run against the draft file would mark every row stale."""
sidecar = run.with_suffix(".json")
meta = json.loads(sidecar.read_text(encoding="utf-8")) if sidecar.exists() else {}
recorded = meta.get("questions_path")
return config.EVALS_DIR / Path(recorded).name if recorded else config.QUESTIONS_PATH
def shared_questions_path(runs: list[Path]) -> Path:
"""The one question file all these runs used; refuses a mix (a paired comparison
needs the same questions)."""
paths = {questions_path_of(r) for r in runs}
if len(paths) > 1:
raise ValueError(f"runs use different question files: {sorted(p.name for p in paths)}")
return paths.pop() if paths else config.QUESTIONS_PATH
def load_inputs(questions_path: Path | None = None):
"""Questions (from questions_path, default the draft set), grades, section
lineage, System A's window coverage and the Step 8 citation checker (scored's
arguments, in order)."""
path = config.QUESTIONS_PATH if questions_path is None else questions_path
questions = {q.id: q for q in load_questions(path)}
grades = load_grades(config.GRADES_PATH)
lineage = ancestry(load_table(config.INDEX_DIR / "sections.parquet"))
naive = load_table(config.INDEX_DIR / "naive_chunks.parquet")
covers = {c: frozenset(s) for c, s in zip(naive.chunk_id, naive.covers_sources, strict=True)}
return questions, grades, lineage, covers, Checker.load()
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("runs", nargs="*", type=Path, help="run files (default: newest per system)")
args = parser.parse_args()
paths = args.runs or latest_runs(config.RUNS_DIR)
if not paths:
raise SystemExit(f"no runs in {config.RUNS_DIR}")
inputs = load_inputs(shared_questions_path(paths))
tables = {p.name: scored(load_table(p), *inputs) for p in paths}
for path in paths:
table = tables[path.name]
print("\n" + "\n".join(format_run(describe(path), summary(table))))
print(by_group(table, "category").to_string(index=False, float_format="%.2f"))
names = list(tables)
for i, a in enumerate(names):
for b in names[i + 1 :]:
print("\n" + format_pair(a, b, *align(tables[a], tables[b])))
if __name__ == "__main__":
main()
|