AI Logic

Architectures

wav2vec 2.0

Updated

Architecture of wav2vec 2.0. Left: the overall pretraining flow (waveform → CNN feature encoder → latent representations Z → one branch is masked and passed through a Transformer to context representations C, the other passes through the quantization module to Q → contrastive loss and diversity loss). Right: the contrastive loss at a masked time step t (cosine similarity between c_t and the correct q_t plus K distractors) and the inside of the quantization module (one entry chosen from each of two codebooks, concatenated, and passed through a linear layer).

Background and Overview

wav2vec 2.0 is a model that pretrains speech representations on untranscribed audio alone and is then fine-tuned on a small amount of transcribed data for speech recognition. It was proposed by Baevski et al. at Facebook AI in 2020. It converts the waveform into a vector for each short segment with convolutions, masks some of them, and trains a Transformer to identify "which sound was in the masked segment" from a set of candidates.

The challenge in speech recognition is that transcribed speech is hard to collect. Practical accuracy requires thousands of hours of transcriptions, yet most of the world's roughly 7,000 languages have nowhere near that much data. Untranscribed speech, on the other hand, is available in large quantities. wav2vec 2.0 brings the "mask and predict" pretraining that BERT applied to text over to speech, and learns the structure of speech from this large pool of audio.

The main results of the paper are as follows (word error rate on LibriSpeech test-clean / test-other).

  • 4.8 / 8.2% with only 10 minutes (48 recordings) of transcribed data
  • With only 1 hour, it outperforms the previous best method (self-training) that used 100 hours
  • 1.8 / 3.3% using all 960 hours

Architecture

wav2vec 2.0 consists of the following three components. The left side of the figure at the top of the article shows the overall pretraining flow; the right side shows the training task at a masked time step and the inside of the quantization module.

ComponentInput → outputContents
Feature encoder ffWaveform XX → latent representations z1,
,zTz_1, \dots, z_TSeven blocks of 1D convolution (each block: convolution → layer normalization → GELU)
Context network ggZZ → context representations c1,
,cTc_1, \dots, c_TTransformer. Positional information is injected by a convolution instead of fixed positional encodings
Quantization moduleztz_t → quantized representation qtq_tSelects one entry from each of two codebooks, concatenates them, and applies a linear transformation

The feature encoder takes a 16 kHz waveform normalized to zero mean and unit variance. All seven convolutions have 512 channels, with strides (5, 2, 2, 2, 2, 2, 2) and kernel widths (10, 3, 3, 3, 3, 2, 2). The strides multiply to 320, so one vector is produced roughly every 20 ms (49 Hz), and each vector covers 400 samples (25 ms) of audio.

The context network is a stack of Transformer layers. The output of a convolution with kernel width 128 and 16 groups, passed through a GELU, is added to the input, followed by layer normalization. This convolution provides cues about relative position. The two model sizes in the paper are as follows.

ModelTransformer layersModel dimensionFeed-forward inner dimensionHeadsParameters
BASE127683,072895M
LARGE241,0244,09616317M

The quantization module replaces the continuous ztz_t with a combination of a finite number of "speech units". There are G=2G = 2 codebooks, each with V=320V = 320 entries. One entry is chosen from each codebook and concatenated, giving up to 3202=102,400320^2 = 102{,}400 combinations. Which entry to choose is decided by applying a Gumbel softmax to logits lg,vl_{g,v} computed from ztz_t.

pg,v=exp⁥((lg,v+nv)/τ)∑k=1Vexp⁥((lg,k+nk)/τ)p_{g,v} = \frac{\exp\left((l_{g,v} + n_v)/\tau\right)}{\sum_{k=1}^{V} \exp\left((l_{g,k} + n_k)/\tau\right)}

n=−log⁥(−log⁥u)n = -\log(-\log u) (where uu is uniform on 0–1) is Gumbel noise, and τ\tau is the temperature. The forward pass picks the single entry with the highest probability, while the backward pass uses the gradient of the softmax output (the straight-through estimator). This makes the whole model trainable by gradients even though it contains a discrete "selection" step.

Training: Pretraining and Fine-tuning

Pretraining proceeds in the following order.

  1. Pass the waveform through the feature encoder to obtain latent representations ZZ.
  2. Randomly select a proportion pp of the time steps of ZZ as starting points and mask the MM consecutive time steps from each (spans may overlap). The vectors at masked time steps are replaced with a single shared learned vector. With p=0.065p = 0.065 and M=10M = 10 as in the paper, about 49% of all time steps are masked, and the mean span length is 14.7 steps (about 299 ms).
  3. Pass the masked ZZ through the context network to obtain CC.
  4. Pass ZZ before masking through the quantization module to obtain the targets QQ.
  5. For each masked time step, compute a loss for identifying the correct qtq_t among other candidates from ctc_t.

