File size: 29,092 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
"""Release candidate 1: the checks, run as one ZEN4 CPU job (see rc1_check.sbatch). Run with CODE/.venv_kraken/bin/python -I.

What it does, in order (every number goes to the results JSON):
  1  every package: SHA256SUMS matches the files, no file is missing from SHA256SUMS, no text file names a /shared/home or /datahub path;
  2  the 20 crops: the first 20 rows of the KOHTD validation screen set V1 (manifest kohtd_screen_v1.tsv, split val, unit word), in manifest order;
  3  each model reads the 20 crops through its own infer.py (python -B -I, cwd in a scratch folder, no CODE path): PaddleOCR-VL 1.6 leader and
     Qwen3-VL-2B leader (bfloat16 on CPU, --unit word), A1 long2x greedy, A1 long2x with the character LM (ungated), A1 long2x_lm_gated;
     compared with the recorded predictions DATA/outputs/r5/preds/<arm>/<checkpoint>/V1.tsv: agreement overall and for rows 1-16 / 17-20;
     every differing row is listed (reference, recorded, new) and for A1 re-read one image at a time to tell a batch effect from a code effect;
  4  the gate rule: gated V1 regenerated from the recorded long2x and long2x_lm files under the current rule, diffed with the recorded gated V1;
  5  the code copied into the packages against the evaluation code (rc1_ref_compare_vlm.py, rc1_ref_compare_a1.py);
  6  the page pipeline on 3 generated and 2 School Notebooks validation pages: live boxes against the stored boxes, hyp lines against the stored
     detB1 lines, page CER (reading order and order free) against DATA/outputs/r5/b1_page_check/score.json detB1 rows (rounded to 4 decimals);
  7  where every loaded Python module came from (none may lie under CODE), and the package folders are unchanged at the end.
Validation data only. Prediction files are opened by exact name; no test file is read.
"""
import csv
import hashlib
import json
import os
import subprocess
import sys
import time
from datetime import datetime, timezone

import numpy as np
from rapidfuzz import process
from rapidfuzz.distance import Levenshtein
from scipy.optimize import linear_sum_assignment

csv.field_size_limit(10 ** 9)

CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
R = DATA + "/release/rc1"
W = DATA + "/tmp/rc1_check"
PY_VLM = CODE + "/.venv_vlm/bin/python"
PY_KR = CODE + "/.venv_kraken/bin/python"
PRED = DATA + "/outputs/r5/preds"
SC = CODE + "/scripts/r5_release"
PK = {"paddle": R + "/turkic-ocr-paddleocr-vl-1.6", "qwen": R + "/turkic-ocr-qwen3-vl-2b", "a1": R + "/turkic-ocr-ppocrv6-medium",
      "det": R + "/turkic-line-detector-yolo11s", "page": R + "/page-pipeline"}
N_CROPS = 20
RESULTS = {}


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


def say(*a):
    print("[check %s]" % utc(), *a, flush=True)


def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def read_tsv(path):
    with open(path, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))


def read_pred(path):
    """Prediction files are opened by exact name; a name with 'test' in it is refused."""
    assert "test" not in os.path.basename(path).lower() and "/test" not in path.lower(), path
    return {r["id"]: r for r in read_tsv(path)}


def env():
    e = dict(os.environ)
    for k in list(e):
        if k.startswith("PYTHON"):
            e.pop(k)
    e.update({"PYTHONDONTWRITEBYTECODE": "1", "HF_HOME": W + "/hf_home", "HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1",
              "YOLO_OFFLINE": "1", "YOLO_CONFIG_DIR": W + "/yolo_cfg", "OMP_NUM_THREADS": "16", "MKL_NUM_THREADS": "16",
              "TOKENIZERS_PARALLELISM": "false"})
    for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
        e.pop(k, None)
    return e


