File size: 13,308 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
"""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, PREAMBLE, 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}
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}


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 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")
    args = parser.parse_args()
    if args.v2_waves:
        build_v2(args)
        return
    if args.smoke:
        args.rounds = min(args.rounds, 10)
    build(args)


if __name__ == "__main__":
    main()