File size: 30,588 Bytes
575b0ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
475
476
477
478
479
480
481
482
483
484
485
486
487
"""Generate the experiment plan (job scripts + plan.json) for the single 8xA100 node.

  python -m tdprm.queue.plan [--rounds 200] [--extra-seeds 0] [--llama-arms all]
  python -m tdprm.queue.gpuq simulate --plan $TDPRM_HOME/queue/plan.json
  nohup python -m tdprm.queue.gpuq run --plan $TDPRM_HOME/queue/plan.json > $TDPRM_HOME/queue/queue.log 2>&1 &

Priority (lower first): data/sampling/state fitting -> OpenJev construction (critical path of the six
1.b arms) -> Qwen-math (first comparison) -> Qwen-HotpotQA -> Llama-math -> Llama-HotpotQA. Each training
job also runs its in-loop evaluations and final test (tdprm.rl.train); only the base model is evaluated
by a separate job.
"""

import argparse
import json
import stat
from collections import defaultdict
from pathlib import Path

from .. import paths
from ..rl.launch import ARMS, DOMAINS, PREAMBLE, TEST_SETS, eval_script, experiment, gpus_for, local_model, train_script

CELLS = [("qwen1.5b", "math"), ("qwen1.5b", "proverqa"), ("llama3b", "math"), ("llama3b", "proverqa")]
ARM_ORDER = ["grpo", "s_hc", "s_gae", "s_gaed", "prm800k", "qwenprm", "versaprm", "j_hc", "j_gae", "j_gaed"]
# Estimated wall-clock hours for 200 rounds (64 prompts x 8 rollouts) on one Qwen-1.5B GPU / two Llama-3B GPUs.
BASE_HOURS = {("qwen1.5b", "math"): 6.0, ("qwen1.5b", "proverqa"): 6.0,
              ("llama3b", "math"): 7.8, ("llama3b", "proverqa"): 7.8,
              ("qwen1.5b", "medcalc"): 7.0, ("qwen1.5b", "medqa"): 5.5,          # MedCalc: ~800-token patient notes
              ("llama3b", "medcalc"): 9.0, ("llama3b", "medqa"): 7.0,
              ("qwen1.5b", "chem"): 6.0, ("llama3b", "chem"): 7.8,
              ("qwen1.5b", "bio"): 5.5, ("llama3b", "bio"): 7.0,
              ("qwen1.5b", "countdown"): 5.0, ("llama3b", "countdown"): 6.5,
              ("qwen1.5b", "kk"): 6.0, ("llama3b", "kk"): 7.8,
              ("qwen1.5b", "csqa"): 4.5, ("llama3b", "csqa"): 6.0,        # short prompts, 768-token replies
              ("qwen1.5b", "siqa"): 4.5, ("llama3b", "siqa"): 6.0}
TEST_HOURS = {"qwen1.5b": 0.3, "llama3b": 0.4}      # in-run final test on the colocated vLLM engine
ARM_FACTOR = {"grpo": 1.0, "s_hc": 1.08, "s_gae": 1.08, "s_gaed": 1.08, "prm800k": 1.25, "qwenprm": 1.25,
              "versaprm": 1.3, "j_hc": 1.25, "j_gae": 1.25, "j_gaed": 1.25}
# v3 (TDPRM_V3_EXPERIMENTS.md; uniform v1 data, references = the existing v1 runs). Order = first-look priority within
# a cell. The belief arms pay one Qwen3-4B reader pass per probed step boundary (estimate +20-60%; update after the
# pilot).
V3_ARM_ORDER = ["b_td_v3", "s_hc_v3", "s_gaed_v3", "b_hc_v3", "j_hc_v3"]
V3_ABLATION_ARMS = ["b_td_v3_nomask", "b_td_v3_zs", "b_td_v3_nozv"]
ARM_FACTOR.update({"b_td_v3": 1.6, "b_hc_v3": 1.6, "b_td_v3_nomask": 1.6, "b_td_v3_zs": 1.6, "b_td_v3_nozv": 1.6,
                   "s_hc_v3": 1.08, "s_gaed_v3": 1.08, "j_hc_v3": 1.25})
SMOKE_ARMS_V3 = ["b_td_v3", "s_hc_v3"]


def write_script(name, body):
    path = paths.QUEUE / "scripts" / f"{name}.sh"
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(".tmp")
    tmp.write_text(body)
    tmp.chmod(tmp.stat().st_mode | stat.S_IXUSR)
    tmp.replace(path)            # a running job's bash keeps reading its old (unlinked) script
    return str(path)


