# Performance plan

How to make whisper-flow transcribe faster and serve more sessions per server. Items are ranked
by expected impact and each one can be its own PR. An
[animated walkthrough](https://dimastatz.github.io/whisper-flow/docs/performance/performance.html)
of the same plan and a [slide deck](https://dimastatz.github.io/whisper-flow/docs/performance/deck.html)
that goes through each item and why it has the impact it does are on GitHub Pages.

Where the time goes today: almost all of it is Whisper inference, and the streaming loop runs
inference more often than it needs to. Everything else (WebSocket, JSON, numpy glue) is
negligible next to it. Impact notes below are estimates from reading the code; measure before and
after each change (step 0).

## At a glance

| # | Change | Impact | Effort | Where |
|---|--------|--------|--------|-------|
| 0 | Measure first: per-call latency, time-to-final, pool wait | enables the rest | S | [streaming.py](../../whisperflow/streaming.py), [tests/benchmark](../../tests/benchmark) |
| 1 | Pluggable backend: whisper.cpp (Metal) / faster-whisper (CUDA, int8 CPU) | **High** | L | [transcriber.py](../../whisperflow/transcriber.py) |
| 2 | `fp16=True` on CUDA | **High** on GPU | S | [transcriber.py:125](../../whisperflow/transcriber.py#L125) |
| 3 | Don't pay for 30 s of encoder on short windows (`audio_ctx`) | **High** | M (needs 1) | [transcriber.py](../../whisperflow/transcriber.py) |
| 4 | Reuse the last partial as the final when only silence followed | **High** | S | [streaming.py:212-231](../../whisperflow/streaming.py#L212-L231) |
| 5 | Greedy decoding (temperature 0, with fallback) | Medium | S | [transcriber.py:102](../../whisperflow/transcriber.py#L102) |
| 6 | Don't re-transcribe a window that got no new audio | Medium | S | [streaming.py:243-264](../../whisperflow/streaming.py#L243-L264) |
| 7 | Model-based VAD (Silero) and a shorter `WF_SILENCE_MS` | Medium | M | [streaming.py:70-73](../../whisperflow/streaming.py#L70-L73), [config.py:25-26](../../whisperflow/config.py#L25-L26) |
| 8 | Distilled and quantized models | Medium | S | [whisperflow/models](../../whisperflow/models) |
| 9 | Concurrency: thread budget per replica, batching on GPU | Medium | M | [transcriber.py:31-55](../../whisperflow/transcriber.py#L31-L55) |
| 10 | Preload models and warm up at startup | Medium | S | [fast_server.py:44-49](../../whisperflow/fast_server.py#L44-L49) |
| 11 | Opt-in slim results (`text` only) | Low | S | [fast_server.py:167-172](../../whisperflow/fast_server.py#L167-L172) |
| 12 | Event-driven queue and small CPU cleanups | Low | S | [streaming.py](../../whisperflow/streaming.py) |

Suggested order: **2 + 5** (one-liners), then **4 + 6** (contained in `streaming.py`), then
**1 + 3** with step 0's numbers to prove the gain.

## 0. Measure first

**Done:** `WF_METRICS=1` (see [protocol.md](../protocol.md#metrics)).

Log, per session: the duration of each inference call, the window length it covered (for the
real-time factor), the time from the end of speech to the final result, and how long a call waits
for a free replica in `ModelPool.acquire()`. Extend `./run.sh -benchmark` to report
time-to-final next to WER, so every item below has a before/after number on LibriSpeech.

## High impact

### 1. Pluggable inference backend

`transcribe_pcm_chunks` calls `openai-whisper` on PyTorch, on `cuda` if available and otherwise
on the CPU ([transcriber.py:91-93](../../whisperflow/transcriber.py#L91-L93)). On a Mac that
means fp32 on the CPU, with the GPU idle.

Put a small interface around model loading and `transcribe` and add:

- **whisper.cpp** (for example via `pywhispercpp`): Metal on Apple Silicon, quantized `ggml`
  models, small memory footprint. The best fit for Macs.
- **faster-whisper** (CTranslate2): fp16 on NVIDIA, int8 on CPU, native word timestamps. The
  best fit for Linux/NVIDIA.

Keep PyTorch as the default and select with an env var (e.g. `WF_BACKEND`). Things to handle:

- **Word timestamps**: committing ([streaming.py:159-187](../../whisperflow/streaming.py#L159-L187))
  needs them. faster-whisper has them; whisper.cpp has token timestamps, which are coarser and
  need testing against `COMMIT_MARGIN_MS`.
- **Vocabulary prompt**: both support an initial prompt.
- **Model files**: whisper.cpp uses `ggml-*.bin`, faster-whisper uses CTranslate2 folders, but
  `list_models()` only lists `*.pt` ([transcriber.py:58-60](../../whisperflow/transcriber.py#L58-L60)).
  `/ready`'s `models` must reflect the active backend.
- **Decoding options**: map `temperature` and `logprob_threshold` to each backend.

### 2. fp16 on CUDA

`fp16=False` is hardcoded ([transcriber.py:125](../../whisperflow/transcriber.py#L125)), so
NVIDIA GPUs run in fp32. Use `fp16 = device == "cuda"`. Typically close to 2x faster on GPU; no
change on CPU.

### 3. Size the encoder to the audio

Whisper pads every input to 30 s before the encoder runs, so a 2 s partial costs as much encoder
time as a 30 s one. Most streaming windows are short (committing keeps them under a few seconds
of uncommitted audio). whisper.cpp exposes `audio_ctx` to shrink the encoder context to the real
audio length; set it from the window duration with a small margin. Check WER on short windows,
since a too-small context can drop words. Requires item 1.

### 4. Reuse the last partial for the final

When a segment ends by silence, `close_segment` transcribes the whole window again
([streaming.py:220](../../whisperflow/streaming.py#L220)). If every chunk added since the last
partial was silent, that partial already covers all the speech. Track whether non-silent audio
arrived after the last inference and, if not, send the last result as the final. This removes one
full inference from every utterance, so the final arrives `WF_SILENCE_MS` after speech instead of
`WF_SILENCE_MS` plus one inference.

## Medium impact

### 5. Greedy decoding

The default `temperature=0.1` ([transcriber.py:102](../../whisperflow/transcriber.py#L102))
samples, so two calls on the same audio can disagree. The commit scheme
(`common_prefix`) and the "same text twice closes the segment" rule (`should_close_segment`)
both depend on consecutive partials agreeing, so randomness costs extra cycles. Use
`temperature=(0.0, 0.2, 0.4)`: greedy first, falling back only when decoding fails.

### 6. Pace re-transcription

The loop sleeps 10 ms, then transcribes the window whether or not new audio arrived
([streaming.py:243-264](../../whisperflow/streaming.py#L243-L264)). A single speaking session
keeps a replica busy all the time and other sessions queue behind it. Transcribe only after a
minimum amount of new audio (e.g. `WF_MIN_NEW_AUDIO_MS=250`), skip it when everything new is
silence (the transcript can't change), and let silence endpointing close segments. Large win for
sessions per server; small effect on single-user latency.

### 7. Better voice activity detection

Endpointing is a fixed amplitude threshold (`WF_SILENCE_THRESHOLD=500`, `WF_SILENCE_MS=600`).
Background noise above the threshold means a segment never "goes silent", so the window grows
toward the 1000-chunk cap (about 64 s) and each partial gets slower. A small VAD model such as
Silero (fast on CPU) fixes that and makes a shorter `WF_SILENCE_MS` (300-400 ms) safe, which
brings finals in sooner.

### 8. Faster models

**Measured:** see [Choosing a model](../protocol.md#choosing-a-model).

`distil-small.en` and `distil-large-v3` keep most of the accuracy of the original models with a
much faster decoder, and quantized variants exist for both backends in item 1. The default
`tiny.en` is already fast; this matters for users who move to larger models for accuracy.

### 9. Concurrency

`WF_MODEL_REPLICAS=1` with 8 executor threads means sessions take turns on one model
([transcriber.py:31-55](../../whisperflow/transcriber.py#L31-L55)). With several replicas on CPU,
each PyTorch replica uses all cores by default and they oversubscribe the machine: set
`torch.set_num_threads(cores // replicas)`. On GPU, batching windows from several sessions into
one forward pass uses the device better than adding replicas.

### 10. Preload and warm up

Startup loads only the default model ([fast_server.py:44-49](../../whisperflow/fast_server.py#L44-L49)).
A session that picks another model waits for the load, and on GPU the first inference is slow
while kernels initialize. Add `WF_PRELOAD_MODELS` and run one dummy transcription per model in
the lifespan hook.

## Low impact

### 11. Slim results

Every partial sends Whisper's full result (segments, tokens, word timestamps) as JSON
([fast_server.py:167-172](../../whisperflow/fast_server.py#L167-L172)), while clients such as
whisper-code read only `data.text`. An opt-in `start` option (e.g. `"result": "text"`) would cut
serialization and bandwidth for remote servers. Keep the default unchanged, or bump
`PROTOCOL_VERSION` per [docs/protocol.md](../protocol.md).

**Done:** `{"type": "start", "result": "text"}`. The default is unchanged, so `PROTOCOL_VERSION`
stays the same.

### 12. Small CPU cleanups

Wait on the queue instead of polling every 10 ms, keep a running window duration instead of
summing chunk durations on every check, and use a `deque` instead of `list.pop(0)`. Each is
negligible next to inference; do them when touching the code anyway.

**Done:** a session with nothing to transcribe sleeps until audio, a flush or `stop` arrives
(checking at least once a second) instead of waking 100 times a second. While transcribing, the
10 ms cycle is unchanged. The window is a `deque` with a running duration.