def run(cmd, name, cwd):
    t0 = time.time()
    r = subprocess.run(cmd, cwd=cwd, env=env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    with open("%s/log_%s.txt" % (W, name), "w", encoding="utf-8") as f:
        f.write("CMD: " + " ".join(cmd) + "\n--- stdout\n" + r.stdout + "\n--- stderr\n" + r.stderr)
    say(name, "exit", r.returncode, "%.1f s" % (time.time() - t0))
    return {"exit": r.returncode, "seconds": round(time.time() - t0, 1), "stderr_tail": r.stderr[-400:]}


def cer(refs, hyps):
    ce = sum(Levenshtein.distance(a, b) for a, b in zip(refs, hyps))
    n = sum(len(a) for a in refs)
    return ce / n if n else float("nan")


# ----------------------------------------------------------------------------------------------- 1
def package_files(pkg):
    out = []
    for dp, dn, fn in os.walk(pkg):
        for f in fn:
            if f != "SHA256SUMS":
                out.append(os.path.relpath(os.path.join(dp, f), pkg))
    return sorted(out)


def check_sums():
    res = {}
    for key, pkg in PK.items():
        listed = {}
        sp = pkg + "/SHA256SUMS"
        for ln in open(sp, encoding="utf-8"):
            ln = ln.rstrip("\n")
            if ln:
                h, p = ln.split("  ", 1)
                listed[os.path.normpath(p)] = h
        files = package_files(pkg)
        bad = [p for p in files if listed.get(os.path.normpath(p)) != sha256(os.path.join(pkg, p))]
        missing_in_sums = [p for p in files if os.path.normpath(p) not in listed]
        gone = [p for p in listed if not os.path.exists(os.path.join(pkg, p))]
        hits = []
        for p in files:
            if p.endswith((".py", ".json", ".txt", ".jinja", ".yaml", ".tsv")) and os.path.getsize(os.path.join(pkg, p)) < 5_000_000:
                t = open(os.path.join(pkg, p), encoding="utf-8", errors="replace").read()
                for s in ("/shared/home", "/datahub", "CLUSTER_USER"):
                    if s in t:
                        hits.append([p, s])
        res[key] = {"n_files": len(files), "sha256sums_ok": not bad and not missing_in_sums and not gone, "mismatch": bad,
                    "files_not_in_sums": missing_in_sums, "listed_but_missing": gone, "text_files_naming_cluster_paths_or_user": hits,
                    "mtime_newest": max(os.path.getmtime(os.path.join(pkg, p)) for p in files),
                    "sums_mtime": os.path.getmtime(sp)}
    return res


# ----------------------------------------------------------------------------------------------- 2, 3, 4
def write_manifest(path, rows):
    with open(path, "w", encoding="utf-8", newline="") as f:
        f.write("id\timage\n")
        for r in rows:
            f.write("%s\t%s\n" % (r["id"], r["image"]))
    return path


def v1_manifests():
    """The V1 rows (KOHTD validation screen set, split val, unit word). Writes: the first 20 rows (the 20 crops), the first 32 rows (the
    VLM evaluation read V1 in manifest order in batches of 16, so rows 17-32 form the second batch together), and all 3678 rows in the order
    in which predict.py of the evaluation batched them (stable sort by label length, D.eval_order, batches of 32)."""
    man = DATA + "/data/processed/r5/manifests/kohtd_screen_v1.tsv"
    rows = read_tsv(man)
    assert all(r["split"] == "val" for r in rows), "V1 holds a row that is not validation"
    assert len(rows) == 3678
    assert all(r["unit"] == "word" for r in rows[:32])
    order = sorted(range(len(rows)), key=lambda i: len(rows[i]["text"]))
    return {"manifest": man, "rows": rows, "m20": write_manifest(W + "/v1_first20.tsv", rows[:N_CROPS]),
            "m32": write_manifest(W + "/v1_first32.tsv", rows[:32]),
            "m_all_eval_order": write_manifest(W + "/v1_all_eval_order.tsv", [rows[i] for i in order]),
            "m_all_manifest_order": write_manifest(W + "/v1_all_manifest_order.tsv", rows), "ids_all": [r["id"] for r in rows]}


def compare(out_path, rec, ids, refs, split=None, keep=40):
    """Compare an output TSV (id, text) with a recorded prediction file on the given ids, in that order. split: row count of the first
    batch of the recorded evaluation (agreement is also given for rows up to split and after it)."""
    out = {r["id"]: r["text"] for r in read_tsv(out_path)}
    same = [out.get(i) == rec[i]["hyp"] for i in ids]
    diffs = [{"row": k + 1, "id": i, "reference": refs[i], "recorded": rec[i]["hyp"], "new": out.get(i)} for k, i in enumerate(ids) if not same[k]]
    new_h = [out.get(i) or "" for i in ids]
    res = {"rows": len(ids), "identical": int(sum(same)), "agreement": sum(same) / len(ids),
           "cer_new_on_these_rows": cer([refs[i] for i in ids], new_h),
           "cer_recorded_on_these_rows": cer([refs[i] for i in ids], [rec[i]["hyp"] for i in ids]),
           "rows_differing": len(diffs), "differing_rows_first_%d" % keep: diffs[:keep]}
    if split:
        res.update({"rows_up_to_%d_identical" % split: int(sum(same[:split])), "rows_up_to_%d" % split: len(same[:split]),
                    "rows_after_%d_identical" % split: int(sum(same[split:])), "rows_after_%d" % split: len(same[split:])})
    return res


def gate_regeneration():
    g = read_pred(PRED + "/A1/long2x/V1.tsv")
    lm = read_pred(PRED + "/A1/long2x_lm/V1.tsv")
    gated = read_pred(PRED + "/A1/long2x_lm_gated/V1.tsv")
    n_diff, diffs, old_only = 0, [], 0
    for i, r in gated.items():
        greedy = g[i]["hyp"]
        regen = "" if greedy.strip() == "" else lm[i]["hyp"]
        old_rule = "" if greedy == "" else lm[i]["hyp"]
        if regen != r["hyp"]:
            n_diff += 1
            if len(diffs) < 10:
                diffs.append({"id": i, "greedy": greedy, "lm": lm[i]["hyp"], "recorded_gated": r["hyp"], "regenerated": regen})
        if old_rule != regen:
            old_only += 1
    return {"rows": len(gated), "rows_in_greedy_file": len(g), "rows_in_lm_file": len(lm), "regenerated_differs_from_recorded": n_diff,
            "rows_where_old_and_current_rule_differ": old_only, "examples": diffs}


# ----------------------------------------------------------------------------------------------- 6
def page_cers(hyp_lines, ref_lines):
    nref = sum(len(r) for r in ref_lines)
    ro = Levenshtein.distance(" ".join(hyp_lines), " ".join(ref_lines))
    if not hyp_lines or not ref_lines:
        of = sum(len(h) for h in hyp_lines) + nref
    else:
        C = process.cdist(hyp_lines, ref_lines, scorer=Levenshtein.distance, dtype=np.int32)
        ri, ci = linear_sum_assignment(C)
        matched = int(C[ri, ci].sum())
        un_h = sum(len(hyp_lines[i]) for i in range(len(hyp_lines)) if i not in set(ri.tolist()))
        un_r = sum(len(ref_lines[j]) for j in range(len(ref_lines)) if j not in set(ci.tolist()))
        of = matched + un_h + un_r
    return ro, of, nref


def school_orig(pid):
    sp, num = pid.split("_")[1], int(pid.split("_")[2])
    assert sp == "val"
    base = DATA + "/data/raw/school_notebooks_ru"
    d = json.load(open("%s/annotations_%s.json" % (base, sp), encoding="utf-8"))
    fn = {im["id"]: im["file_name"] for im in d["images"]}[num]
    return "%s/val_test_images/%s/%s" % (base, sp, fn)


def page_check():
    PG = DATA + "/data/processed/r5_linedet_det"
    gen_ids = ["pg_val_diagram_az_l_000008", "pg_val_diagram_kk_h_000029", "pg_val_map_tt_l_000022"]
    sch_ids = ["school_val_0", "school_val_45"]
    gen = {r["id"]: r for r in read_tsv(PG + "/gen/pages_gen_val.tsv") if r["id"] in gen_ids}
    sch = {r["id"]: r for r in read_tsv(PG + "/school2/pages_school_val.tsv") if r["id"] in sch_ids}
    pages = [gen[i] for i in gen_ids] + [sch[i] for i in sch_ids]
    for p in pages:
        assert "val" in p["id"] and "test" not in p["id"]
    man = W + "/pages5.tsv"
    hi = W + "/pages5_hires.tsv"
    with open(man, "w", encoding="utf-8", newline="") as f:
        f.write("id\timage\n")
        for p in pages:
            f.write("%s\t%s\n" % (p["id"], p["image"]))
    with open(hi, "w", encoding="utf-8", newline="") as f:
        f.write("id\timage\tscale\n")
        for p in pages:
            if p["id"].startswith("school_"):
                f.write("%s\t%s\t%r\n" % (p["id"], school_orig(p["id"]), 1.0 / float(p["scale"])))
    out_p, out_l, out_b, mods = W + "/page_pages.tsv", W + "/page_lines.tsv", W + "/page_boxes.tsv", W + "/mods_page.json"
    r = run([PY_VLM, "-B", "-I", PK["page"] + "/infer.py", "--manifest", man, "--out", out_p, "--lines-out", out_l, "--hires-tsv", hi,
             "--detector-python", PY_KR, "--device", "cpu", "--threads", "16", "--keep-boxes", out_b, "--report-modules", mods],
            "page_pipeline", W + "/run")
    res = {"run": r, "pages": [p["id"] for p in pages]}
    if r["exit"] != 0:
        return res
    # stored boxes
    stored_boxes = {}
    for name in ("gen", "school"):
        for ln in open("%s/outputs/r5/linedet/det_eval/e2e_yolo_s2_%s_val_A1_long_pages.jsonl" % (DATA, name), encoding="utf-8"):
            j = json.loads(ln)
            if j["id"] in gen_ids + sch_ids:
                stored_boxes[j["id"]] = j["boxes"]
    live = {r["id"]: json.loads(r["boxes"]) for r in read_tsv(out_b)}
    stored_hyp = {}
    for s in ("gen", "school"):
        for c in range(4):
            for ln in open("%s/outputs/r5/b1_page_check/%s_detB1_c%d.jsonl" % (DATA, s, c), encoding="utf-8"):
                j = json.loads(ln)
                stored_hyp[j["id"]] = j
    score = json.load(open(DATA + "/outputs/r5/b1_page_check/score.json", encoding="utf-8"))
    srow = {}
    for cell in score["cells"]:
        if cell["prompt"] == "detB1":
            for pp in cell["per_page"]:
                srow[pp["id"]] = pp
    lines = {}
    for r in read_tsv(out_l):
        lines.setdefault(r["id"], []).append(r["text"])
    per = []
    tot = {"ro": 0, "of": 0, "n": 0}
    for p in pages:
        pid = p["id"]
        hyp = [t for t in lines.get(pid, []) if t]
        ref = json.loads(p["ref_lines_json"])
        ro, of, n = page_cers(hyp, ref)
        tot["ro"] += ro
        tot["of"] += of
        tot["n"] += n
        a, b = sorted(live[pid], key=lambda x: (x[1], x[0])), sorted(stored_boxes[pid], key=lambda x: (x[1], x[0]))
        maxd = max((abs(u - v) for x, y in zip(a, b) for u, v in zip(x, y)), default=0.0) if len(a) == len(b) else None
        sh = stored_hyp[pid]["hyp_lines"]
        sr = srow[pid]
        per.append({"id": pid, "n_boxes_live": len(a), "n_boxes_stored": len(b), "max_abs_box_diff_px": maxd,
                    "n_hyp_lines": len(hyp), "n_hyp_lines_stored": len(sh), "n_ref_lines": len(ref),
                    "hyp_lines_identical_to_stored": hyp == sh,
                    "n_lines_differing": (sum(1 for x, y in zip(hyp, sh) if x != y) + abs(len(hyp) - len(sh))),
                    "ro_cer": round(ro / max(n, 1), 4), "ro_cer_stored": sr["ro_cer"],
                    "of_cer": round(of / max(n, 1), 4), "of_cer_stored": sr["of_cer"],
                    "ro_cer_unrounded": ro / max(n, 1), "of_cer_unrounded": of / max(n, 1),
                    "ro_equal_rounded": round(ro / max(n, 1), 4) == sr["ro_cer"], "of_equal_rounded": round(of / max(n, 1), 4) == sr["of_cer"],
                    "differing_lines": [[x, y] for x, y in zip(hyp, sh) if x != y][:6]})
    res["per_page"] = per
    res["micro_ro_cer"] = tot["ro"] / max(tot["n"], 1)
    res["micro_of_cer"] = tot["of"] / max(tot["n"], 1)
    s_ro = sum(srow[p["id"]]["ro_cer"] * srow[p["id"]]["ref_chars"] for p in pages) / max(tot["n"], 1)
    s_of = sum(srow[p["id"]]["of_cer"] * srow[p["id"]]["ref_chars"] for p in pages) / max(tot["n"], 1)
    res["micro_ro_cer_stored_rows_recombined"] = s_ro
    res["micro_of_cer_stored_rows_recombined"] = s_of
    res["all_pages_ro_and_of_equal_rounded"] = all(x["ro_equal_rounded"] and x["of_equal_rounded"] for x in per)
    res["all_pages_hyp_lines_identical_to_stored"] = all(x["hyp_lines_identical_to_stored"] for x in per)
    res["all_pages_boxes_identical"] = all(x["max_abs_box_diff_px"] == 0.0 for x in per)
    return res


# ----------------------------------------------------------------------------------------------- 7
def module_origin(mods_json, pkg_dir):
    j = json.load(open(mods_json, encoding="utf-8"))
    under_code = [m for m in j["modules"] if m.startswith(CODE + "/src") or m.startswith(CODE + "/scripts")]
    cats = {"package": 0, "venv_site_packages": 0, "python_stdlib": 0, "other": []}
    for m in j["modules"]:
        if m.startswith(pkg_dir):
            cats["package"] += 1
        elif "/site-packages/" in m:
            cats["venv_site_packages"] += 1
        elif "/lib/python3" in m:
            cats["python_stdlib"] += 1
        else:
            cats["other"].append(m)
    cats["other"] = cats["other"][:10]
    return {"modules_under_CODE_src_or_scripts": under_code, "sys_path": j["sys_path"], "categories": cats}


def main():
    t_all = time.time()
    os.makedirs(W + "/run", exist_ok=True)
    RESULTS.update({"started_utc": utc(), "slurm_job": os.environ.get("SLURM_JOB_ID"), "host": os.uname().nodename,
                    "cpus": os.environ.get("SLURM_CPUS_PER_TASK"), "validation_only": True})
    RESULTS["step1_sha256sums"] = check_sums()
    say("step 1 done", {k: v["sha256sums_ok"] for k, v in RESULTS["step1_sha256sums"].items()})
    V = v1_manifests()
    man20, man32 = V["m20"], V["m32"]
    ids_all = V["ids_all"]
    ids = ids_all[:N_CROPS]
    ids32 = ids_all[:32]
    v1rows = {r["id"]: r for r in V["rows"]}
    RESULTS["step2_crops"] = {"manifest": V["manifest"], "n": len(ids), "ids": ids, "unit": "word", "split": "val",
                              "companion_ids_21_to_32": ids_all[N_CROPS:32],
                              "note": "the 20 crops are the first 20 rows of V1 in manifest order; the VLMs also read rows 21-32 because the recorded "
                                      "evaluation read V1 in manifest order in batches of 16, so rows 17-32 were one batch there"}
    rec = {"paddle": read_pred(PRED + "/paddleocr_vl_1_6/leader/V1.tsv"), "qwen": read_pred(PRED + "/qwen3_vl_2b/leader/V1.tsv"),
           "a1_greedy": read_pred(PRED + "/A1/long2x/V1.tsv"), "a1_lm": read_pred(PRED + "/A1/long2x_lm/V1.tsv"),
           "a1_gated": read_pred(PRED + "/A1/long2x_lm_gated/V1.tsv")}
    refs = {i: rec["paddle"][i]["ref"] for i in ids_all}      # the reference column of the recorded files (validation labels)
    RESULTS["step2_crops"]["recorded_files_hold_all_V1_ids"] = all(i in r for r in rec.values() for i in ids_all)
    RESULTS["step2_crops"]["recorded_ref_equals_manifest_text_after_whitespace_collapse_all_rows"] = all(
        refs[i] == " ".join(v1rows[i]["text"].split()) for i in ids_all)
    mods = {}
    s3 = {}
    # VLMs: the 32 rows, batches of 16 in manifest order as in the evaluation; the 20 crops are rows 1-20
    for key, pkg, name in (("paddle", PK["paddle"], "PaddleOCR-VL 1.6 leader"), ("qwen", PK["qwen"], "Qwen3-VL-2B leader")):
        o = "%s/out_%s.tsv" % (W, key)
        mj = "%s/mods_%s.json" % (W, key)
        r = run([PY_VLM, "-B", "-I", pkg + "/infer.py", "--manifest", man32, "--out", o, "--unit", "word", "--device", "cpu",
                 "--threads", "16", "--with-conf", "--report-modules", mj], "infer_" + key, W + "/run")
        s3[key] = {"model": name, "batch": "rows 1-16 and 17-32 of V1 in manifest order, batch size 16, bfloat16 on CPU", "run": r}
        if r["exit"] == 0:
            s3[key]["the_20_crops"] = compare(o, rec[key], ids, refs, split=16)
            s3[key]["companion_rows_21_32"] = compare(o, rec[key], ids32[N_CROPS:], refs)
            s3[key]["rows_1_32"] = compare(o, rec[key], ids32, refs)
            mods[key] = module_origin(mj, pkg)
            say(key, "20 crops identical", s3[key]["the_20_crops"]["identical"], "of", len(ids), "; rows 1-32:", s3[key]["rows_1_32"]["identical"])
    # A1 on the 20 crops: default behaviour (sorted by width, batch 32), manifest order batch 32, batch 1
    for key, dec, recname, extra in (("a1_default_greedy", "greedy", "a1_greedy", ["--batch-size", "32"]),
                                     ("a1_default_lm", "lm", "a1_lm", ["--batch-size", "32"]),
                                     ("a1_default_lm_gated", "lm_gated", "a1_gated", ["--batch-size", "32"]),
                                     ("a1_manifest_order_bs32_pad0_greedy", "greedy", "a1_greedy", ["--batch-size", "32", "--sort", "none", "--batch-pad", "0"]),
                                     ("a1_bs1_pad0_greedy", "greedy", "a1_greedy", ["--batch-size", "1", "--batch-pad", "0"]),
                                     ("a1_bs1_pad0_lm_gated", "lm_gated", "a1_gated", ["--batch-size", "1", "--batch-pad", "0"])):
        o = "%s/out_%s.tsv" % (W, key)
        mj = "%s/mods_%s.json" % (W, key)
        r = run([PY_KR, "-B", "-I", PK["a1"] + "/infer.py", "--manifest", man20, "--out", o, "--decode", dec] + extra +
                ["--device", "cpu", "--threads", "16", "--with-conf", "--report-modules", mj], "infer_" + key, W + "/run")
        s3[key] = {"decode": dec, "options": extra, "run": r}
        if r["exit"] == 0:
            s3[key].update(compare(o, rec[recname], ids, refs))
            if key == "a1_default_greedy":
                mods["a1"] = module_origin(mj, PK["a1"])
            say(key, "identical", s3[key]["identical"], "of", len(ids))
    # A1 on all 3678 V1 rows. (a) in the evaluation's own batch order (batches of 32 sorted by label length): the condition of the recorded files;
    # (b) the package's default reading (batches of 32 sorted by image width, default --batch-pad: the label-free approximation chosen on V1 by
    # the padding diagnostic job 55176); (c) every crop alone without extra padding. (b) and (c) are what a user without labels gets.
    # The language-model beam search runs in 16 worker processes; if that fails it is run again in one process.
    for key, dec, recname, manifest, extra, what in (
            ("a1_eval_order_all_V1_greedy", "greedy", "a1_greedy", V["m_all_eval_order"], ["--batch-size", "32", "--sort", "none", "--batch-pad", "0"],
             "all V1 rows, stable sort by label length, batches of 32, no extra padding (as predict.py)"),
            ("a1_eval_order_all_V1_lm_gated", "lm_gated", "a1_gated", V["m_all_eval_order"], ["--batch-size", "32", "--sort", "none", "--batch-pad", "0"],
             "same batches as above"),
            ("a1_default_all_V1_greedy", "greedy", "a1_greedy", V["m_all_manifest_order"], ["--batch-size", "32"],
             "default of infer.py: batches of 32 sorted by image width plus the default --batch-pad"),
            ("a1_default_all_V1_lm_gated", "lm_gated", "a1_gated", V["m_all_manifest_order"], ["--batch-size", "32"], "default of infer.py"),
            ("a1_bs1_pad0_all_V1_greedy", "greedy", "a1_greedy", V["m_all_manifest_order"], ["--batch-size", "1", "--batch-pad", "0"],
             "every crop alone, no extra padding")):
        o = "%s/out_%s.tsv" % (W, key)
        base = [PY_KR, "-B", "-I", PK["a1"] + "/infer.py", "--manifest", manifest, "--out", o, "--decode", dec] + extra + ["--device", "cpu", "--threads", "16"]
        r = run(base + (["--workers", "16"] if dec != "greedy" else []), "infer_" + key, W + "/run")
        if r["exit"] != 0 and dec != "greedy":
            r["first_attempt_with_16_workers_failed"] = r.get("stderr_tail")
            r = run(base + ["--workers", "1"], "infer_" + key + "_one_process", W + "/run")
            r["note"] = "ran again with --workers 1 after the 16-worker run failed"
        s3[key] = {"decode": dec, "order": what, "options": extra, "run": r}
        if r["exit"] == 0:
            s3[key]["all_V1_rows"] = compare(o, rec[recname], ids_all, refs, keep=25)
            s3[key]["the_20_crops_inside_that_run"] = compare(o, rec[recname], ids, refs)
            say(key, "identical", s3[key]["all_V1_rows"]["identical"], "of", len(ids_all), "CER new", round(s3[key]["all_V1_rows"]["cer_new_on_these_rows"], 5),
                "recorded", round(s3[key]["all_V1_rows"]["cer_recorded_on_these_rows"], 5), "; the 20 crops:", s3[key]["the_20_crops_inside_that_run"]["identical"])
    # reference run: the evaluation's own predict.py (CODE/src/linedet) on CPU in float32 over the same V1 with the same batches. It separates a
    # numerical effect (the recorded files come from a GPU under bfloat16 autocast) from a code effect of the package.
    evs = W + "/evalsets_v1.json"
    with open(evs, "w", encoding="utf-8") as f:
        json.dump({"sets": [{"name": "V1", "manifest": V["manifest"], "split": "val"}]}, f)
    rp = run([PY_KR, "-I", "-m", "linedet.predict", "--arm", "A1", "--ckpt", "long2x", "--ckpt_dir", DATA + "/checkpoints/r5/linedet_ext",
              "--evalsets", evs, "--only", "V1", "--bs", "32", "--workers", "8", "--device", "cpu", "--pred_dir", W + "/ref_preds",
              "--logit_dir", W + "/ref_topk"], "ref_predict_py_cpu", W + "/run")
    s3["reference_predict_py_cpu_float32_all_V1"] = {"run": rp, "what": "CODE/src/linedet/predict.py, --device cpu --bs 32, V1 only, validation manifest"}
    refp_path = W + "/ref_preds/A1/long2x/V1.tsv"
    if rp["exit"] == 0 and os.path.exists(refp_path):
        read_pred(refp_path)
        outp = {r["id"]: r["hyp"] for r in read_tsv(refp_path)}
        same = [outp.get(i) == rec["a1_greedy"][i]["hyp"] for i in ids_all]
        s3["reference_predict_py_cpu_float32_all_V1"]["vs_recorded_gpu_bf16_file"] = {
            "rows": len(ids_all), "identical": int(sum(same)), "agreement": sum(same) / len(ids_all),
            "on_the_20_crops_identical": int(sum(same[:N_CROPS])),
            "cer_predict_py_cpu": cer([refs[i] for i in ids_all], [outp.get(i) or "" for i in ids_all]),
            "cer_recorded_gpu": cer([refs[i] for i in ids_all], [rec["a1_greedy"][i]["hyp"] for i in ids_all])}
        pk_out = {r["id"]: r["text"] for r in read_tsv(W + "/out_a1_eval_order_all_V1_greedy.tsv")} if os.path.exists(W + "/out_a1_eval_order_all_V1_greedy.tsv") else {}
        if pk_out:
            same2 = [pk_out.get(i) == outp.get(i) for i in ids_all]
            s3["reference_predict_py_cpu_float32_all_V1"]["package_eval_order_vs_predict_py_cpu"] = {
                "rows": len(ids_all), "identical": int(sum(same2)), "agreement": sum(same2) / len(ids_all),
                "first_differences": [{"id": i, "predict_py_cpu": outp.get(i), "package": pk_out.get(i), "reference": refs[i]}
                                      for i, s in zip(ids_all, same2) if not s][:20]}
        say("predict.py CPU vs recorded:", s3["reference_predict_py_cpu_float32_all_V1"]["vs_recorded_gpu_bf16_file"]["identical"], "of", len(ids_all))
    RESULTS["step3_recorded_predictions"] = s3
    RESULTS["step4_gate_rule"] = gate_regeneration()
    # step 5
    r5 = {}
    r5["vlm"] = run([PY_VLM, "-B", "-I", SC + "/rc1_ref_compare_vlm.py", W + "/ref_compare_vlm.json", PK["paddle"], PK["qwen"]], "ref_compare_vlm", W + "/run")
    r5["a1"] = run([PY_KR, "-B", "-I", SC + "/rc1_ref_compare_a1.py", W + "/ref_compare_a1.json", PK["a1"], man20], "ref_compare_a1", W + "/run")
    for k, f in (("vlm", "ref_compare_vlm.json"), ("a1", "ref_compare_a1.json")):
        if os.path.exists(W + "/" + f):
            r5[k + "_result"] = json.load(open(W + "/" + f, encoding="utf-8"))
    RESULTS["step5_code_equals_evaluation_code"] = r5
    # step 6
    RESULTS["step6_page_pipeline"] = page_check()
    if os.path.exists(W + "/mods_page.json"):
        mods["page"] = module_origin(W + "/mods_page.json", PK["page"])
    # detector alone: its own module list (one page)
    mj = W + "/mods_det.json"
    one = W + "/det_one.tsv"
    with open(one, "w", encoding="utf-8", newline="") as f:
        f.write("id\timage\n")
        pg = [r for r in read_tsv(DATA + "/data/processed/r5_linedet_det/gen/pages_gen_val.tsv") if r["id"] == "pg_val_diagram_az_l_000008"][0]
        f.write("%s\t%s\n" % (pg["id"], pg["image"]))
    rr = run([PY_KR, "-B", "-I", PK["det"] + "/infer.py", "--manifest", one, "--out", W + "/det_one_out.tsv", "--device", "cpu",
              "--report-modules", mj], "infer_det", W + "/run")
    RESULTS["step3_detector_alone"] = {"run": rr, "page": "pg_val_diagram_az_l_000008"}
    if rr["exit"] == 0:
        mods["det"] = module_origin(mj, PK["det"])
        RESULTS["step3_detector_alone"]["n_lines"] = int(read_tsv(W + "/det_one_out.tsv")[0]["n_lines"])
    RESULTS["step7_module_origin"] = mods
    RESULTS["step7_no_module_under_CODE"] = all(not v["modules_under_CODE_src_or_scripts"] for v in mods.values())
    # package folders unchanged
    after = check_sums()
    RESULTS["step7_packages_after"] = {k: {"sha256sums_ok": v["sha256sums_ok"], "files_not_in_sums": v["files_not_in_sums"], "n_files": v["n_files"],
                                           "newest_file_not_newer_than_sums": v["mtime_newest"] <= v["sums_mtime"]} for k, v in after.items()}
    RESULTS["finished_utc"] = utc()
    RESULTS["seconds_total"] = round(time.time() - t_all, 1)
    with open(W + "/check_results.json", "w", encoding="utf-8") as f:
        json.dump(RESULTS, f, indent=1, ensure_ascii=False, default=str)
    say("results written", W + "/check_results.json")


if __name__ == "__main__":
    main()