The loss is the sum of a contrastive loss LmL_m and a diversity loss LdL_d (α=0.1\alpha = 0.1 in the paper).

L=Lm+αLdL = L_m + \alpha L_d

The contrastive loss makes the model pick qtq_t as the closest match to ctc_t from a set QtQ_t consisting of the true qtq_t and KK distractors sampled uniformly from other masked time steps of the same utterance (K=100K = 100 in the paper). Similarity is measured by cosine similarity sim(a,b)=a⊀b/∄a∄∄b∄\mathrm{sim}(a, b) = a^\top b / \lVert a \rVert \lVert b \rVert and divided by a temperature Îș=0.1\kappa = 0.1.

Lm=−log⁥exp⁥(sim(ct,qt)/Îș)∑q~∈Qtexp⁥(sim(ct,q~)/Îș)L_m = -\log \frac{\exp\left(\mathrm{sim}(c_t, q_t)/\kappa\right)}{\sum_{\tilde{q} \in Q_t} \exp\left(\mathrm{sim}(c_t, \tilde{q})/\kappa\right)}

This is a form of Contrastive Loss, the same form of loss as in SimCLR for images.

The diversity loss encourages codebook entries to be used evenly. It maximizes the entropy of each codebook's selection probability pˉg\bar{p}_g averaged over the batch.

Ld=1GV∑g=1G−H(pˉg)=1GV∑g=1G∑v=1Vpˉg,vlog⁡pˉg,vL_d = \frac{1}{GV} \sum_{g=1}^{G} -H(\bar{p}_g) = \frac{1}{GV} \sum_{g=1}^{G} \sum_{v=1}^{V} \bar{p}_{g,v} \log \bar{p}_{g,v}

The main pretraining settings in the paper are as follows.

ItemBASELARGE
Crop length per example250k samples (15.6 s)320k samples (20 s)
GPUs and days64 × V100 for 1.6 days128 × V100 for 2.3 days (LS-960), 5.2 days (LV-60k)
Updates400k250k (600k for LV-60k)
Peak learning rate5×10−45 \times 10^{-4}3×10−43 \times 10^{-4}
Gumbel softmax temperature τ\tau2 → 0.52 → 0.1

Optimization uses Adam, with the learning rate warmed up over the first 8% of updates and then decayed linearly. Dropout of 0.1 is applied to the Transformer and elsewhere, and LayerDrop, which randomly skips layers (the same idea as Stochastic Depth), is also used.

For fine-tuning, a randomly initialized linear layer is added on top of the context network to output characters (29 characters plus a word boundary for LibriSpeech), and the model is trained with CTC Loss.

  • For the first 10k updates only the output linear layer is trained; after that the Transformer is trained as well.
  • The feature encoder is not trained.
  • Time steps and channels of the feature encoder output are masked in a way similar to SpecAugment. The paper states that this delays overfitting and substantially lowers error rates, especially in low-resource settings.

Why It Works

The key design of wav2vec 2.0 is that the input to the Transformer stays continuous and only the prediction targets are quantized. In the paper's ablation (BASE, fine-tuned on 10 hours, word error rate on the combined dev-clean and dev-other validation sets, averaged over three runs), this combination gave the best result.

Input to the TransformerTargetsWord error rate (%)
ContinuousQuantized (wav2vec 2.0)7.97
QuantizedQuantized12.18
QuantizedContinuous11.18
ContinuousContinuous8.58

The paper explains the reasons as follows.

  • Why the input is continuous: quantization discards information. Keeping the input continuous preserves more information for building context representations.
  • Why the targets are quantized: continuous targets retain fine details specific to the recording, such as speaker voice characteristics and background noise. The model can use these to find the answer easily, and so fails to learn general representations useful for speech recognition. In fact, with continuous targets, the accuracy of picking the correct answer during pretraining rose from 62% to 78.0%, yet the error rate after fine-tuning got worse.

As an analogy with listening practice: if the masked part is checked against "the recording itself", it can be guessed from superficial cues such as pitch or noise. If the answer is rounded to a coarse unit, "which sound it is", the only way to succeed is to learn to understand the content.

