pystoi developer on retainer: LSTM output adds 512-sample latency — pystoi.stoi() truncates longer signal silently — first 32 ms misaligned against reference — STOI 0.76 vs expected 0.88 — 5 weeks — pystoi developer on monthly retainer
pystoi 0.4.1 • Python 3.9; LSTM speech enhancement adds 512-sample causal-padding latency; len(y_enhanced)=32512 vs len(x_clean)=32000; pystoi.stoi(x_clean, y_enhanced, 16000) silently truncates y_enhanced to 32000 samples; first 512 samples of y_enhanced are LSTM zero-state output (startup noise); x_clean[0:512] correlated against startup noise, not enhanced speech; STOI underestimates intelligibility by 0.12; measured STOI=0.76 vs expected 0.88; fix: y_aligned = y_enhanced[512:][:len(x_clean)]; STOI rises to 0.87 • Northfield Pystoi Ltd. (call center AI speech enhancement; 500 model evaluations/month; 5 weeks; 2.0h retainer engagement)
Northfield Pystoi Ltd. built a speech enhancement evaluation pipeline for a call center AI platform. The pipeline assessed 500 LSTM model variants per month using the Short-Time Objective Intelligibility (STOI) metric computed by pystoi (0.4.1). The enhancement LSTM used causal zero-padding: before inference, the input signal was prepended with 512 zeros (32 ms at 16 kHz) so that the LSTM could produce output for the first frame using its full receptive field. The model was designed to output exactly len(input) + 0 samples, but due to the LSTM’s state flush at the final timestep, the output array was 512 samples longer than the original clean reference: len(y_enhanced) = len(x_clean) + 512 = 32512 for a 2-second 16 kHz clip. When the developer called pystoi.stoi(x_clean, y_enhanced, 16000), pystoi silently truncated y_enhanced to len(x_clean) = 32000 samples, discarding the last 512 samples. This truncation kept the first 512 samples of y_enhanced in place — the LSTM’s zero-state output for the first 32 ms, which is essentially model startup noise rather than enhanced speech. The result: pystoi correlated x_clean[0:512] (the first 32 ms of real speech onset) against y_enhanced[0:512] (model startup noise), producing near-zero correlation for the initial integration windows. Measured STOI was 0.76; the expected score based on listening tests was 0.88. The developer spent 5 weeks adjusting LSTM architecture, training loss, batch normalization, and regularization before the alignment issue was identified.
The STOI algorithm’s sensitivity to temporal alignment comes from its core computation: for each one-third-octave frequency band (15 bands from 150 Hz to 4500 Hz), pystoi computes the sample-level correlation between x and y within a 384 ms sliding integration window. The correlation at each frame is corr(x_band[t:t+N], y_band[t:t+N]) where N = 6144 samples (384 ms at 16 kHz). Perfect temporal alignment gives correlation near 1.0 for high-SNR speech; a 512-sample shift means the first 512 samples of each window are drawn from mismatched speech content. For the first integration window (t=0), all 6144 samples include the initial 512 misaligned samples; the correlation depends on how much of the 512-sample mismatch affects the band correlation. At 32 ms misalignment, consonant onsets and fricative bursts — the most intelligibility-critical phonetic features — that appear at the start of an utterance are systematically misaligned. The STOI average over all windows and bands is pulled down by approximately 0.12 for a 512-sample shift in a 32000-sample utterance. The enhancement model was genuinely good (the last 32000 samples of y_enhanced[512:32512] gave STOI=0.87), but the measurement was consistently wrong because the alignment step was missing.
The annotated buggy and fixed evaluation pipeline, with signal alignment validation and latency compensation:
# Northfield Pystoi Ltd. — pystoi 0.4.1 LSTM latency alignment fix
# pystoi 0.4.1; Python 3.9; NumPy 1.23
# Speech enhancement quality monitoring; 500 model evaluations/month
# Call center AI platform; causal LSTM enhancement model
#
# Problem: LSTM causal padding adds 512-sample initial output latency
# len(y_enhanced) = len(x_clean) + 512
# pystoi.stoi(x_clean, y_enhanced, 16000) truncates y to len(x)
# First 512 samples of y_enhanced = LSTM zero-state output (startup noise)
# x_clean[0:512] correlated against startup noise → low STOI
# Measured STOI=0.76 vs expected 0.88 based on listening tests
# Fix: Trim LSTM output latency before STOI: y_aligned = y_enhanced[512:][:len(x_clean)]
import numpy as np
import pystoi
import soundfile as sf
SAMPLE_RATE = 16000
LSTM_OUTPUT_LATENCY_SAMPLES = 512 # 32ms at 16kHz — LSTM causal padding flush
def compute_stoi_buggy(x_clean: np.ndarray, y_enhanced: np.ndarray, fs: int) -> float:
"""BUGGY: passes length-mismatched arrays to pystoi without alignment."""
# pystoi silently truncates the longer signal to match the shorter.
# len(y_enhanced) = len(x_clean) + 512 (LSTM latency flush)
# pystoi takes y_enhanced[:len(x_clean)] — keeping startup noise at start
# First 512 samples of y_enhanced are LSTM zero-state output, not speech
# x_clean[0:512] = speech onset; y_enhanced[0:512] = LSTM startup noise
# Temporal misalignment causes STOI integration window correlation to drop
# Result: STOI=0.76 for a model that subjectively sounds like STOI≈0.88
return pystoi.stoi(x_clean, y_enhanced, fs) # BUG: unaligned signals
def compute_stoi(
x_clean: np.ndarray,
y_enhanced: np.ndarray,
fs: int,
model_latency_samples: int = LSTM_OUTPUT_LATENCY_SAMPLES,
) -> float:
"""FIXED: trim LSTM output latency before STOI to ensure temporal alignment."""
# LSTM causal-padding latency: first model_latency_samples of y_enhanced
# are based on zero-padded input (not actual speech). Trim them before STOI.
# Also trim y to exactly len(x) to prevent silent truncation.
if model_latency_samples > 0:
y_aligned = y_enhanced[model_latency_samples : model_latency_samples + len(x_clean)]
else:
y_aligned = y_enhanced[:len(x_clean)]
if len(y_aligned) < len(x_clean):
# y is shorter than x even after alignment — truncate x
x_eval = x_clean[:len(y_aligned)]
y_eval = y_aligned
else:
x_eval = x_clean
y_eval = y_aligned
return pystoi.stoi(x_eval, y_eval, fs)
def verify_signal_alignment(
x_clean: np.ndarray,
y_enhanced: np.ndarray,
fs: int,
max_lag_samples: int = 10,
) -> int:
"""
Compute cross-correlation lag between x and y to detect temporal misalignment.
Returns the detected lag in samples (positive = y leads x; negative = y lags x).
Raises if lag exceeds max_lag_samples (indicating alignment problem).
"""
# Use first 250ms (4000 samples at 16kHz) for fast cross-correlation
n_check = min(len(x_clean), len(y_enhanced), int(0.250 * fs))
xcorr = np.correlate(x_clean[:n_check], y_enhanced[:n_check], mode='full')
lag = np.argmax(np.abs(xcorr)) - (n_check - 1)
if abs(lag) > max_lag_samples:
raise ValueError(
f"Signal alignment check failed: detected lag = {lag} samples "
f"({lag / fs * 1000:.1f} ms). "
f"This suggests the enhancement model introduces an output latency "
f"of {abs(lag)} samples. "
f"Pass model_latency_samples={abs(lag)} to compute_stoi() to align "
f"signals before STOI evaluation. "
f"Without alignment, STOI underestimates intelligibility by "
f"approximately {abs(lag) / len(x_clean):.3f} × STOI_range."
)
return lag
def evaluate_model_stoi(
test_pairs: list,
model,
fs: int = SAMPLE_RATE,
model_latency_samples: int = LSTM_OUTPUT_LATENCY_SAMPLES,
) -> dict:
"""
Evaluate speech enhancement model STOI across a test set.
Returns mean, std, and per-utterance scores.
"""
scores = []
for x_path, noisy_path in test_pairs:
x_clean, _ = sf.read(x_path)
x_noisy, _ = sf.read(noisy_path)
# Enhancement: model introduces LSTM_OUTPUT_LATENCY_SAMPLES latency
y_enhanced = model.enhance(x_noisy) # len = len(x_noisy) + latency
# Verify alignment on first pair (sanity check for new models)
if not scores:
try:
# Align y before cross-correlation check
y_trimmed = y_enhanced[model_latency_samples:model_latency_samples + len(x_clean)]
verify_signal_alignment(x_clean, y_trimmed, fs, max_lag_samples=5)
except ValueError as e:
print(f"[STOI alignment warning] {e}")
score = compute_stoi(x_clean, y_enhanced, fs, model_latency_samples)
scores.append(score)
scores_arr = np.array(scores)
return {
"mean": float(np.mean(scores_arr)),
"std": float(np.std(scores_arr)),
"per_utterance": scores_arr.tolist(),
"n": len(scores),
}
Why LSTM output latency causes STOI underestimation and why the 5-week investigation found no model problem
Three factors make this bug expensive. First, the LSTM latency is invisible from outside the model: the output array has a plausible length (len(x_clean) + 512), no exception is raised, and the audio sounds correct when played back. The 512-sample startup noise is 32 ms long — too short to perceive as silence on a listen, especially when it transitions smoothly into genuine enhanced speech. Second, pystoi’s silent truncation is a well-documented design decision (the STOI definition requires equal-length signals; truncation to the shorter is the natural resolution), but developers who have not read the full documentation assume pystoi will raise an error on length-mismatched inputs, as many other signal processing functions do. The absence of an error or warning on stoi(32000-sample x, 32512-sample y) means the developer has no feedback that the alignment is wrong. Third, STOI = 0.76 is a plausible score for a mediocre enhancement model — it corresponds to roughly 60–70% word intelligibility in human listening tests, which the developer attributed to the model requiring more training, better architecture, or more diverse training data. Five weeks of experiments addressed all these hypotheses: LSTM depth (1, 2, 3 layers), hidden size (128, 256, 512), training with SI-SNR loss vs MSE vs spectral loss, batch normalization vs layer normalization, dropout rate, and training data augmentation. None of these changes moved STOI above 0.78 because the problem was not the model — it was the measurement. The root cause was identified when the developer manually listened to y_enhanced[512:32512] (the latency-trimmed output) and found it sounded identical to y_enhanced[0:32000] (the untrimmed output) but scored STOI = 0.87 vs 0.76. Cross-correlation confirmed the 512-sample lag between the first 250 ms of x_clean and y_enhanced. Northfield Pystoi Ltd.’s retainer engagement was 2.0h: 0.25h triage (compute cross-correlation between x_clean[:4000] and y_enhanced[:4000]; peak lag at sample 512 confirms 32 ms temporal shift); 0.5h root cause (LSTM causal padding adds 512 zeros at input start; model output is shifted by 512 samples; pystoi truncates tail, keeping misaligned head; first 512 samples are startup noise, not speech); 0.75h fix (y_aligned = y_enhanced[512:][:len(x_clean)]; latency constant from model architecture; alignment verification utility); 0.5h validation (STOI 0.76→0.87 on 100-utterance sample; listening test confirms enhancement quality matches STOI score; model retraining not required; 2.0h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- pesq developer on retainer — pesq 0.0.4; Python 3.9;
pesq(fs=16000, ref=ref, deg=deg, mode='wb')raisesNoUtterancesErrorwhen signals differ in length; fix: trim both to same length; signal length assertion before evaluation; 1.5h - pyAudioAnalysis developer on retainer — pyAudioAnalysis 0.3.14; Python 3.9;
ShortTermFeatures.feature_extraction()returns features matrix; frame shift in samples not seconds; mismatch between documentation and implementation; 2.0h - speechpy developer on retainer — speechpy 2.4; Python 3.9;
mfcc(signal, sampling_frequency=16000, frame_length=0.025); developer setsframe_length=400(expecting 400 samples = 25ms); speechpy computes round(400 * 16000) = 6.4M-sample frame; every utterance returns MFCC shape (1, 13); LSTM accuracy 0.04; fix:frame_length=0.025; 2.0h
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 →