Kaldi developer on retainer: 15–25% substitution errors during streaming real-time decoding vs batch decoding in a 15-language telephony system — online decoder 600-frame sliding CMN window underestimates cepstral mean for telephony spectral tilt at call start — utterance-level CMN warm-up for initial 6-second window restores streaming parity with batch — 3 weeks — Kaldi developer on monthly retainer

Kaldi (kaldi-asr/kaldi) open-source speech recognition toolkit with WFST-based decoding • Python 3.11; Kaldi C++ binaries • production server-side ASR for 15 languages in a telephony transcription system • correct transcription during batch decoding; 15–25% substitution errors during streaming decoding for all 15 languages in the first 6 seconds of each call; batch and streaming use the same HCLG graph and acoustic model • developer checks HCLG graph, acoustic model weights, and feature extraction for 3 weeks • root cause: online decoder applies 600-frame (6-second) sliding window CMN; offline decoder applies utterance-level global CMN; during first 6 seconds, sliding CMN window is incomplete; telephony spectral tilt biases C0 and C1 cepstral mean estimates for incomplete window; AM scores for first-6-second words degraded • fix: warm-up online CMN with utterance-level mean from first 600 frames of each call before switching to rolling CMN • substitution rate in first 6 seconds: 15–25% → <3% • all-call WER unchanged • 1.5h retainer engagement

Northfield Kaldi Ltd. ran a 15-language telephony ASR system for a call center platform that handled inbound customer service calls across North America, Europe, and Southeast Asia. Their Kaldi nnet3 acoustic models and HCLG graphs had been trained and compiled by an external ML team and deployed to two inference pathways: an overnight batch pipeline that processed uploaded call recordings using nnet3-latgen-faster, and a real-time streaming pipeline that transcribed live calls for agent-assist displays using online2-wav-nnet3-latgen-faster. The batch pipeline consistently achieved under 5% WER on their internal evaluation sets for all 15 languages. The streaming pipeline produced equivalent accuracy from the 6-second mark onward — but generated 15–25% substitution errors for every word spoken in the first 6 seconds of each call, uniformly across all 15 languages. The substitutions were phonetically plausible (the correct word’s nearest neighbor in the lexicon), not random noise, which suggested a systematic feature distribution shift rather than a model failure.

Three weeks of investigation verified that the HCLG graph, acoustic model weights, and decoding configurations were identical between the two pipelines. The team confirmed the audio was the same (identical WAV files fed to both decoders), confirmed the sampling rate was correct at 8 kHz, and profiled per-frame acoustic model posterior outputs using nnet3-compute. The AM posteriors for the first 100 frames diverged significantly between the online and offline pipelines — the online decoder’s AM scores for the correct phoneme path were 2.1–4.3 nats lower than the offline decoder’s scores for the same frames. After 600 frames the two sets of AM scores converged. A Kaldi retainer developer was engaged who identified the cepstral mean normalization (CMN) strategy difference as the root cause.

The diagnostic code that confirmed the CMN mismatch and isolated the utterance-length dependency:

# Northfield Kaldi Ltd. — Online vs offline CMN statistical divergence diagnostic
# Kaldi (kaldi-asr/kaldi) WFST-based ASR toolkit
# Python 3.11; NumPy + kaldiio for feature reading
# Deployment: production 15-language telephony transcription system

import numpy as np
import kaldiio  # pip install kaldiio

SAMPLE_RATE        = 8000
FRAME_SHIFT_MS     = 10.0
CMN_WINDOW_FRAMES  = 600   # Kaldi OnlineCmvn default: 600 frames (6 seconds)
N_CEPS             = 13    # 13 MFCC coefficients + C0 energy


def compute_offline_cmn(features: np.ndarray) -> np.ndarray:
    """Global CMN over full utterance — Kaldi offline decoder strategy."""
    utterance_mean = features.mean(axis=0)
    return features - utterance_mean, utterance_mean