def py_job(module_args):
    return PREAMBLE.format(repo=paths.REPO, home=paths.HOME) + f"python -m {module_args}\n"


SMOKE_ARMS = ["grpo", "s_gae", "j_gae", "prm800k", "versaprm"]


def build(args):
    jobs = []
    smoke = args.smoke
    cells = [("qwen1.5b", "math")] if smoke else CELLS
    backbones = sorted({b for b, _ in cells}, key=lambda b: ("qwen" not in b, b))
    domains = [d for d in ("math", "proverqa") if any(c[1] == d for c in cells)]
    tiny = {"sample": " --max-prompts 256", "fit": " --max-rollouts 1000",
            "build": " --rounds 2 --proposals 1 --round-size 200 --per-backbone 300",
            "label": " --n-ref 40", "calib": " --n-ref 40 --n-warm 200"} if smoke else defaultdict(str)

    def add(jid, body, gpus, priority, deps=(), est=1.0, **extra):
        jobs.append({"id": jid, "script": write_script(jid, body), "gpus": gpus, "priority": priority,
                     "deps": list(deps), "est_hours": round(est, 2), **extra})

    add("prep_data", py_job("tdprm.data.prepare"), 0, 0, est=0.3)
    add("download_models", PREAMBLE.format(repo=paths.REPO, home=paths.HOME) +
        "bash $TDPRM_REPO/tdprm/scripts/download_models.sh\n", 0, 0, est=0.6)
    prep = ["prep_data", "download_models"]
    for ci, (b, d) in enumerate(cells):
        add(f"sample_{b}_{d}", py_job(f"tdprm.sampling.base_rollouts --backbone {b} --domain {d}" + tiny["sample"]),
            1, 1 + ci * 0.1, prep, est={"qwen1.5b": 0.35, "llama3b": 0.6}[b])
        add(f"fit_spectral_{b}_{d}", py_job(f"tdprm.states.fit spectral --backbone {b} --domain {d}" + tiny["fit"]),
            1, 2 + ci * 0.1, [f"sample_{b}_{d}"], est={"qwen1.5b": 0.3, "llama3b": 0.45}[b])
    for b in backbones:
        add(f"eval_base_{b}", eval_script(local_model(paths.BACKBONES[b]), f"{b}-base/step_0"), 1, 6, prep,
            est={"qwen1.5b": 0.25, "llama3b": 0.4}[b])
    jev_group = []
    for di, d in enumerate(domains):
        # OpenJev-27B (bf16 fits one A100-80GB): build + balance the domain's state set from both backbones' steps;
        # then label a few thousand steps per cell as the reference for JevK5 (online labeler) calibration,
        # after which JevK5 labels the warm-start rollouts.
        jid = f"openjev_states_{d}"
        add(jid, py_job(f"tdprm.states.openjev build --domain {d}" + tiny["build"]), 1, 3 + di,
            [f"sample_{b}_{d}" for b in backbones], est=1.5)
        jev_group.append(jid)
        for b in backbones:
            lid, cid = f"openjev_label_{b}_{d}", f"jevk5_calib_{b}_{d}"
            add(lid, py_job(f"tdprm.states.openjev label --backbone {b} --domain {d}" + tiny["label"]),
                1, 3.1 + di, [jid], est=0.4)
            add(cid, py_job(f"tdprm.states.openjev calibrate --backbone {b} --domain {d}" + tiny["calib"]),
                1, 3.2 + di, [lid], est=0.35)
            jev_group += [lid, cid]
    llama_arms = ARM_ORDER if args.llama_arms == "all" else args.llama_arms.split(",")
    seeds = [0] if smoke else [1] + list(range(2, 2 + args.extra_seeds))   # smoke runs never collide with real ones
    for ci, (b, d) in enumerate(cells):
        arms = SMOKE_ARMS if smoke else (ARM_ORDER if b == "qwen1.5b" else llama_arms)
        for seed in seeds:
            if seed > 1 and (b, d) != ("qwen1.5b", "math"):
                continue
            for ai, arm in enumerate(arms):
                exp = experiment(b, d, arm, seed)
                deps = [f"sample_{b}_{d}"]
                if ARMS[arm].get("extractor") == "spectral":
                    deps.append(f"fit_spectral_{b}_{d}")
                if ARMS[arm].get("extractor") == "jev":
                    deps.append(f"jevk5_calib_{b}_{d}")
                est = BASE_HOURS[(b, d)] * ARM_FACTOR[arm] * args.rounds / 200 + TEST_HOURS[b]
                prio = 10 + 10 * ci + ai * 0.1 + (50 if seed > 1 else 0)
                tid = f"train_{exp}"
                add(tid, train_script(b, d, arm, seed, args.rounds), gpus_for(b, arm), prio, deps, est,
                    first_look_frac=(100 / args.rounds if ci == 0 and seed == 1 and not smoke else None))
    out = paths.QUEUE / ("plan_smoke.json" if smoke else "plan.json")
    reservations = [{"gpus": args.jev_gpus, "jobs": jev_group}] if args.jev_gpus else []
    out.write_text(json.dumps({"jobs": jobs, "reservations": reservations}, indent=1))
    print(f"wrote {out}: {len(jobs)} jobs "
          f"({sum(j['id'].startswith('train_') for j in jobs)} training runs, "
          f"{sum(j['id'].startswith('eval_') for j in jobs)} evaluations)")
    return out


