File size: 4,886 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 | """Gated language-model predictions (clarification H9): <checkpoint>_lm_gated.
Per row: the LM output where the greedy output is non-empty, the empty string where the greedy output is empty. "Empty" means no character other than white
space (str.strip() == ""); until 23 Nov 2026 only the exact empty string counted, and a greedy output of one space let the LM text through (545 rows in 3 folders,
found by a PAGES check on A2 long2x synth_clutter_val). Pure file work, no model run, no tuned
parameter. Same columns as every prediction file; conf = the LM conf where the LM output is kept and the greedy conf (and conf_min) where the
output is emptied. Rows are those of the <checkpoint>_lm file (which holds at most 4,000 random lines per set). Applies to every
preds/<label>/<checkpoint> that has a <checkpoint>_lm folder; idempotent (rewrites when an input is newer).
Usage: python -m linedet.lm_gate [--labels A1,A2,...] [--pred_dir DIR] [--force] (--force rewrites even when the output file is newer than its inputs)
"""
import argparse
import csv
import os
from .common import PRED_DIR, cer_wer, load_json, save_json, utcnow, write_tsv
LABELS = ["A1", "A2", "A3", "A4", "A1s", "A1_s2", "A2_s2", "A4b"]
def read(path):
with open(path, newline="", encoding="utf-8") as f:
return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))
def is_empty(h):
"""H9: a plain output with no character other than white space counts as empty"""
return h.strip() == ""
def gate_one(pred_dir, label, ck, force=False):
gd, ld, od = [os.path.join(pred_dir, label, x) for x in (ck, ck + "_lm", ck + "_lm_gated")]
if not os.path.isdir(ld) or not os.path.isdir(gd):
return None
meta = load_json(os.path.join(ld, "meta.json")) if os.path.exists(os.path.join(ld, "meta.json")) else {}
old = os.path.join(od, "meta.json")
per_set = dict(load_json(old).get("per_set", {})) if os.path.exists(old) else {}
n_sets = 0
for f in sorted(os.listdir(ld)):
if not f.endswith(".tsv"):
continue
s = f[:-4]
gp = os.path.join(gd, f)
if not os.path.exists(gp):
continue
out = os.path.join(od, f)
if not force and os.path.exists(out) and os.path.getmtime(out) >= max(os.path.getmtime(gp), os.path.getmtime(os.path.join(ld, f))):
per_set.setdefault(s, {"kept_from_earlier_run": True})
continue
greedy = {r["id"]: r for r in read(gp)}
rows, refs, hyps, n_emptied = [], [], [], 0
for r in read(os.path.join(ld, f)):
g = greedy.get(r["id"])
if g is None:
continue
if is_empty(g["hyp"]):
hyp, conf, cmin = "", g.get("conf", ""), g.get("conf_min", "")
n_emptied += 1
else:
hyp, conf, cmin = r["hyp"], r.get("conf", ""), r.get("conf_min", "")
rows.append((r["id"], r["ref"], hyp, conf, cmin, 0))
refs.append(r["ref"])
hyps.append(hyp)
write_tsv(out, ["id", "ref", "hyp", "conf", "conf_min", "hit_cap"], rows)
cer, wer, *_ = cer_wer(refs, hyps)
per_set[s] = {"n": len(rows), "cer": cer, "wer": wer, "rows_emptied_because_greedy_was_empty_or_blank": n_emptied}
n_sets += 1
if per_set:
m = dict(meta)
m.update({"checkpoint": ck + "_lm_gated", "per_set": per_set, "created": utcnow(),
"decoding": (meta.get("decoding", "") + " | gated (clarification H9): LM output where the greedy output is non-empty (not blank), empty string otherwise; conf of emptied rows = greedy conf"),
"gated_from": {"greedy": gd, "lm": ld}, "gate_rule_version": "23 Nov 2026: empty = white space only counts as empty"})
save_json(os.path.join(od, "meta.json"), m)
return n_sets
def gate_all(pred_dir=PRED_DIR, labels=None, force=False):
done = {}
for label in (labels or LABELS):
ld = os.path.join(pred_dir, label)
if not os.path.isdir(ld):
continue
for ck in sorted(os.listdir(ld)):
if ck.endswith("_lm") or ck.endswith("_lm_gated"):
continue
try:
n = gate_one(pred_dir, label, ck, force)
except Exception as e: # never break the caller
print("lm_gate failed for", label, ck, repr(e)[:200])
continue
if n:
done["%s/%s" % (label, ck)] = n
return done
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--labels", default="")
ap.add_argument("--pred_dir", default=PRED_DIR)
ap.add_argument("--force", action="store_true")
a = ap.parse_args()
done = gate_all(a.pred_dir, [x for x in a.labels.split(",") if x] or None, a.force)
print("gated:", done)
if __name__ == "__main__":
main()
|