File size: 15,389 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""R5 VLMA test-pass mode (test-pass plan, Part B): predictions of one VLMA checkpoint on LOCKED sets.

A NEW script; eval_vlm.py, vlm_common.py, postproc.py and every file the leader jobs call stay byte-identical (this script
only imports vlm_common and postproc). Decoding is exactly that of validation (eval_vlm.py): the model's own processor
and chat template with the one instruction, greedy, one beam, no repetition penalty, stop on the generation-config end
ids + tokenizer eos + the trained answer-end token, max_new_tokens 48 (word) / 192 (line), batch 16, minimum-patch-grid
padding, and the cap-retry folder <ckpt>_retry (temperature 0.3, seed 20261121 per set, kept if it ends properly).

GATE (as score.py): a set is LOCKED when the registry says locked true or split test. This script reads ONLY locked
sets, and only when BOTH --test-pass is given AND the gate file exists (default DATA/outputs/r5/RULE/test_pass_started.txt;
--gate-file exists for the CPU test only). Without both it exits with code 3 before loading the model and before opening
any manifest or image. With the real registry it also refuses before --not-before-utc (default 2026-11-24T12:00:00Z).
Every manifest row must carry the registry entry's split. Page sets are skipped (no token cap).

Outputs (the layout score.py --test-pass reads, FORMATS.txt section 1-2):
 <preds>/<arm>/<ckpt>/<set>.tsv (id, ref, hyp, conf, conf_min, hit_cap, n_tokens) + <set>.raw.jsonl (resumable);
 <preds>/<arm>/<ckpt>_retry/<set>.tsv + .raw.jsonl;
 clarification J4 (23 Nov): <set>.tsv is written only for a COMPLETE set (atomically); a set stopped by the deadline
 is written as <set>.partial.tsv only, a name the scorer does not match to any registry set;
 meta.json of both folders: a key "test_pass" (gate file and its sha256, registry sha256, decoding, per set rows / done /
 complete / hit_cap share / padded / reused); validation keys are left as they are. No score is computed or printed here.

usage: eval_vlm_test.py --short S --arm A --ckpt C --model-dir DIR --registry R --evalsets JSON --preds-root P
                        --sets s1,s2 --test-pass [--gate-file F] [--batch 16] [--deadline-utc T] [--device cuda]
