File size: 24,527 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
"""R5 leader runner (amendment 3.3 D2), usable on any GPU slot; one long job per slot, each step in a subprocess.

Order of work:
 1. catch-up D9 validation of finished VLMA short arms that miss a D9 set that became ready later (e.g. print_real_val);
 2. wait for the leaders file (DATA/outputs/r5/leaders/leaders.json, copied there from records/R5/RULE/leaders.json);
 3. P_lead: plan_lead.json is computed ONCE (first runner to get the plan lock) from measured speeds only, then never
    rewritten (see plan());
 4. the four leader runs, each claimed by one slot at a time (mkdir lock + heartbeat; stale after 15 min, then any
    slot may take the run over and it resumes from its checkpoint):
      seed 1: checkpoint 'leader' of <arm>: from <arm>/short_state (weights + AdamW moments), sequence seed 20261121
              rows 150,000 .. P_lead, 3% re-warm + cosine over the extra samples; then validation on EVERY val set;
      seed 2: checkpoints 'short_seed2' then 'leader_seed2' of the SAME arm (scorer convention <checkpoint>_seed2):
              short_seed2 from the released weights on the seed-20261122 sequence (same settings as the short runs:
              150,000 samples, 3 h cap, curve points curve_<n>_seed2), D9 validation, then leader_seed2 exactly as
              seed 1 (rows 150,000 .. P_lead of its own sequence), then validation on every val set.
Training stops by train_deadline_utc; validation by eval_deadline_utc.

leaders.json (written separately):
 {"leaders": [{"short": "glm_ocr", "arm": "glm_ocr", "kind": "vlma"},
              {"short": "x", "arm": "x", "kind": "vlmb", "train_cmd": [...], "eval_cmd": [...]}],
  "slot_windows_utc": {"V": "2026-11-22T06:00:00Z", "L": "2026-11-22T20:00:00Z"},   # earliest start per slot
  "confirmed_utc": "..."}
 kind vlmb: command templates (lists) with placeholders {phase} {arm} {seq} {n} {start_row} {init_state} {deadline}
 {seed_index} {data_order_seed} {cap_hours} {ckpt} {model_dir} {sets}; train_cmd must accept the train_vlm.py options.

usage: leader_runner.py CONFIG_JSON
"""
import glob
import json
import os
import shutil
import signal
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import leader_cmds as lc  # noqa: E402

CFG = sys.argv[1]
CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
S = os.path.join(CODE, "scripts", "r5_vlma")
PY = [os.path.join(CODE, ".venv_vlm", "bin", "python"), "-I"]
REG = os.path.join(S, "models_r5.tsv")
MODELS = os.path.join(DATA, "hf_cache", "j2_models")
CK = os.path.join(DATA, "checkpoints", "r5")
V = os.path.join(DATA, "outputs", "r5", "vlma")
PREDS = os.path.join(DATA, "outputs", "r5", "preds")
EVALSETS = os.path.join(DATA, "data", "processed", "r5", "evalsets.json")
LD = os.path.join(DATA, "outputs", "r5", "leaders")
LOGD = os.path.join(DATA, "logs", "r5_vlma")
P_SHORT = 150000
D9 = ["V1", "synth_hand_val", "synth_typed_val", "synth_clutter_val", "print_real_val", "hkr_val_s2000",
      "chd_val_s2000", "school_val_s2000"]
os.makedirs(LD, exist_ok=True)
os.makedirs(LOGD, exist_ok=True)
JOB = os.environ.get("SLURM_JOB_ID", "nojob")


def cfg():
    return json.load(open(CFG))


def ts(s):
    return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()


def utc(t=None):
    return datetime.fromtimestamp(t or time.time(), timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def say(*a):
    print(f"[lead {cfg()['slot']} {utc()}]", *a, flush=True)


def jload(p, default=None):
    try:
        return json.load(open(p))
    except Exception:  # noqa: BLE001
        return default


def jdump(obj, p):
    tmp = p + ".tmp.%s" % JOB
    json.dump(obj, open(tmp, "w"), indent=1, ensure_ascii=False)
    os.replace(tmp, p)


CUR = {"proc": None}


def run(tag, cmd, hard_deadline, env=None):
    lp = os.path.join(LOGD, "lead_%s_%s.log" % (tag.replace(":", "_"), JOB))
    say(f"{tag}: start; log {lp}")
    if env is None:
        env = dict(os.environ)
        env.pop("HF_TOKEN", None)
        env.pop("HUGGING_FACE_HUB_TOKEN", None)
        env.update(HF_HUB_OFFLINE="1", TOKENIZERS_PARALLELISM="false", PYTHONUNBUFFERED="1")
    with open(lp, "a") as lf:
        lf.write(f"\n===== {utc()} job {JOB} cmd: {' '.join(cmd)}\n")
        lf.flush()
        p = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT, env=env)
        CUR["proc"] = p
        termed = None
        while True:
            try:
                rc = p.wait(timeout=30)
                CUR["proc"] = None
                say(f"{tag}: exit {rc}")
                return rc
            except subprocess.TimeoutExpired:
                pass
            now = time.time()
            if termed is None and now >= hard_deadline:
                p.send_signal(signal.SIGTERM)
                termed = now
            elif termed is not None and now - termed > 600:
                p.kill()


