"""R5 REF, arm R1 = HTR-Flor (TensorFlow): training with the pinned code of arthurflor23/handwritten-text-recognition@1ca49af (2021-06-23).
What comes from the pinned code, unchanged: network.model.HTRModel (architecture "flor", CTC loss, RMSprop), network.layers, data.preproc
(preprocess, augmentation, normalization), data.generator.Tokenizer (repeated-letter separator token), the callbacks of HTRModel.get_callbacks
(CSVLogger, ModelCheckpoint best val_loss, EarlyStopping, ReduceLROnPlateau).
What this script changes (every change is listed in recipes.json "deviations"):
- the tokenizer keeps Unicode (the pinned one maps text to ASCII, which deletes Cyrillic); charset = characters of the training labels, case kept;
- the generator reads uint8 images from a memory-mapped array and builds augmented batches in worker processes (the pinned one holds the HDF5 in RAM);
- the TensorBoard callback is dropped;
- batch 32 and ReduceLROnPlateau patience 10 (the KOHTD paper, section 5.2/5.4) instead of the code defaults 16 and 15;
- a wall-clock budget, SIGTERM handling and a per-epoch resume state (model + optimizer + callback counters) are added.
Usage: python -I ref_flor_train.py --run i|ii --out
[--budget_s N] [--resume] [--smoke_pool N --batch 8 ...]
"""
import argparse
import collections
import itertools
import json
import multiprocessing as mp
import os
import signal
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
STOP = {"flag": False, "why": None}
# ---------------------------------------------------------------- worker side (created before TensorFlow is imported)
_W = {}
def _winit(src, pool_path, seed):
sys.path.insert(0, src)
from data import preproc as pp # pinned
_W["pp"] = pp
_W["arr"] = np.load(pool_path, mmap_mode="r") if pool_path else None
np.random.seed(seed + os.getpid() % 100000)
def _make_aug_paths(paths):
"""Run (iii): the images of the mix are read from disk, preprocessed with the pinned function, then augmented as in _make_aug."""
pp = _W["pp"]
x = np.stack([_prep_one(pp, p) for p in paths])
x = pp.augmentation(x, rotation_range=1.5, scale_range=0.05, height_shift_range=0.025, width_shift_range=0.05, erode_range=5, dilate_range=3)
return np.clip(x, 0, 255).astype(np.uint8)
def _prep_one(pp, path):
try:
return pp.preprocess(path, input_size=INPUT_SIZE)
except Exception:
return np.full(INPUT_SIZE[:2], 255, dtype=np.uint8) # unreadable image: blank page (counted by the caller's log only)
def _make_aug(idx):
"""Pinned augmentation (data/preproc.py augmentation, the parameter values of the pinned data/generator.py next_train_batch).
The result is integer valued (nearest-neighbour warp, erode, dilate), so it is sent back as uint8 and normalised in the main process."""
pp = _W["pp"]
x = np.asarray(_W["arr"][idx])
x = pp.augmentation(x, rotation_range=1.5, scale_range=0.05, height_shift_range=0.025, width_shift_range=0.05, erode_range=5, dilate_range=3)
return np.clip(x, 0, 255).astype(np.uint8)
def _make_plain(idx):
return np.asarray(_W["arr"][idx])
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--run", required=True, choices=["i", "ii", "iii"])
ap.add_argument("--mix_list", default=rc.REFDATA + "/mix_iii_R1.tsv", help="run iii: the 150,016 mix_v1 samples (image, text) in training order")
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("--resume", action="store_true")
ap.add_argument("--batch", type=int, default=32) # KOHTD paper 5.2/5.4: mini-batches of 32
ap.add_argument("--reduce_patience", type=int, default=10) # KOHTD paper 5.4: decay 0.2 after 10 epochs without improvement
ap.add_argument("--stop_patience", type=int, default=20) # KOHTD paper 5.2/5.4: early stopping patience 20
ap.add_argument("--epochs", type=int, default=1000) # pinned main.py default
ap.add_argument("--workers", type=int, default=2)
ap.add_argument("--prefetch", type=int, default=6)
ap.add_argument("--gpu_mem_mb", type=int, default=14000)
ap.add_argument("--cpu", action="store_true", help="smoke test on CPU: no GPU check")
ap.add_argument("--smoke_pool", type=int, default=0, help="smoke test: keep only rows whose pool index is below this number")
ap.add_argument("--max_steps", type=int, default=0, help="stop after this many training batches (smoke test)")
ap.add_argument("--steps_per_epoch", type=int, default=0, help="smoke test: override steps per epoch")
ap.add_argument("--pool", default=rc.REFDATA + "/flor_pool_u8.npy")
ap.add_argument("--ids", default=rc.REFDATA + "/pool_ids.txt")
ap.add_argument("--refdata", default=rc.REFDATA)
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
a.budget_s = min(a.budget_s, a.budget_cap_s)
t_start = time.time()
deadline = t_start + a.budget_s
log = open(os.path.join(a.out, "train_stdout_extra.log"), "a")
def say(*x):
s = "[%s] %s" % (rc.utc(), " ".join(str(i) for i in x))
print(s, flush=True)
log.write(s + "\n")
log.flush()
# ---- data (text only here; images are read by the worker processes)
MIXRUN = a.run == "iii"
if MIXRUN:
trn, val = rc.read_manifest(a.mix_list), []
for r in trn:
assert "test" not in r["image"].lower().split("/")[-2:], "a test image reached the mix list"
if a.smoke_pool:
trn = trn[:a.smoke_pool]
tr_idx = va_idx = None
pool_path = None
if a.epochs == 1000:
a.epochs = 4 # four quarters of P_short = 150,016 samples (the 25/50/75/100 % learning-curve points)
else:
pool_path = a.pool
ids = open(a.ids, encoding="utf-8").read().split("\n")
ids = [i for i in ids if i]
pos = {k: i for i, k in enumerate(ids)}
if a.run == "i":
trn, val = rc.read_manifest(rc.MANIFESTS + "/kohtd_train.tsv"), rc.read_manifest(rc.MANIFESTS + "/kohtd_val.tsv")
else:
trn, val = rc.read_manifest(rc.MANIFESTS + "/kohtd_rand_train.tsv"), rc.read_manifest(rc.MANIFESTS + "/kohtd_rand_val.tsv")
for r in trn + val:
assert r["split"] in ("train", "val"), "a test row reached the training script"
if a.smoke_pool:
trn = [r for r in trn if pos[r["id"]] < a.smoke_pool]
val = [r for r in val if pos[r["id"]] < a.smoke_pool]
tr_idx = np.array([pos[r["id"]] for r in trn], dtype=np.int64)
va_idx = np.array([pos[r["id"]] for r in val], dtype=np.int64)
chars = json.load(open(os.path.join(a.refdata, "charset_%s.json" % a.run), encoding="utf-8"))["chars"]
say("run", a.run, "train", len(trn), "val", len(val), "charset", len(chars))
# ---- worker pool before TensorFlow is imported (fork after CUDA initialisation is unsafe)
pool = mp.get_context("fork").Pool(a.workers, initializer=_winit, initargs=(rc.HTRFLOR_SRC, pool_path, 20261121))
os.environ.setdefault("TF_FORCE_GPU_ALLOW_GROWTH", "true")
import tensorflow as tf
tf.config.threading.set_intra_op_parallelism_threads(2)
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:
say("FAIL: no GPU visible to TensorFlow (nvidia libraries did not load?)")
raise SystemExit(3)
say("tensorflow", tf.__version__, "gpus", gpus)
sys.path.insert(0, rc.HTRFLOR_SRC)
from network.model import HTRModel # pinned
from data.generator import Tokenizer # pinned
from data import preproc as pp # pinned (normalization)
from tensorflow.keras import backend as K # noqa: F401
from itertools import groupby
class KzTokenizer(Tokenizer):
"""Pinned Tokenizer with Unicode kept: same repeated-letter separator trick, no NFKD-to-ASCII step."""
def encode(self, text):
if isinstance(text, bytes):
text = text.decode()
text = unicodedata.normalize("NFC", text)
text = " ".join(text.split())
groups = ["".join(g) for _, g in groupby(text)]
text = "".join([self.UNK_TK.join(list(x)) if len(x) > 1 else x for x in groups])
out = []
for ch in text:
k = self.chars.find(ch)
out.append(self.UNK if k == -1 else k)
return np.asarray(out)
tok = KzTokenizer(chars=chars, max_text_length=MAX_TEXT)
def encode_batch(rows):
y = [tok.encode(r["text"]) for r in rows]
y = [np.pad(v, (0, tok.maxlen - len(v))) for v in y]
return np.asarray(y, dtype=np.int16)
# ---- batch streams
if MIXRUN:
steps = (len(trn) // a.batch) // 4 if not a.steps_per_epoch else a.steps_per_epoch # quarter of the run per Keras epoch
else:
steps = int(np.ceil(len(trn) / a.batch)) if not a.steps_per_epoch else a.steps_per_epoch
vsteps = int(np.ceil(len(val) / a.batch))
rng = np.random.RandomState(42)
def train_stream_mix(start_batch):
"""Run (iii): the list is already in a seeded random order; batch k is rows k*32 .. k*32+31; a resume continues at start_batch."""
pend = collections.deque()
nb = len(trn) // a.batch
for k in range(start_batch, nb):
rows = trn[k * a.batch:(k + 1) * a.batch]
pend.append((pool.apply_async(_make_aug_paths, ([r["image"] for r in rows],)), rows))
if len(pend) >= a.prefetch:
f, rw = pend.popleft()
yield pp.normalization(f.get()), encode_batch(rw)
while pend:
f, rw = pend.popleft()
yield pp.normalization(f.get()), encode_batch(rw)
def train_stream():
epoch = 0
pend = collections.deque()
while True:
order = rng.permutation(len(trn))
for s in range(0, len(order), a.batch):
sel = order[s:s + a.batch]
fut = pool.apply_async(_make_aug, (tr_idx[sel],))
pend.append((fut, sel))
if len(pend) >= a.prefetch:
f, sl = pend.popleft()
yield pp.normalization(f.get()), encode_batch([trn[i] for i in sl])
epoch += 1
def val_stream():
while True:
pend = collections.deque()
for s in range(0, len(val), a.batch):
sel = np.arange(s, min(s + a.batch, len(val)))
pend.append((pool.apply_async(_make_plain, (va_idx[sel],)), sel))
if len(pend) >= 4:
f, sl = pend.popleft()
yield pp.normalization(f.get()), encode_batch([val[i] for i in sl])
while pend:
f, sl = pend.popleft()
yield pp.normalization(f.get()), encode_batch([val[i] for i in sl])
# ---- model (pinned)
model = HTRModel(architecture="flor", input_size=INPUT_SIZE, vocab_size=tok.vocab_size, beam_width=10,
stop_tolerance=a.stop_patience, reduce_tolerance=a.reduce_patience)
model.compile(learning_rate=0.001)
n_params = int(model.model.count_params())
say("parameters", n_params, "vocab_size", tok.vocab_size)
ckpt_w = os.path.join(a.out, "checkpoint_weights.hdf5")
cbs = model.get_callbacks(logdir=a.out, checkpoint=ckpt_w, verbose=1)
cbs = [c for c in cbs if c.__class__.__name__ != "TensorBoard"]
if MIXRUN:
# run (iii) is a fixed budget of 150,016 samples = 4 Keras epochs of a quarter each: no validation, so EarlyStopping,
# ReduceLROnPlateau and the best-loss ModelCheckpoint (which all need val_loss and could not act in 4 epochs) are not used.
cbs = [c for c in cbs if c.__class__.__name__ == "CSVLogger"]
es = rl = mc = None
else:
es = [c for c in cbs if c.__class__.__name__ == "EarlyStopping"][0]
rl = [c for c in cbs if c.__class__.__name__ == "ReduceLROnPlateau"][0]
mc = [c for c in cbs if c.__class__.__name__ == "ModelCheckpoint"][0]
# ---- resume state
rdir = os.path.join(a.out, "resume")
os.makedirs(rdir, exist_ok=True)
state_path = os.path.join(rdir, "state.json")
model.model.optimizer.build(model.model.trainable_variables) # create the optimizer slots so that a checkpoint can be restored into them
ckpt = tf.train.Checkpoint(model=model.model, optimizer=model.model.optimizer)
RESUME = {}
st = {"epochs_done": 0, "batches_done": 0, "wall_used_s": 0.0, "history": [], "es": {}, "rl": {}, "lr": 0.001}
if a.resume and os.path.exists(state_path):
st = json.load(open(state_path))
ckpt.read(os.path.join(rdir, "ckpt")).expect_partial()
K.set_value(model.model.optimizer.learning_rate, st["lr"])
if not MIXRUN:
if os.path.exists(ckpt_w):
model.model.load_weights(ckpt_w)
RESUME["best_weights"] = model.model.get_weights()
ckpt.read(os.path.join(rdir, "ckpt")).expect_partial() # restore the last (not best) weights again
RESUME["es"], RESUME["rl"], RESUME["mc_best"] = st["es"], st["rl"], st["mc_best"]
say("RESUMED at epoch", st["epochs_done"], "batches", st["batches_done"], "lr", st["lr"], "wall used", st["wall_used_s"])
deadline = t_start + max(0.0, a.budget_s - st["wall_used_s"])
class Control(tf.keras.callbacks.Callback):
def __init__(self):
super().__init__()
self.batches = st["batches_done"]
self.t_epoch = None
self.epoch_times = []
self.reason = None
def on_train_begin(self, logs=None):
# EarlyStopping and ReduceLROnPlateau reset their counters in their own on_train_begin (they come first in the list);
# on a resume the saved counters are put back here.
if RESUME:
es.wait, es.best, es.best_epoch = RESUME["es"]["wait"], RESUME["es"]["best"], RESUME["es"]["best_epoch"]
rl.wait, rl.best, rl.cooldown_counter = RESUME["rl"]["wait"], RESUME["rl"]["best"], RESUME["rl"]["cooldown_counter"]
mc.best = RESUME["mc_best"] # ModelCheckpoint keeps its own best; without this a worse epoch after a resume would overwrite the best weights file
if "best_weights" in RESUME:
es.best_weights = RESUME["best_weights"]
def on_epoch_begin(self, epoch, logs=None):
self.t_epoch = time.time()
def on_train_batch_end(self, batch, logs=None):
self.batches += 1
if self.batches == 20 or self.batches % 500 == 0:
say("batches", self.batches, "loss", None if logs is None else float(logs.get("loss", -1)))
why = None
if STOP["flag"]:
why = STOP["why"]
elif time.time() > deadline:
why = "time_budget"
elif a.max_steps and self.batches >= a.max_steps:
why = "max_steps"
if why and not self.reason:
self.reason = why
self.model.stop_training = True
def on_epoch_end(self, epoch, logs=None):
self.epoch_times.append(time.time() - self.t_epoch)
if self.batches % steps != 0:
# the run was stopped inside this epoch: it is NOT written to the resume state or the curve files, so that a resume repeats the
# whole epoch from the state of the previous epoch end and the batch counts stay a multiple of the epoch length
say("partial epoch", epoch + 1, "stopped after", self.batches, "batches in total; resume state keeps epoch", st["epochs_done"])
write_summary(self.reason or "running_partial_epoch", True)
return
st["epochs_done"] = epoch + 1
st["batches_done"] = self.batches
st["wall_used_s"] = st["wall_used_s"] + (time.time() - self.t_epoch)
st["lr"] = float(K.get_value(self.model.optimizer.learning_rate))
st["history"].append({"epoch": epoch + 1, "loss": float(logs.get("loss", -1)), "val_loss": float(logs.get("val_loss", -1)), "lr": st["lr"],
"epoch_seconds": round(self.epoch_times[-1], 1), "batches_total": self.batches})
if not MIXRUN:
st["es"] = {"wait": int(es.wait), "best": float(es.best), "best_epoch": int(getattr(es, "best_epoch", 0))}
st["rl"] = {"wait": int(rl.wait), "best": float(rl.best), "cooldown_counter": int(rl.cooldown_counter)}
st["mc_best"] = float(mc.best)
elif not self.reason:
# learning-curve point: weights after 25, 50, 75, 100 % of the run (37,504 samples each quarter with batch 32)
self.model.save_weights(os.path.join(a.out, "curve_%d.hdf5" % (self.batches * a.batch)))
ckpt.write(os.path.join(rdir, "ckpt"))
tmp = state_path + ".tmp"
json.dump(st, open(tmp, "w"))
os.replace(tmp, state_path)
say("epoch", epoch + 1, "val_loss", logs.get("val_loss"), "lr", st["lr"], "seconds", round(self.epoch_times[-1], 1), "batches", self.batches)
write_summary("running", True)
ctl = Control()
def write_summary(reason, provisional):
"""train_summary.json is written at every epoch end (provisional) and at the end, so that the prediction tasks find it even after a kill."""
peak = None
try:
if gpus:
peak = tf.config.experimental.get_memory_info("GPU:0")["peak"]
except Exception:
pass
summ = {"run": a.run, "arm": "R1", "stopped_because": reason, "provisional": provisional, "epochs_done": st["epochs_done"], "batches_done": ctl.batches,
"samples_seen": ctl.batches * a.batch, "batch": a.batch, "steps_per_epoch": steps, "train_rows": len(trn), "val_rows": len(val),
"best_val_loss": None if MIXRUN else float(es.best), "best_epoch": None if MIXRUN else int(getattr(es, "best_epoch", 0)) + 1, "final_lr": st["lr"],
"parameters": n_params, "wall_seconds_this_session": round(time.time() - t_start, 1), "wall_seconds_total": round(st["wall_used_s"], 1),
"peak_gpu_bytes": peak, "tensorflow": tf.__version__, "charset_size": len(chars), "history": st["history"],
"stopping_rule": ("fixed budget P_short = 150,016 samples (4 x 1,172 batches of 32), RMSprop 0.001 constant (the paper's learning-rate decay needs validation epochs and cannot act in 4 epochs), batch 32; final weights = 100 % point" if MIXRUN else
"EarlyStopping patience %d on val_loss, ReduceLROnPlateau factor 0.2 patience %d, lr 0.001 RMSprop, batch %d (KOHTD paper 5.2, 5.4)" % (a.stop_patience, a.reduce_patience, a.batch)),
"finished_utc": rc.utc(), "paper_rule_reached": (not provisional) and ((ctl.batches * a.batch >= 150000) if MIXRUN else reason in ("early_stopping", "epoch_limit"))}
tmp = os.path.join(a.out, "train_summary.json.tmp")
json.dump(summ, open(tmp, "w"), indent=1)
os.replace(tmp, os.path.join(a.out, "train_summary.json"))
return summ
def on_term(sig, frm):
STOP["flag"], STOP["why"] = True, "sigterm"
say("SIGTERM received: stopping after the current batch")
signal.signal(signal.SIGTERM, on_term)
signal.signal(signal.SIGINT, on_term)
t0 = time.time()
gen = train_stream_mix(st["epochs_done"] * steps) if MIXRUN else train_stream()
h = model.fit(x=gen, epochs=a.epochs, initial_epoch=st["epochs_done"], steps_per_epoch=steps,
validation_data=None if MIXRUN else val_stream(), validation_steps=None if MIXRUN else vsteps, callbacks=cbs + [ctl], shuffle=True, verbose=2)
reason = ctl.reason or ("early_stopping" if (es is not None and es.stopped_epoch > 0) else ("epoch_limit" if st["epochs_done"] >= a.epochs else "unknown"))
summ = write_summary(reason, False)
say("DONE", reason, "epochs", st["epochs_done"], "samples", summ["samples_seen"])
pool.terminate()
if __name__ == "__main__":
main()