File size: 28,381 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 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 | """R5 VLMB queue runner for GPU slot L (one long Slurm job; every task in its own subprocess).
VLMA's runner.py (copy: records/R5/VLMB/harness/runner_VLMA_copy.py) adapted to the maker-code arms:
- each model runs with its own pinned venv (registry column "venv"); scripts vlmb_train_vlm.py / vlmb_eval_vlm.py;
- the smoke task also runs vlmb_check.py on the GPU (adapter training forward vs the maker's own forward on 4 KOHTD
train crops; pass = argmax agreement >= 0.98 on target positions, or "no separate forward"), then 20 steps with a
save at 10 and a resume, then generation on 16 train crops from the exported weights. A model whose smoke fails is
retried once at the end of the queue, then left "not trained".
- the queue file is re-read before every task, so models are added to "short" when their CPU set-up passes;
- the short runs wait for the shared sequence file (built by VLMA from mix_v1.yaml; rows 0-149,999 = P_short);
- leaders (amendment 3.2 C4): only an explicit entry "L" in the leaders file starts a continuation on this slot (no
automatic pick); from leaders_start_utc a running short run is told to stop (SIGUSR1: it saves, exports and is
validated), then the leader runs. A leader that is a VLMA arm runs with VLMA's own scripts and venv.
- the runner exits when nothing is runnable after idle_exit_utc, or 10 min before deadline_utc.
usage: vlmb_runner.py QUEUE_JSON
"""
import glob
import json
import os
import shutil
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_vlmb")
SA = os.path.join(CODE, "scripts", "r5_vlma")
REG = os.path.join(S, "models_r5_vlmb.tsv")
REG_A = os.path.join(SA, "models_r5.tsv")
MODELS = os.path.join(DATA, "hf_cache", "r5_vlmb_models")
MODELS_A = os.path.join(DATA, "hf_cache", "j2_models")
CK = os.path.join(DATA, "checkpoints", "r5")
V = os.path.join(DATA, "outputs", "r5", "vlmb")
VA = 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(VA, "smoke_seq_kohtd_train.tsv")
LOGD = os.path.join(DATA, "logs", "r5_vlmb")
os.makedirs(LOGD, exist_ok=True)
JOB = os.environ.get("SLURM_JOB_ID", "nojob")
def read_reg(path):
out = {}
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
hdr = f.readline().rstrip("\n").split("\t")
for line in f:
r = dict(zip(hdr, line.rstrip("\n").split("\t")))
out[r["short"]] = r
return out
def py_for(short):
r = read_reg(REG)[short]
return [os.path.join(CODE, ".venv_vlm_" + r["venv"], "bin", "python"), "-I"]
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", "L")
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)
# ---- shared arms across two slots (added by stage VLMC on 2026-11-21 on request) ----------------
# A queue file may name another queue file under "shared_queue": this runner also takes that file's "short" arms, after
# its own list. Arms listed there, and with "claim_own": true this runner's own arms, run only once across slots: the
# runner that starts an arm first creates DATA/outputs/r5/vlmb/claims/<arm>.json atomically (O_CREAT|O_EXCL, owner =
# slot name, so a restarted job of the same slot keeps its claim); any other slot skips that arm and counts it as
# finished for exit_when_done. A queue file without these keys behaves exactly as before.
CLAIMS = os.path.join(V, "claims")
def jdump_atomic(obj, path):
tmp = path + ".tmp%d" % os.getpid()
json.dump(obj, open(tmp, "w"), indent=1)
os.replace(tmp, path)
def jload_retry(path, default):
"""Read a JSON file that another runner may be replacing; retry briefly on a read error."""
for _ in range(5):
try:
return json.load(open(path)) if os.path.exists(path) else default
except Exception: # noqa: BLE001
time.sleep(1)
return json.load(open(path))
def arm_lists(q):
"""(own arms + shared arms in order, set of claimable arms)."""
own = list(q.get("short", []))
shared = []
sq = q.get("shared_queue")
if sq:
try:
shared = [a for a in json.load(open(sq)).get("short", []) if a not in own]
except Exception as ex: # noqa: BLE001
say("shared queue unreadable", repr(ex)[:120])
claimable = set(shared) | (set(own) if q.get("claim_own") else set())
return own + shared, claimable
# Claim expiry (21 Nov): a claim held by another slot expires when its Slurm job is no longer running
# (squeue: unknown job id or an end state) AND that slot's runner state does not show the arm finished; the claim file
# is then renamed to <arm>.json.expired_<utc>_by_<slot> and this slot claims the arm. squeue errors count as "running"
# (no takeover on a controller hiccup). Built for two slots, where only one live runner can try a takeover.
JOB_END_STATES = ("COMPLETED", "FAILED", "CANCELLED", "TIMEOUT", "NODE_FAIL", "PREEMPTED", "OUT_OF_MEMORY",
"BOOT_FAIL", "DEADLINE", "REVOKED", "SPECIAL_EXIT")
_JOBQ = {}
def job_alive(job):
job = str(job or "")
if not job.isdigit():
return True
c = _JOBQ.get(job)
if c and time.time() - c[0] < 60:
return c[1]
try:
r = subprocess.run(["squeue", "-h", "-j", job, "-o", "%T"], capture_output=True, text=True, timeout=60)
states = (r.stdout or "").split()
if r.returncode == 0:
alive = bool(states) and not all(s.startswith(JOB_END_STATES) for s in states)
else:
alive = "Invalid job id" not in (r.stderr or "")
except Exception: # noqa: BLE001
alive = True
_JOBQ[job] = (time.time(), alive)
return alive
def finished_in_slot(arm, slot):
st = jload_retry(os.path.join(V, f"runner_state_{slot}.json"), {}) or {}
return (st.get(f"short:{arm}", {}).get("status") in ("done", "failed_final")
or st.get(f"smoke:{arm}", {}).get("status") == "failed_final")
def claim_info(arm):
p = os.path.join(CLAIMS, arm + ".json")
if not os.path.exists(p):
return None
try:
return json.load(open(p))
except Exception: # noqa: BLE001
return {"slot": "unreadable (being written by another runner)", "unreadable": True}
def claim_owner(arm):
return (claim_info(arm) or {}).get("slot")
def claim_expired(info, arm):
return (not info.get("unreadable") and info.get("slot") != SLOT and not job_alive(info.get("job"))
and not finished_in_slot(arm, info.get("slot")))
def claimed_elsewhere(arm, claimable):
if arm not in claimable:
return False
info = claim_info(arm)
return info is not None and info.get("slot") != SLOT and not claim_expired(info, arm)
def try_claim(arm):
os.makedirs(CLAIMS, exist_ok=True)
p = os.path.join(CLAIMS, arm + ".json")
for _ in range(3):
try:
fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
except FileExistsError:
info = claim_info(arm)
if info is None:
continue
if info.get("slot") == SLOT:
return True
if not claim_expired(info, arm):
return False
try:
os.rename(p, p + ".expired_%s_by_%s" % (utc().replace(":", ""), SLOT))
say(f"claim on {arm} by slot {info.get('slot')} job {info.get('job')} expired (job not running, arm not "
f"finished there); taking it over")
except FileNotFoundError:
pass
continue
with os.fdopen(fd, "w") as f:
json.dump({"arm": arm, "slot": SLOT, "job": JOB, "utc": utc()}, f)
say(f"claimed {arm} for slot {SLOT}")
return True
return False
CUR = {"proc": None, "curve_s": 0.0}
class CurveClock:
"""Training-task timeout pause (21 Nov, decision (a)): learning-curve evaluation time does not count
against the training task's timeout. vlmb_train_vlm.py's curve_eval opens PREDS/<arm>/curve_<n>/curve_v1.raw.jsonl
when it starts and writes meta.json (with eval_seconds) when it ends. A curve folder whose raw file was written
during this task and whose meta.json is missing or older is running: its time so far (since the raw file's mtime at
first sight) is excluded; once meta.json appears, its measured eval_seconds are excluded instead."""
def __init__(self, arm, t0):
self.arm, self.t0, self.seen, self.done = arm, t0, {}, {}
def excluded(self, now, tid):
for raw in glob.glob(os.path.join(PREDS, self.arm, "curve_*", "curve_v1.raw.jsonl")):
d = os.path.dirname(raw)
if d in self.done:
continue
try:
rm = os.path.getmtime(raw)
except OSError:
continue
if rm < self.t0 - 5:
continue
mp = os.path.join(d, "meta.json")
if d not in self.seen:
self.seen[d] = min(rm, now)
say(f"{tid}: curve evaluation running ({os.path.basename(d)}); training timeout paused")
if os.path.exists(mp) and os.path.getmtime(mp) >= rm:
try:
es = float(json.load(open(mp)).get("eval_seconds"))
except Exception: # noqa: BLE001
es = max(0.0, os.path.getmtime(mp) - self.seen[d])
self.done[d] = es
say(f"{tid}: curve evaluation {os.path.basename(d)} done, {es:.0f} s excluded from the training timeout")
running = sum(now - t for d, t in self.seen.items() if d not in self.done)
return sum(self.done.values()) + running
def run(tid, cmd, timeout_s, poll=None, curve_arm=None):
q = rq()
hard = ts(q["deadline_utc"])
lp = os.path.join(LOGD, tid.replace(":", "_") + f"_{JOB}.log")
say(f"{tid}: start ({os.path.basename(cmd[2])}) log {lp}")
env = dict(os.environ)
env.pop("HF_TOKEN", None)
env.pop("HUGGING_FACE_HUB_TOKEN", None)
short = tid.split(":", 1)[1] if ":" in tid else "x"
env.update(HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", TOKENIZERS_PARALLELISM="false", PYTHONUNBUFFERED="1",
PYTHONDONTWRITEBYTECODE="1", HF_HOME=os.path.join(DATA, "hf_cache", "r5_vlmb_home"),
HF_MODULES_CACHE=os.path.join(DATA, "tmp", "r5_vlmb_hf_modules", short),
TORCHINDUCTOR_CACHE_DIR=os.path.join(DATA, "tmp", "r5_vlmb_inductor", short),
TRITON_CACHE_DIR=os.path.join(DATA, "tmp", "r5_vlmb_triton", short))
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()
clock = CurveClock(curve_arm, t0) if curve_arm else None
CUR["curve_s"] = 0.0
excl = 0.0
termed = None
while True:
try:
rc = p.wait(timeout=30)
CUR["proc"] = None
if clock is not None:
try:
CUR["curve_s"] = clock.excluded(time.time(), tid)
except Exception: # noqa: BLE001
pass
say(f"{tid}: exit {rc} after {time.time() - t0:.0f}s"
+ (f" ({CUR['curve_s']:.0f}s of curve evaluation not counted in the timeout)" if clock else ""))
return rc
except subprocess.TimeoutExpired:
pass
now = time.time()
if clock is not None:
try:
excl = clock.excluded(now, tid)
except Exception as ex: # noqa: BLE001
say(f"{tid}: curve clock error {repr(ex)[:120]}")
CUR["curve_s"] = excl
if termed is None and (now >= hard or now - t0 - excl >= 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)
PRECF = os.path.join(V, "precision_fallback.json")
def prec(short):
"""pure_bf16 (VLMA's rule) unless this model ran out of memory at micro-batch 1 under it; then amp_bf16 (fp32
weights + bf16 autocast, 16 instead of 20 bytes per parameter), recorded as a stated deviation."""
d = jload_retry(PRECF, {})
return d.get(short, {}).get("precision", "pure_bf16")
def oom_fallback(short, arm, phase):
mk = os.path.join(V, "runs", arm, phase, "oom_mb1.json")
if not os.path.exists(mk) or prec(short) != "pure_bf16":
return False
d = jload_retry(PRECF, {})
d[short] = {"precision": "amp_bf16", "why": "CUDA out of memory at micro-batch 1 under pure bf16 + fp32 master",
"evidence": mk, "oom": json.load(open(mk)), "utc": utc()}
jdump_atomic(d, PRECF)
os.rename(mk, mk + ".seen")
say(f"{short}: OOM at micro-batch 1 under pure_bf16; switching to amp_bf16 (stated deviation)")
return True
def train_cmd(short, phase, seq, n, extra=()):
q = rq()
return py_for(short) + [os.path.join(S, "vlmb_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"],
"--precision", prec(short)] + list(extra)
def eval_cmd(short, arm, ckpt, export_dir, extra=()):
q = rq()
st = os.path.join(export_dir, "model_bf16.pt") if export_dir != "none" else "none"
return py_for(short) + [os.path.join(S, "vlmb_eval_vlm.py"), "--short", short, "--arm", arm, "--ckpt", ckpt,
"--base-dir", os.path.join(MODELS, short), "--state", st, "--registry", REG,
"--deadline-utc", q["deadline_utc"]] + list(extra)
def run_json(arm, phase, root=None):
p = os.path.join(root or V, "runs", arm, phase, "run.json")
return json.load(open(p)) if os.path.exists(p) else {}
def do_smoke(short):
arm = "smoke_" + short
for d in (os.path.join(CK, arm), os.path.join(V, "runs", arm)):
shutil.rmtree(d, ignore_errors=True)
ckf = os.path.join(V, "runs", arm, "check")
# check in fp32 weights (amp mode, no autocast inside the check) on 8 crops; fail only on clear divergence
rc0 = run(f"smoke:{short}", py_for(short) + [os.path.join(S, "vlmb_check.py"), "--short", short, "--model-dir",
os.path.join(MODELS, short), "--seq", SMOKE_SEQ, "--out", ckf,
"--n", "8", "--device", "cuda", "--precision", "amp_bf16"], 1800)
chk = json.load(open(os.path.join(ckf, "check.json"))) if os.path.exists(os.path.join(ckf, "check.json")) else {}
eq = chk.get("equivalence")
eq_ok = (rc0 == 0) and (isinstance(eq, str) or (isinstance(eq, dict) and eq.get("argmax_agreement_on_targets", 0) >= 0.95))
base = ["--arm", arm, "--save-every-min", "1000"]
rc1 = None
for attempt in range(2):
rc1 = run(f"smoke:{short}", train_cmd(short, "smoke", SMOKE_SEQ, 640, base + ["--stop-after-steps", "10"]), 2400) if eq_ok else None
if rc1 == 0 or not oom_fallback(short, arm, "smoke"):
break
for d in (os.path.join(CK, arm), os.path.join(V, "runs", arm, "smoke")):
shutil.rmtree(d, ignore_errors=True)
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 = (eq_ok and 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": [rc0, rc1, rc2, rc3], "equivalence": eq, "check_ok": eq_ok,
"base_loss_eval_mode": chk.get("base_loss_eval_mode"), "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 = jload_retry(sp, {})
allp[short] = summ
jdump_atomic(allp, sp)
if ok:
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))
sets = m.get("sets") or {}
if not sets:
return False
if all(v.get("complete") for v in sets.values()):
return True
# rule of 2026-11-22 (VLMC): an evaluation stopped by its time limit, with V1 complete, counts as done; sets
# not finished keep the label "not evaluated (time)" (the eval script lists them under not_evaluated_sets)
v1 = sets.get("V1") or sets.get("kohtd_screen_v1") or {}
return v1.get("complete") is True and all(v.get("complete") is True or v.get("status") == "not evaluated (time)"
for v in 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:
# 4.5 h training-task timeout, learning-curve evaluation time excluded (CurveClock; 21 Nov)
run(f"short:{short}", train_cmd(short, "short", q["seq"], 150000, ["--cap-hours", "3.0"]), 4.5 * 3600, poll=stop_poll,
curve_arm=short)
mark(f"short:{short}", train_timeout_curve_seconds_excluded=round(CUR["curve_s"], 1))
rj = run_json(short, "short")
if not rj.get("exported") and oom_fallback(short, short, "short"):
run(f"short:{short}", train_cmd(short, "short", q["seq"], 150000, ["--cap-hours", "3.0"]), 4.5 * 3600,
poll=stop_poll, curve_arm=short)
mark(f"short:{short}", train_timeout_curve_seconds_excluded_oom_rerun=round(CUR["curve_s"], 1))
rj = run_json(short, "short")
if not rj.get("exported"):
return False
if not eval_done(short, "short"):
sets = ",".join(q.get("short_eval_sets", [])) # amendment 3.3 D9: reduced validation list for short runs
run(f"short:{short}", eval_cmd(short, short, "short", rj["export_dir"],
["--evalsets", EVALSETS, "--preds-root", PREDS, "--batch", "16"]
+ (["--sets", sets] if sets else [])), 3 * 3600)
return eval_done(short, "short")
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])
return None
def do_long(L):
"""Continuation of a leader on slot L. VLMB arm: own scripts; VLMA arm: VLMA's train_vlm.py / eval_vlm.py."""
q = rq()
short = L["short"]
arm = L.get("arm", short)
mine = short in read_reg(REG)
root = V if mine else VA
st_dir = os.path.join(CK, arm, "short_state")
rj_s = run_json(arm, "short", root)
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
ext = ["--arm", arm, "--start-row", "150000", "--init-state", st_dir, "--init-optimizer", "--cap-hours", "100"]
rj = run_json(arm, "long", root)
if not (rj.get("exported") and str(rj.get("flag", "")).startswith(("complete", "stopped at the absolute deadline"))):
if mine:
cmd = train_cmd(short, "long", q["seq"], n, ext)
else:
cmd = [os.path.join(CODE, ".venv_vlm", "bin", "python"), "-I", os.path.join(SA, "train_vlm.py"), "--short", short,
"--registry", REG_A, "--models-dir", MODELS_A, "--seq", q["seq"], "--ckpt-root", CK, "--out-root",
os.path.join(VA, "runs"), "--phase", "long", "--n-samples", str(n), "--deadline-utc",
q["train_deadline_utc"]] + ext
run(f"long:{short}", cmd, 20 * 3600)
rj = run_json(arm, "long", root)
if not rj.get("exported"):
return False
if not eval_done(arm, "long"):
if mine:
cmd = eval_cmd(short, arm, "long", rj["export_dir"], ["--evalsets", EVALSETS, "--preds-root", PREDS, "--batch", "16"])
else:
cmd = [os.path.join(CODE, ".venv_vlm", "bin", "python"), "-I", os.path.join(SA, "eval_vlm.py"), "--short", short,
"--arm", arm, "--ckpt", "long", "--model-dir", rj["export_dir"], "--registry", REG_A, "--deadline-utc",
q["deadline_utc"], "--evalsets", EVALSETS, "--preds-root", PREDS, "--batch", "16"]
run(f"long:{short}", cmd, 4 * 3600)
return eval_done(arm, "long")
def seq_ready():
q = rq()
return os.path.exists(q["seq"]) and os.path.exists(q["seq"] + ".done")
def next_task(stt, q, retry):
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
arms, claimable = arm_lists(q)
for s in arms:
if claimed_elsewhere(s, claimable):
continue
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():
return ("short", s, f"short:{s}")
return None
say(f"slot {SLOT} job {JOB} queue {QF}")
stt0 = load_state()
for tid, d in stt0.items():
if d.get("status") == "running":
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
arms_all, claimable_all = arm_lists(q)
L = leaders_for_slot()
if L and stt.get(f"long:{L['short']}", {}).get("status") not in ("done", "failed_final") and (
now >= ts(q["leaders_start_utc"]) or all(stt.get(f"short:{s}", {}).get("status") in ("done", "failed_final")
or claimed_elsewhere(s, claimable_all) for s in arms_all)):
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
# amendment 3.3 D8: slot L passes to the line block after the short round; no new task after no_new_task_after_utc,
# and the job ends as soon as every listed arm is done or failed for good
if q.get("no_new_task_after_utc") and now >= ts(q["no_new_task_after_utc"]):
say("no_new_task_after_utc passed; exit so slot L passes on")
break
fin = ("done", "failed_final")
if q.get("exit_when_done") and all(stt.get(f"short:{s}", {}).get("status") in fin
or stt.get(f"smoke:{s}", {}).get("status") == "failed_final"
or claimed_elsewhere(s, claimable_all) for s in arms_all):
say("short round complete for every listed arm; exit so slot L passes on")
break
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 the sequence file / new models / leaders); sleeping 300 s")
time.sleep(300)
continue
kind, s, tid = pick
if s in claimable_all and not try_claim(s):
say(f"{s}: claimed by slot {claim_owner(s)} meanwhile; re-picking")
continue
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")
|