File size: 27,567 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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
#!/usr/bin/env python3
"""FAIR beta ablation for the flagship RSM (BETA_FAIR stream, owner 2026-11-08) -- STEP 1: coverage + run plan.

Every beta point uses the paper's proposer (flagship_latex.proposer_for) and the membership head, and the paper's
Table 6 successor model / checkpoint / particles / read-out / flow steps; ONLY beta (and the chain cap it implies)
changes.  Loader = verdict_table.cells(task), exclusions = plot_beta_sweep_best.file_check (gamma_scope 0.99 +
chain hop QC), exactly as status/beta_sweep_best.* uses.

beta = 0.99 = gamma: the coin chain has p = 0 (cap 0, "degenerate", excluded by verdict_table), i.e. it IS the
single-hop estimator at beta 0.99.  That point is therefore read from / planned as the d1 (fold depth 1) cell.
No-recursion control at beta b: the d1 cell (one hop at beta b, membership read once, no continuation).

Out: status/beta_fair_coverage.json, status/beta_fair_current.pdf, status/packs/beta_fair/payloads/*.sh,
     status/packs/beta_fair/plan.json
"""
import json, math, os, re, sys, glob, random, shlex, time
from collections import defaultdict
from pathlib import Path

ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
sys.path.insert(0, str(ROOT / "scripts"))
os.environ["RSM_EXTRA_EPOCHS"] = "500"
import verdict_table as VT
import beta_patterns_analyze as BP
import plot_beta_sweep_best as PB

GAMMA = 0.99
BETAS = [0.90, 0.93, 0.95, 0.97, 0.98, 0.99]
NEED_EPS = 50
OUT = ROOT / "status/packs/beta_fair"
PAY = OUT / "payloads"

# Paper Table 6 (owner) + rise_repro flagship_rsm_setting.tex (published cell files).  tag = cell-name tag
# before -es<E>; plab = proposer label in the cell name; paper = Table 1 RSM number.
SPEC = {
    "square_sub_20100": dict(label="Square (Sub.)", prop="RISE policy", model="M", ck="best", lab="Mb", P=16,
                             score="logit", flow=8, beta=0.98, tag="ONACTORP16lo", plab="S0A", paper=54.0,
                             paper_pm=1.3),
    "square_expert_play": dict(label="Square (Cov.)", prop="RISE policy", model="L40", ck="best", lab="L40b",
                               P=16, score="prob", flow=8, beta=0.90, tag="ONACTOR", plab="S0A", paper=20.9,
                               paper_pm=2.6),
    "two_piece_expert_suboptimal": dict(label="Piece (Sub.)", prop="RISE policy", model="M", ck="s100000",
                                        lab="Ms100k", P=8, score="prob", flow=8, beta=0.95, tag="ONACTORP8pr",
                                        plab="S0A", paper=47.1, paper_pm=3.5),
    "two_piece_expert_play": dict(label="Piece (Cov.)", prop="RISE policy", model="L40", ck="best", lab="L40b",
                                  P=16, score="prob", flow=8, beta=0.98, tag="ONACTOR", plab="S0A", paper=48.7,
                                  paper_pm=0.7),
    "mug_expert_suboptimal": dict(label="Mug (Sub.)", prop="BC-expert", model="M_s1", ck="best", lab="Ms1b",
                                  P=16, score="logit", flow=8, beta=0.98, tag="ONS3H1P16lo", plab="S3H1",
                                  paper=23.1, paper_pm=2.1),
    "threading_expert_play": dict(label="Thread (Cov.)", prop="IDQL policy@500", model="M", ck="best", lab="Mb",
                                  P=8, score="prob", flow=8, beta=0.98, tag="ONS0AidqlE500P8pr",
                                  plab="S0AidqlE500", paper=25.8, paper_pm=1.1),
    "two_piece_expert_play_tipping": dict(label="Piece-tip (Cov.)", prop="RISE policy", model="M", ck="best",
                                          lab="Mb", P=16, score="prob", flow=4, beta=0.95, tag="ONACTORF4",
                                          plab="S0A", paper=7.3, paper_pm=0.4),
}
REC = re.compile(r"^(?P<model>\S+)@(?P<ck>\S+) b(?P<beta>[0-9.]+) (?P<len>(?:CHRB|CH|L)\d+) N(?P<n>\d+)"
                 r"(?: P(?P<P>\d+) (?P<score>\S+))?(?P<rest>.*)$")


