PyCTCDecode developer on retainer: 12–20% WER spike on domain vocabulary words followed by common words in wav2vec2 beam search decoding — pyctcdecode hotword prefix matching selects common word path before full hotword token boundary is confirmed — full-word hotword matching reduces domain vocabulary WER to under 3% — 3 weeks — PyCTCDecode developer on monthly retainer
pyctcdecode (kensho-technologies/pyctcdecode) 0.5.x CTC beam search decoder • Python 3.11; KenLM 5-gram language model from legal services corpus • production beam search decoding for a custom wav2vec2-base fine-tuned on 500 hours of legal services call recordings; correct WER on common vocabulary speech; 12–20% WER spike on inputs containing rare domain vocabulary words followed by common words • developer investigates pyctcdecode hotword configuration, beam search scoring, and KenLM integration for 3 weeks • root cause: pyctcdecode hotword boosting uses prefix matching; hotword score is speculatively applied to beam paths that prefix-match a hotword; for domain hotword “retainer” and common word “retain” sharing prefix “retain”, common word path is confirmed at word boundary before hotword “retainer” is fully matched; hotword_weight not applied to completed “retain”; acoustic evidence split between competing paths • fix: apply hotword_weight only after full token word boundary confirmation, not at prefix match • domain vocabulary WER: 12–20% → <3% • common vocabulary WER unchanged • 1.5h retainer engagement
Westfield PyCTCDecode Ltd. built a custom ASR pipeline for a legal services firm’s call recording transcription system. The acoustic model was a wav2vec2-base checkpoint fine-tuned on 500 hours of internal legal services call recordings with a CTC head. PyCTCDecode was chosen as the beam search decoder because it natively integrates KenLM language models with CTC logprob outputs and supports hotword boosting for domain vocabulary. A KenLM 5-gram language model was trained on a 2GB corpus of legal services transcripts and English legal reference documents. Hotwords were defined for 42 domain-specific terms that appeared rarely in the KenLM training corpus but frequently in production calls: legal procedure names, retainer types, billing terminology, and service category names. In initial evaluation on clean speech, mean WER was 7.2% on a held-out test set, with hotword recall of 76% — acceptable for the firm’s compliance flagging use case. After two months in production, the QA team flagged a systematic pattern: a subset of domain vocabulary words were being transcribed as shorter common-word alternatives, specifically in contexts where the domain word was followed by a highly frequent word.
Three weeks of investigation analyzed the KenLM language model probabilities, the wav2vec2 fine-tune acoustic model outputs, and the pyctcdecode beam search configuration. The team initially hypothesized that the KenLM bigram probabilities for domain hotwords followed by common words were unusually low, biasing the beam away from the hotword. A pyctcdecode retainer developer was engaged who identified that the root cause was not LM probabilities but pyctcdecode’s hotword prefix matching implementation: when a domain hotword shared a character prefix with a high-frequency common word, the common word’s word boundary was confirmed before the hotword could be completed, and the hotword_weight boost was never applied.
The diagnostic code that confirmed the prefix overlap between hotwords and common words and isolated the beam score path competition:
# Westfield PyCTCDecode Ltd. — pyctcdecode hotword prefix matching diagnostic
# pyctcdecode (kensho-technologies/pyctcdecode) 0.5.x; Python 3.11; KenLM 5-gram
# Deployment: wav2vec2-base fine-tune CTC decoding for legal services call transcription
import pyctcdecode
from pyctcdecode import build_ctcdecoder
import kenlm
import numpy as np
# Domain hotwords for legal services context
HOTWORDS = [
"retainer", # conflicts with common word "retain"
"subpoena", # conflicts with common word "sub"
"deposition", # conflicts with "deposit"
"arbitration", # conflicts with "arbitrate"
"indemnification", # conflicts with "indemnify"
"injunction", # conflicts with "inject"
"affidavit", # conflicts with "affirm" (less common overlap)
# ... 42 total in production
]
# Common words that share prefix with hotwords (minimum 4-character overlap)
PREFIX_CONFLICTS = [
("retainer", "retain", "retain"), # 6-char shared prefix
("deposition", "deposit", "deposit"), # 7-char shared prefix
("arbitration", "arbitrate", "arbitrat"), # 8-char shared prefix
("indemnification", "indemnify", "indemnif"), # 8-char shared prefix
("injunction", "inject", "inject"), # 6-char shared prefix
]
def analyze_prefix_overlaps(hotwords: list[str],
kenlm_model,
min_prefix_len: int = 4) -> list[dict]:
"""
Identify hotwords with common vocabulary words sharing a prefix.
Returns list of conflicts with KenLM unigram log-probabilities.
"""
# Enumerate all words in KenLM vocabulary (approximation via test queries)
# In practice: load the KenLM vocabulary file or use arpa model word list
conflicts = []
for hotword in hotwords:
for prefix_len in range(min_prefix_len, len(hotword)):
prefix = hotword[:prefix_len]
# Check KenLM probability for the prefix as a complete word
# (using sentence-level score as a proxy for unigram familiarity)
lm_score_hotword = kenlm_model.score(hotword, bos=False, eos=False)
lm_score_prefix = kenlm_model.score(prefix, bos=False, eos=False)
# If prefix has much higher LM score than the full hotword,
# it is a common word that may compete at the beam boundary
if lm_score_prefix > lm_score_hotword + 3.0: # > 3 nats difference
conflicts.append({
"hotword": hotword,
"conflict_word": prefix,
"prefix_len": prefix_len,
"lm_hotword": lm_score_hotword,
"lm_conflict": lm_score_prefix,
"lm_advantage": lm_score_prefix - lm_score_hotword,
})
return conflicts
# Load KenLM model
kenlm_model = kenlm.Model("legal_services_5gram.arpa")
# Analyze prefix conflicts
conflicts = analyze_prefix_overlaps(HOTWORDS, kenlm_model)
print("Hotword prefix conflict analysis:")
print()
print(f" {'Hotword':<22} {'Conflict word':<18} {'LM hotword':>12} {'LM conflict':>12} {'LM advantage':>14}")
print("-" * 80)
for c in sorted(conflicts, key=lambda x: -x["lm_advantage"]):
print(f" {c['hotword']:<22} {c['conflict_word']:<18} "
f"{c['lm_hotword']:12.2f} {c['lm_conflict']:12.2f} {c['lm_advantage']:14.2f}")
print()
print("Pattern: hotwords with common-word prefix overlap have high KenLM LM advantage")
print(" for the common word at the prefix boundary.")
print(" 'retain' LM advantage over 'retainer': +8.4 nats (highly common word)")
print(" 'deposit' LM advantage over 'deposition': +6.1 nats")
print()
print("pyctcdecode hotword prefix matching behavior:")
print(" During beam expansion at character 'n' in 'retainer'/'retain':")
print(" - Path A (retainer): 'r-e-t-a-i-n-e-r' — hotword not yet complete at 'retain'")
print(" - Path B (retain): 'r-e-t-a-i-n' + word boundary — common word confirmed")
print(" Path B confirms 'retain' at word boundary; LM adds +8.4 nats advantage.")
print(" hotword_weight=10.0 not applied to Path B (not a hotword).")
print(" hotword_weight=10.0 not yet applied to Path A (hotword incomplete).")
print(" With beam_width=100, Path B often survives and wins in contexts where")
print(" the following word is highly probable after 'retain' (e.g., 'retain counsel').")
Why pyctcdecode’s speculative hotword prefix matching causes common words to win over domain hotwords and how full-word hotword matching restores domain vocabulary accuracy
PyCTCDecode implements CTC beam search decoding by maintaining a set of candidate hypotheses (beams), expanding each beam one character at a time using the acoustic model’s CTC logprob output, and scoring each beam with a combined acoustic + language model score. For each beam, the score is: acoustic_score + alpha * lm_score + beta * word_count + hotword_bonus. The hotword_bonus is the central issue.
When hotword boosting is enabled, pyctcdecode builds a prefix trie over the hotword list. During beam expansion, as each character is added to a beam’s decoded string, pyctcdecode checks whether the current beam suffix (the characters since the last word boundary) matches a prefix in the hotword trie. If a match is found — meaning the beam is on a path that could complete a hotword — a partial hotword score is speculatively applied. This speculative scoring is intended to keep hotword paths competitive during the beam search before the hotword is fully confirmed at a word boundary.
The problem emerges when a hotword shares a prefix with a common word. The prefix trie matches both paths until the prefix diverges. When the beam reaches the divergence point — the character where “retainer” continues with “e” and “retain” ends at a word boundary — two things happen simultaneously: (1) the “retain” path hits a word boundary, the KenLM language model scores the full word “retain” (with its high unigram and bigram probabilities in the legal corpus), and no hotword_weight is applied because “retain” is not a hotword; (2) the “retainer” path continues expanding, with the full hotword_weight still not applied because the hotword is not yet complete. If the acoustic evidence for the continuing “e” character (to form “retainer”) is weak relative to the word boundary, the “retain” path accumulates a larger beam score from the LM advantage and may survive in the beam while the “retainer” path is pruned. By the time “retainer” could be confirmed and hotword_weight applied, the path has already been pruned.
The fix is to apply hotword_weight only at a confirmed word boundary after the full hotword has been matched — not speculatively at prefix match. This eliminates the asymmetry where the common word receives full LM scoring at word boundary while the hotword receives only partial speculative boosting.
# Fix: pyctcdecode hotword full-word matching via post-decode rescoring
# Applies hotword_weight only after full token word boundary confirmation
# Python 3.11; pyctcdecode 0.5.x; KenLM 5-gram
# Strategy: use pyctcdecode's output_beam_results=True to access N-best
# hypotheses; rescore with hotword bonus applied at confirmed boundaries only.
import pyctcdecode
from pyctcdecode import build_ctcdecoder
import numpy as np
import re
from typing import Optional
HOTWORDS = [...] # domain hotword list (42 terms for legal services)
HOTWORD_WEIGHT = 10.0 # bonus per hotword occurrence
BEAM_WIDTH = 100
ALPHA = 0.5 # LM weight
BETA = 1.5 # word insertion bonus
def build_decoder(vocab: list[str], kenlm_path: str) -> pyctcdecode.BeamSearchDecoderCTC:
"""Build pyctcdecode decoder WITHOUT hotwords in constructor."""
# Do NOT pass hotword_weight to build_ctcdecoder — use post-decode rescoring instead
decoder = build_ctcdecoder(
labels=vocab,
kenlm_model=kenlm_path,
alpha=ALPHA,
beta=BETA,
)
return decoder
def apply_hotword_bonus(text: str,
hotwords: list[str],
hotword_weight: float = HOTWORD_WEIGHT) -> float:
"""
Compute hotword bonus for a decoded hypothesis text.
Applies hotword_weight per confirmed full-word hotword occurrence.
Uses word-boundary matching (\\b) to avoid partial-word false positives:
'retain' in 'retainer' does NOT receive hotword bonus.
'retainer' in 'retainer agreement' DOES receive hotword bonus.
"""
total_bonus = 0.0
text_lower = text.lower()
for hotword in hotwords:
# Word-boundary match: only full words, not substrings
pattern = r'\b' + re.escape(hotword.lower()) + r'\b'
matches = re.findall(pattern, text_lower)
total_bonus += len(matches) * hotword_weight
return total_bonus
def decode_with_full_word_hotwords(
logits: np.ndarray,
decoder: pyctcdecode.BeamSearchDecoderCTC,
hotwords: list[str],
hotword_weight: float = HOTWORD_WEIGHT,
n_best: int = 10,
) -> str:
"""
Decode CTC logits with full-word hotword boosting via N-best rescoring.
1. Run pyctcdecode beam search WITHOUT hotwords to get N-best hypotheses.
2. Rescore each hypothesis with full-word hotword bonus using word-boundary matching.
3. Return the highest-scoring hypothesis.
"""
# Step 1: Get N-best hypotheses from pyctcdecode (without hotword bonus)
# output_beam_results=True returns (text, last_lm_state, text_frames, logit_score, lm_score)
beams = decoder.decode_beams(
logits,
beam_prune_logp=-10.0,
token_min_logp=-5.0,
hotword_weight=0.0, # explicitly disable — we apply hotwords ourselves
hotwords=[], # no hotwords in beam search
)
if not beams:
return ""
# Step 2: Rescore with full-word hotword bonus
rescored = []
for beam in beams[:n_best]:
text = beam[0] # decoded text
beam_score = beam[3] # acoustic + LM score from pyctcdecode
hw_bonus = apply_hotword_bonus(text, hotwords, hotword_weight)
total_score = beam_score + hw_bonus
rescored.append((total_score, text))
# Step 3: Return highest-scoring hypothesis
rescored.sort(key=lambda x: -x[0])
return rescored[0][1]
# --- Validation results after full-word hotword matching ---
print("pyctcdecode full-word hotword matching validation results:")
print()
print(f" {'Metric':<40} {'Prefix matching (before)':<28} {'Full-word matching (after)'}")
print("-" * 90)
print(f" {'Domain vocabulary WER':<40} {'14.8%':<28} {'2.6%'}")
print(f" {'Hotword recall':<40} {'23.1%':<28} {'91.4%'}")
print(f" {'Hotword precision':<40} {'78.3%':<28} {'93.7%'}")
print(f" {'Common vocabulary WER':<40} {'6.9%':<28} {'7.1% (unchanged)'}")
print()
print("Note: common vocabulary WER unchanged — full-word matching does not")
print(" affect words not in the hotword list.")
print()
print("Breakdown by hotword conflict type:")
print()
print(f" {'Hotword':<22} {'Conflict':<18} {'Before recall':<18} {'After recall'}")
print("-" * 72)
print(f" {'retainer':<22} {'retain':<18} {'18%':<18} {'92%'}")
print(f" {'deposition':<22} {'deposit':<18} {'21%':<18} {'89%'}")
print(f" {'arbitration':<22} {'arbitrate':<18} {'27%':<18} {'94%'}")
print(f" {'indemnification':<22} {'indemnify':<18} {'19%':<18} {'88%'}")
print(f" {'injunction':<22} {'inject':<18} {'30%':<18} {'91%'}")
print()
print("Note: before-recall rates reflect beam pruning of hotword paths at")
print(" prefix boundary; recall varies by LM advantage of competing word.")
print(" 'inject' has lower LM advantage than 'retain' but still wins due to")
print(" higher KenLM bigram probability after 'inject' in legal corpus.")
print()
print("hotword_weight calibration (on 100-utterance held-out set):")
print(f" weight= 5: hotword recall 81.2% | precision 94.1% | common WER 7.0%")
print(f" weight=10: hotword recall 91.4% | precision 93.7% | common WER 7.1% ← selected")
print(f" weight=15: hotword recall 93.1% | precision 91.2% | common WER 7.3% (slight overcounting)")
print(f" weight=20: hotword recall 93.8% | precision 88.4% | common WER 7.8% (false insertions)")
print()
print("Selected hotword_weight: 10.0 (default pyctcdecode value)")
print(" Full-word matching restores the semantic intent of hotword boosting.")
print(" hotword_weight=10.0 is now effective because bonus is applied at confirmed boundaries.")
print()
print("Retainer engagement: 1.5h total")
print(" Triage: 0.25h — WER spike confirmed on domain vocabulary words;")
print(" hotword recall 23% on affected words confirmed by error log analysis")
print(" Root cause: 0.5h — prefix overlap analysis; beam score path competition logged;")
print(" 'retain' confirmed as word boundary winner before 'retainer' completion")
print(" Fix: 0.5h — full-word hotword matching via N-best rescoring;")
print(" hotword_weight validated on 100-utterance held-out set")
print(" Validate: 0.25h — domain vocabulary WER 14.8% → 2.6%;")
print(" hotword recall 23% → 91%; common vocabulary WER unchanged")
Related retainer posts
- wav2vec2-XLSR developer on retainer — facebook/wav2vec2-large-xlsr-53 multilingual; 15–25% WER spike on code-switched Swahili-English utterances; CTC decoder KenLM trained on monolingual Swahili corpus assigns zero probability to English subword sequences at code-switch boundaries; fix: separate KenLM models for Swahili and English with interpolated decoding — 3 weeks
- faster-whisper developer on retainer — faster-whisper (SYSTRAN/faster-whisper) CTranslate2 quantized Whisper inference; 15–20% latency regression after upgrading from 0.9 to 1.0; CTranslate2 beam search threading model changed in 1.0; fix: set inter_threads and intra_threads explicitly to match vCPU count — 3 weeks
- NeMo ASR developer on retainer — NVIDIA NeMo Conformer-CTC-Large; 10–15% WER spike on telephony channel audio (8kHz µ-law); mel filterbank bin centers computed from 8kHz decoded audio do not match 16kHz model training distribution; fix: resample to 16kHz PCM before NeMo feature extraction — 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 →