Datasets:
File size: 20,170 Bytes
f36cc9a | 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 | """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)
|