turkic-ocr-code / scripts /r5_vlma /ptrl_driver.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
7.17 kB
"""R5 PT-RL driver for the one GPU job r5_ptrl_V (records/R5/RULE/r5_posttrain_experiment.txt).
Readiness gate: DATA/outputs/r5/ptrl/READY must exist and list the sha256 of ptrl.py, vlm_common.py and eval_vlm.py as
they are now (written by VLMA only after the ZEN4 CPU tests passed). Otherwise: status "not run, not ready", exit 0.
Per arm, in the order C, D, G: a 3-minute GPU smoke (an arm whose smoke fails is skipped and recorded, never fixed);
the 70-minute run (resumes if a state exists); export; validation on V1, curve_v1, synth_clutter_val, synth_hand_val,
synth_typed_val, print_real_val into preds/paddleocr_vl_1_6/ptrl_<arm> (greedy; plus the cap-retry folder). A stage
is started only if the time left in the job allows it; an evaluation left out is done later by the leader runner's
catch-up. Status: DATA/outputs/r5/ptrl/status.json.
usage: ptrl_driver.py JOB_END_EPOCH
"""
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time
from datetime import datetime, timezone
END = float(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"]
O = sys.argv[2] if len(sys.argv) > 2 else os.path.join(DATA, "outputs", "r5", "ptrl") # argv[2]: test folder only
CK = os.path.join(DATA, "checkpoints", "r5")
LOGD = os.path.join(DATA, "logs", "r5_vlma")
os.makedirs(O, exist_ok=True)
JOB = os.environ.get("SLURM_JOB_ID", "nojob")
SETS = "V1,curve_v1,synth_clutter_val,synth_hand_val,synth_typed_val,print_real_val"
BASE = os.path.join(CK, "paddleocr_vl_1_6", "short_state")
COMMON = ["--registry", os.path.join(S, "models_r5.tsv"), "--models-dir", os.path.join(DATA, "hf_cache", "j2_models"),
"--base-state", BASE, "--seq", os.path.join(DATA, "data", "processed", "r5", "seq", "mix_v1_seq.tsv"),
"--start-row", "150000", "--ckpt-root", CK, "--out-root", os.path.join(DATA, "outputs", "r5", "ptrl", "runs")]
def utc():
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def sha(p):
return hashlib.sha256(open(p, "rb").read()).hexdigest()
STATUS_P = os.path.join(O, "status.json")
status = json.load(open(STATUS_P)) if os.path.exists(STATUS_P) else {}
def put(**kw):
status.update(kw)
status["updated_utc"] = utc()
tmp = STATUS_P + ".tmp"
json.dump(status, open(tmp, "w"), indent=1)
os.replace(tmp, STATUS_P)
def run(tag, cmd, budget_s):
lp = os.path.join(LOGD, "ptrl_%s_%s.log" % (tag, JOB))
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")
t0 = time.time()
with open(lp, "a") as lf:
lf.write(f"\n===== {utc()} job {JOB} cmd: {' '.join(cmd)}\n")
lf.flush()
try:
rc = subprocess.run(["timeout", "-k", "120", str(int(max(budget_s, 60)))] + cmd, stdout=lf,
stderr=subprocess.STDOUT, env=env).returncode
except Exception as e: # noqa: BLE001
rc = -1
lf.write(repr(e) + "\n")
print(f"[ptrl_driver {utc()}] {tag}: rc {rc} after {time.time() - t0:.0f}s (log {lp})", flush=True)
return rc, round(time.time() - t0, 1), lp
def left():
return END - time.time()
# ---------------- readiness gate ----------------
ready_p = os.path.join(O, "READY")
files = {f: os.path.join(S, f) for f in ("ptrl.py", "vlm_common.py", "eval_vlm.py")}
ok = os.path.exists(ready_p)
if ok:
rd = json.load(open(ready_p))
ok = all(rd.get("sha256", {}).get(f) == sha(p) for f, p in files.items())
if not ok:
put(job=JOB, result="not run, not ready", why="READY file missing or code changed since the CPU tests", utc=utc())
print("[ptrl_driver] not run, not ready", flush=True)
sys.exit(0)
put(job=JOB, started_utc=utc(), code_sha256={f: sha(p) for f, p in files.items()})
for arm in ("C", "D", "G"):
rec = status.get("arm_" + arm, {})
ph = "ptrl_" + arm
if rec.get("state") in ("done", "smoke failed, skipped"):
continue
# 1) 3-minute smoke (training minutes = 3; model loads not counted), no export
if not rec.get("smoke_ok"):
if left() < 20 * 60:
rec.update(state="not run: no time left in the job for the smoke")
put(**{"arm_" + arm: rec})
continue
sm = "smoke_" + ph
rc, sec, lp = run(sm, PY + [os.path.join(S, "ptrl.py"), "--arm-kind", arm, "--phase", sm, "--minutes", "3",
"--no-export", "--save-every-min", "1000"] + COMMON, 15 * 60)
shutil.rmtree(os.path.join(CK, "paddleocr_vl_1_6", sm + "_state"), ignore_errors=True)
if rc != 0:
rec.update(state="smoke failed, skipped", smoke_rc=rc, smoke_log=lp, smoke_seconds=sec)
put(**{"arm_" + arm: rec})
continue
rec.update(smoke_ok=True, smoke_seconds=sec)
put(**{"arm_" + arm: rec})
# 2) the 70-minute run (training seconds; resumes from its state if any)
rj = os.path.join(O, "runs", "paddleocr_vl_1_6", ph, "run.json")
done_train = os.path.exists(rj) and json.load(open(rj)).get("exported")
if not done_train:
if left() < 80 * 60:
rec.update(state="not run: less than 80 min left in the job")
put(**{"arm_" + arm: rec})
continue
rc, sec, lp = run(ph, PY + [os.path.join(S, "ptrl.py"), "--arm-kind", arm, "--phase", ph, "--minutes", "70"] + COMMON,
left() - 120)
rec.update(train_rc=rc, train_wall_seconds=sec, train_log=lp)
done_train = os.path.exists(rj) and json.load(open(rj)).get("exported")
if not done_train:
rec.update(state="training did not finish")
put(**{"arm_" + arm: rec})
continue
rec.update(run=json.load(open(rj)))
put(**{"arm_" + arm: rec})
# 3) validation (greedy + cap-retry folder); left out if under 25 min remain (leader runner catch-up does it)
if left() < 25 * 60:
rec.update(state="trained; validation left to the leader runner catch-up (no time)")
put(**{"arm_" + arm: rec})
continue
rc, sec, lp = run(ph + "_eval", PY + [os.path.join(S, "eval_vlm.py"), "--short", "paddleocr_vl_1_6", "--arm",
"paddleocr_vl_1_6", "--ckpt", ph, "--model-dir", os.path.join(CK, "paddleocr_vl_1_6", ph),
"--registry", os.path.join(S, "models_r5.tsv"), "--evalsets",
os.path.join(DATA, "data", "processed", "r5", "evalsets.json"), "--preds-root",
os.path.join(DATA, "outputs", "r5", "preds"), "--batch", "16", "--sets", SETS,
"--deadline-utc", "2026-11-23T18:55:00Z"],
left() - 60)
rec.update(eval_rc=rc, eval_seconds=sec, state="done" if rc == 0 else "trained; validation incomplete")
put(**{"arm_" + arm: rec})
put(finished_utc=utc())
print("[ptrl_driver] finished", flush=True)