From 9f296e4ef6ded034d9b2c8c79130c5573e096e03 Mon Sep 17 00:00:00 2001 From: Arinjay Wyawhare <72088094+jaywyawhare@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:23:39 +0530 Subject: [PATCH] Add repeats, bootstrap intervals, paired comparison, and judge audit to the agent benchmark --- benchmarks/agent/README.md | 83 ++++++++++++---- benchmarks/agent/harness.py | 30 ++++-- benchmarks/agent/run.py | 25 ++++- benchmarks/agent/scoring.py | 174 +++++++++++++++++++++++++++++++++- tests/test_agent_benchmark.py | 91 +++++++++++++++--- 5 files changed, 354 insertions(+), 49 deletions(-) diff --git a/benchmarks/agent/README.md b/benchmarks/agent/README.md index 159c42e5..a2fab87c 100644 --- a/benchmarks/agent/README.md +++ b/benchmarks/agent/README.md @@ -8,7 +8,9 @@ the same model on the same questions under two conditions: | `baseline` | `list_documents`, `read_document`, and `search_documents` (plain text or regex search over lines). | | `graph` | The same document tools, plus every read-only tool of the SelfGraph MCP server, over a graph of the same documents. | -It reports accuracy, wall time, tokens, cost, and tool calls for each condition. +Every question runs `--repeats` times (3 by default) under each condition. The +benchmark reports accuracy with a 95% interval, accuracy per question kind, a +paired comparison with `baseline`, wall time, tokens, cost, and tool calls. The graph tools come from the MCP server itself (`src/selfgraph/mcp/server.py`): the benchmark builds it in process with `build_server()`, keeps every tool @@ -25,15 +27,17 @@ adds the server's own instructions to the shared system prompt. ```bash pip install -e ".[llm,kuzu,mcp]" export _API_KEY=... -python benchmarks/agent/run.py --model provider/model +python benchmarks/agent/run.py --model provider/model --judge provider/other-model --audit 30 ``` | Flag | Default | Effect | |------|---------|--------| | `--model` | required | The agent model, in litellm form (`provider/model`). | -| `--judge` | `--model` | The judge model, in the same form. | +| `--judge` | `--model` | The judge model, in the same form. Use a different model; see Scoring. | | `--conditions` | `baseline,graph` | Which conditions to run. | | `--questions N` | all | Run the first N questions. | +| `--repeats N` | 3 | Run every question N times per condition. | +| `--audit N` | off | Write N judged runs, drawn at random, to grade by hand. | | `--price IN,OUT` | litellm's cost data | USD per million input and output tokens for `--model`. | | `--judge-price IN,OUT` | `--price` for the same model, else litellm's cost data | The same for `--judge`. | | `--estimate` | off | Print the cost estimate and stop, with no model call. | @@ -52,8 +56,8 @@ later team or account change retires the earlier one. Every run first prints an estimate per condition and for the judge, then starts. Use `--estimate` to see it without running. The estimate counts about four characters per token over the system prompt, the tool specs, the questions, and -the average document, and assumes five model calls per question, each resending -the conversation so far. Treat it as an order of magnitude. Prices come from +the average document, and assumes five model calls per run, each resending +the conversation so far. It grows linearly with `--repeats`. Treat it as an order of magnitude. Prices come from `--price` and `--judge-price`, or from litellm's own cost data for the model; a row with no price shows `n/a`. @@ -66,14 +70,45 @@ could not find the information. A run that times out, hits the step limit, or fails gives no answer and counts as `wrong`. A judge reply with no valid verdict counts as `unscored`. Accuracy is `correct / runs`. +The runs of one question are not independent samples of the benchmark, so the +95% interval comes from a bootstrap that resamples questions, not runs: it draws +the questions with replacement 2,000 times with a fixed seed and takes the 2.5th +and 97.5th percentiles of the accuracy. With about 40 questions the interval is +wide; read a gap between conditions as real only when the paired interval below +leaves out zero. + +The paired comparison scores each question by its mean over its runs (correct +1, partial 0.5, wrong 0) and counts the questions where a condition does better, +worse, or the same as `baseline`. The accuracy difference is the mean of the +per question differences in accuracy, with a bootstrap interval over the same +paired questions. + +### Judge choice and audit + +The judge defaults to the agent model, which then grades its own answers. The +run allows it but prints a warning, since a model can favour answers in its own +style. Pass `--judge` with a model from a different provider or family. + +`--audit N` writes `-audit.md` next to the results JSON with N runs +the judge graded, drawn with a fixed seed: the question, the gold answer, the +answer, the judge verdict and reason, and an empty human verdict column. Fill in +the human column by the rubric, then report the agreement as the share of rows +where the human and the judge give the same verdict, with the count (for example +`27 of 30, 90%`), and list every row where they differ. 30 rows is a reasonable +minimum; agreement below about 85% means the accuracy numbers need a better +judge or rubric before anyone reads them. + ## Output -The run prints a markdown table of totals per condition and one line each for -the judge's usage and the graph build. It writes `results/.json` -with the options, the graph build (counts, warnings, seconds, tool names), one -record per run (answer, verdict, judge reason, wall seconds, model calls, -tokens, cost, failure, and every tool call with its arguments, status, and -seconds), and the totals per condition. Cost covers the calls with a known +The run prints a markdown table of totals per condition with the accuracy +interval, a table of accuracy per question kind, the paired comparison with +`baseline`, and one line each for the judge's usage and the graph build. It +writes `results/.json` with the options, the graph build (counts, +warnings, seconds, tool names), one record per run (attempt number, answer, +verdict, judge reason, wall seconds, model calls, tokens, cost, failure, and +every tool call with its arguments, status, and seconds), the totals per +condition (`summary`, with `accuracy_ci` and `kinds`), and the paired comparison +(`paired`). Cost covers the calls with a known price; the table marks it `(partial)` when some call had none. Judge tokens and cost are reported apart from the conditions. @@ -118,8 +153,24 @@ Fill this in after the first run. | SelfGraph version | | | Model | | | Judge | | - -| Condition | Runs | Accuracy | Correct | Partial | Wrong | Mean s | p95 s | Input tokens | Output tokens | Cost (USD) | Tool calls | -|-----------|------|----------|---------|---------|-------|--------|-------|--------------|---------------|------------|------------| -| `baseline` | | | | | | | | | | | | -| `graph` | | | | | | | | | | | | +| Repeats | | +| Judge and human agreement | | + +| Condition | Runs | Accuracy | 95% CI | Correct | Partial | Wrong | Mean s | p95 s | Input tokens | Output tokens | Cost (USD) | Tool calls | +|-----------|------|----------|--------|---------|---------|-------|--------|-------|--------------|---------------|------------|------------| +| `baseline` | | | | | | | | | | | | | +| `graph` | | | | | | | | | | | | | + +| Kind | `baseline` | `graph` | +|------|------------|---------| +| lookup | | | +| multi_hop | | | +| connection | | | +| impact | | | +| temporal | | | +| aggregation | | | +| unanswerable | | | + +| Versus `baseline` | Questions | Better | Worse | Tied | Accuracy difference | 95% CI | +|-------------------|-----------|--------|-------|------|---------------------|--------| +| `graph` | | | | | | | diff --git a/benchmarks/agent/harness.py b/benchmarks/agent/harness.py index 1783159a..e76b0994 100644 --- a/benchmarks/agent/harness.py +++ b/benchmarks/agent/harness.py @@ -99,6 +99,7 @@ class Run: condition: str question_id: str kind: str + attempt: int = 1 answer: str = "" failure: str | None = None seconds: float = 0.0 @@ -116,6 +117,7 @@ class Options: judge: str conditions: tuple[str, ...] = CONDITIONS questions: int | None = None + repeats: int = 3 price: Price | None = None judge_price: Price | None = None concurrency: int = 4 @@ -329,7 +331,7 @@ def estimate(setup: Setup, options: Options) -> dict[str, dict[str, Any]]: @param options (Options): the run options, for the conditions and prices. @return (dict[str, dict[str, Any]]): per condition and for the judge: input tokens, output tokens, and cost. """ - count, steps, out = len(setup.questions), ESTIMATE_STEPS, ESTIMATE_OUTPUT + count, steps, out = len(setup.questions) * options.repeats, ESTIMATE_STEPS, ESTIMATE_OUTPUT asked = sum(len(q["question"]) for q in setup.questions) / CHARS_PER_TOKEN gold = sum(len(q["answer"]) for q in setup.questions) / CHARS_PER_TOKEN document = sum(len(d.text) for d in setup.documents) / max(1, len(setup.documents)) / CHARS_PER_TOKEN @@ -337,9 +339,13 @@ def estimate(setup: Setup, options: Options) -> dict[str, dict[str, Any]]: for condition in options.conditions: fixed = len(setup.prompts[condition] + json.dumps(setup.toolboxes[condition].specs)) / CHARS_PER_TOKEN grown = steps * (steps - 1) / 2 * (document + out) - totals[condition] = (count * (steps * fixed + grown) + steps * asked, count * steps * out, options.price) + totals[condition] = ( + count * (steps * fixed + grown) + options.repeats * steps * asked, + count * steps * out, + options.price, + ) runs = len(options.conditions) - judged = runs * (count * (len(JUDGE_PROMPT) / CHARS_PER_TOKEN + out) + asked + gold) + judged = runs * (count * (len(JUDGE_PROMPT) / CHARS_PER_TOKEN + out) + options.repeats * (asked + gold)) totals["judge"] = (judged, runs * count * out, options.judge_price) return { name: {"input_tokens": round(i), "output_tokens": round(o), "cost": cost_of(round(i), round(o), price)} @@ -396,7 +402,9 @@ async def build_graph(folder: Path) -> dict[str, Any]: return {"seconds": seconds, "counts": counts, "warnings": len(result.get("warnings") or [])} -async def _attempt(client: Any, options: Options, setup: Setup, question: dict[str, Any], condition: str) -> Run: +async def _attempt( + client: Any, options: Options, setup: Setup, question: dict[str, Any], condition: str, attempt: int +) -> Run: """Answer and score one question under one condition. @param client (Any): the model client. @@ -404,9 +412,10 @@ async def _attempt(client: Any, options: Options, setup: Setup, question: dict[s @param setup (Setup): the prepared run, for the condition's tools and prompt. @param question (dict[str, Any]): the question with its gold answer. @param condition (str): "baseline" or "graph". + @param attempt (int): which repeat of the question this is, from 1. @return (Run): the scored run; a run with no answer is wrong, a judge failure unscored. """ - run = Run(condition, question["id"], question["kind"]) + run = Run(condition, question["id"], question["kind"], attempt) started = time.perf_counter() try: asked = ask(client, options, question["question"], setup.prompts[condition], setup.toolboxes[condition], run) @@ -429,7 +438,7 @@ async def _attempt(client: Any, options: Options, setup: Setup, question: dict[s async def run_benchmark(setup: Setup, options: Options, client: Any) -> dict[str, Any]: - """Run every question under every condition and return the raw results. + """Run every question options.repeats times under every condition and return the raw results. @param setup (Setup): the prepared run. @param options (Options): the run options. @@ -440,16 +449,19 @@ async def run_benchmark(setup: Setup, options: Options, client: Any) -> dict[str gate = asyncio.Semaphore(options.concurrency) - async def gated(question: dict[str, Any], condition: str) -> Run: + async def gated(question: dict[str, Any], condition: str, attempt: int) -> Run: async with gate: - return await _attempt(client, options, setup, question, condition) + return await _attempt(client, options, setup, question, condition, attempt) graph = None with tempfile.TemporaryDirectory(prefix="selfgraph-agent-bench-") as folder: try: if setup.tools is not None: graph = {**await build_graph(Path(folder)), "tools": setup.tools} - runs = await asyncio.gather(*(gated(q, c) for c in options.conditions for q in setup.questions)) + attempts = range(1, options.repeats + 1) + runs = await asyncio.gather( + *(gated(q, c, a) for c in options.conditions for q in setup.questions for a in attempts) + ) finally: await srv.close() runs_json = [asdict(r) for r in runs] diff --git a/benchmarks/agent/run.py b/benchmarks/agent/run.py index 29712815..ad8362d2 100644 --- a/benchmarks/agent/run.py +++ b/benchmarks/agent/run.py @@ -10,13 +10,17 @@ from typing import Any from harness import CONDITIONS, LiteLLMClient, Options, estimate, litellm_price, prepare, run_benchmark -from scoring import estimate_markdown, markdown, summarize +from scoring import audit_markdown, compare, estimate_markdown, markdown, summarize from selfgraph import __version__ from selfgraph.errors import SelfGraphError, surface_hint RESULTS = Path(__file__).parent / "results" INSTALL = 'pip install "selfgraph[llm,kuzu,mcp]"' +SELF_GRADING = ( + "warning: the judge is the agent model, and a model grading its own answers can bias the verdicts; " + "pass --judge with a different model" +) def _flag(parse: Any, expected: str) -> Any: @@ -71,7 +75,10 @@ def build_parser() -> argparse.ArgumentParser: parser.add_argument( "--conditions", type=_flag(_conditions, "baseline, graph, or both"), default=CONDITIONS, help="baseline,graph" ) - parser.add_argument("--questions", type=_flag(lambda t: int(t) if int(t) > 0 else None, "N > 0"), help="first N") + positive = _flag(lambda t: int(t) if int(t) > 0 else None, "N > 0") + parser.add_argument("--questions", type=positive, help="first N") + parser.add_argument("--repeats", type=positive, default=3, help="runs per question and condition (default 3)") + parser.add_argument("--audit", type=positive, help="write N random judged runs to grade by hand") parser.add_argument("--price", type=price, help="INPUT,OUTPUT USD per million tokens for --model") parser.add_argument("--judge-price", type=price, help="INPUT,OUTPUT USD per million tokens for --judge") parser.add_argument("--estimate", action="store_true", help="print the cost estimate and stop") @@ -100,7 +107,7 @@ def check_requirements(options: Options, calls_litellm: bool) -> str | None: def main(argv: list[str] | None = None, client: Any = None) -> int: - """Print the cost estimate, run the benchmark, write results/.json, and print the totals. + """Print the cost estimate, run the benchmark, write results/.json (and the audit), and print totals. @param argv (list[str] | None): the arguments, or None for sys.argv. @param client (Any): the model client, or None for litellm. @@ -110,11 +117,13 @@ def main(argv: list[str] | None = None, client: Any = None) -> int: judge = args.judge or args.model price = args.price or litellm_price(args.model) judge_price = args.judge_price or (price if judge == args.model else litellm_price(judge)) - options = Options(args.model, judge, args.conditions, args.questions, price, judge_price) + options = Options(args.model, judge, args.conditions, args.questions, args.repeats, price, judge_price) problem = check_requirements(options, client is None and not args.estimate) if problem: print(f"error: {problem}", file=sys.stderr) return 2 + if judge == args.model: + print(SELF_GRADING, file=sys.stderr) started = datetime.now(timezone.utc) try: setup = asyncio.run(prepare(options)) @@ -127,10 +136,16 @@ def main(argv: list[str] | None = None, client: Any = None) -> int: return 1 result = {"started_at": started.isoformat(), "selfgraph": __version__, **result} result["summary"] = summarize(result["runs"], list(options.conditions)) + result["paired"] = compare(result["runs"], list(options.conditions)) args.results.mkdir(parents=True, exist_ok=True) - path = args.results / f"{started.strftime('%Y%m%dT%H%M%SZ')}.json" + stamp = started.strftime("%Y%m%dT%H%M%SZ") + path = args.results / f"{stamp}.json" path.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print(f"\n{markdown(result)}\n\nresults: {path}") + if args.audit: + audit = args.results / f"{stamp}-audit.md" + audit.write_text(audit_markdown(result["runs"], setup.questions, args.audit), encoding="utf-8") + print(f"audit: {audit}") return 0 diff --git a/benchmarks/agent/scoring.py b/benchmarks/agent/scoring.py index c047f9bb..2d728899 100644 --- a/benchmarks/agent/scoring.py +++ b/benchmarks/agent/scoring.py @@ -2,11 +2,16 @@ import json import math +import random import re import statistics from typing import Any VERDICTS = ("correct", "partial", "wrong") +SCORES = {"correct": 1.0, "partial": 0.5} +BOOTSTRAP_SAMPLES = 2000 +BOOTSTRAP_SEED = 20250901 +AUDIT_SEED = 20250902 _OBJECT = re.compile(r"\{.*\}", re.DOTALL) JUDGE_PROMPT = """You grade an answer to a question about a fictional company against a gold answer. @@ -57,12 +62,89 @@ def _cost(usages: list[dict[str, Any]]) -> dict[str, Any]: return {"cost": round(sum(known), 6), "cost_complete": len(known) == len(usages)} +def _per_question(runs: list[dict[str, Any]], condition: str, value: Any) -> dict[str, float]: + """Average a value over each question's runs under one condition. + + @param runs (list[dict[str, Any]]): the run records. + @param condition (str): the condition. + @param value (Callable[[dict[str, Any]], float]): the value of one run. + @return (dict[str, float]): question id to its mean value. + """ + grouped: dict[str, list[float]] = {} + for run in runs: + if run["condition"] == condition: + grouped.setdefault(run["question_id"], []).append(value(run)) + return {question: statistics.fmean(values) for question, values in grouped.items()} + + +def _correct(run: dict[str, Any]) -> float: + """Score a run 1 when correct, else 0. + + @param run (dict[str, Any]): the run record. + @return (float): 1.0 or 0.0. + """ + return float(run["verdict"] == "correct") + + +def _score(run: dict[str, Any]) -> float: + """Score a run 1 when correct, 0.5 when partial, else 0. + + @param run (dict[str, Any]): the run record. + @return (float): the score. + """ + return SCORES.get(run["verdict"], 0.0) + + +def bootstrap(values: list[float]) -> list[float] | None: + """Give the 95% interval of a mean by resampling the values, one per question, with a fixed seed. + + @param values (list[float]): one value per question. + @return (list[float] | None): the low and high bounds, or None with no values. + """ + if not values: + return None + rng = random.Random(BOOTSTRAP_SEED) + means = sorted(statistics.fmean(rng.choices(values, k=len(values))) for _ in range(BOOTSTRAP_SAMPLES)) + return [round(means[int(0.025 * BOOTSTRAP_SAMPLES)], 4), round(means[math.ceil(0.975 * BOOTSTRAP_SAMPLES) - 1], 4)] + + +def compare(runs: list[dict[str, Any]], conditions: list[str]) -> dict[str, dict[str, Any]]: + """Pair every other condition with baseline question by question. + + @param runs (list[dict[str, Any]]): the run records. + @param conditions (list[str]): the conditions in report order. + @return (dict[str, dict[str, Any]]): per condition: questions it scores better, worse, and tied on by mean score, + and the accuracy difference from baseline with its bootstrap interval; empty without baseline. + """ + if "baseline" not in conditions: + return {} + base_score, base_correct = _per_question(runs, "baseline", _score), _per_question(runs, "baseline", _correct) + paired = {} + for condition in conditions: + if condition == "baseline": + continue + score, correct = _per_question(runs, condition, _score), _per_question(runs, condition, _correct) + shared = [q for q in score if q in base_score] + gaps = [score[q] - base_score[q] for q in shared] + differences = [correct[q] - base_correct[q] for q in shared] + paired[condition] = { + "questions": len(shared), + "better": sum(gap > 0 for gap in gaps), + "worse": sum(gap < 0 for gap in gaps), + "tied": sum(gap == 0 for gap in gaps), + "accuracy_difference": round(statistics.fmean(differences), 4) if differences else None, + "difference_ci": bootstrap(differences), + } + return paired + + def summarize(runs: list[dict[str, Any]], conditions: list[str]) -> dict[str, dict[str, Any]]: """Total the runs of each condition. @param runs (list[dict[str, Any]]): the run records. @param conditions (list[str]): the conditions in report order. - @return (dict[str, dict[str, Any]]): per condition: verdicts, accuracy, wall time, tokens, cost, and tool calls. + @return (dict[str, dict[str, Any]]): per condition: verdicts, accuracy with its bootstrap interval, accuracy per + question kind, wall time, tokens, cost, and tool calls. """ totals = {} for condition in conditions: @@ -75,6 +157,11 @@ def summarize(runs: list[dict[str, Any]], conditions: list[str]) -> dict[str, di "runs": len(mine), **counts, "accuracy": round(counts["correct"] / len(mine), 4) if mine else None, + "accuracy_ci": bootstrap(list(_per_question(mine, condition, _correct).values())), + "kinds": { + kind: round(statistics.fmean(_correct(r) for r in mine if r["kind"] == kind), 4) + for kind in dict.fromkeys(r["kind"] for r in mine) + }, "mean_seconds": round(statistics.fmean(seconds), 3) if seconds else None, "p95_seconds": sorted(seconds)[math.ceil(0.95 * len(seconds)) - 1] if seconds else None, "input_tokens": sum(r["usage"]["input_tokens"] for r in mine), @@ -96,6 +183,46 @@ def _number(value: Any) -> str: return f"{value:.2f}" if isinstance(value, float) else str(value) +def _interval(bounds: list[float] | None) -> str: + """Render an interval as [low, high]. + + @param bounds (list[float] | None): the bounds, or None. + @return (str): the interval, or n/a. + """ + return "n/a" if bounds is None else f"[{bounds[0]:.2f}, {bounds[1]:.2f}]" + + +def _kinds_markdown(summary: dict[str, dict[str, Any]]) -> list[str]: + """Render accuracy per question kind, one column per condition. + + @param summary (dict[str, dict[str, Any]]): the totals per condition. + @return (list[str]): the table lines. + """ + kinds = list(dict.fromkeys(kind for s in summary.values() for kind in s["kinds"])) + lines = ["| Kind | " + " | ".join(summary) + " |", "|---|" + "---|" * len(summary)] + for kind in kinds: + cells = [_number(s["kinds"].get(kind)) for s in summary.values()] + lines.append(f"| {kind} | " + " | ".join(cells) + " |") + return lines + + +def _paired_markdown(paired: dict[str, dict[str, Any]]) -> list[str]: + """Render the paired comparison with baseline. + + @param paired (dict[str, dict[str, Any]]): the comparison per condition. + @return (list[str]): the table lines, empty without a comparison. + """ + if not paired: + return [] + lines = ["| Versus baseline | Questions | Better | Worse | Tied | Accuracy difference | 95% CI |", "|---" * 7 + "|"] + for condition, p in paired.items(): + lines.append( + f"| {condition} | {p['questions']} | {p['better']} | {p['worse']} | {p['tied']} " + f"| {_number(p['accuracy_difference'])} | {_interval(p['difference_ci'])} |" + ) + return ["", *lines] + + def markdown(result: dict[str, Any]) -> str: """Render the totals per condition as a markdown table, with lines for the judge and the graph build. @@ -104,17 +231,19 @@ def markdown(result: dict[str, Any]) -> str: """ summary = result["summary"] lines = [ - "| Condition | Runs | Accuracy | Correct | Partial | Wrong | Unscored | Mean s | p95 s | Input tokens " - "| Output tokens | Cost (USD) | Tool calls | Tool errors | Failures |", - "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|", + "| Condition | Runs | Accuracy | 95% CI | Correct | Partial | Wrong | Unscored | Mean s | p95 s " + "| Input tokens | Output tokens | Cost (USD) | Tool calls | Tool errors | Failures |", + "|---" * 16 + "|", ] for condition, s in summary.items(): cost = f"{s['cost']:.4f}" + ("" if s["cost_complete"] else " (partial)") lines.append( - f"| {condition} | {s['runs']} | {_number(s['accuracy'])} | {s['correct']} | {s['partial']} | {s['wrong']} " + f"| {condition} | {s['runs']} | {_number(s['accuracy'])} | {_interval(s['accuracy_ci'])} | {s['correct']} " + f"| {s['partial']} | {s['wrong']} " f"| {s['unscored']} | {_number(s['mean_seconds'])} | {_number(s['p95_seconds'])} | {s['input_tokens']} " f"| {s['output_tokens']} | {cost} | {s['tool_calls']} | {s['tool_errors']} | {s['failures']} |" ) + lines += ["", *_kinds_markdown(summary), *_paired_markdown(result.get("paired") or {})] judged = list(summary.values()) lines += [ "", @@ -132,6 +261,41 @@ def markdown(result: dict[str, Any]) -> str: return "\n".join(lines) +def _cell(text: Any) -> str: + """Make text safe for one markdown table cell. + + @param text (Any): the text. + @return (str): the text on one line with pipes escaped. + """ + return " ".join(str(text or "").split()).replace("|", "\\|") + + +def audit_markdown(runs: list[dict[str, Any]], questions: list[dict[str, Any]], count: int) -> str: + """Draw judged runs at random with a fixed seed for a person to grade beside the judge. + + @param runs (list[dict[str, Any]]): the run records. + @param questions (list[dict[str, Any]]): the questions with their gold answers. + @param count (int): how many runs to draw. + @return (str): the markdown table, with an empty human verdict column. + """ + by_id = {q["id"]: q for q in questions} + judged = [r for r in runs if r["judge_usage"]["calls"]] + drawn = random.Random(AUDIT_SEED).sample(judged, min(count, len(judged))) + lines = [ + f"# Judge audit\n\n{len(drawn)} judged runs drawn at random. Fill in the human verdict " + "(correct, partial, or wrong) by the rubric in scoring.py without looking at the judge column first.\n", + "| Run | Question | Gold answer | Answer | Judge verdict | Judge reason | Human verdict |", + "|---" * 7 + "|", + ] + for r in drawn: + question = by_id[r["question_id"]] + lines.append( + f"| {r['condition']} {r['question_id']} #{r['attempt']} | {_cell(question['question'])} " + f"| {_cell(question['answer'])} | {_cell(r['answer'])} | {r['verdict']} | {_cell(r['reason'])} | |" + ) + return "\n".join(lines) + "\n" + + def estimate_markdown(totals: dict[str, dict[str, Any]]) -> str: """Render the cost estimate as a markdown table. diff --git a/tests/test_agent_benchmark.py b/tests/test_agent_benchmark.py index d78b239e..30acd5a9 100644 --- a/tests/test_agent_benchmark.py +++ b/tests/test_agent_benchmark.py @@ -113,21 +113,34 @@ async def complete(self, model, messages, tools): argv = ["--model", "fake/agent", "--price", "1,10", "--estimate", "--results", str(tmp_path)] assert bench.main(argv, client=NoCalls()) == 0 - out = capsys.readouterr().out + captured = capsys.readouterr() + out = captured.out assert "| baseline |" in out and "| graph |" in out and "| judge |" in out assert "Estimated total:" in out and "for the priced rows" not in out assert not list(tmp_path.iterdir()) + assert captured.err.startswith("warning: the judge is the agent model") + + def output_tokens(text): + return int(next(line for line in text.splitlines() if line.startswith("| baseline |")).split("|")[3]) + + assert bench.main([*argv, "--repeats", "1"], client=NoCalls()) == 0 + once = output_tokens(capsys.readouterr().out) + assert output_tokens(out) == 3 * once def test_agent_benchmark_runs_both_conditions_and_reports(tmp_path, monkeypatch, capsys): bench = _bench(monkeypatch, "run") model = ScriptedModel(importlib.import_module("harness")) argv = ["--model", "fake/agent", "--judge", "fake/judge", "--questions", "2", "--results", str(tmp_path)] - argv += ["--price", "1,10", "--judge-price", "2,20"] + argv += ["--price", "1,10", "--judge-price", "2,20", "--audit", "4"] assert bench.main(argv, client=model) == 0 [path] = tmp_path.glob("*.json") + [audit] = tmp_path.glob("*-audit.md") + assert audit.name == path.stem + "-audit.md" + rows = [line for line in audit.read_text(encoding="utf-8").splitlines() if line.startswith("| ") and "#" in line] + assert len(rows) == 4 and all(row.endswith("| |") for row in rows) result = json.loads(path.read_text(encoding="utf-8")) facts = json.loads((BENCH / "data" / "facts.json").read_text(encoding="utf-8")) assert result["graph"]["counts"]["entities"] == len(facts["entities"]) @@ -136,7 +149,8 @@ def test_agent_benchmark_runs_both_conditions_and_reports(tmp_path, monkeypatch, assert model.offered == {"baseline": documents, "graph": documents + tools} graph_runs = [r for r in result["runs"] if r["condition"] == "graph"] - assert [r["answer"] for r in graph_runs] == ["Payments", "Ines Duarte"] + assert [r["answer"] for r in graph_runs] == ["Payments"] * 3 + ["Ines Duarte"] * 3 + assert [r["attempt"] for r in graph_runs] == [1, 2, 3, 1, 2, 3] calls = graph_runs[0]["tool_calls"] assert [c["name"] for c in calls] == ["get_entity", "check_answerable", "list_relations", "get_entity"] assert [c["ok"] for c in calls] == [False, True, True, True] @@ -145,17 +159,66 @@ def test_agent_benchmark_runs_both_conditions_and_reports(tmp_path, monkeypatch, assert [c["name"] for c in baseline_runs[0]["tool_calls"]] == ["search_documents", "read_document"] graph, baseline = result["summary"]["graph"], result["summary"]["baseline"] - assert (graph["correct"], graph["accuracy"], baseline["wrong"], baseline["accuracy"]) == (2, 1.0, 2, 0.0) + assert (graph["correct"], graph["accuracy"], baseline["wrong"], baseline["accuracy"]) == (6, 1.0, 6, 0.0) + assert (graph["accuracy_ci"], baseline["accuracy_ci"], graph["kinds"]) == ([1.0, 1.0], [0.0, 0.0], {"lookup": 1.0}) tokens = ("input_tokens", "output_tokens", "tool_calls", "tool_errors") - assert [graph[k] for k in tokens] == [1000, 100, 8, 2] - assert [baseline[k] for k in tokens] == [600, 60, 4, 0] - assert graph["cost"] == pytest.approx(0.002) and graph["cost_complete"] is True - assert baseline["cost"] == pytest.approx(0.0012) and graph["judge_cost"] == pytest.approx(0.0004) + assert [graph[k] for k in tokens] == [3000, 300, 24, 6] + assert [baseline[k] for k in tokens] == [1800, 180, 12, 0] + assert graph["cost"] == pytest.approx(0.006) and graph["cost_complete"] is True + assert baseline["cost"] == pytest.approx(0.0036) and graph["judge_cost"] == pytest.approx(0.0012) assert graph["failures"] == baseline["failures"] == 0 and graph["p95_seconds"] > 0 - - out = capsys.readouterr().out - assert out.index("| Estimate |") < out.index("| Condition |") - assert "| graph | 2 | 1.00 | 2 | 0 | 0 | 0 |" in out and "| 1000 | 100 | 0.0020 | 8 | 2 | 0 |" in out - assert "Judge: 200 input tokens, 20 output tokens, 0.0008 USD." in out + paired = {"questions": 2, "better": 2, "worse": 0, "tied": 0, "accuracy_difference": 1.0} + assert result["paired"] == {"graph": {**paired, "difference_ci": [1.0, 1.0]}} + + captured = capsys.readouterr() + out = captured.out + assert out.index("| Estimate |") < out.index("| Condition |") and not captured.err + assert "| graph | 6 | 1.00 | [1.00, 1.00] | 6 | 0 | 0 | 0 |" in out + assert "| 3000 | 300 | 0.0060 | 24 | 6 | 0 |" in out + assert "| lookup | 0.00 | 1.00 |" in out and "| graph | 2 | 2 | 0 | 0 | 1.00 | [1.00, 1.00] |" in out + assert "Judge: 600 input tokens, 60 output tokens, 0.0024 USD." in out assert f"{len(facts['entities'])} entities" in out and f"{len(tools)} read-only tools" in out - assert f"results: {path}" in out + assert f"results: {path}" in out and f"audit: {audit}" in out + + +def _run(condition, question, kind, verdict, attempt=1): + usage = {"input_tokens": 0, "output_tokens": 0, "cost": 0.0, "calls": 1} + record = {"condition": condition, "question_id": question, "kind": kind, "attempt": attempt, "verdict": verdict} + extra = {"seconds": 1.0, "failure": None, "tool_calls": [], "usage": usage, "judge_usage": usage} + return {**record, **extra, "answer": f"{question} answer", "reason": "ok"} + + +def test_agent_benchmark_pairs_conditions_per_question_with_seeded_intervals(monkeypatch): + scoring = _bench(monkeypatch, "scoring") + verdicts = { + "q1": ("lookup", ["correct", "wrong"], ["correct", "correct"]), + "q2": ("lookup", ["wrong", "wrong"], ["partial", "wrong"]), + "q3": ("temporal", ["correct", "correct"], ["wrong", "wrong"]), + "q4": ("temporal", ["partial", "wrong"], ["wrong", "partial"]), + } + runs = [ + _run(condition, q, kind, verdict, attempt) + for q, (kind, base, graph) in verdicts.items() + for condition, row in (("baseline", base), ("graph", graph)) + for attempt, verdict in enumerate(row, 1) + ] + + paired = scoring.compare(runs, ["baseline", "graph"])["graph"] + summary = scoring.summarize(runs, ["baseline", "graph"]) + + assert (paired["better"], paired["worse"], paired["tied"]) == (2, 1, 1) + assert paired["accuracy_difference"] == pytest.approx(-0.125) + low, high = paired["difference_ci"] + assert low < paired["accuracy_difference"] < high + assert paired == scoring.compare(list(reversed(runs)), ["baseline", "graph"])["graph"] + assert summary["graph"]["kinds"] == {"lookup": 0.5, "temporal": 0.0} + assert summary["baseline"]["kinds"] == {"lookup": 0.25, "temporal": 0.5} + assert summary["graph"]["accuracy_ci"] == scoring.bootstrap([1.0, 0.0, 0.0, 0.0]) + assert scoring.compare(runs, ["graph"]) == {} + + questions = [{"id": q, "question": f"What is {q}? a|b", "answer": f"gold\n{q}"} for q in verdicts] + audit = scoring.audit_markdown(runs, questions, 5) + assert audit == scoring.audit_markdown(runs, questions, 5) + rows = [line for line in audit.splitlines() if " #" in line] + assert len(rows) == 5 and len({r.split(" | ")[0] for r in rows}) == 5 + assert all("a\\|b" in r and r.endswith("| |") for r in rows)