File size: 10,297 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
"""Greedy predictions of one arm checkpoint on the validation sets of evalsets.json (never a locked or test set).

Writes, in the shared prediction format: PRED_DIR/<arm>/<checkpoint>/<evalset>.tsv (id, ref, hyp, conf, conf_min, hit_cap) and meta.json.
Also keeps the top-K CTC log-probabilities of every frame (LOGIT_DIR/<arm>/<checkpoint>/<evalset>.npz) so the character
language model can decode later without the network.
"""
import argparse
import json
import os
import sys
import time

import numpy as np
import torch
from torch.utils.data import DataLoader

from . import data as D
from .common import (DATA, LD_CKPT, LD_OUT, LOGIT_DIR, PRED_DIR, R5_PROC, cer_wer, load_json, read_manifest, save_json,
                     to_report_text, utcnow, write_tsv)
from .models import build_arm_for_inference

TOPK = 6


def greedy_strings(lp, out_lens, l2c_single):
    """lp (B,T,C) numpy float32; returns (strings NFD, mean confidence)."""
    best = lp.argmax(-1)
    bestp = np.exp(lp.max(-1))
    res = []
    for b in range(lp.shape[0]):
        T = int(out_lens[b])
        row = best[b, :T]
        prev = 0
        chars, confs = [], []
        for t in range(T):
            k = int(row[t])
            if k != prev and k != 0:
                chars.append(l2c_single.get(k, ""))
                confs.append(float(bestp[b, t]))
            prev = k
        res.append(("".join(chars), float(np.mean(confs)) if confs else 1.0, float(np.min(confs)) if confs else 1.0))
    return res


def eval_sets(evalsets_path, only=None, test=False):
    ev = load_json(evalsets_path)
    sets = ev["sets"] if isinstance(ev, dict) and "sets" in ev else ev
    out = []
    for s in sets:
        if test:                    # scoring pass only: the locked sets, behind the gate file
            if not s.get("locked"):
                continue
        else:
            if s.get("locked"):
                continue
            if s.get("split") not in ("val", "validation"):
                continue
        if only and s["name"] not in only:
            continue
        out.append(s)
    return out


class _EvBS:
    def __init__(self, order, bs):
        self.order, self.bs = order, bs

    def __iter__(self):
        for i in range(0, len(self.order), self.bs):
            yield self.order[i:i + self.bs]

    def __len__(self):
        return (len(self.order) + self.bs - 1) // self.bs


