AI Logic

Architectures

Whisper

Updated:

Architecture of Whisper. Left: the overall flow (encoder: log-mel spectrogram → two convolution layers with GELU → sinusoidal positional encoding → encoder blocks × L → layer normalization; decoder: tokens so far → token embedding plus learned positional embedding → decoder blocks × L that attend to the encoder output via cross-attention → next-token prediction). Right: the sequence of tokens fed to the decoder (previous segment's transcript, startoftranscript, a language tag or nospeech, transcribe or translate, timestamped text or notimestamps followed by text, endoftranscript).

Background and Overview

Whisper is a speech recognition model that trains a single Transformer jointly on multilingual speech recognition, translation into English, language identification, and more, using 680,000 hours of transcribed audio collected from the internet. It was proposed by Radford et al. at OpenAI in 2022. Its goal is to achieve high accuracy out of the box across a wide range of recording conditions without dataset-specific fine-tuning (zero-shot).

Speech recognition up to then faced the following challenges.

  • Self-supervised pretraining (such as wav2vec 2.0): it learns good speech representations, but has no component that turns speech into text (a decoder), so it requires fine-tuning on each dataset before use. The model picks up quirks specific to the fine-tuning data, and accuracy tends to drop on audio from other conditions.
  • Supervised learning on transcribed data: high-quality datasets amount to only a few thousand hours even when combined.

Whisper collected large amounts of "weak supervision" (pairs of audio and transcripts on the internet) of uneven quality, scaling supervised learning up by an order of magnitude. The 680,000 hours break down as follows.

  • English speech recognition: the remaining ~438,000 hours
  • Speech recognition in 96 languages other than English: 117,000 hours
  • Translation from non-English audio into English: 125,000 hours

The main results of the paper are as follows.

  • Compared with a model trained on LibriSpeech that has about the same word error rate on LibriSpeech test-clean (2.7%), it made 55.2% fewer errors on average on other datasets
  • Even the smallest model, Tiny (39M parameters), was about as accurate on other datasets as the best model trained on LibriSpeech

Architecture

Whisper's architecture is an essentially off-the-shelf Transformer encoder and decoder. The paper states that it deliberately chose a proven architecture so that the effects of model improvements would not be confounded with its findings. The left side of the figure at the top of the article shows the overall flow, and the right side shows the sequence of tokens fed to the decoder (the multitask format).

The encoder processes audio in the following order.

  1. Resample the audio to 16 kHz and feed it in 30-second segments.
  2. Compute an 80-channel log-mel spectrogram (the log magnitude of a spectrum divided into frequency bands on the mel scale) with 25 ms windows and a 10 ms stride, and scale it to lie within −1 to 1 over the whole training set.
  3. Pass it through two 1D convolution layers of width 3 (with GELU activation; the second has stride 2). Time steps are now every 20 ms.
  4. Add sinusoidal positional encodings and stack Transformer encoder blocks. The blocks apply normalization first (Pre-LN), and a final layer normalization is applied at the end.

The decoder is a language model conditioned on audio that predicts the next token from the tokens so far.

  • Position information is injected with learned positional embeddings.
  • Each block consists of masked self-attention → cross-attention over the encoder output → MLP.
  • The input token embedding and the weights of the output layer are shared.
  • Tokenization uses the same byte-level BPE as GPT-2. For multilingual models, the vocabulary is refit with the same size so that non-English languages are not split into excessively small pieces.

The encoder and decoder have the same width and the same number of blocks. The paper's five sizes are as follows.

ModelBlocksWidthHeadsParameters
Tiny4384639M
Base6512874M
Small1276812244M
Medium241,02416769M
Large321,280201,550M

Multitask Format and Training

To handle multiple tasks with a single model, Whisper specifies what to do through the sequence of tokens fed to the decoder. The sequence is as follows.

  1. Previous context (included with some probability): the transcript of the preceding segment. This lets the model use the flow of surrounding sentences to fill in hard-to-hear parts.
  2. <|startoftranscript|>: marks the start of prediction.
  3. Language tag: the model predicts a token for the spoken language (99 languages in total). For a segment with no speech, it predicts <|nospeech|>.
  4. Task: <|transcribe|> to transcribe in the same language, or <|translate|> to translate into English.
  5. Timestamps or not: <|notimestamps|> is placed if no timestamps are output. When timestamps are output, the model predicts a start-time token before each sentence and an end-time token after it. Times are relative to the start of the segment, rounded to 20 ms units, and each has its own dedicated token.
  6. Text tokens, followed finally by <|endoftranscript|>.

The loss is applied to all tokens except the previous-context text (cross-entropy for predicting the next token). In this way, language identification, voice activity detection, transcription, translation, and timestamp alignment are all unified into a single form: "predict the next token".

The instruction tokens are like a request note for an interpreter. Writing "This audio is in Japanese", "Please transcribe it as is", and "No timestamps needed" up front lets the same interpreter adjust the job to the request. At inference, the language and task tokens can either be supplied explicitly or predicted by the model.

Data collection centers on filtering to improve transcript quality.

  • Transcripts that appear to be the output of existing speech recognition systems (no punctuation, all upper or lower case, etc.) are detected with several heuristics and removed.
  • Pairs whose audio language does not match the transcript language are removed. However, if the transcript is in English, the pair is used as translation-into-English data.
  • Humans inspected the data sources with high error rates under an initial model and removed low-quality ones.
  • Transcripts overlapping with TED-LIUM 3, which is used for evaluation, are removed.

The training settings are as follows.

ItemValue
OptimizationAdamW, gradient norm clipping
Learning rateWarmup over the first 2,048 updates, then linear decay to 0
Batch256 segments (30 s each)
Updates2202^{20} (2–3 passes over the data)
Data augmentation / regularizationNone (relies on the diversity of the data)

The paper explains that because training covers only a few passes, overfitting is not a major concern. The later Large V2 was trained for 2.5 times as many epochs and added SpecAugment, Stochastic Depth, and BPE-dropout for regularization.

Why It Is Robust

The paper focuses on a discrepancy: models trained only on LibriSpeech make fewer errors than humans on LibriSpeech, yet perform far worse than humans on audio from other conditions.

  • Humans take the test without practicing on a specific dataset. Human performance measures "robustness to unseen conditions".
  • Machine learning models are usually trained extensively on data from the same distribution as the evaluation and then evaluated. Model performance measures "strength within the same distribution".

Whisper is trained on a large amount of data covering diverse recording environments, speakers, and languages, and is not fine-tuned on the evaluation datasets. As a result, it does not overfit to the quirks of specific datasets (such as transcript formatting conventions), and its accuracy degrades less under unseen conditions.

Comparison across data sizes (Medium model. English is the mean word error rate over 12 datasets, multilingual is the word error rate on Fleurs, and translation is BLEU on CoVoST2)

Training data (hours)English WER (%)Multilingual WER (%)Translation into English (BLEU)
3,40530.592.40.2
13,62114.456.67.9
54,48610.936.419.2
681,0709.929.224.8

More data improved every task. However, the gain from 54k to 680k hours is smaller.

Accuracy per language varies greatly with the amount of training data for that language. In the paper's analysis, the log of the amount of training data per language is strongly correlated with the log of the word error rate (r2=0.83r^2 = 0.83), and most of the training data is English. The paper notes that many languages have fewer than 1,000 hours of training data and their accuracy is still low.

Experimental Results

Comparison with a model of the same LibriSpeech accuracy (zero-shot Whisper Large V2 versus wav2vec 2.0 Large fine-tuned on LibriSpeech (no language model). Both are word error rates after the paper's text normalization, in %)

Datasetwav2vec 2.0 LargeWhisper Large V2Relative error reduction (%)
LibriSpeech test-clean2.72.70.0
LibriSpeech test-other6.25.216.1
Common Voice29.99.069.9
TED-LIUM10.54.061.9
CHiME-665.825.561.2
Switchboard28.313.851.2
AMI SDM167.636.446.2
Average (14 rows of the paper's table)29.312.855.2

Although the accuracy on LibriSpeech is almost the same, Whisper's errors on the other datasets are less than half on average.

Multilingual speech recognition (word error rate, in %)

ModelMultilingual LibriSpeechVoxPopuli
XLS-R (1B parameters)10.910.6
mSLAM-CTC (2B parameters)9.79.1
Whisper (zero-shot)7.313.6

On Multilingual LibriSpeech, it outperformed the fine-tuned models, but on VoxPopuli it fell well short.

Model size: the paper shows that scaling from Tiny to Large improves English recognition, multilingual recognition, translation into English, and language identification alike. However, for English speech recognition, the gains diminish as performance approaches human level.

Practical Considerations

Keep the following points in mind when using Whisper.

  • Input is 30 seconds at a time: at most 30 seconds can be fed at once. Long audio is transcribed sequentially by shifting the 30-second window according to the predicted timestamp tokens.
  • Long audio needs decoding heuristics: the paper combines the following heuristics.
    • Use beam search with 5 beams, which is less prone to repetition than greedy decoding
    • Start at temperature 0, and if the average log-probability of the output tokens is below −1 or the gzip compression ratio of the text is above 2.4 (a lot of repeated content), retry with the temperature increased by 0.2 up to 1.0
    • When the temperature is below 0.5, feed the previous window's transcript as previous context
  • Normalize text for evaluation: Whisper is trained on unnormalized transcripts, so punctuation, capitalization, and number formatting may differ from a dataset's reference. The paper normalizes text before computing the word error rate (and has released the normalization code).
  • Specify the language if you can: when the language tag is predicted, it can be wrong for short segments or similar languages. If the language is known, specify it by supplying the language token.

Whisper can make errors such as outputting text unrelated to the audio (hallucination), repeating the same sentence over and over, or dropping the first or last few words of a segment. The paper attributes these to a combination of failures of sequence-to-sequence models, language models, and text-audio alignment, and says that the decoding heuristics above reduce them substantially but do not eliminate them. For critical uses, combine countermeasures such as removing silent segments and checking output probabilities and repetition.

Transcripts in the training data often include speaker names, and early models tended to transcribe plausible but incorrect speaker names. The paper eliminated this behavior by briefly fine-tuning on transcripts without speaker annotations.

Comparison with Other Models

Comparing speech recognition models from the same viewpoints gives the following.

ModelTrainingTraining dataArchitectureUsage
ConformerSupervised on transcribed dataLibriSpeech (about 970 hours), etc.Encoder with built-in convolutions + transducerTrained on the target data before use
wav2vec 2.0, HuBERTPretraining without transcriptions → fine-tuning960 to 60k hours of audio + a few transcriptionsCNN + Transformer encoder, CTC outputFine-tuned on the target data before use
WhisperWeakly supervised (large amounts of transcribed audio)680k hours (including multilingual and translation)Transformer encoder-decoderUsed zero-shot as is

Rough guidelines for choosing are as follows.

  • Transcribing audio from diverse recording conditions and languages without extra training: Whisper is a good fit. Translation, language identification, and timestamped transcription are all possible with a single model.
  • Improving accuracy in a specific domain or language with your own transcriptions: fine-tune wav2vec 2.0 or HuBERT, or train a Conformer. Whisper can also be fine-tuned, but the paper mainly studies its zero-shot performance.
  • Limited compute or low latency: Whisper Large has 1.55B parameters and generates one token at a time with its decoder. Consider using a smaller model (Tiny, Base) or a model that can output everything at once, such as CTC.

PyTorch example

Show code
python
import torch
import whisper   # OpenAI's reference implementation (PyTorch): pip install openai-whisper

"""
Example of using Whisper with OpenAI's reference implementation
1. Process one 30-second window: language identification → transcription (using the paper's multitask format directly)
2. Transcribe long audio with the decoding heuristics of Section 4.5 (beam search, retrying at higher temperature)
"""

model = whisper.load_model("small")          # tiny / base / small / medium / large
model.eval()                                 # inference mode (the reference implementation also disables gradients internally)

# --- 1. One 30-second window ---
audio = whisper.load_audio("speech.wav")     # load via ffmpeg, converted to 16 kHz mono
audio = whisper.pad_or_trim(audio)           # trim or pad with silence to 30 s
mel = whisper.log_mel_spectrogram(audio).to(model.device)   # [80, 3000]: 80 channels × every 10 ms

_, probs = model.detect_language(mel)        # probabilities of the language tag after <|startoftranscript|>
print("Language:", max(probs, key=probs.get))

options = whisper.DecodingOptions(
  language="ja",                 # specify the language tag yourself (None to let the model predict it)
  task="transcribe",             # "translate" translates into English
  without_timestamps=True,       # insert <|notimestamps|>
  fp16=torch.cuda.is_available(),
)
result = whisper.decode(model, mel, options)
print(result.text)

# the special tokens first fed to the decoder (<|startoftranscript|> <|ja|> <|transcribe|>)
tokenizer = whisper.tokenizer.get_tokenizer(multilingual=True, language="ja", task="transcribe")
print(tokenizer.sot_sequence)

# --- 2. Long audio (transcribed by shifting the 30-second window) ---
result = model.transcribe(
  "long_speech.wav",
  language="ja",
  beam_size=5,                                       # beam search with 5 beams
  temperature=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0),        # on failure, retry with temperature raised by 0.2
  logprob_threshold=-1.0,                            # failure if mean log-prob is below −1
  compression_ratio_threshold=2.4,                   # failure if gzip compression ratio exceeds 2.4 (repetition)
  condition_on_previous_text=True,                   # feed the previous window's transcript as context
)
for seg in result["segments"]:
  print(f'{seg["start"]:.2f}–{seg["end"]:.2f}', seg["text"])   # timestamped segments

FAQ

Q. How does Whisper differ from wav2vec 2.0?
A.

wav2vec 2.0 pretrains representations on untranscribed audio and is then fine-tuned with CTC on the target data before being used for speech recognition. Whisper trains its encoder and decoder from scratch with supervised learning on 680,000 hours of transcribed audio and is used as is without fine-tuning. In the paper's comparison of two models with the same accuracy (2.7%) on LibriSpeech test-clean, Whisper made 55.2% fewer errors on average on other datasets.

Q. How is audio longer than 30 seconds transcribed?
A.

It is transcribed in 30-second windows, processed sequentially while shifting the window according to the timestamp tokens predicted by the model. For reliable transcription, the paper combines beam search with 5 beams, retrying at a higher temperature when the average output log-probability is below −1-1 or the gzip compression ratio is above 2.4, and feeding the previous window's transcript as previous context.

Q. Can it be used for Japanese?
A.

Yes. Whisper's multilingual models have language tags for 99 languages, including Japanese, and can transcribe Japanese by specifying <|ja|>. However, according to the paper, accuracy per language is strongly tied to the amount of training data for that language, and most of the training data is English. When using it for Japanese, it is safest to measure the error rate on your own audio.

References

  1. Radford, A., Kim, J. W., Xu, T., Brockman, G., McLeavey, C., & Sutskever, I. (2023). Robust Speech Recognition via Large-Scale Weak Supervision. ICML 2023. arXiv:2212.04356.
  2. OpenAI. Whisper (reference implementation and models). GitHub.
  3. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. NIPS 2017.