File size: 16,254 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
"""R5 VLMA queue runner for one GPU slot (one long Slurm job; every task in its own subprocess).

The queue file (JSON) is re-read before every task, so tasks can be added, reordered or reset while the job runs:
  {"slot": "V", "deadline_utc": "2026-11-22T18:58:00Z", "train_deadline_utc": "2026-11-22T18:55:00Z",
   "smoke": [shorts], "short": [shorts], "reset": [task ids to clear], "mix_yaml": path, "seq": path,
   "leaders_file": path, "leaders_start_utc": "2026-11-22T08:00:00Z", "idle_exit_utc": "2026-11-22T10:00:00Z"}
Task ids: smoke:<short>, short:<short>, long:<short>.
Order: every smoke task; then (once mix_v1.yaml exists and the sequence file is built) every short task in list order;
a failed task is logged and skipped and retried once after all others. Leaders (amendment 3.2 C4): when the leaders
file names an arm for this slot, its continuation runs next; from leaders_start_utc on, a running short training is
told to stop (SIGTERM: it finishes the step, saves, exports), its validation runs, then the leader runs.
If no leaders file exists at leaders_start_utc + 30 min, the runner picks for slot V the arm with the lowest V1 plain
CER among all finished short arms in the prediction folder and writes leaders_auto_<slot>.json (a manual choice can
override it by writing the leaders file). STOP file next to the state file: finish the current task, then exit.
Nothing runs after deadline_utc: subprocesses get SIGTERM at the deadline and SIGKILL 90 s later.

usage: runner.py QUEUE_JSON
"""
import glob
import json
import os
import signal
import subprocess
import sys
import time
from datetime import datetime, timezone

QF = 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")
SMOKE_SEQ = os.path.join(V, "smoke_seq_kohtd_train.tsv")
LOGD = os.path.join(DATA, "logs", "r5_vlma")
os.makedirs(LOGD, exist_ok=True)
JOB = os.environ.get("SLURM_JOB_ID", "nojob")


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"[runner {utc()}]", *a, flush=True)


def rq():
    return json.load(open(QF))


q = rq()
SLOT = q.get("slot", "V")
STATE = os.path.join(V, f"runner_state_{SLOT}.json")
STOPF = os.path.join(V, f"STOP_{SLOT}")


def load_state():
    return json.load(open(STATE)) if os.path.exists(STATE) else {}


def save_state(stt):
    tmp = STATE + ".tmp"
    json.dump(stt, open(tmp, "w"), indent=1)
    os.replace(tmp, STATE)


def mark(tid, **kw):
    stt = load_state()
    d = stt.setdefault(tid, {"attempts": 0, "history": []})
    d.update(kw)
    save_state(stt)


CUR = {"proc": None}


def run(tid, cmd, timeout_s, poll=None):
    """Run one subprocess; returns its exit code (None on timeout/deadline kill)."""
    q = rq()
    hard = ts(q["deadline_utc"])
    lp = os.path.join(LOGD, tid.replace(":", "_") + f"_{JOB}.log")
    say(f"{tid}: start ({' '.join(cmd[2:5])} ...) log {lp}")
    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
        t0 = time.time()
        termed = None
        while True:
            try:
                rc = p.wait(timeout=30)
                CUR["proc"] = None
                say(f"{tid}: exit {rc} after {time.time() - t0:.0f}s")
                return rc
            except subprocess.TimeoutExpired:
                pass
            now = time.time()
            if termed is None and (now >= hard or now - t0 >= timeout_s):
                say(f"{tid}: {'deadline' if now >= hard else 'timeout'}; SIGTERM")
                p.send_signal(signal.SIGTERM)
                termed = now
            elif termed is None and poll is not None and poll():
                say(f"{tid}: stop requested (leaders); SIGUSR1")
                p.send_signal(signal.SIGUSR1)
                termed = now
            elif termed is not None and now - termed > (900 if now < hard else 90):
                say(f"{tid}: SIGKILL")
                p.kill()


def on_term(signum, frame):  # noqa: ARG001
    say(f"runner got signal {signum}; passing SIGTERM to the running task")
    if CUR["proc"] is not None:
        CUR["proc"].send_signal(signal.SIGTERM)


