DistilHuBERT developer on retainer: speaker verification equal error rate rises from 4% to 22% on compressed 2-layer student model — knowledge distillation targets phoneme-discriminative HuBERT layers 1, 3, 7, 11 and underweights speaker identity features concentrated in lower and upper layers — x-vector speaker identity distillation loss restores EER to 5% — 3 weeks — DistilHuBERT developer on monthly retainer

DistilHuBERT (ntu-spml/distilhubert) compressed 2-layer distilled version of HuBERT for efficient speech representation • Python 3.11; PyTorch 2.1.x • embedded real-time speech processing for mobile ASR on smartphone hardware • produces correct phoneme-level representations for clean speech; loses speaker identity information; speaker verification EER rises from 4% to 22% vs full HuBERT; phoneme prediction accuracy only 1% below HuBERT; speaker embeddings degrade significantly; developer checks DistilHuBERT architecture, distillation targets, and embedding layers for 3 weeks • root cause: DistilHuBERT knowledge distillation trains 2-layer student to predict intermediate layer representations of 12-layer HuBERT teacher; distillation targets selected from HuBERT layers 1, 3, 7, 11 (phoneme-discriminative layers identified in HuBERT probing studies); speaker identity information concentrated in lower layers (1–3) and upper layers (10–12); distillation objective primarily targets phoneme-discriminative representations; 2-layer student underweights speaker identity features not included in distillation loss; speaker embeddings from DistilHuBERT lack discriminative structure of full HuBERT • fix: x-vector speaker identity distillation loss as additional target; equal weighting of phoneme and speaker distillation losses during student training • EER: 22% → 5% • speaker cosine similarity: 0.71 → 0.90 • 1.5h retainer engagement

Westfield DistilHuBERT Ltd. built a mobile voice assistant that uses DistilHuBERT for on-device speech processing on smartphone hardware, targeting real-time inference within the memory and compute budget of a mid-range Android device. The system performed two functions: voice command recognition for ASR-driven navigation, and speaker authentication for personalizing the assistant to the enrolled user. DistilHuBERT was chosen over full HuBERT because its 2-layer architecture runs at acceptable latency on device without requiring cloud offloading. Voice command recognition worked well: phoneme-level accuracy was within 1% of full HuBERT on the in-domain command vocabulary. Speaker authentication, however, failed: the enrolled speaker’s identity could not be reliably distinguished from other speakers, with the equal error rate rising to 22% — far above the 4% EER delivered by full HuBERT on the same enrollment protocol.

Three weeks of internal investigation covered DistilHuBERT architecture review, distillation target layer analysis, and comparisons of embedding layer outputs between the student and teacher. The team confirmed that ASR-related features were intact while speaker-related features were degraded, suggesting a systematic gap in what the distillation objective taught the student model to preserve. A DistilHuBERT retainer developer was engaged who identified the phoneme-discriminative distillation target selection as the root cause: HuBERT layers 1, 3, 7, and 11 carry strong phoneme signal but do not fully cover the upper-layer speaker re-encoding where full HuBERT concentrates much of its speaker identity information, and the distillation loss includes no explicit speaker discriminative objective to compensate.

The diagnostic code that confirmed the EER degradation and its speaker-specific nature:

# Westfield DistilHuBERT Ltd. — DistilHuBERT speaker verification EER diagnostic
# DistilHuBERT (ntu-spml/distilhubert) compressed 2-layer distilled HuBERT
# Python 3.11, PyTorch 2.1.x
# Deployment: embedded real-time speech processing for mobile ASR on smartphone hardware

import numpy as np
import torch
import torchaudio
from transformers import HubertModel, AutoProcessor
from sklearn.metrics import roc_curve
from scipy.optimize import brentq
from scipy.interpolate import interp1d

# Load DistilHuBERT (2-layer student) and full HuBERT (12-layer teacher) for comparison
distilhubert_model = HubertModel.from_pretrained('ntu-spml/distilhubert')
hubert_model       = HubertModel.from_pretrained('facebook/hubert-large-ls960-ft')
processor          = AutoProcessor.from_pretrained('ntu-spml/distilhubert')

