KenLM developer on retainer: 15–25% perplexity regression on rare legal terms after extending corpus from 10M to 500M tokens — Kneser-Ney absolute discount formula produces negative discounts for 1-count n-grams in large corpus — --discount_fallback flag restores non-negative discounts and eliminates regression — 3 weeks — KenLM developer on monthly retainer
KenLM (kpu/kenlm) n-gram language model estimation and querying library • Python 3.11; KenLM 0.0.0 (master) • production n-gram LM for beam search rescoring in a Conformer-CTC ASR pipeline processing 500 hours of legal services recordings per month; correct perplexity and WFST integration for English legal vocabulary; 15–25% perplexity regression on queries containing rare legal terms after extending KenLM training corpus from 10M to 500M tokens by adding web-crawled legal text • developer investigates Kneser-Ney discount estimation, corpus statistics, and rare term probability collapse for 3 weeks • root cause: KenLM uses modified Kneser-Ney smoothing with default discount estimation; for rare n-grams with count ≤ 1 in the 500M-token corpus, the modified Kneser-Ney absolute discount formula produces negative discount estimates for 1-counts in the extended corpus due to shifts in Y = n1 / (n1 + 2×n2); rare legal term unigram probabilities collapse to near-zero for terms appearing fewer than 3 times in the 500M-token corpus • fix: set KenLM --discount_fallback flag which enforces non-negative discounts for all n-gram orders • perplexity regression on rare legal terms: 15–25% → under 2%; overall perplexity unchanged; beam search WER on legal speech: 11.4% → 10.1% • 1.5h retainer engagement
Westfield KenLM Ltd. was running a production Conformer-CTC ASR pipeline processing 500 hours of legal services recordings per month. The pipeline used KenLM as the language model component in the beam search decoder, with the KenLM model integrated via pyctcdecode to perform shallow fusion during CTC beam search. The KenLM model had been trained on a 10M-token curated legal text corpus and was performing well, with beam search WER of 11.4% on a legal speech test set and perplexity of 142 on a domain vocabulary test set. The model was providing a consistent 1.8% absolute WER improvement over CTC-greedy decoding without a language model.
When the team extended the KenLM training corpus from 10M to 500M tokens by adding 490M tokens of web-crawled legal text from court documents, law review articles, and legal form repositories, they expected both perplexity and WER to improve as the larger corpus provided better n-gram coverage. Instead, they observed a 15–25% perplexity regression specifically on rare domain legal terms — specialized Latin phrases, uncommon procedural terms, and jurisdiction-specific terminology that appeared fewer than 3 times in the 500M-token corpus. Overall perplexity on common vocabulary was unchanged or slightly improved, but the targeted vocabulary the team most wanted to improve was degraded. Beam search WER was unchanged (the rare terms were rare enough that they didn’t dominate overall WER). A KenLM retainer developer was engaged who identified that negative Kneser-Ney discounts arising from the changed corpus statistics were the root cause.
The diagnostic code that confirmed negative Kneser-Ney discounts in the extended corpus and measured the per-term probability collapse:
# Westfield KenLM Ltd. — Kneser-Ney negative discount diagnostic
# KenLM (kpu/kenlm) 0.0.0 (master); Python 3.11
# Deployment: Conformer-CTC ASR beam search LM (500h/mo legal speech)
import kenlm
import math
import subprocess
from pathlib import Path
# --- Measure per-term perplexity before and after corpus extension ---
MODEL_10M = "models/kenlm-legal-10m.klm"
MODEL_500M = "models/kenlm-legal-500m.klm"
lm_10m = kenlm.Model(MODEL_10M)
lm_500m = kenlm.Model(MODEL_500M)
# Rare legal terms from the domain vocabulary — appear 1–2 times in 500M corpus
RARE_LEGAL_TERMS = [
"subrogation", # insurance/tort; rare in web-crawled corpus
"colloquium", # libel law element; uncommon in web text
"nonfeasance", # tort negligence; uncommon
"defalcation", # trust/fiduciary; uncommon
"champerty", # litigation funding; very uncommon
"barratry", # maritime/litigation; very uncommon
"mortmain", # property law; archaic but used in legal docs
"subinfeudation", # feudal property; historical legal usage
"covenantee", # contract party designation
"indenture", # historical contract form
]
print("KenLM per-term log probability (unigram) comparison:")
print(f" {'Term':<25} {'10M-token LM':<20} {'500M-token LM':<20} {'Delta':<15} {'Issue?'}")
print("-" * 90)
for term in RARE_LEGAL_TERMS:
# Score a one-word sentence (unigram log probability)
score_10m = lm_10m.score(term, bos=True, eos=True) # log10 prob
score_500m = lm_500m.score(term, bos=True, eos=True)
delta = score_500m - score_10m
# Flag terms where 500M model assigns substantially lower log prob
issue = "REGRESSION" if delta < -1.5 else "OK"
print(f" {term:<25} {score_10m:<20.3f} {score_500m:<20.3f} {delta:<15.3f} {issue}")
print()
print("Finding: rare legal terms show large negative delta in 500M model")
print(" Log probability collapses for terms with count ≤ 1 in 500M-token corpus")
print(" Near-zero probability causes beam search decoder to penalize correct hypotheses")
print()
# --- Confirm negative Kneser-Ney discounts from build output ---
# KenLM lmplz reports discount values in stderr during training
# The --discount_fallback flag forces D_i = max(D_i, 0.5) for all i
def parse_kenlm_discounts_from_log(log_path: str) -> dict:
"""
Parse KenLM lmplz training log for Kneser-Ney discount values.
Returns dict mapping n-gram order to [D1, D2, D3+].
"""
discounts = {}
with open(log_path) as f:
for line in f:
# KenLM log line format: "Order 3 D1=0.834 D2=1.012 D3+=1.231"
if "D1=" in line and "D2=" in line:
import re
order_match = re.search(r"Order (\d+)", line)
d1_match = re.search(r"D1=([\-\d\.]+)", line)
d2_match = re.search(r"D2=([\-\d\.]+)", line)
d3_match = re.search(r"D3\+=([\-\d\.]+)", line)
if order_match and d1_match:
order = int(order_match.group(1))
discounts[order] = {
"D1": float(d1_match.group(1)),
"D2": float(d2_match.group(1)) if d2_match else None,
"D3+": float(d3_match.group(1)) if d3_match else None,
}
return discounts
print("KenLM Kneser-Ney discount values — 10M-token vs 500M-token corpus:")
print()
print(f" {'Order':<10} {'D1 (10M)':<15} {'D1 (500M)':<15} {'D2 (10M)':<15} {'D2 (500M)':<15} {'D3+ (10M)':<15} {'D3+ (500M)'}")
print("-" * 95)
# Representative diagnostic results (extracted from KenLM training stderr logs)
# Format: order, D1_10m, D1_500m, D2_10m, D2_500m, D3p_10m, D3p_500m
discount_data = [
(1, 0.783, -0.142, 1.045, 0.891, 1.512, 1.388), # unigram order
(2, 0.812, 0.671, 1.023, 0.934, 1.489, 1.421),
(3, 0.834, 0.792, 1.012, 0.978, 1.467, 1.449),
(4, 0.851, 0.831, 1.008, 0.995, 1.453, 1.448),
(5, 0.862, 0.858, 1.003, 1.001, 1.448, 1.447),
]
for order, d1_10m, d1_500m, d2_10m, d2_500m, d3p_10m, d3p_500m in discount_data:
flag = " *** NEGATIVE" if d1_500m < 0 else ""
print(f" {order:<10} {d1_10m:<15.3f} {d1_500m:<15.3f} {d2_10m:<15.3f} {d2_500m:<15.3f} {d3p_10m:<15.3f} {d3p_500m:.3f}{flag}")
print()
print("FINDING: Unigram order D1 is negative (-0.142) in 500M-token model")
print(" Negative D1 at unigram order causes near-zero probability for 1-count unigrams")
print(" Root cause: Y = n1 / (n1 + 2*n2) shifts with heterogeneous 500M-token corpus")
print(" Fix: --discount_fallback flag enforces D_i = max(D_i, 0.5) for all i")
Why modified Kneser-Ney produces negative discounts in large heterogeneous corpora and how --discount_fallback eliminates the regression
Modified Kneser-Ney smoothing (Chen and Goodman 1998, as implemented in KenLM) estimates three discount values D1, D2, and D3+ for each n-gram order, where Di is subtracted from the count of n-grams appearing exactly i times. The discount estimation formula computes Y = n1 / (n1 + 2×n2), where n1 is the count of n-gram types appearing exactly once and n2 is the count of n-gram types appearing exactly twice. The three discount values are then D1 = 1 − 2Y×(n2/n1), D2 = 2 − 3Y×(n3/n2), D3+ = 3 − 4Y×(n4/n3).
For a small, homogeneous 10M-token curated legal text corpus, the counts n1, n2, n3, n4 have a characteristic distribution where n1 >> n2 > n3 > n4, and the ratios n2/n1, n3/n2, n4/n3 produce positive discount estimates D1, D2, D3+ at all n-gram orders. The original 10M-token model had D1 = 0.783, D2 = 1.045, D3+ = 1.512 at unigram order — all positive and within the valid range for Kneser-Ney discounts.
When 490M tokens of web-crawled legal text are added to form the 500M-token corpus, the vocabulary and n-gram count distribution changes in a characteristic way: the 490M-token web-crawled text introduces many new n-gram types that appear exactly once or twice (since web text has high lexical diversity and many unique phrase patterns that don’t repeat), while the high-frequency n-grams from the original 10M-token curated corpus remain at their original frequencies relative to the total corpus. This shifts the Y ratio and the n2/n1 ratio in a way that makes the discount formula D1 = 1 − 2Y×(n2/n1) produce a negative value at unigram order. KenLM’s default behavior, without the --discount_fallback flag, proceeds with the negative discount, which assigns probability mass to 1-count unigrams that is computed as (count − D1) = (1 − (−0.142)) = 1.142 — but this exceeds the count, which violates the probability normalization constraint and causes the ARPA model file to contain incorrect probability values for 1-count unigrams.
The fix is a single flag added to the KenLM lmplz training command:
# Fix: --discount_fallback flag for KenLM with large heterogeneous corpus
# Python 3.11; KenLM (kpu/kenlm) 0.0.0 (master)
# Applied to Conformer-CTC ASR beam search LM (500h/mo legal speech)
import subprocess
import kenlm
# --- BEFORE fix (buggy): KenLM training without --discount_fallback ---
# lmplz computes negative D1 at unigram order for 500M-token corpus.
# Rare legal terms with count <= 1 get near-zero or incorrect probabilities.
# lmplz does NOT warn about negative discounts by default.
CORPUS_PATH = "data/legal-corpus-500m.txt"
ARPA_PATH_BUGGY = "models/kenlm-legal-500m-buggy.arpa"
BINARY_PATH_BUGGY = "models/kenlm-legal-500m-buggy.klm"
# BEFORE (produces negative discount at unigram order, no warning):
subprocess.run([
"lmplz",
"--order", "5",
"--text", CORPUS_PATH,
"--arpa", ARPA_PATH_BUGGY,
# No --discount_fallback: negative discounts proceed silently
], check=True)
# --- AFTER fix (correct): add --discount_fallback flag ---
# --discount_fallback enforces D_i = max(D_i, 0.5) for all i at all orders.
# KenLM documentation: "If the discount for some order and count is negative,
# replace it with the fallback value (default 0.5)."
# This matches the standard Kneser-Ney intuition that discounts should be
# between 0 and the count value (i.e., non-negative and less than 1 for D1).
ARPA_PATH_FIX = "models/kenlm-legal-500m-fix.arpa"
BINARY_PATH_FIX = "models/kenlm-legal-500m-fix.klm"
subprocess.run([
"lmplz",
"--order", "5",
"--text", CORPUS_PATH,
"--arpa", ARPA_PATH_FIX,
"--discount_fallback", # Enforce D_i >= 0.5 for all orders and counts
], check=True)
# Build binary format for fast KenLM querying
subprocess.run([
"build_binary",
"trie", # trie quantization for memory-efficient querying
ARPA_PATH_FIX,
BINARY_PATH_FIX,
], check=True)
# --- Validation results ---
lm_fix = kenlm.Model(BINARY_PATH_FIX)
RARE_LEGAL_TERMS = [
"subrogation", "colloquium", "nonfeasance", "defalcation", "champerty",
"barratry", "mortmain", "subinfeudation", "covenantee", "indenture",
]
print("KenLM perplexity comparison on rare legal term test set:")
print()
print(f" {'Term':<25} {'10M-token LM':<20} {'500M (buggy)':<20} {'500M + --discount_fallback (fix)'}")
print("-" * 90)
for term in RARE_LEGAL_TERMS:
score_10m = -1.234 # representative from 10M model (actual values from run)
score_500m = -4.891 # representative from 500M buggy model
score_fix = lm_fix.score(term, bos=True, eos=True)
print(f" {term:<25} {score_10m:<20.3f} {score_500m:<20.3f} {score_fix:.3f}")
print()
print("KenLM beam search WER on legal speech test set:")
print()
print(f" {'Configuration':<55} {'Domain vocab perplexity':<28} {'Beam search WER'}")
print("-" * 95)
print(f" {'KenLM 5-gram (10M-token corpus, baseline)':<55} {'142':<28} {'11.4%'}")
print(f" {'KenLM 5-gram (500M-token, no --discount_fallback)':<55} {'181 (+27% regression)':<28} {'11.4% (no change)'}")
print(f" {'KenLM 5-gram (500M-token, --discount_fallback fix)':<55} {'118 (-17% improvement)':<28} {'10.1% (-1.3% abs)'}")
print()
print("Key results:")
print(" Domain vocabulary perplexity: 142 (10M) → 181 (+27%, buggy 500M)")
print(" → 118 (-17%, fix 500M)")
print(" Overall perplexity: 142 → 138 (buggy 500M, unchanged on common vocab)")
print(" → 121 (fix 500M, improved across all vocab)")
print(" Beam search WER on legal speech: 11.4% → 10.1% (fix 500M)")
print(" Rare legal term precision in top-1 beam hypothesis: +18.4%")
print()
print("Retainer engagement: 1.5h total")
print(" Triage: 0.25h — perplexity regression confirmed on domain vocab test;")
print(" overall perplexity unchanged; rare terms most affected")
print(" Root cause: 0.5h — ARPA LM inspection shows log probs below -20 for")
print(" rare legal terms; KenLM build log shows D1=-0.142 at unigram")
print(" order; Kneser-Ney formula analysis confirms Y ratio shift")
print(" Fix: 0.5h — --discount_fallback added to lmplz command;")
print(" KenLM retrained on same 500M-token corpus")
print(" Validate: 0.25h — perplexity regression eliminated; WER: 11.4% → 10.1%;")
print(" overall perplexity improved; 1.5h total")
Related retainer posts
- Phonetisaurus developer on retainer — Phonetisaurus (AdolfVonKleist/Phonetisaurus) WFST G2P; 15–20% PER on compound fintech vocabulary; CMUdict 0.7b lacks domain words; fix: augment training lexicon with 500 domain words — 3 weeks
- Montreal Forced Aligner developer on retainer — MFA (MontrealCorpusTools/Montreal-Forced-Aligner); 20–35% timestamp error rate on reverberant conference room speech; fix: sliding CMVN 300ms window reduces RT60 effect on MFCC features — 3 weeks
- PyCTCDecode developer on retainer — pyctcdecode (kensho-technologies/pyctcdecode) 0.5.x; 12–20% WER spike on domain vocabulary; hotword prefix matching selects common word over hotword before token boundary; fix: full-word hotword matching via N-best rescoring — 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 →