Download scripts/r5_vlmb/vlmb_eval_vlm_testpass.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 33.9 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_vlmb/vlmb_eval_vlm_testpass.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_vlmb/vlmb_eval_vlm_testpass.py
-
curl -L -o vlmb_eval_vlm_testpass.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_vlmb/vlmb_eval_vlm_testpass.py
33.9 kB
| """R5 TEST-PASS copy of VLMB's vlmb_eval_vlm.py (sha256 fb4df8ee5e703ef6be28f79c1766f39844ddf4a59eb1a2b1483db9531147bb30), made by VLMA's make_vlmb_testpass.py | |
| (test-pass plan, Part B): predictions of one maker-code checkpoint on LOCKED sets only, with the gate of | |
| score.py (--test-pass AND the gate file DATA/outputs/r5/RULE/test_pass_started.txt), decided before the adapter or any | |
| manifest is loaded. Decoding, caps, batches, outputs and the cap-retry folder are those of the validation script; | |
| bookkeeping goes to meta_testpass.json; no CER is computed or printed. Original docstring follows. | |
| R5 VLMB: validation predictions of one checkpoint on every VALIDATION set of the registry (never a test set). | |
| VLMA's eval_vlm.py (copy: records/R5/VLMB/harness/eval_vlm_VLMA_copy.py) with the model calls replaced by the adapter: | |
| the pinned base model is built from the maker code, the exported bf16 state dict is loaded into it (strict), and | |
| decoding is the adapter's greedy decoding (one beam, no repetition penalty, no n-gram constraint). Same sets, same | |
| order (V1 first), same caps (48 new tokens for words, 192 for lines, pages skipped), same files: | |
| <preds_root>/<arm>/<ckpt>/<set>.raw.jsonl, <set>.tsv (id, ref, hyp; PLAIN-normalised), <set>.score.json (postproc.py, | |
| byte-identical to VLMA's fingerprinted copy), meta.json with speed at batch 16 on V1 and peak memory at batch 1. | |
| usage: vlmb_eval_vlm.py --short S --arm A --ckpt NAME --base-dir DIR --state PT|none --registry R --evalsets JSON | |
| --preds-root P [--batch 16] [--smoke-seq SEQ --smoke-n 16 --smoke-out FILE] | |
| """ | |
| import argparse | |
| import importlib | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from datetime import datetime, timezone | |
| for _k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): | |
| os.environ.pop(_k, None) | |
| os.environ.setdefault("HF_HUB_OFFLINE", "1") | |
| os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import postproc as pp # noqa: E402 | |
| import torch # noqa: E402 | |
| import transformers # noqa: E402 | |
| from PIL import Image # noqa: E402 | |
| # Performance only (ported by stage VLMC on 2026-11-21 from VLMA's vlm_common.py on request): no cuDNN | |
| # SDPA backend, which re-plans for every new sequence shape (VLMA profile, see vlmb_train_vlm.py). | |
| if hasattr(torch.backends.cuda, "enable_cudnn_sdp"): | |
| torch.backends.cuda.enable_cudnn_sdp(False) | |
| SDPA_NOTE = "cuDNN SDPA backend disabled (torch.backends.cuda.enable_cudnn_sdp(False)); flash / mem-efficient / math backends" | |
| INSTR = "Transcribe the text in this image exactly." | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--short", required=True) | |
| ap.add_argument("--arm", required=True) | |
| ap.add_argument("--ckpt", required=True) | |
| ap.add_argument("--base-dir", required=True) | |
| ap.add_argument("--state", required=True, help="exported model_bf16.pt, or 'none' for the base weights") | |
| ap.add_argument("--registry", required=True) | |
| ap.add_argument("--evalsets", default=None) | |
| ap.add_argument("--preds-root", default=None) | |
| ap.add_argument("--batch", type=int, default=16) | |
| ap.add_argument("--deadline-utc", default="2026-11-22T18:58:00Z") | |
| ap.add_argument("--sets", default="") | |
| ap.add_argument("--device", default="cuda") | |
| ap.add_argument("--smoke-seq", default=None) | |
| ap.add_argument("--smoke-n", type=int, default=16) | |
| ap.add_argument("--smoke-out", default=None) | |
| ap.add_argument("--limit", type=int, default=0, help="test only: first N rows of each set") | |
| ap.add_argument("--test-maxnew", type=int, default=0, help="test only: force this token cap (to exercise the cap-retry path)") | |
| ap.add_argument("--test-pass", action="store_true") | |
| ap.add_argument("--gate-file", default="/path/to/TURKIC_OCR_DATA/outputs/r5/RULE/test_pass_started.txt") | |
| ap.add_argument("--not-before-utc", default="2026-11-24T12:00:00Z") | |
| args = ap.parse_args() | |
| # ---- TEST-PASS GATE (VLMA): before the adapter, the registry or any manifest is opened ---- | |
| _gate_open = bool(args.test_pass) and os.path.exists(args.gate_file) | |
| if not _gate_open: | |
| print("REFUSED: locked sets need --test-pass AND the gate file %s (test_pass=%s, exists=%s); nothing opened" % | |
| (args.gate_file, bool(args.test_pass), os.path.exists(args.gate_file)), flush=True) | |
| sys.exit(3) | |
| if os.path.realpath(args.evalsets or "") == os.path.realpath("/path/to/TURKIC_OCR_DATA/data/processed/r5/evalsets.json") and \ | |
| time.time() < datetime.strptime(args.not_before_utc, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp(): | |
| print("REFUSED: the real registry is not read before %s" % args.not_before_utc, flush=True) | |
| sys.exit(3) | |
| if not [s for s in args.sets.split(",") if s]: | |
| print("REFUSED: --sets must name the locked sets", flush=True) | |
| sys.exit(4) | |
| # SIGTERM / SIGINT (the runner's evaluation timeout): stop at the next batch boundary and label every unfinished set | |
| # "not evaluated (time)" (21 Nov; added by VLMC) | |
| import signal # noqa: E402 | |
| STOP = {"flag": False, "why": ""} | |
| def _stop(signum, frame): # noqa: ARG001 | |
| STOP["flag"] = True | |
| STOP["why"] = "signal %d" % signum | |
| signal.signal(signal.SIGTERM, _stop) | |
| signal.signal(signal.SIGINT, _stop) | |
| NOT_EVALUATED = "not evaluated (time)" | |
| dev = torch.device(args.device) | |
| use_cuda = dev.type == "cuda" | |
| deadline = datetime.strptime(args.deadline_utc, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp() | |
| reg = {} | |
| with open(args.registry, 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"))) | |
| reg[r["short"]] = r | |
| reg = reg[args.short] | |
| MAXNEW = {"word": 48, "line": 192} | |
| if args.test_maxnew: | |
| MAXNEW = {"word": args.test_maxnew, "line": args.test_maxnew} | |
| # prediction columns as VLMA's vlm_common.write_pred_tsv (audit item 3, ported by VLMC 2026-11-21); the maker-code | |
| # adapters return text only, so conf and conf_min stay empty and hit_cap / n_tokens come from re-tokenising the output | |
| CONF_DEF = ("conf and conf_min: empty (the maker-code adapters return text only, no token scores); n_tokens = " | |
| "number of tokens of the decoded output re-tokenised with the model's tokenizer (no special tokens); " | |
| "hit_cap = 1 if n_tokens >= max_new_tokens (estimate), else 0") | |
| def write_pred_tsv(path, rows, done, plain_ref, plain_output): | |
| """Shared prediction format: id, ref (N0), hyp (N0 of raw greedy output), conf, conf_min, hit_cap, n_tokens.""" | |
| def _c(x): | |
| return "" if x is None else str(x) | |
| with open(path, "w", encoding="utf-8") as f: | |
| f.write("id\tref\thyp\tconf\tconf_min\thit_cap\tn_tokens\n") | |
| for r in rows: | |
| if r["id"] in done: | |
| d = done[r["id"]] | |
| f.write(f"{r['id']}\t{plain_ref(r['text'])}\t{plain_output(d['raw'])}\t{_c(d.get('conf'))}\t" | |
| f"{_c(d.get('conf_min'))}\t{int(bool(d.get('hit_cap')))}\t{_c(d.get('n_new'))}\n") | |
| def utc(): | |
| return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | |
| def say(*a): | |
| print(f"[eval {args.arm}/{args.ckpt} {utc()}]", *a, flush=True) | |
| t_load = time.time() | |
| ad = importlib.import_module("adapters.ad_" + args.short).Adapter(args.base_dir, dev, "pure_bf16") | |
| exp_meta = {} | |
| reload_missing = None | |
| if args.state != "none": | |
| sd = torch.load(args.state, map_location="cpu", weights_only=True) | |
| missing, unexpected = ad.model.load_state_dict(sd, strict=False) | |
| reload_missing = list(missing)[:50] | |
| assert not unexpected, unexpected[:5] | |
| # a missing key is allowed only if it is a buffer (kept from the pinned base) or an alias of a tied parameter | |
| # whose other name was loaded | |
| bufs = {n for n, _ in ad.model.named_buffers(remove_duplicate=False)} | |
| alias = {} | |
| for n, p in ad.model.named_parameters(remove_duplicate=False): | |
| alias.setdefault(id(p), []).append(n) | |
| names_of = {n: alias[id(p)] for n, p in ad.model.named_parameters(remove_duplicate=False)} | |
| bad = [k for k in missing if k not in bufs and not any(a in sd for a in names_of.get(k, []))] | |
| assert not bad, ("missing weights", bad[:5]) | |
| print("state loaded; missing keys allowed (buffers kept from base or tied aliases):", list(missing)[:10], flush=True) | |
| del sd | |
| em = os.path.join(os.path.dirname(args.state), "r5_export.json") | |
| if os.path.exists(em): | |
| exp_meta = json.load(open(em)) | |
| ad.prepare_eval() | |
| load_seconds = time.time() - t_load | |
| def gen(imgs, max_new, temperature=None): | |
| out = ad.generate(imgs, max_new) if temperature is None else ad.generate(imgs, max_new, temperature=temperature) | |
| recs = [] | |
| for o in out: | |
| if isinstance(o, dict): | |
| recs.append(o) | |
| else: | |
| n = len(ad.tok(o, add_special_tokens=False).input_ids) if o else 0 | |
| recs.append({"raw": o, "n_new_retokenised": n, "hit_cap_estimate": n >= max_new, | |
| "n_new": n, "hit_cap": n >= max_new, "conf": None, "conf_min": None}) | |
| return recs | |
| def load_img(p): | |
| return Image.open(p).convert("RGB") | |
| if args.smoke_seq: | |
| rows = [] | |
| with open(args.smoke_seq, encoding="utf-8") as f: | |
| hdr = f.readline().rstrip("\n").split("\t") | |
| ix = {h: i for i, h in enumerate(hdr)} | |
| for line in f: | |
| p = line.rstrip("\n").split("\t") | |
| rows.append((p[ix["id"]], p[ix["image"]], p[ix["text"]])) | |
| if len(rows) >= args.smoke_n: | |
| break | |
| t0 = time.time() | |
| recs = [] | |
| for b in range(0, len(rows), args.batch): | |
| bb = rows[b:b + args.batch] | |
| recs += gen([load_img(r[1]) for r in bb], 48) | |
| t1 = time.time() | |
| recs1 = [] | |
| for r in rows: # the same rows one at a time: batched decoding (padding) must not change the output | |
| recs1 += gen([load_img(r[1])], 48) | |
| same = sum(1 for a, b in zip(recs, recs1) if a["raw"] == b["raw"]) | |
| res = {"rows": len(rows), "seconds": round(t1 - t0, 2), "load_seconds": round(load_seconds, 1), | |
| "batch_vs_batch1_identical": same, "batch_vs_batch1_rows": len(rows), "batch": args.batch, | |
| "score_train_rows_not_a_result": pp.score([r[2] for r in rows], [x["raw"] for x in recs]), | |
| "examples": [dict(x, id=r[0], ref=r[2], raw_batch1=y["raw"]) for r, x, y in zip(rows, recs, recs1)]} | |
| os.makedirs(os.path.dirname(args.smoke_out), exist_ok=True) | |
| json.dump(res, open(args.smoke_out, "w"), indent=1, ensure_ascii=False) | |
| say("smoke generation", json.dumps(res["examples"][:4], ensure_ascii=False)) | |
| sys.exit(0) | |
| reg_doc = json.load(open(args.evalsets, encoding="utf-8")) | |
| if isinstance(reg_doc, dict) and isinstance(reg_doc.get("sets"), list): | |
| entries = reg_doc["sets"] | |
| elif isinstance(reg_doc, dict) and isinstance(reg_doc.get("evalsets"), list): | |
| entries = reg_doc["evalsets"] | |
| elif isinstance(reg_doc, list): | |
| entries = reg_doc | |
| else: | |
| entries = [dict(v, name=v.get("name", k)) for k, v in reg_doc.items() if isinstance(v, dict)] | |
| want = [s for s in args.sets.split(",") if s] | |
| VAL = {"val", "validation"} | |
| todo, refused = [], [] | |
| for e in entries: | |
| name = e.get("name") | |
| if want and name not in want: | |
| continue | |
| if not (e.get("locked") is True or str(e.get("split", "")).lower() == "test"): | |
| refused.append({"name": name, "why": "not a locked set (validation goes through vlmb_eval_vlm.py)"}) | |
| continue | |
| if not e.get("manifest") or not os.path.exists(e["manifest"]): | |
| refused.append({"name": name, "why": "manifest missing: %s" % e.get("manifest")}) | |
| continue | |
| todo.append(e) | |
| def read_manifest(path): | |
| import csv | |
| import unicodedata | |
| out = [] | |
| with open(path, encoding="utf-8", newline="") as f: | |
| for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): | |
| r["text"] = unicodedata.normalize("NFC", r.get("text") or "") | |
| out.append(r) | |
| return out | |
| def is_v1(e): | |
| return e.get("name") in ("V1", "kohtd_screen_v1") or os.path.basename(e.get("manifest", "")) == "kohtd_screen_v1.tsv" | |
| # evaluation order (21 Nov, for slow decoders): V1 (the selection set) first, then curve_v1 if it is | |
| # listed, then VLMA's priority order of eval_vlm.py | |
| PRIORITY = ["V1", "curve_v1", "V1lm", "kohtd_val", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000", | |
| "synth_hand_val", "synth_typed_val", "synth_clutter_val", "print_real_val", "hkr_val", "chd_val", "school_val"] | |
| todo.sort(key=lambda e: (not is_v1(e), PRIORITY.index(e["name"]) if e.get("name") in PRIORITY else len(PRIORITY), | |
| e.get("name"))) | |
| out_dir = os.path.join(args.preds_root, args.arm, args.ckpt) | |
| os.makedirs(out_dir, exist_ok=True) | |
| meta_path = os.path.join(out_dir, "meta_testpass.json") # TEST-PASS: the validation meta.json is left as it is | |
| meta = json.load(open(meta_path)) if os.path.exists(meta_path) else {} | |
| meta.update({ | |
| "arm": args.arm, "short": args.short, "model_repo": reg["repo"], "base_revision": reg["revision"], | |
| "checkpoint": args.ckpt, "checkpoint_file": args.state, "samples_seen": exp_meta.get("samples_seen"), | |
| "learning_rate": exp_meta.get("lr"), "train_flag": exp_meta.get("flag"), | |
| "decoding": {"greedy": True, "num_beams": 1, "max_new_tokens": MAXNEW, "batch": args.batch, | |
| "how": "adapter generate (maker decode path)"}, | |
| "instruction": INSTR, "gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu", | |
| "transformers": transformers.__version__, "torch": torch.__version__, "load_seconds": round(load_seconds, 1), | |
| "postproc_sha256_file": "records/R5/VLMA/postproc.sha256", "refused_sets": refused, "adapter_notes": ad.NOTES, | |
| "attention": SDPA_NOTE, "reload_missing_keys": reload_missing, | |
| "tsv_columns": "id, ref (N0: NFC + whitespace collapse), hyp (N0 of the raw greedy output), conf, conf_min, hit_cap, n_tokens", | |
| "conf_definition": CONF_DEF, | |
| "memory_note": "gate G (clarification G6) uses peak_mem_reserved_batch1_GiB (torch.cuda.max_memory_reserved); peak_mem_batch1_GiB is max_memory_allocated; H100, not RTX 5090", | |
| }) | |
| meta.setdefault("sets", {}) | |
| t_all = time.time() | |
| def image_sizes(manifest): | |
| """width x height of every image of a manifest (headers only), cached per manifest path + mtime (VLMA's | |
| eval_vlm.py function; VLMB's own cache folder, written atomically).""" | |
| cdir = os.path.join(os.path.dirname(os.path.abspath(args.preds_root)), "vlmb", "image_sizes") | |
| os.makedirs(cdir, exist_ok=True) | |
| key = os.path.basename(manifest) + "_%d.json" % int(os.path.getmtime(manifest)) | |
| cp = os.path.join(cdir, key) | |
| if os.path.exists(cp): | |
| try: | |
| return json.load(open(cp)) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| out = {} | |
| for r in read_manifest(manifest): | |
| try: | |
| with Image.open(r["image"]) as im: | |
| out[r["id"]] = [im.width, im.height, r.get("unit", "word"), r["image"]] | |
| except Exception: # noqa: BLE001 | |
| pass | |
| tmp = cp + ".tmp%d" % os.getpid() | |
| json.dump(out, open(tmp, "w")) | |
| os.replace(tmp, cp) | |
| return out | |
| v1e = [e for e in todo if is_v1(e)] | |
| def gate_g_memory(): | |
| # Gate G (clarifications G6, H6; VLMA's eval_vlm.py block, ported by VLMC 2026-11-21 for audit item 3): peak memory | |
| # at batch 1 on the 3 largest validation inputs (pixels) of the sets of this call, then 32 V1 crops; measured first, | |
| # before any batch-16 work, after empty_cache and reset_peak_memory_stats | |
| cands = [] | |
| for e in todo: | |
| for rid, (w, h, unit, path) in image_sizes(e["manifest"]).items(): | |
| if unit in MAXNEW: | |
| cands.append((w * h, rid, e["name"], w, h, unit, path)) | |
| cands.sort(reverse=True) | |
| largest, seen_paths = [], set() | |
| for c in cands: # three DISTINCT images (the same image can sit in several sets) | |
| if c[6] not in seen_paths: | |
| seen_paths.add(c[6]) | |
| largest.append(c) | |
| if len(largest) == 3: | |
| break | |
| r32 = read_manifest(v1e[0]["manifest"])[:32] if v1e else [] | |
| torch.cuda.synchronize() | |
| torch.cuda.empty_cache() | |
| torch.cuda.reset_peak_memory_stats() | |
| t0 = time.time() | |
| for c in largest: | |
| gen([load_img(c[6])], MAXNEW[c[5]]) | |
| t_large = time.time() - t0 | |
| t0 = time.time() | |
| for r in r32: | |
| gen([load_img(r["image"])], MAXNEW[r.get("unit", "word")]) | |
| torch.cuda.synchronize() | |
| meta["peak_mem_batch1_GiB"] = round(torch.cuda.max_memory_allocated() / 2**30, 3) | |
| meta["peak_mem_reserved_batch1_GiB"] = round(torch.cuda.max_memory_reserved() / 2**30, 3) | |
| meta["latency_batch1_s_mean_32_V1"] = round((time.time() - t0) / max(len(r32), 1), 4) | |
| meta["latency_batch1_s_largest_inputs"] = round(t_large / max(len(largest), 1), 4) | |
| meta["peak_mem_largest_inputs"] = [{"id": c[1], "set": c[2], "width": c[3], "height": c[4], "unit": c[5]} for c in largest] | |
| meta["peak_mem_batch1_how"] = ("clarification H6: batch 1 on the 3 largest validation inputs (pixels) of the sets of this " | |
| "call, then 32 V1 crops; before any batch-16 pass, after empty_cache and " | |
| "reset_peak_memory_stats; gate G uses peak_mem_reserved_batch1_GiB (reader only; detector " | |
| "not added)") | |
| if False: # TEST-PASS: no gate-G memory measurement on test inputs (H6 uses validation inputs) | |
| # deviation from VLMA's code (VLMC): an error in this measurement (e.g. out of memory on the largest input) is | |
| # recorded in meta.json instead of stopping the validation predictions | |
| try: | |
| gate_g_memory() | |
| except Exception as ex: # noqa: BLE001 | |
| meta["peak_mem_batch1_error"] = repr(ex)[:500] | |
| say("gate-G memory measurement failed:", repr(ex)[:200]) | |
| if use_cuda: | |
| torch.cuda.empty_cache() | |
| json.dump(meta, open(meta_path, "w"), indent=1, ensure_ascii=False) | |
| # ---- cap-retry rule (records/R5/RULE/r5_posttrain_experiment.txt, last paragraph; VLMA's cap_retry() in eval_vlm.py, | |
| # ported by VLMC on 2026-11-21 on request) ---------------------------------------------------------- | |
| import inspect # noqa: E402 | |
| RETRY_T = 0.3 | |
| RETRY_SEED = 20261121 | |
| RETRY_RULE = ("cap-retry rule (records/R5/RULE/r5_posttrain_experiment.txt, adopted 2026-11-21): when greedy decoding stops at " | |
| "the token cap without an end-of-sequence token, decode once more at temperature 0.3 (sampling, top-k and " | |
| "top-p off, torch seed 20261121 set before each set's retries) and keep that output if it ends with a stop " | |
| "token; otherwise keep the greedy output. A separate post-processed figure; the decision figure stays greedy.") | |
| RETRY_OK = "temperature" in inspect.signature(ad.generate).parameters | |
| RETRY_SELECT = ("rows chosen by the greedy hit_cap, which for these maker-code adapters is the re-tokenised estimate " | |
| "(n_tokens of the decoded text >= cap)") | |
| meta["cap_retry"] = ({"rule": RETRY_RULE, "folder": args.ckpt + "_retry", "row_selection": RETRY_SELECT, | |
| "stop_test": "adapter-reported stop token where the adapter returns records (stop_source), else " | |
| "re-tokenised length < cap (estimate)"} | |
| if RETRY_OK else "retry not available (the adapter's generate has no sampling path)") | |
| def cap_retry(e, name, rows, done): | |
| """Write <ckpt>_retry/<set>.* : greedy predictions, except hit_cap rows re-decoded once at temperature 0.3 and kept | |
| if they end properly. Resumable; re-running on a finished checkpoint only adds the retries (catch-up).""" | |
| if not RETRY_OK: | |
| return | |
| rdir = os.path.join(args.preds_root, args.arm, args.ckpt + "_retry") | |
| os.makedirs(rdir, exist_ok=True) | |
| rpath = os.path.join(rdir, name + ".raw.jsonl") | |
| rdone = {} | |
| if os.path.exists(rpath): | |
| for line in open(rpath, encoding="utf-8"): | |
| try: | |
| d = json.loads(line) | |
| rdone[d["id"]] = d | |
| except Exception: # noqa: BLE001 | |
| pass | |
| need = [r for r in rows if done[r["id"]].get("hit_cap") and r["id"] not in rdone] | |
| torch.manual_seed(RETRY_SEED) | |
| with open(rpath, "a", encoding="utf-8") as fp: | |
| for u in sorted(set(r.get("unit", "word") for r in need)): | |
| ru = [r for r in need if r.get("unit", "word") == u] | |
| for b in range(0, len(ru), args.batch): | |
| if time.time() >= deadline or STOP["flag"]: | |
| break | |
| bb = ru[b:b + args.batch] | |
| try: | |
| recs = gen([load_img(r["image"]) for r in bb], MAXNEW[u], temperature=RETRY_T) | |
| except Exception as ex: # noqa: BLE001 | |
| say(f"retry batch failed {repr(ex)[:150]}; greedy output kept for these rows") | |
| recs = [{"raw": "", "hit_cap": True, "retry_error": repr(ex)[:200]} for _ in bb] | |
| for r, x in zip(bb, recs): | |
| kept = not x["hit_cap"] | |
| keep = x if kept else done[r["id"]] | |
| rec = {"id": r["id"], "raw": keep["raw"], "n_new": keep.get("n_new"), "hit_cap": keep.get("hit_cap"), | |
| "conf": keep.get("conf"), "conf_min": keep.get("conf_min"), "retried": True, | |
| "retry_kept": kept, "retry_raw": x["raw"], "greedy_raw": done[r["id"]]["raw"], | |
| "stop_source": x.get("stop_source", "re-tokenised length < cap (estimate)")} | |
| if "retry_error" in x: | |
| rec["retry_error"] = x["retry_error"] | |
| if "eos" in x: # reliability check of the re-tokenised estimate against the adapter's stop flag | |
| nt = len(ad.tok(x["raw"], add_special_tokens=False).input_ids) if x["raw"] else 0 | |
| rec["retry_hit_cap_retokenised"] = nt >= MAXNEW[u] | |
| rec["retry_hit_cap_adapter"] = bool(x["hit_cap"]) | |
| fp.write(json.dumps(rec, ensure_ascii=False) + "\n") | |
| rdone[r["id"]] = rec | |
| fp.flush() | |
| final = {r["id"]: rdone.get(r["id"], done[r["id"]]) for r in rows} | |
| complete_r = all((not done[r["id"]].get("hit_cap")) or r["id"] in rdone for r in rows) | |
| _dst, _stale = ((name + ".tsv", name + ".partial.tsv") if complete_r else (name + ".partial.tsv", name + ".tsv")) # TEST-PASS J4 | |
| write_pred_tsv(os.path.join(rdir, _dst), rows, final, pp.plain_ref, pp.plain_output) | |
| if os.path.exists(os.path.join(rdir, _stale)): | |
| os.remove(os.path.join(rdir, _stale)) | |
| sc = {"plain": {"cer": None, "wer": None}, "pp": {"cer": None, "wer": None}} # TEST-PASS: the scorer computes figures | |
| n_ret = sum(1 for r in rows if r["id"] in rdone) | |
| n_kept = sum(1 for r in rows if rdone.get(r["id"], {}).get("retry_kept")) | |
| both = [rdone[r["id"]] for r in rows if "retry_hit_cap_adapter" in rdone.get(r["id"], {})] | |
| agree = {"compared": len(both), | |
| "agree": sum(1 for x in both if x["retry_hit_cap_adapter"] == x["retry_hit_cap_retokenised"]), | |
| "adapter_cap_estimate_not": sum(1 for x in both if x["retry_hit_cap_adapter"] and not x["retry_hit_cap_retokenised"])} | |
| n_err = sum(1 for r in rows if "retry_error" in rdone.get(r["id"], {})) | |
| rstatus = ("retry failed on %d of %d retried rows (greedy text kept for them; not a 'rule did not help' result)" | |
| % (n_err, n_ret)) if n_err else "ok" | |
| sc.update({"set": name, "complete": complete_r, "rows": len(rows), "retried": n_ret, "retry_kept": n_kept, | |
| "retry_errors": n_err, "retry_status": rstatus, | |
| "rule": RETRY_RULE, "row_selection": RETRY_SELECT, "estimate_vs_adapter_stop_on_retries": agree}) | |
| json.dump(sc, open(os.path.join(rdir, name + ".score.json"), "w"), indent=1) | |
| mp = os.path.join(rdir, "meta_testpass.json") # TEST-PASS | |
| rm = json.load(open(mp)) if os.path.exists(mp) else {} | |
| rm.update({"arm": args.arm, "checkpoint": args.ckpt + "_retry", "greedy_checkpoint_folder": args.ckpt, | |
| "rule": RETRY_RULE, "row_selection": RETRY_SELECT, "short": args.short, | |
| "samples_seen": meta.get("samples_seen"), "learning_rate": meta.get("learning_rate"), | |
| "model_repo": meta.get("model_repo"), "base_revision": meta.get("base_revision"), | |
| "peak_mem_reserved_batch1_GiB": meta.get("peak_mem_reserved_batch1_GiB"), | |
| "tsv_columns": meta.get("tsv_columns"), "conf_definition": CONF_DEF + " (retried rows: sampled path at T 0.3)", | |
| "updated_utc": utc()}) | |
| rm.setdefault("sets", {})[name] = {"complete": complete_r, "rows": len(rows), "retried": n_ret, "retry_kept": n_kept, | |
| "retry_errors": n_err, "retry_status": rstatus, | |
| "estimate_vs_adapter_stop_on_retries": agree, | |
| "plain_cer": sc["plain"]["cer"], "pp_cer": sc["pp"]["cer"], | |
| "plain_wer": sc["plain"]["wer"], "pp_wer": sc["pp"]["wer"]} | |
| json.dump(rm, open(mp, "w"), indent=1, ensure_ascii=False) | |
| say(f"{name}: cap-retry {n_ret} rows re-decoded, {n_kept} kept, {n_err} errors; plain CER {sc['plain']['cer']}") | |
| def split_not_evaluated(): | |
| """Rule of 22 Nov: an evaluation stopped by its time limit, with V1 complete, counts as DONE; the unfinished | |
| sets keep the label 'not evaluated (time)'. With V1 complete they are listed under meta['not_evaluated_sets'] (with | |
| the label and no CER), so meta['sets'] holds the evaluated sets only and the runner's eval_done() reads the task | |
| as done. Without a complete V1 they stay in meta['sets'] (complete False) and the task stays not done.""" | |
| ne = meta.setdefault("not_evaluated_sets", {}) | |
| v1 = [e["name"] for e in todo if is_v1(e)] | |
| if v1 and all(meta["sets"].get(n, {}).get("complete") is True for n in v1): | |
| for k in [k for k, v in meta["sets"].items() if v.get("status") == NOT_EVALUATED]: | |
| ne[k] = meta["sets"].pop(k) | |
| else: | |
| for k in list(ne): | |
| meta["sets"][k] = ne.pop(k) | |
| meta["done_rule"] = ("rule of 2026-11-22: evaluation stopped by its time limit with V1 complete = done; sets " | |
| "not finished are in not_evaluated_sets with status '%s' and no CER figure" % NOT_EVALUATED) | |
| def mark_not_evaluated(e, rows_n=None, done_n=0): | |
| """An unfinished set gets a labelled entry and no CER figure; a later call that completes it overwrites this.""" | |
| name = e["name"] | |
| if meta["sets"].get(name, {}).get("complete") is True: | |
| return | |
| if rows_n is None: | |
| try: | |
| rows_n = len(read_manifest(e["manifest"])) | |
| except Exception: # noqa: BLE001 | |
| rows_n = None | |
| meta["sets"][name] = {"status": NOT_EVALUATED, "complete": False, "rows": rows_n, "done": done_n, | |
| "plain_cer": None, "pp_cer": None, "plain_wer": None, "pp_wer": None, | |
| "why": STOP["why"] or ("deadline %s" % args.deadline_utc), "utc": utc()} | |
| processed = set() | |
| for e in todo: | |
| name = e["name"] | |
| if time.time() >= deadline or STOP["flag"]: | |
| break | |
| processed.add(name) | |
| rows = read_manifest(e["manifest"]) | |
| bad = [r for r in rows if str(r.get("split", "")).lower() != str(e.get("split", "")).lower()] # TEST-PASS | |
| if args.limit: | |
| rows = rows[: args.limit] | |
| if bad: | |
| refused.append({"name": name, "why": "%d manifest rows with split != the registry split" % len(bad)}) | |
| say(f"REFUSED {name}: {len(bad)} rows not val") | |
| continue | |
| units = sorted(set(r.get("unit", "word") for r in rows)) | |
| if any(u not in MAXNEW for u in units): | |
| refused.append({"name": name, "why": "unit %s has no fixed token cap here (needs a manual decision)" % units}) | |
| say(f"SKIPPED {name}: units {units}") | |
| continue | |
| raw_path = os.path.join(out_dir, name + ".raw.jsonl") | |
| done = {} | |
| if os.path.exists(raw_path): | |
| for line in open(raw_path, encoding="utf-8"): | |
| try: | |
| d = json.loads(line) | |
| done[d["id"]] = d | |
| except Exception: # noqa: BLE001 | |
| pass | |
| pend = [r for r in rows if r["id"] not in done] | |
| pend.sort(key=lambda r: r.get("unit", "word")) | |
| say(f"{name}: {len(rows)} rows, {len(done)} done, units {units}") | |
| timing = [] | |
| with open(raw_path, "a", encoding="utf-8") as fp: | |
| for b in range(0, len(pend), args.batch): | |
| if time.time() >= deadline or STOP["flag"]: | |
| say("deadline reached or stop signal; stopping", STOP["why"]) | |
| break | |
| bb = pend[b:b + args.batch] | |
| groups = {} | |
| for r in bb: | |
| groups.setdefault(r.get("unit", "word"), []).append(r) | |
| for u, same in groups.items(): | |
| t0 = time.time() | |
| try: | |
| recs = gen([load_img(r["image"]) for r in same], MAXNEW[u]) | |
| except Exception as ex: # noqa: BLE001 | |
| say(f"batch failed {repr(ex)[:150]}; one at a time") | |
| recs = [] | |
| for r in same: | |
| try: | |
| recs += gen([load_img(r["image"])], MAXNEW[u]) | |
| except Exception as ex2: # noqa: BLE001 | |
| recs.append({"raw": "", "n_new": 0, "hit_cap": False, "error": repr(ex2)[:200]}) | |
| if use_cuda: | |
| torch.cuda.synchronize() | |
| timing.append((len(same), time.time() - t0)) | |
| for r, x in zip(same, recs): | |
| x["id"] = r["id"] | |
| fp.write(json.dumps(x, ensure_ascii=False) + "\n") | |
| done[r["id"]] = x | |
| fp.flush() | |
| complete = all(r["id"] in done for r in rows) | |
| if not complete: | |
| # unfinished (time): predictions so far go to <set>.partial.tsv, no <set>.tsv, no CER figure | |
| write_pred_tsv(os.path.join(out_dir, name + ".partial.tsv"), rows, done, pp.plain_ref, pp.plain_output) | |
| for stale in (name + ".tsv", name + ".score.json"): | |
| if os.path.exists(os.path.join(out_dir, stale)): | |
| os.remove(os.path.join(out_dir, stale)) | |
| mark_not_evaluated(e, len(rows), sum(1 for r in rows if r["id"] in done)) | |
| say(f"{name}: {NOT_EVALUATED} ({sum(1 for r in rows if r['id'] in done)} of {len(rows)} rows read)") | |
| meta["refused_sets"] = refused | |
| meta["wall_seconds_this_call"] = round(time.time() - t_all, 1) | |
| meta["updated_utc"] = utc() | |
| json.dump(meta, open(meta_path, "w"), indent=1, ensure_ascii=False) | |
| break | |
| if os.path.exists(os.path.join(out_dir, name + ".partial.tsv")): | |
| os.remove(os.path.join(out_dir, name + ".partial.tsv")) | |
| refs = [r["text"] for r in rows if r["id"] in done] | |
| raws = [done[r["id"]]["raw"] for r in rows if r["id"] in done] | |
| write_pred_tsv(os.path.join(out_dir, name + ".tsv"), rows, done, pp.plain_ref, pp.plain_output) | |
| sc = {"plain": {"cer": None, "wer": None}, "pp": {"cer": None, "wer": None}} # TEST-PASS: the scorer computes figures | |
| n_changed = sum(1 for x in raws if pp.pp_output(x) != pp.plain_output(x)) | |
| hcs = sum(bool(done[r["id"]].get("hit_cap", done[r["id"]].get("hit_cap_estimate"))) for r in rows | |
| if r["id"] in done) / max(len(refs), 1) | |
| sc.update({"set": name, "manifest": e["manifest"], "complete": complete, "rows": len(rows), "done": len(refs), | |
| "postproc_changed_outputs": n_changed, "hit_cap_share": hcs, "hit_cap_share_estimate": hcs, | |
| "errors": sum(1 for r in rows if r["id"] in done and "error" in done[r["id"]])}) | |
| json.dump(sc, open(os.path.join(out_dir, name + ".score.json"), "w"), indent=1) | |
| meta.setdefault("not_evaluated_sets", {}).pop(name, None) | |
| meta["sets"][name] = {"status": "evaluated", "complete": complete, "rows": len(rows), "done": len(refs), "plain_cer": sc["plain"]["cer"], | |
| "pp_cer": sc["pp"]["cer"], "plain_wer": sc["plain"]["wer"], "pp_wer": sc["pp"]["wer"], | |
| "postproc_changed_outputs": n_changed, "hit_cap_share": hcs} | |
| if is_v1(e) and len(timing) > 1: | |
| n = sum(t[0] for t in timing[1:]) | |
| s = sum(t[1] for t in timing[1:]) | |
| if args.batch == 16 and n: | |
| meta["images_per_second_batch16_V1"] = round(n / s, 3) | |
| meta["images_per_second_note"] = "H100, not RTX 5090; image loading + preprocessing + generate, first batch excluded" | |
| say(f"{name}: plain CER {sc['plain']['cer']} pp CER {sc['pp']['cer']} complete {complete}") | |
| meta["refused_sets"] = refused | |
| meta["wall_seconds_this_call"] = round(time.time() - t_all, 1) | |
| meta["updated_utc"] = utc() | |
| json.dump(meta, open(meta_path, "w"), indent=1, ensure_ascii=False) | |
| if complete and time.time() < deadline and not STOP["flag"]: | |
| try: | |
| cap_retry(e, name, rows, done) | |
| except Exception as ex: # noqa: BLE001 | |
| say(f"{name}: cap-retry failed {repr(ex)[:200]} (greedy figures unaffected)") | |
| if time.time() >= deadline or STOP["flag"]: | |
| break | |
| for e in todo: # sets this call never reached (deadline / stop): labelled, no figure | |
| if e["name"] not in processed and e["name"] not in meta.get("not_evaluated_sets", {}): | |
| mark_not_evaluated(e) | |
| split_not_evaluated() | |
| meta["evaluation_order"] = [e["name"] for e in todo] | |
| meta["evaluation_order_note"] = ("V1 first, then curve_v1 if listed, then VLMA's priority list; a set not finished by the " | |
| "deadline or the runner's evaluation timeout is recorded as '%s' with no CER figure; " | |
| "its partial predictions are in <set>.partial.tsv" % NOT_EVALUATED) | |
| json.dump(meta, open(meta_path, "w"), indent=1, ensure_ascii=False) | |
| say("done", json.dumps(meta.get("sets", {}))) | |