File size: 8,502 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
"""R5 REF, arm R1 = HTR-Flor: predictions of the best-validation-loss checkpoint (pinned code arthurflor23/handwritten-text-recognition@1ca49af).
Every crop of a manifest gets a hypothesis (no crop is dropped). Images are preprocessed on the fly with the pinned data/preproc.py preprocess.
Writes, per checkpoint name C ("ours" = run i, "rand" = run ii):
   DATA/outputs/r5/preds/R1/C/<set>.tsv            greedy CTC decoding (the project's standard decoding)
   DATA/outputs/r5/preds/R1/C_paperdec/<set>.tsv   beam search, width 10, one path (the pinned main.py setting; the KOHTD paper does not state decoding)
   and meta.json beside each.
A locked set (evalsets.json locked=true, or a test manifest) is refused unless the scoring pass has started (token file, ref_common.TEST_TOKEN).
Usage: python -I ref_flor_predict.py --run i|ii --sets name=manifest[,name=manifest...] [--no_beam] [--cpu]
"""
import argparse
import json
import multiprocessing as mp
import os
import sys
import time
import unicodedata

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import ref_common as rc  # noqa: E402

INPUT_SIZE = (1024, 128, 1)
MAX_TEXT = 128
_PP = {}


def _winit(src):
    sys.path.insert(0, src)
    from data import preproc as pp
    _PP["pp"] = pp


