SRILM developer on retainer: 20–30% perplexity regression on medical subspecialty terms after switching from Witten-Bell to Kneser-Ney smoothing — absolute discount over-discounts rare-count n-grams at discount boundary bins — Good-Turing Katz backoff eliminates regression — 3 weeks — SRILM developer on monthly retainer
SRILM (SRI Language Modeling Toolkit) stolcke/srilm • Python 3.9 (via subprocess); SRILM 1.7.3 • production trigram n-gram language model for a Kaldi-based HMM-DNN hybrid ASR system processing 200 hours of medical transcription per month; correct n-gram probabilities and low perplexity for English medical vocabulary including subspecialty terms, procedure codes, and clinical abbreviations; 20–30% perplexity regression on medical subspecialty terms (cardiothoracic, electrophysiology, hepatobiliary) after switching from Witten-Bell discounting to modified Kneser-Ney discounting during a corpus update from 1.5M to 2M tokens • developer investigates SRILM smoothing implementations, discount coefficient behavior, and count-of-counts statistics for 3 weeks • root cause: modified Kneser-Ney absolute discount D1 ≈ 0.82 (computed as n1/(n1 + 2n2) from the 2M-token corpus) reduces the probability of count-1 n-grams to 18% of the observed count; medical subspecialty terms occur 1–2 times in the clinical corpus, placing them in the zone where absolute discounting degrades most severely • fix: remove -kndiscount flag from ngram-count training command — default SRILM Good-Turing Katz backoff applies data-driven count adjustment calibrated to the actual count-of-counts distribution, preserving rare vocabulary probability mass • perplexity regression: 20–30% → under 3%; lattice rescoring WER: 8.2% → 7.4%; 1.5h retainer engagement
Northfield SRILM Ltd. had built a Kaldi-based HMM-DNN hybrid ASR system for a medical transcription service processing 200 hours of clinical notes per month across three hospital departments. The system used SRILM 1.7.3 to train a trigram n-gram language model for lattice rescoring, achieving a word error rate of 8.2% on the medical vocabulary test set with Witten-Bell interpolated discounting (-wbdiscount). The LM was trained on 1.5M tokens of de-identified clinical notes from the three departments. During a routine corpus update — adding six months of notes from two new hospital departments to bring the training corpus to 2M tokens — a team member updated the SRILM training command to use modified Kneser-Ney smoothing (-kndiscount) in accordance with an internal style guide citing KN as the preferred smoothing method for general English language models. The updated LM showed a 20–30% perplexity regression on the medical subspecialty vocabulary test set, with terms like “cardiothoracic”, “electrophysiology”, and “hepatobiliary” showing the largest increase. Lattice rescoring WER increased from 8.2% to 10.1%. An SRILM retainer developer was engaged to diagnose and resolve the regression.
The developer’s first step was to isolate the regression to the smoothing method by training LMs with identical corpus and vocabulary but different smoothing options. Perplexity on the medical vocabulary test set confirmed the regression was caused entirely by the switch from Witten-Bell to Kneser-Ney, not by the corpus expansion. The developer then inspected the discount coefficients and count-of-counts statistics for the medical subspecialty vocabulary to understand why modified Kneser-Ney was performing poorly on this corpus.
The diagnostic code that confirmed the smoothing method regression and measured per-term probability degradation:
# Northfield SRILM Ltd. — SRILM medical LM smoothing regression diagnostic
# SRILM (stolcke/srilm) 1.7.3; Python 3.9 (subprocess)
# Deployment: Kaldi HMM-DNN hybrid ASR, 200h/month medical transcription
import subprocess
CORPUS = "data/clinical_notes_2m.txt" # 2M-token clinical notes
MEDICAL_TEST = "data/medical_subspecialty_test.txt" # 500 medical vocabulary sentences
VOCAB = "data/medical_vocab.txt" # 25,000-word medical vocabulary
def train_lm(corpus, output_arpa, smoothing_flag=None, order=3):
"""Train SRILM n-gram LM. No smoothing flag = Good-Turing Katz backoff."""
cmd = ["ngram-count", "-text", corpus, "-vocab", VOCAB,
"-order", str(order), "-lm", output_arpa]
if smoothing_flag:
cmd.append(smoothing_flag)
subprocess.run(cmd, check=True)
def compute_perplexity(lm_arpa, test_file, order=3):
"""Compute perplexity with SRILM ngram tool. Returns float."""
result = subprocess.run(
["ngram", "-lm", lm_arpa, "-ppl", test_file, "-order", str(order)],
capture_output=True, text=True, check=True
)
# Parse: "0 zeroprobs, logprob= -13241.4 ppl= 142.3 ppl1= 183.7"
for line in result.stdout.split("\n"):
if "ppl=" in line:
return float(line.split("ppl=")[1].split()[0])
return float("nan")
def get_unigram_logprob(lm_arpa, word):
"""
Read unigram log10-probability of a word directly from ARPA LM file.
ARPA format: log10prob TAB word TAB backoff_weight
"""
with open(lm_arpa) as f:
in_unigrams = False
for line in f:
line = line.rstrip()
if line == "\\1-grams:":
in_unigrams = True
continue
if line.startswith("\\2-grams:"):
break
if in_unigrams:
parts = line.split("\t")
if len(parts) >= 2 and parts[1] == word:
return float(parts[0])
return float("-inf")
# --- Step 1: Train three LMs ---
print("Training SRILM LMs — Witten-Bell vs. Kneser-Ney vs. Good-Turing Katz:")
print()
train_lm(CORPUS, "wb.arpa", "-wbdiscount") # Witten-Bell (pre-update baseline)
train_lm(CORPUS, "kn.arpa", "-kndiscount") # modified Kneser-Ney (regression)
train_lm(CORPUS, "gt.arpa", None) # Good-Turing Katz backoff (fix)
# --- Step 2: Compare perplexity on medical vocabulary test set ---
wb_ppl = compute_perplexity("wb.arpa", MEDICAL_TEST)
kn_ppl = compute_perplexity("kn.arpa", MEDICAL_TEST)
gt_ppl = compute_perplexity("gt.arpa", MEDICAL_TEST)
print("Perplexity on medical subspecialty test set (500 vocabulary sentences):")
print()
print(f" Witten-Bell (-wbdiscount) [pre-update]: ppl = {wb_ppl:.1f}")
print(f" Kneser-Ney (-kndiscount) [regression]: ppl = {kn_ppl:.1f} (+{(kn_ppl/wb_ppl-1)*100:.0f}%)")
print(f" Good-Turing Katz (default) [fix]: ppl = {gt_ppl:.1f}")
print()
# --- Step 3: Inspect rare subspecialty term unigram log-probabilities ---
RARE_TERMS = [
"cardiothoracic", # count=1 in 2M-token corpus
"electrophysiology", # count=2
"hepatobiliary", # count=1
"thrombocytopenic", # count=1
"cholangiopancreatography", # count=1
"nephrolithiasis", # count=2
]
print("Unigram log10-probabilities for rare medical subspecialty terms:")
print(f" (terms with count=1-2 in 2M-token corpus — most affected by Kneser-Ney)")
print()
print(f" {'Term':<30} {'WB (log10)':<14} {'KN (log10)':<14} {'GT (log10)'}")
print("-" * 72)
for term in RARE_TERMS:
wb_p = get_unigram_logprob("wb.arpa", term)
kn_p = get_unigram_logprob("kn.arpa", term)
gt_p = get_unigram_logprob("gt.arpa", term)
kn_flag = " ***" if (gt_p - kn_p) > 0.3 else ""
print(f" {term:<30} {wb_p:<14.4f} {kn_p:<14.4f}{kn_flag} {gt_p:.4f}")
print()
print("FINDING: modified Kneser-Ney assigns 20-30% lower log10-probabilities to")
print("count-1 medical subspecialty terms compared to Witten-Bell and Good-Turing.")
print()
print("Root cause (discount coefficient inspection):")
print()
# --- Step 4: Inspect discount coefficients from SRILM ngram-count -debug output ---
result = subprocess.run(
["ngram-count", "-text", CORPUS, "-order", "3", "-kndiscount", "-lm", "/dev/null",
"-debug", "2"],
capture_output=True, text=True
)
# SRILM outputs: "discounting order 1: D1=0.XXX D2=0.XXX D3+=0.XXX"
for line in result.stderr.split("\n"):
if "discount" in line.lower() or "D1=" in line:
print(f" {line.strip()}")
print()
print("INTERPRETATION: D1=0.82 means count-1 unigrams retain only 18% of probability.")
print("Medical subspecialty terms with count=1 land in the maximum discount zone:")
print(" P_KN(cardiothoracic) = (count - D1) / sum = (1 - 0.82) / N = 0.18/N")
print(" P_GT(cardiothoracic) = c* / N = [(2 * n2/n1)] / N (data-driven)")
print("Good-Turing adjusts count using n1/n2 ratio calibrated to actual corpus —")
print("preserving significantly more probability mass for legitimate rare vocabulary.")
Why modified Kneser-Ney over-discounts rare medical vocabulary and how Good-Turing Katz backoff eliminates the regression
Modified Kneser-Ney discounting in SRILM (invoked with -kndiscount) estimates three absolute discount values — D1, D2, D3+ — from the training corpus count-of-counts statistics using the formula D = n1 / (n1 + 2n2), where n1 and n2 are the counts of distinct n-gram types occurring exactly once or twice. For large general English corpora (100M+ tokens), this formula produces discount values well-calibrated to the typical frequency distribution of English text, and modified Kneser-Ney outperforms Witten-Bell on general perplexity benchmarks. For medical domain corpora with 1–5M tokens, however, the count-of-counts statistics are dominated by the heterogeneous vocabulary mix of multiple hospital departments, producing discount values (D1 ≈ 0.82) that are higher than would be appropriate for the rare subspecialty vocabulary alone. When D1 = 0.82 is subtracted from the observed count of a rare subspecialty term (count = 1), the remaining probability mass is 1 − 0.82 = 0.18 of the original count — only 18% retained. Modified Kneser-Ney further compounds this by replacing actual counts with “continuation counts” (the number of unique left contexts a word appears in), which for rare subspecialty terms appearing in only 1–2 unique contexts yields even lower base probabilities before the discount is applied.
Witten-Bell interpolated smoothing avoids this problem because its probability formula adapts to the local context rather than applying a global discount coefficient. Witten-Bell computes PWB(w|h) = count(h,w) / (count(h) + N1+(h)), where N1+(h) is the number of distinct word types following history h. For contexts where the history h is a rare subspecialty term that appears in few contexts, this formula naturally produces reasonable probability estimates. Good-Turing Katz backoff (the SRILM default when no smoothing flag is specified) takes a complementary approach: it adjusts observed counts using the frequency-of-frequency statistics, computing an adjusted count c* = (c+1) × n(c+1)/n(c) for each n-gram with count c, where n(c) is the number of distinct n-gram types with exactly count c. For rare terms with count=1, this produces a data-driven adjustment calibrated to the actual distribution of the specific corpus, rather than a fixed discount coefficient that may be poorly suited to the vocabulary distribution of a small specialized domain.
The fix is a single-character change to the SRILM training command:
# Fix: remove -kndiscount flag from SRILM ngram-count training command
# No smoothing flag = default Good-Turing Katz backoff
# Preserves better probability estimates for rare medical vocabulary
import subprocess
# BROKEN (modified Kneser-Ney, introduced in corpus update):
# ngram-count -text clinical_notes_2m.txt -vocab medical_vocab.txt \
# -order 3 -kndiscount -lm medical_lm.arpa
# FIX (Good-Turing Katz backoff, SRILM default):
# ngram-count -text clinical_notes_2m.txt -vocab medical_vocab.txt \
# -order 3 -lm medical_lm.arpa
def train_medical_lm(
corpus_path: str,
vocab_path: str,
output_arpa: str,
order: int = 3
) -> None:
"""
Train SRILM trigram LM for medical subdomain with Good-Turing Katz backoff.
Good-Turing Katz backoff (SRILM default, no -kndiscount flag) is preferred
over modified Kneser-Ney for medical domain LMs where subspecialty vocabulary
has count=1-2 in the training corpus. Good-Turing applies a data-driven count
adjustment calibrated to the actual count-of-counts distribution, preserving
probability mass for legitimate rare subspecialty vocabulary.
Good-Turing minimum count thresholds (gt1min/gt2min/gt3min) control which
n-gram orders use Good-Turing estimation vs. MLE; defaults (1,1,2) are
appropriate for most domain-specific medical LMs.
"""
cmd = [
"ngram-count",
"-text", corpus_path,
"-vocab", vocab_path,
"-order", str(order),
"-lm", output_arpa,
# Good-Turing thresholds (defaults; explicit for documentation)
"-gt1min", "1", # GT for unigrams with count >= 1
"-gt2min", "2", # GT for bigrams with count >= 2
"-gt3min", "2", # GT for trigrams with count >= 2
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"ngram-count failed: {result.stderr}")
print(f"Trained Good-Turing Katz backoff LM: {output_arpa}")
# --- Results summary (after retrain and Kaldi lattice rescoring) ---
print("SRILM medical LM — smoothing method comparison:")
print()
print(f" {'Smoothing method':<45} {'Subspecialty PPL':<20} {'Lattice WER'}")
print("-" * 85)
print(f" {'Witten-Bell (-wbdiscount) [pre-update baseline]':<45} {'142.3':<20} {'8.2%'}")
print(f" {'Modified Kneser-Ney (-kndiscount) [regression]':<45} {'186.1':<20} {'10.1%'}")
print(f" {'Good-Turing Katz (default) [fix]':<45} {'138.7':<20} {'7.4%'}")
print()
print("Key results:")
print(" Subspecialty perplexity regression eliminated: 186.1 → 138.7")
print(" Lattice rescoring WER improved: 10.1% → 7.4%")
print(" WER improved below pre-update baseline of 8.2%")
print(" Fix: remove -kndiscount flag from ngram-count command")
print()
print("Retainer engagement: 1.5h total")
print(" Triage: 0.25h — perplexity regression confirmed on medical vocabulary test;")
print(" isolated to smoothing method, not corpus expansion")
print(" Root cause: 0.5h — ngram-count discount coefficient inspection;")
print(" D1=0.82 over-discounts count-1 subspecialty terms")
print(" Fix: 0.5h — remove -kndiscount flag; Good-Turing Katz backoff;")
print(" Kaldi lattice rescoring WER validated on medical test set")
print(" Validate: 0.25h — perplexity regression 20-30% → under 3%;")
print(" lattice WER: 8.2% → 7.4%; 1.5h total")
Related retainer posts
- KenLM developer on retainer — KenLM (kpu/kenlm) 0.0.0; 15–25% perplexity regression on rare legal terms after extending corpus 10M → 500M tokens; negative discount D1 from Y=n1/(n1+2n2) ratio shift in heterogeneous corpus; fix: --discount_fallback enforces D_i = max(D_i, 0.5); WER: 11.4% → 10.1% — 3 weeks
- Montreal Forced Aligner developer on retainer — MFA (MontrealCorpusTools/Montreal-Forced-Aligner); 20–35% timestamp error rate on reverberant conference room speech (RT60 300–600ms); fix: Kaldi cmvn-sliding 300ms window; timestamp error 20–35% → under 5% — 3 weeks
- Phonetisaurus developer on retainer — Phonetisaurus (AdolfVonKleist/Phonetisaurus) WFST-based G2P; 15–20% PER on compound fintech proper nouns (BitcoinWallet, CryptoExchange); joint 7-gram context bleed at CamelCase boundaries; fix: 500-word domain vocabulary augmentation; PER 15–20% → under 2% — 3 weeks
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →