Skip to content
Generative models and multimodal Advanced 34 min read

Speech and audio: ASR and TTS

Audio is the hardest everyday signal to model directly: 16,000 to 48,000 numbers per second for a few words of meaning. Speech AI is the story of three representations that tame it: the log-mel spectrogram that recognisers read, the alignment that maps thousands of frames onto a handful of characters, and the neural codec that turns sound into a few hundred discrete tokens per second so that a language model can read and write it.

10,000 ft

Speech recognition (ASR) and speech synthesis (TTS) are among the oldest problems in AI, and each AI era rebuilt them: hidden Markov models with Gaussian mixtures from the 1980s, deep networks inside HMMs from 2012, end-to-end neural models from 2015, and since 2022 web-scale weakly supervised models (Whisper) and language models over audio tokens (VALL-E, Moshi). The ideas are shared with the rest of this track: the codecs are autoencoders with adversarial losses, modern TTS is flow matching or next-token prediction, Whisper's lesson about robustness is CLIP's (vision transformers and CLIP), and voice assistants increasingly put audio tokens straight into an LLM, as vision-language models do with image tokens.

2,000 ft

Recognition: resample to 16 kHz → log-mel spectrogram (80 values every 10 ms) → a convolutional stem that subsamples in time → a transformer or Conformer encoder → a decoder that solves the alignment problem, by CTC (per-frame labels with a blank, marginalised over alignments), a transducer (streaming), or attention (an autoregressive text decoder, as in Whisper). Synthesis: text → (normalise, phonemise) → an acoustic model that predicts a mel spectrogram, with explicit durations → a neural vocoder that invents the phase and produces the waveform; or, in the codec era, text + a 3-second voice prompt → a language model or flow-matching model over neural codec tokens → the codec's decoder.

Speech in and speech out
Speech in and speech out. waveform 16–24 kHz, log-mel 100 frames/s × 80, encoder Conformer / transformer, alignment CTC · transducer · attention, text, neural codec RVQ tokens, 12.5–75 frames/s, TTS model codec LM or flow matching, vocoder / codec decoder, speech, voice promptSpeech in and speech out. waveform 16–24 kHz, log-mel 100 frames/s × 80, encoder Conformer / transformer, alignment CTC · transducer · attention, text, neural codec RVQ tokens, 12.5–75 frames/s, TTS model codec LM or flow matching, vocoder / codec decoder, speech, voice prompt

Ground level

Sound as data

A microphone measures air pressure. Sampled 16,000 times a second at 16 bits, one second of speech is 16,000 numbers (256 kbit); the same second carries about two to three words. By the Nyquist theorem a 16 kHz sample rate captures frequencies up to 8 kHz, which holds nearly all of speech intelligibility; music and high-fidelity TTS use 24, 44.1 or 48 kHz.

Recognisers rarely read raw samples. They read a spectrogram: cut the signal into overlapping windows, take the Fourier transform of each, and keep the energy at each frequency. Whisper's front end, typical of the field, uses 25 ms windows (400 samples) every 10 ms (160 samples): 100 frames per second, each a 201-bin power spectrum. Two perceptual facts then shape it:

  • Pitch is roughly logarithmic in frequency. The difference between 100 and 200 Hz sounds like the difference between 1,000 and 2,000 Hz. The mel scale, \(m = 2595\log_{10}(1 + f/700)\), is close to linear below 1 kHz and logarithmic above. A bank of 80 triangular filters evenly spaced in mel pools the 201 bins into 80 numbers: narrow filters where speech has fine detail, wide ones above.
  • Loudness is roughly logarithmic in energy. So take the log.
02 kHz4 kHz6 kHz8 kHz 16 mel filters (Whisper uses 80): each output = energy under one triangle
A mel filterbank, drawn to scale with 16 filters over 0–8 kHz. The first filter spans about 240 Hz at its base, the last about 2.2 kHz: nine times wider. Low frequencies, where vowels and pitch live, get fine resolution; high frequencies are pooled coarsely. (With 80 filters, the spacing near 440 Hz is 36 Hz and near 3 kHz is 119 Hz; see Build it.)

Worked example: what Whisper reads

A 30-second clip at 16 kHz is 480,000 samples. The log-mel front end turns it into \(3{,}000\times80 = 240{,}000\) numbers, half as many but, more importantly, arranged as 3,000 frames of perceptually meaningful features. Whisper's two-convolution stem (the second with stride 2) halves the frame rate, so the encoder's transformer sees 1,500 positions for 30 seconds: 50 per second. The transcript of 30 seconds of conversational English is roughly 75–90 words, perhaps 100–120 text tokens. The encoder sequence is still more than ten times longer than the output, and nothing says which frames belong to which word.

The alignment problem

That last sentence is the central difficulty of ASR. Training data gives you an utterance and its transcript, not the time at which each letter was spoken; speakers stretch, compress and pause. A model must learn the alignment as well as the labels. Three solutions survive:

Three ways to align frames to text
Three ways to align frames to text. encoder states h₁ … h_T (T large), CTC label or blank per frame, sum over all alignments, transducer (RNN-T) encoder × prediction net → joiner; streams, on-device, attention decoder autoregressive text, cross-attends to all frames, y₁ … y_U (U small)Three ways to align frames to text. encoder states h₁ … h_T (T large), CTC label or blank per frame, sum over all alignments, transducer (RNN-T) encoder × prediction net → joiner; streams, on-device, attention decoder autoregressive text, cross-attends to all frames, y₁ … y_U (U small)

