"""Render docs/tex/flagship_compare_published_vs_repro.tex from scratch/cmp_table/cmp_data.json (CMP_TABLE, 2026-10-03). Pure formatting: every number comes from cmp_data.json (build_cmp_data.py).""" from __future__ import annotations import json import math import re import sys from datetime import datetime, timezone from pathlib import Path R = Path("/proj/dmfexp/zwhong/rsm_rise") D = json.loads((R / "scratch/cmp_table/cmp_data.json").read_text()) OUT = R / "docs/tex/flagship_compare_published_vs_repro.tex" SUMMARY = R / "scratch/cmp_table/summary.json" Z = 1.959963984540054 SHORT = {"square_sub_20100": "Sq-S", "square_expert_play": "Sq-C", "two_piece_expert_suboptimal": "Pc-S", "two_piece_expert_play": "Pc-C", "mug_expert_suboptimal": "Mug", "threading_expert_play": "Thr", "two_piece_expert_play_tipping": "Pc-tip"} FULL_N = 150 # repro: 1 train seed x 3 eval seeds x 50 episodes def esc(s: str) -> str: return (str(s).replace("\\", r"\textbackslash{}").replace("_", r"\_").replace("&", r"\&").replace("%", r"\%") .replace("#", r"\#").replace("$", r"\$").replace("{", r"\{").replace("}", r"\}").replace("~", r"\~{}") .replace("^", r"\^{}").replace("|", r"$|$")) def wilson(k, n): p = k / n den = 1 + Z * Z / n c = (p + Z * Z / (2 * n)) / den h = Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n)) / den return c - h, c + h def newcombe(k1, n1, k2, n2): """p2 - p1 with the Newcombe hybrid-score 95% interval, in points.""" p1, p2 = k1 / n1, k2 / n2 l1, u1 = wilson(k1, n1) l2, u2 = wilson(k2, n2) d = p2 - p1 return 100 * d, 100 * (d - math.sqrt((p2 - l2) ** 2 + (u1 - p1) ** 2)), 100 * (d + math.sqrt((u2 - p2) ** 2 + (p1 - l1) ** 2)) def fmt_d(d): v, lo, hi = d sig = lo > 0 or hi < 0 s = f"{v:+.1f}\\,[{lo:+.1f},{hi:+.1f}]" return (r"\textbf{" + s + "}") if sig else s, sig # ---- pending reasons ----------------------------------------------------------------------------------------------------- def pending_reason(t: str, key: str, e: dict) -> str: decl = D["declared"].get(t, {}).get(key, "") if decl != "ok": if "TBD_P4" in decl: return "P4 proposer screen" return "config: " + decl.split(":")[0] files = D["eval_files"].get(t, []) js = [f for f in files if re.fullmatch(rf"{key}_es\d+\.json", f)] part = [f for f in files if re.fullmatch(rf"{key}_es\d+\.json\.partial", f)] needs = D["pending_needs"].get(t, {}).get(key, []) if needs: roles = sorted({n.split()[0] for n in needs}) if "proposer" in roles: return "training: proposer " + str((e or {}).get("proposer") or "") return "training: " + "+".join(roles) if part: return f"eval running ({len(js)}/3 done)" if js: return f"eval {len(js)}/3 seeds" return "eval not run" def cell_state(t, key): e = D["repro"][t][key] if e and e["n"] >= FULL_N and len(e["eval_seeds"]) == 3: return "ok", e return pending_reason(t, key, e or {}), e # ---- main table --------------------------------------------------------------------------------------------------------- tasks = D["tasks"] cols = D["columns"] printed = D["printed"] summ = {"complete": 0, "pending": 0, "pending_by_reason": {}, "significant": [], "cells": {}} pub_vs_print = [] rows_tex = [] for t, lab in tasks: pubs, reps, dels = [], [], [] for cl, key in cols: pr = printed.get(lab, {}).get(cl) pl = D["published_legacy"][t][key] pk = f"{pr[0]:.1f}" if pr else "--" if pl and pl["n"]: pubs.append(f"{pk}\\,{{\\tiny({pl['n']})}}") if pr and abs(pl["seedmean"] - pr[0]) > 0.051: pub_vs_print.append((t, cl, pr[0], pl["seedmean"], pl["rate"])) else: pubs.append(pk) st, e = cell_state(t, key) rec = {"published_printed": pr[0] if pr else None, "published_k": pl and pl["k"], "published_n": pl and pl["n"]} if st == "ok": summ["complete"] += 1 reps.append(f"{e['rate']:.1f}\\,{{\\tiny({e['n']})}}") d = newcombe(pl["k"], pl["n"], e["k"], e["n"]) s, sig = fmt_d(d) dels.append(s) rec.update(repro_k=e["k"], repro_n=e["n"], delta=d) if sig: summ["significant"].append(f"{SHORT[t]} {cl} {d[0]:+.1f} [{d[1]:+.1f},{d[2]:+.1f}]") else: summ["pending"] += 1 summ["pending_by_reason"][st] = summ["pending_by_reason"].get(st, 0) + 1 extra = "" if e and e.get("n"): extra = f" {e['rate']:.0f}/{e['n']}" reps.append(r"\textit{\tiny pending}") dels.append(r"\textit{\tiny " + esc(st) + "}") rec.update(pending=st, partial_rate=e.get("rate") if e else None, partial_n=e.get("n") if e else None) summ["cells"][f"{SHORT[t]}|{cl}"] = rec rows_tex.append(rf"\multirow{{3}}{{*}}{{{lab}}} & pub. & " + " & ".join(pubs) + r" \\") rows_tex.append(r" & repro & " + " & ".join(reps) + r" \\") rows_tex.append(r" & $\Delta$ & " + " & ".join(dels) + r" \\ \midrule") rows_tex[-1] = rows_tex[-1].replace(r"\midrule", "") hdr = " & ".join(cl for cl, _ in cols) # ---- arms that differ --------------------------------------------------------------------------------------------------- arm_rows = [] for t, lab in tasks: for cl, key in cols: pa = (D["published_legacy"][t][key] or {}).get("arm") pp = (D["published_legacy"][t][key] or {}).get("proposer") ra = (D["repro"][t][key] or {}).get("arm") rpp = (D["repro"][t][key] or {}).get("proposer") if ra is None: continue if (pa, pp) != (ra, rpp): arm_rows.append(f"{SHORT[t]} & {cl} & {esc(pp)}: {esc(pa)} & {esc(rpp)}: {esc(ra)} \\\\") # ---- equivalence bridge ------------------------------------------------------------------------------------------------- EQMAP = [("eq01_sqs_rsm_chain", "square_sub_20100", "RSM", "rsm", ""), ("eq02_sqs_idql", "square_sub_20100", "IDQL", "idql", ""), ("eq03_sqs_ifql", "square_sub_20100", "IFQL", "ifql", "repro IFQL is the best-found $\\gamma{=}0.995$, gate cell the printed $0.9999$"), ("eq04_sqs_tdflow", "square_sub_20100", "TD-Flow", "tdflow", ""), ("eq05_sqs_dinowm", "square_sub_20100", "DINO-WM", "dinowm", ""), ("eq06_pcc_lewm", "two_piece_expert_play", "LeWM", "lewm", "published LeWM: MC noise pinned to seed 0"), ("eq07_pcc_df", "two_piece_expert_play", "DF", "df", "published DF: MC noise pinned to seed 0; printed pools W3/W3s1/W3s2"), ("eq08_pcc_random", "two_piece_expert_play", "rand-128", "random", "control"), ("eq09_pcc_rsm_chain", "two_piece_expert_play", "RSM", "rsm", ""), ("eq10_thr_rsm_chain_n128", "threading_expert_play", "RSM (N=128)", "rsm", "the arm the repro declares"), ("eq11_thr_rsm_chain_n16", "threading_expert_play", "RSM (N=16)", None, "the arm tab:flagship printed (26.0)"), ("eq12_thr_idql", "threading_expert_play", "IDQL", "idql", "")] eq_rows = [] bridge = {} for cell, t, cl, key, note in EQMAP: q = D["equiv"].get(cell) if not q: continue lab = dict(tasks)[t] pr = printed.get(lab, {}).get(cl.split(" ")[0]) d1 = newcombe(q["k_pub"], q["n_pub"], q["k_new"], q["n_new"]) s1, _ = fmt_d(d1) rep_s = d2s = "--" if key: if key == "random": e = D["repro_controls"][t]["random"] else: e = D["repro"][t][key] st, _e = cell_state(t, key) if key != "random" else (("ok" if e and e["n"] >= FULL_N else "pending"), e) if st == "ok": rep_s = f"{e['k']}/{e['n']}" d2 = newcombe(q["k_new"], q["n_new"], e["k"], e["n"]) d2s, _ = fmt_d(d2) bridge[f"{SHORT[t]} {cl}"] = d2 else: rep_s = r"\textit{pending}" eq_rows.append(f"{esc(cell)} & {SHORT[t]} {cl} & {pr[0]:.1f} & {q['k_pub']}/{q['n_pub']} & {q['k_new']}/{q['n_new']} & {s1} & {rep_s} & {d2s} & {{\\tiny {note}}} \\\\" if pr else f"{esc(cell)} & {SHORT[t]} {cl} & -- & {q['k_pub']}/{q['n_pub']} & {q['k_new']}/{q['n_new']} & {s1} & {rep_s} & {d2s} & {{\\tiny {note}}} \\\\") summ["bridge_repro_minus_equiv"] = bridge summ["pub_vs_printed_mismatch"] = pub_vs_print # ---- hand check ------------------------------------------------------------------------------------------------------- hc = (R / "scratch/cmp_table/handcheck.txt") hc_lines = hc.read_text().strip().splitlines() if hc.exists() else ["(hand check missing)"] rem = D.get("published_rematch", []) rem_txt = "; ".join(esc(x) for x in rem) if rem else "none needed" sig_txt = "; ".join(esc(x) for x in summ["significant"]) or "none" _ns = [(abs(v["delta"][0]), k, v["delta"][0]) for k, v in summ["cells"].items() if "delta" in v and k.split("|")[1] not in ("RSM", "TD-Flow")] _ns.sort(reverse=True) ns_txt = (f"up to {_ns[0][0]:.1f} points on single cells (" + ", ".join(f"{esc(k.replace('|', ' '))} {d:+.1f}" for _, k, d in _ns[:3]) + ")") if _ns else "not measurable yet" READING = (r"""\noindent\textbf{Reading the complete cells (snapshot).} Cells whose interval excludes 0: """ + sig_txt + r""". Non-successor columns (BC, BC-u, IDQL, IFQL, LeWM, DINO-WM, DF) do not use the successor sampler, so their $\Delta$ is the retrain + code/noise effect alone and is the yardstick for the successor columns: it reaches """ + ns_txt + r""". Where both exist, Table~\ref{tab:bridge} gives repro$-$equiv (same new code, old vs.\ retrained checkpoints). """ + r"""\par\smallskip\noindent\textit{Published-side arm re-match} (the legacy rule in \texttt{table.py} admits TD-Flow chain caps the printed column did not use, CH150/CH69 instead of the 1e-3 tail cap CH73/CH33; for those cells $k/n$ is taken from the admissible arm whose seed-mean equals the printed value, preferring the arm the repro config declares): """ + rem_txt + ".") now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%MZ") n_tot = summ["complete"] + summ["pending"] pend_txt = "; ".join(f"{v}$\\times$ {esc(k)}" for k, v in sorted(summ["pending_by_reason"].items(), key=lambda kv: -kv[1])) mism = "none" if not pub_vs_print else "; ".join(f"{SHORT[t]} {c}: printed {a:.1f}, rebuilt {b:.1f}" for t, c, a, b, _ in pub_vs_print) tex = r"""\documentclass[10pt]{article} \usepackage[a4paper,landscape,margin=1.4cm]{geometry} \usepackage{booktabs,multirow,amsmath,amssymb,array,xcolor} \usepackage[T1]{fontenc} \usepackage{lmodern} \setlength{\parindent}{0pt}\setlength{\parskip}{4pt} \newcommand{\boxpar}[2]{\noindent\fbox{\begin{minipage}{0.97\linewidth}\textbf{#1}\par\smallskip #2\end{minipage}}} \begin{document} {\large\textbf{tab:flagship -- published (rescaled geometric successor target) vs.\ reproduction on the cleaned code (truncated future, terminal atom)}}\\ {\small CMP\_TABLE stream (rsm\_rise), built """ + now + r""" from \texttt{scratch/cmp\_table/cmp\_data.json}} \textbf{Status at build time:} """ + f"{summ['complete']} of {n_tot}" + r""" flagship cells have a complete reproduction (1 training seed $\times$ 3 eval seeds $\times$ 50 episodes $=150$ episodes); """ + f"{summ['pending']}" + r""" are pending (""" + pend_txt + r"""). The reproduction (branch \texttt{rise\_repro}) is still running P3/P5; this document is a snapshot and is rebuilt by \texttt{scripts/cmp\_table/run\_build.sh}. \textbf{The difference column is NOT a sampler ablation.} The reproduction changes the successor target \emph{and} retrains every checkpoint from scratch at one seed \emph{and} changes how per-decision noise is drawn \emph{and} (Mug) the proposer \emph{and} a few declared settings; see the box on p.~\pageref{box:changes}. Use Table~\ref{tab:bridge} (old checkpoints scored by the new code) to separate the code/noise change from the retrain. \begin{table}[!htbp] \centering \caption{\label{tab:cmp}tab:flagship, published vs.\ reproduction, success rate (\%), with $n$ = pooled episodes in parentheses. $\Delta$ = repro $-$ published pooled rate (points) with the 95\% two-sample binomial interval (Newcombe hybrid score); \textbf{bold}: excludes 0. Definitions below the table.} \scriptsize \setlength{\tabcolsep}{2.5pt} \begin{tabular}{ll|cc|ccccccc} \toprule Task & & """ + hdr + r""" \\ \midrule """ + "\n".join(rows_tex) + r""" \bottomrule \end{tabular} \end{table} {\footnotesize\textbf{pub.}: the value printed in \texttt{docs/tex/flagship\_table.tex} (2026-09-27 06:27, built by \texttt{scripts/flagship\_latex.py}; the table in \texttt{rsm\_tables\_full.pdf}) = mean over 3 training seeds of the selected arm; $n$ and the pooled $k$ used for $\Delta$ come from the same arm re-derived through the loud loader (\texttt{rsmrise.results.table.flagship(legacy=True)} on \texttt{runs/}; 3 training $\times$ 3 eval seeds $\times$ 50 = 450, DF 1350 = 3 W3 replicates, some BC/BC-u/IDQL arms pool duplicate re-runs of the same seeds). \textbf{repro}: the declared arm of \texttt{configs//.yaml} on \texttt{runs\_repro/} via \texttt{rsmrise.results.loader.cells()}, one training seed, eval seeds 0--2, $n=150$; a cell counts as complete only with all 3 eval seeds. The binomial interval treats episodes as independent and ignores between-training-seed variance, so it is too narrow, most of all for the one-seed repro side. \textit{pending} names the missing input (\emph{training: proposer X}: the row's retrained proposer has not reached its checkpoint epoch; \emph{P4 proposer screen}: Mug's union proposer is not chosen yet; \emph{eval running}: JSONs partially written).\par} """ + READING + r""" \noindent\textit{Published printed value vs.\ the rebuilt seed-mean of the same arm (sanity check of the published side):} """ + esc(mism) + r""". \textit{Hand check} (successes counted directly from the named cell JSONs, no loader):\\ {\scriptsize\texttt{""" + r"}\\ \texttt{".join(esc(x) for x in hc_lines) + r"""}} \clearpage \label{box:changes} \boxpar{What changed between the two tables}{ \textbf{(a) Successor target (the intended change; \texttt{rsmrise/data.py:successor\_offsets}).} Anchor at row $t$ of an episode whose last frame is $T$; $R=T-t+1$ frames remain (the anchor is $k=0$). \begin{itemize}\itemsep0pt \item \emph{Published} (\texttt{rsm\_libero/data.py:truncated\_geometric\_future}): the geometric law renormalised to the remaining trajectory, $\;P_{\text{pub}}(k)=\dfrac{(1-\beta)\beta^{k}}{1-\beta^{R}},\ k=0,\dots,R-1$ (drawn as $k=\lceil\log(1-u(1-\beta^R))/\log\beta\rceil-1$), with $\beta\sim U[\beta_{lo},\min(\beta_{hi},\max(\beta_{lo},\varepsilon^{1/R}))]$ per anchor (\texttt{data.py:457-462}, \texttt{--beta-trunc-eps}, default $\varepsilon=0.02$; some cells ran with $\varepsilon\ge\beta_{hi}$, i.e.\ no cap). The mass $\beta^R$ that falls past the episode end is spread proportionally over all real frames. \item \emph{Reproduction} (paper Sec.~4.1 / App.~D Eq.~7, owner decision A1): truncated future with the tail copied onto the last state, $\;P_{\text{repro}}(k)=(1-\beta)\beta^{k}$ for $0\le k