fairseq developer on retainer: non-deterministic WER 9.1% ± 2.4% on identical call center audio — LayerDrop active at inference — model.eval() does not zero encoder.layerdrop — set encoder.layerdrop=0.0 fix — 3 weeks — fairseq developer on monthly retainer
fairseq (facebookresearch/fairseq) + wav2vec 2.0 large (wav2vec2-large-960h) • Python 3.9; PyTorch 2.0; self-supervised speech encoder trained on 960h LibriSpeech with CTC fine-tuning for English ASR • call center transcription API (8000 calls/day, avg 4.5 min each); WER SLA: <10% on internal call center test set; WER non-deterministic across identical audio batches: 9.1% ± 2.4% (range 7.2%–11.8%) with the same input audio replayed in separate API requests — observed after fairseq version upgrade to 1.0.0+ • developer investigates fairseq inference determinism, Transformer encoder layer behavior under model.eval(), LayerDrop training configuration, and WER variance source for 3 weeks • root cause: fairseq 1.0.0 introduced LayerDrop for Transformer encoder regularization; training used --layerdrop 0.1 (10% layer skip probability); model.eval() sets model.training=False and disables nn.Dropout throughout the model but does NOT zero model.encoder.layerdrop; fairseq’s TransformerEncoder.forward() applies torch.bernoulli skip on each encoder layer using self.layerdrop regardless of model.training state; 10% of encoder layers randomly dropped per forward pass during inference → stochastic encoder depth → WER variance • fix: explicitly set model.encoder.layerdrop = 0.0 after model.eval() and before inference • WER variance: ±2.4% → ±0.1% (deterministic); mean WER: 10.3% → 9.1%; 1.5h retainer engagement
Southfield Fairseq Ltd. had built an English call center transcription API for a contact center analytics platform serving 12 enterprise clients, processing 8000 calls per day averaging 4.5 minutes each. The API used a fairseq wav2vec 2.0 large model fine-tuned on 960 hours of LibriSpeech and an additional 400 hours of call center domain audio to achieve the <10% WER SLA required by the analytics platform. The pipeline ran on an 8×A100 GPU cluster using fairseq’s batch inference, returning JSON transcriptions with word-level timestamps. During a routine quarterly audit of transcript accuracy, the QA team discovered that the same call recording, submitted to the API at different times, was producing transcriptions with varying WER — some runs at 7.2% WER on the test set, others at 11.8%, with no changes to the audio input or model configuration between runs. The variance of ±2.4% across repeated runs of an identical 50-call held-out test set confirmed the issue was not measurement noise. A fairseq retainer developer was engaged to identify the source of inference non-determinism and restore WER to a consistent, reproducible value.
The developer’s investigation began by ruling out the most common sources of ASR inference variance: CUDA non-determinism from floating-point reduction order in multi-GPU operations (confirmed not the cause by running single-GPU inference with torch.use_deterministic_algorithms(True), which showed the same variance), and batch composition effects (confirmed not the cause by running single-call inference on each test utterance independently, which also showed variance). The developer then traced the variance to the encoder by logging the encoder output representations for the same audio across five inference runs and confirming they were different. Reading the fairseq TransformerEncoder source code revealed the LayerDrop mechanism: at model checkpoint load time, model.encoder.layerdrop was set to 0.1 from the training configuration, and TransformerEncoder.forward() drew torch.bernoulli samples with probability self.layerdrop for each encoder layer on every forward pass, with no check on model.training. The fix was a single line — model.encoder.layerdrop = 0.0 — added after model.eval(). The developer also checked all other fairseq model components for similar pattern: model.decoder.layerdrop (not applicable for CTC ASR), attention dropout (correctly zeroed by model.eval()), and feature extractor CNN dropout (correctly zeroed). With LayerDrop zeroed, WER variance dropped to ±0.1% (measurement noise from evaluation script floating-point precision), and mean WER improved from 10.3% to 9.1% because the full 24-layer encoder was now consistently used for all inference batches.
The diagnostic code that confirmed the LayerDrop root cause and validated the fix:
# Southfield Fairseq Ltd. — fairseq wav2vec 2.0 LayerDrop inference diagnostic
# fairseq (facebookresearch/fairseq) + wav2vec2-large-960h; Python 3.9; PyTorch 2.0
# Deployment: call center ASR, 8000 calls/day, avg 4.5 min each
# Problem: LayerDrop active at inference → WER non-deterministic ±2.4%
# Fix: model.encoder.layerdrop = 0.0 after model.eval()
import torch
import numpy as np
from fairseq import checkpoint_utils, tasks
from fairseq.data.audio.audio_utils import get_features_or_waveform
CHECKPOINT = "checkpoints/wav2vec2_large_callcenter_v3.pt"
TEST_AUDIO = [f"test_calls/call_{i:04d}.wav" for i in range(50)] # 50-call held-out set
TEST_REF = [open(f"test_refs/call_{i:04d}.txt").read().strip()
for i in range(50)]
def load_model(ckpt_path: str):
models, cfg, task = checkpoint_utils.load_model_ensemble_and_task([ckpt_path])
model = models[0]
model.eval()
return model, task
def transcribe_batch(model, task, audio_paths: list, device: str = "cuda") -> list:
model = model.to(device)
results = []
for path in audio_paths:
wav = get_features_or_waveform(path, need_waveform=True, use_sample_rate=16000)
wav_t = torch.from_numpy(wav).float().unsqueeze(0).to(device)
lengths = torch.tensor([wav_t.shape[1]], device=device)
with torch.inference_mode():
emission, _ = model(source=wav_t, padding_mask=None)
# CTC greedy decode
tokens = emission.argmax(dim=-1).squeeze()
results.append(task.target_dictionary.string(tokens))
return results
def wer(hyps: list, refs: list) -> float:
total_words, total_errors = 0, 0
for hyp, ref in zip(hyps, refs):
h, r = hyp.split(), ref.split()
# simple edit distance
dp = [[0]*(len(h)+1) for _ in range(len(r)+1)]
for i in range(len(r)+1): dp[i][0] = i
for j in range(len(h)+1): dp[0][j] = j
for i in range(1, len(r)+1):
for j in range(1, len(h)+1):
dp[i][j] = (dp[i-1][j-1] if r[i-1]==h[j-1]
else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]))
total_errors += dp[len(r)][len(h)]
total_words += len(r)
return total_errors / total_words if total_words else float("nan")
model, task = load_model(CHECKPOINT)
# --- Confirm encoder.layerdrop value from checkpoint ---
print(f"encoder.layerdrop from checkpoint: {model.encoder.layerdrop}")
# >>> encoder.layerdrop from checkpoint: 0.1
# --- Baseline: model.eval() only, encoder.layerdrop=0.1 retained ---
N_RUNS = 5
wers_baseline = []
for run in range(N_RUNS):
hyps = transcribe_batch(model, task, TEST_AUDIO)
wers_baseline.append(wer(hyps, TEST_REF))
# --- Fix: set encoder.layerdrop=0.0 after eval() ---
model.encoder.layerdrop = 0.0
wers_fixed = []
for run in range(N_RUNS):
hyps = transcribe_batch(model, task, TEST_AUDIO)
wers_fixed.append(wer(hyps, TEST_REF))
print()
print("fairseq wav2vec 2.0 — LayerDrop inference non-determinism diagnostic")
print("=" * 65)
print()
print(f" Baseline (encoder.layerdrop=0.1, model.eval() only):")
print(f" WER per run: {[f'{w*100:.1f}%' for w in wers_baseline]}")
print(f" Mean WER: {np.mean(wers_baseline)*100:.1f}%")
print(f" WER std: ±{np.std(wers_baseline)*100:.1f}%")
print()
print(f" Fix (encoder.layerdrop=0.0 after model.eval()):")
print(f" WER per run: {[f'{w*100:.1f}%' for w in wers_fixed]}")
print(f" Mean WER: {np.mean(wers_fixed)*100:.1f}%")
print(f" WER std: ±{np.std(wers_fixed)*100:.1f}%")
print()
print("Root cause: TransformerEncoder.forward() applies torch.bernoulli(self.layerdrop)")
print(" for each encoder layer regardless of model.training flag")
print(" model.eval() disables nn.Dropout (checks .training) but NOT LayerDrop")
print(" 10% of 24 encoder layers dropped per forward pass → stochastic encoder depth")
print(" Dropped layers = weaker acoustic repr → WER variance ±2.4%")
print()
print("Fix: model.encoder.layerdrop = 0.0 after model.eval()")
print(" Full 24-layer encoder used for all inference batches → deterministic")
print(" Mean WER: 10.3% → 9.1%; WER std: ±2.4% → ±0.1%")
print()
print("Retainer engagement: 1.5h total")
print(" Triage: 0.25h — WER variance confirmed identical audio across 10 runs")
print(" Root cause: 0.50h — TransformerEncoder LayerDrop skip traced; .training bypass")
print(" Fix: 0.50h — encoder.layerdrop=0.0 applied; all components audited")
print(" Validate: 0.25h — WER std ±2.4% → ±0.1%; mean WER 10.3% → 9.1%")
Why fairseq LayerDrop bypasses model.eval() determinism
PyTorch’s model.eval() contract is widely understood to disable stochastic behavior in neural network inference: it sets model.training=False, which causes all nn.Dropout modules to pass through their input unchanged (zero probability of zeroing any element), and causes nn.BatchNorm modules to use running mean and variance rather than batch statistics. This contract works because nn.Dropout and nn.BatchNorm check the self.training attribute in their forward() methods before applying stochastic behavior. The model.eval() call propagates model.training=False through the entire module tree via model.apply(), reaching every submodule. For the vast majority of PyTorch models using standard nn.Dropout, model.eval() is sufficient to guarantee deterministic inference.
LayerDrop in fairseq’s TransformerEncoder was implemented as a custom mechanism that predates the widespread adoption of the nn.Dropout training-mode convention. The layer-skip logic in TransformerEncoder.forward() checks self.layerdrop > 0.0 to decide whether to apply the bernoulli skip — it does not check model.training or any training-mode flag. This was an implementation choice made during fairseq’s rapid research development cycle: LayerDrop was added as a training-time regularization method with the expectation that users would zero encoder.layerdrop before inference as a matter of course. The fairseq documentation for wav2vec 2.0 fine-tuning does not explicitly warn about this requirement, and the standard pattern of model.eval() followed by inference produces silently incorrect (non-deterministic) behavior when the training checkpoint has layerdrop > 0.0. The practical consequence for production systems that fine-tune fairseq models internally is that any new training run with --layerdrop > 0.0 will produce a checkpoint that exhibits inference non-determinism unless the deployment code explicitly handles layerdrop zeroing. The robust fix is to add model.encoder.layerdrop = 0.0 immediately after model.eval() in all inference code, and to include a layerdrop value assertion in the deployment health check to catch regressions when new model checkpoints are deployed.
Related retainer posts
- OpenNMT-py developer on retainer — OpenNMT-py (OpenNMT/OpenNMT-py) 3.4.0; Python 3.9; Spanish→English medical records 2000/day; 20–30% phrase repetition rate; coverage_penalty=None; beam re-attends to high-confidence source tokens; fix: coverage_penalty=summary beta=5.0 — 3 weeks
- Hugging Face Accelerate developer on retainer — Hugging Face Accelerate; Python 3.9; large model distributed training; mixed-precision and gradient checkpointing configuration; throughput optimization — 3 weeks
- DeepSpeed developer on retainer — DeepSpeed; Python 3.9; large model training throughput optimization; ZeRO optimizer stage configuration; mixed-precision training configuration — 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 →