Also, unlike prior work that learned quantization in a separate earlier stage (such as vq-wav2vec), wav2vec 2.0 learns quantization and context representations jointly, end to end. The paper reports that, compared with Discrete BERT, which learns quantization in a separate stage, it cuts the error rate by about one third in low-resource settings.

Both the correct answer and the distractors of the contrastive loss come from the same codebook. If only a tiny fraction of the codebook is used, the candidates become hard to tell apart and the task stops working well. To prevent this and make the model use many codebook entries, the paper adds the diversity loss LdL_d.

Experimental Results

Word error rate with little transcribed data (LibriSpeech test-clean / test-other, in %. Transformer language model)

Transcribed dataBASE (pretrained on LS-960)LARGE (LS-960)LARGE (LV-60k)
10 min6.9 / 12.96.8 / 10.84.8 / 8.2
1 h4.0 / 9.33.9 / 7.62.9 / 5.8
10 h3.2 / 7.83.2 / 6.12.6 / 4.9
100 h2.6 / 6.32.3 / 5.02.0 / 4.0

LS-960 is the 960 hours of LibriSpeech audio (transcriptions unused), and LV-60k is about 53k hours of audio collected from LibriVox. In the 100-hour setting, the previous best, Noisy student (self-training), achieved 4.2 / 8.6%. LARGE (LS-960) achieves 2.3 / 5.0% under the same conditions, reducing errors by 45% / 42%.

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

ModelPretrainingWord error rate
Conformer (supervised only)None1.9 / 3.9
Noisy student (self-training)Self-training on LV-60k audio1.7 / 3.4
LARGE (no pretraining)None2.1 / 4.6
LARGELS-9602.0 / 4.1
LARGELV-60k1.8 / 3.3

Compared with the same architecture without pretraining (2.1 / 4.6%), the benefit of pretraining is especially large on test-other. The paper also notes that these results come from a relatively simple setup, CTC with character outputs, and that switching to sequence-to-sequence models or word-piece vocabularies is expected to improve them further.

On TIMIT phoneme recognition (phoneme error rate, in %), LARGE (LS-960, no language model) achieves 7.4 on the dev set and 8.3 on the test set, below the previous best (9.6 / 11.6 by vq-wav2vec).

Practical Considerations

Keep the following points in mind when using wav2vec 2.0.

  • The input is a 16 kHz waveform: match the sampling rate used in training and normalize to zero mean and unit variance before feeding it in. 8 kHz telephone audio and the like do not fit as is.
  • The output is character CTC: a fine-tuned model outputs probabilities of characters (and blank) every 20 ms. To reduce word errors, decode with beam search combined with a language model. The paper's results also mainly use 4-gram or Transformer language models.
  • Fine-tuning procedure: the paper trains only the output layer for a fixed number of initial updates, keeps the feature encoder frozen, and applies masking-based data augmentation. Skipping these makes overfitting more likely with little data.
  • Pretraining is expensive: even BASE in the paper takes 1.6 days on 64 V100s. Usually one starts from publicly released pretrained weights.
  • Split long audio: the Transformer's cost grows quadratically with the number of time steps. Pretraining also uses 15–20 second crops, so split long recordings before feeding them in.

A model that has only been pretrained (before fine-tuning) cannot output characters. To use it for speech recognition, fine-tune it with CTC on transcribed data or use fine-tuned weights.

The closer the pretraining audio is to the audio you actually want to recognize (language, recording conditions, speaking style), the larger the benefit tends to be. In the paper, too, increasing the pretraining audio from LS-960 to LV-60k lowered the error rate in every setting.

Comparison with Other Models

Comparing representative models for speech recognition and speech representation learning from the same viewpoints gives the following.

ModelTrainingInputPretraining targetRecognition output
wav2vec 2.0Pretraining without transcriptions → fine-tuning with CTCWaveform (features from a CNN)Choose the quantized representation of a masked time step from candidates (contrastive learning)Characters (CTC)
HuBERTPretraining without transcriptions → fine-tuning with CTCWaveform (features from a CNN)Predict the cluster ID of masked time steps (clusters built by k-means from MFCC etc.)Characters (CTC)
ConformerSupervised learning on transcribed dataMel filterbanksNone (architectural design)Transducer decoder
WhisperSupervised learning on 680k hours of transcribed audio from the internetLog-mel spectrogramNone (trained with large-scale weak supervision)Generates text with an encoder-decoder

