#!/usr/bin/env python3 """Phase 2: does an Amharic n-gram language model improve CTC decoding? A CTC model emits a probability per character per frame and decides each frame independently. It has no idea what an Amharic word is, so when the audio is ambiguous it will happily emit a character sequence that is not a word. An n-gram LM scores candidate hypotheses during beam search and pulls the output toward sequences that are actually Amharic. This applies to CTC only. Whisper is seq2seq with its own decoder and does not take an external n-gram the same way. Two rules that make the result honest: 1. Every test AND validation sentence is excluded from the LM training text. An LM that has memorised the references makes the score fiction, and the failure is silent: nothing errors, the number just comes out better. 2. alpha and beta are tuned on VALIDATION, never on test. """ from __future__ import annotations import argparse import io import json import re import subprocess import sys import time import unicodedata from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import geez_eval # noqa: E402 import jiwer # noqa: E402 import numpy as np # noqa: E402 import soundfile as sf # noqa: E402 import torch # noqa: E402 from huggingface_hub import HfApi, snapshot_download # noqa: E402 TEST_REPO = "snapwre/amharic-speech" #: Addis AI's open Amharic text, 10.1M rows. Two orders of magnitude more than #: our 660k words of prompts, and the single biggest upgrade available to the LM. TEXT_REPOS = ["b1n1yam/amharic-combined-corpus"] CTC_MODELS = [ "badrex/Ethio-ASR-multilingual-600M", "badrex/Ethio-ASR-multilingual-1B", "badrex/Ethio-ASR-amharic", ] LANG_TAG = re.compile(r"^\s*\[[A-Z]{2,4}\]\s*") PUNCT = re.compile(r"[።፡፣፤፥፦፧፨\.\,\?\!\:\;\"\'\(\)\[\]]") def log(m: str) -> None: print(f"{time.strftime('%H:%M:%S')} {m}", flush=True) def norm(t: str) -> str: return geez_eval.normalize(LANG_TAG.sub("", t or ""), fold_geez=True) def cer_wer(refs, hyps): R = [norm(r) for r in refs] H = [norm(h) for h in hyps] p = [(r, h) for r, h in zip(R, H) if r] return (float(jiwer.cer([r for r, _ in p], [h for _, h in p])), float(jiwer.wer([r for r, _ in p], [h for _, h in p]))) def lm_text(held: set[str]) -> Path: """Amharic text for the LM, with every held-out sentence removed. Exact whole-line matching is not enough and quietly reported 0 drops across 12.8M lines. Our prompts came from news text and this corpus is news and wiki, so a test sentence sitting INSIDE a longer paragraph is a real risk, and it is exactly the kind of leak that raises no error and silently makes every downstream number better than the truth. Aho-Corasick finds them as substrings in one pass. """ out = Path("lm_corpus.txt") seen: set[str] = set() n_lines = n_drop = 0 matcher = None try: import ahocorasick matcher = ahocorasick.Automaton() for h in held: if len(h) >= 20: # short strings would match by coincidence matcher.add_word(h, h) matcher.make_automaton() log(f" substring matcher armed with {len(matcher)} held-out sentences") except Exception as exc: # noqa: BLE001 log(f" ahocorasick unavailable ({exc}); exact match only. " "Treat contamination as UNVERIFIED.") with out.open("w", encoding="utf-8") as fh: for repo in TEXT_REPOS: try: d = Path(snapshot_download(repo, repo_type="dataset")) except Exception as exc: # noqa: BLE001 log(f" could not fetch {repo}: {exc}") continue import pyarrow.parquet as pq files = sorted(d.rglob("*.parquet")) log(f" {repo}: {len(files)} parquet files") for f in files: try: pf = pq.ParquetFile(f) col = next((c for c in pf.schema_arrow.names if c in ("text", "content", "sentence", "article")), None) if col is None: continue for b in pf.iter_batches(batch_size=2000, columns=[col]): for t in b.to_pydict()[col]: for line in (t or "").splitlines(): s = unicodedata.normalize("NFC", line).strip() if s in held or (matcher is not None and any(matcher.iter(s))): n_drop += 1 continue s = re.sub(r"\s+", " ", PUNCT.sub(" ", s)).strip() if len(s) < 5 or s in seen: continue seen.add(s) fh.write(s + "\n") n_lines += 1 except Exception as exc: # noqa: BLE001 log(f" skip {f.name}: {exc}") log(f" LM corpus: {n_lines:,} lines, {n_drop:,} lines dropped as " f"containing a held-out sentence") if matcher is not None and n_drop == 0: log(" 0 drops with substring matching active: the corpus genuinely " "does not contain our test sentences.") return out def build_kenlm(corpus: Path, order: int = 5) -> Path: arpa, binf = Path("am.arpa"), Path("am.bin") # --skip_symbols: the corpus contains literal tokens and lmplz aborts # on them rather than ignoring them. Without this the whole phase dies at # "Special word is not allowed in the corpus". subprocess.run(f"lmplz -o {order} --discount_fallback --skip_symbols " f"-S 40% < {corpus} > {arpa}", shell=True, check=True) subprocess.run(["build_binary", str(arpa), str(binf)], check=True) log(f" KenLM built: {binf.stat().st_size / 1e6:.0f} MB") return binf def audio_of(row): a, sr = sf.read(io.BytesIO(row["audio"]["bytes"]), dtype="float32") return a.mean(axis=1) if a.ndim > 1 else a def load_split(split, limit=None): import pyarrow.parquet as pq d = Path(snapshot_download(TEST_REPO, repo_type="dataset", allow_patterns=[f"data/{split}-*.parquet"])) rows = [] for f in sorted(d.glob(f"data/{split}-*.parquet")): for b in pq.ParquetFile(f).iter_batches(batch_size=64): for r in b.to_pylist(): rows.append(r) if limit and len(rows) >= limit: return rows return rows @torch.inference_mode() def logits_for(mid, rows, bs): from transformers import AutoModelForCTC, AutoProcessor proc = AutoProcessor.from_pretrained(mid) model = AutoModelForCTC.from_pretrained( mid, torch_dtype=torch.float16).to("cuda").eval() outs = [] for i in range(0, len(rows), bs): chunk = [audio_of(r) for r in rows[i:i + bs]] inp = proc(chunk, sampling_rate=16000, return_tensors="pt", padding=True) key = "input_features" if "input_features" in inp else "input_values" lg = model(inp[key].to("cuda", torch.float16)).logits.float().cpu().numpy() outs += [x for x in lg] if (i // bs) % 10 == 0: log(f" logits {min(i + bs, len(rows))}/{len(rows)}") v = proc.tokenizer.get_vocab() del model torch.cuda.empty_cache() return outs, v def labels_from(vocab: dict) -> list[str]: """pyctcdecode wants labels by index, blank as '', word delimiter as ' '.""" out = [""] * (max(vocab.values()) + 1) for tok, i in vocab.items(): if tok in ("", "", "", ""): out[i] = "" elif tok == "|": out[i] = " " else: out[i] = tok return out def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--push-to", default="snapwre/amharic-asr-benchmark") ap.add_argument("--run", default=time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())) ap.add_argument("--batch-size", type=int, default=16) ap.add_argument("--tune-n", type=int, default=400) args = ap.parse_args() # HfApi() with no token picks up the ambient HF_TOKEN, which here is the # collaborator's READ token for the private audio repo. It cannot write to # our namespace, so every push 404s with "Repository Not Found". Same # ambient-token precedence bug that cost the download workers a day. import os api = HfApi(token=os.environ.get("HF_PUSH_TOKEN") or None) test, val = load_split("test"), load_split("validation") held = {unicodedata.normalize("NFC", r["sentence"]).strip() for r in test + val} log(f"test {len(test)}, validation {len(val)}, {len(held):,} held-out sentences") log("building LM corpus") corpus = lm_text(held) lm = build_kenlm(corpus) from pyctcdecode import build_ctcdecoder tune = val[:args.tune_n] out = {"run": args.run, "lm_corpus_lines": sum(1 for _ in corpus.open()), "models": {}} for mid in CTC_MODELS: log(f"== {mid}") try: lg_t, vocab = logits_for(mid, test, args.batch_size) labels = labels_from(vocab) greedy = [] for x in lg_t: ids = x.argmax(-1) prev, s = -1, [] for i in ids: if i != prev and labels[i]: s.append(labels[i]) prev = i greedy.append("".join(s)) g_cer, g_wer = cer_wer([r["sentence"] for r in test], greedy) log(f" greedy CER {g_cer:.4f} WER {g_wer:.4f}") lg_v, _ = logits_for(mid, tune, args.batch_size) best = None for a in (0.3, 0.5, 0.8): for b in (0.5, 1.5): dec = build_ctcdecoder(labels, str(lm), alpha=a, beta=b) hy = [dec.decode(x) for x in lg_v] c, _ = cer_wer([r["sentence"] for r in tune], hy) log(f" tune a={a} b={b} val CER {c:.4f}") if best is None or c < best[0]: best = (c, a, b) _, A, B = best dec = build_ctcdecoder(labels, str(lm), alpha=A, beta=B) hy = [dec.decode(x) for x in lg_t] l_cer, l_wer = cer_wer([r["sentence"] for r in test], hy) log(f" +KenLM CER {l_cer:.4f} WER {l_wer:.4f} " f"(alpha={A}, beta={B})") out["models"][mid] = { "greedy_cer": g_cer, "greedy_wer": g_wer, "lm_cer": l_cer, "lm_wer": l_wer, "alpha": A, "beta": B, "cer_rel_gain": (g_cer - l_cer) / g_cer if g_cer else None, "wer_rel_gain": (g_wer - l_wer) / g_wer if g_wer else None, } except Exception as exc: # noqa: BLE001 import traceback traceback.print_exc() out["models"][mid] = {"error": f"{type(exc).__name__}: {exc}"} p = Path("/tmp/lm_results.json") p.write_text(json.dumps(out, indent=2)) try: api.upload_file(path_or_fileobj=str(p), repo_id=args.push_to, repo_type="dataset", path_in_repo=f"runs/{args.run}/lm_results.json") log(" pushed lm_results.json") except Exception as exc: # noqa: BLE001 log(f" push failed: {exc}") try: api.upload_file(path_or_fileobj=str(lm), repo_id=args.push_to, repo_type="dataset", path_in_repo="kenlm/am-5gram.bin") log("pushed the KenLM binary") except Exception as exc: # noqa: BLE001 log(f"LM upload failed: {exc}") if __name__ == "__main__": main()