signal.signal(signal.SIGTERM, on_term)


def train_cmd(short, phase, seq, n, extra=()):
    q = rq()
    return PY + [os.path.join(S, "train_vlm.py"), "--short", short, "--registry", REG, "--models-dir", MODELS, "--seq", seq,
                 "--ckpt-root", CK, "--out-root", os.path.join(V, "runs"), "--phase", phase, "--n-samples", str(n),
                 "--deadline-utc", q["train_deadline_utc"]] + list(extra)


def eval_cmd(short, arm, ckpt, model_dir, extra=()):
    q = rq()
    return PY + [os.path.join(S, "eval_vlm.py"), "--short", short, "--arm", arm, "--ckpt", ckpt, "--model-dir", model_dir,
                 "--registry", REG, "--deadline-utc", q["deadline_utc"]] + list(extra)


def run_json(arm, phase):
    p = os.path.join(V, "runs", arm, phase, "run.json")
    return json.load(open(p)) if os.path.exists(p) else {}


# ---------------- task bodies ----------------
def do_smoke(short):
    arm = "smoke_" + short
    import shutil
    for d in (os.path.join(CK, arm), os.path.join(V, "runs", arm)):
        shutil.rmtree(d, ignore_errors=True)
    base = ["--arm", arm, "--save-every-min", "1000"]
    rc1 = run(f"smoke:{short}", train_cmd(short, "smoke", SMOKE_SEQ, 640, base + ["--stop-after-steps", "10"]), 2400)
    rc2 = run(f"smoke:{short}", train_cmd(short, "smoke", SMOKE_SEQ, 640, base), 2400) if rc1 == 0 else None
    rj = run_json(arm, "smoke")
    rc3 = None
    if rc2 == 0 and rj.get("exported"):
        rc3 = run(f"smoke:{short}", eval_cmd(short, arm, "smoke", rj["export_dir"],
                                             ["--smoke-seq", SMOKE_SEQ, "--smoke-n", "16",
                                              "--smoke-out", os.path.join(V, "runs", arm, "smoke", "smoke_generation.json")]), 1800)
    ok = (rc1 == 0 and rc2 == 0 and rc3 == 0 and rj.get("steps") == 20 and rj.get("resumed_from_step") == [10]
          and rj.get("resume_fingerprint_match") is True)
    med = rj.get("median_step_seconds")
    summ = {"short": short, "ok": ok, "rc": [rc1, rc2, rc3], "steps": rj.get("steps"),
            "resumed_from_step": rj.get("resumed_from_step"), "resume_fingerprint_match": rj.get("resume_fingerprint_match"),
            "median_step_seconds_kohtd_words": med, "micro_batch": rj.get("micro_batch"), "oom_events": rj.get("oom_events"),
            "max_mem_GiB_train": rj.get("max_mem_GiB_train"),
            "projected_hours_150k_kohtd_words": round(med * 4688 / 3600, 2) if med else None, "utc": utc()}
    sp = os.path.join(V, "smoke_summary.json")
    allp = json.load(open(sp)) if os.path.exists(sp) else {}
    allp[short] = summ
    json.dump(allp, open(sp, "w"), indent=1)
    if ok:  # keep logs, drop the large smoke weights
        shutil.rmtree(os.path.join(CK, arm), ignore_errors=True)
    return ok


def eval_done(arm, ckpt):
    mp = os.path.join(PREDS, arm, ckpt, "meta.json")
    if not os.path.exists(mp):
        return False
    m = json.load(open(mp))
    return bool(m.get("sets")) and all(v.get("complete") for v in m["sets"].values())


def do_short(short, stop_poll):
    q = rq()
    rj = run_json(short, "short")
    final_flags = ("complete", "short of P", "stopped at the absolute deadline", "interrupted (leaders")
    trained = bool(rj.get("exported")) and str(rj.get("flag", "")).startswith(final_flags)
    if not trained:
        rc = run(f"short:{short}", train_cmd(short, "short", q["seq"], 150000, ["--cap-hours", "3.0"]), 4.5 * 3600, poll=stop_poll)
        rj = run_json(short, "short")
        if not rj.get("exported"):
            return False
    if not eval_done(short, "short"):
        rc = run(f"short:{short}", eval_cmd(short, short, "short", rj["export_dir"],
                                            ["--evalsets", EVALSETS, "--preds-root", PREDS, "--batch", "16"]), 3 * 3600)
    return eval_done(short, "short")