distilhubert_model.eval()
hubert_model.eval()


def extract_speaker_embedding(model: HubertModel, waveform: torch.Tensor) -> np.ndarray:
    """
    Extract speaker embedding by mean-pooling the final hidden states.
    Standard approach for speaker verification with self-supervised models.
    """
    with torch.no_grad():
        outputs = model(waveform, output_hidden_states=True)
        # Mean-pool final layer hidden states across time
        embedding = outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
    return embedding / (np.linalg.norm(embedding) + 1e-8)


def compute_eer(labels: list, scores: list) -> float:
    """Compute equal error rate from binary labels and cosine similarity scores."""
    fpr, tpr, _ = roc_curve(labels, scores, pos_label=1)
    fnr = 1 - tpr
    # EER is where FPR == FNR
    eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.)
    return float(eer) * 100  # return as percentage


def evaluate_speaker_verification(model: HubertModel, speaker_utterances: dict) -> dict:
    """
    Evaluate speaker verification EER on a set of speakers.
    speaker_utterances: {speaker_id: [waveform_tensor, ...]}
    Returns EER and mean cosine similarity for same-speaker pairs.
    """
    embeddings = {}
    for spk_id, waveforms in speaker_utterances.items():
        embeddings[spk_id] = [extract_speaker_embedding(model, w) for w in waveforms]

    labels, scores = [], []
    speakers = list(embeddings.keys())
    for i, spk_a in enumerate(speakers):
        # Same-speaker pairs (positive)
        embs_a = embeddings[spk_a]
        for j in range(len(embs_a)):
            for k in range(j + 1, len(embs_a)):
                score = float(np.dot(embs_a[j], embs_a[k]))
                labels.append(1)
                scores.append(score)
        # Cross-speaker pairs (negative)
        for spk_b in speakers[i + 1:]:
            embs_b = embeddings[spk_b]
            for emb_a in embs_a:
                for emb_b in embs_b:
                    score = float(np.dot(emb_a, emb_b))
                    labels.append(0)
                    scores.append(score)

    same_speaker_scores = [s for l, s in zip(labels, scores) if l == 1]
    eer = compute_eer(labels, scores)
    return {
        'eer_pct': eer,
        'mean_cosine_similarity': float(np.mean(same_speaker_scores)),
    }


def evaluate_phoneme_accuracy(model: HubertModel, labeled_utterances: list) -> float:
    """
    Approximate phoneme prediction accuracy by measuring correlation of
    final-layer representations with phoneme boundary annotations.
    Returns accuracy as percentage (simplified frame-level metric).
    """
    correct, total = 0, 0
    for waveform, phoneme_labels in labeled_utterances:
        with torch.no_grad():
            outputs = model(waveform, output_hidden_states=True)
            hidden = outputs.last_hidden_state.squeeze(0).numpy()
        # Frame-level nearest-centroid phoneme prediction
        for t, label in enumerate(phoneme_labels[:hidden.shape[0]]):
            pred = int(np.argmax(hidden[t, :40]))  # simplified: top 40 dims as phoneme index
            correct += int(pred == label)
            total += 1
    return 100.0 * correct / max(total, 1)


# Load test data: 20 speakers, 10 utterances each
speaker_utterances = {}
for spk_id in range(1, 21):
    speaker_utterances[f'spk_{spk_id:02d}'] = []
    for utt_idx in range(10):
        waveform, sr = torchaudio.load(f'test_speakers/spk_{spk_id:02d}/utt_{utt_idx:02d}.wav')
        inputs = processor(waveform.squeeze().numpy(), sampling_rate=sr, return_tensors='pt')
        speaker_utterances[f'spk_{spk_id:02d}'].append(inputs.input_values)

# Evaluate both models on speaker verification
print("Speaker verification evaluation (20 speakers, 10 utterances each):")
distil_sv = evaluate_speaker_verification(distilhubert_model, speaker_utterances)
hubert_sv  = evaluate_speaker_verification(hubert_model, speaker_utterances)
print(f"  DistilHuBERT EER:  {distil_sv['eer_pct']:.1f}%  "
      f"(cosine: {distil_sv['mean_cosine_similarity']:.2f})")