CTC (Graves et al. 2006) lets the network output, at every frame, either a character or a special blank _. A per-frame path such as _cc_aa_t_ is mapped to text by a many-to-one function \(\mathcal{B}\): merge repeated symbols, then delete blanks, giving cat. A repeated letter needs a blank between its copies (l_l → ll, but ll → l). Training maximises the probability of the transcript summed over every path that collapses to it; a dynamic programme (the forward algorithm, below) does that sum in \(O(TU)\) time, although the number of paths grows exponentially. CTC assumes the frame outputs are conditionally independent given the audio, so on its own it has no language model; production systems decode it with beam search plus an external LM. Trained CTC models are famously peaky: they emit blank almost everywhere and each character in a single spike.

Transducers (RNN-T, Graves 2012) remove the independence assumption with a prediction network, a small language model over the labels emitted so far, combined with the encoder state by a joiner at every (frame, label) pair. Like CTC they are monotonic and can stream: they emit text as audio arrives, which is why on-device dictation systems tend to be transducers.

Attention encoder–decoders (Listen, Attend and Spell, Chan et al. 2015) treat ASR as translation: an autoregressive decoder writes the transcript token by token, cross-attending to all encoder states. LAS reached 14.1% WER on a Google voice-search task without a language model (10.3% with rescoring). They are the most flexible (any output format, punctuation, translation, timestamps as tokens) and the least streamable, and they can hallucinate: an autoregressive decoder can keep writing fluent text that the audio does not support. Whisper is this kind of model.

Encoders and self-supervised speech

Deep Speech 2 (Amodei et al. 2015) showed that a large end-to-end CTC model (convolutions and recurrent layers) trained on thousands of hours could compete with the pipeline systems. The encoder then moved to transformers, and the Conformer (Gulati et al. 2020) combined them with convolutions: each block sandwiches self-attention (global context) and a depthwise convolution module (local patterns such as formant transitions) between two half-step feed-forward layers. It reached 2.1%/4.3% WER on LibriSpeech test-clean/test-other without a language model and 1.9%/3.9% with one, and Conformer variants remain the standard ASR encoder.

Labelled speech is expensive; unlabelled speech is plentiful. wav2vec 2.0 (Baevski et al. 2020) masks spans of the encoder's input latents and trains a transformer to identify the true quantised latent for each masked position among distractors: a contrastive task in the spirit of CLIP and BERT. Fine-tuned with CTC on just 10 minutes of labelled LibriSpeech, it reached 4.8/8.2 WER (clean/other) after pre-training on 53k hours of unlabelled audio; with all 960 labelled hours, 1.8/3.3. HuBERT (Hsu et al. 2021) replaced the contrastive task with BERT-style masked prediction of discrete targets obtained by offline k-means clustering, first of MFCC features, then of its own earlier hidden states, iterating. Those cluster IDs turned out to be a useful discrete "phonetic" vocabulary, an idea that returns below as semantic tokens.

Whisper: weak supervision at web scale

Self-supervised models need fine-tuning for each new dataset, and fine-tuned models overfit to it. Whisper (Radford et al. 2022) took the opposite route: a plain transformer encoder–decoder trained on 680,000 hours of audio paired with transcripts found on the internet. Of those, 117,000 hours covered 96 languages other than English, and 125,000 hours were speech in another language with an English translation. Five details carry the design:

  1. Inputs: 30-second windows of 80-channel log-mel spectrogram, padded or trimmed; long audio is transcribed window by window.
  2. One decoder, many tasks. Special tokens in the decoder prompt specify the task: <|startoftranscript|>, then a language token, then <|transcribe|> or <|translate|>, then <|notimestamps|> or timestamp tokens interleaved with the text. Language identification, transcription, translation and timestamping are all next-token prediction.
  3. Data hygiene. Much transcribed audio on the web is already the output of an ASR system. Training on it would teach the model "transcript-ese" (all-lowercase, no punctuation, the errors of the old system), so heuristics removed machine-generated transcripts.
  4. Scale over cleverness. No self-supervision and, in the original models, no data augmentation or regularisation; five model sizes from 39M to 1,550M parameters.
  5. Zero-shot evaluation. Whisper is evaluated on datasets it was not fine-tuned on, which exposes how much of previous "superhuman" performance was overfitting.

The comparison in Table 2 of the paper is the speech version of CLIP's robustness table. A wav2vec 2.0 Large model fine-tuned on LibriSpeech and the zero-shot Whisper Large V2 have the same 2.7% WER on LibriSpeech test-clean. Elsewhere:

Dataset (WER %) wav2vec 2.0 Large, LibriSpeech-trained Whisper Large V2, zero-shot
LibriSpeech test-clean 2.7 2.7
LibriSpeech test-other 6.2 5.2
Common Voice 29.9 9.0
Switchboard (telephone) 28.3 13.8
CHiME-6 (noisy, far-field) 65.8 25.5
AMI SDM1 (meeting room) 67.6 36.4
Average over the 13 non-test-clean sets in Table 2 29.3 12.8

Whisper makes 55.2% fewer errors on average outside the benchmark it ties on. In 2015 Deep Speech 2 had reported human-level WER on LibriSpeech test-clean and suggested little room was left on clean read speech; by 2021 the state of the art there had fallen from its 5.3% to 1.4%, yet models trained on LibriSpeech still did badly on real-world audio. Benchmark accuracy and robustness are different quantities.

Whisper's failure modes come from being an autoregressive decoder trained on weakly aligned web data. Its paper lists them: getting stuck in repeat loops, skipping the first or last words of a window, and complete hallucination, a fluent transcript unrelated to the audio, most often on silence, music or noise. Production pipelines therefore put a voice-activity detector in front, condition carefully across windows, and check timestamps.