def cap_for(beta, gamma=GAMMA, eps=1e-3):
    p = (gamma - beta) / (gamma * (1.0 - beta))
    return 0 if p <= 0 else int(math.ceil(math.log(eps) / math.log(p)))


def boot_ci(succ, B=2000, seed=0):
    if not succ:
        return None, None
    rng = random.Random(seed); n = len(succ); s = list(succ)
    m = sorted(sum(s[rng.randrange(n)] for _ in range(n)) / n for _ in range(B))
    return m[int(0.025 * B)], m[int(0.975 * B) - 1]


def classify(sp, r):
    """-> (kind, diffs): kind in {matched_chain, matched_d1, other}; diffs = list of knobs that differ."""
    d = []
    if r["model"] != sp["model"]: d.append(f"model {r['model']}")
    if r["ck"] != sp["ck"]: d.append(f"ckpt {r['ck']}")
    if int(r["n"]) != 128: d.append(f"N{r['n']}")
    if r["P"] is None or int(r["P"]) != sp["P"]: d.append(f"P{r['P']}")
    if r["score"] != sp["score"]: d.append(f"readout {r['score']}")
    rest = r["rest"].strip()
    want_rest = "" if sp["flow"] == 8 else f"F{sp['flow']}"
    if rest != want_rest: d.append(f"extra '{rest}'")
    L = r["len"]
    if L.startswith("CHRB"):
        d.append(f"len {L}"); kind = "other"
    elif L.startswith("CH"):
        cap = int(L[2:]); want = cap_for(float(r["beta"]))
        if cap != want: d.append(f"cap {cap}!={want}")
        kind = "matched_chain"
    elif L == "L1":
        kind = "matched_d1"
    else:
        d.append(f"fold {L}"); kind = "other"
    return (kind if not d else "other"), d


def task_cells(task):
    sp = SPEC[task]
    cs = VT.cells(task)
    files = dict(VT.CELL_FILES)
    pols = sorted({k[1] for k in cs})
    heads_on_prop = defaultdict(int)
    groups = defaultdict(lambda: dict(cells={}, kind=None, diffs=None, beta=None, recipe=None))
    excl = defaultdict(int); seedfmt = set()
    for key, succ in cs.items():
        (head, recipe), pol, pseed, eseed = key
        if pol != sp["prop"] or not head.startswith("rsm:"):
            continue
        heads_on_prop[head] += 1
        if head != "rsm:membership":
            continue
        m = REC.match(recipe)
        if not m:
            excl["unparsed recipe"] += 1; continue
        seedfmt.add((str(pseed), str(eseed)))
        r = m.groupdict(); beta = float(r["beta"])
        kind, diffs = classify(sp, r)
        is_chain = r["len"].startswith("CH")
        kept, fl, nq, dropped = [], [], [], []
        for f in files.get(key, []):
            ok, why, n, s = PB.file_check(f, beta, is_chain)
            if ok:
                kept += s; fl.append(str(f)); nq += s
            else:
                excl[why.split(" (")[0]] += 1
                if why.startswith("chain:") and "beta>=gamma" not in why:
                    nq += s; dropped.append(dict(file=str(f), why=why, n=n, s=sum(s)))
        if not kept and not dropped:
            continue
        g = groups[recipe]
        g.setdefault("noqc", {})[f"{pseed}|{eseed}"] = nq
        g.setdefault("qc_dropped", {}).update({f"{pseed}|{eseed}": dropped} if dropped else {})
        if not kept:
            g.update(kind=classify(sp, r)[0], diffs=classify(sp, r)[1], beta=beta, recipe=recipe, len=r["len"])
            continue
        g.update(kind=kind, diffs=diffs, beta=beta, recipe=recipe, len=r["len"])
        g["cells"][f"{pseed}|{eseed}"] = dict(pseed=str(pseed), eseed=str(eseed), n=len(kept), s=sum(kept),
                                              succ=kept, files=fl)
    return pols, dict(heads_on_prop), groups, dict(excl), seedfmt


