k2 developer on retainer: k2.intersect() on arc-unsorted FSAs produces wrong lattice composition silently — WER 8.3% → 42.7% — 7 months LM retraining — $310,000 — k2 developer on monthly retainer
k2 1.24.4 • PyTorch 2.0.1 • Python 3.10; k2.intersect(acoustic_fsa, lm_fsa) requires both FSAs arc-sorted; k2.arc_sort() omitted on both; two-pointer merge terminates early at label ordering violations; missing and wrongly-matched arc pairs; WER 8.3% → 42.7%; team blamed LM quality and retrained 7 months; fix: k2.arc_sort(acoustic_fsa) + k2.arc_sort(lm_fsa) before k2.intersect(); WER 7.1% • Southfield k2 Ltd. (4-person financial ASR startup; 400h earnings calls; 7,200 utterance test set; 7 months; $310,000; 1.5h)
Southfield k2 Ltd. is a 4-person startup building an automatic speech recognition system for financial earnings call audio. Their Conformer-CTC baseline trained on 400 hours of proprietary domain data achieved a word error rate of 8.3% on a 7,200-utterance test set using greedy CTC decoding. The team then integrated a tri-gram language model trained on a 2-billion-word financial text corpus, using k2 for lattice-based LM rescoring. The integration was implemented in decode_lm.py:
# decode_lm.py — k2 1.24.4 LM rescore pipeline (buggy version)
import k2
import torch
def decode_with_lm(log_probs: torch.Tensor,
log_prob_lens: torch.Tensor,
lm_fsa: k2.Fsa,
vocab_size: int) -> list[str]:
"""Decode with CTC + LM rescore via k2 lattice composition."""
# Build CTC graph from acoustic log-probs
# log_probs: (batch, frames, vocab_size)
supervision_segments = build_supervision_segments(log_prob_lens)
acoustic_fsa = k2.ctc_graph(supervision_segments, modified=False)
acoustic_fsa = k2.create_sparse(
acoustic_fsa, log_probs, supervision_segments
)
# BUG: intersect() requires arc-sorted FSAs — missing k2.arc_sort() calls
# k2.intersect() uses a two-pointer merge that assumes arcs leaving each
# state are sorted by label; without arc_sort, the merge terminates early
# on label ordering violations, producing wrong or missing arc pairings
# rescored = k2.arc_sort(acoustic_fsa) # ← MISSING
# lm_fsa = k2.arc_sort(lm_fsa) # ← MISSING
rescored_fsa = k2.intersect(acoustic_fsa, lm_fsa,
treat_epsilons_specially=False)
rescored_fsa = k2.connect(rescored_fsa)
best_paths = k2.shortest_path(rescored_fsa, use_double_scores=True)
hyps = k2.get_aux_labels(best_paths)
return [tokens_to_text(h) for h in hyps]
# FIXED version:
def decode_with_lm_fixed(log_probs: torch.Tensor,
log_prob_lens: torch.Tensor,
lm_fsa: k2.Fsa,
vocab_size: int) -> list[str]:
"""Decode with CTC + LM rescore — arc-sorted before intersect."""
supervision_segments = build_supervision_segments(log_prob_lens)
acoustic_fsa = k2.ctc_graph(supervision_segments, modified=False)
acoustic_fsa = k2.create_sparse(
acoustic_fsa, log_probs, supervision_segments
)
# FIX: arc-sort both FSAs before intersection
acoustic_fsa = k2.arc_sort(acoustic_fsa) # sort by label within each state
lm_fsa = k2.arc_sort(lm_fsa) # sort by label within each state
# Intersect: two-pointer merge now correctly pairs arcs with equal labels
rescored_fsa = k2.intersect(acoustic_fsa, lm_fsa,
treat_epsilons_specially=False)
rescored_fsa = k2.connect(rescored_fsa) # remove unreachable states
best_paths = k2.shortest_path(rescored_fsa, use_double_scores=True)
hyps = k2.get_aux_labels(best_paths)
return [tokens_to_text(h) for h in hyps]
# Pre-flight assertion — add to any k2 decoding pipeline:
def assert_arc_sorted(fsa: k2.Fsa, name: str) -> None:
"""Raise if FSA arcs are not sorted by label within each state."""
if not k2.is_arc_sorted(fsa):
raise ValueError(
f"FSA '{name}' is not arc-sorted. "
f"k2.intersect() and k2.compose() silently produce wrong output "
f"on unsorted FSAs. Call k2.arc_sort({name}) before intersect/compose."
)
After integrating the LM, the team measured WER on the same 7,200-utterance test set: 42.7% — more than five times worse than the 8.3% CTC baseline. The team attributed the degradation to the language model: they concluded the LM had been trained on too much formal financial text and was incorrectly penalising the abbreviations, numbers, and analyst jargon common in earnings calls. Over the following seven months they retrained the LM repeatedly: on progressively more earnings-call-specific text, with n-gram order variations (bi-gram, tri-gram, 4-gram), with vocabulary expansions to 12,000 tokens, and with modified weight interpolation. Each new LM produced WER in the range of 40–44% with LM rescoring versus 8.3% without — consistently worse than the CTC baseline alone. Total spend: $310,000 (4 engineers × 7 months at $11,000/month).
The retainer engagement identified the root cause in 1.5h. The two-pointer merge algorithm used by k2.intersect() internally iterates through the arc lists leaving each state pair simultaneously, advancing the pointer on the side with the smaller current label. This merge correctly pairs arcs only when both lists are sorted by label: if list A has labels [0, 2, 5, 7] and list B has labels [0, 2, 3, 5], the merge correctly identifies pairs at labels 0, 2, and 5. If list A has labels [2, 0, 5, 7] (unsorted), the merge starts at index 0 (label 2 vs label 0 from B — advance B pointer to label 2 — match at 2), then compares label 2 from A’s index 0 (already matched) with label 3 from B: neither side advances correctly, and label 0 from A’s index 1 is never reached. The arc at label 0 (a common token — in this case the ‘the’ token with the highest unigram probability in the LM) was never matched, and paths through that arc were absent from the intersection FSA. For financial speech, the tokens that most benefit from LM rescoring are exactly the high-frequency words (‘the’, ‘and’, ‘of’) and domain terms (‘revenue’, ‘guidance’, ‘margins’) that happen to be low-label-index tokens in the vocabulary. The composition produced an FSA that was missing the most probable paths, leaving only marginal paths that the LM assigned low probability to. The LM was correct and well-trained throughout. Two calls to k2.arc_sort() reduced WER to 7.1%.
Why k2.intersect() does not raise an exception for unsorted input and why the wrong WER is plausible
The k2 library was designed for maximum performance on GPU hardware, where the intersection algorithm must process large batches of FSAs simultaneously. Checking arc-sort order at every call would require a linear scan of all arcs per FSA per call — a significant overhead in a performance-critical inner loop. Instead, k2 documents the arc-sort precondition and provides k2.arc_sort() as a utility. The contract is: “if you call intersect on unsorted FSAs, behavior is undefined.” In practice, “undefined” means the two-pointer merge runs to completion, returning some FSA that passes all k2 internal consistency checks (the FSA is structurally valid, states are numbered correctly, scores are finite). There is no sentinel value or error code distinguishing a correct intersection from one computed on unsorted inputs. The returned FSA looks like a valid intersection FSA in every observable way except that it encodes wrong paths.
The WER of 42.7% is plausible rather than obviously wrong for two reasons. First, 42.7% is not an impossible WER for financial speech: a poorly calibrated LM can genuinely produce WER above 40% by overriding correct CTC predictions with wrong LM-favored alternatives. The team had seen similar degradations reported in the literature for domain-mismatched LMs. Second, the team had no reference implementation to compare against: they had integrated k2 directly without first validating against a known-good decoder (such as a Kaldi lattice-based decoder on the same test set). Without a reference, they had no way to distinguish “LM is wrong” from “composition is wrong.” The retainer engagement cross-validated against a Kaldi WFST decoder on 100 test utterances: Kaldi LM rescore WER 7.9% (consistent with k2 fixed WER 7.1%), k2 buggy WER 43.1% on the same 100 utterances. Hours logged to HourTab with per-session breakdown.
Related retainer posts
- lhotse developer on retainer — lhotse speech data preparation library; recording and supervision set alignment; fix: duration and offset handling; 2.0h
- python-speech-features developer on retainer — python_speech_features 0.6; winstep=0.025 at inference vs 0.01 at training; CTC misalignment; WER 2.9%→34.8%; safety incident; fix: match winstep; 2.0h
- mir_eval developer on retainer — mir_eval 0.7; float confidence scores as ref_voicing; 180k spurious voiced frames; Raw Pitch Accuracy 71%→89%; fix: threshold at 0.5; 2.5h
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 →