Official Codebase of 3DCodeVerse
Python
bestofk: derive k from the data — my first k was too small, in the harness's favour
ziyao97c9382fbea0
diff --git a/harness/bench/bestofk_report.py b/harness/bench/bestofk_report.pyindex ad48774a..4c8cde55 100644--- a/harness/bench/bestofk_report.py+++ b/harness/bench/bestofk_report.py@@ -1,9 +1,15 @@"""Is the harness better than sampling k times for the same money?The reviewer question a harness paper has to answer: a loop that plans, builds, gates and-refines costs ~28x one raw generation on `compare_v4` (median generation cost $0.9221-against $0.0327). Spend that money on 28 independent one-shot samples and keep the best —-does the harness still win?+refines costs many times one raw generation. Spend that money on k independent one-shot+samples instead and keep the best — does the harness still win?++**k is computed from the recorded battery, not written down here.** A first pass took the+median generation cost over every appended row per arm and got 28; taken the way+`paired_compare` builds pairs — LAST row per prompt — the harness costs $1.4675 against+one-shot's $0.0365, so equal compute is 40. Understating k gives the baseline less money+than the harness, and that error runs in the harness's favour, so the ratio is derived+here and printed with the table.python bench/bestofk_report.py bench/out/bestofk --against bench/out/compare_v4@@ -15,7 +21,7 @@ so those rows are the arm the paper reports.**The winner's curse is reported, not hidden.** max() over k noisy scores overestimatesthe true best by roughly `sigma * sqrt(2 ln k)`; with the pro judge's sigma = 0.030-(PAPER_WRITING §2) that is +0.078 at k = 28. The bias runs AGAINST the harness, so a+(PAPER_WRITING §2) that is about +0.08 at k = 40. The bias runs AGAINST the harness, so aharness win that survives it is the conservative reading; a harness loss inside that bandis not a loss."""@@ -65,6 +71,26 @@ def harness_scores(root: Path, *, arm_prefix: str = "harness:") -> dict[str, floreturn out+def gen_costs(root: Path, arm_prefix: str) -> list[float]:+ """Generation cost per PROMPT for an arm — last row per prompt, the basis+ `paired_compare` pairs on. Taken over every appended row instead, resumed and failed+ cells drag the median down and the equal-compute k comes out too small."""+ last: dict[str, float] = {}+ for r in _rows(root / "results.jsonl"):+ if str(r.get("arm", "")).startswith(arm_prefix):+ last[r["prompt_id"]] = float(r.get("gen_cost_usd") or 0.0)+ return [v for v in last.values() if v > 0]+++def equal_compute_k(root: Path, baseline_prefix: str) -> tuple[float, float, int] | None:+ """``(harness $, baseline $, k)`` — how many baseline samples the harness's money buys."""+ h, b = gen_costs(root, "harness:"), gen_costs(root, baseline_prefix)+ if not h or not b:+ return None+ hm, bm = statistics.median(h), statistics.median(b)+ return hm, bm, max(1, round(hm / bm))++def best_of(samples: list[float], k: int) -> float | None:"""Best of the FIRST k samples — the reps are independent and unordered, so this isone draw of best-of-k rather than the best over everything available."""@@ -90,14 +116,20 @@ def curve(one: dict[str, list[float]], harness: dict[str, float], ks: list[int])return out-def report(root: Path, against: Path) -> str:+def report(root: Path, against: Path, *, baseline_prefix: str = "oneshot:") -> str:one = one_shot_samples(root)harness = harness_scores(against)if not one or not harness:return f"nothing to compare: {len(one)} prompts sampled, {len(harness)} harness rows"reps = max(len(v) for v in one.values())- ks = [k for k in (1, 2, 4, 8, 16, 28) if k <= reps]- lines = [f"# harness vs best-of-k one-shot — {len(one)} prompts, up to {reps} reps", "",+ eq = equal_compute_k(against, baseline_prefix)+ ks = sorted({k for k in (1, 2, 4, 8, 16, 32) if k <= reps} | ({eq[2]} if eq and eq[2] <= reps else set()))+ lines = [f"# harness vs best-of-k {baseline_prefix.rstrip(':')} — {len(one)} prompts, up to {reps} reps", ""]+ if eq:+ mark = "reached" if eq[2] <= reps else f"NOT reached yet — {reps} of {eq[2]} reps"+ lines += [f"Equal compute: harness ${eq[0]:.4f} per prompt against ${eq[1]:.4f}, so **k = {eq[2]}** ({mark}).",+ "Costs are the last row per prompt, the basis `paired_compare` pairs on.", ""]+ lines += [f"Winner's-curse bound: judge sigma {JUDGE_SIGMA:.3f}, so a best-of-k maximum carries","about `sigma*sqrt(2 ln k)` of selection noise. It inflates the BASELINE, never the harness.","", "| k | n | best-of-k | harness | harness − best-of-k | 95 % CI | W/L | curse bound |",@@ -116,8 +148,11 @@ def main(argv: list[str] | None = None) -> int:ap.add_argument("root", type=Path, help="directory holding rep*/results.jsonl")ap.add_argument("--against", type=Path, required=True, help="recorded battery with the harness arm")ap.add_argument("--out", type=Path)+ ap.add_argument("--baseline", default="oneshot:",+ help="arm prefix in the recorded battery whose cost sets equal compute "+ "(oneshot: | oneshot+repair:) — must match what the reps generated")ns = ap.parse_args(argv)- text = report(ns.root, ns.against)+ text = report(ns.root, ns.against, baseline_prefix=ns.baseline)print(text)if ns.out:ns.out.write_text(text)diff --git a/harness/tests/compare_bench/test_bestofk_report.py b/harness/tests/compare_bench/test_bestofk_report.pyindex 526e049c..67fea5b5 100644--- a/harness/tests/compare_bench/test_bestofk_report.py+++ b/harness/tests/compare_bench/test_bestofk_report.py@@ -19,6 +19,8 @@ from bench.bestofk_report import (JUDGE_SIGMA,best_of,curve,+ equal_compute_k,+ gen_costs,harness_scores,one_shot_samples,report,@@ -90,3 +92,48 @@ def test_a_prompt_the_harness_never_ran_is_not_paired(tmp_path: Path):assert rows[0]["n"] == 1, "only prompts both arms ran are a pair"text = report(tmp_path / "reps", tmp_path)assert "| 1 | 1 |" in text+++def test_equal_compute_k_is_taken_per_prompt_not_per_row(tmp_path: Path):+ """k is the whole experiment's parameter, and the first pass got it wrong: taking the+ median over every appended row (resumed cells, failed cells) gave 28 where the per-prompt+ basis — the one `paired_compare` pairs on — gives 40. Understating k gives the baseline+ less money than the harness, an error in the harness's favour."""+ rows = [+ # prompt a: a cheap failed first attempt, then the real one. Per row the median+ # would be dragged down; per prompt only the last row counts.+ {"prompt_id": "a", "arm": "harness:x", "gen_cost_usd": 0.10},+ {"prompt_id": "a", "arm": "harness:x", "gen_cost_usd": 2.00},+ {"prompt_id": "b", "arm": "harness:x", "gen_cost_usd": 2.00},+ {"prompt_id": "a", "arm": "oneshot:x", "gen_cost_usd": 0.05},+ {"prompt_id": "b", "arm": "oneshot:x", "gen_cost_usd": 0.05},+ ]+ (tmp_path / "results.jsonl").write_text("\n".join(json.dumps(r) for r in rows))++ assert sorted(gen_costs(tmp_path, "harness:")) == [2.00, 2.00], "last row per prompt"+ h, b, k = equal_compute_k(tmp_path, "oneshot:")+ assert (h, b, k) == (2.00, 0.05, 40)+++def test_a_zero_cost_row_is_not_counted_as_free(tmp_path: Path):+ """A row with no recorded generation cost is missing data, not a free sample; averaging+ it in would inflate k without bound."""+ rows = [+ {"prompt_id": "a", "arm": "oneshot:x", "gen_cost_usd": 0.05},+ {"prompt_id": "b", "arm": "oneshot:x", "gen_cost_usd": 0},+ {"prompt_id": "c", "arm": "oneshot:x"},+ ]+ (tmp_path / "results.jsonl").write_text("\n".join(json.dumps(r) for r in rows))+ assert gen_costs(tmp_path, "oneshot:") == [0.05]+++def test_the_report_says_when_k_has_not_been_reached(tmp_path: Path):+ """A curve that stops short of equal compute answers a different question, so the table+ says so instead of letting the last row read as the verdict."""+ _rep(tmp_path / "reps", "rep01", {"a": 0.2})+ (tmp_path / "results.jsonl").write_text("\n".join(json.dumps(r) for r in [+ {"prompt_id": "a", "arm": "harness:x", "score": 0.6, "gen_cost_usd": 2.00},+ {"prompt_id": "a", "arm": "oneshot:x", "score": 0.1, "gen_cost_usd": 0.05},+ ]))+ text = report(tmp_path / "reps", tmp_path)+ assert "**k = 40**" in text and "NOT reached yet — 1 of 40 reps" in text