"""
import argparse
import hashlib
import json
import os
import sys
import time
from datetime import datetime, timezone

DATA = "/path/to/TURKIC_OCR_DATA"
DEFAULT_GATE = DATA + "/outputs/r5/RULE/test_pass_started.txt"
REAL_REGISTRY = DATA + "/data/processed/r5/evalsets.json"

ap = argparse.ArgumentParser()
ap.add_argument("--short", required=True)
ap.add_argument("--arm", required=True)
ap.add_argument("--ckpt", required=True)
ap.add_argument("--model-dir", required=True)
ap.add_argument("--registry", required=True)
ap.add_argument("--evalsets", required=True)
ap.add_argument("--preds-root", required=True)
ap.add_argument("--sets", required=True, help="comma list of LOCKED set names")
ap.add_argument("--test-pass", action="store_true")
ap.add_argument("--gate-file", default=DEFAULT_GATE, help="default = the scorer's gate; another path only for the CPU test")
ap.add_argument("--not-before-utc", default="2026-11-24T12:00:00Z")
ap.add_argument("--batch", type=int, default=16)
ap.add_argument("--deadline-utc", default="2026-11-24T17:00:00Z")
ap.add_argument("--device", default="cuda")
ap.add_argument("--limit", type=int, default=0, help="CPU test only: first N rows of each set")
args = ap.parse_args()


def utc():
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def say(*a):
    print(f"[test {args.arm}/{args.ckpt} {utc()}]", *a, flush=True)


def sha256(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()


def ts(s):
    return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()


# ---------------- gate: decided before the model or any manifest is opened ----------------
gate_open = bool(args.test_pass) and os.path.exists(args.gate_file)
if not gate_open:
    say("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)))
    sys.exit(3)
if os.path.realpath(args.evalsets) == os.path.realpath(REAL_REGISTRY) and time.time() < ts(args.not_before_utc):
    say("REFUSED: the real registry is not read before %s" % args.not_before_utc)
    sys.exit(3)
reg_doc = json.load(open(args.evalsets, encoding="utf-8"))
entries = reg_doc["sets"] if isinstance(reg_doc, dict) and isinstance(reg_doc.get("sets"), list) else reg_doc
want = [s for s in args.sets.split(",") if s]
todo, refused = [], []
for name in want:
    e = next((x for x in entries if isinstance(x, dict) and x.get("name") == name), None)
    if e is None:
        refused.append({"name": name, "why": "not in the registry"})
    elif 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 eval_vlm.py)"})
    elif not e.get("manifest") or not os.path.exists(e["manifest"]):
        refused.append({"name": name, "why": "manifest missing"})
    else:
        todo.append(e)
if not todo:
    say("nothing to do; refused:", json.dumps(refused))
    sys.exit(0 if not refused else 4)

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import vlm_common as vc  # noqa: E402
import postproc as pp  # noqa: E402
import torch  # noqa: E402
import transformers  # noqa: E402
from PIL import Image  # noqa: E402

dev = args.device
deadline = ts(args.deadline_utc)
MAXNEW = vc.MAXNEW
reg = vc.read_registry(args.registry)[args.short]
t_load = time.time()
proc, tok = vc.load_processor(args.short, args.model_dir)
tok.padding_side = "left"
exp_meta = {}
if os.path.exists(os.path.join(args.model_dir, "r5_export.json")):
    exp_meta = json.load(open(os.path.join(args.model_dir, "r5_export.json")))
tmpl_kw = exp_meta.get("chat_template_kwargs", vc.template_kwargs(proc, tok))
model, load_info = vc.load_model(args.short, args.model_dir, torch.bfloat16, info=True)
model = model.to(dev).eval()
if exp_meta:
    bad_keys = {k: list(load_info.get(k, []))[:10] for k in ("missing_keys", "unexpected_keys", "mismatched_keys") if load_info.get(k)}
    if bad_keys:
        say("REFUSED: exported checkpoint does not reload exactly:", json.dumps(bad_keys)[:600])
        sys.exit(5)
gc, stops, stop_set = vc.gen_setup(model, tok, exp_meta.get("answer_suffix_ids"))
PADDED = {"n": 0}
RETRY_T, RETRY_SEED = 0.3, 20261121


def load_img(p):
    im, npad = vc.pad_min_grid(args.short, proc, Image.open(p).convert("RGB"))
    PADDED["n"] += npad
    return im


def gen(imgs, max_new, temperature=None):
    return vc.generate_batch(args.short, model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, temperature=temperature)


def read_raw(p):
    d = {}
    if os.path.exists(p):
        for line in open(p, encoding="utf-8"):
            try:
                x = json.loads(line)
                d[x["id"]] = x
            except Exception:  # noqa: BLE001
                pass
    return d


def update_meta(folder, name, rec, extra=None):
    mp = os.path.join(folder, "meta.json")
    m = json.load(open(mp)) if os.path.exists(mp) else {}
    tp = m.setdefault("test_pass", {})
    tp.update({"script": "eval_vlm_test.py", "gate_file": args.gate_file, "gate_file_sha256": sha256(args.gate_file),
               "registry": args.evalsets, "registry_sha256": sha256(args.evalsets), "checkpoint_dir": args.model_dir,
               "decoding": {"greedy": True, "num_beams": 1, "max_new_tokens": MAXNEW, "batch": args.batch,
                            "stop_ids": stops, "chat_template_kwargs": tmpl_kw, "instruction": vc.INSTR},
               "conf_definition": vc.CONF_DEF, "attention": vc.SDPA_NOTE, "gpu": torch.cuda.get_device_name(0) if dev == "cuda" else "cpu",
               "transformers": transformers.__version__, "torch": torch.__version__, "refused_sets": refused, "updated_utc": utc()})
    if extra:
        tp.update(extra)
    tp.setdefault("sets", {})[name] = rec
    for k in ("conf_definition",):  # the scorer reads conf_definition from meta.json; keep the validation one if present
        m.setdefault(k, vc.CONF_DEF)
    tmp = mp + ".tmp"
    json.dump(m, open(tmp, "w"), indent=1, ensure_ascii=False)
    os.replace(tmp, mp)


def write_set_tsv(folder, name, rows, recs, complete):
    """Clarification J4: a test set counts only if all of its rows were written. A complete set is written as <name>.tsv
    (atomically, tmp then rename) and any <name>.partial.tsv is removed; an incomplete set is written ONLY as
    <name>.partial.tsv (the scorer does not match that name to a registry set) and any stale <name>.tsv is removed."""
    full, part = os.path.join(folder, name + ".tsv"), os.path.join(folder, name + ".partial.tsv")
    dst, stale = (full, part) if complete else (part, full)
    tmp = dst + ".tmp"
    vc.write_pred_tsv(tmp, rows, recs, pp.plain_ref, pp.plain_output)
    os.replace(tmp, dst)
    if os.path.exists(stale):
        os.remove(stale)


out_dir = os.path.join(args.preds_root, args.arm, args.ckpt)
ret_dir = os.path.join(args.preds_root, args.arm, args.ckpt + "_retry")
os.makedirs(out_dir, exist_ok=True)
os.makedirs(ret_dir, exist_ok=True)
CACHE = {}
say(f"gate open ({args.gate_file}); sets {[e['name'] for e in todo]}; refused {refused}; load {time.time() - t_load:.0f}s")
for e in todo:
    name = e["name"]
    t0 = time.time()
    rows = vc.read_manifest(e["manifest"])
    want_split = str(e.get("split", "")).lower()
    bad = [r for r in rows if str(r.get("split", "")).lower() != want_split]
    if bad:
        refused.append({"name": name, "why": "%d manifest rows with split != registry split %s" % (len(bad), want_split)})
        say(f"REFUSED {name}: rows with another split")
        continue
    if args.limit:
        rows = rows[: args.limit]
    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 (page sets go to the page pipeline)" % units})
        say(f"SKIPPED {name}: units {units}")
        continue
    raw_path = os.path.join(out_dir, name + ".raw.jsonl")
    done = read_raw(raw_path)
    for r in rows:
        if r["id"] in done:
            CACHE[(r["image"], r.get("unit", "word"))] = done[r["id"]]
    pend = [r for r in rows if r["id"] not in done]
    reused = 0
    pad0 = PADDED["n"]
    with open(raw_path, "a", encoding="utf-8") as fp:
        for r in pend:  # the same image in an earlier set of this call (kohtd_test_p2 / p2b lie inside kohtd_test)
            c = CACHE.get((r["image"], r.get("unit", "word")))
            if c is not None:
                x = dict(c, id=r["id"], reused_from_other_set=True)
                fp.write(json.dumps(x, ensure_ascii=False) + "\n")
                done[r["id"]] = x
                reused += 1
        pend = sorted([r for r in pend if r["id"] not in done], key=lambda r: r.get("unit", "word"))
        for u in sorted(set(r.get("unit", "word") for r in pend)):
            ru = [r for r in pend if r.get("unit", "word") == u]
            for b in range(0, len(ru), args.batch):
                if time.time() >= deadline:
                    say("deadline reached; stopping (resumable)")
                    break
                bb = ru[b:b + args.batch]
                try:
                    recs = gen([load_img(r["image"]) for r in bb], MAXNEW[u])
                except Exception as ex:  # noqa: BLE001
                    say(f"batch failed {repr(ex)[:150]}; one at a time")
                    recs = []
                    for r in bb:
                        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]})
                for r, x in zip(bb, recs):
                    x["id"] = r["id"]
                    fp.write(json.dumps(x, ensure_ascii=False) + "\n")
                    done[r["id"]] = x
                    CACHE[(r["image"], u)] = x
                fp.flush()
    complete = all(r["id"] in done for r in rows)
    write_set_tsv(out_dir, name, rows, done, complete)
    n_cap = sum(1 for r in rows if done.get(r["id"], {}).get("hit_cap"))
    update_meta(out_dir, name, {"rows": len(rows), "done": sum(1 for r in rows if r["id"] in done), "complete": complete,
                                "hit_cap_rows": n_cap, "padded_images_this_call": PADDED["n"] - pad0,
                                "reused_from_other_set": reused, "wall_seconds_this_call": round(time.time() - t0, 1),
                                "utc": utc()})
    # cap-retry folder, exactly as eval_vlm.py cap_retry()
    if complete and time.time() < deadline:
        rpath = os.path.join(ret_dir, name + ".raw.jsonl")
        rdone = read_raw(rpath)
        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:
                        break
                    bb = ru[b:b + args.batch]
                    recs = gen([load_img(r["image"]) for r in bb], MAXNEW[u], temperature=RETRY_T)
                    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"]}
                        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)
        write_set_tsv(ret_dir, name, rows, final, complete_r)
        update_meta(ret_dir, name, {"rows": len(rows), "complete": complete_r,
                                    "retried": sum(1 for r in rows if r["id"] in rdone),
                                    "retry_kept": sum(1 for r in rows if rdone.get(r["id"], {}).get("retry_kept")),
                                    "utc": utc()},
                    {"rule": "cap-retry (r5_posttrain_experiment.txt): temperature 0.3, torch seed 20261121 per set, kept if "
                             "it ends with a stop token; greedy folder = decision figure", "greedy_checkpoint_folder": args.ckpt})
    say(f"{name}: {len(rows)} rows, complete {complete}, hit_cap rows {n_cap}, reused {reused}, {time.time() - t0:.0f}s")
    if time.time() >= deadline:
        break
say("done; refused", json.dumps(refused))