File size: 16,680 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
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
#!/usr/bin/env python3
"""BETA_FIXEDCFG table builder (owner 2026-11-11). ONE RSM config for all 7 tasks (config C: L40, P16, prob readout, F8,
N128, gamma 0.99, chain cap rule (1e-3 tail), paper checkpoint rule), swept over beta. Reads the raw eval JSONs only.
  cell value  = success % over 450 episodes (3 proposer ckpts x eval seeds 0-2 x first 50 eps), 95% CI = episode bootstrap
  7-task mean = mean of the 7 per-task rates; CI = bootstrap resampling episodes within each task, the SAME draw for every
                beta (paired), which also gives the paired CI of (beta - best beta) used for the 'flat range' statement
  hops        = MEASURED mean number of chain hops per planning decision = planner.scorer.chain_hops.hops_mean
                (decision-weighted over the 9 files); d1 cells (beta 0.99 = gamma, and the no-recursion control) are a single
                successor read with no chain -> 0 by construction.  EXPECTED = p/(1-p), p = (gamma-beta)/(gamma(1-beta)).
Writes status/beta_fixedcfg_table.json, docs/rebuttal/beta_fixed_config.{tex,md} (+ pdf via tectonic in the shell
wrapper) and the R5 fragments docs/rebuttal/_r5_beta_fixed_config.{tex,md} that make_rebuttal_tables.py appends.
Missing cells are shown as pending (never imputed).
"""
import json, os, sys
import numpy as np

ROOT = '/proj/dmfexp/zwhong/rsm_rise'
D = f'{ROOT}/docs/rebuttal'
GAMMA = 0.99
TASKS = [  # key, label, short, model tag, ON tag, seed prefix
    ('square_sub_20100', 'Square (Sub.)', 'Sq-S', 'L40b', 'ACTOR', 'S0A'),
    ('square_expert_play', 'Square (Cov.)', 'Sq-C', 'L40b', 'ACTOR', 'S0A'),
    ('two_piece_expert_suboptimal', 'Piece (Sub.)', 'Pc-S', 'L40s100k', 'ACTOR', 'S0A'),
    ('two_piece_expert_play', 'Piece (Cov.)', 'Pc-C', 'L40b', 'ACTOR', 'S0A'),
    ('mug_expert_suboptimal', 'Mug (Sub.)', 'Mug', 'L40b', 'S3H1', 'S3H1'),
    ('threading_expert_play', 'Thread (Cov.)', 'Thr', 'L40b', 'S0AidqlE500', 'S0AidqlE500'),
    ('two_piece_expert_play_tipping', 'Piece-tip (Cov.)', 'Tip', 'L40b', 'ACTOR', 'S0A'),
]
CAP = {'0.90': 73, '0.93': 48, '0.95': 33, '0.97': 18, '0.98': 11}
# column key -> (beta, mode, header)
COLS = [('0.90', '0.90', 'chain'), ('0.93', '0.93', 'chain'), ('0.95', '0.95', 'chain'), ('0.97', '0.97', 'chain'),
        ('0.98', '0.98', 'chain'), ('0.99', '0.99', 'd1'), ('d1@0.90', '0.90', 'd1')]
BETA_COLS = [c[0] for c in COLS if c[0] != 'd1@0.90']
NB = 4000
REPRO = '--repro' in sys.argv   # R6: rise_repro track (phaseA_v2, config A, rsmrise harness, 150 eps/cell)
RR = f'{ROOT}/runs_fair/phaseA_v2'
NEP = 150 if REPRO else 450
rng = np.random.default_rng(0)


def exp_hops(b):
    p = (GAMMA - b) / (GAMMA * (1 - b))
    return p / (1 - p)


def cellname(tag, on, sp, b, mode, es, ps):
    mid = f'{CAP[b]}-ch' if mode == 'chain' else '1'
    return f'E1-{tag}-R{b}-{mid}-N128-argmax-ON{on}-es{es}-s{sp}s{ps}'


data = {}   # (task, col) -> dict(succ=np.array[NEP] or None, n, hops, ...)