def on_term(signum, frame):  # noqa: ARG001
    if CUR["proc"] is not None:
        CUR["proc"].send_signal(signal.SIGTERM)


signal.signal(signal.SIGTERM, on_term)


# ---------------- commands ----------------
def fmt(tpl, **kw):
    return [str(x).format(**kw) for x in tpl]


def is_vlmb(L):
    return L.get("kind", "vlma") in ("vlmb", "vlmc")


def env_for(L):
    """subprocess environment: VLMB/VLMC arms per leader_interface.json, VLMA arms as before."""
    if is_vlmb(L):
        e = lc.vlmb_env(L["short"], os.environ)
        e["PYTHONUNBUFFERED"] = "1"
        return e
    return None


def names(L, si):
    """(arm, short-phase, leader-phase). VLMA: seed 2 = same arm, checkpoints short_seed2 / leader_seed2 (scorer
    convention). VLMB/VLMC: seed 2 = arm <short>_s2 with short / leader (leader_interface.json naming, so VLMB's curve
    points of seed 2 do not overwrite seed 1's)."""
    if is_vlmb(L):
        return lc.vlmb_arm(L["short"], si), "short", "leader"
    return (L["arm"], "short", "leader") if si == 1 else (L["arm"], "short_seed2", "leader_seed2")


def train_cmd(L, phase, arm, seq, n, start_row, init_state, seed_index, dos, cap):
    c = cfg()
    if is_vlmb(L):
        return lc.vlmb_train_cmd(L["short"], arm, phase, seq, n, start_row, init_state, cap, c["train_deadline_utc"])
    cmd = PY + [os.path.join(S, "train_vlm.py"), "--short", L["short"], "--arm", arm, "--registry", REG, "--models-dir", MODELS,
                "--seq", seq, "--ckpt-root", CK, "--out-root", os.path.join(V, "runs"), "--phase", phase,
                "--n-samples", str(n), "--start-row", str(start_row), "--cap-hours", str(cap),
                "--deadline-utc", c["train_deadline_utc"], "--seed-index", str(seed_index), "--data-order-seed", str(dos)]
    if init_state:
        cmd += ["--init-state", init_state, "--init-optimizer"]
    return cmd


def eval_cmd(L, arm, ckpt, sets=""):
    c = cfg()
    model_dir = os.path.join(CK, arm, ckpt)
    if is_vlmb(L):
        if not sets and ckpt == "short":
            sets = ",".join(s for s in D9 if s in ready_val_sets())
        return lc.vlmb_eval_cmd(L["short"], arm, ckpt, sets, c["eval_deadline_utc"])
    cmd = PY + [os.path.join(S, "eval_vlm.py"), "--short", L["short"], "--arm", arm, "--ckpt", ckpt, "--model-dir", model_dir,
                "--registry", REG, "--evalsets", EVALSETS, "--preds-root", PREDS, "--batch", "16",
                "--deadline-utc", c["eval_deadline_utc"]]
    if sets:
        cmd += ["--sets", sets]
    return cmd


RUNS_DIR_OF = {}  # arm -> its runs folder (VLMB/VLMC arms write to DATA/outputs/r5/vlmb/runs)


def run_json(arm, phase):
    return jload(os.path.join(RUNS_DIR_OF.get(arm, os.path.join(V, "runs")), arm, phase, "run.json"), {}) or {}


def trained(arm, phase):
    rj = run_json(arm, phase)
    return bool(rj.get("exported")) and str(rj.get("flag", "")).startswith(
        ("complete", "short of P", "stopped at the absolute deadline"))