def run_set(arm, spec, codec, l2c_single, rows, bs, workers, dev):
    items = [(r["image"], r["text"], r.get("kind", "")) for r in rows]
    comps = [{"name": "ev", "share": 1.0, "items": items}]
    flat = D.FlatItems(comps)
    ds = D.LineDS(flat, spec, codec, train=False)
    order = D.eval_order(items)
    loader = DataLoader(ds, batch_sampler=_EvBS(order, bs), num_workers=workers, collate_fn=D.collate,
                        prefetch_factor=4 if workers else None)
    hyps = [None] * len(rows)
    confs = [None] * len(rows)
    cmins = [None] * len(rows)
    topk = [None] * len(rows)
    t0 = time.time()
    n = 0
    for batch in loader:
        lp, ol = arm.infer(batch["image"], batch["seq_lens"], dev)
        lpn = lp.cpu().numpy()
        oln = ol.cpu().numpy()
        res = greedy_strings(lpn, oln, l2c_single)
        k = min(TOPK, lpn.shape[-1])
        idx = np.argpartition(-lpn, k - 1, axis=-1)[..., :k]
        vals = np.take_along_axis(lpn, idx, axis=-1)
        for j, gid in enumerate(batch["gid"]):
            T = int(oln[j])
            hyps[gid] = res[j][0]
            confs[gid] = res[j][1]
            cmins[gid] = res[j][2]
            topk[gid] = (idx[j, :T].astype(np.int16), vals[j, :T].astype(np.float16))
        n += len(batch["gid"])
    return hyps, confs, cmins, topk, time.time() - t0


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--arm", required=True)
    ap.add_argument("--ckpt", required=True, help="short or long")
    ap.add_argument("--out_name", default="", help="folder name under preds/<arm>/ (default: the checkpoint name)")
    ap.add_argument("--test_pass", action="store_true", help="the single scoring pass (clarification H10): locked sets, every crop, no cap; refused unless the gate file exists")
    ap.add_argument("--gate_file", default=LD_OUT + "/test_pass_started.txt")
    ap.add_argument("--arm_label", default="", help="folder name instead of the arm name (second seed: A1_s2; H06 runs)")
    ap.add_argument("--ckpt_dir", default=LD_CKPT)
    ap.add_argument("--evalsets", default=R5_PROC + "/evalsets.json")
    ap.add_argument("--only", default="", help="comma separated eval set names")
    ap.add_argument("--limit", type=int, default=0, help="first N rows per set (smoke tests only)")
    ap.add_argument("--bs", type=int, default=32)
    ap.add_argument("--workers", type=int, default=8)
    ap.add_argument("--device", default="cuda")
    ap.add_argument("--pred_dir", default=PRED_DIR)
    ap.add_argument("--logit_dir", default=LOGIT_DIR)
    a = ap.parse_args()
    if a.test_pass:
        if not os.path.exists(a.gate_file):
            print("REFUSED: %s does not exist (the scoring pass has not started)" % a.gate_file)
            sys.exit(3)
        if a.limit:
            print("REFUSED: --limit (a cap) is not allowed in the test pass")
            sys.exit(3)
    dev = torch.device(a.device)
    path = os.path.join(a.ckpt_dir, a.arm, a.ckpt + ".pt")
    ck = torch.load(path, map_location="cpu", weights_only=False)
    from kraken.lib.codec import PytorchCodec
    from . import models as _models
    opts = ck.get("opts") or {}
    if opts.get("a4_output_ln") is False:
        _models.A4_OPTS["output_ln"] = False
    if opts.get("a4_stretch"):
        D.SPECS["A4"].stretch = True
    codec = PytorchCodec(ck["codec_c2l"])
    l2c_single = codec.l2c_single
    arm = build_arm_for_inference(a.arm, codec)
    arm.load_inference_state(ck["state"])
    arm.to(dev)
    arm.eval()
    spec = D.SPECS[a.arm]
    only = [x for x in a.only.split(",") if x]
    out_dir = os.path.join(a.pred_dir, a.arm_label or a.arm, a.out_name or a.ckpt)
    lg_dir = os.path.join(a.logit_dir, a.arm_label or a.arm, a.out_name or a.ckpt)
    os.makedirs(out_dir, exist_ok=True)
    os.makedirs(lg_dir, exist_ok=True)
    gpu = torch.cuda.get_device_name(0) if dev.type == "cuda" else "cpu"
    if dev.type == "cuda":
        torch.cuda.reset_peak_memory_stats()
    t_all = time.time()
    summary = {}
    for s in eval_sets(a.evalsets, only, a.test_pass):
        man = s["manifest"]
        if not os.path.isabs(man):
            man = os.path.join(R5_PROC, "manifests", man)
        if not os.path.exists(man):
            summary[s["name"]] = {"skipped": "manifest not found: " + man}
            continue
        ok_splits = ("test",) if a.test_pass else ("val", "validation")
        rows = [r for r in read_manifest(man) if r.get("unit") != "page" and (not r.get("split") or r["split"] in ok_splits)]
        if a.limit:
            rows = rows[:a.limit]
        if not rows:
            summary[s["name"]] = {"skipped": "no line or word rows"}
            continue
        hyps, confs, cmins, topk, secs = run_set(arm, spec, codec, l2c_single, rows, a.bs, a.workers, dev)
        hyp_nfc = [to_report_text(h) for h in hyps]
        refs = [r["text"] for r in rows]
        cer, wer, ce, cn, we, wn = cer_wer(refs, hyp_nfc)
        write_tsv(os.path.join(out_dir, s["name"] + ".tsv"), ["id", "ref", "hyp", "conf", "conf_min", "hit_cap"],
                  [(r["id"], r["text"], h, "%.4f" % c, "%.4f" % cm, 0) for r, h, c, cm in zip(rows, hyp_nfc, confs, cmins)])
        lens = np.array([len(t[0]) for t in topk], dtype=np.int64)
        np.savez_compressed(os.path.join(lg_dir, s["name"] + ".npz"), ids=np.array([r["id"] for r in rows]), lens=lens,
                            idx=np.concatenate([t[0] for t in topk]) if len(topk) else np.zeros((0, TOPK), np.int16),
                            lp=np.concatenate([t[1] for t in topk]) if len(topk) else np.zeros((0, TOPK), np.float16))
        summary[s["name"]] = {"n": len(rows), "cer": cer, "wer": wer, "char_errors": ce, "ref_chars": cn, "word_errors": we, "ref_words": wn,
                              "seconds": secs, "lines_per_second_eval": len(rows) / max(secs, 1e-9)}
        print(a.arm, a.ckpt, s["name"], json.dumps(summary[s["name"]]), flush=True)
    meta = {"arm": a.arm_label or a.arm, "model_id": {"A1": "kraken PP-OCRv6 medium, Zenodo record 21788410 (medium.safetensors, sha256 15313b51ace6...)",
                                       "A2": "kraken PP-OCRv6 small, Zenodo record 21788405 (small.safetensors, sha256 3108259779f5...)",
                                       "A1s": "PP-OCRv6 medium architecture of kraken 7.2, from scratch",
                                       "A3": "CRNN from scratch (linedet/models.py)",
                                       "A4": "HTR-VT design, from scratch (linedet/models.py)"}[a.arm],
            "revision": "kraken==7.2 (PyPI); CODE/.venv_kraken", "checkpoint": a.out_name or a.ckpt, "samples_seen": ck["samples_seen"],
            "learning_rate_peak": ck["lr_peak"], "recipe": ck["recipe"], "decoding": "greedy CTC (argmax per frame, collapse repeats, drop blanks), max length not capped",
            "peak_gpu_memory_gib_eval_batch_allocated": (torch.cuda.max_memory_allocated() / 2 ** 30 if dev.type == "cuda" else None),
            "peak_gpu_memory_gib_eval_batch_reserved": (torch.cuda.max_memory_reserved() / 2 ** 30 if dev.type == "cuda" else None),
            "confidence": "conf = mean over emitted characters of the frame maximum probability; conf_min = minimum of the same; hit_cap = 0 (CTC has no length cap)",
            "peak_gpu_memory_batch1_gib": "see OUT/timing.json (measured separately at batch 1)",
            "images_per_second": "per set in summary.lines_per_second_eval (batch %d, data loading included)" % a.bs,
            "gpu": gpu, "wall_time_train_seconds": ck["wall_train_seconds"], "wall_time_predict_seconds": time.time() - t_all,
            "label_form": "trained on NFD, written as NFC", "created": utcnow(), "per_set": summary}
    save_json(os.path.join(out_dir, "meta_test_pass.json" if a.test_pass else "meta.json"), meta)   # the test pass never overwrites the validation meta.json


if __name__ == "__main__":
    main()