def load_repro(key, col, b, mode):
    lab = 'rsm_A_b0p90_norec' if col == 'd1@0.90' else 'rsm_A_b' + b.replace('.', 'p')
    succ, hsum, hw, nfiles, miss = [], 0.0, 0, 0, []
    for s in range(3):
        js = f'{RR}/{key}/eval_rebuttal/singlebeta/{lab}_es{s}.json'
        if not os.path.exists(js):
            miss.append(f'{lab}_es{s}'); continue
        j = json.load(open(js)); sc = j['config']['scorer']; pl = j['config']['planner']
        assert sc['particles'] == 16 and sc['score_kind'] == 'prob' and sc['flow_steps'] == 8 and pl['n'] == 128, js
        assert abs(float(sc['beta']) - float(b)) < 1e-9 and abs(float(sc['gamma']) - GAMMA) < 1e-9, js
        assert sc['chain_cap'] == (CAP[b] if mode == 'chain' else 0), js
        ep = sorted(j['episodes'], key=lambda e: int(e['episode']))
        assert len(ep) == 50 and not j.get('partial'), js
        succ += [1.0 if e['success'] else 0.0 for e in ep]; nfiles += 1
        ch = (j.get('health') or {}).get('chain_hops') or {}
        if mode == 'chain':
            w = ch.get('decisions', 1); hsum += ch['hops_mean'] * w; hw += w
    rec = dict(n=len(succ), nfiles=nfiles, complete=len(succ) == NEP, missing=miss)
    rec['succ'] = np.array(succ) if rec['complete'] else None
    rec['mean'] = 100 * float(np.mean(succ)) if succ else None
    rec['hops'] = (hsum / hw if hw else None) if mode == 'chain' else 0.0
    rec['hops_expected'] = exp_hops(float(b)) if mode == 'chain' else 0.0
    return rec


for key, lab, sh, tag, on, sp in TASKS:
    if REPRO:
        for col, b, mode in COLS:
            data[(key, col)] = load_repro(key, col, b, mode)
        continue
    for col, b, mode in COLS:
        succ, nfiles, hsum, hw, files_missing = [], 0, 0.0, 0, []
        ok = True
        for ps in range(3):
            for es in range(3):
                cn = cellname(tag, on, sp, b, mode, es, ps)
                js = f'{ROOT}/runs/{key}/eval_onactor/{cn}.json'
                if not os.path.exists(js):
                    files_missing.append(cn); ok = False; continue
                j = json.load(open(js))
                ep = j['episodes'][:50]
                assert len(ep) == 50, (js, len(ep))
                po = j['planner_overrides']
                # config-C invariants (asserted on every file, so a wrong cell can never enter the table)
                assert po['plan_particles'] == 16 and po['plan_score'] == 'prob' and po['plan_flow_steps'] == 8, js
                assert po['plan_n'] == 128 and abs(po['plan_beta'] - float(b)) < 1e-9 and po['plan_mode'] == mode, js
                assert abs(po.get('plan_gamma', GAMMA) - GAMMA) < 1e-9, js
                assert '/rsm/L40/' in po['rsm_ckpt'], js
                if mode == 'chain':
                    assert po['plan_chain_cap'] == CAP[b], js
                    ch = j['planner']['scorer']['chain_hops']
                    hsum += ch['hops_mean'] * ch['decisions']; hw += ch['decisions']
                succ += [1.0 if e['success'] else 0.0 for e in ep]
                nfiles += 1
        rec = dict(n=len(succ), nfiles=nfiles, complete=ok and len(succ) == 450, missing=files_missing)
        rec['succ'] = np.array(succ) if rec['complete'] else None
        rec['mean'] = 100 * float(np.mean(succ)) if succ else None
        rec['hops'] = (hsum / hw if hw else None) if mode == 'chain' else 0.0
        rec['hops_expected'] = exp_hops(float(b)) if mode == 'chain' else 0.0
        data[(key, col)] = rec