def v1_cer(meta):
    for k, v in meta.get("sets", {}).items():
        if k in ("V1", "kohtd_screen_v1") and v.get("complete"):
            return v.get("plain_cer")
    return None


def leaders_for_slot():
    q = rq()
    lf = q.get("leaders_file")
    if lf and os.path.exists(lf):
        try:
            d = json.load(open(lf))
            e = d.get(SLOT) or d.get("slot_" + SLOT)
            if e:
                return dict(e, source=lf)
        except Exception as ex:  # noqa: BLE001
            say("leaders file unreadable", repr(ex)[:100])
    auto = os.path.join(V, f"leaders_auto_{SLOT}.json")
    if os.path.exists(auto):
        return dict(json.load(open(auto)), source=auto)
    if time.time() >= ts(q["leaders_start_utc"]) + 1800:
        best = []
        for mp in glob.glob(os.path.join(PREDS, "*", "short", "meta.json")):
            m = json.load(open(mp))
            c = v1_cer(m)
            if c is not None and m.get("short"):
                best.append((c, m["arm"], m["short"]))
        best.sort()
        mine = [b for b in best if b[2] in q.get("short", []) and os.path.isdir(os.path.join(CK, b[1], "short_state"))]
        if mine:
            c, arm, short = mine[0]
            d = {"short": short, "arm": arm, "v1_plain_cer": c, "ranking": best[:6],
                 "why": "no leaders file at leaders_start_utc + 30 min; lowest V1 plain CER among finished short arms with a state on this slot's disk (amendment 3.2 C4)",
                 "written_utc": utc()}
            json.dump(d, open(auto, "w"), indent=1)
            return dict(d, source=auto)
    return None


def do_long(L):
    q = rq()
    short = L["short"]
    arm = L.get("arm", short)
    st_dir = os.path.join(CK, arm, "short_state")
    rj_s = run_json(arm, "short")
    n = L.get("extra_samples")
    if not n:
        sps = rj_s["samples_seen"] / max(rj_s["train_seconds"], 1)
        ev = 0
        mp = os.path.join(PREDS, arm, "short", "meta.json")
        if os.path.exists(mp):
            ev = json.load(open(mp)).get("wall_seconds_this_call", 1800)
        avail = ts(q["train_deadline_utc"]) - time.time() - 1.3 * ev - 1200
        n = int(sps * avail * 0.95) // 32 * 32
        L["extra_samples_computed"] = {"samples_per_s_short": sps, "available_s": avail, "n": n}
    mark(f"long:{short}", plan=L)
    if n < 3200:
        say("long: not enough time left for a continuation", n)
        return False
    rj = run_json(arm, "long")
    if not (rj.get("exported") and str(rj.get("flag", "")).startswith(("complete", "stopped at the absolute deadline"))):
        run(f"long:{short}", train_cmd(short, "long", q["seq"], n,
                                       ["--arm", arm, "--start-row", "150000", "--init-state", st_dir, "--init-optimizer",
                                        "--cap-hours", "100"]), 20 * 3600)
        rj = run_json(arm, "long")
        if not rj.get("exported"):
            return False
    if not eval_done(arm, "long"):
        run(f"long:{short}", eval_cmd(short, arm, "long", rj["export_dir"],
                                      ["--evalsets", EVALSETS, "--preds-root", PREDS, "--batch", "16"]), 4 * 3600)
    return eval_done(arm, "long")


def seq_ready():
    q = rq()
    if os.path.exists(q["seq"]) and os.path.exists(q["seq"] + ".done"):
        return True
    if not os.path.exists(q["mix_yaml"]):
        return False
    b = os.path.join(S, "build_sequence.py")
    if not os.path.exists(b):
        say("mix_v1.yaml exists but build_sequence.py is not written yet")
        return False
    rc = run("build_sequence", PY + [b, q["mix_yaml"], q["seq"]], 3600)
    return rc == 0 and os.path.exists(q["seq"] + ".done")