Rough guidelines for choosing are as follows.

  • Building a recognizer for a language or domain with few transcriptions: fine-tuning a self-supervised pretrained model such as wav2vec 2.0 or HuBERT on a small amount of in-house transcriptions is a good fit.
  • Prioritizing pretraining stability or representation quality: HuBERT replaces contrastive learning with cluster-ID prediction and reports results on par with or better than wav2vec 2.0.
  • Plenty of transcribed data and high accuracy in a single language: a supervised architecture such as Conformer is a candidate.
  • Multilingual use right away without extra training: a general-purpose model trained on large amounts of transcribed audio, such as Whisper, is a good fit.

PyTorch example

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

"""
1. Use wav2vec 2.0 (BASE) fine-tuned on 960 hours of LibriSpeech via Hugging Face transformers
   to transcribe audio (greedy reading of the CTC output)
2. A small, direct implementation of the contrastive loss in Eq. (3) of the paper
"""

# --- 1. Use it for speech recognition ---
name = "facebook/wav2vec2-base-960h"
processor = Wav2Vec2Processor.from_pretrained(name)  # holds waveform normalization and the character vocabulary
model = Wav2Vec2ForCTC.from_pretrained(name)
model.eval()                                         # disable dropout and masking

waveform = torch.randn(16000 * 3)                    # example: 3 s of audio; always use 16 kHz mono
inputs = processor(waveform.numpy(), sampling_rate=16000, return_tensors="pt")  # normalize to zero mean, unit variance
with torch.no_grad():
  logits = model(inputs.input_values).logits         # [1, time steps (~every 20 ms), vocab size]
pred_ids = logits.argmax(dim=-1)                     # most likely character at each step (incl. blank)
print(processor.batch_decode(pred_ids))              # merge repeats, drop blanks, produce strings


# --- 2. Contrastive loss L_m (Eq. 3) ---
def contrastive_loss(c, q, mask, num_negatives=100, kappa=0.1):
  """
  c:    [T, D] context network output (from the masked input)
  q:    [T, D] quantized representations (from Z before masking)
  mask: [T] True at masked time steps
  Makes the model pick q_t as the closest match to c_t among the true q_t and K distractors sampled from other masked steps
  """
  idx = mask.nonzero(as_tuple=True)[0]               # masked time steps
  n = idx.numel()
  # for each step, sample K from the other masked steps (with replacement)
  neg = torch.randint(0, n - 1, (n, num_negatives))
  neg = neg + (neg >= torch.arange(n).unsqueeze(1)).long()   # skip itself
  c_m = c[idx]                                       # [n, D]
  cand = torch.cat([q[idx].unsqueeze(1), q[idx][neg]], dim=1)  # [n, 1 + K, D] (index 0 is the positive)
  sim = F.cosine_similarity(c_m.unsqueeze(1), cand, dim=-1) / kappa  # [n, 1 + K]
  target = torch.zeros(n, dtype=torch.long)          # the positive is always index 0
  return F.cross_entropy(sim, target)                # = mean of −log softmax of the positive


T, D = 200, 256
c = torch.randn(T, D)
q = torch.randn(T, D)
mask = torch.rand(T) < 0.49                          # about 49% of time steps are masked in the paper
print(contrastive_loss(c, q, mask))

FAQ

Q. What do wav2vec 2.0 and BERT have in common, and how do they differ?
A.

They share the pretraining idea of masking part of the input and predicting the masked part from the surrounding context. The difference is what is predicted. BERT predicts masked words from a vocabulary, but speech has no fixed units like words. wav2vec 2.0 therefore uses quantized representations of speech segments as targets and learns by contrastive learning, choosing the correct answer from among distractors.

Q. How much transcribed data is needed?
A.

In the paper, LARGE pretrained on LV-60k (about 53k hours of audio) and fine-tuned on only 10 minutes of transcriptions achieves word error rates of 4.8 / 8.2% on LibriSpeech test-clean / test-other. However, this result uses a language model, and both the pretraining and fine-tuning audio are read English speech, a closely matched condition. It is safer to assume that more data is needed the further the domain or language is from that.

Q. Why is a "diversity loss" added to the loss?
A.

In the contrastive loss, both the correct answer and the distractors come from the same codebook, so if only a tiny fraction of the codebook is used, the candidates become indistinguishable. The diversity loss LdL_d maximizes the entropy of the batch-averaged selection probabilities so that all G×VG \times V entries are used evenly. The paper adds it with weight α=0.1\alpha = 0.1.

References

  1. 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.
  2. Baevski, A., Schneider, S., & Auli, M. (2020). vq-wav2vec: Self-Supervised Learning of Discrete Speech Representations. ICLR 2020. arXiv:1910.05453.
  3. Hugging Face. Transformers documentation: Wav2Vec2.