AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
♪Audio & Speech AI
  1. Audio Basics: From Sound Waves to Spectrograms
  2. Speech Recognition: CTC, wav2vec 2.0 and Whisper
  3. Speech Synthesis: From Text to a Natural Voice
  4. Music & Audio Generation: Codecs, Tokens and Diffusion
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Audio & Speech AI

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.

Intermediate~25 min·5 references
Key terms
Automatic speech recognition (ASR)Connectionist Temporal Classification (CTC)Word error rate (WER)WhisperMel spectrogramSelf-supervised learning

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.

≈
Analogy: the stenographer
A court stenographer hears a stream of sound and types letters without ever being told *which millisecond* belongs to which letter. They also use context: if they half-hear “terima ka…”, they write “terima kasih”. ASR models learn the same two skills — an acoustic skill (sounds → characters/tokens, with unknown timing) and a language skill (which word sequences are plausible).

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) = Σ_{a ∈ B⁻¹(y)} Πₜ p(aₜ | x) L_CTC = −log P(y | x)
B collapses a frame path a (e.g. “h h e _ l l _ l o o”) into text y (“hello”). Sum over all valid paths, product over frames.
In words: CTC does not need to know which frame belongs to which letter. It adds up the probability of every frame-level path a that collapses to the correct text y (merge repeats, then delete blanks); each path's probability is the product of the per-frame probabilities. Training minimizes the negative log of that total.
Symbols(hover a symbol in the formula)
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
T = 2 frames, symbols {a, _}, target y = “a”. Frame 1: p(a) = 0.6, p(_) = 0.4 Frame 2: p(a) = 0.7, p(_) = 0.3 Valid paths: “a a”, “a _”, “_ a” (all collapse to “a”) P = 0.6·0.7 + 0.6·0.3 + 0.4·0.7 = 0.42 + 0.18 + 0.28 = 0.88 L_CTC = −ln 0.88 ≈ 0.128 (“_ _” collapses to empty text, so it is not counted.)

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.

✓
Why this matters for Indonesian and regional languages
Self-supervised models pretrained on many languages (e.g. multilingual wav2vec 2.0 / XLS-R checkpoints on Hugging Face) can be fine-tuned with a few hours of transcribed Javanese, Sundanese or Minang speech — far less than training from scratch would need.

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.

Loading interactive…
Whisper end to end. Press Walk through to follow 30 s of audio from spectrogram to text, or tap the special tokens at the bottom right (language, task, timestamp) to see how one model handles several tasks. Notice that the encoder runs once per window while the decoder loops once per token.
ApproachHow it learnsStrengthsWeaknesses
CTC model (e.g. fine-tuned wav2vec 2.0)Per-frame labels + blank, summed over alignmentsFast, parallel decoding; streaming-friendly; little labeled data needed after SSLNo built-in language model; needs external LM for best accuracy
Attention encoder–decoder (Whisper)Decoder predicts next token, attending to the audioImplicit language model, punctuation, casing, translation, timestampsSlower (autoregressive); can hallucinate text on silence/noise
RNN-Transducer (RNN-T)CTC-like alignment + a prediction network over previous tokensStreaming with a built-in LM; used in on-device assistantsMore 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 = (S + D + I) / N
Reference “saya mau pesan nasi goreng” (N = 5), hypothesis “saya mau pesan nasi goreng dua”: I = 1 → WER = 20%. Hypothesis “saya pesan nasi koreng”: D = 1, S = 1 → WER = 40%.
In words: Align the model's output to the reference transcript with the minimum number of edits, count the wrong words (substituted), missing words (deleted) and extra words (inserted), and divide by the length of the reference. Lower is better; because insertions count, WER can exceed 100%.
Symbols(hover a symbol in the formula)
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
Reference: “saya mau pesan nasi goreng” → N = 5 Hypothesis A: “saya mau pesan nasi goreng dua” → I = 1 WER = (0 + 0 + 1) / 5 = 0.20 = 20% Hypothesis B: “saya pesan nasi koreng” → D = 1 (mau), S = 1 (goreng → koreng) WER = (1 + 1 + 0) / 5 = 0.40 = 40%

Decoding knobs

knobmodel size
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.
knobbeam_size
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).
knobtemperature (with fallback)
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).
knobchunk_length_s / stride
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.
knoblanguage / task
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

python
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.4
The Hugging Face pipeline handles decoding the file, feature extraction, chunking and timestamp stitching[4].
python
import 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']}")
The original openai-whisper package[5]; transcribe() resamples via ffmpeg and applies temperature fallback automatically.
!
Common pitfalls
Hallucination on silence: attention decoders like Whisper can invent fluent text (“Thanks for watching!”) on long silences or music — run voice activity detection (VAD) first. Unfair WER comparisons: “Pak Budi,” vs “pak budi” counts as an error unless you normalise case and punctuation identically for every system. Test-set leakage: public benchmarks may be in web-scraped training data. Domain shift: a model with 5% WER on audiobooks may hit 30% on noisy call-center audio — always evaluate on your own data. Privacy: voice is personal data (biometric in many laws, including Indonesia's UU PDP); get consent and secure storage.
▸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

1.
In CTC, a model outputs the frame sequence “k k _ a a _ _ k a”. What is the collapsed text?
2.
What is the main idea of wav2vec 2.0 pretraining?
3.
Reference has 10 words. The hypothesis has 1 substitution, 2 deletions and 1 insertion. What is the WER?
4.
Whisper outputs “Terima kasih sudah menonton” on a clip that is pure background music. What is the best fix?
5.
Why is CTC decoding usually combined with an external language model?
Score: 0/5

References

  1. [1]
    Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks
    PaperGraves et al.2006doi.org
    ICML 2006 — the CTC loss.
  2. [2]
    wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations
    PaperBaevski et al.2020arxiv.org
  3. [3]
    Robust Speech Recognition via Large-Scale Weak Supervision
    PaperRadford et al.2022arxiv.org
    Whisper.
  4. [4]
    Hugging Face Transformers — Automatic speech recognition task guide
    Docshuggingface.co
  5. [5]
    openai/whisper (official code and model card)
    DocsOpenAIgithub.com
← Previous
Audio Basics: From Sound Waves to Spectrograms
Next →
Speech Synthesis: From Text to a Natural Voice