def summarize(g, paper_keys=None):
    allsucc = [x for c in g["cells"].values() for x in c["succ"]]
    lo, hi = boot_ci(allsucc)
    nq = [x for v in (g.get("noqc") or {}).values() for x in v]
    ps = sorted({c["pseed"] for c in g["cells"].values()}); es = sorted({c["eseed"] for c in g["cells"].values()})
    out = dict(recipe=g["recipe"], beta=g["beta"], kind=g["kind"], diffs=g["diffs"], n=len(allsucc),
               succ=(sum(allsucc) / len(allsucc)) if allsucc else None, ci95=[lo, hi], pseeds=ps, eseeds=es,
               cells={k: dict(n=c["n"], s=c["s"], files=c["files"]) for k, c in sorted(g["cells"].items())},
               qc_dropped=g.get("qc_dropped") or {}, n_noqc=len(nq), succ_noqc=(sum(nq) / len(nq)) if nq else None)
    if paper_keys is not None:
        have = {k for k, c in g["cells"].items() if c["n"] >= NEED_EPS}
        out["qc_dropped_cells"] = sorted(set(out["qc_dropped"]) & set(paper_keys) - have)
        out["missing_cells"] = sorted(set(paper_keys) - have - set(out["qc_dropped_cells"]))
        out["short_cells"] = sorted(k for k, c in g["cells"].items() if c["n"] < NEED_EPS and k in paper_keys)
        out["extra_cells"] = sorted(set(g["cells"]) - set(paper_keys))
        out["coverage"] = ("FULL" if not out["missing_cells"] and not out["qc_dropped_cells"] and not out["short_cells"]
                           and out["n"] >= 9 * NEED_EPS else
                           "PARTIAL(QC-drop only)" if not out["missing_cells"] and not out["short_cells"] else "PARTIAL")
    return out


def band_of(task, sp):
    p = ROOT / f"runs/{task}/rsm/{sp['model']}/ckpt_{sp['ck']}.pt"
    try:
        import torch
        ck = torch.load(p, map_location="cpu", weights_only=False)
        c = ck.get("config") or {}
        return dict(path=str(p), beta_lo=c.get("beta_lo"), beta_hi=c.get("beta_hi"), step=ck.get("step"),
                    mtime=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(p.stat().st_mtime)),
                    cfg={k: c.get(k) for k in ("enc", "d_z", "flow_width", "flow_depth", "chunk")})
    except Exception as e:
        return dict(path=str(p), error=f"{type(e).__name__}: {e}")


def find_template(task, sp):
    """the eval_cell.sh line of an existing payload that produced the paper cell (any seed)."""
    pat = f"E1-{sp['lab']}-R{sp['beta']:.2f}-{cap_for(sp['beta'])}-ch-N128-argmax-{sp['tag']}-es"
    for d in sorted(glob.glob(str(ROOT / f"runs/{task}/eval*/jobs"))):
        for sh in sorted(glob.glob(d + "/*.sh")):
            try:
                txt = open(sh).read()
            except Exception:
                continue
            for line in txt.splitlines():
                if "scripts/eval_cell.sh" in line and pat in line:
                    return sh, line.strip()
    return None, None


