turkic-ocr-code / scripts /j2 /collect.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
8.51 kB
"""Turn finished (or partly finished) J2 outputs into results.tsv. Run on the cluster (the per-crop files hold labels and stay there).
usage: collect.py OUT_ROOT SCREEN_SET_TSV SCORELIB_PY RESULTS_TSV [model ...]
OUT_ROOT = DATA/outputs/j11_stage1_kohtd (model folders s1/ s2/ s3/ with preds.jsonl, timing.jsonl, meta.json).
Robust to a job killed by its time limit: a half-written last line of preds.jsonl or timing.jsonl is skipped and counted
(bad_lines); if meta.json was never written the row is filled from timing.jsonl, the screen set and loadtest/<model>.json.
Every speed and memory column carries the suffix _H100_not_5090: all figures come from one H100, not from an RTX 5090.
A row is complete when crops_done == crops_in_list; the column complete says so.
"""
import importlib.util
import json
import os
import sys
out_root, screen_set, scorelib_py, results_tsv = sys.argv[1:5]
only = set(sys.argv[5:])
assert "screen_set_v1.tsv" in screen_set
spec = importlib.util.spec_from_file_location("scorelib", scorelib_py)
sl = importlib.util.module_from_spec(spec)
spec.loader.exec_module(sl)
labels = {}
with open(screen_set, encoding="utf-8", newline="") as f:
f.readline()
for line in f:
c, form, lab = line.rstrip("\n").split("\t")
labels[c] = lab
prompts_path = os.path.join(os.path.dirname(os.path.abspath(scorelib_py)), "prompts.json")
prompts = json.load(open(prompts_path, encoding="utf-8")) if os.path.exists(prompts_path) else {}
def prompt_source(model):
note = (prompts.get(model) or {}).get("note", "")
if not note:
return "unknown"
if note.startswith("NOT FROM THE CARD"):
return "J2 departure (not from the card)"
if "closest documented" in note or "nearest" in note:
return "nearest documented (page prompt)"
return "card"
def read_jsonl(path):
recs, bad = [], 0
if os.path.exists(path):
for line in open(path, encoding="utf-8"):
if not line.strip():
continue
try:
recs.append(json.loads(line))
except Exception: # noqa: BLE001 (half-written line of a killed job)
bad += 1
return recs, bad
COLS = ["model", "scale", "complete", "prompt_source", "version_revision", "params_unique", "gpu", "crops_done", "crops_in_list",
"cer_pooled", "cer_mean", "cer_mean_cap1", "exact_match", "hr2_ins_per_ref_char", "hr3_share_refs_ge5", "hr4_loop_share",
"empty_share", "other_script_share", "ref_other_script_share", "cer_pooled_casefold", "exact_casefold", "hit_cap_share",
"mean_image_tokens", "crops_per_s_H100_not_5090", "crops_per_s_excl_first_batch_H100_not_5090",
"crops_per_s_median_full_batch_H100_not_5090", "new_tokens_per_s_H100_not_5090", "disk_read_s_per_crop",
"peak_gpu_mem_GiB_H100_not_5090", "batch_size", "job_ids", "errors", "bad_lines", "best_of_scales_pooled_cer", "scales_finished"]
rows = []
by_model = {}
for model in sorted(os.listdir(out_root)):
mdir = os.path.join(out_root, model)
if only and model not in only:
continue
if not os.path.isdir(os.path.join(mdir, "s1")) or model in ("eligibility", "loadtest", "keyaudit"):
continue
lt_path = os.path.join(out_root, "loadtest", model + ".json")
lt = json.load(open(lt_path)) if os.path.exists(lt_path) else {}
for scale in (1, 2, 3):
d = os.path.join(mdir, f"s{scale}")
if not os.path.exists(os.path.join(d, "preds.jsonl")):
continue
meta = json.load(open(os.path.join(d, "meta.json"))) if os.path.exists(os.path.join(d, "meta.json")) else {}
pred_recs, bad1 = read_jsonl(os.path.join(d, "preds.jsonl"))
tim, bad2 = read_jsonl(os.path.join(d, "timing.jsonl"))
preds = {}
for r in pred_recs: # keep the last record per crop
if r.get("crop_file") in labels:
preds[r["crop_file"]] = r
scored, det = [], []
for c, r in preds.items():
s = sl.score_crop(labels[c], r["raw"])
scored.append(s)
det.append((c, s, r))
agg = sl.aggregate(scored)
batch_size = meta.get("batch_size") or (max((t["n"] for t in tim), default=None))
job_ids = meta.get("job_ids") or sorted({t["job_id"] for t in tim if t.get("job_id")})
tot_n = sum(t["n"] for t in tim)
tot_t = sum(t["t_pre"] + t["t_gen"] for t in tim)
tim2 = tim[1:]
tot_n2 = sum(t["n"] for t in tim2)
tot_t2 = sum(t["t_pre"] + t["t_gen"] for t in tim2)
gen_t = sum(t["t_gen"] for t in tim)
full = sorted(t["n"] / (t["t_pre"] + t["t_gen"]) for t in tim if t["n"] == batch_size and (t["t_pre"] + t["t_gen"]) > 0)
median_full = full[len(full) // 2] if full else None # steady speed: no warm-up batch, no odd last batch
n_list = meta.get("crops_in_list") or len(labels)
row = {
"model": model, "scale": scale, "complete": "yes" if len(preds) == n_list else "no (partial)",
"prompt_source": prompt_source(model),
"version_revision": meta.get("repo_revision") or lt.get("revision"),
"params_unique": meta.get("params_unique") or lt.get("model_params_unique"),
"gpu": meta.get("gpu") or "unknown (no meta.json: run was cut off)", "crops_done": len(preds), "crops_in_list": n_list,
"cer_pooled": agg.get("cer_pooled"), "cer_mean": agg.get("cer_mean"), "cer_mean_cap1": agg.get("cer_mean_cap1"),
"exact_match": agg.get("exact"), "hr2_ins_per_ref_char": agg.get("hr2_ins_per_ref_char"),
"hr3_share_refs_ge5": agg.get("hr3_share_refs_ge5"), "hr4_loop_share": agg.get("hr4_loop_share"),
"empty_share": agg.get("empty_share"), "other_script_share": agg.get("other_script_share"),
"ref_other_script_share": agg.get("ref_other_script_share"), "cer_pooled_casefold": agg.get("cer_pooled_casefold"),
"exact_casefold": agg.get("exact_casefold"),
"hit_cap_share": sum(1 for r in preds.values() if r.get("hit_cap")) / max(1, len(preds)),
"mean_image_tokens": (sum(r["n_img_tokens"] for r in preds.values() if r.get("n_img_tokens", -1) >= 0) /
max(1, sum(1 for r in preds.values() if r.get("n_img_tokens", -1) >= 0))),
"crops_per_s_H100_not_5090": (tot_n / tot_t) if tot_t else None,
"crops_per_s_excl_first_batch_H100_not_5090": (tot_n2 / tot_t2) if tot_t2 else None,
"crops_per_s_median_full_batch_H100_not_5090": median_full,
"new_tokens_per_s_H100_not_5090": (sum(t["new_tokens"] for t in tim) / gen_t) if gen_t else None,
"disk_read_s_per_crop": (sum(t.get("t_img", 0) for t in tim) / tot_n) if tot_n else None,
"peak_gpu_mem_GiB_H100_not_5090": (meta.get("peak_gpu_mem_allocated_bytes", 0) / 2 ** 30) if meta.get("peak_gpu_mem_allocated_bytes") else None,
"batch_size": batch_size, "job_ids": ",".join(job_ids), "errors": meta.get("errors"), "bad_lines": bad1 + bad2,
}
rows.append(row)
by_model.setdefault(model, {})[scale] = row
with open(os.path.join(d, "scored.tsv"), "w", encoding="utf-8") as f: # stays on the cluster (holds labels)
f.write("crop_file\tref\tout\tdist\tcer\texact\tloop\thr3\tempty\tn_new\thit_cap\tn_img_tokens\n")
for c, s, r in det:
f.write("\t".join(str(x) for x in [c, s["ref"], s["hyp"], s["dist"], round(s["cer"], 4), int(s["exact"]), int(s["loop"]),
int(s["hr3"]), int(s["empty"]), r["n_new"], int(r["hit_cap"]), r["n_img_tokens"]]) + "\n")
for model, sc in by_model.items():
full_rows = [r for r in sc.values() if r["complete"] == "yes"]
best = min((r["cer_pooled"] for r in full_rows), default=None)
for r in sc.values():
r["best_of_scales_pooled_cer"] = best # minimum over the finished scales of this model
r["scales_finished"] = ",".join(str(s) for s, x in sorted(sc.items()) if x in full_rows)
def fmt(v):
if v is None:
return ""
if isinstance(v, float):
return f"{v:.4f}"
return str(v)
with open(results_tsv, "w", encoding="utf-8") as f:
f.write("\t".join(COLS) + "\n")
for r in rows:
f.write("\t".join(fmt(r.get(c)) for c in COLS) + "\n")
print("rows", len(rows), "complete", sum(1 for r in rows if r["complete"] == "yes"), "->", results_tsv)