File size: 9,505 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
#!/usr/bin/env python3
"""BETA_FIXEDCFG (owner 2026-11-11): ONE fixed RSM config "C" (L40, P16, prob, F8, N128, gamma 0.99, chain cap rule,
paper checkpoint rule) on all 7 tasks, swept over beta.
  chain cells: beta 0.90 (cap 73), 0.93 (48), 0.97 (18)          [0.95/0.98 exist from REBUTTAL_DEFAULT_BETA]
  d1 cells   : beta 0.99 (= gamma: single hop) and beta 0.90 (no-recursion control)
Sq-C (square_expert_play) / Pc-C (two_piece_expert_play): config C = their paper L40b '' cells -> all exist already.
Other 5 tasks: clone rule of scripts/rebuttal_default_beta_gen_cd.py (copied, NOT imported: that script rewrites its payloads
on import). Validation, all asserted:
  (1) every existing paper-cell CHAIN block of the task is reproduced byte-for-byte from one template;
  (2) every existing paper-cell D1 block (R<b>-1-N128) is reproduced byte-for-byte by the d1 transform of that template;
  (3) the config-C clones at 0.95/0.98 reproduce byte-for-byte the commands that produced the existing C cells
      (status/packs/rebuttal_default_beta/payloads_cd/rdbcd_*.sh), and their JSONs' planner_overrides/eval_ckpt.
d1 transform = cell 'R<b>-<cap>-ch-N128' -> 'R<b>-1-N128', plan_mode=chain -> d1, drop training.plan_chain_cap=<cap>.
"""
import glob, json, os, re, sys
ROOT = '/proj/dmfexp/zwhong/rsm_rise'
OUT = f'{ROOT}/status/packs/beta_fixedcfg'
CAP = {'0.90': 73, '0.93': 48, '0.95': 33, '0.97': 18, '0.98': 11}
T = {
 'square_sub_20100': ('Mb', 'ACTOR', 'S0A', 'P16lo', ' training.plan_particles=16 training.plan_score=logit', 'M/ckpt_best.pt', 'L40b', 'L40/ckpt_best.pt'),
 'two_piece_expert_suboptimal': ('Ms100k', 'ACTOR', 'S0A', 'P8pr', ' training.plan_particles=8 training.plan_score=prob', 'M/ckpt_s100000.pt', 'L40s100k', 'L40/ckpt_s100000.pt'),
 'mug_expert_suboptimal': ('Ms1b', 'S3H1', 'S3H1', 'P16lo', ' training.plan_particles=16 training.plan_score=logit', 'M_s1/ckpt_best.pt', 'L40b', 'L40/ckpt_best.pt'),
 'threading_expert_play': ('Mb', 'S0AidqlE500', 'S0AidqlE500', 'P8pr', ' training.plan_particles=8 training.plan_score=prob', 'M/ckpt_best.pt', 'L40b', 'L40/ckpt_best.pt'),
 'two_piece_expert_play_tipping': ('Mb', 'ACTOR', 'S0A', 'F4', ' training.plan_flow_steps=4', 'M/ckpt_best.pt', 'L40b', 'L40/ckpt_best.pt'),
}
cmd_re = re.compile(r'(/proj/dmfexp/zwhong/rsm_rise/scripts/eval_cell\.sh (\S+) .*?) 2>&1')


def read_cmds(globs):
    out = {}
    for g in globs:
        for f in sorted(glob.glob(g)):
            for m in cmd_re.finditer(open(f).read()):
                c = m.group(1); out[(m.group(2), re.search(r'exp\.eval_cell=(\S+)', c).group(1))] = c
    return out


cmds = read_cmds([f'{ROOT}/status/packs/beta_fair/payloads*/*.sh', f'{ROOT}/status/packs/rebuttal_beta/payloads*/*.sh'])
cd_cmds = read_cmds([f'{ROOT}/status/packs/rebuttal_default_beta/payloads_cd/*.sh'])


def pat(task):
    tag, on, sp, suf, *_ = T[task]
    return re.compile(rf'^E1-{tag}-R(0\.\d+)-(\d+)-ch-N128-argmax-ON{on}{suf}-es(\d)-s{sp}s(\d)$')