def build_cmd(task, sp, tmpl_line, beta, mode, pseed_lab, policy_ckpt, eseed, out_dir):
    """Rewrite the paper payload's eval_cell.sh call: change ONLY beta / cap (or chain -> d1), seed paths."""
    toks = shlex.split(tmpl_line.split(" 2>&1 | tee ")[0])
    # toks: eval_cell.sh task ckpt env json overrides...
    env = toks[3]
    assert toks[4].endswith(".json"), toks[:6]
    ov = [t for t in toks[5:]]
    assert all("=" in t for t in ov), [t for t in ov if "=" not in t]
    keep = [t for t in ov if not re.match(r"^(exp\.eval_seed|exp\.eval_cell|training\.plan_beta|training\.plan_mode|"
                                          r"training\.plan_depth|training\.plan_chain_cap)=", t)]
    if mode == "chain":
        cap = cap_for(beta)
        name = f"E1-{sp['lab']}-R{beta:.2f}-{cap}-ch-N128-argmax-{sp['tag']}-es{eseed}-s{pseed_lab}"
        rd = ["training.plan_mode=chain", "training.plan_depth=1", f"training.plan_beta={beta}",
              f"training.plan_chain_cap={cap}"]
    else:   # d1: one hop at beta, membership read once, no continuation
        name = f"E1-{sp['lab']}-R{beta:.2f}-1-N128-argmax-{sp['tag']}-es{eseed}-s{pseed_lab}"
        rd = ["training.plan_mode=d1", "training.plan_depth=1", f"training.plan_beta={beta}"]
    js = out_dir / f"{name}.json"
    keep = [t for t in keep if not t.startswith("exp.eval_seed") and not t.startswith("exp.eval_cell")]
    pre = [t for t in keep if t.startswith("exp.")]; post = [t for t in keep if not t.startswith("exp.")]
    cmd = [str(ROOT / "scripts/eval_cell.sh"), task, policy_ckpt, env, str(js), *pre,
           f"exp.eval_seed={eseed}", f"exp.eval_cell={name}", *rd, *post]
    return name, js, cmd


def cell_block(name, js, cmd, out_dir):
    q = shlex.quote; log = out_dir / "logs" / f"{name}.log"
    return (f"if [ -f {q(str(js))} ]; then echo \"[beta_fair] {name} exists, skip\"; else\n"
            f"  {' '.join(q(c) for c in cmd)} 2>&1 | tee {q(str(log))}; rc=${{PIPESTATUS[0]}}\n"
            f"  if [ -f {q(str(js))} ]; then python {ROOT}/scripts/wandb_log_eval.py {q(str(js))} || true\n"
            f"  else rm -f {q(str(js) + '.tmp')}; rc_all=${{rc:-1}}; echo \"[beta_fair] {name} FAILED rc=$rc\"; fi\n"
            f"fi\n")