SEQ_OK = {"v": False}


def seq_ready_cached():
    if not SEQ_OK["v"]:
        SEQ_OK["v"] = seq_ready()
    return SEQ_OK["v"]


def next_task(stt, q, retry):
    """Smoke test of a model before its short run. While the sequence is not ready, only smoke tests run; once it is
    ready, the models are taken in list order (smoke test just before its short run if not yet done)."""
    def eligible(d):
        if d.get("status") in ("done", "failed_final", "running"):
            return False
        return d.get("status") == "failed" if retry else d.get("attempts", 0) == 0
    for s in q.get("short", []):
        sm, sh = stt.get(f"smoke:{s}", {}), stt.get(f"short:{s}", {})
        if sm.get("status") != "done":
            if eligible(sm):
                return ("smoke", s, f"smoke:{s}")
            continue
        if eligible(sh) and seq_ready_cached():
            return ("short", s, f"short:{s}")
    return None


# ---------------- main loop ----------------
say(f"slot {SLOT} job {JOB} queue {QF}")
stt0 = load_state()
for tid, d in stt0.items():
    if d.get("status") == "running":  # the previous job died inside this task: resume it, not a failure
        d["status"] = "interrupted"
        d["attempts"] = max(0, d.get("attempts", 1) - 1)
        d.setdefault("history", []).append("interrupted by job end, seen by job %s" % JOB)
save_state(stt0)
while True:
    q = rq()
    stt = load_state()
    for tid in q.get("reset", []):
        if tid in stt and stt[tid].get("reset_token") != q.get("reset_token"):
            say(f"reset {tid}")
            stt[tid] = {"attempts": 0, "history": stt[tid].get("history", []), "reset_token": q.get("reset_token")}
    save_state(stt)
    now = time.time()
    if now >= ts(q["deadline_utc"]) - 600:
        say("deadline near; exit")
        break
    if os.path.exists(STOPF):
        say("STOP file; exit")
        break
    L = leaders_for_slot() if now >= ts(q["leaders_start_utc"]) or all(
        stt.get(f"short:{s}", {}).get("status") in ("done", "failed_final") for s in q["short"]) else None
    if L and stt.get(f"long:{L['short']}", {}).get("status") not in ("done", "failed_final"):
        tid = f"long:{L['short']}"
        a = stt.get(tid, {}).get("attempts", 0)
        mark(tid, status="running", attempts=a + 1, started=utc())
        try:
            ok = do_long(L)
        except Exception as ex:  # noqa: BLE001
            say(f"{tid}: runner error {repr(ex)[:300]}")
            ok = False
        mark(tid, status="done" if ok else ("failed" if a == 0 else "failed_final"), ended=utc())
        continue
    pick = next_task(stt, q, False) or next_task(stt, q, True)
    if pick is None:
        if now >= ts(q.get("idle_exit_utc", q["deadline_utc"])):
            say("nothing left to do and idle exit time passed; exit")
            break
        say("nothing runnable now (waiting for mix_v1.yaml / sequence / leaders); sleeping 300 s")
        time.sleep(300)
        continue
    kind, s, tid = pick
    a = stt.get(tid, {}).get("attempts", 0)
    mark(tid, status="running", attempts=a + 1, started=utc(), job=JOB)

    def stop_poll():
        qq = rq()
        if time.time() < ts(qq["leaders_start_utc"]):
            return False
        Lx = leaders_for_slot()
        return bool(Lx) and Lx.get("short") != s and (Lx.get("interrupt_running", True))

    try:
        ok = do_smoke(s) if kind == "smoke" else do_short(s, stop_poll)
    except Exception as ex:  # noqa: BLE001
        say(f"{tid}: runner error {repr(ex)[:300]}")
        ok = False
    mark(tid, status="done" if ok else ("failed" if a == 0 else "failed_final"), ended=utc())
    say(f"{tid}: {'done' if ok else 'FAILED'}")
say("runner finished")