Level 3 In-Depth AI · Vision, Audio and Multimodal
Speech Recognition
Turning spoken audio into text. Modern systems turn a spectrogram into text with a neural network, either labelling frames and collapsing them with CTC, or generating the transcript token by token like Whisper. Word error rate is how they are judged, and they now run well on a laptop.
- Level
- ●●●●● Intermediate
- Reading
- 14 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 30 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 30 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Matrices and Matrix Multiplication
- Partial Derivatives and Gradients
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Tensors and Shapes
- Gradient Descent
- Supervised Learning
- Audio as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- Speech Recognition
Read them roughly in this order. See it on the concept map →
Why it matters
Automatic speech recognition (ASR), or speech-to-text, turns spoken language into written text. It is behind dictation on phones, voice assistants, automatic subtitles on video, meeting transcription and note-taking tools, call-centre analytics, medical dictation, accessibility for deaf and hard-of-hearing people, and searching podcasts and recordings. It is also the "ears" of voice interfaces to language models: many voice assistants transcribe what you say, send the text to an LLM, and speak the reply with text-to-speech.
ASR was a famously hard problem for decades. In 2022, OpenAI released Whisper, an open model trained on 680,000 hours of audio from the web, and accurate multilingual transcription became something anyone can run on a laptop for free. Knowing how these systems work helps you pick a model, prepare audio properly, read error rates honestly and avoid the strange failures they still have.
The intuition
Recall from Audio as Data that sound can be drawn as a spectrogram: a picture of which frequencies are loud at each moment, with about 100 columns (frames) per second. Speech leaves visible patterns in that picture. Vowels show bands of energy, "s" shows a hiss at high frequencies, and stop consonants such as "p" and "t" show a short silence and then a burst.
So speech recognition is like reading a strange, smeared kind of handwriting where letters stretch and squash depending on how fast someone talks. Two problems make it hard:
- Alignment: we know the transcript ("hello") and the audio (say 50 frames), but not which frames belong to which letter. People talk at different speeds, and sounds blend into each other.
- Ambiguity: "recognise speech" and "wreck a nice beach" sound almost identical. Resolving that needs knowledge of language, which words are likely, not just acoustics.
Modern systems solve these in one of two ways. CTC models label every audio frame with a letter or a "nothing new here" blank, then collapse the labels into text. Encoder–decoder models such as Whisper listen to the whole clip, then write the transcript token by token, like a language model that is listening.
Key idea Speech recognition maps a spectrogram to text. CTC labels each frame (with a special blank) and collapses repeats; encoder–decoder models like Whisper generate text token by token while attending to the audio. Both are judged by word error rate: the fraction of words substituted, deleted or inserted.
How it works
The input
Audio is resampled to 16 kHz mono and turned into a log-mel spectrogram with 25 ms windows every 10 ms (Audio as Data), so one second of speech becomes 100 frames of 80 numbers each. Some models (wav2vec 2.0, for example) start from the raw waveform with a learned convolutional front end instead. An acoustic model, the part of the system that maps sounds to symbols, then processes the frames. Today it is usually a The Transformer or a Conformer (a Transformer with convolution layers added, good at both local sound patterns and long-range context).
CTC: labelling frames without alignments
Connectionist temporal classification (CTC, 2006) lets you train on (audio, transcript) pairs without knowing which frame goes with which letter. The network outputs, for every frame, a probability distribution over the characters (or subword tokens) plus one extra symbol, the CTC blank, meaning "no new symbol here".
A frame-level path is turned into text by a fixed rule: merge repeated symbols, then delete blanks.
The blank does two jobs. It fills frames between sounds, and it separates genuinely repeated letters: "l l" with a blank between becomes "ll", while "l l" without one merges into a single "l".
Many frame paths collapse to the same text. With 4 frames, "-hi-", "hhi-", "h-ii" and "hhii" all give "hi". The CTC loss is minus the log of the total probability of all paths that collapse to the correct transcript:
Here is the true transcript, is one frame-level path (one symbol per frame ), is the model's probability of that symbol at frame , and is the set of all paths that collapse to . There are exponentially many such paths, but a dynamic-programming recursion (the forward algorithm) adds them all up efficiently. PyTorch's nn.CTCLoss does this for you.
CTC models are fast and non-autoregressive (all frames are predicted at once), and they are naturally suited to streaming. Their weakness is that each frame's prediction is made independently, so they have no built-in model of language. Systems often add an external language model when decoding with beam search (Decoding: Temperature, Top-k and Top-p), which rescues "recognise speech" over "wreck a nice beach".
Encoder–decoder models: Whisper
Whisper is a standard encoder–decoder The Transformer:
- Encoder: the 80-channel log-mel spectrogram of a 30-second window (3,000 frames) passes through two convolution layers, the second of which halves the length to 1,500 frames. Position embeddings are added, and a stack of self-attention blocks produces 1,500 audio vectors.
- Decoder: an autoregressive Transformer that generates text tokens one at a time. At each step it attends to its own previous tokens (masked self-attention, like GPT) and to all the audio vectors through cross-attention.
- Special tokens at the start of the decoder's input select the task:
<|startoftranscript|>, a language token such as<|en|>,<|transcribe|>or<|translate|>(translate speech into English), and whether to predict timestamps. One model therefore does language identification, transcription in about 99 languages, translation to English and timestamping.
Whisper's key ingredient was data, not architecture. It was trained on 680,000 hours of audio paired with transcripts found on the internet. Such transcripts are imperfect and only loosely checked, so this is called weak supervision: a huge amount of noisy labels instead of a small amount of perfect ones. The result is unusually robust: it handles accents, background noise and technical vocabulary far better than models trained on clean benchmark audio, even when those score better on the benchmark itself.
Model sizes range from tiny (39 million parameters) to large (1.55 billion). The large-v3 version (2023) uses 128 mel bands, and large-v3-turbo (2024) cuts the decoder from 32 layers to 4 for much faster decoding with little loss in accuracy. Whisper is still the most widely used open recogniser, but as of late 2026 it is no longer the most accurate: newer open models, such as NVIDIA's Canary and Parakeet families (Conformer encoders) and several Conformer-plus-LLM designs, have lower average WER on the Hugging Face Open ASR Leaderboard.
Self-supervised speech models
Labelled speech is scarce for most of the world's roughly 7,000 languages. wav2vec 2.0 (2020) pretrains on unlabelled audio: it masks parts of the latent speech representation and learns to identify the correct hidden part among distractors, a form of contrastive self-supervised learning. Fine-tuned with CTC on as little as 10 minutes of transcribed speech, it produced usable recognisers. HuBERT and later models refined the idea. This is the route to ASR for low-resource languages.
Measuring it: word error rate
Word error rate (WER) counts the word-level edits needed to turn the system's output into the reference transcript, divided by the number of words in the reference:
is substitutions, deletions, insertions, and the number of reference words. It is the word-level version of the character error rate in OCR and Document AI, computed with the same edit-distance algorithm.
Worked example. Reference: "the cat sat on the mat" (6 words). Output: "a cat sat on the mat today". There is one substitution (the → a), no deletion and one insertion (today), so WER = 2/6 ≈ 0.33. Note that WER can exceed 1 (100%) if the system inserts lots of extra words.
WER depends heavily on text normalisation. Are "Dr." and "doctor", "10" and "ten", or "OK" and "okay" different words? Are case and punctuation counted? Whisper's authors used a dedicated normaliser to make comparisons fair. Always normalise both texts the same way before comparing systems, and report which normalisation you used. As rough orientation, clean read English speech (the LibriSpeech "clean" test set) is transcribed by strong models with WER of a few per cent or less. Noisy, accented, conversational or multi-speaker audio is much harder.
Around the recogniser
A practical transcription system has more pieces:
- Voice activity detection (VAD) finds the stretches that contain speech, so silence and music are skipped. This saves compute and avoids hallucinated text.
- Long-audio chunking: Whisper works on 30-second windows, so long recordings are cut into chunks (ideally at pauses) and the results stitched together.
- Speaker diarisation answers "who spoke when?" and is needed for meetings and interviews. It is a separate model, for example from the pyannote toolkit.
- Streaming recognition emits text while the person is still speaking, as dictation and live captions require. CTC and RNN-Transducer models stream naturally. Whisper was designed for offline use, although streaming wrappers exist.
In code
A complete CTC recogniser trained from scratch on synthetic "speech". Each letter has its own characteristic spectrum and lasts a random 2 to 5 frames, with heavy noise. The model is never told which frames belong to which letter. It runs in under 10 seconds on a CPU.
import torch
import torch.nn as nn
ALPHABET = "-abcd" # index 0 is the CTC blank
torch.manual_seed(0)
sound_of = torch.randn(5, 16) # each letter has a characteristic 16-band "spectrum"
def make_batch(n):
"""Fake audio features: each letter lasts 2-5 frames, with noise. No alignment given."""
feats, targets, f_lens, t_lens = [], [], [], []
for _ in range(n):
letters = torch.randint(1, 5, (torch.randint(3, 7, (1,)).item(),))
frames = [sound_of[l].repeat(torch.randint(2, 6, (1,)).item(), 1) for l in letters]
x = torch.cat(frames) + 0.8 * torch.randn(sum(len(f) for f in frames), 16)
feats.append(x); targets.append(letters); f_lens.append(len(x)); t_lens.append(len(letters))
feats = nn.utils.rnn.pad_sequence(feats, batch_first=True)
return feats, torch.cat(targets), torch.tensor(f_lens), torch.tensor(t_lens)
def greedy_decode(log_probs, length):
"""Best symbol per frame, merge repeats, drop blanks."""
best = log_probs[:length].argmax(-1).tolist()
out, prev = [], None
for s in best:
if s != prev and s != 0:
out.append(ALPHABET[s])
prev = s
return "".join(out)
class Recogniser(nn.Module):
def __init__(self):
super().__init__()
self.rnn = nn.GRU(16, 64, batch_first=True, bidirectional=True)
self.out = nn.Linear(128, len(ALPHABET))
def forward(self, x):
return self.out(self.rnn(x)[0]).log_softmax(-1) # (N, T, 5)
model = Recogniser()
ctc = nn.CTCLoss(blank=0)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for step in range(601):
x, y, x_len, y_len = make_batch(32)
log_probs = model(x)
loss = ctc(log_probs.transpose(0, 1), y, x_len, y_len) # CTCLoss wants (T, N, C)
opt.zero_grad(); loss.backward(); opt.step()
if step % 200 == 0:
print(f"step {step:3d} CTC loss {loss.item():.3f}")
x, y, x_len, y_len = make_batch(200)
with torch.no_grad():
lp = model(x)
truths = ["".join(ALPHABET[i] for i in t) for t in torch.split(y, y_len.tolist())]
preds = [greedy_decode(lp[i], x_len[i]) for i in range(200)]
print("example:", truths[0], "->", preds[0])
print("exact-match accuracy:", sum(p == t for p, t in zip(preds, truths)) / 200)
# step 0 CTC loss 3.245
# step 200 CTC loss 0.126
# step 400 CTC loss 0.122
# step 600 CTC loss 0.209
# example: dacdb -> dacdb
# exact-match accuracy: 0.845
Every one of the 31 mistakes in this run involves a letter repeated twice in a row, such as "aaddc" read as "addc". Two identical sounds back to back look like one long sound, unless the model learns to put a blank between them. That is exactly the double-letter problem CTC's blank exists to solve, and real recognisers face it with words like "bookkeeper".
Running Whisper locally with OpenAI's openai-whisper package (needs ffmpeg installed; speech.mp3 is any recording, and the weights download on first use):
import whisper
model = whisper.load_model("turbo") # or "tiny", "base", "small", "medium", "large"
result = model.transcribe("speech.mp3") # language is detected automatically
print(result["text"])
for seg in result["segments"]:
print(f"[{seg['start']:6.1f} -> {seg['end']:6.1f}] {seg['text']}")
The same through Hugging Face Transformers, plus scoring with the jiwer package:
import jiwer
from transformers import pipeline
asr = pipeline("automatic-speech-recognition", model="openai/whisper-small")
hypothesis = asr("speech.wav", return_timestamps=True)["text"] # timestamps allow audio > 30 s
print(jiwer.wer("the cat sat on the mat", "a cat sat on the mat today")) # 0.333...
For speed on CPUs and small GPUs, faster-whisper (CTranslate2) and whisper.cpp run the same models several times faster.
Common pitfalls
- Hallucinations on silence and noise. Encoder–decoder models sometimes "transcribe" text that was never said, especially in silence, music or noise: repeated phrases, invented sentences, or video-outro phrases learned from web subtitles. Use voice activity detection to skip non-speech, and check the transcripts for repeated loops.
- Wrong sample rate or channels. Models expect 16 kHz mono. Libraries usually resample, but check, because feeding raw 44.1 kHz arrays by hand produces garbage.
- Comparing WER without the same normalisation. Punctuation, casing, numbers and contractions can change WER by many points. Normalise identically and report it.
- Benchmark WER is not your WER. Test on audio like yours: your microphones, accents, vocabulary and background noise. Names, jargon and code-switching (mixing languages) are frequent failure points. Whisper's
initial_promptwith key terms often helps. - Long audio. Naive 30-second chunking can cut words in half and lose context. Use chunking with overlap or at pauses (as the pipelines above do).
- Assuming one speaker. Without diarisation, a meeting transcript is a wall of text. Overlapping speech is still hard for all systems.
Watch out Transcripts look authoritative but are not verbatim truth. A dropped "not" reverses a sentence's meaning, and hallucinated phrases can appear in medical or legal records. For anything consequential, keep the audio, have a person check critical passages, and make clear to readers that the text was machine-generated. Recording and transcribing people also requires their consent in many jurisdictions.
Where it leads
- Multimodal LLMs feed audio features straight into language models, so they can listen, understand tone and reply in speech.
- Music and Voice Generation covers the reverse direction: text-to-speech and music.
- Data Augmentation for audio (SpecAugment, noise, speed changes) is standard in ASR training.
- Running Models Locally covers running Whisper and other models on your own hardware.
- AI in Your Daily Workflow shows practical uses such as transcribing meetings and voice notes.
A bit of history
Bell Labs' "Audrey" (1952) recognised spoken digits from a single speaker, and IBM's Shoebox (1962) understood 16 words. From the 1970s, statistical methods took over. Hidden Markov models combined with Gaussian mixture models, together with n-gram language models, dominated speech recognition from the 1980s to around 2010, largely thanks to work at IBM, CMU and Bell Labs. Fred Jelinek's group at IBM made the statistical approach mainstream.
Deep learning arrived in 2012, when Hinton, Deng and colleagues from several labs showed that deep neural networks inside HMM systems cut error rates substantially. Google, Microsoft and IBM deployed them within a few years. Graves introduced CTC in 2006, and Baidu's Deep Speech (2014) used it for end-to-end recognition. Attention-based encoder–decoders (Listen, Attend and Spell, 2015) and RNN-Transducers made fully neural systems standard. Microsoft reported human-level WER on the Switchboard conversational benchmark in 2016, with the caveats that come with any single benchmark. wav2vec 2.0 (2020) brought self-supervised learning to speech, and OpenAI's Whisper (September 2022) showed that large-scale weak supervision gives robust, multilingual, open models. Speech is now one more input stream for multimodal AI.
Try it
- Compute the WER of "please turn of the lights" against "please turn off the lights", then compute the CER. Why is WER so much harsher here?
- In the CTC code, change the noise from 0.8 to 1.5 and retrain. How does exact-match accuracy change? Then make every letter last 4–8 frames instead of 2–5.
- Try it: record yourself reading a paragraph with some names and technical terms. Transcribe it with Whisper "tiny" and "small" and compute the WER of each against what you actually read.
Hint for 1: one substitution in 5 words is a WER of 0.2. But only one character is missing out of 26, a CER of about 0.04.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Hugging Face Audio Course
A free hands-on course on audio with Transformers, from waveforms and spectrograms to audio classification, speech recognition with Whisper and text-to-speech.
Robust Speech Recognition via Large-Scale Weak Supervision
Whisper: a Transformer trained on 680k hours of audio for robust speech recognition.
Whisper (official code and models)
The open-source release of Whisper, with installation instructions, the list of model sizes and a simple command-line tool and Python API for transcription and translation.
Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks
Introduced the CTC loss, which trains a network to output label sequences from unsegmented input such as speech, without frame-by-frame alignments.
wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations
Learns speech representations from unlabelled audio by masking and contrastive prediction, then fine-tunes with CTC on very little labelled speech.
Speech and Language Processing
The standard NLP textbook, kept up to date with chapters on Transformers and LLMs. Free drafts online.
Fine-Tune Whisper For Multilingual ASR with Hugging Face Transformers
A step-by-step guide to preparing speech data, fine-tuning Whisper on a new language and measuring word error rate.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/speech-recognition.md