def main():
    res, plan_cells = {}, []
    for task, sp in SPEC.items():
        print(f"=== {task}", flush=True)
        pols, heads, groups, excl, seedfmt = task_cells(task)
        paper_recipe = None
        for rec, g in groups.items():
            if g["kind"] == "matched_chain" and abs(g["beta"] - sp["beta"]) < 1e-9:
                paper_recipe = rec
        paper_have = sorted(groups[paper_recipe]["cells"]) if paper_recipe else []
        ps_ = sorted({k.split("|")[0] for k in paper_have}); es_ = sorted({k.split("|")[1] for k in paper_have})
        paper_keys = sorted(f"{a}|{b}" for a in ps_ for b in es_)   # the full policy x eval seed grid
        assert len(paper_keys) == 9, (task, paper_keys)
        pg = summarize(groups[paper_recipe], paper_keys) if paper_recipe else None
        matched, d1, other = [], [], []
        for rec, g in sorted(groups.items(), key=lambda kv: (kv[1]["beta"], kv[0])):
            s = summarize(g, paper_keys)
            (matched if g["kind"] == "matched_chain" else d1 if g["kind"] == "matched_d1" else other).append(s)
        tmpl_sh, tmpl = find_template(task, sp)
        # proposer checkpoints by seed label, from the paper cell JSONs
        pol_ck = {}
        if pg:
            for k, c in pg["cells"].items():
                for f in c["files"]:
                    try:
                        pol_ck[k.split("|")[0]] = json.load(open(f))["eval_ckpt"]
                    except Exception:
                        pass
        # wall time per cell of the paper arm
        walls = []
        if pg:
            for c in pg["cells"].values():
                for f in c["files"]:
                    try:
                        j = json.load(open(f)); walls.append(float(j.get("wall_time_s") or 0) / max(1, j["num_episodes"]) * 50)
                    except Exception:
                        pass
        wall50 = (sorted(walls)[len(walls) // 2] if walls else None)
        wpts = []
        for s_ in [g for g in groups.values() if g["kind"] in ("matched_chain", "matched_d1")]:
            E_ = BP.expected_hops(s_["beta"], GAMMA) if s_["kind"] == "matched_chain" else 0.0
            for c in s_["cells"].values():
                for f in c["files"]:
                    try:
                        j = json.load(open(f)); wpts.append((max(E_, 0.0), float(j["wall_time_s"]) / max(1, j["num_episodes"]) * 50))
                    except Exception:
                        pass
        wfit = None
        if len({round(e, 3) for e, _ in wpts}) >= 2:
            n_ = len(wpts); mx = sum(e for e, _ in wpts) / n_; my = sum(w for _, w in wpts) / n_
            vb = sum((e - mx) ** 2 for e, _ in wpts)
            bb = sum((e - mx) * (w - my) for e, w in wpts) / vb if vb > 0 else 0.0
            wfit = (my - bb * mx, max(bb, 0.0))
        cov = {}
        for b in BETAS:
            if abs(b - GAMMA) < 1e-9:
                cand = [s for s in d1 if abs(s["beta"] - b) < 1e-9]; mode = "d1"
            else:
                cand = [s for s in matched if abs(s["beta"] - b) < 1e-9]; mode = "chain"
            if cand:
                s = cand[0]
                cov[f"{b:.2f}"] = dict(status=s["coverage"], mode=mode, n=s["n"], succ=s["succ"],
                                       missing=s["missing_cells"], short=s["short_cells"], recipe=s["recipe"])
                miss = s["missing_cells"] + s["short_cells"]
                cov[f"{b:.2f}"].update(qc_dropped=s["qc_dropped_cells"], n_noqc=s["n_noqc"], succ_noqc=s["succ_noqc"])
            else:
                cov[f"{b:.2f}"] = dict(status="MISSING", mode=mode, n=0, missing=paper_keys)
                miss = list(paper_keys)
            for k in miss:
                plan_cells.append(dict(task=task, beta=b, mode=mode, key=k, wall50=wall50))
        # no-recursion control at the smallest-beta matched point with the best success (among chain betas<0.99)
        chain_pts = [s for s in matched if s["n"] > 0 and s["beta"] <= 0.95 + 1e-9]
        best_small = (max(chain_pts, key=lambda s: (s["succ"], s["n"]))["beta"] if chain_pts else sp["beta"])
        ctrl = [s for s in d1 if abs(s["beta"] - best_small) < 1e-9]
        ctrl_status = (ctrl[0]["coverage"] if ctrl else "MISSING")
        if ctrl_status != "FULL" and abs(best_small - GAMMA) > 1e-9:
            miss = (ctrl[0]["missing_cells"] + ctrl[0]["short_cells"]) if ctrl else list(paper_keys)
            for k in miss:
                plan_cells.append(dict(task=task, beta=best_small, mode="d1", key=k, wall50=wall50, control=True))
        res[task] = dict(spec=sp, pols=pols, heads_on_proposer=heads, exclusions=excl, paper_recipe=paper_recipe,
                         paper_cell=pg, paper_keys=paper_keys, matched=matched, d1=d1, other=other,
                         coverage=cov, norec_control=dict(beta=best_small, status=ctrl_status,
                                                          cell=(ctrl[0] if ctrl else None)),
                         band=band_of(task, sp), template_payload=tmpl_sh, template_line=tmpl,
                         policy_ckpts=pol_ck, wall_s_per_50=wall50, wall_fit=wfit)
        print(f"   pols={pols}\n   heads={heads}\n   paper={paper_recipe} n={pg and pg['n']} succ={pg and pg['succ']}"
              f"  keys={paper_keys}\n   band={res[task]['band']}\n   template={tmpl_sh}", flush=True)
        for s in matched + d1:
            print(f"   [{s['kind']}] b{s['beta']} {s['recipe']}: {s['coverage']} n={s['n']} "
                  f"{100 * (s['succ'] or 0):.1f}% miss={s['missing_cells']} short={s['short_cells']} "
                  f"qcdrop={s['qc_dropped_cells']} noqc n={s['n_noqc']} {100 * (s['succ_noqc'] or 0):.1f}%")
        for s in other:
            print(f"   [other] b{s['beta']} {s['recipe']}: n={s['n']} {100 * (s['succ'] or 0):.1f}% diffs={s['diffs']}")

    # ---- payloads -----------------------------------------------------------------------------------------
    PAY.mkdir(parents=True, exist_ok=True)
    for old in PAY.glob("*.sh"):
        old.unlink()
    jobs = []
    for pc in plan_cells:
        r = res[pc["task"]]; sp = r["spec"]
        if not r["template_line"]:
            pc["error"] = "no template payload found"; continue
        pseed_lab, eseed = pc["key"].split("|")
        ck = r["policy_ckpts"].get(pseed_lab)
        if not ck:
            pc["error"] = f"no proposer ckpt for seed {pseed_lab}"; continue
        out_dir = ROOT / f"runs/{pc['task']}/eval_onactor"
        es = re.sub(r"\D", "", eseed)
        ps = pseed_lab if pseed_lab.startswith(sp["plab"]) else f"{sp['plab']}s{re.sub(chr(92)+'D', '', pseed_lab)}"
        name, js, cmd = build_cmd(pc["task"], sp, r["template_line"], pc["beta"], pc["mode"], ps, ck, es, out_dir)
        if js.exists():
            pc["note"] = "json already exists (excluded by QC or loader?)"
        E = BP.expected_hops(pc["beta"], GAMMA) if pc["mode"] == "chain" else 0.0
        if r["wall_fit"]:
            w = r["wall_fit"][0] + r["wall_fit"][1] * E
        else:
            E0 = BP.expected_hops(sp["beta"], GAMMA)
            w = (pc["wall50"] or 900.0) * (0.55 + 0.45 * max(E, 1.0) / max(E0, 1.0))
        w *= 1.15   # margin: node variance / resume overhead
        pc.update(name=name, json=str(js), est_s=w, cmd=cmd, out_dir=str(out_dir))
        jobs.append(pc)
    # LPT per task into payloads; total payload count a multiple of 8 so every node is full
    TARGET = 3 * 3600.0
    tot = sum(j["est_s"] for j in jobs)
    npay = max(8, int(math.ceil(tot / TARGET / 8.0)) * 8) if jobs else 0
    by_task = defaultdict(list)
    for j in jobs:
        by_task[j["task"]].append(j)
    alloc = {t: max(1, round(npay * sum(x["est_s"] for x in L) / tot)) for t, L in by_task.items()} if jobs else {}
    while jobs and sum(alloc.values()) != npay:   # fix rounding so the node count stays exact
        t = max(alloc, key=lambda t: sum(x["est_s"] for x in by_task[t]) / alloc[t]) if sum(alloc.values()) < npay \
            else max((t for t in alloc if alloc[t] > 1), key=lambda t: -sum(x["est_s"] for x in by_task[t]) / alloc[t])
        alloc[t] += 1 if sum(alloc.values()) < npay else -1
    payloads = []
    for t in sorted(by_task):
        bins = [dict(task=t, cells=[], s=0.0) for _ in range(min(alloc[t], len(by_task[t])))]
        for j in sorted(by_task[t], key=lambda x: -x["est_s"]):
            b = min(bins, key=lambda b: b["s"]); b["cells"].append(j); b["s"] += j["est_s"]
        payloads += bins
    for i, b in enumerate(payloads):
        lines = ["#!/usr/bin/env bash", "set -uo pipefail", f"cd {ROOT}", "rc_all=0",
                 "echo \"[beta_fair] host=$(hostname) job=${SLURM_JOB_ID:-none} gpu=${CUDA_VISIBLE_DEVICES:-?}\""]
        for j in b["cells"]:
            lines.append(f"mkdir -p {shlex.quote(j['out_dir'] + '/logs')}")
            lines.append(cell_block(j["name"], Path(j["json"]), j["cmd"], Path(j["out_dir"])))
        lines.append("exit $rc_all")
        p = PAY / f"bf_{i:03d}_{b['task']}.sh"
        p.write_text("\n".join(lines) + "\n"); p.chmod(0o755)
        b["path"] = str(p)
    nodes = [payloads[k:k + 8] for k in range(0, len(payloads), 8)]
    plan = dict(n_cells=len(jobs), n_eps=50 * len(jobs), gpu_hours=tot / 3600.0, n_payloads=len(payloads),
                n_nodes=len(nodes), payload_hours=[b["s"] / 3600.0 for b in payloads],
                nodes=[[b["path"] for b in nd] for nd in nodes],
                cells=[{k: v for k, v in j.items() if k != "cmd"} for j in jobs],
                unplanned=[pc for pc in plan_cells if "error" in pc],
                per_task={t: dict(cells=len(L), gpu_h=sum(x["est_s"] for x in L) / 3600.0) for t, L in by_task.items()})
    json.dump(plan, open(OUT / "plan.json", "w"), indent=1, default=str)
    print(f"PLAN: {plan['n_cells']} cells, {plan['n_eps']} eps, {plan['gpu_hours']:.1f} GPU-h, "
          f"{plan['n_payloads']} payloads on {plan['n_nodes']} 8-GPU nodes; per task {plan['per_task']}; "
          f"unplanned {len(plan['unplanned'])}")

    # ---- plot ---------------------------------------------------------------------------------------------
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    tasks = list(SPEC)
    fig, axs = plt.subplots(2, 4, figsize=(19, 8.4), squeeze=False)
    xpos = lambda b: -math.log10(1 - b + 1e-9)
    for ax, t in zip(axs.flat, tasks):
        r = res[t]; sp = r["spec"]
        pts = []
        for b in BETAS:
            src = r["d1"] if abs(b - GAMMA) < 1e-9 else r["matched"]
            c = [s for s in src if abs(s["beta"] - b) < 1e-9 and s["n"] > 0]
            if c:
                pts.append((b, c[0]))
        xs = [xpos(b) for b, _ in pts]; ys = [100 * s["succ"] for _, s in pts]
        lo = [100 * (s["succ"] - s["ci95"][0]) for _, s in pts]; hi = [100 * (s["ci95"][1] - s["succ"]) for _, s in pts]
        if pts:
            ax.plot(xs, ys, "-", color="#2a6fdb", lw=1.2, alpha=0.6)
        for (b, s), x, y, l, h in zip(pts, xs, ys, lo, hi):
            full = s.get("coverage") == "FULL"
            ax.errorbar([x], [y], yerr=[[l], [h]], fmt="o", color="#2a6fdb", mfc="#2a6fdb" if full else "white",
                        ms=7, capsize=3, lw=1.2)
            ax.annotate(f"n={s['n']}", (x, y + h), textcoords="offset points", xytext=(0, 4), ha="center",
                        fontsize=7.5)
            if s.get("n_noqc") and s["n_noqc"] != s["n"]:
                ax.plot([x + 0.03], [100 * s["succ_noqc"]], marker="d", color="#888", ms=5)
                ax.annotate(f"no hop-QC n={s['n_noqc']}", (x + 0.03, 100 * s["succ_noqc"]), textcoords="offset points",
                            xytext=(4, -9), fontsize=6.5, color="#666")
        miss = [b for b in BETAS if not any(abs(b - pb) < 1e-9 for pb, _ in pts)]
        for b in miss:
            ax.plot([xpos(b)], [1], marker="x", color="#c0392b", ms=8)
        ctl = r["norec_control"]["cell"]
        if ctl and ctl["n"] > 0:
            ax.errorbar([xpos(ctl["beta"]) + 0.03], [100 * ctl["succ"]],
                        yerr=[[100 * (ctl["succ"] - ctl["ci95"][0])], [100 * (ctl["ci95"][1] - ctl["succ"])]],
                        fmt="s", color="#e67e22", ms=6, capsize=3, label="1 hop, no recursion")
        ax.axhline(sp["paper"], color="#555", ls="--", lw=1)
        ax.plot([xpos(sp["beta"])], [sp["paper"]], marker="*", color="#555", ms=13,
                label=f"paper T1 {sp['paper']} (b{sp['beta']})")
        ax.set_xticks([xpos(b) for b in BETAS]); ax.set_xticklabels([f"{b:g}" for b in BETAS], fontsize=8)
        top = max([sp["paper"]] + [y + h for y, h in zip(ys, hi)] + [5])
        ax.set_ylim(0, min(100, top * 1.2 + 3))
        ax.set_title(f"{sp['label']} [{t}]\n{sp['prop']} | {sp['model']}@{sp['ck']} P{sp['P']} {sp['score']}"
                     + (f" F{sp['flow']}" if sp['flow'] != 8 else ""), fontsize=8.5)
        ax.set_xlabel("beta (b0.99 = single hop = chain with p=0)", fontsize=8); ax.set_ylabel("success (%)")
        ax.grid(alpha=0.3); ax.legend(fontsize=7, loc="lower left")
    ax = axs.flat[-1]; ax.axis("off")
    ax.text(0, 0.95, "FAIR beta ablation (matched cells only)\n\n"
            "filled = FULL (3 policy x 3 eval seeds, 450 eps)\nhollow = PARTIAL  red x = MISSING\n"
            "grey diamond = same cells without the chain hop-QC drop (paper rule)\n"
            "error bars: 95% bootstrap CI over episodes\nsame proposer + membership head + model/ckpt/P/readout\n"
            "as paper Table 6; only beta (and its chain cap) varies\n"
            "gamma=0.99 scope + chain hop QC as beta_sweep_best", va="top", fontsize=9)
    fig.suptitle("RSM success vs beta, paper-matched settings only (status/beta_fair_current.pdf)", fontsize=11)
    fig.tight_layout(rect=(0, 0, 1, 0.95))
    fig.savefig(ROOT / "status/beta_fair_current.pdf"); plt.close(fig)

    # strip per-episode lists before dumping
    json.dump(dict(stamp=VT.build_stamp(("verdict_table",)), betas=BETAS, tasks=res, plan_summary={
        k: plan[k] for k in ("n_cells", "n_eps", "gpu_hours", "n_payloads", "n_nodes", "per_task")}),
        open(ROOT / "status/beta_fair_coverage.json", "w"), indent=1, default=str)
    print("wrote status/beta_fair_coverage.json status/beta_fair_current.pdf", flush=True)

    # ---- flagship cross-check (what the paper's RSM column actually selects) --------------------------------
    try:
        import flagship_latex as FL
        print("FL.RSM_PROPOSER", FL.RSM_PROPOSER, "PROPOSER_BY_TASK", FL.PROPOSER_BY_TASK,
              "ALLOWED", FL._ALLOWED_RSM_FAMILIES, flush=True)
        rows, _ = FL.build(VT.cells)
        fx = [dict(task=r["task"], label=r["label"], proposer=r.get("proposer_used"), arm=r.get("arm"),
                   chain_arm=r.get("rsm_chain_arm"), chain_rate=r.get("rsm_chain_rate"), chain_n=r.get("rsm_chain_n"),
                   pooled=r.get("pooled"), eps=r.get("eps"), rsm_cell=r.get("rsm"), chain_disp=r.get("rsm_chain_disp"))
              for r in rows]
        json.dump(fx, open(OUT / "flagship_selection.json", "w"), indent=1, default=str)
        for x in fx:
            print("FLAGSHIP", x, flush=True)
    except BaseException as e:
        print("flagship cross-check failed:", type(e).__name__, str(e)[:500], flush=True)


if __name__ == "__main__":
    main()