Worked example: word error rate

WER is the word-level edit distance divided by the number of reference words: \(\text{WER} = (S + D + I)/N\) for substitutions, deletions and insertions. Reference: the cat sat on the mat (\(N = 6\)). Hypothesis: the cat sat on a mat mat. One substitution (the → a) and one insertion (mat): WER \(= 2/6 = 33\%\). WER can exceed 100% (insert enough words), and it depends heavily on text normalisation: "Dr." vs "doctor", "twenty five" vs "25". Whisper's authors built a normaliser to compare systems fairly; always normalise both sides the same way before you compare numbers.

Text to speech: from pipelines to vocoders

TTS runs the problem backwards and adds a new difficulty: it is one-to-many. One sentence can be spoken in countless ways (speed, pitch contour, emphasis, voice). A model trained with a regression loss on spectrograms predicts the average rendition, which sounds flat and buzzy, exactly as an L2-trained image model produces blur. Every advance in TTS is a way to model the distribution rather than its mean.

The classic neural pipeline has three stages:

  1. Front end. Normalise text ("Dr. Smith paid €5" → "doctor Smith paid five euros") and convert graphemes to phonemes. Many modern models learn this implicitly from characters.
  2. Acoustic model, text → mel spectrogram. Tacotron 2 (Shen et al. 2017) used an attention-based sequence-to-sequence network and reached a mean opinion score of 4.53 against 4.58 for professional recordings. Autoregressive attention is slow and occasionally skips or repeats words, so FastSpeech 2 (Ren et al. 2020) went non-autoregressive: predict each phoneme's duration (plus pitch and energy) explicitly, expand the phoneme sequence to frame length, and generate all frames in parallel. Giving the model pitch and energy as inputs removes part of the one-to-many ambiguity from the loss.
  3. Vocoder, mel spectrogram → waveform. A mel spectrogram discards the phase, so the vocoder must invent a plausible one. WaveNet (van den Oord et al. 2016) generated audio one sample at a time with stacks of dilated causal convolutions (dilations 1, 2, 4, …, 512 give a block a receptive field of 1,024 samples), over 256 μ-law quantised levels, and set a new bar for naturalness, but sample-by-sample generation is slow. HiFi-GAN (Kong et al. 2020) made it parallel: a convolutional generator upsamples the mel spectrogram to a waveform, trained with multi-period and multi-scale discriminators that judge periodic structure and fine detail; it generated 22.05 kHz audio 167.9× faster than real time on a V100 GPU, and a small variant ran 13.4× faster than real time on a CPU.

VITS (Kim et al. 2021) merged stages 2 and 3 into one end-to-end model: a VAE whose decoder is a HiFi-GAN generator, a normalising flow to make the prior expressive, an adversarial loss, and a stochastic duration predictor so that the same text can be spoken at different rhythms. Its alignment between text and frames is found during training by monotonic alignment search, a dynamic programme closely related to the CTC recursion below.

Neural codecs: audio as tokens

To let a language model generate audio, audio must become a sequence of discrete tokens at a manageable rate. A neural audio codec is an autoencoder whose bottleneck is quantised:

  • SoundStream (Zeghidour et al. 2021) introduced the modern recipe: a convolutional encoder, a residual vector quantiser (RVQ), a convolutional decoder, trained with reconstruction and adversarial losses. RVQ quantises the latent with one codebook, then quantises the residual error with a second, and so on; dropping later codebooks at training time ("quantizer dropout") lets one model run at 3 to 18 kbps. At 3 kbps it beat Opus at 12 kbps in listening tests.
  • EnCodec (Défossez et al. 2022): 75 latent frames per second at 24 kHz, codebooks of 1,024 entries (10 bits each), and bitrates of 1.5, 3, 6, 12 or 24 kbps by using 2, 4, 8, 16 or 32 codebooks. At 6 kbps (8 codebooks) that is 600 tokens per second.
  • Mimi, the codec inside Moshi (Défossez et al. 2024): 12.5 frames per second, 8 codebooks of 2,048 entries, 1.1 kbps, and its first codebook is trained by distillation from a self-supervised speech model (WavLM) so that it carries semantic (phonetic) content, while the rest carry acoustic detail.

The rate matters because a transformer's cost scales with sequence length. Text arrives at perhaps 3–4 tokens per second of speech; EnCodec at 6 kbps produces 600; Mimi produces 100. The history of audio LMs is largely a history of driving that number down.

Speech generation as language modelling

AudioLM (Borsos et al. 2022) generated speech and piano continuations with a hierarchy: first coarse semantic tokens (k-means clusters of w2v-BERT features, the HuBERT idea) for long-term structure, then SoundStream acoustic tokens for the first codebooks, then the remaining codebooks for fine detail. VALL-E (Wang et al. 2023) applied the same idea to TTS: condition on the phonemes of the text and on the EnCodec tokens of a 3-second recording of the target voice, and generate the codec tokens of the new speech. An autoregressive transformer produces the first codebook (which carries most of the content and prosody), and a non-autoregressive one fills the remaining seven codebooks in parallel. Trained on 60,000 hours of English audiobooks (LibriLight), hundreds of times more than earlier TTS systems, it could clone a voice, and its recording conditions, from three seconds. Because decoding samples tokens, the same text gives different renditions, which is exactly the one-to-many behaviour TTS needs. The authors used sampling rather than beam search for the autoregressive stage because beam search could send the model into an infinite loop.