def v2_factor(arm):
    base = arm.replace("_nogate", "").replace("_v2", "")
    return ARM_FACTOR.get(base, ARM_FACTOR["s_gae"])        # vp_* (value probe) costs like the spectral arms


def v2_inputs(b, d, arm):
    """Existing files a v2 training job needs (no prep jobs: v2 reuses data, rollouts and states)."""
    spec, cell = ARMS[arm], f"$TDPRM_HOME/states/{b}_{d}"
    deps = [f"file:$TDPRM_HOME/data/train/{d}_{b}.parquet"]
    if spec.get("extractor") == "spectral":
        deps += [f"file:{cell}/spectral_k7.npz", f"file:{cell}/spectral_warm.npz"]
    if spec.get("extractor") == "jev":
        deps += [f"file:$TDPRM_HOME/states/{d}_openjev_states.json", f"file:{cell}/jevk5_calibration.json",
                 f"file:{cell}/jev_warm.npz"]
    return deps


def build_v2(args):
    """v2 jobs (scripts run this checkout via TDPRM_REPO), merged into an existing plan file so that one queue
    drives every GPU. Waves are priorities 21, 22, ... : after every Qwen v1 cell, before the Llama v1 cells (30+).
    A GPU pilot (10 rounds) runs first; every wave job waits for the pilot check's PASS marker. Held Llama v1 jobs
    are released when the pilot check has run, so the waves (higher priority) still start first."""
    jobs = []

    def add(jid, body, gpus, priority, deps=(), est=1.0):
        jobs.append({"id": jid, "script": write_script(jid, body), "gpus": gpus, "priority": priority,
                     "deps": list(deps), "est_hours": round(est, 2), "v2": True})

    waves = [w for w in args.v2_waves.split(";") if w.strip()]
    cells = sorted({tuple(w.split("=")[0].split(":")) for w in waves} | {("qwen1.5b", "math")})
    for b, d in cells:
        add(f"retest_{b}_{d}", py_job(f"tdprm.sampling.base_rollouts --backbone {b} --domain {d} --retest-only"),
            0, 0.5, [f"file:$TDPRM_HOME/rollouts/{b}_{d}.jsonl.gz"], 0.05)
    pilot_runs = []
    for b, arm in [("qwen1.5b", a) for a in args.v2_pilot.split(",")] + [("llama3b", args.v2_pilot_llama)]:
        exp = experiment(b, "math", arm, 0)
        pilot_runs.append(exp)
        body = train_script(b, "math", arm, 0, 10, "--eval-prompts 32 --no-test").rstrip("\n")
        # a pilot always "finishes": pilot_v2_check judges it from its logs, so a failure cannot block the queue
        add(f"pilot_{exp}", body + " || echo '[pilot] training exited with an error'\n", gpus_for(b), 9.5,
            [f"retest_{b}_math"] + v2_inputs(b, "math", arm), 0.6 if b == "qwen1.5b" else 1.0)
    marker = "$TDPRM_HOME/report/pilot_v2.PASS"
    qwen_marker = "$TDPRM_HOME/report/pilot_v2_qwen.PASS"
    add("pilot_v2_check", py_job(f"tdprm.report.pilot_v2 --runs {' '.join(pilot_runs)}"), 0, 9.6,
        [f"pilot_{e}" for e in pilot_runs], 0.05)
    qwen_pilots = [e for e in pilot_runs if e.startswith("qwen")]
    add("pilot_v2_qwen_check", py_job(f"tdprm.report.pilot_v2 --name pilot_v2_qwen --runs {' '.join(qwen_pilots)}"),
        0, 9.6, [f"pilot_{e}" for e in qwen_pilots], 0.05)
    held = " ".join(args.v2_release)
    if held:
        add("release_llama_v1", PREAMBLE.format(repo=paths.REPO, home=paths.HOME) +
            f"for j in {held}; do python -m tdprm.queue.gpuq retry --plan {args.v2_merge_into} $j; done\n",
            0, 9.7, ["pilot_v2_check"], 0.01)
    # every Qwen wave before any Llama wave; Qwen waves only need the Qwen pilots, Llama waves need the full check
    order = sorted(range(len(waves)), key=lambda i: (waves[i].startswith("llama"), i))
    for rank, wi in enumerate(order):
        cell, arms = waves[wi].split("=")
        b, d = cell.split(":")
        for ai, arm in enumerate(arms.split(",")):
            exp = experiment(b, d, arm, 1)
            add(f"train_{exp}", train_script(b, d, arm, 1, args.rounds), gpus_for(b), 21 + rank + ai * 0.01,
                [f"file:{qwen_marker if b == 'qwen1.5b' else marker}", f"retest_{b}_{d}"] + v2_inputs(b, d, arm),
                BASE_HOURS[(b, d)] * v2_factor(arm) * args.rounds / 200 + TEST_HOURS[b])
    target = paths.QUEUE / args.v2_merge_into if "/" not in args.v2_merge_into else Path(args.v2_merge_into)
    data = json.loads(target.read_text())
    # Llama jobs (v2 and v1) start only after these Qwen v2 runs have finished (any final outcome)
    after = [f"after:{j['id']}" for j in jobs if j["id"].startswith("train_qwen1.5b-")
             and j["id"].split("-")[1] in args.llama_after_domains]          # train_<backbone>-<domain>-<arm>-<seed>
    if not after and args.llama_after_domains:
        raise SystemExit(f"no Qwen v2 runs found for {args.llama_after_domains}: Llama would not wait")
    for j in jobs + data["jobs"]:
        if j["id"].startswith("train_llama3b"):
            j["deps"] = [d for d in j["deps"] if not d.startswith("after:")] + after
    ids = {j["id"] for j in jobs}
    data["jobs"] = [j for j in data["jobs"] if not j.get("v2") and j["id"] not in ids] + jobs
    tmp = target.with_suffix(".tmp")
    tmp.write_text(json.dumps(data, indent=1))
    tmp.replace(target)
    print(f"merged {len(jobs)} v2 jobs into {target} "
          f"({sum(j['id'].startswith('train_') for j in jobs)} training runs, {len(pilot_runs)} pilots)")


