AI Logic

Architectures

HuBERT

Updated:

Architecture of HuBERT. Left: the overall pre-training pipeline (from the waveform, one branch goes CNN encoder → masking → Transformer → projection compared with cluster embeddings; the other uses an offline k-means teacher to produce target cluster IDs, trained with cross-entropy on masked time steps only). Right: rebuilding the teacher (k-means on MFCC into 100 clusters in the 1st iteration, on layer 6 of the 1st-iteration model into 500 in the 2nd, and on layer 9 of the 2nd-iteration model into 500 for LARGE and X-LARGE), with an example of the time steps where the loss is applied

Background and Overview

HuBERT (Hidden-Unit BERT) is a speech model that clusters untranscribed speech with k-means to create "pseudo-labels" and is pre-trained to predict the labels of masked segments, as in BERT. It was proposed in 2021 by Hsu et al. at Facebook AI. Its architecture is almost the same as wav2vec 2.0; the difference lies in the pre-training target.

Pre-training on speech poses three difficulties that text and images do not.

  • One utterance contains many sounds: Training that treats "one input = one class", as with images, cannot be used.
  • No predefined units like words: With text, the model simply predicts words from a vocabulary, but speech has no predetermined "vocabulary of sounds".
  • Sound boundaries are unknown: Without labels, it is unclear where one sound begins and ends.

HuBERT creates this "vocabulary of sounds" provisionally with k-means in a separate step. At first the clusters are coarse ones built from MFCC features, but by predicting only at masked time steps, the model can learn the structure of speech even from coarse labels. Afterwards, the clusters are rebuilt from the outputs of an intermediate layer of the trained model, gradually improving the labels.

In the paper, HuBERT was pre-trained on 960 hours of LibriSpeech or 60,000 hours of Libri-light, and matched or surpassed wav2vec 2.0 in word error rate in every fine-tuning setting: 10 minutes, 1 hour, 10 hours, 100 hours, and 960 hours. X-LARGE, with about 1 billion parameters, reduced errors relative to LARGE by up to 19% on dev-other and up to 13% on test-other.

Architecture

The HuBERT network has the same form as wav2vec 2.0. The left side of the figure at the top of the article shows the overall pre-training pipeline; the right side shows how the teacher cluster IDs are made and at which time steps the loss is applied.

  1. CNN encoder: Seven 1-D convolutional layers (512 channels, strides (5, 2, 2, 2, 2, 2, 2), kernel widths (10, 3, 3, 3, 3, 2, 2)) turn the 16 kHz waveform into one vector about every 20 ms (downsampling by a factor of 320).
  2. Masking: Some of these time steps are replaced by a shared learned vector.
  3. Transformer: A stack of encoders as in BERT produces an output oto_t at each time step.
  4. Projection and comparison: oto_t is transformed by a projection matrix AA, and the cluster probabilities are computed from the cosine similarity with the embedding ece_c of each cluster cc.
pf(c∣X~,t)=exp⁡(sim(Aot,ec)/τ)∑c′=1Cexp⁡(sim(Aot,ec′)/τ)p_f(c \mid \tilde{X}, t) = \frac{\exp\left(\mathrm{sim}(A o_t, e_c)/\tau\right)}{\sum_{c'=1}^{C} \exp\left(\mathrm{sim}(A o_t, e_{c'})/\tau\right)}

sim\mathrm{sim} is cosine similarity, τ=0.1\tau = 0.1 is the temperature, and CC is the number of clusters.

The three sizes in the paper are as follows. The CNN encoder is the same for all three.

ModelTransformer layersEmbedding dimFFN inner dimHeadsProjection dimParameters
BASE127683,072825695M
LARGE241,0244,09616768317M
X-LARGE481,2805,120161,024964M

The difference from wav2vec 2.0 is that there is no quantization module and no contrastive loss. Since the targets are cluster IDs supplied from outside, the model does not need to produce targets internally.

Training: Building a Teacher and Predicting Masked Time Steps

HuBERT's pre-training repeats two steps several times: "build teacher cluster IDs" and "predict the IDs at masked time steps".

Building the teacher cluster IDs (offline)

