turkic-ocr-code / scripts /r5_vlma /testpass_build_tasks.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
18.6 kB
"""R5 test pass: build the ONE shared task list of both GPU slots in the order of clarification J2
(records/R5/RULE/j11_v3_4_clarifications_2.txt, sha256 c34671e9...). Reads only testpass_config.json, the registry
evalsets.json (names, locked flag, unit), the two model registries and selection.json; never a test manifest or image.
Mode "selection" when selection.json is FROZEN at build time: the file and its .sha256 file exist and agree, provisional
is false, B1 is named, and generated_utc is not later than times_utc.not_before (12:00 UTC). B1 and B2 are read from the
role fields of select_b1b2.py (roles.B1/B2: arm, checkpoint, seed2_checkpoint, seed2_arm, short_checkpoint,
short_seed2_checkpoint, short_seed2_arm). Otherwise mode "fallback" (J2 last paragraph): rows 1, 2 and 6 run as the four
leader-length arms' finals in the order hunyuanocr, minicpm_ocr_1_0, paddleocr_vl_1_6, qwen3_vl_2b; row 4 then holds the
P_short checkpoints of those four arms (B1/B2 are among them and unknown) before the line P_short rows.
The builder never fails on selection.json: any exception while reading it or building from its roles means "not frozen"
(fallback, the exception recorded in the list's notes); --force-fallback forces the fallback (the runner's second try).
Rows (J2): 1 B1 finals, 2 B2 finals (row-1 sets: kohtd_test with p2/p2b in the same call, print_real_test,
synth_clutter_test); 3 line decision tier (LINEDET's run() lines, A1/A2 long2x first; LM decoding and its H9 gate hook
run inside each call); 4 B1/B2 at P_short and the line P_short checkpoints on kohtd_test; 5 REF's test_pass_commands.sh
(REF_DEVICE=gpu, slot L, J8); 6 the other leader-length arms (finals on row-1 sets, then P_short on kohtd_test); 7 H14
P_short of every other VLM arm on kohtd_test, cheapest first, granite/youtu/unlimited last; 8 C8 remainder (line arms,
then linedet.lm_gate over all labels, leader finals, leader P_short, short-only arms) on every other locked set.
Locks: one evaluation per VLM checkpoint at a time (vlm_<arm>_<ckpt>: the calls share meta.json); one LINEDET call per
LABEL at a time (linedet_<label>: lm_decode's gate hook rewrites the gated files of every checkpoint of its label); the
final linedet.lm_gate (all labels) runs only while no LINEDET call runs (lock linedet_ALL, exclusive over linedet_*).
A (folder, checkpoint, set) triple is scheduled once: a later row gets only the sets not scheduled before it.
Sets excluded everywhere: config sets.excluded (more_real_print and synth_pages_test by J6; kohtd_rand_test by its
registry text). A checkpoint that does not exist when its task comes up is recorded by the runner as not run.
usage: testpass_build_tasks.py --config testpass_config.json --final [--force-fallback] (the runner; writes testpass_dir/tasks_shared.json ONCE)
testpass_build_tasks.py --config C --out PREVIEW.json [--now-utc T] [--selection S] [--evalsets E] (preview / tests)
"""
import argparse
import csv
import hashlib
import json
import os
import sys
import time
import traceback
from datetime import datetime, timezone
ap = argparse.ArgumentParser()
ap.add_argument("--config", required=True)
ap.add_argument("--final", action="store_true", help="write <testpass_dir>/tasks_shared.json once (mkdir lock); a second call only reads it")
ap.add_argument("--force-fallback", action="store_true", help="ignore selection.json (the runner's second try after a failed build)")
ap.add_argument("--out", default="")
ap.add_argument("--now-utc", default="", help="tests only: pretend the build time")
ap.add_argument("--selection", default="", help="tests only: another selection.json")
ap.add_argument("--evalsets", default="", help="tests only: another registry")
ap.add_argument("--testpass-dir", default="", help="tests only: another testpass folder")
a = ap.parse_args()
def utc(t=None):
return datetime.fromtimestamp(time.time() if t is None else t, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def ts(s):
return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()
def sha(p):
h = hashlib.sha256()
with open(p, "rb") as f:
for b in iter(lambda: f.read(1 << 20), b""):
h.update(b)
return h.hexdigest()
CFG = json.load(open(a.config, encoding="utf-8"))
P = CFG["paths"]
TPD = a.testpass_dir or P["testpass_dir"]
SEL = a.selection or P["selection"]
REGP = a.evalsets or P["evalsets"]
NOW = ts(a.now_utc) if a.now_utc else time.time()
NOT_BEFORE = ts(CFG["times_utc"]["not_before"])
OUT = os.path.join(TPD, "tasks_shared.json") if a.final else a.out
if not OUT:
sys.exit("give --final (runner) or --out (preview)")
if a.final and (a.now_utc or a.selection or a.evalsets):
sys.exit("--final takes no test overrides")
if a.final and os.path.exists(OUT):
print("task list already built:", OUT, sha(OUT))
sys.exit(0)
LOCK = os.path.join(TPD, "build.lock")
if a.final:
os.makedirs(TPD, exist_ok=True)
try:
os.mkdir(LOCK)
except FileExistsError: # the other slot is building it now: wait for its file (the build takes about a second)
for _ in range(240):
if os.path.exists(OUT):
print("task list built by the other slot:", OUT, sha(OUT))
sys.exit(0)
time.sleep(1)
sys.exit("build lock %s held for 4 min and no task list: remove the lock after checking" % LOCK)
import atexit
import shutil
atexit.register(lambda: None if os.path.exists(OUT) else shutil.rmtree(LOCK, ignore_errors=True)) # a failed build frees the lock
def read_shorts(p):
with open(p, encoding="utf-8") as f:
return [r["short"] for r in csv.DictReader(f, delimiter="\t")]
VLMA = set(read_shorts(P["vlma_registry"]))
MAKER = set(read_shorts(P["maker_registry"]))
reg_doc = json.load(open(REGP, encoding="utf-8"))
ents = reg_doc["sets"] if isinstance(reg_doc, dict) and isinstance(reg_doc.get("sets"), list) else reg_doc
LOCKED = {e["name"]: e for e in ents if isinstance(e, dict) and (e.get("locked") is True or str(e.get("split", "")).lower() == "test")}
S = CFG["sets"]
EXCL = S["excluded"]
LEAD = list(CFG["leader_arms_fallback_order"])
LR = CFG["line_rows"]
CKR = P["ckpt_root"]
H14 = [x for x, _ in CFG["h14_order_tp_plan_tier_B_minutes"]]
base_notes = []
for n in sorted(LOCKED):
if n not in S["other_order"] and n not in EXCL:
base_notes.append("locked set %s is in neither other_order nor excluded: appended to other_order" % n)
OTHER = [n for n in S["other_order"] if n in LOCKED and n not in EXCL] + sorted(n for n in LOCKED if n not in S["other_order"] and n not in EXCL)
for n in S["other_order"]:
if n not in LOCKED:
base_notes.append("set %s of other_order is not a locked registry set: not scheduled" % n)
def clean(sets):
return [s for s in sets if s in LOCKED and s not in EXCL]
# ---------------------------------------------------------------- selection.json: frozen or not (never raises)
sel_info = {"path": SEL, "exists": os.path.exists(SEL), "forced_fallback": bool(a.force_fallback)}
sel, checks = None, {}
try:
if os.path.exists(SEL) and not a.force_fallback:
sel_info["sha256"] = sha(SEL)
shp = SEL + ".sha256"
sel_info["sha256_file"] = open(shp).read().strip() if os.path.exists(shp) else None
sel = json.load(open(SEL, encoding="utf-8"))
gen = str(sel.get("generated_utc") or "")
checks = {"sha256_file_matches": bool(sel_info.get("sha256_file")) and sel_info["sha256_file"].split()[0] == sel_info["sha256"],
"not_provisional": sel.get("provisional") is False,
"b1_named": bool(sel.get("B1")) and isinstance((sel.get("roles") or {}).get("B1"), dict),
"generated_by_not_before": bool(gen) and ts(gen) <= NOT_BEFORE and ts(gen) <= NOW,
"generated_utc": gen}
except Exception: # noqa: BLE001 (unreadable or malformed: not frozen)
sel_info["error"] = traceback.format_exc()[-600:]
checks = {"readable": False}
FROZEN = bool(checks) and all(v for k, v in checks.items() if k != "generated_utc")
sel_info["checks"] = checks
def build(mode):
"""the task list of one mode; returns (tasks, notes, not_scheduled, B1, B2)"""
tasks, sched, notes, not_scheduled = [], {}, [], []
def vlm_task(row, short, folder, ckpt, sets, why):
if short in VLMA:
kind = "vlma"
elif short in MAKER:
kind = "vlmb"
else:
not_scheduled.append({"row": row, "arm": folder, "checkpoint": ckpt, "why": "arm %s is in no model registry" % short})
return
if kind == "vlmb" and row != "8": # no reuse of kohtd_test outputs in the maker-code script: p2/p2b go to row 8
sets = [s for s in sets if s not in ("kohtd_test_p2", "kohtd_test_p2b")]
have = sched.setdefault((folder, ckpt), [])
todo = [s for s in clean(sets) if s not in have]
if not todo:
return
first = not have
have.extend(todo)
t = {"id": "r%s:%s:%s" % (row, folder, ckpt) + ("" if first else ":rest"), "row": row,
"kind": kind, "short": short, "arm": folder, "ckpt": ckpt, "sets": todo, "batch": 16, "why": why,
"lock": "vlm_%s_%s" % (folder, ckpt)}
if kind == "vlma":
t["model_dir"] = os.path.join(CKR, folder, ckpt)
t["exists_path"] = t["model_dir"]
else:
t["state"] = os.path.join(CKR, folder, ckpt, "model_bf16.pt")
t["exists_path"] = t["state"]
tasks.append(t)
def line_task(row, lab, arm, ckd, ckpt, sets, why):
have = sched.setdefault(("line:" + lab, ckpt), [])
todo = [s for s in clean(sets) if s not in have]
if not todo:
return
first = not have
have.extend(todo)
cd = LR["ckpt_dirs"][ckd]
tasks.append({"id": "r%s:line:%s:%s" % (row, lab, ckpt) + ("" if first else ":rest"), "row": row,
"kind": "cmd", "owner": "LINEDET", "arm": lab, "ckpt": ckpt, "sets": todo,
"argv": ["bash", P["linedet_task"], lab, arm, cd, ckpt, ",".join(todo)], "gate": P["gate_linedet"],
"lock": "linedet_%s" % lab, "blocked_by": ["linedet_ALL"], "exists_path": os.path.join(cd, arm, ckpt + ".pt"), "why": why})
def finals_of_role(r):
out = [(r["arm"], r["arm"], r["checkpoint"])]
if r.get("seed2_checkpoint"):
out.append((r["arm"], r.get("seed2_arm") or r["arm"], r["seed2_checkpoint"]))
return out
def shorts_of_role(r):
out = [(r["arm"], r["arm"], r.get("short_checkpoint") or "short")]
if r.get("short_seed2_checkpoint"):
out.append((r["arm"], r.get("short_seed2_arm") or r["arm"], r["short_seed2_checkpoint"]))
return out
def finals_of_leader(arm):
return [(arm, arm, "leader")] + ([(arm, arm, CFG["leader_seed2"][arm])] if CFG["leader_seed2"].get(arm) else [])
def shorts_of_leader(arm):
return [(arm, arm, "short")] + ([(arm, arm, CFG["short_seed2"][arm])] if CFG["short_seed2"].get(arm) else [])
def pshort_sets(short):
return S["pshort_vlma"] if short in VLMA else S["pshort_maker"]
if mode == "selection":
roles = sel.get("roles") or {}
B = [(b, roles[b]) for b in ("B1", "B2") if isinstance(roles.get(b), dict)]
if "B2" not in roles:
notes.append("selection.json names no B2 (%s): row 2 is empty" % sel.get("B2_reason"))
b_arms = [r["arm"] for _, r in B]
others = [x for x in LEAD if x not in b_arms]
for i, (b, r) in enumerate(B): # rows 1 and 2
for short, folder, ck in finals_of_role(r):
vlm_task(str(i + 1), short, folder, ck, S["row1_vlm"], "J2 step %d: %s final checkpoint" % (i + 1, b))
missing_refs = [x for x in ("R1", "R2", "R1_rand", "R2_rand", "R1_iii", "R2_iii") if x not in roles]
if missing_refs:
notes.append("selection.json lacks the reference roles %s (J7, AUDIT G2): the verdict blocks that read them are not "
"evaluable; the REF task runs regardless" % missing_refs)
else:
B, others = [], []
for arm in LEAD:
for short, folder, ck in finals_of_leader(arm):
vlm_task("1", short, folder, ck, S["row1_vlm"], "J2 fallback (rows 1, 2, 6): leader-length final")
for lab, arm, ckd, ck in LR["decision_tier_row3"]: # row 3
line_task("3", lab, arm, ckd, ck, S["row3_line"], "J2 step 3: line row of the decision tier (LM decoding + H9 gate hook in the same call)")
if mode == "selection": # row 4
for b, r in B:
for short, folder, ck in shorts_of_role(r):
vlm_task("4", short, folder, ck, pshort_sets(short), "J2 step 4 (H13): %s at P_short" % b)
else:
for arm in LEAD:
for short, folder, ck in shorts_of_leader(arm):
vlm_task("4", short, folder, ck, pshort_sets(short), "J2 step 4 in fallback: the four leader arms at P_short (B1/B2 unknown)")
for lab, arm, ckd, ck in LR["pshort_row4"]:
line_task("4", lab, arm, ckd, ck, S["pshort_line"], "J2 step 4 (H13): line P_short checkpoint")
tasks.append({"id": "r5:ref_test_pass_commands", "row": "5", "kind": "cmd", "owner": "REF", "argv": ["bash", P["ref_commands"]],
"env": dict(CFG["ref"]["env"]), "gate": P["gate_ref"], "slot": CFG["ref"]["slot"],
"pin_wait_max_seconds": CFG["ref"]["pin_wait_max_seconds"], "lock": "ref",
"why": "J2 step 5 with J8: REF's script unchanged, REF_DEVICE=gpu on slot L (R1/R2 ours and mix on kohtd_test, p2, p2b; rand on kohtd_rand_test)"})
for arm in others: # row 6 (selection mode only)
for short, folder, ck in finals_of_leader(arm):
vlm_task("6", short, folder, ck, S["row1_vlm"], "J2 step 6: other leader-length final")
for arm in others:
for short, folder, ck in shorts_of_leader(arm):
vlm_task("6", short, folder, ck, pshort_sets(short), "J2 step 6: other leader-length arm at P_short")
done_arms = set(LEAD) | {r["arm"] for _, r in B}
for short in H14: # row 7
if short not in done_arms:
vlm_task("7", short, short, "short", pshort_sets(short), "J2 step 7 (H14): P_short, cheapest first by tp_plan.json")
for short in sorted((VLMA | MAKER) - set(H14) - done_arms):
not_scheduled.append({"row": "7", "arm": short, "why": "VLM arm in a registry but not in AUDIT's tier B list (no estimate): not scheduled"})
for lab, arm, ckd, ck in LR["decision_tier_row3"] + LR["pshort_row4"] + LR["rest_row8"]: # row 8
line_task("8", lab, arm, ckd, ck, OTHER, "J2 step 8 (C8): line arm on every other locked set")
tasks.append({"id": "r8:linedet_lm_gate", "row": "8", "kind": "cmd", "owner": "LINEDET",
"argv": [P["linedet_python"], "-I", "-m", "linedet.lm_gate"], "gate": P["gate_linedet"],
"lock": "linedet_ALL", "exclusive_prefix": "linedet_",
"why": "clarification H9 gated form over all labels, as LINEDET's script ends (each lm_decode call already gates its own label); "
"runs only while no LINEDET call runs"})
lead_roles = [r for _, r in B]
for r in lead_roles:
for short, folder, ck in finals_of_role(r):
vlm_task("8", short, folder, ck, OTHER, "J2 step 8 (C8): leader-length final on every other locked set")
for arm in (others if mode == "selection" else LEAD):
for short, folder, ck in finals_of_leader(arm):
vlm_task("8", short, folder, ck, OTHER, "J2 step 8 (C8): leader-length final on every other locked set")
for r in lead_roles:
for short, folder, ck in shorts_of_role(r):
vlm_task("8", short, folder, ck, OTHER, "J2 step 8 (C8): leader-length arm at P_short on every other locked set")
for arm in (others if mode == "selection" else LEAD):
for short, folder, ck in shorts_of_leader(arm):
vlm_task("8", short, folder, ck, OTHER, "J2 step 8 (C8): leader-length arm at P_short on every other locked set")
for short in H14:
if short not in done_arms:
vlm_task("8", short, short, "short", OTHER, "J2 step 8 (C8): short-only VLM arm on every other locked set, cheapest first")
ids = [t["id"] for t in tasks]
assert len(ids) == len(set(ids)), "duplicate task ids"
b1 = B[0][1]["arm"] if B else None
b2 = B[1][1]["arm"] if len(B) > 1 else None
return tasks, notes, not_scheduled, b1, b2
MODE = "selection" if FROZEN else "fallback"
notes = list(base_notes)
built = None
if MODE == "selection":
try:
built = build("selection")
except Exception: # noqa: BLE001 (a malformed role: fall back, never fail)
notes.append("building from selection.json failed, J2 fallback used instead: " + traceback.format_exc()[-500:])
MODE = "fallback"
if MODE == "fallback":
notes.append("selection.json not frozen at build time (%s): J2 fallback, rows 1, 2 and 6 = the four leader-length arms' finals "
"in the order %s; row 4 holds their P_short checkpoints" % (json.dumps(checks) if checks else "absent, unreadable or forced", LEAD))
built = build("fallback")
tasks, n2, not_scheduled, B1, B2 = built
notes += n2
doc = {"schema": "r5-testpass-tasks-1", "built_utc": utc(NOW) if a.now_utc else utc(), "mode": MODE,
"builder": os.path.abspath(__file__), "builder_sha256": sha(os.path.abspath(__file__)),
"config": os.path.abspath(a.config), "config_sha256": sha(a.config), "registry": REGP, "registry_sha256": sha(REGP),
"selection": sel_info, "B1": B1, "B2": B2,
"excluded_sets": EXCL, "other_sets_order": OTHER, "notes": notes, "not_scheduled": not_scheduled,
"rows_count": {r: sum(1 for t in tasks if t["row"] == r) for r in sorted(set(t["row"] for t in tasks))},
"tasks": tasks}
tmp = OUT + ".tmp.%d" % os.getpid()
with open(tmp, "w", encoding="utf-8") as f:
json.dump(doc, f, indent=1, ensure_ascii=False)
os.replace(tmp, OUT)
with open(OUT + ".sha256", "w") as f:
f.write("%s %s %s\n" % (sha(OUT), os.path.basename(OUT), doc["built_utc"]))
print("built", OUT, "mode", MODE, "tasks", len(tasks), "sha256", sha(OUT))
for n in notes:
print("note:", n)