wav2vec2 developer on retainer: Wav2Vec2ForCTC called without attention_mask on padded batch — padding zeros attended by real audio frames — short utterances in long batch have corrupted representations — WER 48% not 6% on short clips — $380,000 — 8 months — wav2vec2 developer on monthly retainer

transformers 4.35.0 • torch 2.0.1 • Python 3.10; processor(audio_list, padding=True) returns input_values and attention_mask; model(input_values=inputs.input_values) called without attention_mask; padding zeros attended by real audio Transformer layers; short utterances (0.5–3 s) batched with long (20–35 s): 90–97% padding; CTC decoder on corrupted hidden states; WER 48.3% on short clips vs 6.1% with mask; overall WER 23.4% vs 5.8%; fix: model(input_values=..., attention_mask=inputs.attention_mask) • Westfield Wav2Vec2 Transcribe Ltd. (6-person medical transcription startup; 8 months; 2.0h)

Westfield Wav2Vec2 Transcribe Ltd. is a 6-person startup building a medical transcription platform for hospital outpatient clinics. Clinicians speak into a mobile tablet app to record symptom descriptions, medication histories, and brief patient ID confirmations; the platform uses facebook/wav2vec2-large-960h-lv60 to transcribe in real time. The batch inference code for the nightly evaluation pipeline was:

# evaluate_batch.py  (transformers 4.35.0, torch 2.0.1)
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
import torch

processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-large-960h-lv60")
model     = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-large-960h-lv60").to("cuda")
model.eval()

def transcribe_batch(audio_list: list[list[float]]) -> list[str]:
    # Pad to equal length within the batch
    inputs = processor(
        audio_list,
        padding=True,          # pads shorter clips with 0.0
        return_tensors="pt",
        sampling_rate=16000
    )
    # inputs.input_values:   [B, T_max]  float32 — real audio + padding zeros
    # inputs.attention_mask: [B, T_max]  int64  — 1=real, 0=padding  ← NOT USED

    with torch.no_grad():
        logits = model(
            input_values=inputs.input_values.to("cuda")
            # attention_mask omitted ← bug
        ).logits

    predicted_ids = torch.argmax(logits, dim=-1)
    return processor.batch_decode(predicted_ids)

# Test set WER by utterance length:
# 0.5–3 s  (patient confirmations: "yes", "no", "John Smith"):  WER 48.3%
# 5–15 s   (symptom descriptions):                              WER  9.4%
# 20–35 s  (medication histories):                              WER  7.2%
# Overall:                                                       WER 23.4%

When processor(..., padding=True) is called on a list of variable-length audio arrays, it pads each array to T_max (the length of the longest clip in the batch) using zeros and returns a corresponding attention_mask that marks which positions are real audio. If attention_mask is not passed to model.forward(), the Transformer attends to all T_max positions including the padded zeros, corrupting the hidden-state representations for real audio frames.

How padding attention corrupts short-utterance hidden states

# wav2vec2-large convolutional encoder stride: total downsample factor = 320
# At 16,000 Hz: 1 Transformer time step = 320 samples = 20 ms of audio

# BATCH COMPOSITION (nightly evaluation):
# Short clip: "yes" (1 second of real audio)
#   Input samples: 16,000
#   Transformer time steps (real): 16,000 / 320 = 50 steps
# Long clip: medication history (30 seconds)
#   Input samples: 480,000
#   Transformer time steps (real): 480,000 / 320 = 1,500 steps

# After processor(..., padding=True):
#   T_max = 1,500 steps (padded to longest in batch)
#   Short clip: 50 real steps + 1,450 padding steps
#   Padding fraction for short clip: 1,450 / 1,500 = 96.7%

# SELF-ATTENTION WITHOUT attention_mask:
# For a real audio position t (t ≤ 50 for the short clip):
#   h_t = Σ_{j=1}^{1500} α_{t,j} × v_j
# Attention weights α_{t,j} are softmax over 1,500 positions.
# Without masking: attention distributes across ALL 1,500 positions.
# Real positions j ≤ 50 collectively receive ~50/1500 = 3.3% of the attention budget.
# Padding positions j > 50 collectively receive ~1450/1500 = 96.7%.
#
# The convolutional encoder applied to padding zeros produces near-zero but
# non-identical features (leaky activations, batch norm with non-zero means).
# These near-zero padding features carry systematic structured noise that
# contaminates h_t for all real positions in the short clip.

# WITH attention_mask (correct behavior):
# attention_mask propagated through get_feat_extract_output_lengths():
#   raw mask [B, 16000] → reduced mask [B, 50] (for 1-second clip)
# For position t, attention only over real positions j ≤ 50:
#   h_t = Σ_{j=1}^{50} α_{t,j} × v_j
# Real audio features get full attention budget → clean representations

