Ten minutes of transcripts, 48 short recordings, train a recognizer that makes about 8 errors per 100 words on hard audiobook speech. The trick is 53,200 hours of untranscribed audio, used first.
Pick how many hours of transcripts the model gets, then read what it hears. Switch between wav2vec 2.0 and HuBERT. Then we build, piece by piece, the encoder, the masking, the speech units and the two ways to predict them.
You need a little Python and the idea of a neural network trained by a loss. A transformer helps but is not required. We build the rest from zero.
Based on Baevski et al., wav2vec 2.0 (2020), Hsu et al., HuBERT (2021), Chen et al., WavLM (2021) and Baevski et al., data2vec (2022). The explanations, toys and devices here are our own.
Word error rates are the papers' LibriSpeech test results with a Transformer language model: wav2vec 2.0 Tables 1 and 2, HuBERT Tables II and III. Grey crosses are systems with no pretraining: a hybrid DNN/HMM on 100 h and wav2vec 2.0 LARGE from scratch on 960 h. The sentence is our own; we mark as many words wrong as the error rate gives for its 39 words.
Chapter 0
Measure the gap between transcribed and untranscribed speech
You want a speech recognizer for a language with few recordings that have text. A transcript is the text of what someone said, typed by a person who listened. Someone must listen to every second and type every word. The wav2vec 2.0 paper notes that most of the nearly 7,000 languages in the world have little transcribed speech.
Untranscribed audio is everywhere: audiobooks, radio, podcasts. The wav2vec 2.0 paper used 53,200 hours of public audiobooks from LibriVox, with no text at all. Its smallest labeled set was ten minutes: 48 recordings of about 12.5 seconds each.
Teal is untranscribed audio. Warm is the labeled set. Pick a labeled set, then turn the log scale off.
Hours from the wav2vec 2.0 paper, section 4.1: LV-60k is 53.2k hours of LibriVox audio; the labeled sets are the Libri-light 10 min, 1 h and 10 h splits, LibriSpeech train-clean-100 and all 960 h.
At ten minutes the untranscribed pool is 319,200 times bigger. On a linear scale the labeled bar is thinner than a pixel.
Self-supervised learning trains a model on a task it can grade by itself, with no human labels. For speech the task is: hide part of the audio, then predict what was there. To do it well, the model must learn which sounds exist and which sounds follow which. Then a small labeled set maps that knowledge to letters.
We score a recognizer by its word error rate (WER): the words it substitutes, drops or adds, per 100 words of the true text. In the wav2vec 2.0 paper, a hybrid system trained on 100 labeled hours with no pretraining gets 18.6% WER on the hard test set. The pretrained model with ten minutes of labels gets 8.2%.
Symptom: a recognizer trained on a few hours of transcripts works on its training speakers and fails on new ones.
Measure: WER on speakers it never heard, next to WER on the training set.
Fix: learn the sounds of speech from untranscribed audio first. That is this lesson.
Chapter 1
Follow one second of audio through both phases and name every shape
The recipe has two phases. Pretraining runs on untranscribed audio and solves a pretext task: a puzzle the data grades by itself. Fine-tuning runs on a small labeled set and teaches the real task, speech to letters.
| Phase | Data | Task | What it trains |
|---|---|---|---|
| Pretrain | 53,200 h, no text | predict hidden frames | encoder and transformer |
| Fine-tune | 10 min to 960 h, with text | frames to letters, CTC loss | a new output layer, then the transformer |
Each row is a stage with its output shape. Pick a phase and press Step to move the packet down.
Shapes for the BASE size: 512 encoder channels and 768 transformer dimensions (HuBERT Table I; wav2vec 2.0 BASE is the same). The 29 outputs are HuBERT's CTC vocabulary: 26 letters, a space, an apostrophe and a blank.
Read the shapes for one second at 16,000 samples per second. The encoder gives 49 frames of 512 numbers. The transformer turns them into 49 context vectors of 768 numbers, each one informed by the whole second. Fine-tuning adds one linear layer from 768 to 29 outputs.
The fine-tuning loss is CTC (connectionist temporal classification). The model outputs a letter or a blank at each frame. CTC adds up every way those per-frame outputs can spell the transcript, so nobody needs to mark which frame holds which letter.
Symptom: on ten minutes of labels, training loss falls and test WER rises after a few thousand steps.
Measure: WER on a held-out set at every checkpoint.
Fix: do what wav2vec 2.0 does. Keep the encoder frozen, train only the new output layer for the first 10,000 updates, and mask frames during fine-tuning too.
Chapter 2
Count the frames that seven strided convolutions make from raw audio
A microphone gives 16,000 numbers per second. A transformer cannot attend over 16,000 positions per second of speech, and one sample alone means nothing. So both wav2vec 2.0 and HuBERT start with a feature encoder: seven 1-D convolutions that read the raw waveform and output short frames.
There is no spectrogram. The convolutions learn their own filters during pretraining. Each layer has a kernel width k (how many inputs it reads at once) and a stride s (how far it jumps between reads). The widths are 10, 3, 3, 3, 3, 2, 2. The strides are 5, 2, 2, 2, 2, 2, 2.
How long is a layer's output? Call the input length L-in and the output length L-out.
L-out equals the floor of L-in minus k, over s, plus one.
Place the first window of width k at the start. Count how many jumps of s fit before the window runs off the end. Add one for the first window. That is L-out.
One second: L-in = 16,000, k = 10, s = 5. L-out = ⌊15,990 / 5⌋ + 1 = 3,199. The next six layers give 1,599, 799, 399, 199, 99 and 49 frames.
Each blue bracket is one frame: 25 ms of audio it sees, 20 ms after the one before. Drag the clip length.
Kernel widths and strides from wav2vec 2.0 section 4.2 and HuBERT Table I. The waveform is a made-up mix of tones.
Two numbers fall out. The strides multiply to 5 × 26 = 320 samples. So a new frame starts every 20 ms. Each frame sees 400 samples, 25 ms of sound. One second gives 49 frames, not 50: the first frame needs a full 25 ms window.
Symptom: a pretrained model gives nonsense on phone-call audio.
Measure: check the sample rate. At 8,000 samples per second, 320 samples are 40 ms, so every frame covers twice the time the model learned.
Fix: resample all audio to 16 kHz before the encoder.
Chapter 3
Choose span starts at random and see how much of the clip goes dark
This is the pretext task, taken from BERT. Hide some frames from the transformer. Ask it what was there, using only the frames around the gap. The answer is free: it is the audio you hid.
Hiding single frames is too easy. Sounds blend into their neighbours, so a model can fill one 20 ms hole by copying. So wav2vec 2.0 hides spans. It picks a share p of all frames as span starts, then masks each start and the M − 1 frames after it. Spans may overlap. Every masked frame gets the same learned vector in place of its own.
What share of frames ends up hidden? A frame stays visible only if none of the M frames at or just before it is a start. Each frame is a start with chance p. Call the hidden share f.
f is about one minus, one minus p, to the M.
Take the chance that one frame is not a start, 1 minus p. Multiply it by itself M times: no start anywhere in reach. That frame stays visible. One minus that is f.
wav2vec 2.0: 0.93510 = 0.511, so f = 0.489, about 49% masked. HuBERT: 0.9210 = 0.434, so f = 0.566. The paper reports about 49%, with merged spans of 14.7 frames (299 ms) on average.
Each cell is one 20 ms frame; yellow cells are the hidden ones. Drag the start chance and the span length, then resample.
Starts drawn without replacement, round(p × 250) of them, as in wav2vec 2.0 section 3.1. Our numpy run of the paper's setting on 15 s clips gives 49.1% masked and merged spans of 14.6 frames.
Merged spans run longer than M because neighbouring spans overlap. In the paper's setting, half the clip is dark and the model sees the other half.
Symptom: the pretext loss drops fast and the features help little after fine-tuning.
Measure: masked share and span length. With M = 1, every hole has two visible neighbours.
Fix: mask spans. The data2vec paper reports that speech needs span masking, where text can mask single tokens.
Chapter 4
See why predicting the exact vector blurs, and how a codebook gives crisp choices
A masked frame was a vector of 512 numbers. Why not predict those numbers directly? Because the gap is often ambiguous. A hidden 200 ms might hold "s" or "sh", and the context fits both.
A model trained with squared error predicts the average of what could be there. The average of "s" and "sh" is a vector halfway between, which no speaker ever made. A classifier instead puts a probability on each real option. So both methods predict a speech unit: an index into a finite set of learned sound types.
Purple dots are two real sounds, A and B. Pink is the model's guess. Drag the chance that the gap held A, and switch the target type.
An illustrative toy in two dimensions. Real frames have 512, but the average lands between the options in any number of dimensions.
wav2vec 2.0 learns its units with product quantization. It keeps G codebooks, each a list of V learned vectors called entries. For each frame it picks one entry from every codebook and joins them. How many different units can it make? Call that count N.
N equals V to the G.
The first codebook offers V choices. For each of them the second offers V more. With G codebooks, multiply V by itself G times.
V = 320 and G = 2 give N = 320 × 320 = 102,400 possible units, while the model stores only 640 entries.
A hard pick has no gradient. The Gumbel softmax fixes that: it adds random noise to the scores, picks the top entry going forward, and uses the soft probabilities going backward. Its temperature falls from 2 during training. The paper's analysis finds that many units specialize in particular phonetic sounds, with no phonetic labels given.
Symptom: the quantizer uses a few dozen entries for everything.
Measure: count how often each entry wins across a batch.
Fix: wav2vec 2.0 adds a diversity loss with weight 0.1 that rewards using all entries equally often.
Chapter 5
Score the true unit against 100 distractors and read the contrastive loss
wav2vec 2.0 turns each masked frame into a multiple-choice question. The transformer outputs a context vector for the gap. Then the model sees 101 candidate units: the true one for that frame and 100 distractors. It must point to the true one.
The distractors are the units of other masked frames in the same recording. So the model cannot win by noticing a different speaker or microphone; it must know which sound belongs in this gap.
Name the parts. The context vector at masked frame t is c-t. The true unit is q-t. The candidate set Q-t holds q-t and the distractors. Cosine similarity, sim, scores how well two vectors point the same way, from −1 to 1. A temperature κ (kappa) sharpens the scores.
L-m equals minus the log of: e to the sim of c-t and q-t over kappa, divided by the sum over q-tilde in Q-t of e to the sim of c-t and q-tilde over kappa.
Score every candidate against c-t. Turn the scores into shares that add to one. Take the share of the true unit q-t. The loss is minus its log: small when q-t gets most of the share.
With made-up similarities: 0.8 for q-t and 0.2 for each of 100 distractors, κ = 0.1. The true score is e8 = 2,981; the distractors give 100 × e2 = 739. Share 2,981 / 3,720 = 0.80, so L-m = 0.22. A blind guess gives log 101 = 4.62.
The green bar is the true unit's share; grey is all distractors together, with each one drawn small below. Drag the similarities, the count and the temperature.
K = 100 and κ = 0.1 are wav2vec 2.0's settings (section 4.2). We made up the similarities, and all distractors share one similarity to keep the arithmetic visible.
Set κ to 1 and the same similarities give the true unit under 2% of the share. A small temperature makes a 0.6 gap in similarity decisive. The full pretraining loss adds the diversity term: L = L-m + 0.1 × L-d.
Symptom: the contrastive loss stalls near log 101 = 4.62.
Measure: codebook use and the similarity gap between true units and distractors.
Fix: check the temperature, and keep the diversity loss on so the codebook does not collapse to a few entries.
Chapter 6
Run k-means by hand and turn every frame into a pseudo-label
wav2vec 2.0 learns its units and its predictor at the same time, with a temperature schedule and a diversity loss to keep both healthy. HuBERT splits the job in two. First, make the targets with a plain clustering tool. Second, train the model to predict them.
For the first round, HuBERT computes MFCC features for every frame: 13 coefficients that summarize the sound's spectrum, plus their first and second changes over time, 39 numbers. Then it runs k-means with 100 clusters. Each frame's cluster number is its pseudo-label: a label made by a machine, not a person.
k-means repeats two steps. Name a frame's features x-t and the centre of cluster c μ-c (mu-c). The assignment step gives frame t the label z-t.
z-t equals the arg-min over c of the squared distance between x-t and mu-c.
Measure the distance from x-t to every centre μ-c. Give the frame the number of the nearest one: that is z-t. Then move each centre to the mean of its frames, and repeat until nothing changes.
With made-up one-number frames 1.0, 1.4, 2.0, 6.0, 6.6, 7.4 and centres 2 and 5: the first three go to centre 2, the rest to 5. New centres: 1.47 and 6.67. A frame at 4.0 is 6.42 from the first and 7.11 from the second, so its label is cluster 1.
Dots are frames; their shape is the true sound, which k-means never sees. Purple stars are centres. Press Step, or change how many clusters.
An illustrative toy: four made-up sounds, 30 frames each, in two dimensions. Purity is HuBERT's phone purity: the share of frames whose cluster's most common sound is their own sound.
HuBERT clusters with scikit-learn's MiniBatchKMeans, 10,000 frames per batch, and k-means++ starts with 20 random tries. The labels do not need to be good. The paper's point is that they need to be consistent: the same sound should get the same number.
Symptom: with too few clusters, two different sounds share one label.
Measure: purity on a small set with phone labels, the way HuBERT does.
Fix: more clusters. HuBERT moves from 100 to 500 in later rounds.
Chapter 7
Train on masked pseudo-labels, then cluster the model's own features for better labels
Now mask spans as in Chapter 3, with p = 8% and spans of 10 frames. At each masked frame, the model predicts that frame's pseudo-label: one of 100 classes. This is BERT's task with clusters in place of words.
Name the parts. M is the set of masked frames. X-tilde is the clip with those frames masked. p-f of z-t given X-tilde and t is the model's probability for the true pseudo-label z-t at frame t.
L-m equals minus the sum over t in M of log p-f of z-t, given X-tilde and t.
For each masked frame, look up the probability p-f the model gave to the right cluster z-t. Take minus its log. Add these up over the masked frames only.
With made-up probabilities 0.6, 0.3 and 0.05 on three masked frames: 0.51 + 1.20 + 3.00 = 4.71. A blind guess over 100 clusters costs log 100 = 4.61 per frame.
Why masked frames only? HuBERT also tried a loss on visible frames. There the model can copy the frame's own sound and imitate k-means. On masked frames it must infer the sound from context, which is an acoustic model and a language model at once. The paper finds the masked-only loss holds up better when the clusters are poor.
Shapes are the true sounds. Purple stars are the k-means centres of each round's features. Step through the rounds and watch purity.
An illustrative toy: we pull the four made-up sounds apart by a set amount each round, then run k-means with 4 clusters. The rounds and layers are HuBERT's: MFCC, then layer 6 of round-one BASE, then layer 9 of round-two BASE.
The trick is iteration. A model trained on rough MFCC labels still learns features better than MFCCs. So cluster those features instead. HuBERT's second round runs k-means with 500 clusters on layer 6 of the first model. Its LARGE and X-LARGE models train on 500 clusters from layer 9 of the second-round BASE model.
| wav2vec 2.0 | HuBERT | |
|---|---|---|
| Targets | units learned with the model | k-means labels, made offline |
| Loss | contrastive, 100 distractors | cross-entropy over 100 or 500 classes |
| Extra parts | Gumbel schedule, diversity loss | rounds of re-clustering |
| Mask | p = 6.5%, M = 10 | p = 8%, M = 10 |
Symptom: the second round is no better than the first.
Measure: purity of clusters from each transformer layer.
Fix: cluster a middle layer. HuBERT picks layer 6 of 12; top layers lean toward the training targets.
Chapter 8
Plot word error against labeled hours for three pretrained models and two baselines
Both papers test the same way. Pretrain on Libri-Light audiobooks: 53,200 hours after wav2vec 2.0's cleaning, 60,000 in HuBERT's count. Fine-tune on 10 minutes, 1, 10, 100 or 960 hours of LibriSpeech transcripts. Score on test-clean and on test-other, the harder half with less clear speech.
Pink is wav2vec 2.0; purple is HuBERT, thin for LARGE and thick for X-LARGE. Grey crosses had no pretraining. Drag the labeled hours.
wav2vec 2.0 Table 1 (LARGE, LV-60k, Transformer LM) and Table 2; HuBERT Tables II and III (LL-60k, Transformer LM). Baselines: hybrid DNN/HMM on 100 h (5.8 / 18.6) and wav2vec 2.0 LARGE from scratch on 960 h (2.1 / 4.6), both from the wav2vec 2.0 tables. Lines between the five points are only a guide.
Three things stand out. First, the curves are flat: going from 10 minutes to 960 hours, 5,760 times more labels, cuts wav2vec 2.0's test-other WER from 8.2% to 3.3%. Second, at 100 hours the pretrained model makes 4.0% errors where the system with no pretraining makes 18.6%.
Third, HuBERT matches or beats wav2vec 2.0 at every amount in Table II except one: at 100 hours on test-clean, HuBERT LARGE is 0.1 behind. The X-LARGE model has 964 million weights, against 317 million for the LARGE models, so part of its gain is size.
Every number here uses a Transformer language model during decoding, which fixes many spelling slips. The wav2vec 2.0 appendix also reports results with no language model; the gap between few and many labels is wider there.
Symptom: your own ten-minute fine-tune scores far worse than the paper.
Measure: decode with and without a language model, and check that the test speakers are not in your pretraining audio.
Fix: compare like with like: same language model, same test split.
Chapter 9
Compare four answers to one question: what should a masked frame predict?
All four models mask spans of frames. They differ in the target they put behind the mask. Switch between them below.
Blue cells are frames, yellow is the masked span, pink is the context the transformer gives. The row above is the target. Pick a method.
A schematic. Settings from the papers: WavLM mixes noise or a second speaker into 20% of utterances, overlap under 50%; data2vec averages the top 8 of 12 teacher blocks for speech.
WavLM keeps HuBERT's pseudo-labels but changes the input. For some utterances it mixes in noise or part of a second speaker, under half the length. The target stays the pseudo-label of the main speaker's clean speech. So the model learns to pick one voice out of a mix, which helps tasks like speaker identification. WavLM trains on 94,000 hours (60,000 Libri-Light, 10,000 GigaSpeech, 24,000 English VoxPopuli) and led the SUPERB benchmark of many speech tasks.
data2vec drops discrete targets. A teacher, a copy of the model whose weights trail the student's as a slow moving average, sees the whole clip. Its block outputs at masked frames become the target. Name the output of teacher block l at frame t, after normalization, a-hat-l-t. The target y-t averages the top K blocks of the L in the teacher.
y-t equals one over K, times the sum over l from L minus K plus one to L, of a-hat-l-t.
Run the teacher on the clip with nothing masked. At frame t, take the outputs a-hat of its top K blocks and average them. The student, which saw the masked clip, must output y-t.
With made-up one-number outputs 0.2, 0.4, 0.5, 0.9, 1.1, 1.0, 1.3, 1.6 from blocks 5 to 12: y-t = 7.0 / 8 = 0.875. For speech the student regresses it with an L2 loss.
The teacher's weights follow the student's with a factor that rises from 0.999 to 0.9999, so its targets change slowly. The same recipe trains data2vec on images and text.
The units travel further. AudioLM uses k-means clusters of a related masked model, w2v-BERT, as its semantic tokens for generating speech. XLS-R pretrains wav2vec 2.0 on 436,000 hours in 128 languages. Whisper takes the other road: 680,000 hours of weakly labeled audio and no pretext task.
Symptom: features from a speech-recognition-tuned model work poorly for speaker or emotion tasks.
Measure: try a weighted sum of every layer's output, as SUPERB does; lower layers carry more about the speaker.
Fix: use the pretrained model, not the fine-tuned one, and pick a model trained for many tasks, such as WavLM.
Chapter 10
Keep the numbers, the checks and the core code in one place
A convolutional encoder turns 16 kHz audio into one frame every 20 ms. A mask hides about half the frames, in spans of 10. A transformer predicts a discrete unit for each masked frame: by picking it from 100 distractors (wav2vec 2.0) or by classifying a k-means pseudo-label (HuBERT). A little labeled data and a CTC layer then turn the features into text.
| Term | What it is | Number |
|---|---|---|
| Frame rate | product of the strides, 320 samples | 20 ms; 49 frames per second |
| Receptive field | audio one frame sees | 400 samples, 25 ms |
| Mask (wav2vec 2.0) | start chance p, span M | 0.065, 10: about 49% masked |
| Mask (HuBERT) | start chance p, span M | 0.08, 10: about 57% masked |
| Codebooks | G groups of V entries | 2 × 320: 102,400 units |
| Contrastive loss | distractors K, temperature κ | 100, 0.1 |
| HuBERT clusters | round 1, later rounds | 100 on MFCC, then 500 |
| Unlabeled audio | LibriVox audiobooks | 53.2k h (wav2vec 2.0), 60k h (HuBERT) |
| 10 min of labels | test-clean / test-other WER | 4.8 / 8.2 (wav2vec 2.0 LARGE) |
| 960 h of labels | test-clean / test-other WER | 1.8 / 3.3 (wav2vec 2.0), 1.8 / 2.9 (HuBERT X-LARGE) |
| Model sizes | BASE, LARGE, X-LARGE weights | 95M, 317M, 964M |
pythonimport numpy as np, torch, torch.nn.functional as F def n_frames(n_samples, kernels=(10,3,3,3,3,2,2), strides=(5,2,2,2,2,2,2)): L = n_samples for k, s in zip(kernels, strides): L = (L - k) // s + 1 # 16000 -> 49 return L def span_mask(T, p=0.065, M=10, rng=np.random.default_rng()): starts = rng.choice(T, round(p * T), replace=False) mask = np.zeros(T, bool) for s in starts: mask[s:s + M] = True # spans may overlap; about 49% masked return mask def contrastive_loss(c, q, negs, kappa=0.1): # c, q: [D]; negs: [K, D] from the same clip cands = torch.cat([q[None], negs]) # [K+1, D], true unit first logits = F.cosine_similarity(c[None], cands, dim=-1) / kappa return F.cross_entropy(logits[None], torch.tensor([0])) def hubert_loss(logits, labels, mask): # logits: [T, C]; labels: [T] k-means ids; mask: [T] bool return F.cross_entropy(logits[mask], labels[mask], reduction='sum') # masked frames only # HuBERT targets: from sklearn.cluster import MiniBatchKMeans # km = MiniBatchKMeans(100, batch_size=10000, n_init=20).fit(mfcc_frames); labels = km.predict(frames)
Now press Present or Teach and explain from memory: the frame count, the masked share, why units, the contrastive pick and HuBERT's loop. Then go back to the hero and say why ten minutes of labels are enough.
This lesson draws on Baevski, Zhou, Mohamed and Auli, wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations; Hsu et al., HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units; Chen et al., WavLM; Baevski et al., data2vec; and Babu et al., XLS-R. The toys, sentences and devices are our own.