# ---- bootstrap: per-task CIs and paired 7-task mean
idx = rng.integers(0, NEP, size=(NB, NEP))
res = {'tasks': {}, 'mean': {}, 'cols': [c[0] for c in COLS], 'gamma': GAMMA, 'n_boot': NB}
boot_task = {}
for key, lab, sh, *_ in TASKS:
    res['tasks'][key] = {'label': lab, 'short': sh, 'cells': {}}
    for col, b, mode in COLS:
        r = data[(key, col)]
        out = {k: r[k] for k in ('n', 'nfiles', 'complete', 'mean', 'hops', 'hops_expected')}
        if r['complete']:
            bs = 100 * r['succ'][idx].mean(1); boot_task[(key, col)] = bs
            out['ci'] = [float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5))]
        res['tasks'][key]['cells'][col] = out
for col, b, mode in COLS:
    if all(data[(t[0], col)]['complete'] for t in TASKS):
        bm = np.mean([boot_task[(t[0], col)] for t in TASKS], 0)
        res['mean'][col] = dict(mean=float(np.mean([data[(t[0], col)]['mean'] for t in TASKS])),
                                ci=[float(np.percentile(bm, 2.5)), float(np.percentile(bm, 97.5))],
                                hops=float(np.mean([data[(t[0], col)]['hops'] for t in TASKS])) if mode == 'chain' else 0.0,
                                hops_expected=exp_hops(float(b)) if mode == 'chain' else 0.0, complete=True)
        boot_task[('mean', col)] = bm
    else:
        res['mean'][col] = dict(complete=False, ntasks=sum(data[(t[0], col)]['complete'] for t in TASKS))
done_beta = [c for c in BETA_COLS if res['mean'][c]['complete']]
finding = None
if done_beta:
    best = max(done_beta, key=lambda c: res['mean'][c]['mean'])
    flat, worse = [], []
    for c in [c for c in res['cols'] if res['mean'][c]['complete']]:
        d = boot_task[('mean', c)] - boot_task[('mean', best)]
        lo, hi = float(np.percentile(d, 2.5)), float(np.percentile(d, 97.5))
        res['mean'][c]['diff_vs_best'] = dict(best=best, mean=res['mean'][c]['mean'] - res['mean'][best]['mean'], ci=[lo, hi])
        if c in done_beta:
            (flat if (c == best or hi >= 0) else worse).append(c)
    res['finding'] = finding = dict(best=best, within_noise_of_best=flat, below_best=worse,
                                    all_beta_complete=len(done_beta) == len(BETA_COLS))
res['per_task_best'] = {}
for key, *_ in TASKS:
    cs = [c for c in BETA_COLS if data[(key, c)]['complete']]
    if cs:
        m = max(data[(key, c)]['mean'] for c in cs)
        res['per_task_best'][key] = [c for c in cs if abs(data[(key, c)]['mean'] - m) < 1e-9]
TNUM, STEM = ('R7', '_bfc_sweep_repro') if REPRO else ('R6', '_bfc_sweep')
json.dump(res, open(f'{ROOT}/status/beta_fixedcfg_table' + ('_repro' if REPRO else '') + '.json', 'w'), indent=1)

# ---------------------------------------------------------------- render
f1 = lambda x: f'{x:.1f}'
HDR = {'0.90': '0.90', '0.93': '0.93', '0.95': '0.95', '0.97': '0.97', '0.98': '0.98', '0.99': '0.99 (single hop)',
       'd1@0.90': 'no recursion'}


def hw(ci, m):
    return max(m - ci[0], ci[1] - m)


def cell(key, col, tex):
    r = res['mean'][col] if key == 'mean' else res['tasks'][key]['cells'][col]
    if not r.get('complete'):
        n = r.get('n', None)
        return ('pending' if tex else 'pending') + (f' (n={n})' if n else '')
    bold = (col in BETA_COLS) and (col == (finding or {}).get('best') if key == 'mean' else col in res['per_task_best'].get(key, []))
    m, h = r['mean'], hw(r['ci'], r['mean'])
    if tex:
        s = f'\\textbf{{{f1(m)}}}' if bold else f1(m)
        return s + f'{{\\scriptsize$\\pm${h:.1f}}}'
    return (f'**{f1(m)}**' if bold else f1(m)) + f' ±{h:.1f}'