IterationFeatures clusteredClustersModel trained
1st39-dim MFCC (13 coefficients plus first- and second-order deltas)100BASE (250k steps)
2ndOutput of layer 6 of the 1st-iteration BASE500BASE (400k steps)
LARGE / X-LARGEOutput of layer 9 of the 2nd-iteration BASE500LARGE / X-LARGE (400k steps)

k-means uses scikit-learn's MiniBatchKMeans with mini-batches of 10,000 frames and k-means++ initialization. Because Transformer outputs are high-dimensional and the full dataset does not fit in memory, from the 2nd iteration on the clusters are fit on 10% of the training data.

Predicting the IDs at masked time steps

  1. Among the time steps of the CNN encoder output, p=8%p = 8\% are randomly chosen as start points, and the l=10l = 10 consecutive time steps from each are masked (the same scheme as wav2vec 2.0).
  2. The masked sequence X~\tilde{X} is passed through the Transformer to obtain cluster probabilities at each time step.
  3. Over the set MM of masked time steps, the log probabilities of the correct cluster IDs ztz_t are summed to form a cross-entropy loss.
Lm=−∑t∈Mlog⁡pf(zt∣X~,t)L_m = -\sum_{t \in M} \log p_f(z_t \mid \tilde{X}, t)

The paper defines the loss as L=αLm+(1−α)LuL = \alpha L_m + (1 - \alpha) L_u, combined with the loss LuL_u on unmasked time steps, and shows experimentally that α=1\alpha = 1 (masked time steps only) is robust to coarse teachers.

Optimization uses Adam (β=(0.9,0.98)\beta = (0.9, 0.98)), with the learning rate increased linearly from 0 to its peak over the first 8% of steps (warmup) and then decreased linearly to 0. The peak learning rate is 5×10−45 \times 10^{-4} for BASE, 1.5×10−31.5 \times 10^{-3} for LARGE, and 3×10−33 \times 10^{-3} for X-LARGE.

For fine-tuning, the projection layer is removed, a randomly initialized softmax layer is added, and the model is trained with CTC Loss. The outputs are the 26 English letters, a word boundary token, an apostrophe, and the CTC blank symbol. The CNN encoder is frozen, and for an initial number of steps only the new output layer is trained.

Why Coarse Teachers Still Work

The key points of HuBERT are two: predicting only at masked time steps and rebuilding the teacher.

Why predict only at masked time steps

Predicting the labels of unmasked time steps is a task of merely looking at the input sound and imitating k-means. If the teacher is coarse, the model simply memorizes that coarseness. The labels of masked time steps, by contrast, cannot be seen from the input and must be inferred from the surrounding context. The paper argues that in this case the model learns both to turn the visible parts into meaningful representations (an acoustic model) and to capture long-range relations between time steps (a language model).

The paper's comparison (BASE pre-trained for 100k steps and fine-tuned on 10 hours; dev-other word error rate in %) is as follows.

TeacherClustersMasked steps only (α=1\alpha = 1)All steps (α=0.5\alpha = 0.5)Unmasked steps only (α=0\alpha = 0)
k-means on MFCC10017.8629.5796.37
k-means on layer 6 of 1st-iteration BASE50011.9113.4723.29
k-means on layer 9 of 2nd-iteration BASE50010.7511.5913.79
Phone-state labels from transcripts (reference)8,97610.389.169.79

The coarser the teacher, the greater the benefit of training only on masked time steps. With accurate labels derived from transcripts, using all time steps is slightly better.

The paper argues that what matters in a teacher is "consistency" rather than "correctness". As long as similar sounds always receive the same ID, the model can learn the sequential structure of speech even if the IDs do not correspond one-to-one with actual phonemes.

Why rebuild the teacher

The outputs of an intermediate layer of the trained model reflect phonetic differences better than MFCC. The paper confirms this with a metric showing how much uncertainty about the phoneme is reduced by observing the cluster ID (PNMI; closer to 1 is better).

Features clustered100 clusters500 clusters
MFCC0.2530.285
Layer 6 of 1st-iteration BASE0.5610.684

(Mean of 10 runs, with k-means fit on 10 hours of data)

In the 1st-iteration model, intermediate layers around layer 6 are best, and cluster quality drops sharply in the last few layers. The paper suggests this is because, having been trained on a coarse teacher, the last layers imitate even the teacher's flaws. When rebuilding the teacher, use an intermediate layer rather than the last one.

Experimental Results

