Sub topic 12
Speed and memory: GPU use, fp16, and quantization
This chapter assumes you can already run whisper.load_model and model.transcribe and read the result dictionary. It also assumes you know the model sizes from the earlier chapter. You should know that a neural network is a set of numeric weights, and you should be able to run a Python script and nvidia-smi from a terminal. The goal is to make transcription faster and fit it into the memory you have, without losing accuracy you care about.
Where the time and memory go
Whisper transcription has two costs.
- Encoder pass. Each 30-second window becomes a log-Mel spectrogram. The encoder processes it once. This is a large, regular matrix workload that suits a GPU.
- Decoder loop. The decoder generates text one token at a time. Every token needs a forward pass, and beam search multiplies that work by the beam width. Many small steps make this part latency-bound.
Memory has three parts:
- Weights. The parameter count times the bytes per parameter.
- Activations and caches. Intermediate tensors, plus the decoder's key/value cache, which grows with the number of tokens generated and with beam size.
- Audio buffers. A long file is loaded into RAM as a 16 kHz float array. One hour is about 57.6 million samples, or roughly 230 MB as float32. This is small next to the weights.
Weights are the part you can shrink most easily, by storing each number with fewer bits.
Choosing a device
whisper.load_model places the model on a CUDA GPU if PyTorch can see one, and on the CPU otherwise. You can also set the device yourself. Check what you have first:
import torch
import whisper
print("CUDA available:", torch.cuda.is_available())
if torch.cuda.is_available():
print("GPU:", torch.cuda.get_device_name(0))
device = "cuda" if torch.cuda.is_available() else "cpu"
model = whisper.load_model("small", device=device)
print("Model is on:", next(model.parameters()).device)If torch.cuda.is_available() returns False on a machine that has an NVIDIA GPU, you usually have a CPU-only PyTorch build. Reinstall PyTorch with the CUDA variant that matches your driver.
The README's rough guide for the openai-whisper models looks like this. Treat the numbers as approximate, since they depend on the GPU and the audio.
| Model | Parameters | Approx. VRAM | Relative speed |
|---|---|---|---|
| tiny | 39 M | ~1 GB | ~10x |
| base | 74 M | ~1 GB | ~7x |
| small | 244 M | ~2 GB | ~4x |
| medium | 769 M | ~5 GB | ~2x |
| large | 1550 M | ~10 GB | 1x |
Speeds are relative to large. The turbo variant is also available in recent releases. It is a pruned large model that runs several times faster than large at a small accuracy cost.
fp16: half the memory
Neural network weights are normally stored as 32-bit floats (fp32, 4 bytes each). A 16-bit float (fp16, 2 bytes) halves weight memory and lets a GPU use faster hardware paths. Whisper tolerates fp16 well, so on a GPU it is the default.
transcribe has an fp16 parameter that defaults to True. On a CPU, fp16 is not supported for this model, so Whisper prints a warning ("FP16 is not supported on CPU; using FP32 instead") and falls back to fp32. Pass fp16=False on CPU to avoid the warning.
import whisper
model = whisper.load_model("medium") # on a CUDA GPU
result = model.transcribe("audio.mp3", fp16=True)
print(result["text"])You can estimate weight memory before downloading anything:
PARAMS = {"tiny": 39e6, "base": 74e6, "small": 244e6, "medium": 769e6, "large": 1550e6}
BYTES = {"fp32": 4, "fp16": 2, "int8": 1}
for name, count in PARAMS.items():
row = ", ".join(f"{p}: {count * b / 1e9:.2f} GB" for p, b in BYTES.items())
print(f"{name:7s} {row}")For large this prints 6.20 GB for fp32, 3.10 GB for fp16 and 1.55 GB for int8. The real VRAM use is higher than these weight-only figures because of activations, the key/value cache and framework overhead.
Measuring speed: the real-time factor
Before tuning, measure. The real-time factor (RTF) is processing time divided by audio duration. An RTF of 0.1 means one minute of audio takes six seconds. Lower is faster.
import time
import torch
import whisper
from whisper.audio import SAMPLE_RATE, load_audio
device = "cuda" if torch.cuda.is_available() else "cpu"
use_fp16 = device == "cuda"
audio = load_audio("audio.mp3") # float32 array at 16 kHz mono
duration = len(audio) / SAMPLE_RATE
model = whisper.load_model("small", device=device)
start = time.perf_counter()
model.transcribe(audio, fp16=use_fp16)
elapsed = time.perf_counter() - start
print(f"audio: {duration:.1f} s, processing: {elapsed:.1f} s, RTF: {elapsed / duration:.3f}")Two measurement habits matter:
- Do a warm-up run first. The first call on a GPU includes CUDA initialization and kernel setup. Time the second call, or run a short clip beforehand.
- Keep the model load out of the timer. Loading reads hundreds of megabytes from disk and is a one-time cost in a long-running service.
You can watch VRAM from Python with torch.cuda.max_memory_allocated(), or from a terminal with nvidia-smi. Note that nvidia-smi reports memory reserved by PyTorch's allocator, which is often higher than memory in active use.
Quantization: fewer bits per weight
Quantization stores weights as low-precision integers, typically 8-bit (int8), and converts them back to approximate floating-point values during computation. It reduces memory and can speed up CPU inference, at the cost of small numerical errors. For speech recognition those errors usually raise word error rate only slightly, but you should verify that on your own audio using the WER method from the evaluation chapter.
There are two practical routes.
Dynamic quantization in PyTorch (CPU)
PyTorch can quantize the linear layers of a loaded model in place. This runs on the CPU and keeps fp32 for everything else:
import torch
import whisper
model = whisper.load_model("small", device="cpu")
quantized = torch.quantization.quantize_dynamic(
model, {torch.nn.Linear}, dtype=torch.qint8
)
result = quantized.transcribe("audio.mp3", fp16=False)
print(result["text"])This needs no extra package, but the gain varies by CPU and PyTorch version, and the quantization API has moved between releases. Benchmark it against the unquantized model before adopting it.
Quantized runtimes
Dedicated runtimes ship better-optimized int8 kernels than PyTorch's generic path. The faster-whisper library, covered in the next chapter, uses the CTranslate2 engine and lets you pick the numeric type with one argument. The common values are:
| `compute_type` | Device | Effect |
|---|---|---|
| `float16` | GPU | Half the weight memory of fp32, the usual GPU default. |
| `int8_float16` | GPU | int8 weights with fp16 compute. Lowest GPU memory. |
| `int8` | CPU or GPU | Smallest and often fastest on CPU. |
| `float32` | CPU or GPU | Reference quality, highest memory. |
Not every device supports every type. If a type is unsupported, CTranslate2 raises an error or converts to a supported type, depending on the setup.
Decoding settings that cost speed
Several options you met earlier affect speed as well as quality:
beam_size. Beam search keeps several candidate sequences alive, so a beam size of 5 does roughly five times the decoder work per step compared with greedy decoding. It also uses more memory for the key/value cache.- Temperature fallback. By default
transcriberetries a window at higher temperatures when its output looks bad (too repetitive or low-probability). Each retry repeats the whole decode for that window. On noisy audio, many retries can double the processing time. Passing a single temperature, such astemperature=0.0, disables the fallback, but then a failed window is not retried and may contain repeated text. word_timestamps=True. This runs an extra alignment step using the cross-attention weights, which adds time on top of the decode.condition_on_previous_text. Setting it toFalsedoes not make decoding faster. People often turn it off to stop repetition loops from spreading across windows, and it is worth knowing it is a quality control, not a speed control.
Fitting in memory: a decision path
When a model does not fit, work through these steps in order and stop when it fits:
- Confirm you are not holding two models in memory (for example, a leftover from an earlier notebook cell). Call
del modelandtorch.cuda.empty_cache(). - Use fp16 on GPU if you are not already.
- Lower
beam_size, or use greedy decoding. - Move to a smaller model size, or the turbo variant instead of
large. - Switch to an int8 runtime such as faster-whisper.
Dropping a model size costs accuracy, especially on accented speech and low-resource languages. Quantizing a larger model often beats using a smaller model at full precision. For example, medium in int8 uses about 0.8 GB for weights, which is less than small in fp32 at about 1 GB. Measure both on your data before assuming that.
Common mistakes
- Benchmarking the first call. CUDA warm-up inflates it. Time a later call.
- Expecting fp16 gains on CPU. The CPU path is fp32 in openai-whisper, so
fp16=Truechanges nothing there. - Comparing speeds across different audio. Silence is fast to process and dense speech is slower, so compare on identical files.
- Reading
nvidia-smias exact use. It includes cached memory that PyTorch keeps reserved for reuse.
Exercise
A large model has about 1550 million parameters. Estimate the weight-only memory in GB when stored as fp16, and as int8. Then explain why the real VRAM use on a GPU will be higher than your estimate.
Show answer
fp16 uses 2 bytes per parameter: 1550e6 × 2 = 3.1 GB. int8 uses 1 byte per parameter: 1550e6 × 1 = 1.55 GB. Real VRAM use is higher because the GPU also holds activations for the encoder and decoder, the decoder's key/value cache (which grows with beam size and generated tokens), and framework overhead such as CUDA context and PyTorch's reserved allocator cache.
Exercise
You time a transcription of a 10-minute file on a GPU and get 45 seconds on the first run and 18 seconds on the second run. What is the real-time factor you should report, and why is the first number misleading?
Show answer
The audio is 600 seconds, so RTF = 18 / 600 = 0.03. The first run includes one-time CUDA initialization and kernel setup, so it measures start-up cost as well as steady-state transcription speed.
Exercise
Your service transcribes noisy audio and is much slower than on clean audio, although the model and hardware are the same. Name one decoding behavior that could explain this, and one trade-off of turning it off.
Show answer
The default temperature fallback retries windows whose output looks bad, and every retry repeats the decode for that window, so noisy audio triggers many retries. Passing a single temperature such as temperature=0.0 disables the retries and restores speed, but a window that decodes badly is then kept as is and may contain repeated or low-quality text.