def pat_d1(task):
    tag, on, sp, suf, *_ = T[task]
    return re.compile(rf'^E1-{tag}-R(0\.\d+)-1-N128-argmax-ON{on}{suf}-es(\d)-s{sp}s(\d)$')


POL = {}
for (task, cell), c in cmds.items():
    if task in T and pat(task).match(cell):
        ps = int(pat(task).match(cell).group(4))
        POL.setdefault((task, ps), set()).add(re.search(r'eval_cell\.sh \S+ (\S+) ', c).group(1))
for k, v in POL.items():
    assert len(v) == 1, (k, v)
POL = {k: v.pop() for k, v in POL.items()}


def clone(c, task, beta, es, ps, size='M', extra=None, mode='chain'):
    """extra=None: keep the paper knobs; '' : fixed config C knobs (P16 prob F8). mode 'chain' | 'd1'."""
    tag, on, sp, suf, ko, mck, ltag, lck = T[task]
    ob, ocap, oes, ops = pat(task).match(re.search(r'exp\.eval_cell=(\S+)', c).group(1)).groups()
    oldcell = f'E1-{tag}-R{ob}-{ocap}-ch-N128-argmax-ON{on}{suf}-es{oes}-s{sp}s{ops}'
    ntag = tag if size == 'M' else ltag
    nsuf = suf if extra is None else extra
    mid = f'{CAP[beta]}-ch' if mode == 'chain' else '1'
    newcell = f'E1-{ntag}-R{beta}-{mid}-N128-argmax-ON{on}{nsuf}-es{es}-s{sp}s{ps}'
    n = c.replace(oldcell, newcell).replace(POL[(task, int(ops))], POL[(task, ps)])
    n = n.replace(f'exp.eval_seed={oes} ', f'exp.eval_seed={es} ')
    assert f'training.plan_beta={float(ob)} ' in n
    n = n.replace(f'training.plan_beta={float(ob)} ', f'training.plan_beta={float(beta)} ')
    assert f' training.plan_chain_cap={ocap} ' in n and ' training.plan_mode=chain ' in n
    if mode == 'chain':
        n = n.replace(f'training.plan_chain_cap={ocap} ', f'training.plan_chain_cap={CAP[beta]} ')
    else:
        n = n.replace(f' training.plan_chain_cap={ocap} ', ' ').replace(' training.plan_mode=chain ', ' training.plan_mode=d1 ')
    if size == 'L40':
        assert f'/rsm/{mck} ' in n
        n = n.replace(f'/runs/{task}/rsm/{mck} ', f'/runs/{task}/rsm/{lck} ')
    if extra is not None:
        assert n.endswith(ko), n[-80:]
        n = n[:-len(ko)]
        assert extra == ''
    return n, newcell


def check_json(cmd, js):
    j = json.load(open(js)); po = j['planner_overrides']
    for k, v in re.findall(r'training\.(\S+)=(\S+)', cmd):
        jv = po.get(k)
        assert str(jv) == v or (isinstance(jv, float) and float(v) == jv), (js, k, v, jv)
    for k, d in [('plan_particles', 16), ('plan_score', 'prob'), ('plan_flow_steps', 8)]:
        if f'training.{k}=' not in cmd:
            assert po[k] == d, (js, k, po[k])
    assert j['eval_ckpt'] in cmd


BETAS_CH = sys.argv[1].split(',') if len(sys.argv) > 1 else ['0.90', '0.93', '0.97']
D1_BETAS = ['0.99', '0.90']
nval = nd1 = ncd = 0; tmpl = {}
for task in T:
    ex = {k[1]: v for k, v in cmds.items() if k[0] == task and pat(task).match(k[1])}
    tk = sorted(ex)[0]; tmpl[task] = ex[tk]
    for k, v in ex.items():
        b, cap, es, ps = pat(task).match(k).groups()
        if b not in CAP: continue
        g, _ = clone(ex[tk], task, b, int(es), int(ps))
        assert g == v, (k, g, v); nval += 1
    exd = {k[1]: v for k, v in cmds.items() if k[0] == task and pat_d1(task).match(k[1])}
    for k, v in exd.items():
        b, es, ps = pat_d1(task).match(k).groups()
        if b not in CAP and b != '0.99': continue
        CAP.setdefault(b, 0)
        g, cell = clone(ex[tk], task, b, int(es), int(ps), mode='d1')
        assert cell == k and g == v, (k, g, v); nd1 += 1
    for b in ['0.95', '0.98']:
        for ps in range(3):
            for es in range(3):
                g, cell = clone(tmpl[task], task, b, es, ps, 'L40', '')
                assert cd_cmds[(task, cell)] == g, (task, cell); ncd += 1
                check_json(g, f'{ROOT}/runs/{task}/eval_onactor/{cell}.json')