def build_v3(args):
    """v3 jobs (scripts run this checkout via TDPRM_REPO) in their own plan file, driven by one queue.
    Priorities: reader smoke test, pre-flight and a 10-round GPU pilot (b_td_v3, s_hc_v3 in both Qwen cells) first;
    the pilot check writes report/pilot_v3.PASS, which every wave job waits for. Each ";" in --v3-waves starts a
    new priority level (10, 11, ...); --v3-seed-waves runs with --v3-seeds at +100 (after every seed-1 run)."""
    jobs = []

    def add(jid, body, gpus, priority, deps=(), est=1.0):
        jobs.append({"id": jid, "script": write_script(jid, body), "gpus": gpus, "priority": priority,
                     "deps": list(deps), "est_hours": round(est, 2), "v3": True})

    reader = f"file:$TDPRM_MODELS/{paths.READER.split('/')[-1]}/config.json"

    def inputs(b, d, arm):
        return v2_inputs(b, d, arm) + ([reader] if ARMS[arm]["credit"] == "belief" else [])

    gate = []
    if args.v3_pilot:
        pre = PREAMBLE.format(repo=paths.REPO, home=paths.HOME)
        rep = "$TDPRM_HOME/report"
        if not args.v3_no_preflight:
            add("smoke_v3_reader", pre + f'mkdir -p {rep}\nCUDA_VISIBLE_DEVICES=${{CUDA_VISIBLE_DEVICES%%,*}} '
                f'python -m tdprm.states.server belief --model $TDPRM_MODELS/{paths.READER.split("/")[-1]} --port $PORT '
                f'> {rep}/smoke_v3_reader_server.log 2>&1 &\nSERVER_PID=$!\n'
                "trap 'kill $SERVER_PID 2>/dev/null || true' EXIT\nwait_health $SERVER_PID\n"
                f"python -m tdprm.scripts.smoke_v3_reader --url http://127.0.0.1:$PORT 2>&1 | tee {rep}/smoke_v3_reader.txt "
                "|| echo '[smoke] reader smoke test failed'\n", 1, 1.0, [reader], 0.05)
            for d, rounds in (("proverqa", "1,96"), ("math", "1,196")):
                run = experiment("qwen1.5b", d, "grpo", 1)
                add(f"preflight_v3_{d}", pre + f"mkdir -p $TDPRM_HOME/report\npython -m tdprm.scripts.preflight_v3 --run {run} "
                    f"--domain {d} --rounds {rounds} --n 512 2>&1 | tee $TDPRM_HOME/report/preflight_v3_{d}.txt "
                    f"|| echo '[preflight] failed'\n", 1, 1.0, [reader, f"file:$TDPRM_HOME/runs/{run}/DONE"], 0.2)
        pilot_runs = []
        for cell in args.v3_pilot_cells.split(","):
            b, d = cell.split(":")
            for arm in args.v3_pilot.split(","):
                exp = experiment(b, d, arm, 0)
                pilot_runs.append(exp)
                body = train_script(b, d, arm, 0, 10, "--eval-prompts 32 --no-test").rstrip("\n")
                # GPU0 memory every 5 s for check (e); a pilot always "finishes": pilot_v3 judges it from its logs
                mem = (f'mkdir -p "$TDPRM_HOME/runs/{exp}/logs"\nnvidia-smi --query-gpu=memory.used '
                       f'--format=csv,noheader,nounits -i $TDPRM_GPU0 -l 5 > "$TDPRM_HOME/runs/{exp}/logs/gpu_mem.log" &'
                       f'\nMEM_PID=$!')
                body = body.replace('LOGDIR=', mem + '\nLOGDIR=', 1)
                add(f"pilot_{exp}", body + " || echo '[pilot] training exited with an error'\n"
                    "kill $MEM_PID 2>/dev/null || true\n", gpus_for(b), 2.0, inputs(b, d, arm), 1.0)
        name = args.v3_pilot_name
        add(f"{name}_check", py_job(f"tdprm.report.pilot_v3 --name {name} --runs {' '.join(pilot_runs)}"), 0, 2.1,
            [f"pilot_{e}" for e in pilot_runs], 0.05)
        gate = [f"file:$TDPRM_HOME/report/{name}.PASS"]

    def waves(spec, seeds, base):
        for level, wave in enumerate(w for w in spec.split(";") if w.strip()):
            cell, arms = wave.split("=")
            b, d = cell.split(":")
            for seed in seeds:
                for ai, arm in enumerate(a.strip() for a in arms.split(",") if a.strip()):
                    exp = experiment(b, d, arm, seed)
                    if args.skip_done and (paths.RUNS / exp / "DONE").exists():
                        continue
                    add(f"train_{exp}", train_script(b, d, arm, seed, args.rounds), gpus_for(b),
                        base + level + seed * 0.001 + ai * 0.01, gate + inputs(b, d, arm),
                        BASE_HOURS[(b, d)] * ARM_FACTOR[arm] * args.rounds / 200 + TEST_HOURS[b])
                    if gate:
                        jobs[-1]["produced_by"] = f"{args.v3_pilot_name}_check"       # gpuq simulate: the marker's producer

    waves(args.v3_waves, [1], 10)
    if args.v3_seed_waves:
        waves(args.v3_seed_waves, [int(s) for s in args.v3_seeds.split(",")], 110)
    target = paths.QUEUE / args.v3_out if "/" not in args.v3_out else Path(args.v3_out)
    target.parent.mkdir(parents=True, exist_ok=True)
    tmp = target.with_suffix(".tmp")
    tmp.write_text(json.dumps({"jobs": jobs}, indent=1))
    tmp.replace(target)
    print(f"wrote {len(jobs)} v3 jobs to {target} ({sum(j['id'].startswith('train_') for j in jobs)} training runs)")
    return target