def _prep(path):
    try:
        return _PP["pp"].preprocess(path, input_size=INPUT_SIZE)
    except Exception:
        return np.zeros(INPUT_SIZE[:2], dtype=np.uint8)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--run", required=True, choices=["i", "ii", "iii"])
    ap.add_argument("--sets", required=True)
    ap.add_argument("--train_dir", default=None)
    ap.add_argument("--no_beam", action="store_true")
    ap.add_argument("--cpu", action="store_true")
    ap.add_argument("--workers", type=int, default=3)
    ap.add_argument("--batch", type=int, default=128)
    ap.add_argument("--limit", type=int, default=0, help="smoke test: first N rows of each set")
    ap.add_argument("--pred_root", default=rc.PREDS)
    ap.add_argument("--gpu_mem_mb", type=int, default=10000)
    ap.add_argument("--refdata", default=rc.REFDATA)
    ap.add_argument("--weights_file", default=None, help="override: weights file (default checkpoint_weights.hdf5 of the train dir; run iii: curve_150016.hdf5)")
    ap.add_argument("--ck_name", default=None, help="override of the checkpoint folder name (default ours / rand / mix)")
    a = ap.parse_args()
    ck_name = a.ck_name or {"i": "ours", "ii": "rand", "iii": "mix"}[a.run]
    train_dir = a.train_dir or (rc.DATA + "/checkpoints/r5/ref/R1_" + a.run)
    sets = [s.split("=", 1) for s in a.sets.split(",") if s]
    loaded = []
    for name, path in sets:
        rows = rc.read_manifest(path)
        rc.check_locked(name, path, rows)
        loaded.append((name, path, rows[:a.limit] if a.limit else rows))
    chars = json.load(open(os.path.join(a.refdata, "charset_%s.json" % a.run), encoding="utf-8"))["chars"]
    summ = json.load(open(os.path.join(train_dir, "train_summary.json")))
    pool = mp.get_context("fork").Pool(a.workers, initializer=_winit, initargs=(rc.HTRFLOR_SRC,))

    os.environ.setdefault("TF_FORCE_GPU_ALLOW_GROWTH", "true")
    import tensorflow as tf
    tf.config.threading.set_intra_op_parallelism_threads(3)
    tf.config.threading.set_inter_op_parallelism_threads(2)
    gpus = tf.config.list_physical_devices("GPU")
    if gpus:
        tf.config.set_logical_device_configuration(gpus[0], [tf.config.LogicalDeviceConfiguration(memory_limit=a.gpu_mem_mb)])
    elif not a.cpu:
        print("FAIL: no GPU visible to TensorFlow")
        raise SystemExit(3)
    sys.path.insert(0, rc.HTRFLOR_SRC)
    from network.model import HTRModel
    from data.generator import Tokenizer
    from data import preproc as pp
    from tensorflow.keras import backend as K

    tok = Tokenizer(chars=chars, max_text_length=MAX_TEXT)   # decode() is unchanged
    model = HTRModel(architecture="flor", input_size=INPUT_SIZE, vocab_size=tok.vocab_size, beam_width=10, top_paths=1)
    model.compile(learning_rate=0.001)
    wfile = a.weights_file or os.path.join(train_dir, "curve_150016.hdf5" if a.run == "iii" else "checkpoint_weights.hdf5")
    model.model.load_weights(wfile)
    gpu_name = None
    try:
        gpu_name = tf.config.experimental.get_device_details(gpus[0]).get("device_name") if gpus else "cpu"
    except Exception:
        pass

    # batch-1 memory and speed (once)
    x1 = np.zeros((1,) + INPUT_SIZE, dtype=np.float32)
    model.model.predict(x1, verbose=0)
    peak1 = None
    try:
        if gpus:
            tf.config.experimental.reset_memory_stats("GPU:0")
            model.model.predict(x1, verbose=0)
            peak1 = tf.config.experimental.get_memory_info("GPU:0")["peak"]
    except Exception:
        pass

    def decode(out, greedy):
        n = len(out)
        res = [None] * n
        T = out.shape[1]
        for s in range(0, n, 256):
            chunk = out[s:s + 256]
            dec, log = K.ctc_decode(chunk, np.asarray([T] * len(chunk)), greedy=greedy, beam_width=10, top_paths=1)
            seqs = [[int(p) for p in row if p != -1] for row in dec[0].numpy()]
            for j, sq in enumerate(seqs):
                res[s + j] = tok.decode(sq)
        return res

    for name, path, rows in loaded:
        t0 = time.time()
        paths = [r["image"] for r in rows]
        hyp_g, hyp_b, conf = [], [], []
        speed_imgs = 0
        t_inf = 0.0
        for s in range(0, len(paths), a.batch * 8):
            imgs = np.stack(pool.map(_prep, paths[s:s + a.batch * 8], chunksize=16))
            x = pp.normalization(imgs)
            t1 = time.time()
            out = model.model.predict(x, batch_size=a.batch, verbose=0)
            t_inf += time.time() - t1
            speed_imgs += len(x)
            hyp_g += decode(out, True)
            if not a.no_beam:
                hyp_b += decode(out, False)
            conf += [float(np.exp(np.mean(np.log(np.clip(o.max(axis=-1), 1e-8, 1.0))))) for o in out]
        meta_common = {"model": "HTR-Flor (Gated-CNN-BGRU), arm R1, reference only", "model_revision": rc.HTRFLOR_COMMIT, "checkpoint": ck_name,
                       "weights": os.path.basename(wfile) + (" (best validation loss)" if a.run != "iii" else " (weights after the stated number of samples; the 150,016 point is the final one)"), "samples_seen": summ["samples_seen"], "epochs_done": summ["epochs_done"],
                       "stopped_because": summ["stopped_because"], "paper_rule_reached": summ.get("paper_rule_reached"), "learning_rate": summ["final_lr"],
                       "parameters": summ["parameters"], "peak_gpu_memory_bytes_batch1": peak1, "images_per_second_model_only_batch%d" % a.batch: round(speed_imgs / max(t_inf, 1e-9), 1),
                       "gpu": gpu_name, "wall_seconds_this_set": round(time.time() - t0, 1), "written_utc": rc.utc(), "set": name, "rows": len(rows),
                       "conf": "geometric mean over frames of the largest softmax probability (not a calibrated probability)", "data_role": rc.data_role(a.run, name),
                       "train_data": {"i": "KOHTD train forms of the project split (run i)", "ii": "crop-level random 70% of the KOHTD train+validation pool (run ii, seed 20261121)",
                                      "iii": "mix_v1, the first 150,016 eligible samples of the project's seeded mix stream (run iii, data-order seed 20261121)"}[a.run]}
        d1 = os.path.join(a.pred_root, "R1", ck_name)
        rc.write_preds(d1, name, rows, hyp_g, conf)
        m1 = dict(meta_common, decoding="greedy CTC (keras ctc_decode greedy=True), no lexicon, no language model")
        json.dump(m1, open(os.path.join(d1, "meta.json"), "w"), indent=1)
        json.dump(m1, open(os.path.join(d1, "meta_%s.json" % name), "w"), indent=1)
        if not a.no_beam:
            d2 = os.path.join(a.pred_root, "R1", ck_name + "_paperdec")
            rc.write_preds(d2, name, rows, hyp_b, conf)
            m2 = dict(meta_common, decoding="CTC beam search width 10, top path 1 (keras ctc_decode greedy=False, as in the pinned main.py), no lexicon, no language model")
            json.dump(m2, open(os.path.join(d2, "meta.json"), "w"), indent=1)
            json.dump(m2, open(os.path.join(d2, "meta_%s.json" % name), "w"), indent=1)
        print(name, len(rows), "rows", round(time.time() - t0, 1), "s", flush=True)
    pool.terminate()


if __name__ == "__main__":
    main()