def hcell(key, col):
    r = res['mean'][col] if key == 'mean' else res['tasks'][key]['cells'][col]
    if col in ('0.99', 'd1@0.90'):
        return '0'
    if key == 'mean':
        return f2(r['hops']) if r.get('complete') else '--'
    return f2(r['hops']) if r.get('hops') is not None and r.get('complete') else '--'


f2 = lambda x: f'{x:.2f}'


def dcell(col, tex):
    r = res['mean'][col]; d = r.get('diff_vs_best')
    if not d:
        return '--'
    if abs(d['mean']) < 1e-12 and d['ci'] == [0.0, 0.0]:
        return 'best'
    s = f"{d['mean']:+.1f} [{d['ci'][0]:+.1f},{d['ci'][1]:+.1f}]"
    return '{\\scriptsize ' + s + '}' if tex else s
exp_row = {c: ('0' if c in ('0.99', 'd1@0.90') else f2(exp_hops(float(c)))) for c in [x[0] for x in COLS]}

# Plain-language layer (TABLE_CLEANUP 2026-11-12): captions only say what differs from the document's protocol note
# (tasks, 450 episodes = 3 policy seeds x 3 evaluation seeds x 50, CI / bold meaning, gamma / beta, RSM (paper)).
if finding:
    fb = finding['best']; fl = finding['within_noise_of_best']
    fl_s = ', '.join(fl)
    take = (f"The 7-task mean peaks at beta={fb} ({f1(res['mean'][fb]['mean'])}%); betas whose paired 95% CI of the "
            f"difference to the peak contains 0: {fl_s}"
            + (f"; significantly below the peak: {', '.join(finding['below_best'])}" if finding['below_best'] else '')
            + ". " + ("The single hop (beta=gamma=0.99, no recursion) is "
                      + ("below the peak" if '0.99' in finding['below_best'] else "within noise of the peak")
                      + f" ({f1(res['mean']['0.99']['mean'])}%)." if res['mean']['0.99'].get('complete') else '')
            + ("" if finding['all_beta_complete'] else " [PARTIAL: some beta columns still pending]"))
else:
    take = '[PENDING: no complete beta column yet]'
foot = ("Betas below 0.90 lie outside the range the paper's models were trained for (0.90-0.995) and are not run on "
        "them; Table R2 of the rebuttal tables covers beta 0.80-0.99 with models fine-tuned to support smaller beta, and "
        "the paper's one-step world-model baselines (DINO-WM, LeWM in Table 1) are the short-horizon reference.")
if REPRO:
    foot = foot.replace("the paper's models were trained for (0.90-0.995) and are not run on them",
                        "Table R6's models were trained for and are not run here either")
TITLE = "How does varying beta affect aggregate performance?"
cap = ("One RSM setting for all 7 tasks (as defined in the protocol note); only beta changes, on the same episodes for "
       "every beta. "
       "+- = 95% CI half-width; bold = best beta per row. No recursion = the same model read once at beta 0.90, without "
       "chaining. Lower block: measured average number of hops per decision (expected value p/(1-p) with "
       "p=(gamma-beta)/(gamma(1-beta)) in its first row).")
if REPRO:
    cap = ("The same sweep on independently retrained RSM models (different training seed; 16 sampled futures per "
           "candidate, 8 sampling steps, 128 candidate actions; proposal policy and training step chosen per task by the "
           "paper's selection rule); only beta changes. n=150 episodes per cell (3 evaluation seeds x 50; the same "
           "episodes and candidate draws for every beta). +- = 95% CI half-width; bold = best beta per row. No recursion "
           "= the same model read once at beta 0.90. Lower block: measured average number of hops per decision (expected "
           "value in its first row).")