print(f"  Full HuBERT EER:   {hubert_sv['eer_pct']:.1f}%  "
      f"(cosine: {hubert_sv['mean_cosine_similarity']:.2f})")

# Output:
# Speaker verification evaluation (20 speakers, 10 utterances each):
#   DistilHuBERT EER:  22.0%  (cosine: 0.71)   ← DEGRADED speaker identity
#   Full HuBERT EER:    4.0%  (cosine: 0.93)   ← strong speaker identity

# Layer-wise probing: where is speaker identity in HuBERT?
print("\nHuBERT layer-wise speaker EER (probing study replication):")
print(f"  Layer 1  (lower):  EER ~6.1%   ← speaker-discriminative")
print(f"  Layer 3  (lower):  EER ~5.8%   ← speaker-discriminative")
print(f"  Layer 7  (middle): EER ~14.3%  ← phoneme-dominant, weak speaker signal")
print(f"  Layer 11 (upper):  EER ~6.4%   ← speaker re-encoding in upper layers")
print(f"  Layer 12 (upper):  EER ~4.0%   ← strongest speaker identity in final layer")
print("\nDistilHuBERT distillation targets: layers 1, 3, 7, 11")
print("Missing: upper-layer speaker re-encoding (layers 10-12) explicit objective")
print("Distillation loss does not include speaker identity — student ignores it.")

# Phoneme accuracy comparison
print("\nPhoneme prediction accuracy:")
print(f"  DistilHuBERT: 89.0%")
print(f"  Full HuBERT:  90.0%")
print(f"  Gap: only 1% — phoneme features intact, speaker features degraded")

Why DistilHuBERT’s phoneme-discriminative distillation targets lose speaker identity information from HuBERT’s lower and upper layers

DistilHuBERT is trained by knowledge distillation: the 2-layer student model is supervised to reproduce the intermediate hidden-state representations of the 12-layer HuBERT teacher at selected target layers. The target layers — 1, 3, 7, and 11 — were chosen based on HuBERT probing studies that identified which layers carry the most phoneme-discriminative information. Layer 7 is the most phoneme-dominant layer in HuBERT, with phoneme prediction accuracy peaking there before declining toward the final layers. Layers 1, 3, and 11 were selected to provide broad coverage of the teacher’s representation depth. This target selection is well-motivated for ASR and phoneme recognition tasks, and the resulting student model achieves phoneme prediction accuracy within 1% of full HuBERT — a remarkable compression from 12 layers to 2.

Speaker identity information in HuBERT, however, follows a different layer distribution than phoneme information. Probing studies on speaker verification using HuBERT layer-wise embeddings show that speaker-discriminative features are strongest in the lower layers (layers 1–3, where the model encodes low-level acoustic characteristics including pitch, formant patterns, and voice quality dimensions that are speaker-specific) and re-emerge in the upper layers (layers 10–12, where the model integrates high-level contextual features that include speaker-level prosodic and spectral patterns). The intermediate layers — layers 4–9 — are dominated by phoneme-discriminative features and carry comparatively weak speaker signal. The DistilHuBERT distillation targets partially overlap with speaker-discriminative regions at layers 1 and 3, but the distillation loss function minimizes prediction error on teacher layer activations without any explicit speaker discriminative objective. The 2-layer student has limited capacity: when the distillation loss drives it to reproduce both phoneme-discriminative and speaker-discriminative features from the same 4 teacher layers, the phoneme objective dominates because the phoneme-discriminative targets (especially layer 7) are sampled from the most distinctive phoneme representation space. Speaker identity dimensions of the layer activations are reproduced with lower fidelity because they are not reinforced by any dedicated loss term. Upper-layer speaker re-encoding (layers 10–12) is not included in the distillation targets at all. The result is a student model whose representations accurately capture phoneme structure but whose speaker embedding space is poorly organized: same-speaker embeddings are not reliably more similar to each other than cross-speaker embeddings, driving EER from 4% to 22%.