def eval_sets_done(arm, ckpt):
    m = jload(os.path.join(PREDS, arm, ckpt, "meta.json"), {}) or {}
    return {k for k, v in (m.get("sets") or {}).items() if v.get("complete")}


def ready_val_sets():
    reg = jload(EVALSETS, {}) or {}
    out = []
    for e in reg.get("sets", []):
        if str(e.get("split")) == "val" and not e.get("locked") and e.get("manifest") and os.path.exists(e["manifest"]):
            if str(e.get("unit", "word")) in ("word", "line"):
                out.append(e["name"])
    return out


# ---------------- sequences ----------------
def ensure_seq(path, seed):
    """build a sequence file once; the other slot waits for it (claim lock, so two slots never write one file)."""
    t_end = time.time() + 3600
    while time.time() < t_end:
        if os.path.exists(path) and os.path.exists(path + ".done"):
            return True
        c = cfg()
        if not os.path.exists(c["mix_yaml"]):
            return False
        name = "build_seq_%d" % seed
        if claim(name):
            HB["names"].add(name)
            try:
                if not os.path.exists(path + ".done"):
                    run(name, PY + [os.path.join(S, "build_sequence.py"), c["mix_yaml"], path, "--seed", str(seed)],
                        time.time() + 3600)
            finally:
                HB["names"].discard(name)
                release(name)
            return os.path.exists(path + ".done")
        time.sleep(60)
    return False


# ---------------- claims ----------------
def claim(name):
    d = os.path.join(LD, "claim_" + name)
    try:
        os.mkdir(d)
    except FileExistsError:
        hb = os.path.join(d, "heartbeat")
        age = time.time() - (os.path.getmtime(hb) if os.path.exists(hb) else os.path.getmtime(d))
        if age < 900:
            return False
        say(f"claim {name}: stale ({age:.0f}s); taking over")
        shutil.rmtree(d, ignore_errors=True)
        try:
            os.mkdir(d)
        except FileExistsError:
            return False
    open(os.path.join(d, "owner"), "w").write(f"{cfg()['slot']} job {JOB} {utc()}\n")
    open(os.path.join(d, "heartbeat"), "w").write(utc())
    return True


def release(name):
    shutil.rmtree(os.path.join(LD, "claim_" + name), ignore_errors=True)


HB = {"names": set()}


def heartbeat_loop():
    while True:
        for n in list(HB["names"]):
            try:
                with open(os.path.join(LD, "claim_" + n, "heartbeat"), "w") as f:
                    f.write(utc())
            except Exception:  # noqa: BLE001
                pass
        time.sleep(60)


threading.Thread(target=heartbeat_loop, daemon=True).start()


# ---------------- P_lead planner ----------------
def wall_speed(arm, phase="short", runs_dir=None):
    """samples per wall second of the training phase, saves and curve points included (from the train log)."""
    tl = os.path.join(runs_dir or os.path.join(V, "runs"), arm, phase, "train_log.jsonl")
    first = last = None
    n = 0
    for line in open(tl, encoding="utf-8"):
        d = json.loads(line)
        if "step_s" in d:
            t = ts(d["utc"])
            first = t if first is None else first
            last = t
            n = d["samples"]
    return n / max(last - first, 1.0), n, last - first


def eval_seconds_per_crop(arm):
    m = jload(os.path.join(PREDS, arm, "short", "meta.json"), {}) or {}
    rows = sum(v.get("done", 0) for v in (m.get("sets") or {}).values())
    return (m.get("wall_seconds_this_call", 1800) / max(rows, 1)), rows, m.get("wall_seconds_this_call")


def n_rows_all_val():
    reg = jload(EVALSETS, {}) or {}
    n = 0
    for e in reg.get("sets", []):
        if e["name"] in ready_val_sets():
            n += int(e.get("n_rows") or 0)
    return n