# ---- markdown
md = [f"**Table {TNUM}. {TITLE}" + (" (independently retrained models)" if REPRO else "") + f"** {cap}", "",
      "| Task | " + " | ".join(HDR[c[0]] for c in COLS) + " |", "|---" * (len(COLS) + 1) + "|"]
for key, lab, *_ in TASKS:
    md.append(f"| {lab} | " + " | ".join(cell(key, c[0], False) for c in COLS) + " |")
md.append("| **7-task mean** | " + " | ".join(cell('mean', c[0], False) for c in COLS) + " |")
md.append("| *difference to best beta, paired [95% CI]* | " + " | ".join(dcell(c[0], False) for c in COLS) + " |")
md += ["", "| Average hops per decision (measured) | " + " | ".join(HDR[c[0]] for c in COLS) + " |", "|---" * (len(COLS) + 1) + "|",
       "| *expected value p/(1-p)* | " + " | ".join(exp_row[c[0]] for c in COLS) + " |"]
for key, lab, *_ in TASKS:
    md.append(f"| {lab} | " + " | ".join(hcell(key, c[0]) for c in COLS) + " |")
md.append("| **7-task mean** | " + " | ".join(hcell('mean', c[0]) for c in COLS) + " |")
md_take = take + " " + foot
open(f'{D}/{STEM}.md', 'w').write("\n".join(md) + "\n\n" + md_take + "\n")

# ---- tex (caption = what differs; the takeaway line (last md line) is added under the table by the document assembler)
txc = lambda s: (s.replace('%', r'\%').replace('+-', r'$\pm$').replace('p=(gamma-beta)/(gamma(1-beta))', 'FORMULA')
                 .replace('p/(1-p)', '$p/(1-p)$').replace('beta', r'$\beta$').replace('gamma', r'$\gamma$')
                 .replace(' x ', r' $\times$ ').replace('FORMULA', r'$p=(\gamma-\beta)/(\gamma(1-\beta))$'))
L = [r"\begin{table}[h!]", r"\centering\small", r"\setlength{\tabcolsep}{4pt}",
     r"\caption{\textbf{" + TITLE.replace('beta', r'$\beta$') + ("" if not REPRO else " (independently retrained models)")
     + "} " + txc(cap) + "}",
     r"\label{tab:beta_fixed_config" + ("_repro" if REPRO else "") + "}",
     r"\resizebox{\linewidth}{!}{\begin{tabular}{l" + "c" * (len(COLS) - 1) + "|c}", r"\toprule",
     r"$\beta$ & " + " & ".join(HDR[c[0]] for c in COLS) + r" \\", r"\midrule"]
for key, lab, *_ in TASKS:
    L.append(f"{lab} & " + " & ".join(cell(key, c[0], True) for c in COLS) + r" \\")
L += [r"\midrule", r"\textbf{7-task mean} & " + " & ".join(cell('mean', c[0], True) for c in COLS) + r" \\",
      r"{\scriptsize difference to best $\beta$, paired} & " + " & ".join(dcell(c[0], True) for c in COLS) + r" \\",
      r"\midrule",
      r"\multicolumn{" + str(len(COLS) + 1) + r"}{l}{\emph{Average number of hops per decision (measured)}} \\",
      r"expected $p/(1-p)$ & " + " & ".join(exp_row[c[0]] for c in COLS) + r" \\", r"\midrule"]
for key, lab, *_ in TASKS:
    L.append(f"{lab} & " + " & ".join(hcell(key, c[0]) for c in COLS) + r" \\")
L += [r"\midrule", r"7-task mean & " + " & ".join(hcell('mean', c[0]) for c in COLS) + r" \\", r"\bottomrule",
      r"\end{tabular}}", r"\end{table}"]
frag = "\n".join(L)
open(f'{D}/{STEM}.tex', 'w').write(frag + "\n")
# standalone docs/rebuttal/beta_fixed_config.{tex,md} (Table 1 transfer + Table 2 sweep) is assembled by scripts/beta_fixedcfg_loto.py
print('WROTE', TNUM, STEM)
for col in [c[0] for c in COLS]:
    print(col, res['mean'][col])
print('finding', finding)