Speech Recognition: CTC, wav2vec 2.0 and Whisper
How machines turn speech into text: the alignment problem, CTC, self-supervised pretraining with wav2vec 2.0, large-scale weak supervision with Whisper, and how to measure quality with WER.
Automatic speech recognition (ASR) powers meeting transcripts, YouTube captions, voice search, call-center analytics and accessibility tools. It is hard because speech is continuous (no spaces between words), varies with accent, speed and microphone, mixes with noise, and — in Indonesia especially — often code-switches between Indonesian, English and regional languages in one sentence. Modern systems solve this with deep networks trained on huge amounts of audio; this lesson explains the three ideas that matter most: CTC, self-supervised pretraining, and weakly supervised encoder–decoder models like Whisper.
The alignment problem
A log-mel spectrogram has ~100 frames per second, while people speak ~10–15 characters per second. The training data only says “this 4-second clip says *selamat pagi*” — not where each letter starts. Classic systems (HMM–GMM, then hybrid DNN–HMM) solved this with hand-built pronunciation dictionaries and forced alignment. End-to-end deep learning replaced that machinery with two main tricks: CTC (marginalise over all alignments) and attention-based encoder–decoders (let the decoder learn where to look).
CTC: Connectionist Temporal Classification
CTC (Graves et al., 2006)[1] lets a network output one symbol per frame from the vocabulary plus a special blank token “_”. A many-to-one collapse rule turns a frame sequence into text: (1) merge repeated symbols, (2) delete blanks. The blank is what allows real double letters: “l _ l” survives as “ll”. The loss sums the probability of every frame path that collapses to the correct transcript, computed efficiently with dynamic programming (the forward–backward algorithm), so no alignment labels are needed.
- P(y | x)
- probability of the transcript y given the audio features x
- Σ_{a ∈ B⁻¹(y)}
- sum over all frame paths a that collapse to y
- B⁻¹(y)
- the set of all paths that the collapse function B maps to y (⁻¹ = inverse: “which inputs give this output”)
- Πₜ
- product over all frames t = 1 … T
- p(aₜ | x)
- the model's softmax probability of symbol aₜ (a letter or blank “_”) at frame t
- L_CTC
- the CTC loss to minimize
- log
- natural logarithm; −log turns a probability near 1 into a loss near 0
▸Worked example
CTC assumes each frame's output is conditionally independent of the others given the audio, so it has no built-in language model. In practice CTC outputs are decoded with beam search plus an external n-gram or neural language model, which fixes many spelling errors. CTC is fast, non-autoregressive and naturally streaming-friendly, which is why it remains popular for on-device ASR.
wav2vec 2.0: learning from unlabeled speech
Transcribed audio is expensive, but raw audio is plentiful. wav2vec 2.0 (Baevski et al., 2020)[2] applies Self-supervised learning to speech: a CNN encodes the raw waveform into latent frames (~20 ms each), a Transformer builds contextual representations, and during pretraining spans of latent frames are masked. The model must pick the true quantized latent for each masked step among distractors (a contrastive loss), much like BERT's masked-word task. After pretraining, a small linear layer is added and the model is fine-tuned with CTC on labeled data. With 53k hours of unlabeled audio and only 10 minutes of labeled data it reached 4.8 / 8.2 WER on LibriSpeech test-clean / test-other.
Whisper: weak supervision at scale
Whisper (Radford et al., 2022)[3] takes the opposite route: a standard Transformer Encoder–Decoder trained with ordinary supervised learning on 680,000 hours of (noisily) transcribed audio collected from the web, in ~100 languages. The encoder reads 30-second log-mel windows; the decoder generates text tokens autoregressively, steered by special tokens such as <|id|> (language), <|transcribe|> or <|translate|> (task, translate = into English) and timestamp tokens. Because the training data is so diverse, Whisper is robust zero-shot: it works on new domains without fine-tuning, though fine-tuning still helps for specific accents or jargon.
| Approach | How it learns | Strengths | Weaknesses |
|---|---|---|---|
| CTC model (e.g. fine-tuned wav2vec 2.0) | Per-frame labels + blank, summed over alignments | Fast, parallel decoding; streaming-friendly; little labeled data needed after SSL | No built-in language model; needs external LM for best accuracy |
| Attention encoder–decoder (Whisper) | Decoder predicts next token, attending to the audio | Implicit language model, punctuation, casing, translation, timestamps | Slower (autoregressive); can hallucinate text on silence/noise |
| RNN-Transducer (RNN-T) | CTC-like alignment + a prediction network over previous tokens | Streaming with a built-in LM; used in on-device assistants | More complex, memory-hungry training |
Measuring quality: Word Error Rate
Word Error Rate (WER) counts the minimum number of word substitutions (S), deletions (D) and insertions (I) needed to turn the hypothesis into the reference (Levenshtein distance on words), divided by the number of reference words N. Lower is better; it can exceed 100% if the model inserts many words. For languages without spaces (Chinese, Japanese, Thai) or for very short words, the Character Error Rate (CER) is used instead.
- WER
- word error rate, usually written as a percentage
- S
- substitutions: reference words replaced by a different word
- D
- deletions: reference words the model left out
- I
- insertions: extra words the model added
- N
- number of words in the reference transcript
▸Worked example
Decoding knobs
- What it is
- Number of parameters of the ASR model, e.g. Whisper tiny (39M), base (74M), small (244M), medium (769M), large (1.55B), turbo (809M, fewer decoder layers).
- ↑ If you increase it
- Lower WER, especially for low-resource languages, accents and noise; but slower, needs more VRAM, higher cost per hour of audio.
- ↓ If you decrease it
- Runs on CPU/phone in real time, but noticeably more errors on names, rare words and non-English speech.
- Typical values
- small/medium for Indonesian on a laptop GPU; large-v3 or turbo for best quality.
- What it is
- How many partial transcripts the decoder keeps at each step (1 = greedy decoding).
- ↑ If you increase it
- Usually slightly lower WER and fewer weird outputs; cost grows roughly linearly with the beam; gains saturate around 5.
- ↓ If you decrease it
- Fastest; greedy decoding may lock into an early mistake or a repetition loop.
- Typical values
- 1 for real-time, 5 for offline transcription (Whisper CLI default).
- What it is
- Sampling randomness of the decoder. openai-whisper starts at 0 and retries with 0.2, 0.4, … if the output looks bad (too repetitive by compression ratio, or low average log-probability).
- ↑ If you increase it
- Helps escape repetition loops on hard segments, but transcripts become less deterministic and may contain invented words.
- ↓ If you decrease it
- Deterministic, most-likely text; can get stuck repeating the same phrase on noisy audio.
- Typical values
- 0 with fallback (0.0 → 1.0 in steps of 0.2).
- What it is
- For long audio, the pipeline splits the file into chunks (Whisper sees at most 30 s) with overlapping strides, then stitches the text.
- ↑ If you increase it
- More context per chunk, fewer boundary cuts, but higher memory and latency (capped at 30 s for Whisper).
- ↓ If you decrease it
- Lower latency (good for live captions), but words cut at boundaries are more often lost or duplicated.
- Typical values
- 30 s chunks with ~5 s stride for Whisper; batch chunks for throughput.
- What it is
- Forces the language token (e.g. Indonesian) and the task (transcribe vs translate-to-English) instead of auto-detecting.
- ↑ If you increase it
- Setting it explicitly avoids wrong-language transcripts (e.g. Indonesian detected as Malay) and skips language detection on the first 30 s.
- ↓ If you decrease it
- Leaving it on auto works for single-language files but can flip languages mid-file on code-switched speech.
- Typical values
- language='indonesian', task='transcribe'.
In code
from transformers import pipeline
import jiwer
asr = pipeline("automatic-speech-recognition",
model="openai/whisper-small",
chunk_length_s=30, device=0) # device=-1 for CPU
out = asr("rapat.wav",
generate_kwargs={"language": "indonesian", "task": "transcribe"},
return_timestamps=True)
print(out["text"])
for c in out["chunks"][:3]:
print(c["timestamp"], c["text"])
# Evaluate against a human transcript (normalise case/punctuation first!)
ref = "saya mau pesan nasi goreng"
hyp = "saya pesan nasi koreng"
print("WER:", jiwer.wer(ref, hyp)) # 0.4import whisper # pip install openai-whisper (needs ffmpeg)
model = whisper.load_model("small")
result = model.transcribe("rapat.mp3", language="id", beam_size=5)
print(result["text"])
for seg in result["segments"][:3]:
print(f"[{seg['start']:.1f}-{seg['end']:.1f}] {seg['text']}")▸Go deeper: streaming ASR and the CTC forward algorithm
The CTC forward variable αₜ(s) is the total probability of all paths that, after t frames, have produced the first s symbols of the blank-augmented label “_ y₁ _ y₂ _ … _”. It is updated from αₜ₋₁ of the same state, the previous state, and (if the symbols differ) the state two back — skipping a blank. P(y|x) is read off the last two states at the final frame. Cost is O(T·U), linear in both audio length and transcript length.
For live captions, models must emit text before the sentence ends. CTC and RNN-T encoders with limited right-context (chunked attention) do this natively; Whisper was designed for 30-second offline windows, so streaming wrappers re-run it on a sliding buffer and only commit words that stay stable across runs.
Quiz
References
- [1]Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural NetworksPaperGraves et al.2006doi.orgICML 2006 — the CTC loss.
- [2]wav2vec 2.0: A Framework for Self-Supervised Learning of Speech RepresentationsPaperBaevski et al.2020arxiv.org
- [3]
- [4]Hugging Face Transformers — Automatic speech recognition task guideDocshuggingface.co
- [5]openai/whisper (official code and model card)DocsOpenAIgithub.com