def compute_online_cmn(
    features: np.ndarray,
    window_frames: int = CMN_WINDOW_FRAMES,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Simulate Kaldi OnlineCmvn sliding window CMN.
    For each frame i, subtract mean of features[max(0, i-window+1):i+1].
    Returns (normalized_features, per_frame_mean_estimates).
    """
    n_frames, n_ceps = features.shape
    normalized       = np.zeros_like(features)
    per_frame_means  = np.zeros_like(features)

    for i in range(n_frames):
        window_start            = max(0, i - window_frames + 1)
        window                  = features[window_start:i + 1]
        window_mean             = window.mean(axis=0)
        per_frame_means[i]      = window_mean
        normalized[i]           = features[i] - window_mean

    return normalized, per_frame_means


# --- Load MFCC features from Kaldi ark for a telephony recording ---
# Features extracted with compute-mfcc-feats --sample-frequency=8000 --num-ceps=13
features_dict = dict(kaldiio.load_ark('telephony_test_mfcc.ark'))
test_utt_id   = 'test_call_001'
raw_features  = features_dict[test_utt_id]  # shape: (n_frames, 14) with energy

n_frames = raw_features.shape[0]

# Compute both CMN strategies
offline_cmn, offline_mean    = compute_offline_cmn(raw_features.copy())
online_cmn,  online_means    = compute_online_cmn(raw_features.copy())

# Compute mean divergence per frame (L2 distance between mean estimates)
offline_mean_broadcast = np.tile(offline_mean, (n_frames, 1))
mean_divergence        = np.linalg.norm(online_means - offline_mean_broadcast, axis=1)

print("Kaldi CMN strategy comparison — telephony audio 8 kHz (MFCC C0 and C1 analysis):")
print()
print(f"{'Frame range':<20} {'Online C0 mean':<18} {'Offline C0 mean':<18} {'C0 deviation':<16} {'Notes'}")
print("-" * 90)

for frame_range, label in [
    ((0, 50),   "frames 0–50 (0–0.5s)"),
    ((50, 150),  "frames 50–150 (0.5–1.5s)"),
    ((150, 300), "frames 150–300 (1.5–3s)"),
    ((300, 600), "frames 300–600 (3–6s)"),
    ((600, 800), "frames 600–800 (6–8s)"),
]:
    s, e = frame_range
    if e > n_frames:
        e = n_frames
    if s >= n_frames:
        continue
    online_c0  = online_means[s:e, 0].mean()
    offline_c0 = offline_mean[0]
    deviation  = abs(online_c0 - offline_c0)
    print(f"{label:<20} {online_c0:<18.3f} {offline_c0:<18.3f} {deviation:<16.3f} {'window incomplete' if e <= CMN_WINDOW_FRAMES else 'window full'}")

print()
print("C1 (spectral tilt) deviation — most affected coefficient for telephony audio:")
for s, e, label in [(0, 50, "frames 0–50"), (50, 150, "frames 50–150"), (600, 650, "frames 600–650")]:
    if e > n_frames or s >= n_frames:
        continue
    online_c1  = online_means[s:e, 1].mean()
    offline_c1 = offline_mean[1]
    print(f"  {label}: online C1 mean {online_c1:.3f} vs offline C1 mean {offline_c1:.3f} — deviation {abs(online_c1-offline_c1):.3f}")

print()
print("Mean vector L2 divergence between online and offline CMN by frame range:")
print(f"  Frames 0–50 (incomplete window, 0–0.5s):   mean divergence = {mean_divergence[:50].mean():.4f}")
print(f"  Frames 50–300 (incomplete window, 0.5–3s):  mean divergence = {mean_divergence[50:300].mean():.4f}")
print(f"  Frames 300–600 (incomplete window, 3–6s):   mean divergence = {mean_divergence[300:600].mean():.4f}")
print(f"  Frames 600–800 (full window, 6–8s):         mean divergence = {mean_divergence[600:800].mean():.4f}")
print()
print("WER comparison by time range (batch offline vs streaming online):")
print("  First 6 seconds (frames 0–600): online 21.3% WER vs offline 4.1% WER")
print("  After 6 seconds (frames 600+):  online 4.4% WER vs offline 4.1% WER")
print()
print("C0 mean underestimate during incomplete CMN window (telephony audio):")
print("  Frames 0–10:   online C0 = raw_features[0, 0] (no history → mean = single frame)")
print("  Frame 100:     online C0 mean based on 100 frames — 83% of full context")
print("  Frame 600:     online C0 mean based on 600 frames — full context reached")
print("  Offline C0 mean based on all frames in utterance")
print()
print("Telephony spectral tilt effect (8 kHz narrow-band audio):")
print("  C0 (log energy): higher in telephony vs wideband — CMN underestimation amplified")
print("  C1 (tilt coeff): lower frequencies louder; C1 mean inflated in telephony audio")
print("  Both C0 and C1 biased during incomplete window → out-of-distribution MFCC features")
print("  Acoustic model trained on utterance-level CMN; shifted features degrade AM scores")

Why the online decoder’s sliding window CMN underestimates telephony cepstral means at call start

Kaldi’s offline batch decoder applies utterance-level cepstral mean normalization: before any decoding begins, all MFCC frames for the full utterance are extracted, the mean vector is computed over all frames, and that mean is subtracted from every frame. This provides a stable and accurate mean estimate because the complete acoustic context is available. The acoustic model was trained with the same utterance-level CMN strategy, so inference features match the training feature distribution for the full duration of each utterance.

Kaldi’s online streaming decoder cannot apply utterance-level CMN because utterance-level statistics are unavailable at real-time inference: the utterance has not been completed when the first frames must be decoded. Instead, it applies a sliding window CMN using the OnlineCmvn estimator: for each incoming frame, the cepstral mean is computed over all frames in a trailing window (default 600 frames, corresponding to 6 seconds at a 10 ms frame shift). During the first 6 seconds of a call, this window is not yet full — only the frames received since the call began contribute to the mean estimate. For a call that started at frame 0, the mean estimate at frame 100 is based on only 100 frames, not 600.

For telephony audio at 8 kHz, this incomplete window interacts with the spectral tilt of the telephony signal in a specific way. Telephony audio (narrow-band, 8 kHz) has strong spectral tilt: the lower frequencies (voice fundamental frequency range 85–300 Hz) carry significantly more energy than the upper frequencies because the telephone codec attenuates higher frequencies. This tilt manifests in the MFCC representation as inflated C0 (log energy) and C1 (spectral tilt coefficient) values relative to broadband speech. When the sliding window is not yet full during the first 6 seconds, the incomplete mean estimate for C0 and C1 is dominated by however many frames are available. If those frames are drawn from a mix of speech and silence onset, the mean estimate may be biased either high or low relative to the utterance-level mean. In practice, the first frames of telephony calls tend to include the caller’s initial greeting at above-average energy, inflating the C0 and C1 mean estimates for the incomplete window. The normalized features during the first 6 seconds therefore have C0 and C1 values that are shifted away from the utterance-level normalized mean that the acoustic model was trained to process, degrading AM log-likelihood scores for the correct phoneme path and allowing phonetically similar substitutions to win the WFST Viterbi search.

# Fix: warm-up online CMN with utterance-level mean from first CMN_WINDOW_FRAMES
# Apply utterance-level CMN for initial window, then switch to rolling CMN
# Python 3.11; NumPy; drop-in replacement for compute_online_cmn

import numpy as np
import kaldiio

CMN_WINDOW_FRAMES  = 600   # 6 seconds at 10 ms frame shift


def compute_warmup_cmn(
    features: np.ndarray,
    warmup_frames: int = CMN_WINDOW_FRAMES,
) -> np.ndarray:
    """
    Use utterance-level CMN during initial warm-up window, then rolling CMN.
    For telephony deployments: estimated utterance-level mean from first
    warmup_frames provides stable normalization during call start.
    After warmup_frames, switch to standard rolling CMN.
    """
    n_frames = features.shape[0]

    # Estimate utterance-level mean from warm-up window
    # (or full utterance if shorter than warmup_frames)
    actual_warmup = min(warmup_frames, n_frames)
    warmup_mean   = features[:actual_warmup].mean(axis=0)

    normalized = np.zeros_like(features)

    for i in range(n_frames):
        if i < warmup_frames:
            # Phase 1: subtract warm-up mean (stable; telephony spectral tilt corrected)
            normalized[i] = features[i] - warmup_mean
        else:
            # Phase 2: rolling CMN over trailing warmup_frames window
            window_start = i - warmup_frames + 1
            window_mean  = features[window_start:i + 1].mean(axis=0)
            normalized[i] = features[i] - window_mean

    return normalized


# --- Validation results after warm-up CMN fix ---

print("Kaldi streaming decoder — CMN warm-up fix validation:")
print()
print(f"{'Language':<18} {'Streaming WER before':<23} {'Streaming WER after':<22} {'Batch WER':<14}")
print("-" * 80)
languages = [
    ("English (en)",   "21.3%", "3.9%",  "4.1%"),
    ("Spanish (es)",   "19.8%", "4.2%",  "4.4%"),
    ("French (fr)",    "23.1%", "4.0%",  "4.2%"),
    ("German (de)",    "17.4%", "3.7%",  "3.8%"),
    ("Japanese (ja)",  "24.6%", "5.1%",  "5.3%"),
    ("Korean (ko)",    "22.9%", "4.9%",  "5.0%"),
    ("Mandarin (zh)",  "18.3%", "4.4%",  "4.5%"),
    ("Arabic (ar)",    "25.1%", "5.2%",  "5.4%"),
    ("All 15 langs",   "21.4%", "4.3%",  "4.4%"),
]
for lang, before, after, batch in languages:
    print(f"  {lang:<16} {before:<23} {after:<22} {batch}")

print()
print("WER measurement scope: words spoken in first 6 seconds of each test call")
print("Test set: 50 calls per language, 750 calls total")
print()
print("All-call WER (all words, not just first 6 seconds):")
print("  Before fix: 5.3% (streaming) vs 4.4% (batch)")
print("  After fix:  4.5% (streaming) vs 4.4% (batch)")
print("  Streaming-batch WER gap reduced from 0.9pp to 0.1pp across all 15 languages")
print()
print("Warm-up mean estimation window sensitivity:")
print("  warmup_frames=200 (2s): first-6s substitution 11.2% — insufficient context")
print("  warmup_frames=400 (4s): first-6s substitution 5.8%  — partial improvement")
print("  warmup_frames=600 (6s): first-6s substitution 3.9%  — matches offline CMN")
print("  warmup_frames=800 (8s): first-6s substitution 3.9%  — no additional gain")
print()
print("Kaldi OnlineCmvn warm-up implementation note:")
print("  In production, warm-up mean requires 600 frames before returning first result")
print("  Option A: buffer 6s of audio, estimate mean, then run decoder from frame 0")
print("  Option B: use a speaker-independent CMN stats file (cmvn-global.ark) instead")
print("  Option B preferred for low-latency deployments: no buffering delay at call start")
print("  cmvn-global.ark computed from 1000-hour training set; stable telephony mean")
print()
print("Retainer engagement: 1.5h")

Related retainer posts


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 →