File size: 16,796 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
"""R5 REF, arm R2 = the recogniser that Bimurat et al. 2024 trained in PaddleOCR (they call it SVTR-Tiny), run with PaddleOCR itself at the pinned
commit PaddlePaddle/PaddleOCR@e218c0a (v2.10.0) and its config configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml.

Why this config: the settings that the paper states (MobileNetV1Enhance backbone scale 0.5, average last pooling, MultiHead with CTCHead and SARHead,
MultiLoss, Adam 0.9/0.999, L2 3e-5, cosine learning rate) are exactly the keys of PaddleOCR's PP-OCRv3 recogniser configs (algorithm SVTR_LCNet);
PaddleOCR's own SVTR-Tiny config (configs/rec/rec_svtrnet.yml) has an SVTRNet backbone, CTC only and AdamW. See recipes.json.

This wrapper does not edit PaddleOCR. It (1) writes a config = the pinned config + the overrides listed below, (2) chooses the number of epochs from a
measured speed so that the cosine schedule completes inside the wall-clock budget (the paper's 100 epochs if they fit), (3) patches two names in memory
(ppocr.data.set_signal_handlers -> no-op, because the pinned handler kills the whole process group; tools.program.save_model -> a wrapper that keeps
the best checkpoint across resumes, keeps the previous 'latest', and stops cleanly after a 'latest' save when the budget is used or SIGTERM arrived),
(4) runs the pinned tools/train.py.

Overrides of the pinned config (all listed in recipes.json): lr 1e-4 and warm-up 1 epoch (paper 2.4, config: 1e-3 and 5), epoch_num (above),
character dictionary and list files (KOHTD), single card (distributed false), save_epoch_step large, checkpoints (resume), num_workers.
Unchanged from the pinned config: batch 128, image shape [3, 48, 320], max_text_length 25, RecConAug + RecAug, MultiHead, losses, eval every 2000 iterations.

Usage: python -I ref_ppocr_run.py --run i|ii --out <dir> [--budget_s N] [--epochs E] [--resume] [--cpu] [--smoke_n N]
"""
import argparse
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import threading
import time

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

STOP = {"flag": False}
PROG = {}


def kill_children():
    me = os.getpid()
    for d in os.listdir("/proc"):
        if d.isdigit():
            try:
                parts = open("/proc/%s/stat" % d).read().rsplit(")", 1)[1].split()
                if int(parts[1]) == me:
                    os.kill(int(d), signal.SIGKILL)
            except Exception:
                pass


