File size: 8,272 Bytes
c6a8401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CMP_TABLE (owner request 2026-10-03): published tab:flagship vs the rise_repro reproduction, per cell.

Read-only on the rise_repro worktree and runs_repro.  Numbers come ONLY from:
  * published side: the printed value parsed from docs/tex/flagship_table.tex (the 2026-09-27 build by
    scripts/flagship_latex.py that rsm_tables_full.pdf includes) via rsmrise.results.table.published_oracle, and the
    pooled k/n of the same arm from the frozen selection rule re-run through the loud loader
    (table.flagship(legacy=True) on runs/, the P4.1 oracle) -- k/n is needed for the binomial interval;
  * repro side: rsmrise.results.loader.cells() on runs_repro through table.flagship() (declared arms);
  * equivalence gate: runs_repro/equivalence/_report.json (equivalence_report.py, LSF 19213).
Writes scratch/cmp_table/cmp_data.json.
"""
from __future__ import annotations

import json
import math
import sys
import traceback
from collections import defaultdict
from pathlib import Path

PKG = Path("/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm_repro/rise_repro")
sys.path.insert(0, str(PKG))
sys.path.insert(0, str(PKG / "experiments"))

from rsmrise import paths  # noqa: E402
from rsmrise.results import loader, table  # noqa: E402

OUT = Path("/proj/dmfexp/zwhong/rsm_rise/scratch/cmp_table")
OUT.mkdir(parents=True, exist_ok=True)
TEX = paths.ROOT / "docs" / "tex" / "flagship_table.tex"
Z = 1.959963984540054


def wilson(k, n):
    lo, hi = loader.wilson(k, n)
    return lo, hi


def newcombe(k1, n1, k2, n2):
    """95% interval of p2 - p1 (Newcombe 1998 hybrid score, method 10), in points."""
    p1, p2 = k1 / n1, k2 / n2
    l1, u1 = wilson(k1, n1)
    l2, u2 = wilson(k2, n2)
    l1, u1, l2, u2 = l1 / 100, u1 / 100, l2 / 100, u2 / 100     # loader.wilson returns percent
    d = p2 - p1
    lo = d - math.sqrt((p2 - l2) ** 2 + (u1 - p1) ** 2)
    hi = d + math.sqrt((u2 - p2) ** 2 + (p1 - l1) ** 2)
    return 100 * d, 100 * lo, 100 * hi


def ent(e):
    if e is None:
        return None
    return {"k": e.k, "n": e.n, "rate": e.rate, "seedmean": e.seedmean, "n_cells": e.n_cells,
            "train_seeds": list(e.train_seeds), "eval_seeds": list(e.eval_seeds),
            "arm": None if e.arm is None else f"{e.arm.family} | {e.arm.recipe}",
            "proposer": None if e.proposer is None else e.proposer.label, "status": e.status}


def main():
    res = {"published_tex": str(TEX), "notes": []}
    tasks = list(table.TASKS)
    cols = list(table.COLUMNS)
    res["tasks"] = [(t, loader.ROW_LABEL[t]) for t in tasks]
    res["columns"] = cols

    # ---- published: printed values + the frozen rule's pooled k/n ----------------------------------------------
    printed = table.published_oracle(TEX, "flagship")
    res["printed"] = {lab: {c: list(v) for c, v in d.items()} for lab, d in printed.items()}
    leg_cells = {t: loader.cells(t, paths.RUNS, legacy=True, allow="all", extra_epochs=(500,)) for t in tasks}
    leg = table.flagship(tasks, legacy=True, cells_by_task=leg_cells)
    res["published_legacy"] = {t: {key: ent(leg.entry(t, key)) for _, key in cols} for t in tasks}
    # Where the legacy rule's pick does not reproduce the printed number (it admits TD-Flow CH150 arms, the printed
    # column used the 1e-3 tail cap CH73/CH33), re-match: the admissible arm whose seed-mean rounds to the printed value,
    # preferring the arm the repro config declares (configs were generated from the printed arms, RESULTS2 sec. 2).
    rematch = []
    for t in tasks:
        lab = loader.ROW_LABEL[t]
        decl = table.declared_cells(t)
        for cl, key in cols:
            pv = printed.get(lab, {}).get(cl)
            e = res["published_legacy"][t][key]
            if not pv or not e or e["seedmean"] is None or abs(e["seedmean"] - pv[0]) <= 0.051:
                continue
            cands, _pk = table._admissible_legacy(leg_cells[t], t, key)
            hits = [(a, x) for a, x in cands if x.n and x.seedmean is not None and abs(x.seedmean - pv[0]) <= 0.051]
            want = None
            cfg = decl.get(key)
            if cfg is not None and not isinstance(cfg, str):
                want = loader.arm_of_config(cfg).recipe
            hits.sort(key=lambda ax: (ax[0].recipe != want, -ax[1].n, ax[0].recipe))
            if hits:
                old_arm = e["arm"]
                res["published_legacy"][t][key] = ent(hits[0][1])
                res["published_legacy"][t][key]["rematched_from"] = old_arm
                rematch.append(f"{t} {cl}: printed {pv[0]} -> {hits[0][0].recipe} ({len(hits)} matching arms; legacy pick was {old_arm})")
            else:
                rematch.append(f"{t} {cl}: printed {pv[0]}, no admissible arm matches; kept legacy pick {e['arm']} ({e['seedmean']:.2f})")
    res["published_rematch"] = rematch
    legc = table.controls(tasks, legacy=True, cells_by_task=leg_cells)
    res["published_legacy_controls"] = {t: {key: ent(legc.entry(t, key)) for _, key in table.CONTROL_COLUMNS} for t in tasks}

    # ---- repro: declared arms on runs_repro ---------------------------------------------------------------------
    rep_cells, rej = {}, {}
    for t in tasks:
        try:
            c = loader.cells(t, paths.REPRO_RUNS, allow=("partial_file", "partial"))
        except loader.LoaderError as e:
            res["notes"].append(f"repro loader refused {t}: {e}")
            c = loader.cells(t, paths.REPRO_RUNS, allow="all")
        rep_cells[t] = c
        rej[t] = dict(c.rejections.counts)
    res["repro_rejections"] = rej
    rp = table.flagship(tasks, cells_by_task=rep_cells)
    res["repro"] = {t: {key: ent(rp.entry(t, key)) for _, key in cols} for t in tasks}
    rpc = table.controls(tasks, cells_by_task=rep_cells)
    res["repro_controls"] = {t: {key: ent(rpc.entry(t, key)) for _, key in table.CONTROL_COLUMNS} for t in tasks}

    # declared config status (Mug TBD_P4 etc.)
    decl = {}
    for t in tasks:
        d = table.declared_cells(t)
        decl[t] = {k: (v if isinstance(v, str) else "ok") for k, v in d.items()}
    res["declared"] = decl

    # ---- why a cell is pending: p5_ready's needs + on-disk eval files ---------------------------------------------
    pend = defaultdict(dict)
    try:
        import p5_ready
        for t in tasks:
            rep = p5_ready.task_report(paths.CONFIGS / t)
            pend[t]["_status"] = rep.status + (f" {rep.error}" if rep.error else "")
            for keyname, (why, names) in rep.missing.items():
                for nm in set(names):
                    pend[t].setdefault(nm, []).append(f"{keyname}: {why}")
    except Exception:  # noqa: BLE001
        res["notes"].append("p5_ready failed: " + traceback.format_exc()[-600:])
    files = {}
    for t in tasks:
        d = paths.REPRO_RUNS / t / "eval"
        files[t] = sorted(p.name for p in d.glob("*")) if d.exists() else []
    res["pending_needs"] = pend
    res["eval_files"] = files

    # ---- equivalence gate ----------------------------------------------------------------------------------------
    rep = json.loads((paths.REPRO_RUNS / "equivalence" / "_report.json").read_text())
    eq = defaultdict(lambda: {"k_new": 0, "n_new": 0, "k_pub": 0, "n_pub": 0, "files": 0})
    for r in rep["rows"]:
        if r.get("state") != "done":
            continue
        q = eq[r["cell"]]
        q["task"] = r["task"]
        for a in ("k_new", "n_new", "k_pub", "n_pub"):
            q[a] += r[a]
        q["files"] += 1
    res["equiv_gate"] = rep.get("gate")
    res["equiv_summary"] = rep.get("summary")
    res["equiv_configs"] = rep.get("configs")
    res["equiv"] = dict(eq)

    # ---- intervals ----------------------------------------------------------------------------------------------
    cmp_ = {}
    for t in tasks:
        for _, key in cols:
            p, r = res["published_legacy"][t][key], res["repro"][t][key]
            if p and r and p["n"] and r["n"]:
                cmp_[f"{t}|{key}"] = newcombe(p["k"], p["n"], r["k"], r["n"])
    res["delta_ci"] = cmp_
    (OUT / "cmp_data.json").write_text(json.dumps(res, indent=1, default=str))
    print("wrote", OUT / "cmp_data.json")
    for n in res["notes"]:
        print("NOTE", n[:400])


if __name__ == "__main__":
    main()