Sub topic 6
Tuning decoding: language, beam size, temperature, and prompts
This chapter assumes you can already run model.transcribe() from the openai-whisper package and read the result dictionary. It also assumes you know that Whisper is an encoder-decoder transformer that generates text one token at a time. Here you will learn which decoding options change the output and how they interact. You will also learn which ones to leave alone.
What decoding means in Whisper
The encoder turns a 30-second log-Mel spectrogram into a sequence of audio features. The decoder then produces text tokens one at a time. At each step it computes a probability for every token in its vocabulary, and a decoding strategy picks the next token.
Decoding options control three things:
- What the decoder is told before it starts: the language, the task, and an optional prompt.
- How it searches: greedy or beam search, and how random the choice is.
- When it gives up on a result and tries again: the fallback thresholds.
model.transcribe() accepts most of these as keyword arguments. Lower-level code can use whisper.DecodingOptions and whisper.decode() for a single 30-second window.
Fixing the language
By default, Whisper detects the language from the first 30 seconds of audio. The decoder starts with special tokens that name the language and the task. Detection picks the language token with the highest probability.
Detection can fail. A short clip, a noisy recording, or code-switching (a speaker mixing two languages) can produce the wrong language token. The decoder then writes text in that language, which can look like a bad translation or like gibberish. If you know the language, set it:
import whisper
model = whisper.load_model("small")
result = model.transcribe("interview.mp3", language="en", fp16=False)
print(result["language"])
print(result["text"])Setting language skips detection. It also removes a source of error, because the language no longer depends on the first 30 seconds alone. Use the two-letter code, such as en, es, or de.
The task option is either "transcribe" (the default) or "translate". Translation always produces English. Chapter 7 covers it in detail.
Greedy decoding and beam search
The simplest strategy is greedy decoding. At each step the decoder takes the single most likely token. It is fast, but an early wrong choice cannot be undone.
Beam search keeps several candidate sequences at once. At each step it extends every candidate, scores the results, and keeps the best ones. The number kept is the beam size. At the end it returns the candidate with the best overall score.
In openai-whisper, transcribe() uses greedy decoding unless you pass beam_size. Passing beam_size=5 switches to beam search with five candidates.
import whisper
model = whisper.load_model("small")
result = model.transcribe(
"interview.mp3",
language="en",
beam_size=5,
best_of=None,
fp16=False,
)
print(result["text"])Notes on this call:
best_ofapplies to sampling (see the next section). When you usebeam_size, setbest_of=None. Whisper rejects a call that sets both to non-Nonevalues.- Beam search costs more time and memory, roughly in proportion to the beam size.
- The accuracy gain is usually small, often a fraction of a percentage point of word error rate. It matters more on hard audio.
- The faster-whisper library defaults to
beam_size=5, so results between libraries can differ even with the same model.
Temperature, sampling, and fallback
Temperature controls randomness. At temperature 0, the decoder is deterministic: it picks the most likely token (or follows beam search). At a higher temperature, the decoder samples from the probability distribution, so less likely tokens can be chosen.
You might expect that zero is always best. It is not, because greedy decoding at temperature 0 can fall into a repetition loop, such as the same phrase repeated until the window ends. Sampling at a higher temperature can break out of the loop.
Whisper handles this with temperature fallback. By default transcribe() uses a tuple of temperatures:
temperature = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0)It decodes each window at temperature 0 first. It then checks the result against two thresholds. If either check fails, it retries the window at the next temperature.
| Option | Default | Fails when | What it catches |
|---|---|---|---|
| `compression_ratio_threshold` | 2.4 | The gzip compression ratio of the text is above the threshold | Repetitive text, such as loops |
| `logprob_threshold` | -1.0 | The average log probability of the tokens is below the threshold | Low-confidence output |
A third option, no_speech_threshold (default 0.6), works differently. If the model's no-speech probability is above this value and the average log probability is also below logprob_threshold, Whisper treats the window as silence and skips it.
You can pass a single number to disable fallback:
result = model.transcribe("audio.mp3", temperature=0.0)With temperature=0.0, a repetition loop or a low-confidence window is kept as it is. Output becomes reproducible, which helps for tests and comparisons.
When the temperature is above 0, best_of sets how many samples are drawn. Whisper keeps the sample with the best score. The default is 5.
result = model.transcribe(
"audio.mp3",
temperature=(0.0, 0.4, 0.8),
best_of=3,
compression_ratio_threshold=2.4,
logprob_threshold=-1.0,
no_speech_threshold=0.6,
)Retries add time. A file where many windows fail the checks takes noticeably longer than a clean one.
Prompts and context
The initial_prompt option gives the decoder some text to treat as if it came just before the audio. The model is trained to use preceding text as context, so a prompt can nudge it in useful ways:
- Spelling of names and jargon. A prompt such as "Dr. Nguyen discusses Kubernetes and PostgreSQL." makes those spellings more likely.
- Style. A prompt with punctuation and capital letters encourages punctuated output. A prompt without them can lead to the opposite.
- Domain. A sentence about medicine or law shifts the likely vocabulary.
import whisper
model = whisper.load_model("small")
prompt = "Dr. Nguyen discusses Kubernetes, PostgreSQL, and the Grafana dashboard."
result = model.transcribe(
"meeting.mp3",
language="en",
initial_prompt=prompt,
fp16=False,
)
print(result["text"])A prompt is a hint, not an instruction. Whisper is not a chat model, so text like "Please transcribe carefully" is treated as words that came before the audio, not as a command. Keep prompts short and written as plain transcript-style text.
Conditioning on previous text
For long audio, Whisper processes one window after another. By default, condition_on_previous_text=True feeds the text of earlier windows into the next one as a prompt. This helps with consistent spelling and style across the file.
The drawback is that errors propagate. If one window produces a repetition loop or an odd style, the next windows can copy it. Setting condition_on_previous_text=False makes each window independent. This often fixes runs of repeated text, at the cost of less consistency in names and punctuation.
result = model.transcribe(
"long_talk.mp3",
condition_on_previous_text=False,
fp16=False,
)initial_prompt applies to the first window only. In later windows, the previous text takes its place when conditioning is on. If you want a vocabulary hint on every window, turn conditioning off and note that recent versions of openai-whisper keep the initial prompt in context only for the first window. To check what your installed version does, inspect whisper/transcribe.py.
Other useful options
| Option | Effect | When to use it |
|---|---|---|
| `fp16` | Uses half precision on GPU. On CPU, Whisper warns and falls back to fp32 | Set `fp16=False` on CPU to silence the warning |
| `word_timestamps` | Adds a `words` list to each segment | When you need word-level timing (Chapter 9) |
| `suppress_tokens` | Token IDs the decoder may not produce. The default `"-1"` suppresses a standard set of symbols | Rarely changed |
| `without_timestamps` | Decodes text without timestamp tokens | Faster, but segment times become coarse |
| `verbose` | `True` prints segments as they are decoded, `False` prints only a progress bar, `None` prints nothing | Debugging and long files |
A practical tuning order
Change one option at a time and measure. Chapter 10 shows how to compute word error rate for this.
- Set
languageif you know it. - Add
initial_promptif names or jargon are wrong. - Turn off
condition_on_previous_textif you see repeated text. - Try
beam_size=5if accuracy still matters more than speed. - Adjust the fallback thresholds last, and only if you see loops or dropped speech.
Common errors
- Wrong language output. Detection failed. Set
language. - Error when passing
beam_sizewithbest_of. Setbest_of=Nonewhen using beam search. - Repeated phrases. Set
condition_on_previous_text=False, and check that temperature fallback is not disabled. - Results change from run to run. Sampling is active after a fallback. Use a single temperature of 0.0 for repeatable output.
- Prompt text appears in the output. Shorten the prompt, make it read like real transcript text, or drop it for that file.
Exercise
You transcribe a one-hour lecture with model.transcribe("lecture.mp3"). Around minute 20, the same sentence repeats for about two minutes. Name two options you could change to reduce this, and say what each does.
Show answer
Set condition_on_previous_text=False, so a looping window is not fed into the next window as a prompt and the loop cannot spread. Also keep temperature fallback enabled (the default tuple of temperatures) with compression_ratio_threshold at 2.4, so a repetitive window is detected by its high compression ratio and re-decoded at a higher temperature. Passing a single temperature=0.0 would disable that recovery and make loops more likely.
Exercise
A colleague calls model.transcribe("a.mp3", beam_size=5) and gets an error, while model.transcribe("a.mp3", beam_size=5, best_of=None) works. Explain why, and say what best_of normally does.
Show answer
best_of controls how many samples are drawn when the temperature is above 0, and it is a separate search strategy from beam search. Whisper does not allow both to be set at the same time, so best_of must be None when beam_size is used. Without beam search, best_of makes Whisper draw several samples and keep the one with the best score.