print(f'[validate] {nval} paper chain blocks + {nd1} paper d1 blocks reproduced byte-for-byte; '
      f'{ncd} existing config-C cells (0.95/0.98) reproduced byte-for-byte + JSON overrides match')
assert nd1 > 0 and ncd == 5 * 2 * 9

blocks = []
for task in T:
    for kind, beta in [('d1', '0.99')] + [('chain', b) for b in BETAS_CH] + [('d1', '0.90')]:
        for ps in range(3):
            for es in range(3):
                c, cell = clone(tmpl[task], task, beta, es, ps, 'L40', '', mode=kind)
                js = f'{ROOT}/runs/{task}/eval_onactor/{cell}.json'
                if os.path.exists(js): continue
                blocks.append((task, cell, c, js))
print(f'[gen] {len(blocks)} missing cells')
NS = int(os.environ.get('BF_SLOTS', 24))
os.makedirs(f'{OUT}/payloads', exist_ok=True)
for f in glob.glob(f'{OUT}/payloads/bfc_*.sh'): os.remove(f)
# sort by task so each slot keeps the same task (warm page cache), then deal round-robin over slots by task block
blocks.sort(key=lambda b: (b[0], b[1]))
q, r = divmod(len(blocks), NS)
bounds = [i * q + min(i, r) for i in range(NS + 1)]
pays = []
for i in range(NS):
    mine = blocks[bounds[i]:bounds[i + 1]]
    if not mine: continue
    p = f'{OUT}/payloads/bfc_{i:03d}.sh'
    with open(p, 'w') as fh:
        fh.write('#!/usr/bin/env bash\nset -uo pipefail\ncd /proj/dmfexp/zwhong/rsm_rise\nrc_all=0\n')
        fh.write('echo "[bfc] host=$(hostname) job=${SLURM_JOB_ID:-none} gpu=${CUDA_VISIBLE_DEVICES:-?}"\n')
        for task, cell, c, js in mine:
            d = os.path.dirname(js)
            fh.write(f'mkdir -p {d}/logs\n')
            fh.write(f'if [ -f {js} ]; then echo "[bfc] {cell} exists, skip"; else\n')
            fh.write(f'  {c} 2>&1 | tee {d}/logs/{cell}.log; rc=${{PIPESTATUS[0]}}\n')
            fh.write(f'  if [ -f {js} ]; then python /proj/dmfexp/zwhong/rsm_rise/scripts/wandb_log_eval.py {js} || true\n')
            fh.write(f'  else rm -f {js}.tmp; rc_all=${{rc:-1}}; echo "[bfc] {cell} FAILED rc=$rc"; fi\nfi\n\n')
        if i % 8 == 7:  # last slot of each 8-GPU node rebuilds the table at its end (cpu partition is starved)
            fh.write('bash /proj/dmfexp/zwhong/rsm_rise/scripts/beta_fixedcfg_build.sh > /proj/dmfexp/zwhong/rsm_rise/logs/slurm/'
                     'rr_bfc_build_inpack.${SLURM_JOB_ID:-0}.$(date -u +%H%M%S).out 2>&1 || true\n')
        fh.write('exit $rc_all\n')
    os.chmod(p, 0o755); pays.append(p)
json.dump({'note': 'BETA_FIXEDCFG config C (L40 P16 prob F8) at chain beta ' + ','.join(BETAS_CH) +
           ' + d1 beta 0.99/0.90 on the 5 tasks without paper L40 cells; proposer seeds 0-2 x eval seeds 0-2',
           'cells': [b[1] + '@' + b[0] for b in blocks], 'payloads': pays},
          open(f'{OUT}/plan_bfc.json', 'w'), indent=1)
print('[gen] wrote', f'{OUT}/plan_bfc.json', len(pays), 'payloads')