Download src/linedet/lm_decode.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/linedet/lm_decode.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/src/linedet/lm_decode.py
-
curl -L -o lm_decode.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/src/linedet/lm_decode.py
11.4 kB
| """Character n-gram language model decoding of CTC outputs: CTC prefix beam search (beam 16) with a KenLM character model. | |
| The language model (order 6, modified Kneser-Ney, built by lmplz) sees characters as tokens ("words"); the space is the token | |
| "▁". It is trained only on training text. The weight alpha and the per-character insertion bonus beta are tuned on the | |
| kohtd_lmtune set only, per arm and checkpoint. Reads the sparse top-K frame log-probabilities saved by predict.py. | |
| """ | |
| import argparse | |
| import glob | |
| import json | |
| import math | |
| import os | |
| import sys | |
| import time | |
| from multiprocessing import Pool | |
| import numpy as np | |
| from .common import LD_OUT, LOGIT_DIR, PRED_DIR, R5_PROC, cer_wer, load_json, read_manifest, save_json, to_report_text, utcnow, write_tsv | |
| SP_TOKEN = "▁" | |
| NEG = -1e30 | |
| LN10 = math.log(10.0) | |
| _LM = None | |
| _L2C = None | |
| def _init(lm_path, c2l): | |
| global _LM, _L2C | |
| import kenlm | |
| _LM = kenlm.Model(lm_path) | |
| _L2C = {v[0]: k for k, v in c2l.items() if len(v) == 1} | |
| def _lse(a, b): | |
| if a < b: | |
| a, b = b, a | |
| if b <= NEG: | |
| return a | |
| return a + math.log1p(math.exp(b - a)) | |
| def beam_search(idx, lp, alpha, beta, beam=16, prune=-10.0): | |
| """idx (T,K) int labels, lp (T,K) natural-log probabilities (the top-K of each frame), blank is label 0. | |
| Returns the best prefix as a string (NFD).""" | |
| import kenlm | |
| lm = _LM | |
| st0 = kenlm.State() | |
| lm.BeginSentenceWrite(st0) | |
| # prefix -> [p_blank, p_nonblank, lm_total(weighted), state] | |
| beams = {(): [0.0, NEG, 0.0, st0]} | |
| lm_cache = {} | |
| def lm_extend(prefix, c): | |
| key = (prefix, c) | |
| r = lm_cache.get(key) | |
| if r is None: | |
| parent = beams.get(prefix) | |
| pstate = parent[3] if parent is not None else lm_cache[("state", prefix)] | |
| out = kenlm.State() | |
| tok = _L2C.get(c, "") | |
| tok = SP_TOKEN if tok == " " else tok | |
| s = lm.BaseScore(pstate, tok, out) * LN10 | |
| r = (alpha * s + beta, out) | |
| lm_cache[key] = r | |
| return r | |
| for t in range(idx.shape[0]): | |
| cand = {} | |
| ids = idx[t] | |
| lps = lp[t].astype(np.float64) | |
| pb_t = None | |
| for j in range(len(ids)): | |
| if int(ids[j]) == 0: | |
| pb_t = float(lps[j]) | |
| if pb_t is None: | |
| pb_t = -20.0 | |
| for prefix, (pb, pnb, lmt, st) in beams.items(): | |
| tot = _lse(pb, pnb) | |
| # blank | |
| e = cand.get(prefix) | |
| if e is None: | |
| cand[prefix] = [tot + pb_t, NEG, lmt, st] | |
| else: | |
| e[0] = _lse(e[0], tot + pb_t) | |
| for j in range(len(ids)): | |
| c = int(ids[j]) | |
| if c == 0: | |
| continue | |
| p = float(lps[j]) | |
| if p < prune: | |
| continue | |
| last = prefix[-1] if prefix else None | |
| if c == last: | |
| # repeat without blank collapses into the same prefix | |
| e = cand.get(prefix) | |
| if e is None: | |
| cand[prefix] = [NEG, pnb + p, lmt, st] | |
| else: | |
| e[1] = _lse(e[1], pnb + p) | |
| src = pb # a new copy of c needs a blank in between | |
| else: | |
| src = tot | |
| if src <= NEG: | |
| continue | |
| newp = prefix + (c,) | |
| lm_cache[("state", prefix)] = st | |
| add, nst = lm_extend(prefix, c) | |
| e = cand.get(newp) | |
| if e is None: | |
| cand[newp] = [NEG, src + p, lmt + add, nst] | |
| else: | |
| e[1] = _lse(e[1], src + p) | |
| # keep the best `beam` prefixes by total probability plus language-model score | |
| items = sorted(cand.items(), key=lambda kv: _lse(kv[1][0], kv[1][1]) + kv[1][2], reverse=True)[:beam] | |
| beams = {k: v for k, v in items} | |
| # end of sentence term | |
| import kenlm as _k | |
| best, best_s = (), NEG | |
| for prefix, (pb, pnb, lmt, st) in beams.items(): | |
| out = _k.State() | |
| eos = lm.BaseScore(st, "</s>", out) * LN10 | |
| s = _lse(pb, pnb) + lmt + alpha * eos | |
| if s > best_s: | |
| best, best_s = prefix, s | |
| text = "".join(_L2C.get(c, "") for c in best) | |
| return text, (best_s / max(len(best), 1) if best_s > NEG else float("nan")) | |
| def _decode_one(args): | |
| idx, lp, alpha, beta, beam = args | |
| return beam_search(idx, lp, alpha, beta, beam) | |
| def load_npz(path): | |
| z = np.load(path, allow_pickle=False) | |
| lens = z["lens"] | |
| off = np.concatenate([[0], np.cumsum(lens)]) | |
| return z["ids"], lens, off, z["idx"], z["lp"] | |
| def decode_set(pool, npz, alpha, beta, beam, sel=None): | |
| ids, lens, off, idx, lp = npz | |
| sel = range(len(ids)) if sel is None else sel | |
| jobs = [(idx[off[i]:off[i + 1]].astype(np.int64), lp[off[i]:off[i + 1]].astype(np.float32), alpha, beta, beam) for i in sel] | |
| return pool.map(_decode_one, jobs, chunksize=8) # list of (text, normalised score) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--arm", required=True) | |
| ap.add_argument("--ckpt", required=True) | |
| ap.add_argument("--lm", default=LD_OUT + "/lm/char6.klm") | |
| ap.add_argument("--codec", default=LD_OUT + "/codec_union.json") | |
| ap.add_argument("--evalsets", default=R5_PROC + "/evalsets.json") | |
| ap.add_argument("--tune_set", default="", help="name of the lmtune evalset (default: the set whose name contains lmtune)") | |
| ap.add_argument("--beam", type=int, default=16) | |
| ap.add_argument("--max_lines", type=int, default=0, help="cap per evalset for the language-model decoding (seeded random subset); 0 = every line. The validation jobs pass 4000 explicitly; the test pass has no cap (clarification H10)") | |
| ap.add_argument("--test_pass", action="store_true", help="the single scoring pass: decode the test sets that predict.py --test_pass wrote, every crop, alpha and beta taken from the validation tuning, no cap; refused unless the gate file exists") | |
| ap.add_argument("--gate_file", default=LD_OUT + "/test_pass_started.txt") | |
| ap.add_argument("--workers", type=int, default=16) | |
| ap.add_argument("--pred_dir", default=PRED_DIR) | |
| ap.add_argument("--logit_dir", default=LOGIT_DIR) | |
| ap.add_argument("--alphas", default="0.2,0.4,0.7,1.0") | |
| ap.add_argument("--betas", default="0.0,0.5,1.0,1.5") | |
| 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.max_lines: | |
| print("REFUSED: --max_lines (a cap) is not allowed in the test pass") | |
| sys.exit(3) | |
| c2l = load_json(a.codec)["c2l"] | |
| lg_dir = os.path.join(a.logit_dir, a.arm, a.ckpt) | |
| base_dir = os.path.join(a.pred_dir, a.arm, a.ckpt) | |
| out_dir = os.path.join(a.pred_dir, a.arm, a.ckpt + "_lm") | |
| os.makedirs(out_dir, exist_ok=True) | |
| meta0 = load_json(os.path.join(base_dir, "meta_test_pass.json" if a.test_pass else "meta.json")) | |
| sets = list(meta0["per_set"].keys()) | |
| tune = a.tune_set or next((s for s in sets if "lmtune" in s.lower()), None) | |
| fixed_params = None | |
| if a.test_pass: # no tuning in the test pass: alpha and beta are those tuned on the validation set V1lm for this checkpoint | |
| vm = load_json(os.path.join(out_dir, "meta.json")) | |
| fixed_params = vm["tuning"]["best"] | |
| tune = None | |
| t0 = time.time() | |
| with Pool(a.workers, initializer=_init, initargs=(a.lm, c2l)) as pool: | |
| # ---- tune alpha, beta on the lmtune set only | |
| tuned = None | |
| if tune and "cer" in meta0["per_set"].get(tune, {}): | |
| npz = load_npz(os.path.join(lg_dir, tune + ".npz")) | |
| refs = [r["ref"] for r in _read_pred(os.path.join(base_dir, tune + ".tsv"))] | |
| grid = [] | |
| for al in [float(x) for x in a.alphas.split(",")]: | |
| for be in [float(x) for x in a.betas.split(",")]: | |
| hyp = [to_report_text(h) for h, _ in decode_set(pool, npz, al, be, a.beam)] | |
| cer, wer, *_ = cer_wer(refs, hyp) | |
| grid.append({"alpha": al, "beta": be, "cer": cer, "wer": wer}) | |
| print(a.arm, a.ckpt, "tune", al, be, round(cer, 4), flush=True) | |
| grid_greedy = meta0["per_set"][tune]["cer"] | |
| best = min(grid, key=lambda g: g["cer"]) | |
| tuned = {"set": tune, "grid": grid, "best": best, "greedy_cer_on_tune_set": grid_greedy} | |
| alpha, beta = (tuned["best"]["alpha"], tuned["best"]["beta"]) if tuned else (0.0, 0.0) | |
| if fixed_params: | |
| alpha, beta = fixed_params["alpha"], fixed_params["beta"] | |
| tuned = {"from": "validation tuning of this checkpoint (V1lm)", "best": fixed_params} | |
| summary = {} | |
| for s in sets: | |
| if "cer" not in meta0["per_set"][s]: | |
| continue | |
| npz = load_npz(os.path.join(lg_dir, s + ".npz")) | |
| rows = _read_pred(os.path.join(base_dir, s + ".tsv")) | |
| n = len(rows) | |
| sel = list(range(n)) | |
| if a.max_lines and n > a.max_lines: | |
| rng = np.random.default_rng(20261121) | |
| sel = sorted(rng.choice(n, a.max_lines, replace=False).tolist()) | |
| dec = decode_set(pool, npz, alpha, beta, a.beam, sel) | |
| hyp = [to_report_text(h) for h, _ in dec] | |
| scores = [sc for _, sc in dec] | |
| refs = [rows[i]["ref"] for i in sel] | |
| cer, wer, ce, cn, we, wn = cer_wer(refs, hyp) | |
| g_cer, g_wer, *_ = cer_wer(refs, [rows[i]["hyp"] for i in sel]) | |
| write_tsv(os.path.join(out_dir, s + ".tsv"), ["id", "ref", "hyp", "conf", "conf_min", "hit_cap"], | |
| [(rows[i]["id"], rows[i]["ref"], h, "%.4f" % sc, "", 0) for i, h, sc in zip(sel, hyp, scores)]) | |
| summary[s] = {"n": len(sel), "of_total": n, "cer": cer, "wer": wer, "greedy_cer_same_lines": g_cer, "greedy_wer_same_lines": g_wer} | |
| print(a.arm, a.ckpt, s, json.dumps(summary[s]), flush=True) | |
| meta = dict(meta0) | |
| meta.update({"checkpoint": a.ckpt + "_lm", "decoding": "CTC prefix beam search, beam %d, KenLM character 6-gram (modified Kneser-Ney), alpha %.2f, beta %.2f; top-%d labels per frame" % (a.beam, alpha, beta, 6), | |
| "lm": a.lm, "tuning": tuned, | |
| "confidence": "conf = final beam log-score (CTC log-probability plus alpha x language-model log-probability plus beta per character, natural log) divided by the number of characters; conf_min is empty (not defined for the beam); hit_cap = 0", "max_lines_per_set": a.max_lines, "per_set": summary, "created": utcnow(), | |
| "lm_decode_seconds": time.time() - t0}) | |
| save_json(os.path.join(out_dir, "meta_test_pass.json" if a.test_pass else "meta.json"), meta) | |
| try: # clarification H9: gated LM predictions (file work only) | |
| from .lm_gate import gate_all | |
| print("lm_gate:", gate_all(a.pred_dir, [a.arm])) | |
| except Exception as e: | |
| print("lm_gate hook failed:", repr(e)[:200]) | |
| def _read_pred(path): | |
| import csv | |
| with open(path, newline="", encoding="utf-8") as f: | |
| return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)) | |
| if __name__ == "__main__": | |
| main() | |