Download scripts/r5_onemodel/om_eval_pages.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 9.57 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_onemodel/om_eval_pages.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_onemodel/om_eval_pages.py
-
curl -L -o om_eval_pages.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_onemodel/om_eval_pages.py
9.57 kB
| """ONEMODEL pilot (design ONEMODEL-pilot-1): whole-page reading in spotting mode of one checkpoint on validation page sets. | |
| Sets: gen_val (300 generated val pages), school_val (150 School Notebooks val pages) from the build records (images | |
| pre-resized to <= 1,605,632 px); clutter_spot (the 500 synth_clutter_val images, resized with the same page rule; descriptive). | |
| Prompt 'Spotting:', page processor size, greedy, one beam, no repetition penalty, stop on the generation stop ids (+ the | |
| trained answer end), left padding, batch --batch, max_new_tokens from build_report.json (frozen before training). | |
| Writes one JSON line per page as soon as its batch is read (resumable): <out-root>/<name>/<set>.jsonl with the raw output | |
| (special tokens kept), n_new, hit_cap, n_visual, seconds; then <set>.done.json. Exit 99 when --max-seconds is reached. | |
| On CUDA, also seconds per page at batch 1 and peak reserved memory at batch 1 on 4 pages per set (before batched work). | |
| usage: om_eval_pages.py --model-dir DIR --name NAME --sets gen_val,school_val[,clutter_spot] [--device cuda] [--max-seconds S] | |
| """ | |
| import argparse | |
| import csv | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from datetime import datetime, timezone | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| import om_common as C # noqa: E402 | |
| import om_text as T # noqa: E402 | |
| import torch # noqa: E402 | |
| import transformers # noqa: E402 | |
| from PIL import Image # noqa: E402 | |
| vc = C.vc | |
| csv.field_size_limit(10 ** 9) | |
| CLUTTER = C.DATA + "/data/processed/r5/frozen_eval_v1/synth_clutter_val.tsv" | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--model-dir", required=True) | |
| ap.add_argument("--name", required=True) | |
| ap.add_argument("--sets", default="gen_val,school_val") | |
| ap.add_argument("--data-root", default=C.DATA + "/data/processed/r6_onemodel") | |
| ap.add_argument("--out-root", default=C.DATA + "/outputs/r6_onemodel/page_preds") | |
| ap.add_argument("--batch", type=int, default=8) | |
| ap.add_argument("--max-new", type=int, default=0, help="default: build_report.json max_new_tokens.value") | |
| ap.add_argument("--device", default="cuda") | |
| ap.add_argument("--threads", type=int, default=0) | |
| ap.add_argument("--max-seconds", type=float, default=0.0) | |
| ap.add_argument("--limit", type=int, default=0, help="smoke: first N pages of each set") | |
| ap.add_argument("--ids", default="", help="smoke: only these page ids (comma list)") | |
| ap.add_argument("--batch1-probe", type=int, default=4) | |
| a = ap.parse_args() | |
| T0 = time.time() | |
| dev = a.device | |
| if a.threads: | |
| torch.set_num_threads(a.threads) | |
| def utc(): | |
| return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | |
| def say(*x): | |
| print("[om_eval %s %s]" % (a.name, utc()), *x, flush=True) | |
| rep = json.load(open(os.path.join(a.data_root, "build_report.json"), encoding="utf-8")) | |
| max_new = a.max_new or int(rep["max_new_tokens"]["value"]) | |
| out_dir = os.path.join(a.out_root, a.name) | |
| os.makedirs(out_dir, exist_ok=True) | |
| def load_set(name): | |
| if name in ("gen_val", "school_val"): | |
| p = os.path.join(a.data_root, "records", name + ".jsonl") | |
| T.guard_not_test(p) | |
| rows = [] | |
| with open(p, encoding="utf-8") as f: | |
| for line in f: | |
| r = json.loads(line) | |
| assert r["split"] == "val", r["id"] | |
| rows.append({"id": r["id"], "image": r["image"], "resize": False}) | |
| return rows | |
| if name == "clutter_spot": | |
| T.guard_not_test(CLUTTER) | |
| with open(CLUTTER, encoding="utf-8", newline="") as f: | |
| rows = [r for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)] | |
| assert all(r["split"] == "val" for r in rows) | |
| return [{"id": r["id"], "image": r["image"], "resize": True} for r in rows] | |
| raise SystemExit("unknown set " + name) | |
| def load_img(r): | |
| im = Image.open(r["image"]).convert("RGB") | |
| if r["resize"]: | |
| w, h = T.spot_size(im.size[0], im.size[1]) | |
| im = im.resize((w, h), Image.LANCZOS) | |
| else: | |
| w, h = T.fit_size(im.size[0], im.size[1]) | |
| assert (w, h) == im.size, "record image %s is not at the page size rule" % r["image"] | |
| return im | |
| t_load = time.time() | |
| proc, tok, model = C.load(a.model_dir, info=False) | |
| tok.padding_side = "left" | |
| model = model.to(dev).eval() | |
| exp = {} | |
| if os.path.exists(os.path.join(a.model_dir, "r5_export.json")): | |
| exp = json.load(open(os.path.join(a.model_dir, "r5_export.json"))) | |
| tmpl_kw = exp.get("chat_template_kwargs", vc.template_kwargs(proc, tok)) | |
| gc, stops, stop_set = vc.gen_setup(model, tok, exp.get("answer_suffix_ids")) | |
| meta = {"design": T.DESIGN_ID, "name": a.name, "model_dir": os.path.realpath(a.model_dir), "export_meta": exp, | |
| "prompt": T.SPOT_PROMPT, "page_processor_kwargs": C.PAGE_PROC_KW, "max_new_tokens": max_new, "batch": a.batch, | |
| "decoding": {"greedy": True, "num_beams": 1, "repetition_penalty": 1.0, "stop_ids": stops}, | |
| "device": dev, "gpu": torch.cuda.get_device_name(0) if dev == "cuda" else "cpu", "transformers": transformers.__version__, | |
| "torch": torch.__version__, "load_seconds": round(time.time() - t_load, 1), "started_utc": utc()} | |
| sets = [s for s in a.sets.split(",") if s] | |
| want_ids = set(x for x in a.ids.split(",") if x) | |
| if (dev == "cuda" and a.batch1_probe and not os.path.exists(os.path.join(out_dir, "batch1_probe.json")) | |
| and not (a.max_seconds and a.max_seconds < 1800)): # the probe is skipped when less than 30 min of budget is left | |
| probe = [] | |
| torch.cuda.synchronize() | |
| torch.cuda.empty_cache() | |
| torch.cuda.reset_peak_memory_stats() | |
| for s in sets: | |
| if s == "clutter_spot": | |
| continue | |
| for r in load_set(s)[:a.batch1_probe]: | |
| im = load_img(r) | |
| t1 = time.time() | |
| x = C.generate_pages(model, proc, tok, [im], max_new, tmpl_kw, gc, stop_set, dev)[0] | |
| torch.cuda.synchronize() | |
| probe.append({"set": s, "id": r["id"], "seconds": round(time.time() - t1, 3), "n_new": x["n_new"], "hit_cap": x["hit_cap"]}) | |
| json.dump({"pages": probe, "peak_mem_reserved_batch1_GiB": round(torch.cuda.max_memory_reserved() / 2 ** 30, 3), | |
| "peak_mem_allocated_batch1_GiB": round(torch.cuda.max_memory_allocated() / 2 ** 30, 3), "utc": utc()}, | |
| open(os.path.join(out_dir, "batch1_probe.json"), "w"), indent=1) | |
| say("batch-1 probe done", json.dumps(probe)[:300]) | |
| status = 0 | |
| for s in sets: | |
| rows = load_set(s) | |
| if want_ids: | |
| rows = [r for r in rows if r["id"] in want_ids] | |
| if a.limit: | |
| rows = rows[:a.limit] | |
| path = os.path.join(out_dir, s + ".jsonl") | |
| done = set() | |
| if os.path.exists(path): | |
| with open(path, encoding="utf-8") as f: | |
| for line in f: | |
| try: | |
| done.add(json.loads(line)["id"]) | |
| except ValueError: | |
| pass | |
| pend = [r for r in rows if r["id"] not in done] | |
| say("%s: %d pages, %d done, max_new %d" % (s, len(rows), len(done), max_new)) | |
| if dev == "cuda": | |
| torch.cuda.reset_peak_memory_stats() | |
| with open(path, "a", encoding="utf-8") as fo: | |
| for b in range(0, len(pend), a.batch): | |
| if a.max_seconds and time.time() - T0 > a.max_seconds: | |
| status = 99 | |
| break | |
| bb = pend[b:b + a.batch] | |
| imgs = [load_img(r) for r in bb] | |
| t1 = time.time() | |
| try: | |
| recs = C.generate_pages(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev) | |
| except Exception as ex: # noqa: BLE001 (as eval_vlm.py: retry one image at a time, record what still fails) | |
| say("batch failed %s; one at a time" % repr(ex)[:150]) | |
| recs = [] | |
| for im in imgs: | |
| try: | |
| recs += C.generate_pages(model, proc, tok, [im], max_new, tmpl_kw, gc, stop_set, dev) | |
| except Exception as ex2: # noqa: BLE001 | |
| recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_visual": None, "error": repr(ex2)[:200]}) | |
| dt = time.time() - t1 | |
| for r, im, x in zip(bb, imgs, recs): | |
| x.update({"id": r["id"], "set": s, "img_w": im.size[0], "img_h": im.size[1], "batch_seconds": round(dt, 2), | |
| "batch_size": len(bb), "n_instances": len(T.parse_output(x["raw"]))}) | |
| fo.write(json.dumps(x, ensure_ascii=False) + "\n") | |
| fo.flush() | |
| say("%s %d/%d batch %.1fs max n_new %d" % (s, b + len(bb), len(pend), dt, max(x["n_new"] for x in recs))) | |
| if status == 99: | |
| say("time budget reached; exit 99") | |
| break | |
| ids_written = set() | |
| with open(path, encoding="utf-8") as f: | |
| for line in f: | |
| try: | |
| ids_written.add(json.loads(line)["id"]) | |
| except (ValueError, KeyError): | |
| pass # a line torn by a hard kill: that page is simply read again on resume | |
| n_done = len(ids_written & {r["id"] for r in rows}) | |
| info = {"set": s, "pages": len(rows), "written": n_done, "complete": n_done >= len(rows), "utc": utc()} | |
| if dev == "cuda": | |
| info["peak_mem_reserved_GiB_batch"] = round(torch.cuda.max_memory_reserved() / 2 ** 30, 3) | |
| json.dump(info, open(os.path.join(out_dir, s + ".done.json"), "w"), indent=1) | |
| meta["finished_utc"] = utc() | |
| meta["status"] = status | |
| json.dump(meta, open(os.path.join(out_dir, "meta_%s_%s.json" % (os.environ.get("SLURM_JOB_ID") or "local", "+".join(sets))), "w"), | |
| indent=1, ensure_ascii=False) | |
| sys.exit(status) | |