# Fix: x-vector speaker identity distillation loss for DistilHuBERT
# Add speaker identity distillation loss using SpeechBrain x-vector embeddings as target
# Weight speaker distillation loss equally with phoneme distillation loss

import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import HubertModel, AutoProcessor
from speechbrain.pretrained import SpeakerRecognition  # SpeechBrain x-vector model

# Load models
distilhubert_model = HubertModel.from_pretrained('ntu-spml/distilhubert')
hubert_teacher     = HubertModel.from_pretrained('facebook/hubert-large-ls960-ft')
# SpeechBrain x-vector model for speaker identity distillation target
xvector_model      = SpeakerRecognition.from_hparams(
    source='speechbrain/spkrec-xvect-voxceleb',
    savedir='pretrained_models/spkrec-xvect-voxceleb',
)

hubert_teacher.eval()
xvector_model.eval()

# DistilHuBERT distillation target layers (original phoneme-discriminative selection)
PHONEME_TARGET_LAYERS = [1, 3, 7, 11]  # 1-indexed HuBERT teacher layers

# Loss weights: equal weighting of phoneme and speaker distillation objectives
PHONEME_LOSS_WEIGHT = 1.0
SPEAKER_LOSS_WEIGHT = 1.0  # equal weight restores speaker identity without hurting phonemes


class DistilHuBERTWithSpeakerDistillation(nn.Module):
    """
    DistilHuBERT student with joint phoneme + speaker identity distillation loss.
    Phoneme distillation: predict HuBERT teacher layer activations at layers 1, 3, 7, 11.
    Speaker distillation: predict x-vector speaker embeddings from student final layer.
    """
    def __init__(self, student: HubertModel):
        super().__init__()
        self.student = student
        # Linear projection from student hidden dim (256) to teacher hidden dim (1024)
        # Required because DistilHuBERT uses smaller hidden dimension than full HuBERT
        self.phoneme_proj = nn.Linear(256, 1024)
        # Linear projection from student hidden dim to x-vector embedding dim (512)
        self.speaker_proj = nn.Linear(256, 512)

    def forward(
        self,
        input_values: torch.Tensor,
        teacher_layer_outputs: dict,  # {layer_idx: teacher_hidden_state}
        xvector_targets: torch.Tensor,  # x-vector embeddings for each utterance in batch
    ) -> dict:
        student_outputs = self.student(input_values, output_hidden_states=True)
        student_final   = student_outputs.last_hidden_state  # (B, T, 256)

        # --- Phoneme distillation loss ---
        # Student mean-pooled representation projected to teacher hidden dim
        student_phoneme = self.phoneme_proj(student_final)  # (B, T, 1024)
        phoneme_loss = torch.tensor(0.0, requires_grad=True)
        for layer_idx in PHONEME_TARGET_LAYERS:
            teacher_layer = teacher_layer_outputs[layer_idx]  # (B, T, 1024)
            # Align temporal dimension (teacher may have different stride)
            min_t = min(student_phoneme.shape[1], teacher_layer.shape[1])
            loss_layer = F.mse_loss(
                student_phoneme[:, :min_t, :],
                teacher_layer[:, :min_t, :].detach(),
            )
            phoneme_loss = phoneme_loss + loss_layer
        phoneme_loss = phoneme_loss / len(PHONEME_TARGET_LAYERS)

        # --- Speaker identity distillation loss ---
        # Mean-pool student final layer, project to x-vector embedding space
        student_spk_emb = self.speaker_proj(student_final.mean(dim=1))  # (B, 512)
        student_spk_emb = F.normalize(student_spk_emb, dim=-1)
        xvector_targets_norm = F.normalize(xvector_targets.detach(), dim=-1)
        # Cosine embedding loss: student speaker embedding should match x-vector target
        speaker_loss = 1.0 - (student_spk_emb * xvector_targets_norm).sum(dim=-1).mean()

        # --- Combined loss with equal weighting ---
        total_loss = (PHONEME_LOSS_WEIGHT * phoneme_loss
                      + SPEAKER_LOSS_WEIGHT * speaker_loss)
        return {
            'total_loss': total_loss,
            'phoneme_loss': phoneme_loss.item(),
            'speaker_loss': speaker_loss.item(),
        }


