◆ AI All-in-One

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
↗ Plan a path here

Read first

Audio as DataThe Transformer

This leads to

—
The full path from zero — 30 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Matrices and Matrix Multiplication
  7. Partial Derivatives and Gradients
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Tensors and Shapes
  12. Gradient Descent
  13. Supervised Learning
  14. Audio as Data
  15. Linear Regression
  16. The Perceptron
  17. Logistic Regression
  18. Neural Networks
  19. Recurrent Neural Networks
  20. Backpropagation
  21. Activation Functions
  22. Vanishing and Exploding Gradients
  23. Normalization Layers: BatchNorm and LayerNorm
  24. LSTMs and GRUs
  25. Residual Connections
  26. Sequence-to-Sequence Models
  27. Attention
  28. Self-Attention and Multi-Head Attention
  29. Positional Encodings
  30. The Transformer
  31. 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:

  1. 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.
  2. 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.

audio: 30 s at 16 kHz log-mel80 × 3,000 2 conv layers3,000 → 1,500 frames Encoderself-attention blocks 1,500 audio vectors Decodermasked self-attention + cross-attention cross-attention <|sot|> <|en|> <|transcribe|> <|notimestamps|> The cat special tokens choose the task: language, transcribe ortranslate, timestamps or not; then the words so far next token: “sat”predicted one token at a time, like a GPT Whisperan encoder–decoder Transformer
Fig. 1 Whisper: an encoder turns 30 seconds of log-mel spectrogram into 1,500 audio vectors. A decoder generates the transcript one token at a time, looking at the audio through cross-attention. Special tokens at the start select the language and the task.

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.

1234567891011121314frame 1. Best symbol per frame␣ = blank (no new letter) h h ␣ e e ␣ l l ␣ l l o o ␣ 2. Merge repeatshh → h, ll → l, oo → o h ␣ e ␣ l ␣ l o ␣ 3. Remove blanksthe transcript h e l l o “hello” The blank between the two l's (frame 9) is what keeps “hello” from collapsing to “helo”.Training with CTC loss sums over every frame-level path that collapses to the correct text.
Fig. 2 CTC decoding. Take the most likely symbol per frame, merge repeats, then remove blanks. The blank between the two l's is what keeps the double letter.

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:

LCTC=−log⁡∑π ∈ B−1(y) ∏t=1Tpt(πt)L_{\text{CTC}} = -\log \sum_{\pi \,\in\, \mathcal{B}^{-1}(\mathbf{y})} \ \prod_{t=1}^{T} p_t(\pi_t)

Here y\mathbf{y} is the true transcript, π\pi is one frame-level path (one symbol per frame tt), pt(πt)p_t(\pi_t) is the model's probability of that symbol at frame tt, and B−1(y)\mathcal{B}^{-1}(\mathbf{y}) is the set of all paths that collapse to y\mathbf{y}. 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:

WER=S+D+IN\text{WER} = \frac{S + D + I}{N}

SS is substitutions, DD deletions, II insertions, and NN 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_prompt with 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

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

  1. 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?
  2. 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.
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A CTC model outputs the frame path -hh-e-ll-ll-oo- (where - is the blank). What text does it decode to?

  2. Reference: "the cat sat on the mat". Output: "a cat sat on the mat today". What is the word error rate?

  3. Your Whisper transcripts of meeting recordings contain repeated phrases and sentences nobody said, mostly during silent stretches. What is the best first fix?

  4. Vendor A reports 4% WER and vendor B 7% WER on different test sets with different normalisation. What should you do?

  5. Why is Whisper's training described as weak supervision?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face Audio Course

Hugging Face · 2023 · Beginner · Free

A free hands-on course on audio with Transformers, from waveforms and spectrograms to audio classification, speech recognition with Whisper and text-to-speech.

Tool

Whisper (official code and models)

OpenAI · Beginner · Free

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.

Book

Speech and Language Processing

Dan Jurafsky & James H. Martin · Intermediate · Free

The standard NLP textbook, kept up to date with chapters on Transformers and LLMs. Free drafts online.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/speech-recognition.md