Spaces:
Sleeping
Sleeping
Download eval/experiments.py from amitnaik07/beam-data-desk: direct link, hf CLI and curl.
- Browser
- Download file 7.57 kB
-
https://huggingface.co/spaces/amitnaik07/beam-data-desk/resolve/main/eval/experiments.py
- Command line
-
hf download hf://spaces/amitnaik07/beam-data-desk/eval/experiments.py
-
curl -L -o experiments.py https://huggingface.co/spaces/amitnaik07/beam-data-desk/resolve/main/eval/experiments.py
7.57 kB
| """Repeat runs and the GRR definition experiment (2026-10-31). | |
| python -m eval.experiments | |
| Reads the first sweep (results/combined/runs.jsonl) plus results/repeats/r{2,3}/ and results/definition/*/, and | |
| writes results/definition/SUMMARY.md and results/definition/summary.json. | |
| - Repeats: Beam medium and high ran the 20 hard tasks two more times, so each setting has three runs per task. | |
| - Definition: Beam high ran the 13 tasks that depend on gross revenue retention with one extra system-prompt | |
| paragraph, either the GRR rule ("grr_def") or a same-length definition of an unrelated metric ("placebo"), two | |
| runs each. Its baseline is the three base-prompt runs from the repeats. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import statistics | |
| import sys | |
| from math import comb | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent.parent | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from eval.report import cost # noqa: E402 | |
| RESULTS = ROOT / "results" | |
| OUT = RESULTS / "definition" | |
| HARD = [f"T{i}" for i in range(48, 68)] | |
| GRR = ["T48", "T49", "T50", "T52", "T54", "T56", "T58", "T60", "T62", "T64", "T65", "T66", "T67"] | |
| EFFORTS = ["medium", "high"] | |
| def _load(path: Path) -> list[dict]: | |
| if not path.exists(): | |
| return [] | |
| return [json.loads(l) for l in path.read_text().splitlines() if l.strip()] | |
| def _beam(rows: list[dict], effort: str, tasks: list[str]) -> dict[str, dict]: | |
| """-> {task_id: row} for Beam at one effort, skipping runs that failed on the provider side.""" | |
| return {r["task_id"]: r for r in rows | |
| if r["model"].startswith("reflection/") and r["effort"] == effort and r["task_id"] in tasks | |
| and not r.get("api_error") and not r.get("mock")} | |
| def exact_mcnemar(b: int, c: int) -> float: | |
| """Two-sided exact McNemar p-value for b vs c discordant pairs.""" | |
| n = b + c | |
| if n == 0: | |
| return 1.0 | |
| tail = sum(comb(n, i) for i in range(min(b, c) + 1)) / 2 ** n | |
| return min(1.0, 2 * tail) | |
| def _arm_stats(reps: list[dict[str, dict]], tasks: list[str]) -> dict: | |
| complete = [r for r in reps if all(t in r for t in tasks)] | |
| rows = [r[t] for r in complete for t in tasks] | |
| return { | |
| "runs": len(complete), | |
| "correct_per_run": [sum(r[t]["correct"] for t in tasks) for r in complete], | |
| "mean_correct": round(statistics.fmean(sum(r[t]["correct"] for t in tasks) for r in complete), 2) | |
| if complete else None, | |
| "mean_tool_calls": round(statistics.fmean(x["tool_calls"] for x in rows), 2) if rows else None, | |
| "mean_output_tokens": round(statistics.fmean(x["completion_tokens"] for x in rows)) if rows else None, | |
| "cost_per_run_usd": round(sum(cost(x) for x in rows) / len(complete), 3) if complete else None, | |
| "per_task": {t: sum(r[t]["correct"] for r in complete) for t in tasks}, | |
| } | |
| def _paired(a: list[dict[str, dict]], b: list[dict[str, dict]], tasks: list[str]) -> dict: | |
| """Pair run i of arm a with run i of arm b on the same task; count the discordant pairs.""" | |
| win = loss = 0 | |
| for ra, rb in zip(a, b): | |
| for t in tasks: | |
| if t in ra and t in rb and ra[t]["correct"] != rb[t]["correct"]: | |
| win += ra[t]["correct"] | |
| loss += rb[t]["correct"] | |
| return {"a_only": win, "b_only": loss, "p": round(exact_mcnemar(win, loss), 4)} | |
| def main() -> int: | |
| first = _load(RESULTS / "combined" / "runs.jsonl") | |
| reps = {e: [_beam(first, e, HARD)] + [_beam(_load(RESULTS / "repeats" / f"r{i}" / "runs.jsonl"), e, HARD) | |
| for i in (2, 3)] for e in EFFORTS} | |
| repeats = {e: _arm_stats(reps[e], HARD) for e in EFFORTS} | |
| for e in EFFORTS: | |
| pt = repeats[e]["per_task"] | |
| n = repeats[e]["runs"] | |
| repeats[e]["always_right"] = sum(v == n for v in pt.values()) | |
| repeats[e]["always_wrong"] = sum(v == 0 for v in pt.values()) | |
| repeats[e]["mixed"] = sum(0 < v < n for v in pt.values()) | |
| base = [{t: r[t] for t in GRR if t in r} for r in reps["high"]] | |
| arms = {"base": base} | |
| for name in ("grr_def", "placebo"): | |
| arms[name] = [_beam(_load(OUT / f"{name}_r{i}" / "runs.jsonl"), "high", GRR) for i in (1, 2)] | |
| definition = {k: _arm_stats(v, GRR) for k, v in arms.items()} | |
| tests = { | |
| "grr_def_vs_placebo": _paired(arms["grr_def"], arms["placebo"], GRR), | |
| "grr_def_vs_base": _paired(arms["grr_def"], arms["base"], GRR), | |
| "placebo_vs_base": _paired(arms["placebo"], arms["base"], GRR), | |
| } | |
| misses = {k: sorted({t for r in v for t in GRR if t in r and not r[t]["correct"]}) for k, v in arms.items()} | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| summary = {"repeats": repeats, "definition": definition, "tests": tests, "misses": misses} | |
| (OUT / "summary.json").write_text(json.dumps(summary, indent=2)) | |
| (OUT / "SUMMARY.md").write_text(render(summary)) | |
| print(render(summary)) | |
| return 0 | |
| def _fmt_runs(s: dict, n: int) -> str: | |
| if not s["runs"]: | |
| return "not run" | |
| rng = f"{min(s['correct_per_run'])}-{max(s['correct_per_run'])}" | |
| return f"{s['mean_correct']:g} of {n} (runs: {', '.join(map(str, s['correct_per_run']))}; range {rng})" | |
| def render(s: dict) -> str: | |
| rp, d, t = s["repeats"], s["definition"], s["tests"] | |
| lines = ["# Repeat runs and the GRR definition experiment", "", | |
| "Generated by `python -m eval.experiments`. Beam 1.0 on Baseten, agent limit 24 steps.", "", | |
| "## Repeats: Beam on the 20 hard tasks, three runs each", "", | |
| "| Effort | Correct (of 20) | Always right | Always wrong | Mixed | Avg tool calls | Cost per 20-task sweep |", | |
| "|---|---|---|---|---|---|---|"] | |
| for e in EFFORTS: | |
| x = rp[e] | |
| lines.append(f"| {e} | {_fmt_runs(x, 20)} | {x['always_right']} | {x['always_wrong']} | {x['mixed']} | " | |
| f"{x['mean_tool_calls']} | ${x['cost_per_run_usd']} |") | |
| lines += ["", "## Definition: Beam high on the 13 GRR tasks", "", | |
| "`base` is the normal system prompt (the three runs above). `grr_def` adds one paragraph stating the " | |
| "per-account GRR rule. `placebo` adds a paragraph of about the same length defining average days to " | |
| "pay, which no task asks about.", "", | |
| "| Prompt | Correct (of 13) | Avg tool calls | Avg output tokens | Cost per 13-task sweep |", | |
| "|---|---|---|---|---|"] | |
| for k in ("base", "grr_def", "placebo"): | |
| x = d[k] | |
| lines.append(f"| {k} | {_fmt_runs(x, 13)} | {x['mean_tool_calls']} | {x['mean_output_tokens']} | " | |
| f"${x['cost_per_run_usd']} |") | |
| lines += ["", "Paired comparison (run i of one arm against run i of the other, same task; exact McNemar):", ""] | |
| for k, v in t.items(): | |
| a, b = k.split("_vs_") | |
| lines.append(f"- {a} vs {b}: {a} right and {b} wrong {v['a_only']} times, the reverse {v['b_only']} " | |
| f"times, p = {v['p']}") | |
| lines += ["", "Tasks missed at least once:", ""] | |
| for k, v in s["misses"].items(): | |
| lines.append(f"- {k}: {', '.join(v) if v else 'none'}") | |
| lines += ["", "Per task (runs correct):", "", "| Task | base | grr_def | placebo |", "|---|---|---|---|"] | |
| for task in GRR: | |
| lines.append(f"| {task} | " + " | ".join(f"{d[k]['per_task'].get(task, 0)}/{d[k]['runs']}" | |
| for k in ("base", "grr_def", "placebo")) + " |") | |
| return "\n".join(lines) + "\n" | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |