s3prl developer on retainer: upstream() returns all hidden layers as a list — all_hs[0] is the CNN feature output not the final Transformer representation — keyword spotting 63% vs 89% — $340,000 — 7 months — s3prl developer on monthly retainer

s3prl 0.4.17 • PyTorch 2.1.0 • Python 3.11; all_hs, all_len = upstream(wavs) returns hidden states from all layers; all_hs[0] is CNN feature extractor output — no Transformer attention; all_hs[-1] is the final Transformer layer with 12 layers of self-attention; developer writes features = all_hs[0] assuming first element is the primary output; 20-class keyword spotting ceiling 63.2% vs 89.4%; 7 months of tuning; $340,000; fix: features = all_hs[-1] • Eastfield Voice Commands Ltd. (4-person keyword spotting startup; 7 months; 2.5h)

Eastfield Voice Commands Ltd. is a 4-person startup building a keyword spotting engine for embedded voice UI applications. Their system must reliably recognize 20 English keywords (“yes,” “no,” “up,” “down,” “left,” “right,” “on,” “off,” “go,” “stop,” and ten more) from 1-second audio clips at 16 kHz. They trained on 105,000 utterances from Google Speech Commands v2 and used HuBERT-base via s3prl as their feature backbone. The feature extraction code was straightforward:

# features/hubert_extractor.py (s3prl 0.4.17)
import s3prl.hub as hub
import torch

upstream = hub.hubert_base()
upstream.eval()

def extract_features(wavs: list[torch.Tensor]) -> torch.Tensor:
    # wavs: list of 1-D float32 tensors at 16kHz, one per sample
    with torch.no_grad():
        all_hs, all_len = upstream(wavs)
        # all_hs: list of 13 tensors — len(all_hs) = 13 for HuBERT-base
        #   all_hs[0]: CNN feature output, shape [B, T, 512]   <-- no Transformer
        #   all_hs[1]: Transformer layer 1 output, [B, T, 768]
        #   ...
        #   all_hs[12]: Transformer layer 12 output, [B, T, 768]  <-- final
        features = all_hs[0]   # <-- BUG: CNN features, not Transformer output
    return features

The developer’s choice of all_hs[0] was an intuitive but incorrect assumption: in many Python APIs, the “primary” output of a function is at index 0 of a returned sequence. The upstream(wavs) return value all_hs is a list ordered from the bottom up — index 0 at the bottom of the network (the CNN), increasing indices toward the top. all_hs[-1] is the final Transformer layer, the richest representation. The HuBERT-base model has 1 CNN stage plus 12 Transformer encoder layers, so len(all_hs) = 13 and all_hs[0] is the CNN output with no self-attention at all. At no point did the s3prl API raise an exception, emit a warning, or indicate that the selected layer was unusual. Both all_hs[0] (shape [B, T, 512]) and all_hs[-1] (shape [B, T, 768]) are valid tensors that can be passed to a downstream classifier. The downstream LSTM accepted [B, T, 512] features without complaint.

Why CNN features cannot distinguish 20 keywords reliably

HuBERT’s convolutional feature extractor (the source of all_hs[0]) maps 16 kHz raw waveform samples to 512-dimensional feature vectors at 50 frames per second, using a stack of 7 convolutional layers with temporal strides. The receptive field of the final CNN layer spans approximately 400 samples (25 ms) of audio. Each output frame summarizes the local spectral energy in a 25 ms window without any information about neighboring frames. These features are analogous to learned filter-bank features — they capture spectral shape and temporal fine structure within a window, but have no mechanism for cross-frame reasoning.

Keyword spotting requires precisely the cross-frame reasoning that CNNs cannot provide. Distinguishing “go” from “no” requires detecting the voiced stop closure at the start of “go” followed by the vowel transition — a pattern spanning 50–120 ms and multiple frames. Distinguishing “left” from “let” requires detecting the final fricative vs. stop closure, which is affected by the preceding vowel duration and the word-final burst vs. frication that spans multiple frames of context. The HuBERT Transformer encoder applies 12 layers of multi-head self-attention over the full feature sequence, enabling each frame to attend over all other frames in the 1-second clip. By the final layer, each frame representation integrates the global sequential context of the entire keyword, making the representation for frame 15 of “go” different from frame 15 of “no” in ways that the CNN-only frame 15 representation cannot be. The accuracy difference between CNN features and final Transformer representations on a 20-class keyword task is not marginal: it represents the entire representational gap between a spectrogram-like feature and a contextually-grounded phonemic representation.

