Skip to content

Speech decoding policy

L14.4 owns token selection and long-form seeking; L14.3 owns model execution. A LogitsSource.step(prefix) returns the next-token row for a complete, nonempty prefix. Prefixes may repeat, shrink, or switch branches. A source must not mutate previously returned rows. Whisper’s adapter shares cross-KV within an audio window and reuses the common-prefix self-KV across branch changes. It truncates changed suffixes, recomputes the final token on a rewind, and resets self-KV after failed decoder calls. Its storage remains bounded by one model context, rather than retaining every explored beam.

Multilingual prompts start with SOT, the selected language token, then the transcribe or translate token. Text-only generation appends no_timestamps. An English-only tokenizer emits SOT without language/task controls and rejects translation or non-English language selection. Unknown tasks and languages are errors. Language detection queries the SOT row without a task or language prefix and normalizes over language tokens only. Ties choose the first language in tokenizer order.

Timestamp ids form the vocabulary suffix beginning at timestamp_begin. Each increment represents 20 ms for standard Whisper. The caller identifies sample_begin, excluding prompt and control tokens from all rules:

  1. Suppress no_timestamps during timestamp decoding.
  2. The initial generated token must be a timestamp, at most timestamp_begin + max_initial_index (inclusive).
  3. After a start timestamp, suppress timestamps so text or EOT follows.
  4. After text followed by an end timestamp, suppress ordinary text. Another timestamp may begin the next segment; EOT may finish the window.
  5. A segment end must exceed its start. A new segment start may equal the preceding end. Earlier timestamp ids are masked.
  6. After structural masking, compare total timestamp probability with the largest individual non-timestamp probability. If timestamp mass is greater, suppress all non-timestamp ids. Equality does not force a timestamp.

The filter returns a separate float64 row, permits negative infinity for suppressed tokens, rejects NaNs and positive infinity, and fails if no legal token remains. It does not suppress other control tokens or enforce the actual recording duration; those are responsibilities of the decode-window policy.

The state machine follows the reference OpenAI Whisper decoding policy. Recorded-logit parity must check it independently of the model adapter.

DecodeOptions defaults follow the Whisper reference policy (see decode.py): temperatures (0.0, 0.2, 0.4, 0.6, 0.8, 1.0), best_of=5, patience=1.0, compression_ratio_threshold=2.4, logprob_threshold=-1.0, no_speech_threshold=0.6 and max_initial_timestamp=1.0. Additional explicit bounds are max_tokens=224, suppress_tokens=(-1,) and suppress_blank=True. Minus one expands to the tokenizer’s non-speech list. SOT, previous-context, task and no-speech control tokens are always suppressed during generation. The initial blank and EOT are suppressed when suppress_blank is enabled.

Previous transcript tokens are prefixed by sot_prev, truncated to at most half the model context minus one, before the current SOT sequence. Generated length is bounded by both max_tokens and remaining model context. A result excludes EOT and preceding context. Timestamp ids remain in tokens; text decodes only ordinary text ids and strips boundary whitespace.

Temperature zero uses greedy selection when beam size is zero or one. Larger beams retain the best cumulative-log-probability live paths and collect up to round(beam_size * patience) completed paths. At the length limit, unfinished paths can fill missing candidates with an unscored EOT. Positive temperatures use best_of independent trajectories with the supplied course PCG32 stream. Sampling uses the temperature-scaled distribution; scores always use the untempered filtered distribution. Candidate selection divides cumulative log probability by generated length excluding EOT. avg_logprob divides by that length plus one. Stable ascending token ids break equal-logit choices.

No-speech probability comes from the unfiltered SOT row. Compression ratio is UTF-8 text byte length divided by len(zlib.compress(text_bytes)). Window results have relative timestamp endpoints; the long-form loop must still turn them into duration-bounded absolute segments and decide fallback/seek behavior.

Fallback tries temperatures in order until compression ratio and average log probability pass their thresholds. A window with high no-speech probability and low average log probability stops retries. The long-form loop skips that window; confident speech overrides a high no-speech probability.

transcribe accepts finite mono 16 kHz samples, at most 30 minutes. It computes log-mel features once for the full recording with a padded final window. Each seek encodes its feature window once; fallback attempts reuse the same cross-KV. Language detection runs only for the first window when no language was supplied. Seek is measured in 10 ms feature frames; output times are absolute seconds.

Consecutive timestamp tokens delimit completed segments. An incomplete trailing segment resumes at the last completed endpoint. A terminal timestamp consumes the full current window. Empty or zero-duration pieces are omitted, endpoints are clamped to the recording, and every iteration advances at least one frame. Only accepted segment tokens enter prompt history. Disabled conditioning or a selected temperature above 0.5 clears that history before the next window.