def make_config(a, epochs, out, resume_ckpt):
    import yaml
    src = rc.PPOCR_ROOT + "/configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml"
    cfg = yaml.load(open(src, "rb"), Loader=yaml.Loader)
    tag = a.run
    g = cfg["Global"]
    g["use_gpu"] = not a.cpu
    g["epoch_num"] = int(epochs)
    g["distributed"] = False
    g["save_model_dir"] = out + "/model"
    g["save_epoch_step"] = 1 if tag == "iii" else 100000     # run iii: iter_epoch_1..4 are the 25/50/75/100 % learning-curve points
    g["character_dict_path"] = "%s/ppocr_dict_%s.txt" % (a.refdata, tag)
    g["use_space_char"] = True
    g["checkpoints"] = resume_ckpt
    g["pretrained_model"] = None
    g["save_res_path"] = out + "/predicts.txt"
    g["eval_batch_step"] = [0, 100000 if tag == "iii" else (4 if a.smoke_n else 2000)]   # run iii: no evaluation inside the 4-epoch fixed budget
    g["print_batch_step"] = 10
    cfg["Optimizer"]["lr"]["learning_rate"] = 0.0001   # Bimurat 2024, section 2.4
    # Bimurat 2024, section 2.4: warm-up of one epoch out of 100 (1 % of the run). Run iii has 4 epochs of 293 iterations, so 1 % = 0.04 epoch.
    cfg["Optimizer"]["lr"]["warmup_epoch"] = 0.04 if tag == "iii" else 1
    tr_list, va_list = "%s/ppocr_%s_train.txt" % (a.refdata, tag), "%s/ppocr_%s_val.txt" % (a.refdata, tag)
    if a.smoke_n:
        for src_l, dst_l, n in ((tr_list, out + "/smoke_train.txt", a.smoke_n), (va_list, out + "/smoke_val.txt", max(a.smoke_n // 4, 8))):
            with open(src_l, encoding="utf-8") as fi, open(dst_l, "w", encoding="utf-8") as fo:
                for i, line in enumerate(fi):
                    if i >= n:
                        break
                    fo.write(line)
        tr_list, va_list = out + "/smoke_train.txt", out + "/smoke_val.txt"
    if tag == "iii":
        cfg["Train"]["dataset"]["ratio_list"] = [0.999]    # makes SimpleDataSet rebuild its list at every epoch; the list of epoch k is chunk k of the mix stream (patched below)
    cfg["Train"]["dataset"]["data_dir"] = "/"
    cfg["Train"]["dataset"]["label_file_list"] = [tr_list]
    cfg["Train"]["loader"]["batch_size_per_card"] = a.batch
    cfg["Train"]["loader"]["num_workers"] = a.workers
    cfg["Eval"]["dataset"]["data_dir"] = "/"
    cfg["Eval"]["dataset"]["label_file_list"] = [va_list]
    cfg["Eval"]["loader"]["batch_size_per_card"] = a.batch
    cfg["Eval"]["loader"]["num_workers"] = max(1, a.workers // 2)
    os.makedirs(out, exist_ok=True)
    p = out + "/config_ref.yml"
    yaml.dump(cfg, open(p, "w"), default_flow_style=False, sort_keys=False)
    return p


def n_lines(p):
    with open(p, "rb") as f:
        return sum(1 for _ in f)


def calibrate(a, out, t_start):
    """Run the real training for a short time and read the speed from PaddleOCR's own log line 'ips: x samples/s'."""
    cdir = out + "_calib"
    shutil.rmtree(cdir, ignore_errors=True)
    cmd = [sys.executable, "-I", os.path.abspath(__file__), "--run", a.run, "--out", cdir, "--epochs", "100", "--calib_s", str(a.calib_s), "--workers", str(a.workers),
           "--batch", str(a.batch), "--refdata", a.refdata] + (["--cpu"] if a.cpu else []) + (["--smoke_n", str(a.smoke_n)] if a.smoke_n else [])
    res = subprocess.run(cmd, timeout=a.calib_s + 600, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    text = res.stdout.decode("utf-8", "replace")
    open(out + "_calibration_output.txt", "w", encoding="utf-8").write(text[-20000:])
    ips = [float(x) for x in re.findall(r"ips: ([0-9.]+) samples/s", text)]
    ips = ips[3:] if len(ips) > 6 else ips
    shutil.rmtree(cdir, ignore_errors=True)
    if not ips:
        return None
    ips.sort()
    return ips[len(ips) // 2]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--run", required=True, choices=["i", "ii", "iii"])
    ap.add_argument("--out", required=True)
    ap.add_argument("--budget_s", type=float, default=17100, help="seconds available (the driver passes {REMAIN}); the run stops at min(budget_s, budget_cap_s)")
    ap.add_argument("--budget_cap_s", type=float, default=16800)
    ap.add_argument("--epochs", type=int, default=0, help="0 = decide from the measured speed (at most 100, the paper's number)")
    ap.add_argument("--epochs_max", type=int, default=100)
    ap.add_argument("--resume", action="store_true")
    ap.add_argument("--cpu", action="store_true")
    ap.add_argument("--smoke_n", type=int, default=0)
    ap.add_argument("--max_epochs_smoke_stop", type=int, default=0, help="smoke test: stop cleanly after this many epochs (saves latest)")
    ap.add_argument("--batch", type=int, default=128)
    ap.add_argument("--workers", type=int, default=3)
    ap.add_argument("--calib_s", type=float, default=240)
    ap.add_argument("--refdata", default=rc.REFDATA)
    a = ap.parse_args()
    a.budget_s = min(a.budget_s, a.budget_cap_s)
    if a.run == "iii" and not a.epochs:
        a.epochs = 4        # four quarters of P_short = 150,016 samples (293 iterations of 128 each = 37,504 samples per epoch)
    t_start = time.time()
    os.makedirs(a.out, exist_ok=True)
    os.environ.setdefault("FLAGS_allocator_strategy", "auto_growth")
    os.environ.setdefault("OMP_NUM_THREADS", "2")
    os.environ["PYTHONPATH"] = rc.PPOCR_ROOT
    logf = open(a.out + "/wrapper.log", "a")

    def say(*x):
        s = "[%s] %s" % (rc.utc(), " ".join(str(i) for i in x))
        print(s, flush=True)
        logf.write(s + "\n")
        logf.flush()

    if a.calib_s and "--calib_s" in sys.argv and a.epochs == 100 and a.out.endswith("_calib"):
        threading.Timer(a.calib_s, lambda: (kill_children(), os._exit(0))).start()

    if not a.cpu:
        import paddle
        if not paddle.is_compiled_with_cuda() or paddle.device.cuda.device_count() < 1:
            say("FAIL: PaddlePaddle sees no GPU")
            raise SystemExit(3)
        x = paddle.randn([8, 3, 48, 320])
        w = paddle.randn([16, 3, 3, 3])
        y = paddle.nn.functional.conv2d(x.cuda() if hasattr(x, "cuda") else x, w.cuda() if hasattr(w, "cuda") else w)
        y.sum().item()
        say("GPU self-check ok", paddle.__version__, paddle.device.cuda.get_device_name())

    state_path = a.out + "/wrapper_state.json"
    st = json.load(open(state_path)) if (a.resume and os.path.exists(state_path)) else {}
    if not a.smoke_n:
        n_train = n_lines("%s/ppocr_%s_train.txt" % (a.refdata, a.run))
    else:
        n_train = a.smoke_n
    if "epochs" not in st:
        if a.epochs:
            st["epochs"], st["epochs_how"] = a.epochs, "given on the command line"
        else:
            ips = calibrate(a, a.out, t_start)
            if ips is None:
                st["epochs"], st["epochs_how"] = 20, "calibration failed (no speed read); fallback 20 epochs"
            else:
                left = a.budget_s - (time.time() - t_start) - 120
                ep_s = n_train / ips
                ep_s_total = ep_s * 1.08          # evaluation every 2000 iterations: about 8 % extra (estimate)
                e = int(0.92 * left / ep_s_total)
                st["epochs"] = max(2, min(a.epochs_max, e))
                st["epochs_how"] = "measured %.1f samples/s -> %.0f s per epoch; %.0f s left; %d epochs fit (cap %d)" % (ips, ep_s, left, e, a.epochs_max)
                st["measured_ips_calibration"] = ips
        st["offset_steps"] = 0
        st["session"] = 0
        json.dump(st, open(state_path, "w"), indent=1)
    say("epochs", st["epochs"], st.get("epochs_how"))
    deadline = t_start + a.budget_s
    st["session"] = st.get("session", 0) + 1

    # resume checkpoint
    mdir = a.out + "/model"
    resume_ckpt = None
    if a.resume:
        for pre in ("latest", "latest_prev"):
            if os.path.exists("%s/%s.pdparams" % (mdir, pre)) and os.path.exists("%s/%s.states" % (mdir, pre)):
                resume_ckpt = "%s/%s" % (mdir, pre)
                break
        say("resume checkpoint:", resume_ckpt)
    cfg_path = make_config(a, st["epochs"], a.out, resume_ckpt)
    json.dump(st, open(state_path, "w"), indent=1)

    # ---- patches (in memory only)
    sys.path.insert(0, rc.PPOCR_ROOT)
    os.chdir(rc.PPOCR_ROOT)
    import ppocr.data as ppdata
    ppdata.set_signal_handlers = lambda: None
    if a.run == "iii":
        # Run iii: epoch k trains on chunk k of the mix list (the first 150,016 eligible draws of the project's seeded mix stream, 4 chunks of 37,504).
        import ppocr.data.simple_dataset as psd
        orig_get = psd.SimpleDataSet.get_image_info_list
        n_all = n_lines("%s/ppocr_iii_train.txt" % a.refdata) if not a.smoke_n else a.smoke_n
        chunk = n_all // 4

        def get_chunk(self, file_list, ratio_list):
            if self.mode != "train":
                return orig_get(self, file_list, ratio_list)
            k = int(self.seed) if self.seed is not None and 1 <= int(self.seed) <= 4 else 1    # the first build of tools/train.py passes seed 1024 (only used to count iterations)
            with open(file_list[0] if isinstance(file_list, list) else file_list, "rb") as f:
                lines = f.readlines()
            return lines[(k - 1) * chunk: k * chunk]

        psd.SimpleDataSet.get_image_info_list = get_chunk
    import tools.program as program
    orig_save = program.save_model
    keep = a.out + "/best_keep"
    os.makedirs(keep, exist_ok=True)

    def best_acc_kept():
        try:
            return json.load(open(keep + "/best.json"))["acc"]
        except Exception:
            return -1.0

    def patched_save(model, optimizer, model_path, logger, config, is_best=False, prefix="ppocr", **kw):
        if prefix == "latest":
            for ext in (".pdparams", ".pdopt", ".states"):
                if os.path.exists("%s/latest%s" % (model_path, ext)):
                    shutil.copy2("%s/latest%s" % (model_path, ext), "%s/latest_prev%s" % (model_path, ext))
        r = orig_save(model, optimizer, model_path, logger, config, is_best=is_best, prefix=prefix, **kw)
        bm = kw.get("best_model_dict") or {}
        if prefix == "best_accuracy":
            acc = float(bm.get("acc", 0.0))
            if acc > best_acc_kept():
                for ext in (".pdparams", ".states"):
                    shutil.copy2("%s/best_accuracy%s" % (model_path, ext), "%s/best_accuracy%s" % (keep, ext))
                json.dump({"acc": acc, "norm_edit_dis": float(bm.get("norm_edit_dis", 0.0)), "epoch": kw.get("epoch"), "global_step_in_session": kw.get("global_step"),
                           "total_steps_at_save": st["offset_steps"] + int(kw.get("global_step", 0))}, open(keep + "/best.json", "w"))
        if prefix == "latest":
            PROG.update({"epoch": kw.get("epoch"), "steps_total": st["offset_steps"] + int(kw.get("global_step", 0))})
            json.dump(PROG, open(a.out + "/progress.json", "w"))
            write_summary("running", True)
            why = "sigterm" if STOP["flag"] else ("time_budget" if time.time() > deadline else (
                "max_epochs_smoke" if a.max_epochs_smoke_stop and kw.get("epoch", 0) >= a.max_epochs_smoke_stop + PROG.get("start_epoch_offset", 0) else None))
            if why:
                finish(why)
        return r

    def write_summary(why, provisional):
        """train_summary.json is written at every 'latest' save (provisional) and at the end, so that the prediction tasks find it even after a kill."""
        steps = PROG.get("steps_total", 0)
        best = json.load(open(keep + "/best.json")) if os.path.exists(keep + "/best.json") else {}
        summ = {"run": a.run, "arm": "R2", "stopped_because": why, "provisional": provisional, "epochs_planned": st["epochs"], "epochs_how": st.get("epochs_how"),
                "epochs_done": PROG.get("epoch", 0), "total_steps": steps, "batch": a.batch, "samples_seen": steps * a.batch,
                "train_rows": n_train, "paper_epochs": 100, "compressed_schedule": (st["epochs"] < 100) if a.run != "iii" else None,
                "paper_rule_reached": (not provisional) and ((steps * a.batch >= 150000) if a.run == "iii" else (why == "finished" and st["epochs"] >= 100)), "best": best, "finished_utc": rc.utc(),
                "stopping_rule": "100 epochs, cosine learning rate, lr 1e-4, warm-up 1 epoch, Adam 0.9/0.999, L2 3e-5 (Bimurat 2024, section 2.4); batch 128 is the config default (not stated)",
                "wall_seconds_session": round(time.time() - t_start, 1)}
        tmp = a.out + "/train_summary.json.tmp"
        json.dump(summ, open(tmp, "w"), indent=1)
        os.replace(tmp, a.out + "/train_summary.json")
        return summ

    def finish(why):
        summ = write_summary(why, False)
        try:   # every file of the pinned repository that this process imported (rule 0.11: these are the files to read and hash)
            mods = sorted({m.__file__ for m in list(sys.modules.values()) if getattr(m, "__file__", None) and str(m.__file__).startswith(rc.PPOCR_ROOT)})
            open(a.out + "/executed_pinned_files.txt", "w").write("\n".join(mods) + "\n")
        except Exception as e:
            say("could not list modules", e)
        say("DONE", why, "epochs", summ["epochs_done"], "samples", summ["samples_seen"])
        logf.flush()
        kill_children()
        os._exit(0)

    program.save_model = patched_save

    def on_term(sig, frm):
        STOP["flag"] = True
        say("SIGTERM received: will stop after the next 'latest' save (end of epoch)")
        threading.Timer(100, lambda: (say("grace over, exiting"), finish("sigterm_grace_over"))).start()

    signal.signal(signal.SIGTERM, on_term)
    if resume_ckpt:
        try:
            import pickle
            sd = pickle.load(open(resume_ckpt + ".states", "rb"), encoding="latin1")
            PROG["start_epoch_offset"] = int(sd.get("epoch", 0))
            st["offset_steps"] = int(json.load(open(a.out + "/progress.json")).get("steps_total", 0)) if os.path.exists(a.out + "/progress.json") else 0
        except Exception as e:
            say("could not read resume state:", e)
    sys.argv = ["tools/train.py", "-c", cfg_path]
    import runpy
    try:
        runpy.run_path(rc.PPOCR_ROOT + "/tools/train.py", run_name="__main__")
    except SystemExit as e:
        say("train.py exited", e)
    finish("finished")


if __name__ == "__main__":
    main()