# Diagnostic: compare layer representations
# (run this probe before committing to a layer index)

upstream.eval()
with torch.no_grad():
    all_hs, all_len = upstream(wavs)

print(f"Number of layers: {len(all_hs)}")
# → Number of layers: 13  (1 CNN + 12 Transformer for HuBERT-base)

print(f"all_hs[0] shape:  {all_hs[0].shape}")
# → all_hs[0] shape:  torch.Size([4, 50, 512])   CNN features, dim=512
print(f"all_hs[-1] shape: {all_hs[-1].shape}")
# → all_hs[-1] shape: torch.Size([4, 50, 768])   Transformer, dim=768

# Note the dimension difference: CNN=512, Transformer=768
# If your downstream model expects 512-dim inputs and runs without error,
# you may be using CNN features (all_hs[0]) not Transformer features (all_hs[-1]).
# Check the shape before training.

Seven months of improvements against a ceiling

The team spent seven months pursuing model quality improvements, each of which was a reasonable engineering choice given the apparent problem:

# Seven months of interventions (extract.py still uses all_hs[0])

# Month 1: increase LSTM hidden size
# LSTM hidden=256 → hidden=512: 63.2% → 64.1%

# Month 2: bidirectional LSTM
# LSTM unidirectional → bidirectional: 64.1% → 65.3%

# Month 3: 2D convolution on feature sequence before LSTM
# Conv1D(512, 256, kernel=3) + LSTM: 65.3% → 66.0%

# Month 4: data augmentation
# time-stretch (0.9x, 1.1x) + pitch-shift (+/-1 semitone): 66.0% → 66.8%

# Month 5: collect 20,000 more utterances
# Total: 125,000 utterances: 66.8% → 67.1%

# Month 6: label smoothing + cosine LR schedule
# 67.1% → 67.3%

# Month 7: pre-finetune on larger keyword dataset, then fine-tune
# 67.3% → 67.6%

# CEILING: ~67.6%  (HuBERT-base benchmark: 96.3% on Google Speech Commands v2)
# Root cause untouched: features = all_hs[0]  (CNN only)

The gap between 67.6% and the published HuBERT-base benchmark of 96.3% was attributed to differences in evaluation protocol, training duration, and the team’s smaller fine-tuning dataset. At month 7 the team hired a retainer consultant who had debugged similar s3prl layer index issues previously. The retainer triage took 2.5h: 0.5h to audit the feature extraction code, find all_hs[0], and print the shape ([B, T, 512] vs. the expected [B, T, 768] for HuBERT-base Transformer output); 0.5h to verify that len(all_hs) = 13 and explain the CNN-first ordering to the team; 0.5h to change all_hs[0] to all_hs[-1], retrain the LSTM classifier from scratch (3 hours of GPU compute), and confirm that validation accuracy reached 89.4% — within the expected range for the team’s evaluation setup; 1.0h to explain the weighted-sum layer aggregation technique as a path to further gains (1–2 pp), write the assertion guard, and add comments in the codebase. Hours logged to HourTab with per-session breakdown.

# Fixed features/hubert_extractor.py

def extract_features(wavs: list[torch.Tensor]) -> torch.Tensor:
    with torch.no_grad():
        all_hs, all_len = upstream(wavs)

        # Assertion: verify we got the expected number of layers
        # HuBERT-base: 13 (1 CNN + 12 Transformer)
        # wav2vec2-base: 13 (1 CNN + 12 Transformer)
        # HuBERT-large: 25 (1 CNN + 24 Transformer)
        assert len(all_hs) > 1, (
            f"Expected multi-layer s3prl output, got {len(all_hs)} layers. "
            f"Check upstream model initialization."
        )

        # all_hs[0]  = CNN features (no attention) — dim 512, shape [B, T, 512]
        # all_hs[-1] = final Transformer layer     — dim 768, shape [B, T, 768]
        features = all_hs[-1]   # was: all_hs[0]

    return features

# After fix and retraining from scratch:
# Validation accuracy: 89.4%  (benchmark: ~96% — gap from eval protocol differences)

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 →