File size: 11,426 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 | """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()
|