Word error rate with little transcribed data (LibriSpeech test-clean / test-other, in %; pre-trained on 60,000 hours of Libri-light and decoded with a Transformer language model)

Transcribed datawav2vec 2.0 LARGEHuBERT LARGEHuBERT X-LARGE
10 min4.8 / 8.24.7 / 7.64.6 / 6.8
1 h2.9 / 5.82.9 / 5.42.8 / 4.8
10 h2.6 / 4.92.4 / 4.62.3 / 4.0
100 h2.0 / 4.02.1 / 3.91.9 / 3.5

Only on 100-hour test-clean did HuBERT LARGE fall 0.1 points behind wav2vec 2.0 LARGE; in all other settings it was equal or better. It also beat DiscreteBERT, which has the same target (predicting cluster IDs) but takes quantized units as input, by a wide margin in every setting. The paper argues that using the raw waveform as input without quantization is important for not losing information.

Word error rate using all 960 hours (test-clean / test-other, in %)

ModelWord error rate
Conformer L (supervised only)1.9 / 3.9
wav2vec 2.0 LARGE1.8 / 3.3
HuBERT LARGE1.9 / 3.3
HuBERT X-LARGE1.8 / 2.9

This is state of the art among pre-training-only methods, but it does not reach methods that combine pre-training with self-training (pseudo-labeling), such as Conformer XXL + Noisy Student at 1.4 / 2.6%. The paper expects that HuBERT combined with self-training would perform equally well or better.

Practical Considerations

Keep the following points in mind when using HuBERT.

  • Input is a 16 kHz waveform: As with wav2vec 2.0, match the sampling rate used in training.
  • Pre-training takes a lot of work: k-means and pre-training are repeated several times, and running k-means on Transformer outputs requires a lot of memory. Usually one starts from publicly available pre-trained weights.
  • Choose the layer for building the teacher: Cluster quality varies greatly with the layer used for rebuilding. The paper uses layer 6 for the 1st-iteration model and layer 9 for the 2nd.
  • Masking ratio: In the paper's comparison, a start-point ratio of p=8%p = 8\% gave the best results. It also reports that larger batches and longer training reduce errors.
  • Recognition output is CTC: To reduce word errors, decode with beam search combined with a language model.

HuBERT's pre-training target is cluster IDs. The output of a model that has not been fine-tuned is not characters, so it cannot be used for speech recognition as is. For recognition, use weights fine-tuned with CTC.

The outputs of pre-trained HuBERT can also be used as features for tasks other than speech recognition. For example, UTMOS, which predicts the naturalness of speech, uses features extracted from self-supervised models such as HuBERT.

Comparison with Other Models

Comparing speech models pre-trained without transcripts from the same viewpoint gives the following.

ModelInputPre-training objectiveHow targets are madeAuxiliary techniques
DiscreteBERTQuantized units (vq-wav2vec)Predict the units at masked stepsQuantizer trained in a separate stageNone (teacher is fixed)
wav2vec 2.0Waveform (features from a CNN)Pick the quantized representation at masked steps from candidates (contrastive learning)Quantization module inside the model, trained jointlyDiversity loss, Gumbel-softmax temperature schedule
HuBERTWaveform (features from a CNN)Predict cluster IDs at masked steps (cross-entropy)Offline k-means, rebuilt at each iterationTeacher rebuilding

The paper summarizes the differences from wav2vec 2.0 as follows.

  • wav2vec 2.0's contrastive loss requires designing where to sample distractors from, a diversity loss, and temperature tuning. By creating targets externally, HuBERT gets by with an ordinary classification loss.
  • wav2vec 2.0 quantizes only the CNN encoder output, but the paper's analysis shows that intermediate Transformer layers yield much higher cluster quality.

Rough guidelines for choosing are as follows.

  • Speech recognition for languages or domains with few transcripts: Fine-tune pre-trained wav2vec 2.0 or HuBERT weights on the transcripts at hand. In the paper's results, HuBERT is equal or better in every setting.
  • Discrete, phoneme-like units: In the paper's analysis, IDs obtained by k-means on HuBERT's intermediate layers correspond better to phonemes than those from MFCC (PNMI rises from 0.25–0.29 to 0.56–0.69).
  • Multilingual recognition without extra training: Whisper, trained on large amounts of transcribed speech, is a good fit.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import HubertForCTC, Wav2Vec2Processor