# QUANTIFIED EFFECT ON WER:
# Single-example inference (no padding, no mask needed):  WER 6.1%  ← reference
# Batch inference with attention_mask:                    WER 6.1%  ← same
# Batch inference without attention_mask:
#   clip padded to  2% of T_max (30-s clip):              WER  7.2%  ← minor
#   clip padded to 50% of T_max (5-s in 10-s batch):      WER 15.4%
#   clip padded to 97% of T_max (1-s in 30-s batch):      WER 48.3%  ← severe

Why the bug was invisible on the standard evaluation set

The team benchmarked WER on a held-out evaluation set during development. That evaluation set contained only medium-length utterances (10–20 seconds), batched together because they were sorted by length before batching. Within those homogeneous batches, the longest clip was not much longer than the shortest; padding was always <20% of the sequence. WER on that evaluation set was 7.1%, which the team considered acceptable. The clinical deployment mixed short patient confirmations with long dictation, producing the cross-length batches that exposed the bug.

# Development evaluation set: sorted by length, homogeneous batches
# Utterance length distribution: 90% of clips 8–18 seconds
# Padding within batch: <15% of T_max
# WER without attention_mask: 7.1%  ← looks acceptable
# WER with attention_mask:    6.9%  ← marginal difference

# Clinical deployment batch composition (mixed utterance types):
# Short patient confirmations: "yes" / "no" / patient name / DOB   0.5–3 s
# Symptom reports: "sharp pain in left shoulder since Monday"       5–15 s
# Medication histories: 20–35 s
# Batches sorted by submission order (not length) → cross-length mixing

# Eight months of model substitutions (all evaluated on mixed batches):
# facebook/wav2vec2-large-960h-lv60    WER 23.4%
# facebook/wav2vec2-large-xlsr-53      WER 24.1%  (multilingual; worse on English)
# facebook/wav2vec2-large-robust       WER 21.8%  (better noise robustness)
# Custom fine-tune on 300h clinical    WER 20.4%  (domain adaptation helps)
# Custom fine-tune + n-gram LM         WER 19.1%
# Beam search width 50                 WER 18.7%
# CEILING: 18.7% (without attention_mask)
# TARGET: <8%

# DIAGNOSIS — single example vs batch comparison:
# Single inference (batch_size=1, one "yes" clip):
#   logits = model(input_values=inputs.input_values.to('cuda')).logits
#   WER: 6.1%  ← no padding, no mask needed
# Batch inference (same "yes" clip, batched with 30-second clip):
#   logits = model(input_values=inputs.input_values.to('cuda')).logits
#   WER: 48.3%  ← same model, same audio, same code — different WER
# → bug is in batching, not the model

The retainer consultant identified the missing attention_mask in 2.0 hours: 0.5h to audit the batch inference code, notice attention_mask absent from the model() call despite processor(..., padding=True) returning it; 0.5h to reproduce the WER discrepancy between batch_size=1 (WER 6.1%) and batch_size=16 mixed-length (WER 23.4%) on the same audio files, confirming the issue was in the batching path; 0.5h to quantify the WER improvement by utterance length bucket (short clips: 48.3% → 6.1%; medium: 9.4% → 5.8%; long: 7.2% → 5.9%) with the fix applied; 0.5h to audit all inference call sites, add the attention_mask argument, and add a defensive assertion. Hours logged to HourTab with per-session breakdown.

# Fixed evaluate_batch.py

from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
import torch

processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-large-960h-lv60")
model     = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-large-960h-lv60").to("cuda")
model.eval()

def transcribe_batch(audio_list: list[list[float]]) -> list[str]:
    inputs = processor(
        audio_list,
        padding=True,
        return_tensors="pt",
        sampling_rate=16000
    )

    # Defensive check: ensure attention_mask is present for padded batches
    assert inputs.attention_mask is not None, (
        "attention_mask is None — this should never happen with padding=True"
    )

    with torch.no_grad():
        logits = model(
            input_values=inputs.input_values.to("cuda"),
            attention_mask=inputs.attention_mask.to("cuda")   # ← added
        ).logits

    predicted_ids = torch.argmax(logits, dim=-1)
    return processor.batch_decode(predicted_ids)

# After fix:
# 0.5–3 s  (patient confirmations):  WER  6.1%  (was 48.3%)
# 5–15 s   (symptom descriptions):   WER  5.8%  (was  9.4%)
# 20–35 s  (medication histories):   WER  5.9%  (was  7.2%)
# Overall:                            WER  5.8%  (was 23.4%)

# Note: for batch_size=1 (no padding), attention_mask is all-ones —
# passing it is a no-op but harmless. The safe default is to always pass it.

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 →