"""Top-of-README summaries: role-labelled solver scores, paired differences against three judges, and highlights. Global context: `report.build()` calls these helpers and writes their markdown into the HIGHLIGHTS and RESULTS regions of README.md. Every number below is read from results files; nothing here is typed by hand. """ from collections import namedtuple from math import sqrt from statistics import NormalDist, mean from .design import GITHUB from .learnability_analysis import paired_change from .storage import rows from .tables import markdown # One solver arm in the summary table. `family` names the judge model, `role` its place in the design. Arm = namedtuple("Arm", "family role key label") FAMILIES = {"frozen": "Frozen Qwen3.5-4B judges", "original": "Qwen2.5-1.5B-Instruct judges"} # Roles follow reports/planned-runs.md: D3 is the treatment, shallower chains and flat votes are baselines, # the untrained, exact and shuffled rewards are controls, and the gated or pre-trained judge stacks are ablations. ARMS = ( Arm("frozen", "Method", "new-judges/winner-d3", "Three judges: Judge 3's verdict is the reward"), Arm("frozen", "Baseline", "new-judges/winner-d2", "Two judges: Judge 2's verdict"), Arm("frozen", "Baseline", "new-judges/winner-d1", "One judge: Judge 1's verdict"), Arm("frozen", "Control", "base", "Starting solver, no training"), Arm("original", "Method", "d3-17", "Three judges: Judge 3's verdict is the reward"), Arm("original", "Baseline", "d2-17", "Two judges: Judge 2's verdict"), Arm("original", "Baseline", "d1-17", "One judge: Judge 1's verdict"), Arm("original", "Baseline", "flat-17", "Majority of three independent Judge 1 votes"), Arm("original", "Control", "base", "Starting solver, no training"), Arm("original", "Control", "oracle-17", "Exact checker reward (upper reference)"), Arm("original", "Control", "shuffle-17", "Judge 3 rewards shuffled within each group of four"), Arm("original", "Ablation", "hybrid-17", "Judge 3 verdict multiplied by the exact checker"), Arm("original", "Ablation", "exact-prefix1", "Three calls, Judge 1 first trained on exact labels"), Arm("original", "Ablation", "exact-prefix2", "Three calls, Judges 1–2 first trained on exact labels"), Arm("original", "Ablation", "exact-prefix3", "Three calls, Judges 1–3 first trained on exact labels"), Arm("original", "Ablation", "top-prefix1", "Three calls, Judge 1 first trained top-down"), Arm("original", "Ablation", "top-prefix2", "Three calls, Judges 1–2 first trained top-down"), Arm("original", "Ablation", "top-prefix3", "Three calls, Judges 1–3 first trained top-down"), Arm("original", "Ablation", "exact-depth1", "One judge, trained on exact labels"), Arm("original", "Ablation", "exact-depth2", "Two judges, trained on exact labels"), Arm("original", "Ablation", "top-depth1", "One judge, trained top-down"), Arm("original", "Ablation", "top-depth2", "Two judges, trained top-down"), Arm("original", "Ablation", "alt-exact-solver", "Continues exact-prefix3 against refreshed exact-route judges"), ) def replace_region(text, name, content, required=True): """Swap the text between `` and ``, keeping everything else verbatim.""" start, end = f"", f"" if start not in text or end not in text: if required: raise ValueError(f"README.md lacks the {name} markers") return text head, rest = text.split(start, 1) _, tail = rest.split(end, 1) return f"{head}{start}\n{content.strip(chr(10))}\n{end}{tail}" def wilson(proportion, n): """Wilson score endpoints for a binomial proportion on distinct problems (Wilson, 1927, JASA 22:209).""" z = NormalDist().inv_cdf(.975) denominator = 1+z*z/n center = (proportion+z*z/(2*n))/denominator radius = z*sqrt(proportion*(1-proportion)/n+z*z/(4*n*n))/denominator return max(0.0, center-radius), min(1.0, center+radius) def outcomes(path): """Per-problem exact outcomes from a finished development evaluation, keyed by canonical problem ID.""" if not (path.parent/"development.json").is_file() or not path.is_file(): return None return {r["key"]: int(r["correct"]) for r in rows(path)} def solver_scores(source, root): """Read every registered arm. Arms whose problem IDs differ from the starting solver's are left out.""" base = outcomes(source/"base"/"replay.jsonl") scores = {family: {} for family in FAMILIES} for arm in ARMS: path = (source/arm.key/"replay.jsonl" if arm.family == "original" or arm.key == "base" else root/arm.key/"solutions.jsonl") values = outcomes(path) if values is not None and base is not None and values.keys() == base.keys(): scores[arm.family][arm.key] = values return scores def glance_rows(scores): """One row per registered arm, with the paired difference from that family's three-judge solver.""" method = {a.family: scores[a.family].get(a.key) for a in ARMS if a.role == "Method"} table = [] for arm in ARMS: values = scores[arm.family].get(arm.key) reference = method[arm.family] row = dict(family=arm.family, role=arm.role, key=arm.key, label=arm.label, correct=None, n=None, interval=None, change=None) if values: row.update(correct=sum(values.values()), n=len(values)) row["interval"] = wilson(row["correct"]/row["n"], row["n"]) if reference and arm.role != "Method": # Same seeded paired bootstrap as the registered learnability contrasts (learnability_analysis.py). row["change"] = paired_change(values, reference) table.append(row) return table def verdict(change): """A difference counts only when its whole paired 95% interval lies on one side of zero.""" low, high = change["interval"] return "higher" if low > 0 else "lower" if high < 0 else "not distinguishable" def plain(label): """The treatment in a few words: 'Exact checker reward (upper reference)' becomes 'exact checker reward'.""" words = label.split(":")[0].split(" (")[0] return words[0].lower() + words[1:] def short(row): return row["key"].removeprefix("new-judges/winner-") def glance_markdown(table): """Render the role-labelled table, then say in words which arms beat or trailed three judges.""" records, sentences = [], [] for family, title in FAMILIES.items(): members = [r for r in table if r["family"] == family] groups = {"higher": [], "lower": [], "not distinguishable": []} for r in members: if r["correct"] is None: records.append([title, r["role"], f"`{short(r)}`", r["label"], "Pending", "—", "—", "—"]) continue low, high = r["interval"] difference = interval = "—" if r["change"]: c = r["change"] difference = f"{100*c['delta']:+.2f}" interval = f"{100*c['interval'][0]:+.1f} to {100*c['interval'][1]:+.1f}" groups[verdict(c)].append(f"{plain(r['label'])} (`{short(r)}`, {difference} pp)") records.append([title, f"**{r['role']}**" if r["role"] == "Method" else r["role"], f"`{short(r)}`", r["label"], f"{r['correct']}/{r['n']} ({100*r['correct']/r['n']:.1f}%)", f"{100*low:.1f}–{100*high:.1f}", difference, interval]) parts = [f"{label} three judges: " + "; ".join(names) for label, names in (("Higher than", groups["higher"]), ("Lower than", groups["lower"]), ("Not distinguishable from", groups["not distinguishable"])) if names] if parts: sentences.append(f"- **{title}.** " + ". ".join(parts) + ".") headers = ["Judges", "Role", "Arm", "Solver reward or treatment", "Exact development solutions", "Wilson 95% (%)", "Minus three judges (pp)", "Paired 95% interval (pp)"] return (markdown(headers, records) + "\n\n**In plain words.** \"Higher\" or \"lower\" means the whole paired " "95% interval lies above or below zero.\n\n" + "\n".join(sentences)) def group_advantages(rewards): """GRPO advantages exactly as TRL 1.19 computes them with scale_rewards="group" (training.py). TRL `GRPOTrainer._generate_and_score_completions`: (r - mean_g) / (nanstd_g + 1e-4), where `trl.trainer.utils.nanstd` applies Bessel's correction. https://github.com/huggingface/trl/blob/v1.19.0/trl/trainer/grpo_trainer.py """ center = mean(rewards) spread = sqrt(sum((r-center)**2 for r in rewards)/(len(rewards)-1)) return [(r-center)/(spread+1e-4) for r in rewards] def pp(change): return (f"{100*change['delta']:+.2f} percentage points, paired 95% interval " f"{100*change['interval'][0]:+.1f} to {100*change['interval'][1]:+.1f}") def gap(row): """Short form of a row's paired difference from three judges: +90.62 [+78.1, +100.0].""" c = row["change"] return f"{100*c['delta']:+.2f} [{100*c['interval'][0]:+.1f}, {100*c['interval'][1]:+.1f}]" def score(row): return f"{row['correct']}/{row['n']}" def highlights(data, table): """Positive and negative findings, each with its denominator, interval and kind of evidence.""" find = {(r["family"], r["key"]): r for r in table if r["correct"] is not None} bullets = [] online = data.get("online_solvers") or {} contrasts = online.get("three_depths", {}).get("contrasts", {}) one, two, three = (find.get(("frozen", f"new-judges/winner-d{d}")) for d in (1, 2, 3)) if one and two and "two_minus_one" in contrasts: bullets.append(f"**Positive: a second judge helped.** With frozen Qwen3.5-4B judges, the solver trained on " f"Judge 2's verdict solved {score(two)} development problems, against {score(one)} with " f"Judge 1 alone ({pp(contrasts['two_minus_one'])}). Single seed; the one-judge arm was " "registered after the two- and three-judge scores were known.") audit = next((i for i in online.get("three_depths", {}).get("interventions", []) if (i["lower"], i["upper"]) == (2, 3)), None) if two and three and "three_minus_two" in contrasts: text = (f"**Negative: a third judge did not help.** Rewarding Judge 3's verdict gave {score(three)}, against " f"{score(two)} for Judge 2 ({pp(contrasts['three_minus_two'])}).") if audit: text += (f" Replayed on the three-judge run's own training answers, Judge 3 fixed {audit['fixed']} of " f"Judge 2's verdicts, introduced {audit['harmed']} errors and changed the relative GRPO credit " f"in {audit['changed_credit_groups']}/{audit['groups']} groups. The replay swaps the reward on " "logged answers without retraining.") bullets.append(text + " Single seed.") review = (data.get("depth_review") or [None])[0] deep, shallow = find.get(("original", "d3-17")), find.get(("original", "d2-17")) if deep and shallow and shallow["change"]: text = (f"**Negative: with Qwen2.5-1.5B-Instruct judges, the third judge collapsed training.** The " f"three-judge solver solved {score(deep)} development problems, against {score(shallow)} for two " f"judges (two minus three: {pp(shallow['change'])}).") if review: valid = review["three"]["training"]["correct"] wrong = review["n"]-valid j2, j3 = review["same_answers_paid"] text += (f" On the same {review['n']:,} training answers, Judge 3 rewarded {100*j3['correct']/valid:.1f}% " f"of correct and {100*j3['wrong']/wrong:.1f}% of wrong answers; Judge 2 rewarded " f"{100*j2['correct']/valid:.1f}% and {100*j2['wrong']/wrong:.1f}%.") late = {arm: review[arm]["quarters"][-1] for arm in ("two", "three")} last = late["three"] text += (f" In the last quarter of training, {last['correct']}/{last['n']} of the three-judge run's " f"samples were exactly correct, against {late['two']['correct']}/{late['two']['n']} for the " f"two-judge run, and Judge 3 rewarded {last['rewarded_wrong']} of its " f"{last['n']-last['correct']} wrong samples.") seed = f" {review['seed']}" if review else "" bullets.append(text + f" Single seed{seed}; post hoc diagnosis.") controls = [(find.get(("original", key)), label) for key, label in (("oracle-17", "the exact checker"), ("hybrid-17", "Judge 3 gated by the checker"), ("shuffle-17", "within-group shuffled Judge 3 rewards"))] if all(row for row, _ in controls): (oracle, _), (hybrid, _), (shuffle, _) = controls bullets.append(f"**Controls: the solver can learn this task; the judge reward limits it.** With the same " f"Qwen2.5-1.5B-Instruct judges and seed, the solver reached {score(oracle)} with the exact " f"checker as reward (control) and {score(hybrid)} with Judge 3's verdict gated by the checker " f"(ablation), against {score(shuffle)} with Judge 3's rewards shuffled within each group " f"(control) and {score(deep) if deep else 'no score'} with Judge 3 alone. Paired differences " f"from Judge 3 alone, in percentage points with 95% intervals: exact checker {gap(oracle)}, " f"gated {gap(hybrid)}, shuffled {gap(shuffle)}. Single seed; each arm changes only the reward.") grid = next((g for g in data.get("matched_depth", []) if g["phase"] == "development"), None) stack = (grid or {}).get("stacks", {}).get("exact") if stack: bullets.append(f"**Negative: judges trained on exact labels learned to approve everything.** The fitted " f"exact-label stack approved {', '.join(map(str, stack['approved']))} of {stack['n']} " f"starting-solver answers at depths one, two and three, including " f"{', '.join(map(str, stack['false']))} of the {stack['invalid']} incorrect ones. Fixed-answer " "replay: the solver's answers stay fixed and only the judges change.") frozen = data.get("newer_judges") or {} if frozen.get("review"): records = {r["key"]: r for r in frozen["results"]} w, c = (records[k]["metrics"]["twins"] for k in ("confirm-winner", "confirm-control")) estimate = frozen["decision"]["estimates"]["twins"] bullets.append(f"**Evidence audit: Judge 3 rarely checks the evidence it reviews.** When one number in " f"Judge 2's report was altered, frozen {records['confirm-winner']['model']} endorsed the sound " f"report and located and repaired the altered one on {w['visible']}/{w['n']} fresh pairs, " f"against {c['visible']}/{c['n']} for {records['confirm-control']['model']} " f"({100*estimate['delta']:+.2f} percentage points, paired 95% interval " f"{100*estimate['ci'][0]:+.2f} to {100*estimate['ci'][1]:+.2f}). With the evidence masked, " f"both passed {w['masked']}/{w['n']} and {c['masked']}/{c['n']}. Fixed solver answers on a " "confirmation cohort specified before inference with these judges.") primary = data.get("primary", {}) sizes = sorted({r["n"] for r in table if r["n"]}) cohort = f" on {' or '.join(map(str, sizes))} problems" if sizes else "" bullets.append("**Still open.** " + ( "The preregistered three-seed held-out comparison has not run, so every result above is a single-seed " f"development estimate{cohort}." if "delta" not in primary else f"The preregistered held-out difference (three minus two judges) was {100*primary['delta']:+.2f} percentage " f"points, interval {100*primary['ci'][0]:+.2f} to {100*primary['ci'][1]:+.2f}.")) return ("## Key results\n\n" + "\n".join(f"- {b}" for b in bullets) + f"\n\nRole-labelled scores for every arm are in [Results at a glance](#results-at-a-glance). " f"[Preregistration]({GITHUB}/blob/main/reports/preregistration.md) · " f"[Paper]({GITHUB}/blob/main/reports/paper.pdf)\n\n")