"""
1. Transcribe speech with HuBERT LARGE fine-tuned on 960 hours of LibriSpeech, using Hugging Face transformers
2. A small implementation of the loss in Eqs. (1) and (3) of the paper: "predict cluster IDs only at masked time steps"
"""

# --- 1. Use for speech recognition ---
name = "facebook/hubert-large-ls960-ft"
processor = Wav2Vec2Processor.from_pretrained(name)  # Waveform normalization and character vocabulary (same format as wav2vec 2.0)
model = HubertForCTC.from_pretrained(name)
model.eval()                                         # Disable dropout and masking

waveform = torch.randn(16000 * 3)                    # Example: 3 seconds of audio. Always use 16 kHz mono
inputs = processor(waveform.numpy(), sampling_rate=16000, return_tensors="pt")
with torch.no_grad():
  logits = model(inputs.input_values).logits         # [1, time steps (about every 20 ms), vocab size]
print(processor.batch_decode(logits.argmax(dim=-1)))  # Greedy reading of the CTC output


# --- 2. Prediction loss on masked time steps only ---
class MaskedUnitHead(nn.Module):
  """Project the Transformer output o_t and form logits as cosine similarity with each cluster embedding e_c ÷ τ (Eq. 3)"""

  def __init__(self, dim=768, proj_dim=256, num_clusters=100, tau=0.1):
    super().__init__()
    self.proj = nn.Linear(dim, proj_dim)                    # Projection matrix A
    self.codes = nn.Parameter(torch.randn(num_clusters, proj_dim))  # Cluster embeddings e_c
    self.tau = tau

  def forward(self, o):                                     # o: [B, T, dim]
    a = F.normalize(self.proj(o), dim=-1)
    e = F.normalize(self.codes, dim=-1)
    return a @ e.t() / self.tau                             # [B, T, C]


def masked_prediction_loss(logits, targets, mask):
  """
  logits:  [B, T, C] cluster logits
  targets: [B, T]    correct cluster IDs z_t produced by k-means
  mask:    [B, T]    True at masked time steps (the paper uses α = 1: loss only here)
  """
  return F.cross_entropy(logits[mask], targets[mask])


B, T = 2, 150
o = torch.randn(B, T, 768)                                  # Transformer output (computed from the masked input)
z = torch.randint(0, 100, (B, T))                           # 1st iteration: IDs from k-means on MFCC (100 clusters)
mask = torch.rand(B, T) < 0.5
head = MaskedUnitHead()
head.train()
loss = masked_prediction_loss(head(o), z, mask)
loss.backward()
print(loss.item())

FAQ

Q. What is the main difference between HuBERT and wav2vec 2.0?
A.

How the pre-training targets are made. wav2vec 2.0 produces targets with a quantization module inside the model and is trained with contrastive learning, picking the correct answer from confusable candidates. HuBERT uses cluster IDs produced by offline k-means as targets and is trained with ordinary classification (cross-entropy). The network architecture is almost the same.

Q. Can coarse labels such as k-means on MFCC really yield useful representations?
A.

Yes, by predicting only at masked time steps. In the paper's comparison, with k-means on MFCC (100 clusters) as the teacher, training only on masked time steps gave a dev-other word error rate of 17.86%, while training only on unmasked time steps gave 96.37%, meaning almost nothing was learned. Rebuilding the labels from intermediate layers of the trained model further improves this to 11.91% and 10.75%.

Q. How many clusters should be used?
A.

The paper uses 100 for the 1st iteration (MFCC) and 500 from the 2nd iteration on (intermediate Transformer layers). For MFCC, the differences among 50, 100, and 500 clusters were small (17.86–18.68% on dev-other); which features are clustered affected the results far more than the number of clusters.

References

  1. Hsu, W.-N., Bolte, B., Tsai, Y.-H. H., Lakhotia, K., Salakhutdinov, R., & Mohamed, A. (2021). HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units. IEEE/ACM Transactions on Audio, Speech, and Language Processing, 29, 3451–3460. arXiv:2106.07447.
  2. Baevski, A., Zhou, H., Mohamed, A., & Auli, M. (2020). wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations. NeurIPS 2020. arXiv:2006.11477.
  3. Hugging Face. Transformers documentation: Hubert.