def plan(runs_list, windows):
    """runs_list: [(L, seed_index)] - amendment 3.4: 2 leaders x 2 seeds + 2 extra arms x seed 1."""
    c = cfg()
    end = ts(c["plan_end_utc"])  # training end (24 Nov 11:30Z)
    end_eval = ts(c.get("plan_end_eval_utc", c["plan_end_utc"]))  # validation end (24 Nov 11:55Z)
    margin = float(c.get("plan_margin", 0.9))
    info = {}
    work = []
    tail = {}
    full_rows = n_rows_all_val()
    for L, si in runs_list:
        arm = L["arm"]
        if arm not in info:
            v, n, w = wall_speed(arm, runs_dir=RUNS_DIR_OF.get(arm))
            spc, rows, ew = eval_seconds_per_crop(arm)
            info[arm] = {"wall_samples_per_s_short": v, "used_samples_per_s": v * margin, "short_samples": n,
                         "short_wall_s": w, "eval_s_per_crop": spc, "d9_rows": rows, "d9_eval_wall_s": ew,
                         "full_val_rows": full_rows, "kind": L.get("kind", "vlma")}
        v = info[arm]["used_samples_per_s"]
        spc, ew = info[arm]["eval_s_per_crop"], info[arm]["d9_eval_wall_s"]
        load = 600.0
        name = "%s_seed%d" % (arm, si)
        final_eval = full_rows * spc / margin
        tail[name] = final_eval
        if si == 1:
            work.append({"run": name, "fixed": load + final_eval, "per_sample": 1.0 / v, "extra_short": 0.0})
        else:
            work.append({"run": name, "fixed": 2 * load + (ew or 1800) / margin + final_eval, "per_sample": 1.0 / v,
                         "extra_short": P_SHORT / v})
    now = time.time()
    starts = {s: (now if str(t).upper() == "NOW" else max(now, ts(t))) for s, t in windows.items() if t}
    starts = {s: t for s, t in starts.items() if t < end}
    # remaining seconds of a run as a + b * P (P = P_lead): seed 1 trains P - 150,000; seed 2 trains its own 150,000 too
    lin = {}
    for w in work:
        if w["extra_short"] > 0:
            lin[w["run"]] = (w["fixed"], w["per_sample"])
        else:
            lin[w["run"]] = (w["fixed"] - P_SHORT * w["per_sample"], w["per_sample"])
    runs = sorted(lin)
    slots = sorted(starts)
    best = None
    for code in range(len(slots) ** len(runs)):  # every placement of the runs on the slots (no run is split)
        place, x = {}, code
        for r in runs:
            place[r] = slots[x % len(slots)]
            x //= len(slots)
        pmax = float("inf")
        for s in slots:
            mine = [r for r in runs if place[r] == s]
            if not mine:
                continue
            A = sum(lin[r][0] for r in mine)
            B = sum(lin[r][1] for r in mine)
            # all work incl. every final validation by end_eval, and all work except the last run's final validation
            # (the slot runs its largest-tail run last) by the training end
            pmax = min(pmax, (end_eval - starts[s] - A) / B, (end - starts[s] - (A - max(tail[r] for r in mine))) / B)
        loads = sorted(sum(lin[r][0] + lin[r][1] * pmax for r in runs if place[r] == s) for s in slots)
        key = (pmax, -loads[-1])
        if best is None or key > best[0]:
            best = (key, place)
    (pbest, _), place = best
    P = max(P_SHORT, int(pbest) // 32 * 32)
    feasible = pbest >= P_SHORT
    timeline = {}
    for s in slots:
        t = starts[s]
        for r in sorted([r for r in runs if place[r] == s], key=lambda r: -(lin[r][0] + lin[r][1] * P)):
            d = lin[r][0] + lin[r][1] * P
            timeline.setdefault(s, []).append({"run": r, "start_utc": utc(t), "end_utc": utc(t + d), "hours": round(d / 3600, 2)})
            t += d
    return {"P_lead": P, "feasible": feasible, "placement": place, "timeline_estimate": timeline, "inputs": info,
            "slot_starts_utc": {k: utc(v) for k, v in starts.items()}, "plan_end_utc": c["plan_end_utc"],
            "margin_on_speed": margin,
            "plan_end_eval_utc": c.get("plan_end_eval_utc"),
            "method": "amendment 3.4 E3: largest multiple of 32 such that some placement of the six runs on the slots "
                      "(each run on one slot; all placements tried) keeps every slot's training before plan_end_utc and "
                      "all its work incl. final validation before plan_end_eval_utc; per run: model loads, training at "
                      "the measured wall-clock speed of the leader's short run x margin (seed 2 also trains its own "
                      "150,000), seed-2 D9 validation and the final validation on every ready val set at the measured "
                      "seconds per crop; speeds only, never accuracy",
            "computed_utc": utc(), "computed_by_job": JOB}


def get_plan(leaders, windows):
    """plan_lead.json is written once by the first runner that gets the plan lock and never rewritten."""
    p = os.path.join(LD, "plan_lead.json")
    while not os.path.exists(p):
        if claim("plan"):
            try:
                if not os.path.exists(p):
                    pl = plan(leaders, windows)
                    jdump(pl, p)
                    say("P_lead planned:", pl["P_lead"], json.dumps(pl["placement"]))
            except Exception as ex:  # noqa: BLE001
                say("planning failed:", repr(ex)[:300], "; retry in 5 min")
                release("plan")
                time.sleep(300)
                continue
            release("plan")
        else:
            time.sleep(30)
    return jload(p)


# ---------------- stages of one leader run ----------------
def phases(seed_index):
    """scorer convention: the second seed is a checkpoint of the SAME arm named <checkpoint>_seed2."""
    return ("short", "leader") if seed_index == 1 else ("short_seed2", "leader_seed2")


def do_run(L, seed_index, P):
    c = cfg()
    arm, ph_short, ph_lead = names(L, seed_index)
    seq = c["seq1"] if seed_index == 1 else c["seq2"]
    dos = 20261121 if seed_index == 1 else 20261122
    tdl, edl = ts(c["train_deadline_utc"]), ts(c["eval_deadline_utc"])
    if seed_index == 2:
        if not ensure_seq(seq, dos):
            say("seed-2 sequence not ready")
            return False
        if not trained(arm, ph_short):
            run(f"{arm}:{ph_short}", train_cmd(L, ph_short, arm, seq, P_SHORT, 0, None, 2, dos, 3.0), tdl + 900, env_for(L))
            if not trained(arm, ph_short):
                return False
        want = [s for s in D9 if s in ready_val_sets()]
        if not set(want) <= eval_sets_done(arm, ph_short):
            run(f"{arm}:{ph_short}_eval", eval_cmd(L, arm, ph_short), edl, env_for(L))
    if not trained(arm, ph_lead):
        init = os.path.join(CK, arm, ph_short + "_state")
        run(f"{arm}:{ph_lead}", train_cmd(L, ph_lead, arm, seq, P - P_SHORT, P_SHORT, init, seed_index, dos, 100.0),
            tdl + 900, env_for(L))
        if not trained(arm, ph_lead):
            return False
    want = ready_val_sets()
    if not set(want) <= eval_sets_done(arm, ph_lead):
        run(f"{arm}:{ph_lead}_eval", eval_cmd(L, arm, ph_lead), edl, env_for(L))
    return set(want) <= eval_sets_done(arm, ph_lead)


def collect():
    """results.json and runs.tsv of all VLMA arms in DATA/outputs/r5/vlma/ (cheap; reads logs and meta files only)."""
    try:
        run("collect", PY + [os.path.join(S, "collect_results.py"), REG, V], time.time() + 600)
    except Exception as ex:  # noqa: BLE001
        say("collect failed", repr(ex)[:200])


# ---------------- main ----------------
say(f"slot {cfg()['slot']} job {JOB} config {CFG}")
collect()
def retry_sets_done(arm, ckpt):
    m = jload(os.path.join(PREDS, arm, ckpt + "_retry", "meta.json"), {}) or {}
    return {k for k, v in (m.get("sets") or {}).items() if v.get("complete")}


# 1. catch-up of finished short arms (VLMA's own arms): D9 sets that became ready later, and the cap-retry folder
#    (<ckpt>_retry: only the hit_cap rows are re-decoded; r5_posttrain_experiment.txt). Claimed per arm, so both slots
#    can share it.
for short in cfg().get("short_arms", []):
    if time.time() >= ts(cfg()["train_deadline_utc"]):
        break
    if not trained(short, "short"):
        continue
    want = [s for s in D9 if s in ready_val_sets()]
    done_sets = eval_sets_done(short, "short")
    if (not set(want) <= done_sets or not done_sets <= retry_sets_done(short, "short")) and claim("eval_" + short):
        HB["names"].add("eval_" + short)
        try:
            run(f"{short}:catchup_d9", eval_cmd({"short": short, "kind": "vlma"}, short, "short"), ts(cfg()["eval_deadline_utc"]))
        finally:
            HB["names"].discard("eval_" + short)
            release("eval_" + short)
# PT-RL checkpoints whose validation the 5-hour job could not finish
PTRL_SETS = "V1,curve_v1,synth_clutter_val,synth_hand_val,synth_typed_val,print_real_val"
for kx in ("C", "D", "G"):
    ck = "ptrl_" + kx
    if not os.path.exists(os.path.join(CK, "paddleocr_vl_1_6", ck, "r5_export.json")):
        continue
    want = [s for s in PTRL_SETS.split(",") if s in ready_val_sets()]
    if set(want) <= eval_sets_done("paddleocr_vl_1_6", ck) or not claim("eval_" + ck):
        continue
    HB["names"].add("eval_" + ck)
    try:
        run(f"{ck}:catchup_eval", eval_cmd({"short": "paddleocr_vl_1_6", "kind": "vlma"}, "paddleocr_vl_1_6", ck, PTRL_SETS),
            ts(cfg()["eval_deadline_utc"]))
    finally:
        HB["names"].discard("eval_" + ck)
        release("eval_" + ck)
collect()
# 2. wait for the leaders file
lf = os.path.join(LD, "leaders.json")
while not os.path.exists(lf):
    if time.time() >= ts(cfg()["train_deadline_utc"]):
        say("no leaders file before the training deadline; exit")
        sys.exit(0)
    say("waiting for", lf)
    time.sleep(300)
LJ = jload(lf)
# amendment 3.4 E2: "leaders" = the two leaders (two seeds each unless an entry says "seeds"), "extra" = the two extra
# arms (seed 1 only: continue from their short checkpoint on seed-1 data). kind "vlmb" (or "vlmc") = maker-code arm,
# launched through VLMB's leader_interface.json (leader_cmds.py).
RUNS = []
for L in LJ.get("leaders", []):
    for si in L.get("seeds", [1, 2]):
        RUNS.append((L, int(si)))
for L in LJ.get("extra", []):
    for si in L.get("seeds", [1]):
        RUNS.append((L, int(si)))
for L, si in RUNS:
    L.setdefault("arm", L["short"])
    if is_vlmb(L):
        RUNS_DIR_OF[L["arm"]] = lc.vlmb_runs_dir()
        RUNS_DIR_OF[lc.vlmb_arm(L["short"], 2)] = lc.vlmb_runs_dir()
windows = dict(cfg().get("slot_windows_default_utc", {cfg()["slot"]: "NOW"}))
windows.update(LJ.get("slot_windows_utc") or {})
PLAN = get_plan(RUNS, windows)
P = PLAN["P_lead"]
say("P_lead", P, "runs", ["%s_seed%d" % (L["arm"], si) for L, si in RUNS])


def est_work(L, si):
    """remaining-work estimate for ordering only (planned speed; seed 2 also has its own short phase)."""
    v = PLAN["inputs"].get(L["arm"], {}).get("used_samples_per_s") or 1.0
    arm, ph_short, ph_lead = names(L, si)
    done_lead = run_json(arm, ph_lead).get("samples_seen", 0) or 0
    short_left = 0 if si == 1 or trained(arm, ph_short) else P_SHORT - (run_json(arm, ph_short).get("samples_seen", 0) or 0)
    return (short_left + max(P - P_SHORT - done_lead, 0)) / v


# 3. leader runs: the runs the plan placed on this slot first, longest remaining first; each claimed by one slot at a time
state_p = os.path.join(LD, "runs_state.json")
while time.time() < ts(cfg()["train_deadline_utc"]):
    st = jload(state_p, {}) or {}
    todo = []
    for L, si in RUNS:
        name = "%s_seed%d" % (L["arm"], si)
        if st.get(name, {}).get("status") in ("done", "failed_final"):
            continue
        todo.append((L, si, name))
    if not todo:
        say("all leader runs done or failed twice; exit")
        break
    mine = cfg()["slot"]
    # runs the plan placed on this slot first (longest remaining first), then any open run of the other slot
    todo.sort(key=lambda x: (PLAN.get("placement", {}).get(x[2], mine) != mine, -est_work(x[0], x[1])))
    took = False
    for L, si, name in todo:
        if not claim("run_" + name):
            continue
        took = True
        HB["names"].add("run_" + name)
        try:
            ok = do_run(L, si, P)
        except Exception as ex:  # noqa: BLE001
            say(f"{name}: error {repr(ex)[:300]}")
            ok = False
        finally:
            HB["names"].discard("run_" + name)
            release("run_" + name)
        st = jload(state_p, {}) or {}
        d = st.setdefault(name, {"attempts": 0})
        d["attempts"] += 1
        d["status"] = "done" if ok else ("failed" if d["attempts"] < 2 else "failed_final")
        d["last_utc"] = utc()
        d["last_job"] = JOB
        jdump(st, state_p)
        collect()
        break
    if not took:
        say("every open run is claimed by another slot; waiting")
        time.sleep(300)
say("leader runner finished")