WhisperTokenizer.from_pretrained reads local HF tokenizer.json and optional generation_config.json, reusing the course’s byte BPE. It validates every byte symbol and all 1501 contiguous timestamp ids. Both no-speech spellings, <|nospeech|> and HF’s <|nocaptions|>, are supported. Template post-processing is not executed: the decode policy constructs control sequences explicitly. The generation config supplies multilingual mode and suppression ids; without it the standard 51864-token English vocabulary is recognized. Other vocabularies must contain language controls. Ordinary transcript input rejects special-token syntax instead of allowing it to alter the decoder prompt.

tinyllm transcribe --model DIR --audio FILE.wav loads model and tokenizer from the same directory, checks vocabulary agreement, mixes/resamples WAV input to 16 kHz and emits JSON text plus segments. --out also writes that same JSON. --greedy disables fallback, while the default temperature schedule retains it. --beam, --best-of, --patience, --language, --task, --max-tokens, --seed, --no-timestamps and --no-condition-on-previous-text expose the policy settings. --detect-language returns language probabilities for the first window. Invalid inputs return exit code 2 with an error on stderr.

tinyllm transcribe --logits-trace traces.npz --opts opts.json uses the same fallback and long-form loop without loading weights. Options contain a local tokenizer directory (relative to the options file), duration in seconds, window_frames in 10 ms frames, optional context_size (448), and a decode object matching DecodeOptions. Unknown option keys fail.

NPZ arrays use this v1 layout, loaded with pickle disabled:

ArrayShapeMeaning
prefix_offsets[R+1] integerStrictly increasing boundaries, from 0 to N
prefix_ids[N] integerConcatenated complete, nonempty prefixes
seeks[R] integer, optionalNonnegative mel-frame offsets; default zero
logits[R,V] floatDense next-token rows
token_ids, values[R,K] integer/floatAlternative sparse top-k rows
vocab_sizescalar integerRequired only for sparse rows

Dense and sparse encodings cannot be mixed. Sparse ids must be unique within a row; unrecorded vocabulary entries are negative infinity. Each row must have a finite choice. Duplicate seek/prefix keys, missing queried prefixes, NaN, positive infinity, invalid offsets, and vocabulary/context violations fail. Playback returns copies so timestamp masks cannot alter the recording. Sparse rows remain sparse in storage and expand only when queried.

A recording must include every branch visited by its selected search settings, SOT language/silence queries, and all fallback attempts. Missing branches are errors, never extrapolated logits. Python and Rust can therefore consume the same recordings without re-running an encoder or downloading model weights.

L14.4 has public contracts, a chapter, and a reference solution. The timestamp rules and greedy and beam search are checked against independent recorded cases; real-checkpoint tokenizer and long-form transcript parity need separate evidence from a real model. None of this establishes production ASR accuracy.

tinyllm logits --model DIR --audio-features FEATURES.npz --decoder-prompts PROMPTS.jsonl --out OUTPUT.npz runs the Whisper forward pass. The feature archive contains mel, a finite floating array [batch, mel, frames]; --feature-key NAME selects another key. Each JSONL row contains ids, a nonempty list of nonnegative integer token ids. Rows match the feature batch and have equal lengths. The output archive contains logits with shape [batch, tokens, vocab]. The final stdout line reports out and prompts. Invalid inputs exit 2 without creating the output.

tinyllm features --audio PATH --kind whisper-log-mel --n-mels 80 --out OUTPUT.npz accepts a WAV file or a directory of WAV files, sorted by filename. --n-mels accepts 80 or 128. The command downmixes, resamples to 16 kHz, and pads or trims each clip to 30 seconds before computing log-mel features. Output keys are <filename-stem>.f<mel-count>, each shaped [mel-count, 3000]. The final JSON line reports out, clips, and n_mels. Empty directories and malformed WAV input exit 2 without creating the output.

tinyllm eval asr --pred SEGMENTS.json --ref TRANSCRIPT.txt accepts the transcription command’s object or a list of segment objects. Segment text is joined in order; a text-only object is also accepted. Both transcripts use basic_normalize. The final JSON line contains pooled wer, cer, word substitution/deletion/insertion counts, reference_words, and normalizer (whisper-basic). Invalid predictions and an empty normalized reference exit 2. This command scores a single recording; corpus inference and bootstrap intervals require the separate corpus evaluation path.

tinyllm eval asr --model DIR --data MANIFEST.jsonl [--language CODE] [--seed 0] [--bootstrap 1000] loads one Whisper model and tokenizer, then transcribes every manifest item. Each JSONL row has audio (a WAV path relative to the manifest, or absolute) and text (the reference transcript). References must each contain normalized words so every bootstrap resample has a defined denominator. Empty corpora, missing WAV files, and malformed rows fail before model loading.

Output reports pooled wer, cer, utterance-bootstrap wer_ci (95% percentile interval), items, reference_words, normalizer, seed, and bootstrap. Resampling operates on word-edit count rows; it does not average per-item WER or rerun inference. The seed controls decoding and bootstrap reproducibility. Real-checkpoint accuracy needs a separate run against a real model.

Both model transcription and recorded-logit playback include top-level ids: all segment token ids concatenated in segment order, including timestamp tokens. This is the envelope a token-for-token comparison of two transcripts reads.