Datasets:
Download code/build_tables.py from Boesgaard/delivered-sooner: direct link, hf CLI and curl.
- Browser
- Download file 20.2 kB
-
https://huggingface.co/datasets/Boesgaard/delivered-sooner/resolve/main/code/build_tables.py
- Command line
-
hf download hf://datasets/Boesgaard/delivered-sooner/code/build_tables.py
-
curl -L -o build_tables.py https://huggingface.co/datasets/Boesgaard/delivered-sooner/resolve/main/code/build_tables.py
20.2 kB
| """Build the curated tables (panels/, results/, readouts/) from the experiment records in records/. | |
| uv run --no-project --with pandas --with pyarrow --with zstandard python code/build_tables.py | |
| Every count the paper prints for these tables is asserted at the end, so a successful run reproduces them. | |
| The script only reads records/ and writes panels/, results/ and readouts/. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import sys | |
| from pathlib import Path | |
| import pandas as pd | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from common import ARMS, MODELS, RECORDS, ROOT, SHORTERBETTER_MODELS, STRATA, iter_jsonl, read_json, same, source_dataset # noqa: E402 | |
| B8K = 8192 | |
| def write(df: pd.DataFrame, rel: str): | |
| out = ROOT / rel | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| df.to_parquet(out, index=False) | |
| print(f"{rel}: {len(df)} rows") | |
| def as_bool(v): | |
| if isinstance(v, str): | |
| return v == "True" | |
| return bool(v) | |
| # ------------------------------------------------------------------------------------------------ panels | |
| def panel_frame(path: Path, name: str, extra=None) -> pd.DataFrame: | |
| rows = [] | |
| for order, r in enumerate(iter_jsonl(path)): | |
| src = source_dataset(r["id"]) | |
| rows.append({"panel": name, "panel_order": order, "question_id": r["id"], "stratum": r["area"], | |
| "stratum_source": STRATA.get(r["area"], r["area"]), "source_dataset": src["source_dataset"], | |
| "hf_dataset": src["hf_dataset"], "source_split": src["split"], "source_key": src["source_key"], | |
| "seed": int(r["seed"]), "sample": int(r.get("sample", 0))}) | |
| df = pd.DataFrame(rows) | |
| if extra: | |
| extra(df) | |
| return df | |
| def panels(): | |
| main = panel_frame(RECORDS / "confirmation256/panel.jsonl", "main256", | |
| lambda d: d.insert(len(d.columns), "readout_designated", d["panel_order"] < 64)) | |
| rep = panel_frame(RECORDS / "replication512/panel.jsonl", "replication512", | |
| lambda d: d.insert(len(d.columns), "in_readout_panel", d["panel_order"] < 256)) | |
| readout = rep[rep["in_readout_panel"]].drop(columns="in_readout_panel").assign(panel="readout256") | |
| comp = panel_frame(RECORDS / "agenda/competition64_panel.jsonl", "competition64") | |
| comp["contest"] = comp["question_id"].str.split("__").str[0] | |
| sb = panel_frame(RECORDS / "independent_lineage/math128_panel.jsonl", "shorterbetter_math128") | |
| jm = panel_frame(RECORDS / "portable_qwick_japanese/panel.jsonl", "jmmlu128") | |
| jm["stratum_source"] = "JMMLU (" + jm["stratum"] + ")" | |
| # consistency: the readout subset of the 64 designated main questions, the 256 readout questions, the disjointness | |
| designated = {r["id"] for r in iter_jsonl(RECORDS / "confirm_baseline/readout_subset_base/scored/traces.scored.jsonl")} | |
| assert designated == set(main.loc[main.readout_designated, "question_id"]) | |
| rep_readout = {r["id"] for r in iter_jsonl(RECORDS / "replicate_baseline/readout_subset_base/scored/traces.scored.jsonl")} | |
| assert rep_readout == set(readout["question_id"]) | |
| assert not set(main.question_id) & set(rep.question_id) | |
| assert set(comp.question_id) == set(main.loc[main.stratum == "hardmath", "question_id"]) | |
| assert set(sb.question_id) <= set(main.question_id) | |
| for df, name in [(main, "main256"), (rep, "replication512"), (readout, "readout256"), (comp, "competition64"), | |
| (sb, "shorterbetter_math128"), (jm, "jmmlu128")]: | |
| write(df, f"panels/{name}.parquet") | |
| return main, rep | |
| # ----------------------------------------------------------------------------------------------- results | |
| def scored_frame(experiment: str, arm: str) -> pd.DataFrame: | |
| run, stem, scored = ARMS[experiment][arm] | |
| rows = [] | |
| for r in iter_jsonl(RECORDS / run / "scored" / scored): | |
| native = int(r["native_generated_tokens"]) | |
| natural_correct = int(r["native_correct_v2"]) | |
| model = SHORTERBETTER_MODELS.get(arm, MODELS[arm]) if experiment.startswith("shorterbetter") else MODELS[arm] | |
| rows.append({ | |
| "experiment": experiment, "arm": arm, "model": model, "question_id": r["id"], "stratum": r["area"], | |
| "seed": int(r["seed"]), "token_budget": int(r["max_new_tokens"]), | |
| "generated_tokens": int(r["generated_tokens"]), "native_generated_tokens": native, | |
| "forced_generated_tokens": int(r["forced_generated_tokens"]), "thinking_tokens": int(r["thinking_tokens"]), | |
| "natural_completion": as_bool(r["natural_completion"]), | |
| "hit_token_budget": r["native_finish_reason"] == "length", | |
| "forced_answer_used": as_bool(r["forced"]), | |
| "natural_correct": bool(natural_correct), "final_correct": bool(int(r["correct_v2"])), | |
| "final_correct_alt_scorer": bool(int(r["correct_v3"])), | |
| "natural_correct_by_8192": bool(natural_correct) and native <= B8K, | |
| "final_answer_key": r.get("answer_key"), "text_sha256": r["text_sha256"], | |
| "trace_file": f"records/{run}/{stem}.jsonl.zst", | |
| }) | |
| return pd.DataFrame(rows) | |
| def results(): | |
| out = {} | |
| for experiment in ARMS: | |
| df = pd.concat([scored_frame(experiment, arm) for arm in ARMS[experiment]], ignore_index=True) | |
| out[experiment] = df | |
| write(df, f"results/{experiment}.parquet") | |
| # registered 768-question accuracy test: the 256-question panel and the 512 new questions, parent vs all-32 | |
| a = out["main256_32k"][out["main256_32k"].arm.isin(["parent", "transplant_all32"])].assign(cohort="main256") | |
| b = out["replication512_32k"].assign(cohort="replication512") | |
| acc = pd.concat([a, b], ignore_index=True) | |
| acc.insert(0, "test", "accuracy768") | |
| write(acc, "results/accuracy768.parquet") | |
| out["accuracy768"] = acc | |
| return out | |
| def qwick(): | |
| rows = [] | |
| for arm, folder, stem in [("qwick_recipient", "recipient", "child_qwick"), ("qwick_patched", "patch", "child_qwick_mlp_patch")]: | |
| think = {} | |
| for r in iter_jsonl(RECORDS / f"portable_qwick_japanese/{folder}/{stem}.jsonl.zst"): | |
| ids = r["native_token_ids"] | |
| think[r["id"]] = ids.index(248069) if 248069 in ids else len(ids) | |
| for s in read_json(RECORDS / f"portable_qwick_japanese/scoring_transport/{'patch' if folder == 'patch' else 'recipient'}.json"): | |
| rows.append({"experiment": "jmmlu128_8k", "arm": arm, | |
| "model": "Qwick-3.5-9B" + (" with the Concise-9B MLP update installed" if folder == "patch" else ""), | |
| "question_id": s["id"], "stratum": s["area"], "token_budget": B8K, | |
| "generated_tokens": int(s["sampled"]), "thinking_tokens": think[s["id"]], | |
| "natural_completion": bool(s["natural_completion"]), "forced_answer_used": bool(s["forced"]), | |
| "requested_format_correct": bool(s["strict_final"]), "requested_format_valid": bool(s["strict_valid"]), | |
| "committed_letter_correct": bool(s["terminal_final"]), "committed_letter": s["terminal_answer"], | |
| "trace_file": f"records/portable_qwick_japanese/{folder}/{stem}.jsonl.zst"}) | |
| df = pd.DataFrame(rows) | |
| write(df, "results/jmmlu128_8k_qwick.parquet") | |
| return df | |
| # ---------------------------------------------------------------------------------------------- readouts | |
| def readout_rows(path: Path, readout_set: str, arm: str): | |
| return [{"readout_set": readout_set, "arm": arm, "question_id": r["id"], "cut_thinking_tokens": int(r["t"]), | |
| "readout_correct": bool(int(r["correct_v2"])), "readout_has_answer": as_bool(r["has_answer"]), | |
| "readout_answer_key": r.get("answer_key"), "readout_generated_tokens": int(r["generated_tokens"]), | |
| "readout_finish_reason": r["finish_reason"]} for r in iter_jsonl(path)] | |
| def readouts(res): | |
| rows = [] | |
| for arm, (run, stem, _) in ARMS["main256_32k"].items(): | |
| rows += readout_rows(RECORDS / run / f"readout_subset_{stem}/scored/readouts.scored.jsonl", "main256_first64", arm) | |
| for side, arm in (("B", "parent"), ("F", "transplant_all32")): | |
| rows += readout_rows(RECORDS / f"full256_stability/{side}/scored_probes.jsonl", "main256_full_grid", arm) | |
| for arm, (run, stem, _) in ARMS["replication512_32k"].items(): | |
| rows += readout_rows(RECORDS / run / f"readout_subset_{stem}/scored/readouts.scored.jsonl", "readout256", arm) | |
| ro = pd.DataFrame(rows).sort_values(["readout_set", "arm", "question_id", "cut_thinking_tokens"], ignore_index=True) | |
| write(ro, "readouts/forced_readouts.parquet") | |
| # stabilization points and available/delivered flags | |
| stab = [] | |
| sets = [("main256_first64", "main256_32k", list(ARMS["main256_32k"]), "legacy"), | |
| ("main256_full_grid", "main256_32k", ["parent", "transplant_all32"], "full"), | |
| ("readout256", "replication512_32k", ["parent", "transplant_all32"], "legacy")] | |
| for readout_set, experiment, arms, grid in sets: | |
| for arm in arms: | |
| sc = res[experiment][res[experiment].arm == arm].set_index("question_id") | |
| sub = ro[(ro.readout_set == readout_set) & (ro.arm == arm)] | |
| pipeline = {} | |
| if readout_set != "main256_full_grid": | |
| run, stem, _ = ARMS[experiment][arm] | |
| for r in iter_jsonl(RECORDS / run / f"readout_subset_{stem}/scored/traces.scored.jsonl"): | |
| pipeline[r["id"]] = int(r["answer_fixed_tokens"]) | |
| for qid, g in sub.groupby("question_id"): | |
| s = sc.loc[qid] | |
| t = int(s.thinking_tokens) | |
| probes = {int(c): (rc, rk) for c, rc, rk in zip(g.cut_thinking_tokens, g.readout_correct, g.readout_answer_key)} | |
| cuts = sorted(probes) | |
| legacy = list(range(2048, t - 1024, 2048)) | |
| fixed, matched = t, False | |
| for c in reversed(cuts): | |
| if not same(s.final_correct, s.final_answer_key, *probes[c]): | |
| break | |
| fixed, matched = c, True | |
| done = s.native_generated_tokens if s.natural_correct else math.inf | |
| known = min([done] + [c for c in legacy if c in probes and probes[c][0]]) | |
| stab.append({"readout_set": readout_set, "experiment": experiment, "arm": arm, "question_id": qid, | |
| "stratum": s.stratum, "thinking_tokens": t, "final_correct": bool(s.final_correct), | |
| "n_readouts": len(cuts), "grid": grid, "terminal_run_found": matched, | |
| "stabilization_point": fixed, "post_stability_thinking_tokens": t - fixed, | |
| "pipeline_stabilization_point": pipeline.get(qid), | |
| "available_by_8192": known <= B8K if readout_set != "main256_first64" else None, | |
| "delivered_by_8192": done <= B8K if readout_set != "main256_first64" else None}) | |
| # questions without any readout (too short for an interior cut) are stable at their full length | |
| for qid in set(pipeline) - set(sub.question_id): | |
| s = sc.loc[qid] | |
| t = int(s.thinking_tokens) | |
| done = s.native_generated_tokens if s.natural_correct else math.inf | |
| flag = done <= B8K if readout_set != "main256_first64" else None | |
| stab.append({"readout_set": readout_set, "experiment": experiment, "arm": arm, "question_id": qid, | |
| "stratum": s.stratum, "thinking_tokens": t, "final_correct": bool(s.final_correct), | |
| "n_readouts": 0, "grid": grid, "terminal_run_found": False, "stabilization_point": t, | |
| "post_stability_thinking_tokens": 0, "pipeline_stabilization_point": pipeline[qid], | |
| "available_by_8192": flag, "delivered_by_8192": flag}) | |
| st = pd.DataFrame(stab) | |
| # questions of the full-grid and readout-256 sets that had no probe at all still count for available/delivered | |
| for readout_set, experiment, n in (("main256_full_grid", "main256_32k", 256), ("readout256", "replication512_32k", 256)): | |
| for arm in ("parent", "transplant_all32"): | |
| have = set(st[(st.readout_set == readout_set) & (st.arm == arm)].question_id) | |
| sc = res[experiment][res[experiment].arm == arm].set_index("question_id") | |
| want = set(read_panel_ids(readout_set)) | |
| extra = [] | |
| for qid in sorted(want - have): | |
| s = sc.loc[qid] | |
| done = s.native_generated_tokens if s.natural_correct else math.inf | |
| extra.append({"readout_set": readout_set, "experiment": experiment, "arm": arm, "question_id": qid, | |
| "stratum": s.stratum, "thinking_tokens": int(s.thinking_tokens), "final_correct": bool(s.final_correct), | |
| "n_readouts": 0, "grid": "full" if readout_set == "main256_full_grid" else "legacy", | |
| "terminal_run_found": False, "stabilization_point": int(s.thinking_tokens), | |
| "post_stability_thinking_tokens": 0, "pipeline_stabilization_point": None, | |
| "available_by_8192": done <= B8K, "delivered_by_8192": done <= B8K}) | |
| st = pd.concat([st, pd.DataFrame(extra)], ignore_index=True) if extra else st | |
| assert len(st[(st.readout_set == readout_set) & (st.arm == arm)]) == n, (readout_set, arm) | |
| st = st.sort_values(["readout_set", "arm", "question_id"], ignore_index=True) | |
| for col in ("available_by_8192", "delivered_by_8192", "terminal_run_found", "final_correct"): | |
| st[col] = st[col].map(lambda v: None if v is None else bool(v)).astype("boolean") | |
| st["pipeline_stabilization_point"] = st["pipeline_stabilization_point"].astype("Int64") | |
| write(st, "readouts/stabilization.parquet") | |
| return ro, st | |
| _PANEL_CACHE = {} | |
| def read_panel_ids(readout_set): | |
| if readout_set not in _PANEL_CACHE: | |
| if readout_set == "main256_full_grid": | |
| _PANEL_CACHE[readout_set] = [r["id"] for r in iter_jsonl(RECORDS / "confirmation256/panel.jsonl")] | |
| else: | |
| _PANEL_CACHE[readout_set] = [r["id"] for r in iter_jsonl(RECORDS / "replication512/panel.jsonl")][:256] | |
| return _PANEL_CACHE[readout_set] | |
| # ----------------------------------------------------------------------------------------- paper checks | |
| def checks(res, qw, st): | |
| m = res["main256_32k"].groupby("arm") | |
| expect = { # arm: sampled, thinking, natural, final, at cap, natural correct by 8K (paper Tables 2, 5 and Table 1) | |
| "parent": (15932, 15181, 186, 199, 35, 63), "transplant_all32": (11961, 11120, 196, 203, 22, 112), | |
| "transplant_late16": (12554, 11722, 190, 196, 21, 103), "donor": (11165, 10262, 202, 206, 16, 122), | |
| "reverse_all32": (14816, 14008, 192, 199, 24, 74), "activation_edit": (16068, 15310, 187, 202, 37, None), | |
| "random_direction": (16271, 15526, 181, 204, 41, None)} | |
| for arm, (gen, think, nat, fin, cap, by8k) in expect.items(): | |
| g = m.get_group(arm) | |
| got = (round(g.generated_tokens.mean()), round(g.thinking_tokens.mean()), g.natural_correct.sum(), | |
| g.final_correct.sum(), g.hit_token_budget.sum(), g.natural_correct_by_8192.sum()) | |
| assert got[:5] == (gen, think, nat, fin, cap) and (by8k is None or got[5] == by8k), (arm, got) | |
| sums = m.generated_tokens.sum() | |
| assert (sums["parent"], sums["transplant_all32"], sums["transplant_late16"], sums["donor"], sums["reverse_all32"]) == ( | |
| 4078679, 3061916, 3213722, 2858154, 3792909) | |
| acc = res["accuracy768"].groupby("arm") | |
| p, t = acc.get_group("parent"), acc.get_group("transplant_all32") | |
| assert len(p) == len(t) == 768 and (p.natural_correct.sum(), t.natural_correct.sum()) == (552, 594) | |
| assert round(100 * (t.final_correct.sum() - p.final_correct.sum()) / 768, 2) == 1.69 | |
| assert round(100 * (1 - t.generated_tokens.sum() / p.generated_tokens.sum()), 2) == 24.35 | |
| e = res["main256_8k"].groupby("arm") | |
| base = e.get_group("parent") | |
| assert (base.natural_correct.sum(), base.final_correct.sum(), base.generated_tokens.sum()) == (71, 177, 1841483) | |
| saving = lambda arm: round(100 * (1 - e.get_group(arm).generated_tokens.sum() / base.generated_tokens.sum()), 2) # noqa: E731 | |
| assert saving("dial_plus1") == 8.81 and saving("dial_plus2") == 12.78 and saving("placement_late16") == 7.52 | |
| assert saving("placement_exact_count_spread") == 4.79 | |
| assert [e.get_group(a).natural_correct.sum() for a in ("dial_plus1", "dial_plus2", "dial_minus1")] == [107, 114, 72] | |
| assert [e.get_group(a).final_correct.sum() for a in ("dial_plus1", "dial_plus2", "dial_minus1", "placement_late16", | |
| "placement_exact_count_spread")] == [178, 175, 163, 176, 179] | |
| neo = e.get_group("neo_patched").generated_tokens.sum() / e.get_group("neo_recipient").generated_tokens.sum() - 1 | |
| assert round(100 * neo, 2) == 1.31 | |
| c = res["competition64_64k"].groupby("arm") | |
| for arm, (mean_gen, nat, fin, cap) in {"parent": (34543, 51, 53, 7), "dial_plus1": (24832, 51, 51, 3), | |
| "dial_minus1": (44335, 43, 45, 17)}.items(): | |
| g = c.get_group(arm) | |
| assert (round(g.generated_tokens.mean()), g.natural_correct.sum(), g.final_correct.sum(), g.hit_token_budget.sum()) == ( | |
| mean_gen, nat, fin, cap), arm | |
| by32k = c.get_group("parent") | |
| assert (by32k.natural_correct & (by32k.native_generated_tokens <= 32768)).sum() == 34 | |
| s = res["shorterbetter_math128"].groupby("arm") | |
| assert [s.get_group(a).final_correct.sum() for a in ("parent", "transplant_all", "donor")] == [65, 48, 36] | |
| q = qw.groupby("arm") | |
| assert (q.get_group("qwick_recipient").requested_format_correct.sum(), q.get_group("qwick_patched").requested_format_correct.sum()) == (86, 69) | |
| assert (q.get_group("qwick_recipient").committed_letter_correct.sum(), q.get_group("qwick_patched").committed_letter_correct.sum()) == (108, 109) | |
| qs = 1 - q.get_group("qwick_patched").thinking_tokens.sum() / q.get_group("qwick_recipient").thinking_tokens.sum() | |
| assert round(100 * qs, 1) == 15.3 | |
| # available versus delivered by 8,192 tokens: 183/182 and 63/112 (main), 184/184 and 81/120 (readout panel) | |
| for readout_set, want in (("main256_full_grid", (183, 182, 63, 112)), ("readout256", (184, 184, 81, 120))): | |
| g = st[st.readout_set == readout_set].groupby("arm") | |
| got = (g.get_group("parent").available_by_8192.sum(), g.get_group("transplant_all32").available_by_8192.sum(), | |
| g.get_group("parent").delivered_by_8192.sum(), g.get_group("transplant_all32").delivered_by_8192.sum()) | |
| assert got == want, (readout_set, got) | |
| # post-stability share on the full grid: 76% of the transplant's thinking saving came after stabilization | |
| g = st[st.readout_set == "main256_full_grid"].pivot(index="question_id", columns="arm") | |
| post = (g.post_stability_thinking_tokens.parent - g.post_stability_thinking_tokens.transplant_all32).sum() | |
| total = (g.thinking_tokens.parent - g.thinking_tokens.transplant_all32).sum() | |
| assert round(100 * post / total) == 76 | |
| # readout panel: 3,754 fewer post-stability thinking tokens per question | |
| g = st[st.readout_set == "readout256"].pivot(index="question_id", columns="arm") | |
| assert round((g.post_stability_thinking_tokens.parent - g.post_stability_thinking_tokens.transplant_all32).mean()) == 3754 | |
| # first-64 subset: parent 17,208 thinking tokens on average, 9,258 after stabilization (pipeline points) | |
| f = st[(st.readout_set == "main256_first64") & (st.arm == "parent")] | |
| assert round(f.thinking_tokens.mean()) == 17208 | |
| assert round((f.thinking_tokens - f.pipeline_stabilization_point).mean(), 1) == 9257.5 | |
| print("all paper checks passed") | |
| if __name__ == "__main__": | |
| panels() | |
| res = results() | |
| qw = qwick() | |
| ro, st = readouts(res) | |
| checks(res, qw, st) | |