MED_BASELINES = ("grpo", "qwenprm", "versaprm", "prm800k")
SAMPLE_ARGS = {"bio": " --max-prompts 16000", "siqa": " --max-prompts 16000"}   # Social IQa: 33k pool        # 42k-question pool: sample a shuffled 16k (enough after the filter)


def med_priority(backbone, domain, arm, index):
    """Medicine training order: Qwen (10+) before Llama (30+); within a backbone, b_hc_v3 first (-0.1), then grpo,
    qwenprm, versaprm, then the other v3 HC arms (+2), then prm800k (+2.5); the calculation domain before MedQA; then
    the --med-arms order. (b_td_v3 was dropped on Oct 17: it uses no transition table.)"""
    tier = 10 if backbone == "qwen1.5b" else 30
    # Oct 17: b_hc_v3 (most promising transition-based method) first, prm800k after the other v3 arms
    group = -0.1 if arm == "b_hc_v3" else 2.5 if arm == "prm800k" else (0 if arm in MED_BASELINES else 2)
    return round(tier + group + (0.1 if domain == "medqa" else 0) + index * 0.001, 4)


def build_medicine(args):
    """Medicine pair in its own plan file (scripts run this checkout via TDPRM_REPO). --med-domains: the calculation
    side and MedQA (since Oct 17 chem,medqa: WebInstruct-verified Chemistry replaced MedCalc-Bench, whose long patient
    notes made rounds 2-3x slower). Data must already be prepared (python -m tdprm.data.prepare --domains ...).
    Regenerating keeps the job ids of unchanged cells, so their queue state (done / held / running) carries over.
    Jobs, by priority:
      1-3  base sampling (training parquet + pass@1), spectral fit, OpenJev states + JevK5 labels/calibration
      2    10-round GPU pilots of --med-pilot arms in both Qwen cells; the check writes report/<name>.PASS
           (--med-pilot "": no pilots; the v3 arms wait for the existing marker of an earlier pilot check)
      6    base-model evaluation on the medicine test sets (evals/<b>-base/step_0_medicine.json)
      10+  Qwen training runs (v1 arms need only the cell's data; v3 arms also wait for the PASS marker); baselines
           (grpo and the three PRMs) ahead of the v3 arms (med_priority)
      30+  Llama training runs, after the pilot check and every Qwen cell's state preparation (so every Qwen run is
           ready, and queued ahead of them, before any Llama run can start)
    GPUs: --med-jev-gpus are held for the OpenJev/JevK5 chain and --med-pilot-gpus for the pilots until each group
    finishes, so early training runs cannot delay the states or the gate."""
    jobs = []

    def add(jid, body, gpus, priority, deps=(), est=1.0):
        jobs.append({"id": jid, "script": write_script(jid, body), "gpus": gpus, "priority": priority,
                     "deps": list(deps), "est_hours": round(est, 2), "medicine": True})

    domains, backbones = tuple(args.med_domains.split(",")), ("qwen1.5b", "llama3b")
    reader = f"file:$TDPRM_MODELS/{paths.READER.split('/')[-1]}/config.json"
    for ci, (b, d) in enumerate((b, d) for b in backbones for d in domains):
        add(f"sample_{b}_{d}", py_job(f"tdprm.sampling.base_rollouts --backbone {b} --domain {d}{SAMPLE_ARGS.get(d, '')}"),
            1, 1 + ci * 0.1,
            [f"file:$TDPRM_HOME/data/pool/{d}_train.jsonl"], {"qwen1.5b": 0.4, "llama3b": 0.7}[b])
        add(f"fit_spectral_{b}_{d}", py_job(f"tdprm.states.fit spectral --backbone {b} --domain {d}"), 1, 2 + ci * 0.1,
            [f"sample_{b}_{d}"], {"qwen1.5b": 0.3, "llama3b": 0.45}[b])
    jev_group = []
    for di, d in enumerate(domains):
        add(f"openjev_states_{d}", py_job(f"tdprm.states.openjev build --domain {d}"), 1, 3 + di * 0.5,
            [f"sample_{b}_{d}" for b in backbones], 1.0)
        jev_group.append(f"openjev_states_{d}")
        for b in backbones:
            lid, cid = f"openjev_label_{b}_{d}", f"jevk5_calib_{b}_{d}"
            add(lid, py_job(f"tdprm.states.openjev label --backbone {b} --domain {d}"), 1, 3.1 + di * 0.5,
                [f"openjev_states_{d}"], 0.3)
            add(cid, py_job(f"tdprm.states.openjev calibrate --backbone {b} --domain {d}"), 1, 3.2 + di * 0.5,
                [lid], 0.2)
            jev_group += [lid, cid]
    base_evals = {args.med_eval_key: DOMAINS[domains[-1]].get("test") or TEST_SETS}   # evals/<b>-base/step_0_<key>
    for b in backbones:
        for key, sets in base_evals.items():
            add(f"eval_base_{b}_{key}", eval_script(local_model(paths.BACKBONES[b]), f"{b}-base/step_0_{key}", sets=sets),
                1, 6, [f"file:$TDPRM_HOME/data/eval/{x}.jsonl" for x in sets], {"qwen1.5b": 0.3, "llama3b": 0.5}[b])

    def cell_deps(b, d, arm):
        spec = ARMS[arm]
        deps = [f"sample_{b}_{d}"]
        if spec.get("extractor") == "spectral":
            deps.append(f"fit_spectral_{b}_{d}")
        if spec.get("extractor") == "jev":
            deps.append(f"jevk5_calib_{b}_{d}")
        if spec["credit"] == "belief":
            deps.append(reader)
        return deps

    name = args.med_pilot_name
    pilot_group, pilot_runs = [], []
    for d in domains:
        for arm in [a for a in args.med_pilot.split(",") if a]:
            exp = experiment("qwen1.5b", d, arm, 0)
            pilot_runs.append(exp)
            body = train_script("qwen1.5b", d, arm, 0, 10, "--eval-prompts 32 --no-test").rstrip("\n")
            mem = (f'mkdir -p "$TDPRM_HOME/runs/{exp}/logs"\nnvidia-smi --query-gpu=memory.used '
                   f'--format=csv,noheader,nounits -i $TDPRM_GPU0 -l 5 > "$TDPRM_HOME/runs/{exp}/logs/gpu_mem.log" &'
                   f'\nMEM_PID=$!')
            body = body.replace("LOGDIR=", mem + "\nLOGDIR=", 1)
            add(f"pilot_{exp}", body + " || echo '[pilot] training exited with an error'\n"
                "kill $MEM_PID 2>/dev/null || true\n", gpus_for("qwen1.5b"), 2.0, cell_deps("qwen1.5b", d, arm), 0.8)
            pilot_group.append(f"pilot_{exp}")
    if pilot_runs:
        add(f"{name}_check", py_job(f"tdprm.report.pilot_v3 --name {name} --runs {' '.join(pilot_runs)}"), 0, 2.1,
            pilot_group, 0.05)
        pilot_group.append(f"{name}_check")
    gate = f"file:$TDPRM_HOME/report/{name}.PASS"
    qwen_prep = [f"after:{j}" for d in domains for j in (f"sample_qwen1.5b_{d}", f"fit_spectral_qwen1.5b_{d}",
                                                           f"jevk5_calib_qwen1.5b_{d}")]
    arms = args.med_arms.split(",")
    for bi, b in enumerate(backbones):
        for di, d in enumerate(domains):
            for ai, arm in enumerate(arms):
                exp = experiment(b, d, arm, 1)
                deps = cell_deps(b, d, arm) + ([gate] if ARMS[arm].get("channel") == "v3" else [])
                if b != "qwen1.5b":
                    deps += ([f"after:{name}_check"] if pilot_runs else []) + qwen_prep
                add(f"train_{exp}", train_script(b, d, arm, 1, args.rounds), gpus_for(b), med_priority(b, d, arm, ai),
                    deps, BASE_HOURS[(b, d)] * ARM_FACTOR[arm] * args.rounds / 200 + TEST_HOURS[b])
                if ARMS[arm].get("channel") == "v3" and pilot_runs:
                    jobs[-1]["produced_by"] = f"{name}_check"
    reservations = []
    if args.med_jev_gpus:
        reservations.append({"gpus": args.med_jev_gpus, "jobs": jev_group})
    if args.med_pilot_gpus:
        reservations.append({"gpus": args.med_pilot_gpus, "jobs": pilot_group})
    for j in jobs:
        j["priority"] = round(j["priority"] + args.med_priority_offset, 4)
    if args.med_merge_into:                     # append to a running plan (its jobs, state and reservations are kept)
        target = paths.QUEUE / args.med_merge_into
        data = json.loads(target.read_text())
        ids = {j["id"] for j in jobs}
        if ids & {j["id"] for j in data["jobs"] if j["id"] not in ids}:
            raise SystemExit("job id collision")
        data["jobs"] = [j for j in data["jobs"] if j["id"] not in ids] + jobs
        data["reservations"] = data.get("reservations", []) + reservations
        tmp = target.with_suffix(".tmp")
        tmp.write_text(json.dumps(data, indent=1))
        tmp.replace(target)
        print(f"merged {len(jobs)} jobs ({sum(j['id'].startswith('train_') for j in jobs)} training runs) into {target}")
        return target
    target = paths.QUEUE / args.med_out
    tmp = target.with_suffix(".tmp")
    tmp.write_text(json.dumps({"jobs": jobs, "reservations": reservations}, indent=1))
    tmp.replace(target)
    print(f"wrote {len(jobs)} medicine jobs to {target} ({sum(j['id'].startswith('train_') for j in jobs)} training "
          f"runs, {len(pilot_runs)} pilots)")
    return target


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--rounds", type=int, default=200, help="GRPO rounds (64 prompts x 8 rollouts each)")
    parser.add_argument("--extra-seeds", type=int, default=0, help="extra seeds for the Qwen-math cell")
    parser.add_argument("--llama-arms", default="all")
    parser.add_argument("--smoke", action="store_true",
                        help="tiny end-to-end check (Qwen-math, 10 rounds, small samples); use a separate TDPRM_HOME")
    parser.add_argument("--jev-gpus", type=lambda s: [int(x) for x in s.split(",")] if s else [], default="7",
                        help="GPUs held for the OpenJev/JevK5 state pipeline until it finishes")
    parser.add_argument("--v2-waves", default="", help='v2 only: "b:d=arm,arm;b:d=arm,..." (priority waves)')
    parser.add_argument("--v2-merge-into", default=str(paths.QUEUE / "plan.json"))
    parser.add_argument("--v2-pilot", default="grpo_v2,s_gae_v2,vp_gae_v2,j_gae_v2,prm800k_v2")
    parser.add_argument("--v2-pilot-llama", default="s_gae_v2")
    parser.add_argument("--v2-release", nargs="*", default=[], help="held job ids to release after the pilot")
    parser.add_argument("--llama-after-domains", nargs="*", default=["proverqa"],
                        help="Llama training jobs wait until every Qwen v2 run of these domains has finished")
    parser.add_argument("--v3-waves", default="", help='v3: "b:d=arm,arm;b:d=arm,..." (each ";" a priority level)')
    parser.add_argument("--v3-seed-waves", default="", help="v3: waves replicated with --v3-seeds (after seed 1)")
    parser.add_argument("--v3-seeds", default="2,3")
    parser.add_argument("--v3-pilot", default=",".join(SMOKE_ARMS_V3), help='v3 pilot arms ("" = no pilot gate)')
    parser.add_argument("--v3-pilot-cells", default="qwen1.5b:math,qwen1.5b:proverqa")
    parser.add_argument("--v3-pilot-name", default="pilot_v3", help="pilot check job <name>_check, marker report/<name>.PASS")
    parser.add_argument("--v3-no-preflight", action="store_true", help="no reader smoke test / pre-flight jobs")
    parser.add_argument("--v3-out", default="plan_v3_all.json", help="v3 plan file (in $TDPRM_HOME/queue)")
    parser.add_argument("--skip-done", action="store_true", help="v3: skip runs that already have a DONE marker")
    parser.add_argument("--medicine", action="store_true", help="medicine pair plan (build_medicine)")
    parser.add_argument("--med-domains", default="chem,medqa", help="calculation side,MedQA (medcalc,medqa before Oct 17)")
    # only methods that count back over a transition table (HC arms); b_td_v3 (belief progress, no transitions) was
    # dropped on Oct 17
    parser.add_argument("--med-arms", default="grpo,qwenprm,s_hc_v3,versaprm,j_hc_v3,prm800k,b_hc_v3")
    parser.add_argument("--med-pilot", default="s_hc_v3", help="pilot arms in both Qwen medicine cells")
    parser.add_argument("--med-pilot-name", default="pilot_v3_med")
    parser.add_argument("--med-jev-gpus", type=lambda s: [int(x) for x in s.split(",")] if s else [], default="",
                        help="GPUs held for the OpenJev/JevK5 chain (default none: its jobs outrank training anyway)")
    parser.add_argument("--med-pilot-gpus", type=lambda s: [int(x) for x in s.split(",")] if s else [], default="5,6")
    parser.add_argument("--med-out", default="plan_medicine.json")
    parser.add_argument("--med-eval-key", default="pair", help="base-model eval job/name: evals/<b>-base/step_0_<key>")
    parser.add_argument("--med-merge-into", default="", help="merge the jobs into this existing plan file instead")
    parser.add_argument("--med-priority-offset", type=float, default=0.0,
                        help="added to every job's priority (e.g. 40: after every job of the plan merged into)")
    args = parser.parse_args()
    if args.medicine:
        build_medicine(args)
        return
    if args.v3_waves:
        build_v3(args)
        return
    if args.v2_waves:
        build_v2(args)
        return
    if args.smoke:
        args.rounds = min(args.rounds, 10)
    build(args)


if __name__ == "__main__":
    main()