MusicGen (Copet et al. 2023) showed how to predict all codebooks with one transformer: a delay pattern offsets codebook \(k\) by \(k\) steps, so that at each step the model predicts codebook 1 of frame \(t\), codebook 2 of frame \(t-1\), and so on, in parallel. Each fine codebook is then predicted after the coarser ones of the same frame already exist.

codebook 1codebook 2codebook 3codebook 4 step 1234567 f1f2f3f4 f1f2f3f4 f1f2f3f4 f1f2f3f4
MusicGen's delay pattern for four codebooks. Each column is one transformer step that predicts four tokens at once. Frame f1's fine codebooks are predicted on later steps, after its coarse ones exist; a 4-frame clip takes 7 steps instead of 16 (flattened) or a second model (VALL-E's split).

Sampling settings matter here as much as in text: MusicGen samples with top-k = 250 at temperature 1.0.

Flow matching for speech

The other route to one-to-many TTS is the continuous generative modelling of the rest of this track. Voicebox (Le et al. 2023) trains a non-autoregressive flow-matching model to infill masked speech given the surrounding audio and the text: TTS is infilling an empty span after a voice prompt, and editing or denoising are infilling a span in the middle. Trained on 60K hours of English and 50K hours of multilingual audiobooks, it beat VALL-E on intelligibility (1.9% vs 5.9% WER) and speaker similarity (0.681 vs 0.580) while being up to 20× faster. F5-TTS (Chen et al. 2024) simplified further: pad the character sequence with filler tokens to the length of the speech, and let a diffusion transformer learn the alignment itself, with no duration model, phoneme aligner or text encoder, at a real-time factor of 0.15.

Speech-native dialogue

A voice assistant can be a cascade: voice-activity detection decides you have stopped talking, ASR transcribes, an LLM answers in text, TTS speaks. It is modular and debuggable, but latency adds up and everything that is not words (tone, hesitation, laughter, interruption) is lost at the ASR step. With plausible component latencies (wait 0.5 s of silence to be sure the user has finished, 0.2 s for the final transcript, 0.4 s to the LLM's first token, 0.2 s to the first audio), a cascade answers about 1.3 s after the user stops, against the 230 ms average gap between turns in natural conversation that the Moshi paper cites.

Moshi (Défossez et al. 2024) is a speech-native alternative: a 7B text LLM (Helium) extended to model two audio streams at once, the user's and its own, as Mimi tokens, so it is full-duplex: it listens while it speaks and can be interrupted or backchannel. A small "depth" transformer predicts the 8 codebooks of each frame, and an inner monologue, time-aligned text tokens predicted before the audio tokens of the same frame, lets it keep the reasoning quality of a text LLM. Its theoretical latency is 160 ms (200 ms in practice). Frontier assistants with real-time voice modes follow the same direction, although their architectures are not published.

Voice is identity

Three seconds of audio are enough for codec language models to imitate a voice. Consent, disclosure and anti-impersonation safeguards are part of the engineering, not an afterthought; VALL-E's own paper names spoofing voice identification and impersonation as its main risks. See robustness, fairness and privacy and governance.

History

Sixty years of speech in one picture
Sixty years of speech in one picture. HMM–GMM 1980s–2000s phones, pronunciation dictionaries, CTC 2006 alignment-free training, DNN–HMM 2012 deep nets replace GMMs, Deep Speech 2, LAS 2015 end-to-end ASR, WaveNet 2016 neural waveform generation, Tacotron 2 2017, HiFi-GAN 2020 neural TTS pipeline, wav2vec 2.0, HuBERT 2020–21 self-supervised speech, Whisper 2022 680k hours, weak supervision, SoundStSixty years of speech in one picture. HMM–GMM 1980s–2000s phones, pronunciation dictionaries, CTC 2006 alignment-free training, DNN–HMM 2012 deep nets replace GMMs, Deep Speech 2, LAS 2015 end-to-end ASR, WaveNet 2016 neural waveform generation, Tacotron 2 2017, HiFi-GAN 2020 neural TTS pipeline, wav2vec 2.0, HuBERT 2020–21 self-supervised speech, Whisper 2022 680k hours, weak supervision, SoundSt

How the field moved

For three decades ASR meant a hidden Markov model over phone states with Gaussian-mixture emission densities, a hand-built pronunciation lexicon and an n-gram language model, trained by the forward–backward algorithm, the ancestor of CTC's recursion. Around 2012, groups at Toronto, Microsoft, Google and IBM showed jointly that replacing the Gaussian mixtures with deep networks cut error rates sharply, one of the first industrial wins of the deep learning reset. Alex Graves's CTC (2006) and transducer (2012) made the HMM unnecessary; Baidu's Deep Speech 2 and Google's LAS (both 2015) showed fully end-to-end systems could compete. On the synthesis side, DeepMind's WaveNet (2016) ended the era of concatenative and parametric vocoders. The 2020s then imported the large-model playbook: self-supervision (Meta's wav2vec 2.0 and HuBERT), weak supervision at scale (OpenAI's Whisper, 2022), and discrete tokens plus language models (Google's SoundStream and AudioLM, Meta's EnCodec, Microsoft's VALL-E), ending in speech-native dialogue models such as Kyutai's Moshi (2024).

First principles

Why log-mel? A recogniser must be invariant to things that do not change the words: phase, small shifts in timing, overall loudness, the speaker's exact pitch. The magnitude spectrum throws away phase; the mel pooling throws away fine frequency detail where the ear has none; the log turns loudness changes into additive offsets that normalisation removes. Every step discards information the task does not need. Synthesis needs exactly what was thrown away, which is why a TTS system needs a vocoder (or a codec decoder) to put phase and fine structure back.

Why alignment is a latent variable. The transcript is a short sequence \(\mathbf{y}\), the audio a long one \(\mathbf{x}\), and the alignment \(\pi\) between them is unobserved. The principled objective is the marginal likelihood \(p(\mathbf{y}\mid\mathbf{x}) = \sum_\pi p(\mathbf{y}, \pi\mid\mathbf{x})\), the same move as in EM for mixtures or the VAE. CTC and transducers restrict \(\pi\) to monotonic paths, which makes the sum an exact dynamic programme; attention decoders let the network learn a soft, implicit alignment, which is more flexible and loses the guarantee of monotonicity, hence their loops and skips.

Why discrete tokens? Next-token prediction with cross-entropy is the most scalable generative recipe known, and it needs a finite vocabulary. A codec turns audio into one, and residual quantisation makes the trade-off between bits and fidelity explicit: rate–distortion theory says each extra bit per dimension of a Gaussian source buys about 6 dB of signal-to-noise ratio, so each 8-bit codebook spread over a 16-dimensional latent should buy about 3 dB. The toy codec under Build it gets almost exactly that.

Why weak supervision won for ASR. As with CLIP, the alternative to careful labels is a lot of imperfect ones. 680,000 hours of web transcripts contain every accent, microphone, noise condition and domain, so the model never learns the shortcuts of a single benchmark. The price is noise in the labels, which Whisper paid in filtering effort and in hallucination.

The maths

Short-time Fourier transform and log-mel. With window \(w\) of length \(N\) and hop \(H\), frame \(t\) and frequency bin \(k\):

\[ X[t,k] = \sum_{n=0}^{N-1} x[tH + n]\,w[n]\,e^{-2\pi i kn/N},\qquad M[t,m] = \log\Big(\sum_k F[m,k]\,|X[t,k]|^2 + \epsilon\Big), \]

where \(F\in\mathbb{R}^{80\times(N/2+1)}\) holds the triangular mel filters. Whisper: \(N = 400\), \(H = 160\) at 16 kHz.

CTC. Let \(y_t^k\) be the network's softmax output for symbol \(k\) at frame \(t\), and \(\mathcal{B}\) the collapse map. Assuming conditional independence across frames,

\[ p(\mathbf{l}\mid\mathbf{x}) = \sum_{\pi\in\mathcal{B}^{-1}(\mathbf{l})}\ \prod_{t=1}^{T} y_t^{\pi_t}, \qquad \mathcal{L}_{\text{CTC}} = -\log p(\mathbf{l}\mid\mathbf{x}). \]
Derivation: the CTC forward recursion

Insert blanks around every label: \(\mathbf{l}' = (\_, l_1, \_, l_2, \dots, l_U, \_)\), length \(S = 2U+1\). Let \(\alpha_t(s)\) be the total probability of all path prefixes of length \(t\) that collapse to the first \(s\) symbols of \(\mathbf{l}'\) (ending in \(\mathbf{l}'_s\)). A valid path at frame \(t\) can reach position \(s\) only from \(s\) (repeat the symbol), \(s-1\) (advance), or \(s-2\) (skip a blank), and the skip is allowed only when \(\mathbf{l}'_s\) is not a blank and differs from \(\mathbf{l}'_{s-2}\) (otherwise the two identical labels would merge). Hence

\[ \alpha_t(s) = y_t^{\mathbf{l}'_s}\times \begin{cases} \alpha_{t-1}(s) + \alpha_{t-1}(s-1) & \text{if } \mathbf{l}'_s = \_ \text{ or } \mathbf{l}'_s = \mathbf{l}'_{s-2},\\ \alpha_{t-1}(s) + \alpha_{t-1}(s-1) + \alpha_{t-1}(s-2) & \text{otherwise,} \end{cases} \]

with \(\alpha_1(1) = y_1^{\_}\), \(\alpha_1(2) = y_1^{l_1}\) and all other \(\alpha_1(s) = 0\). A complete path ends on the last label or the final blank: \(p(\mathbf{l}\mid\mathbf{x}) = \alpha_T(S) + \alpha_T(S-1)\). The cost is \(O(TS)\). The same recursion run backwards gives \(\beta_t(s)\), and \(\partial \log p/\partial y_t^k\) follows from \(\sum_{s:\mathbf{l}'_s = k}\alpha_t(s)\beta_t(s)\), exactly the forward–backward algorithm of HMMs. In practice everything is done in log space with log-sum-exp (numerical computing).

Transducer. With encoder state \(\mathbf{f}_t\) and prediction-network state \(\mathbf{g}_u\) after \(u\) labels, the joiner gives \(p(k\mid t, u) = \operatorname{softmax}\big(W\tanh(\mathbf{f}_t + \mathbf{g}_u)\big)_k\) over labels plus blank; a blank advances \(t\), a label advances \(u\). The likelihood is again a sum over monotonic paths through the \(T\times U\) lattice, computed by a forward recursion.

Attention ASR. \(p(\mathbf{y}\mid\mathbf{x}) = \prod_u p(y_u\mid y_{<u}, \operatorname{Enc}(\mathbf{x}))\): an ordinary language model with cross-attention.

μ-law companding (WaveNet). For \(x\in[-1,1]\) and \(\mu = 255\): \(f(x) = \operatorname{sign}(x)\,\frac{\ln(1+\mu|x|)}{\ln(1+\mu)}\), then quantise to 256 levels. Quiet samples get fine resolution, loud ones coarse, matching perception.

Residual vector quantisation. With codebooks \(C_1,\dots,C_Q\) and \(\mathbf{r}_0 = \mathbf{z}\):

\[ \mathbf{q}_i = \arg\min_{\mathbf{c}\in C_i}\lVert \mathbf{r}_{i-1} - \mathbf{c}\rVert,\qquad \mathbf{r}_i = \mathbf{r}_{i-1} - \mathbf{q}_i,\qquad \hat{\mathbf{z}} = \sum_{i=1}^{Q}\mathbf{q}_i . \]

Bitrate \(= f_{\text{frame}}\cdot Q\cdot\log_2|C|\): EnCodec at 6 kbps is \(75\cdot8\cdot10\); Mimi is \(12.5\cdot8\cdot11 = 1{,}100\) bit/s.

VALL-E's factorisation. With codec tokens \(c_{t,j}\) (frame \(t\), codebook \(j\)), phonemes \(\mathbf{x}\) and the prompt's tokens \(\tilde C\):

\[ p(C\mid\mathbf{x},\tilde C) = \underbrace{\prod_t p(c_{t,1}\mid c_{<t,1},\mathbf{x},\tilde C_{:,1})}_{\text{autoregressive}} \ \prod_{j=2}^{8}\underbrace{p(c_{:,j}\mid c_{:,<j},\mathbf{x},\tilde C)}_{\text{non-autoregressive}} . \]

Build it

Three small programs: the front end of a recogniser, the loss that trains it, and the codec that lets a language model speak.

1. A log-mel front end from scratch (HTK-style mel formula; Whisper uses librosa's Slaney-style filters, which differ in detail but not in idea).

import numpy as np

sr, n_fft, hop, n_mels = 16000, 400, 160, 80        # Whisper's front end: 25 ms window, 10 ms hop
def hz_to_mel(f): return 2595 * np.log10(1 + f / 700)
def mel_to_hz(m): return 700 * (10 ** (m / 2595) - 1)

def mel_filterbank():
    """80 triangular filters, evenly spaced on the mel scale from 0 to 8 kHz."""
    mels = np.linspace(hz_to_mel(0), hz_to_mel(sr / 2), n_mels + 2)
    bins = np.fft.rfftfreq(n_fft, 1 / sr)                       # 201 FFT bin centre frequencies
    fb = np.zeros((n_mels, len(bins)))
    for m in range(n_mels):
        lo, c, hi = mel_to_hz(mels[m:m + 3])
        fb[m] = np.clip(np.minimum((bins - lo) / (c - lo), (hi - bins) / (hi - c)), 0, None)
    return fb

def log_mel(x):
    frames = np.lib.stride_tricks.sliding_window_view(x, n_fft)[::hop]   # (T, 400)
    spec = np.abs(np.fft.rfft(frames * np.hanning(n_fft), axis=1)) ** 2  # power, (T, 201)
    return np.log10(np.maximum(spec @ mel_filterbank().T, 1e-10))         # (T, 80)

t = np.arange(sr * 2) / sr                                          # two seconds
x = np.where(t < 1, np.sin(2 * np.pi * 440 * t), np.sin(2 * np.pi * 3000 * t))  # A4, then 3 kHz
M = log_mel(x)
print("samples:", x.shape, "-> log-mel:", M.shape)
print("loudest mel bin, first second:", M[:90].mean(0).argmax(), " second second:", M[110:].mean(0).argmax())
centres = mel_to_hz(np.linspace(hz_to_mel(0), hz_to_mel(sr / 2), n_mels + 2)[1:-1])
print("filter width near 440 Hz: %.0f Hz, near 3 kHz: %.0f Hz" %
      tuple(np.diff(centres)[[np.abs(centres - f).argmin() for f in (440, 3000)]]))
print("30 s of audio ->", (30 * sr - n_fft) // hop + 1, "frames x 80 mels (a centred STFT, as Whisper uses, gives 3000)")

Output:

samples: (32000,) -> log-mel: (198, 80)
loudest mel bin, first second: 15  second second: 53
filter width near 440 Hz: 36 Hz, near 3 kHz: 119 Hz
30 s of audio -> 2998 frames x 80 mels (a centred STFT, as Whisper uses, gives 3000)

32,000 samples become 198 frames of 80 numbers. The 440 Hz tone lands in mel bin 15 and the 3 kHz tone in bin 53: a 6.8× ratio in frequency is only 3.5× in bin index, which is the mel compression at work.

2. CTC from scratch, checked by brute force. The forward algorithm sums over all alignments in \(O(TS)\); with 6 frames and a 4-symbol vocabulary we can also enumerate all \(4^6 = 4{,}096\) paths and check it.

import numpy as np, itertools

def ctc_log_prob(logp, target, blank=0):
    """log p(target | x) by the CTC forward algorithm. logp: (T, V) log-softmax outputs."""
    ext = [blank]
    for c in target: ext += [c, blank]                  # "cat" -> _ c _ a _ t _
    S, T = len(ext), len(logp)
    alpha = np.full((T, S), -np.inf)
    alpha[0, 0], alpha[0, 1] = logp[0, blank], logp[0, ext[1]]
    for t in range(1, T):
        for s in range(S):
            paths = [alpha[t - 1, s]]                                       # stay
            if s >= 1: paths.append(alpha[t - 1, s - 1])                    # advance one
            if s >= 2 and ext[s] != blank and ext[s] != ext[s - 2]:
                paths.append(alpha[t - 1, s - 2])                           # skip a blank
            alpha[t, s] = np.logaddexp.reduce(paths) + logp[t, ext[s]]
    return np.logaddexp(alpha[-1, -1], alpha[-1, -2])   # end on the last label or the final blank

def collapse(path, blank=0):
    """CTC's many-to-one map B: merge repeats, then drop blanks."""
    out = [k for k, _ in itertools.groupby(path)]
    return tuple(c for c in out if c != blank)

rng = np.random.default_rng(0)
T, V = 6, 4                                              # 6 frames; vocab {_, a, b, c}
logits = rng.standard_normal((T, V)); logits[:, 1] += 1.0
logp = logits - np.logaddexp.reduce(logits, axis=1, keepdims=True)
target = (1, 2, 2)                                        # "abb": the repeat needs a blank between
fast = ctc_log_prob(logp, target)
brute = np.logaddexp.reduce([logp[np.arange(T), list(p)].sum()
        for p in itertools.product(range(V), repeat=T) if collapse(p) == target])
n = sum(collapse(p) == target for p in itertools.product(range(V), repeat=T))
print(f"alignments of 6 frames that collapse to 'abb': {n} of {V**T}")
print(f"forward algorithm log p = {fast:.6f}   brute force = {brute:.6f}")
best = tuple(int(i) for i in logp.argmax(1))
print("best path:", "".join("_abc"[i] for i in best), "-> greedy decode:",
      "".join("_abc"[i] for i in collapse(best)), f"| CTC loss for 'abb': {-fast:.3f}")

Output:

alignments of 6 frames that collapse to 'abb': 28 of 4096
forward algorithm log p = -8.642217   brute force = -8.642217
best path: aacaca -> greedy decode: acaca | CTC loss for 'abb': 8.642

Only 28 of 4,096 paths spell abb (the double b forces a blank between them), and the recursion's answer matches the enumeration to six decimals. The "network" here is random, so its greedy decode is nonsense; training would push probability onto those 28 paths. At realistic sizes (\(T = 1{,}500\), \(U = 100\)) enumeration is impossible and the recursion costs about \(1{,}500\times201\) steps.

3. A residual vector quantiser. We stand in for an audio encoder's output with correlated 16-dimensional latent frames, learn eight 256-entry codebooks by k-means on successive residuals, and measure reconstruction quality as codebooks are added.

import numpy as np
rng = np.random.default_rng(0)

# Stand-in for an audio encoder's output: 16-d latent frames with correlated dimensions.
D, K = 16, 256                                     # latent width, entries per codebook (8 bits)
mix = rng.standard_normal((D, D)) * np.linspace(1.0, 0.1, D)
train = rng.standard_normal((20000, D)) @ mix.T
test = rng.standard_normal((5000, D)) @ mix.T

def kmeans(x, k, iters=15):
    c = x[rng.choice(len(x), k, replace=False)]
    for _ in range(iters):
        d = (x**2).sum(1, keepdims=True) - 2 * x @ c.T + (c**2).sum(1)
        a = d.argmin(1)
        for j in range(k):
            if np.any(a == j): c[j] = x[a == j].mean(0)
    return c

def quantize(x, c):
    d = (x**2).sum(1, keepdims=True) - 2 * x @ c.T + (c**2).sum(1)
    i = d.argmin(1); return i, c[i]

# Residual VQ: each stage quantises what the previous stages left over.
codebooks, r = [], train.copy()
for q in range(8):
    c = kmeans(r, K); codebooks.append(c)
    _, qr = quantize(r, c); r = r - qr

r, recon = test.copy(), np.zeros_like(test)
print("codebooks | tokens per frame | SNR of reconstruction")
for q, c in enumerate(codebooks, 1):
    _, qr = quantize(r, c); recon += qr; r -= qr
    snr = 10 * np.log10((test**2).sum() / ((test - recon)**2).sum())
    print(f"{q:9d} | {q:16d} | {snr:6.1f} dB")

for name, hz, nq, bits in [("EnCodec 24 kHz, 8 codebooks", 75, 8, 10), ("Mimi (Moshi)", 12.5, 8, 11)]:
    print(f"{name}: {hz} frames/s x {nq} codebooks x {bits} bits = {hz*nq*bits/1000:.2f} kbps, "
          f"{hz*nq:.0f} tokens per second")

Output:

codebooks | tokens per frame | SNR of reconstruction
        1 |                1 |    4.8 dB
        2 |                2 |    8.2 dB
        3 |                3 |   11.3 dB
        4 |                4 |   14.1 dB
        5 |                5 |   16.7 dB
        6 |                6 |   19.2 dB
        7 |                7 |   21.6 dB
        8 |                8 |   23.8 dB
EnCodec 24 kHz, 8 codebooks: 75 frames/s x 8 codebooks x 10 bits = 6.00 kbps, 600 tokens per second
Mimi (Moshi): 12.5 frames/s x 8 codebooks x 11 bits = 1.10 kbps, 100 tokens per second

After the first stage, each extra 8-bit codebook buys about 2.5–3 dB, close to the rate–distortion prediction of 3 dB for 0.5 extra bits per dimension. That smooth, additive quality ladder is why codecs can drop codebooks to change bitrate and why language models can generate the coarse codebooks first and the fine ones later.

Things to try

  • Speech features. Record yourself saying "one two three" (any phone, export WAV, load with the standard wave module) and plot log_mel with matplotlib. Find the vowels (dark horizontal bands, the formants) and the s sounds (energy above 4 kHz).
  • CTC gradients. Add the backward recursion, compute \(\partial\mathcal{L}/\partial\,\text{logits}\), and train the 6×4 logits directly by gradient descent on target abb. Watch the outputs become peaky: mostly blank, one spike per character.
  • Greedy vs beam. Implement CTC prefix beam search (the Distill article gives the algorithm) and find a logp where it beats greedy decoding.
  • Codebook size vs count. Compare 4 codebooks of 256 entries with 2 codebooks of 65,536 (same bits). Which reconstructs better, and which is easier for a language model to predict?
  • A real one. With PyTorch, pip install openai-whisper, transcribe a recording of yourself, then the same recording with music mixed in. Then run 10 seconds of silence and see whether it hallucinates.

In practice

  • ASR choices (as of 2026). For general transcription, Whisper-family models and their successors remain the common baseline; distilled and quantised variants run on laptops (see on-device AI). For streaming and on-device dictation, transducer models. For a new language or domain with little labelled data, a self-supervised encoder fine-tuned with CTC.
  • Always measure on your audio. Benchmark WER says little about your microphones, accents, jargon and noise. Build a small labelled test set and normalise text before scoring.
  • Guard against hallucination. Run voice-activity detection to skip silence, set a no-speech threshold, watch for repeated phrases, and prefer models with word timestamps so you can check alignment. For high-stakes transcripts, show confidence and keep the audio.
  • Domain vocabulary. Names and jargon are the usual errors. Whisper accepts a text prompt that biases decoding; transducer systems support contextual biasing; an LLM post-correction pass with the vocabulary list also works.
  • TTS choices. For a fixed product voice, a fine-tuned single-speaker model (VITS-style or a small flow-matching model) is cheap and stable. For many voices or cloning, codec-LM or flow-matching models; check the licence and consent requirements for any voice you clone.
  • Latency budget. For voice agents, measure time from end-of-speech to first audio, not model speed. Endpointing (deciding the user has finished) is often the largest single term.

Common misconceptions

\"WER of 3% means 97% of words are right\"

WER counts insertions as errors and can exceed 100%; it also depends on normalisation. And a 3% average hides the distribution: errors concentrate on names, numbers and rare words, which are often the words that matter.

\"Whisper is a speech-to-text model, so it cannot make things up\"

It is an autoregressive language model conditioned on audio. When the audio is uninformative (silence, noise, music) the text prior takes over and it can emit fluent, plausible and entirely invented sentences. Treat its output like any other generative model's.

\"A mel spectrogram is a complete description of the sound\"

It discards phase and fine frequency detail. Two different waveforms can share a mel spectrogram, and turning one back into audio requires a model (a vocoder) to invent the missing information.

Check yourself

How many encoder positions does Whisper process for 30 seconds of audio, and why?

The log-mel front end gives 100 frames per second (10 ms hop), 3,000 frames for 30 s. The convolutional stem's second layer has stride 2, halving that to 1,500 positions.

Why does CTC need a blank symbol? Give two reasons.

First, most frames do not correspond to the onset of a new character; the blank lets the network say "nothing new here" without being forced to emit a label. Second, without a blank there would be no way to output a doubled letter: repeats are merged, so ll needs l_l.

What independence assumption does CTC make, and what does a transducer add to remove it?

CTC assumes the per-frame outputs are conditionally independent given the audio, so the probability of a path is a product of frame probabilities and the model has no internal language model. A transducer adds a prediction network that conditions each output on the labels already emitted, combined with the acoustic state by a joiner.

A system's WER falls from 6% to 3% on LibriSpeech test-clean. Should you expect its WER on phone calls to halve?

No. Whisper's Table 2 shows two models with identical 2.7% WER on test-clean differing by more than 2× on telephone (Switchboard: 28.3 vs 13.8) and far-field audio. In-distribution gains can come from fitting the benchmark's quirks. Evaluate on out-of-distribution sets that look like your use.

EnCodec at 24 kHz uses 75 frames per second and 1,024-entry codebooks. What bitrate and token rate do 4 codebooks give?

\(75\times4\times10 = 3{,}000\) bit/s (3 kbps) and \(75\times4 = 300\) tokens per second.

Why does an L2 loss on mel spectrograms produce flat, buzzy TTS?

Speech given text is one-to-many. The L2-optimal prediction is the conditional mean over all plausible renditions, which averages away pitch movement and fine harmonic structure, exactly as L2-trained image models blur. Adversarial losses (HiFi-GAN), flows (VITS), sampling over discrete tokens (VALL-E) or flow matching (Voicebox, F5-TTS) model the distribution instead.

Hard: why does VALL-E generate the first codebook autoregressively but the other seven in parallel?

In residual quantisation, the first codebook carries the coarse content: which phone, pitch and timing, i.e. the parts with long-range dependencies that need sequential modelling and sampling for diversity. Later codebooks refine the residual of the same frame and depend mostly on the codebooks already chosen for that frame and its neighbours, so they can be predicted in parallel given the first, saving seven passes of autoregressive decoding.

Hard: a cascade voice agent responds 1.3 s after the user stops. List where you would look first and why a speech-native model helps.

Endpointing usually dominates: the system waits for a silence threshold before committing. Then LLM time-to-first-token, the ASR's final pass, and TTS time-to-first-audio. Streaming every stage (partial transcripts, speculative LLM starts, streaming TTS) overlaps them. A speech-native full-duplex model removes the hand-offs entirely: it listens and generates continuously, can begin responding (or backchannel) without a hard endpoint, and keeps paralinguistic cues the ASR step would discard. The cost is less modularity and harder evaluation and control.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads