Sub topic 3
How Whisper works: an encoder-decoder transformer trained on weakly supervised data
This chapter explains the model inside Whisper: what goes in, what comes out, how the two halves of the network divide the work, and why the training data shapes the behavior you see. It assumes you know basic Python, have a general idea of what a neural network is, and have read the earlier chapters on speech recognition and on 16 kHz mono audio and log-Mel spectrograms. You do not need to know the transformer math in detail.
The big picture
Whisper is a sequence-to-sequence model. It takes a fixed-size input, an 80-channel log-Mel spectrogram covering 30 seconds of audio, and produces a sequence of text tokens. The same network handles several jobs: transcription, translation to English, language identification, and voice activity detection (marking segments with no speech).
Older speech systems often chained separate parts: an acoustic model, a pronunciation dictionary, a language model, and hand-written text normalization. Whisper replaces that chain with one transformer that is trained end to end. The tradeoff is that you get fewer places to inspect or patch the pipeline, and more of the behavior comes from the training data.
The encoder
The encoder turns the spectrogram into a sequence of vectors that represent what was heard.
- The input is a matrix of 80 mel channels by 3000 frames. Each frame covers 10 ms, so 3000 frames is 30 seconds.
- A small stem of two 1D convolution layers processes the frames. The second layer uses a stride of 2, which halves the length from 3000 to 1500 positions. Each position now covers about 20 ms.
- Sinusoidal positional encodings are added so the model knows the order of positions.
- A stack of transformer encoder blocks applies self-attention, so every position can look at every other position in the window. This gives each vector context from the whole 30 seconds.
The output is a 1500-position sequence of feature vectors. Its width depends on the model size. The encoder always processes the full 30 seconds, even if the clip is two seconds long, because shorter audio is padded with zeros. That is why very short clips cost about as much encoder time as full windows.
The decoder
The decoder is an autoregressive text generator. Autoregressive means it produces one token at a time, and each new token is conditioned on all the tokens it has produced so far.
Each decoder block has three parts:
- Masked self-attention over the tokens generated so far. Masked means a position cannot see tokens that come after it.
- Cross-attention, where the decoder queries the encoder's 1500 audio vectors. This is how the text stays tied to the sound.
- A feed-forward layer.
The decoder uses learned positional embeddings and shares its token embedding matrix with the output projection. At each step it produces a probability distribution over the vocabulary. The decoding strategy (greedy, beam search, temperature sampling) then chooses a token from that distribution. Those options are covered in a later chapter.
Tokens, not words
Whisper uses a byte-level byte-pair-encoding (BPE) tokenizer. BPE splits text into frequent subword pieces, and byte-level means any Unicode text can be represented, so there are no unknown characters. The English-only models use a GPT-2 style vocabulary. The multilingual models use a vocabulary refit for many languages, which helps with non-English text.
Whisper does not output a word list with spaces added afterward. The space is part of the token, so a token like " hello" is different from "hello". Punctuation and capitalization come out of the model directly, because the training transcripts contained them.
Special tokens: one model, many tasks
The decoder's input starts with special tokens that act as a task specification. This is how a single network does several jobs.
| Token | Role | Column | Column | Column | Column |
|---|---|---|---|---|---|
| `<\ | startoftranscript\ | >` | Marks the start of decoding | ||
| Language token, such as `<\ | en\ | >` or `<\ | es\ | >` | Names the spoken language |
| `<\ | transcribe\ | >` or `<\ | translate\ | >` | Selects the task |
| `<\ | notimestamps\ | >` | Present if timestamps are not predicted | ||
| Timestamp tokens, such as `<\ | 0.00\ | >` | Mark time in 0.02 s steps within the window | ||
| `<\ | endoftext\ | >` | Ends the sequence | ||
| `<\ | nospeech\ | >` | Signals that the window has no speech (in the original design) |
A typical decoder prompt for English transcription with timestamps is:
<|startoftranscript|><|en|><|transcribe|>The model then emits a timestamp token, text tokens, another timestamp token, and so on, until <|endoftext|>.
If you do not set a language, Whisper runs one decoder step right after <|startoftranscript|> and reads the probabilities over the language tokens. The most likely one is chosen. This is language detection, and it is part of the same network, not a separate classifier. It only looks at the first 30 seconds, which matters later when you transcribe recordings that switch languages.
Timestamps are predicted as ordinary tokens. The model learns to emit a timestamp token at the start and end of each segment, which is why timestamps are quantized to 20 ms and why they can be wrong in the same way text can.
You can see the language-detection step directly with the package's lower-level API:
import whisper
model = whisper.load_model("base")
audio = whisper.load_audio("audio.mp3")
audio = whisper.pad_or_trim(audio)
mel = whisper.log_mel_spectrogram(audio).to(model.device)
_, probs = model.detect_language(mel)
top = sorted(probs.items(), key=lambda kv: kv[1], reverse=True)[:3]
for lang, p in top:
print(lang, round(p, 3))pad_or_trim forces the audio to exactly 30 seconds, and detect_language returns a probability for every supported language. The three highest are printed. If the top two probabilities are close, the automatic choice is unreliable, and you should set language yourself.
Weakly supervised training data
The part of Whisper that is most unlike older research systems is its training data. Whisper was trained on about 680,000 hours of audio paired with transcripts collected from the internet. This is called weakly supervised because the transcripts were not produced by a careful annotation process. They are text that happened to exist alongside the audio, with unknown and varying quality.
The mix, as reported by the authors, was roughly:
- about 438,000 hours of English speech with English transcripts,
- about 117,000 hours of speech in 96 other languages, with transcripts in the same language,
- about 125,000 hours of non-English speech with English transcripts, which supplies the translation task.
The authors filtered the data to remove low-quality transcripts. One rule removed transcripts that looked machine-generated, such as text in all lowercase with no punctuation, because training on the output of other speech systems would teach the model their errors. They also used a language-identification check to make sure the spoken language matched the transcript language, except when the transcript was English and the task was translation.
Audio was cut into 30-second windows paired with the matching piece of the transcript. Windows with no speech were kept as well, which is where the model learns to produce an empty or no-speech result.
Why this scale of data matters
Because the data is broad, covering many recording conditions, accents, background noises, and subjects, the model works across domains without fine-tuning. The paper describes this as robustness: Whisper often does worse than specialized models on a single clean benchmark, but makes fewer large errors on new, messy audio.
The same data also explains the behavior you will need to handle:
- The transcripts came from the web, so many contain text such as subtitles credits, "thanks for watching", or sign-offs. The model can generate such phrases on silence or music. This is one source of hallucination.
- Subtitle-style transcripts often leave out filler words ("um", repeated words) and do not mark stutters. Whisper's output tends to be cleaned up and is not a strict verbatim record.
- Languages differ greatly in hours of training data. Accuracy is much better for high-resource languages than low-resource ones, and the translation task is most reliable in the direction of "into English" since that is what the data contains.
- The data has no speaker labels, so the model has no notion of who is speaking. Diarization needs another tool.
Training objective
Training is plain supervised learning on the decoder's next-token prediction. Given the spectrogram and all previous tokens, the model is trained to predict the next token, using cross-entropy loss. The task tokens, language token, and timestamp tokens are part of the target sequence, so the model learns to emit them the same way it learns text.
Two training details shape how you prompt it:
- During training, the model sometimes sees the previous segment's text as context, placed before
<|startoftranscript|>. This is what makes theinitial_promptoption work, and it is also how long-form transcription carries context from one window to the next. - Special tokens control what is predicted. A prompt that includes
<|notimestamps|>produces plain text, and omitting it produces timestamp tokens.
Inspecting the model yourself
You can check the model's structure from Python. This prints the dimensions that define each model size. The next chapter uses the same values to compare sizes.
import whisper
model = whisper.load_model("base")
dims = model.dims
print("mel channels:", dims.n_mels)
print("encoder positions:", dims.n_audio_ctx)
print("encoder layers:", dims.n_audio_layer)
print("decoder layers:", dims.n_text_layer)
print("model width:", dims.n_audio_state)
print("vocabulary size:", dims.n_vocab)
print("parameters:", sum(p.numel() for p in model.parameters()))For the base model you should see 80 mel channels, 1500 encoder positions, 6 encoder layers, 6 decoder layers, a width of 512, and about 74 million parameters. The vocabulary size is 51,865 for multilingual models.
Consequences for your code
Knowing the architecture lets you predict behavior instead of memorizing it.
- Fixed 30-second input. Anything longer must be split into windows. The
transcribefunction does this for you, sliding the window forward and using the last predicted timestamp to decide where the next window starts. - Encoder cost is per window. The encoder runs once per window regardless of how much speech it holds. The decoder cost grows with the number of output tokens.
- Autoregressive decoding is serial. Each token needs a forward pass that depends on the previous token, so decoding cannot be fully parallelized. This is why beam search is slower than greedy decoding, and why faster runtimes concentrate on optimizing the decoder.
- Errors can compound. Because each token is conditioned on earlier ones, a wrong token or a repeated phrase can push the decoder into a loop. Temperature fallback and compression-ratio checks exist to catch this.
- Language and task are inputs, not outputs of separate code. Setting
language="en"simply changes the decoder's starting tokens.
Exercise
A 3-second clip and a 30-second clip are transcribed with the same Whisper model on the same hardware. Why is the encoder time nearly identical for both, and what part of the runtime is most likely to differ?
Show answer
The audio is padded with silence to exactly 30 seconds before the log-Mel spectrogram is computed, so the encoder always processes 3000 frames (1500 positions after the convolution stem). The decoder time differs, because it generates one token per step and the 30-second clip usually contains many more tokens of text than the 3-second clip.
Exercise
You transcribe a recording with no language set, and Whisper outputs gibberish in the wrong language. Using what you know about how language detection works, give two causes and one fix.
Show answer
Language detection is a single decoder step based on the first 30 seconds of audio. It can fail if that window begins with silence, music, or noise, or if the speech is short, accented, or in a low-resource language, so the top language probabilities are close and the wrong token wins. Fix it by passing the language explicitly, for example language="en" in transcribe, or by checking the probabilities from detect_language first.
Exercise
Whisper's training transcripts came from the web and were not manually checked. Name two behaviors in its output that this data explains.
Show answer
Possible answers include: hallucinated phrases such as "thanks for watching" on silence or music, because similar text appeared at the end of many training transcripts; cleaned-up output that drops filler words and stutters, because many transcripts were subtitle-style rather than verbatim; and uneven accuracy across languages, because the hours of data per language differ greatly.