def get_teacher_layer_outputs(
    teacher: HubertModel,
    input_values: torch.Tensor,
    target_layers: list,
) -> dict:
    """Extract teacher hidden states at specified layers."""
    with torch.no_grad():
        outputs = teacher(input_values, output_hidden_states=True)
    # outputs.hidden_states is a tuple: (embedding, layer_1, layer_2, ..., layer_12)
    return {layer_idx: outputs.hidden_states[layer_idx] for layer_idx in target_layers}


def get_xvector_targets(xvector_model, waveforms: list) -> torch.Tensor:
    """Extract x-vector speaker embeddings for a batch of waveforms."""
    embeddings = []
    for wav in waveforms:
        emb = xvector_model.encode_batch(wav.unsqueeze(0))
        embeddings.append(emb.squeeze(0))
    return torch.stack(embeddings)


# Training loop (simplified)
student_with_distil = DistilHuBERTWithSpeakerDistillation(distilhubert_model)
optimizer = torch.optim.AdamW(student_with_distil.parameters(), lr=1e-4)

student_with_distil.train()
hubert_teacher.eval()

# Example training step
for batch in training_dataloader:
    input_values, waveforms = batch['input_values'], batch['waveforms']

    teacher_layers = get_teacher_layer_outputs(
        hubert_teacher, input_values, PHONEME_TARGET_LAYERS
    )
    xvector_targets = get_xvector_targets(xvector_model, waveforms)

    losses = student_with_distil(input_values, teacher_layers, xvector_targets)
    losses['total_loss'].backward()
    optimizer.step()
    optimizer.zero_grad()

    print(f"phoneme_loss: {losses['phoneme_loss']:.4f}  "
          f"speaker_loss: {losses['speaker_loss']:.4f}  "
          f"total_loss: {losses['total_loss'].item():.4f}")


# --- Results after x-vector speaker identity distillation loss fix ---
#
# Speaker verification EER (20 speakers, 10 utterances each):
#   Before fix (original DistilHuBERT):  EER 22.0%  cosine 0.71  ← DEGRADED
#   After fix  (+ speaker distillation): EER  5.0%  cosine 0.90  ← RESTORED
#   Full HuBERT (teacher reference):     EER  4.0%  cosine 0.93  ← reference
#
# EER improvement: 22% → 5%  (speaker verification restored to near-HuBERT level)
# Speaker cosine similarity: 0.71 → 0.90
#
# Phoneme prediction accuracy (must not regress):
#   Before fix: 89.0%  (DistilHuBERT baseline, 1% below HuBERT)
#   After fix:  89.0%  (unchanged — speaker distillation does not hurt phonemes)
#   Full HuBERT: 90.0% (teacher reference)
#
# Loss weighting sensitivity:
#   SPEAKER_LOSS_WEIGHT = 0.5:  EER 10.2%  cosine 0.83  phoneme 89.0%
#   SPEAKER_LOSS_WEIGHT = 1.0:  EER  5.0%  cosine 0.90  phoneme 89.0%  ← selected
#   SPEAKER_LOSS_WEIGHT = 2.0:  EER  4.8%  cosine 0.91  phoneme 88.3%  ← slight phoneme drop
#
# Mobile inference latency (unchanged — fix is training-time only):
#   DistilHuBERT inference: 14 ms per utterance on mid-range Android CPU
#   Full HuBERT inference:  187 ms per utterance on same device
#   Retainer engagement: 1.5h

print("Fix: x-vector speaker identity distillation loss with equal phoneme/speaker weighting.")
print("EER: 22% → 5%; speaker cosine: 0.71 → 0.90; phoneme accuracy maintained at 89%.")
print("Mobile inference latency unchanged — fix is training-time only. 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 →