Download scripts/r5_vlma/corun_check.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_vlma/corun_check.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_vlma/corun_check.py
-
curl -L -o corun_check.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_vlma/corun_check.py
11.4 kB
| """R5 test pass, clarification J3: co-run check of two evaluation processes on one GPU, on VALIDATION data only. | |
| Run as a step inside job 52335 after the HunyuanOCR seed-2 validation and before 12:00 UTC (corun_check.sh): | |
| 1. refuses when the GPU already runs a compute process (other work would distort the speed and could run out of | |
| memory beside a job that must not be disturbed), when the host has less than --min-free-gib available, or after | |
| --latest-utc; | |
| 2. scratch registry: V1 (kohtd_screen_v1, words) and print_real_val (lines), both VALIDATION manifests of the real | |
| registry, entered as CORUN_W / CORUN_L with locked true and split val (eval_vlm_test.py reads only locked entries and | |
| requires rows of the entry's split); scratch gate file; scratch preds roots; the real gate is not touched; | |
| 3. reads every image of the check rows once (page cache), then runs eval_vlm_test.py (the test-pass code, batch 16, | |
| greedy, max_new_tokens 48/192) once alone, then twice at the same time on the same rows (same batches); | |
| 4. images per second = rows / (end of the last set - start of the first set) from each call's meta.json (model loading | |
| excluded); for the pair: 2 x rows / (latest end - earliest start) over both processes; | |
| 5. passes when (a) pair >= 1.2 x single and (b) every greedy output ("raw" in <set>.raw.jsonl) of each concurrent | |
| process equals the single-process output byte for byte, row by row; | |
| 6. writes --nfile: first line "2" when it passes, else "1"; second line a JSON summary; full report in <out>/corun_check.json. | |
| usage: corun_check.py [--short hunyuanocr --model-dir DATA/checkpoints/r5/hunyuanocr/leader] [--words 2048 --lines 512] | |
| """ | |
| import argparse | |
| import csv | |
| import json | |
| import os | |
| import subprocess | |
| import sys | |
| import time | |
| from datetime import datetime, timezone | |
| CODE = "/path/to/TURKIC_OCR_CODE" | |
| DATA = "/path/to/TURKIC_OCR_DATA" | |
| S = os.path.join(CODE, "scripts", "r5_vlma") | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--short", default="hunyuanocr") | |
| ap.add_argument("--model-dir", default=DATA + "/checkpoints/r5/hunyuanocr/leader") | |
| ap.add_argument("--words", type=int, default=2048) | |
| ap.add_argument("--lines", type=int, default=512) | |
| ap.add_argument("--batch", type=int, default=16) | |
| ap.add_argument("--out", default=DATA + "/outputs/r5/vlma/corun") | |
| ap.add_argument("--nfile", default=DATA + "/outputs/r5/vlma/testpass_nproc.txt") | |
| ap.add_argument("--latest-utc", default="2026-11-24T11:45:00Z") | |
| ap.add_argument("--min-free-gib", type=float, default=40.0) | |
| ap.add_argument("--force", action="store_true", help="run although the GPU has a compute process (the result is then flagged)") | |
| a = ap.parse_args() | |
| def utc(): | |
| return datetime.now(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 say(*x): | |
| print("[corun %s]" % utc(), *x, flush=True) | |
| rep = {"started_utc": utc(), "rule": "clarification J3: N=2 iff pair >= 1.2 x single images/s AND every greedy output byte-identical", | |
| "short": a.short, "model_dir": a.model_dir, "batch": a.batch, "words": a.words, "lines": a.lines} | |
| def finish(n, why): | |
| rep.update({"N": n, "decision": why, "ended_utc": utc()}) | |
| os.makedirs(a.out, exist_ok=True) | |
| json.dump(rep, open(os.path.join(a.out, "corun_check.json"), "w"), indent=1) | |
| tmp = a.nfile + ".tmp" | |
| with open(tmp, "w") as f: | |
| f.write("%d\n%s\n" % (n, json.dumps({k: rep.get(k) for k in ("N", "decision", "single_images_per_s", "pair_images_per_s", | |
| "ratio", "greedy_identical", "ended_utc", "short")}))) | |
| os.replace(tmp, a.nfile) | |
| say("N=%d: %s (report %s/corun_check.json, N file %s)" % (n, why, a.out, a.nfile)) | |
| sys.exit(0) | |
| if time.time() >= ts(a.latest_utc): | |
| say("REFUSED: after %s (J3: the check runs before 12:00); nothing written, the slots run N=1 by default" % a.latest_utc) | |
| sys.exit(2) | |
| q = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader"], capture_output=True, text=True) | |
| g = subprocess.run(["nvidia-smi", "--query-gpu=name,utilization.gpu,memory.used,memory.total", "--format=csv,noheader"], capture_output=True, text=True) | |
| rep["gpu_before"] = g.stdout.strip() | |
| rep["gpu_compute_apps_before"] = q.stdout.strip() | |
| mem = {ln.split(":")[0]: ln.split(":")[1].strip() for ln in open("/proc/meminfo") if ":" in ln} | |
| free_gib = int(mem.get("MemAvailable", "0 kB").split()[0]) / 2 ** 20 | |
| rep["host_mem_available_gib"] = round(free_gib, 1) | |
| if q.stdout.strip() and not a.force: | |
| say("REFUSED: the GPU runs a compute process (%s); run again when it is idle" % q.stdout.strip().replace("\n", "; ")) | |
| sys.exit(2) | |
| if free_gib < a.min_free_gib: | |
| say("REFUSED: %.1f GiB available on the host, need %.0f" % (free_gib, a.min_free_gib)) | |
| sys.exit(2) | |
| if not os.path.isdir(a.model_dir): | |
| say("REFUSED: no model at %s" % a.model_dir) | |
| sys.exit(2) | |
| rep["flag_forced_with_busy_gpu"] = bool(q.stdout.strip()) | |
| reg = json.load(open(DATA + "/data/processed/r5/evalsets.json", encoding="utf-8")) | |
| ents = reg["sets"] if isinstance(reg, dict) else reg | |
| src = {e["name"]: e for e in ents if e.get("name") in ("V1", "print_real_val")} | |
| for n in ("V1", "print_real_val"): | |
| e = src[n] | |
| assert e.get("locked") is not True and str(e.get("split")).lower() in ("val", "validation"), "not a validation set: %s" % n | |
| os.makedirs(a.out, exist_ok=True) | |
| for d in ("single", "p0", "p1"): | |
| subprocess.call(["rm", "-rf", os.path.join(a.out, d)]) | |
| regp = os.path.join(a.out, "registry_corun.json") | |
| json.dump({"about": "co-run check (J3): VALIDATION manifests entered as locked so that eval_vlm_test.py reads them; not a test set", | |
| "sets": [{"name": "CORUN_W", "manifest": src["V1"]["manifest"], "split": "val", "locked": True, "unit": "word"}, | |
| {"name": "CORUN_L", "manifest": src["print_real_val"]["manifest"], "split": "val", "locked": True, "unit": "line"}]}, | |
| open(regp, "w"), indent=1) | |
| gate = os.path.join(a.out, "gate_corun.txt") | |
| open(gate, "w").write("co-run check scratch gate %s (not the test-pass gate)\n" % utc()) | |
| nbytes = 0 | |
| for name, lim in (("V1", a.words), ("print_real_val", a.lines)): | |
| with open(src[name]["manifest"], encoding="utf-8") as f: | |
| for i, r in enumerate(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)): | |
| if i >= lim: | |
| break | |
| with open(r["image"], "rb") as im: | |
| nbytes += len(im.read()) | |
| rep["warmed_image_bytes"] = nbytes | |
| def cmd(tag): | |
| # --limit applies per set: the word set gets a.words rows; the line set is a scratch copy of the first a.lines rows | |
| # of print_real_val (below), so one call per process loads the model once | |
| return [CODE + "/.venv_vlm/bin/python", "-I", S + "/eval_vlm_test.py", "--short", a.short, "--arm", "corun", "--ckpt", "c", | |
| "--model-dir", a.model_dir, "--registry", S + "/models_r5.tsv", "--evalsets", regp, "--preds-root", os.path.join(a.out, tag), | |
| "--sets", "CORUN_W,CORUN_L", "--test-pass", "--gate-file", gate, "--batch", str(a.batch), "--limit", str(a.words), | |
| "--deadline-utc", "2026-11-24T11:58:00Z", "--device", "cuda"] | |
| # the line set must hold a.lines rows under the same --limit: a scratch copy of the first a.lines rows of print_real_val | |
| lp = os.path.join(a.out, "corun_lines.tsv") | |
| with open(src["print_real_val"]["manifest"], encoding="utf-8") as f, open(lp, "w", encoding="utf-8") as g2: | |
| for i, ln in enumerate(f): | |
| if i > a.lines: | |
| break | |
| g2.write(ln) | |
| regd = json.load(open(regp)) | |
| regd["sets"][1]["manifest"] = lp | |
| json.dump(regd, open(regp, "w"), indent=1) | |
| env = dict(os.environ, HF_HUB_OFFLINE="1", TOKENIZERS_PARALLELISM="false", PYTHONUNBUFFERED="1") | |
| for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): | |
| env.pop(k, None) | |
| def launch(tag): | |
| lf = open(os.path.join(a.out, tag + ".log"), "w") | |
| return subprocess.Popen(cmd(tag), stdout=lf, stderr=subprocess.STDOUT, env=env), lf | |
| def timing(tag): | |
| m = json.load(open(os.path.join(a.out, tag, "corun", "c", "meta.json"))) | |
| sets = m["test_pass"]["sets"] | |
| st, en, rows, comp = [], [], 0, True | |
| for n in ("CORUN_W", "CORUN_L"): | |
| x = sets[n] | |
| e = ts(x["utc"]) | |
| st.append(e - x["wall_seconds_this_call"]) | |
| en.append(e) | |
| rows += x["rows"] | |
| comp = comp and x["complete"] is True | |
| return min(st), max(en), rows, comp | |
| def raws(tag): | |
| out = {} | |
| for n in ("CORUN_W", "CORUN_L"): | |
| for ln in open(os.path.join(a.out, tag, "corun", "c", n + ".raw.jsonl"), encoding="utf-8"): | |
| x = json.loads(ln) | |
| out[(n, x["id"])] = (x["raw"], x.get("conf")) | |
| return out | |
| say("single process: %s, %d word + %d line rows, batch %d" % (a.short, a.words, a.lines, a.batch)) | |
| p, lf = launch("single") | |
| rc = p.wait() | |
| lf.close() | |
| if rc != 0: | |
| finish(1, "single-process run failed (exit %d, log %s/single.log): N=1" % (rc, a.out)) | |
| s0, s1, rows, comp = timing("single") | |
| if not comp: | |
| finish(1, "single-process run incomplete: N=1") | |
| rep["single_window_s"] = round(s1 - s0, 1) | |
| rep["rows_per_process"] = rows | |
| rep["single_images_per_s"] = round(rows / max(s1 - s0, 1), 2) | |
| say("single: %d rows in %.0f s = %.2f images/s" % (rows, s1 - s0, rep["single_images_per_s"])) | |
| say("two processes at once") | |
| p0, l0 = launch("p0") | |
| time.sleep(1) | |
| p1, l1 = launch("p1") | |
| q2 = None | |
| time.sleep(60) | |
| q2 = subprocess.run(["nvidia-smi", "--query-gpu=utilization.gpu,memory.used", "--format=csv,noheader"], capture_output=True, text=True).stdout.strip() | |
| rep["gpu_during_pair"] = q2 | |
| r0, r1 = p0.wait(), p1.wait() | |
| l0.close() | |
| l1.close() | |
| if r0 != 0 or r1 != 0: | |
| finish(1, "a concurrent process failed (exits %d, %d; logs p0.log, p1.log; out of memory?): N=1" % (r0, r1)) | |
| a0, b0, n0, c0 = timing("p0") | |
| a1, b1, n1, c1 = timing("p1") | |
| if not (c0 and c1): | |
| finish(1, "a concurrent run is incomplete: N=1") | |
| win = max(b0, b1) - min(a0, a1) | |
| rep["pair_window_s"] = round(win, 1) | |
| rep["pair_overlap_s"] = round(min(b0, b1) - max(a0, a1), 1) | |
| rep["pair_images_per_s"] = round((n0 + n1) / max(win, 1), 2) | |
| rep["ratio"] = round(rep["pair_images_per_s"] / rep["single_images_per_s"], 3) | |
| ref = raws("single") | |
| mism, confd = {}, 0.0 | |
| for tag in ("p0", "p1"): | |
| got = raws(tag) | |
| bad = [k for k in ref if got.get(k, (None,))[0] != ref[k][0]] | |
| mism[tag] = {"rows_compared": len(ref), "missing": sum(1 for k in ref if k not in got), "raw_differs": len(bad), | |
| "examples": [[k[0], k[1], ref[k][0], got.get(k, (None,))[0]] for k in bad[:5]]} | |
| for k in ref: | |
| if k in got and ref[k][1] is not None and got[k][1] is not None: | |
| confd = max(confd, abs(float(ref[k][1]) - float(got[k][1]))) | |
| rep["greedy_comparison"] = mism | |
| rep["conf_max_abs_difference_info_only"] = confd | |
| rep["greedy_identical"] = all(v["raw_differs"] == 0 and v["missing"] == 0 for v in mism.values()) | |
| say("pair: %d rows in %.0f s = %.2f images/s (ratio %.3f); greedy identical: %s" % | |
| (n0 + n1, win, rep["pair_images_per_s"], rep["ratio"], rep["greedy_identical"])) | |
| if rep["ratio"] >= 1.2 and rep["greedy_identical"]: | |
| finish(2, "passed: ratio %.3f >= 1.2 and every greedy output identical" % rep["ratio"]) | |
| finish(1, "failed: ratio %.3f%s, greedy identical %s" % (rep["ratio"], " < 1.2" if rep["ratio"] < 1.2 else "", rep["greedy_identical"])) | |