From 84da5fe78f4f9676a846fc0951113b23288c04de Mon Sep 17 00:00:00 2001 From: Jaeyeong Choi <144660874+Jaeyeong-CHOI@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:50:51 +0900 Subject: [PATCH 1/2] feat(whisper): load quantized MLX exports and the openai/whisper rank-file tokenizer The mlx-community Whisper exports (whisper-{tiny,base,small}-{4bit,8bit}, whisper-large-v3-turbo-4bit, whisper-tiny.en-4bit) are affine-quantized and ship multilingual.tiktoken / gpt2.tiktoken instead of tokenizer.json. None of them could be served: - the server's startup tokenizer sent the rank file to the HunYuan tiktoken reader, which fails on the "= 50256" placeholder line ("Invalid symbol 61, offset 0.") and stopped the server; - the Whisper loader required tokenizer.json; - every projection and the token embedding were dense layers over the packed uint32 planes, and the compute dtype was read from the packed table, so the mel spectrogram was cast to uint32 and the first request aborted. Projections and the tied token embedding that ship .scales now run through UnifiedLinear / UnifiedEmbedding (the reference nn.quantize class predicate), the quantization block is read through the shared QuantizationArgs and validated, the compute dtype falls back to the scales dtype, and a quantized export keeps its tensors as written. Without tokenizer.json the byte-level BPE is built from the rank file, with merges recovered as Hugging Face's TikTokenConverter does and the special tokens numbered as openai/whisper's get_encoding numbers them for the model's n_vocab; a rank beyond what n_vocab leaves for the BPE is refused before it can size the rank table, and load_tokenizer uses the same builder for a Whisper directory. Only a declared (non-null) quantization block skips the bf16 -> f16 conversion. Whether a model is multilingual follows the reference rule n_vocab >= 51865, so an English-only checkpoint is no longer prompted with a language and task token. --- docs/audio-api.md | 6 +- docs/supported-models.md | 2 +- scripts/ci/check_env_var_docs.py | 8 + scripts/whisper_mlx_reference.py | 186 ++++++++ src/models/config.rs | 6 +- src/models/sanitize.rs | 4 +- src/models/whisper/decoder.rs | 20 +- src/models/whisper/decoding.rs | 6 +- src/models/whisper/encoder.rs | 4 +- src/models/whisper/layers.rs | 57 ++- src/models/whisper/mod.rs | 536 +++++++++++++++++++++- src/models/whisper/real_tests.rs | 295 ++++++++++++ src/models/whisper/tokenizer.rs | 746 ++++++++++++++++++++++++++++++- src/tokenizer/mod.rs | 84 ++++ 14 files changed, 1896 insertions(+), 64 deletions(-) create mode 100755 scripts/whisper_mlx_reference.py create mode 100644 src/models/whisper/real_tests.rs diff --git a/docs/audio-api.md b/docs/audio-api.md index 2596526ad7..914919292e 100644 --- a/docs/audio-api.md +++ b/docs/audio-api.md @@ -37,7 +37,7 @@ Pass a Whisper checkpoint directory to `-m`. The server detects `model_type: "wh mlxcel-server -m models/whisper-base ``` -Both the native MLX key layout and the HuggingFace `WhisperForConditionalGeneration` layout load without conversion. The checkpoint directory must contain `config.json`, one or more SafeTensors weight files, and `tokenizer.json`. +Both the native MLX key layout and the HuggingFace `WhisperForConditionalGeneration` layout load without conversion. The checkpoint directory must contain `config.json`, one or more SafeTensors weight files, and a tokenizer: `tokenizer.json`, or the openai/whisper rank file the MLX exports ship instead (`multilingual.tiktoken`, or `gpt2.tiktoken` for the English-only models). A rank file is read only when `tokenizer.json` is absent, and its special tokens are numbered the way openai/whisper numbers them for the model's `n_vocab`. Loading a Whisper checkpoint occupies the audio slot only; the server does not serve `/v1/chat/completions` or generation requests from that process. Chat and STT are separate server instances. @@ -45,7 +45,9 @@ Loading a Whisper checkpoint occupies the audio slot only; the server does not s **Long audio.** Audio longer than 30 seconds is split into consecutive 30-second windows, each transcribed independently. The results are concatenated in order. Word-level timestamps, segment-level timestamps, and VAD-gated chunking are follow-ups. -**Current limitations.** Non-quantized (fp16/f32) checkpoints only; quantized Whisper weights are not yet supported. Greedy decoding only; beam search is a follow-up. +**Quantized checkpoints.** MLX affine exports, which declare `"quantization": {"group_size": 64, "bits": 4}` (or `8`) in `config.json`, load as published, for example `mlx-community/whisper-tiny-4bit` or `mlx-community/whisper-large-v3-turbo-4bit`. Every projection and the token embedding that ship a `.scales` tensor run as quantized matmuls, including the tied output head; the convolutions and positional tables stay dense, as in the reference loader. Other quantization modes are refused at load. + +**Current limitations.** Greedy decoding only; beam search is a follow-up. A checkpoint that ships its weights only as `weights.npz`, or no tokenizer file at all (mlx-whisper falls back to the rank files bundled in its Python package), does not load. ## Kokoro TTS setup diff --git a/docs/supported-models.md b/docs/supported-models.md index 80cfc9ab08..b151839f56 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -860,7 +860,7 @@ mlxcel loads Whisper-style encoder-decoder ASR checkpoints (`model_type: "whispe When the server's loaded checkpoint is detected as Whisper, the speech-to-text slot is populated and `POST /v1/audio/transcriptions` (transcribe in place) and `POST /v1/audio/translations` (translate to English) return the recognized text. Uploaded audio is decoded with the shared WAV reader, resampled to 16 kHz, and processed in consecutive 30-second windows. An explicit `language` hint is honored; otherwise the language is detected from the first decoder step. Token suppression follows the Whisper rules: `suppress_blank`, the non-speech symbol set, and `<|notimestamps|>`. -This first port targets non-quantized (fp16/f32) checkpoints with greedy decoding, and the loader accepts both the native MLX and HuggingFace key layouts. Loading a Whisper checkpoint serves speech-to-text only; chat generation is not available in the same process. Beam search, word-level and segment timestamps, quantized checkpoints, and streaming transcription are follow-ups. +The port decodes greedily, and the loader accepts both the native MLX and HuggingFace key layouts, fp16/f32 weights and the MLX affine 4-bit and 8-bit exports (`mlx-community/whisper-*-4bit`, `-8bit`), with either `tokenizer.json` or the openai/whisper `multilingual.tiktoken` / `gpt2.tiktoken` rank file those exports ship (see [Whisper STT setup](audio-api.md#whisper-stt-setup)). Loading a Whisper checkpoint serves speech-to-text only; chat generation is not available in the same process. Beam search, word-level and segment timestamps, and streaming transcription are follow-ups. ## Text-to-speech (TTS) diff --git a/scripts/ci/check_env_var_docs.py b/scripts/ci/check_env_var_docs.py index 1b40b5e4b2..9ccfb12092 100755 --- a/scripts/ci/check_env_var_docs.py +++ b/scripts/ci/check_env_var_docs.py @@ -339,6 +339,14 @@ "MLXCEL_TEST_EMBED_LORA_PROMPT", "MLXCEL_TEST_EMBED_LORA_TOLERANCE", )), + ("test-only: checkpoint directory, mlx-whisper reference files and " + "openai/whisper tokenizer.json of the Whisper real-checkpoint parity " + "tests in models/whisper/real_tests.rs", ( + "MLXCEL_TEST_WHISPER_DIR", + "MLXCEL_TEST_WHISPER_HF_TOKENIZER", + "MLXCEL_TEST_WHISPER_REFERENCE", + "MLXCEL_TEST_WHISPER_TOKENIZER_REFERENCE", + )), ("test-only: input of the Qwen3-VL vision stage-dump test in " "qwen3_vl_stage_dump_tests.rs", ( "MLXCEL_QWEN3_VL_STAGE_DUMP_DIR", diff --git a/scripts/whisper_mlx_reference.py b/scripts/whisper_mlx_reference.py new file mode 100755 index 0000000000..3dc462bd47 --- /dev/null +++ b/scripts/whisper_mlx_reference.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +# Copyright 2025-2026 Lablup Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Write an mlx-whisper reference for the Whisper real-checkpoint parity tests. + +The output is a safetensors file read by ``src/models/whisper/real_tests.rs``: + +* ``audio``: the 16 kHz mono clip (f32), so the Rust side needs no decoder; +* ``mel``: the first 30 s log-mel window exactly as ``mlx_whisper.transcribe`` + builds it (f32, ``[1, 3000, n_mels]``); +* ``tokens``: the decoder prompt plus the greedy tokens of + ``mlx_whisper.decoding.decode`` with ``temperature=0`` and + ``without_timestamps=True`` (the end-of-text token excluded), as i32; +* ``prompt_len``: the prompt length, as a one-element i32 tensor; +* ``logits``: the teacher-forced decoder logits over ``tokens`` (f32, + ``[len(tokens), n_vocab]``), computed in float16 like ``transcribe``; + +plus the decoded text and the language in the safetensors metadata. + +``--tokenizer-out`` also writes a JSON file for the tokenizer parity test: the +special-token ids and the token ids tiktoken assigns to a multilingual corpus, +from the encoding ``mlx_whisper.tokenizer.get_encoding`` builds for the model. + +mlx-whisper's ``load_model`` reads ``weights.safetensors`` / ``weights.npz``; +the mlx-community quantized exports name the file ``model.safetensors``, so the +model is assembled here the same way ``load_model`` does it (``nn.quantize`` +with the ``.scales`` class predicate when ``config.json`` has a +``quantization`` block) from whichever of the three files exists. + +Usage:: + + python scripts/whisper_mlx_reference.py --model DIR --audio clip.flac \ + --out ref.safetensors [--language en] [--tokenizer-out tok.json] + +Requires ``mlx``, ``mlx-whisper`` and ``miniaudio`` (for decoding the clip). +""" + +import argparse +import json +from pathlib import Path + +import miniaudio +import mlx.core as mx +import mlx.nn as nn +import numpy as np +from mlx.utils import tree_unflatten +from mlx_whisper import audio, decoding, whisper +from mlx_whisper.tokenizer import get_encoding, get_tokenizer + +CORPUS = [ + "Hello world.", + " He said: \"it's 3:45 p.m.\" -- isn't it?", + "The quick brown fox jumps over the lazy dog 1234567890 times!!!", + " leading and inner spaces\tand\ttabs\nand newlines\n\n", + "안녕하세요. 오늘 날씨가 정말 좋네요.", + "こんにちは、世界。今日はいい天気ですね。", + "你好,世界!今天天气很好。", + "Привет, мир! Ça va? Größe, naïve café, jalapeño.", + "♪♪ la la ♪ [music] (applause) <> {braces} ~tilde~ «guillemets»", + "emoji: 😀🎉👍🏽 and math ∑∫√∞ ≠ ≤", + "'s 't 're 've 'm 'll 'd I'M YOU'RE", + "https://example.com/path?query=1&x=2#frag", +] + + +def load_model(path: Path, dtype=mx.float16) -> whisper.Whisper: + config = json.loads((path / "config.json").read_text()) + config.pop("model_type", None) + quantization = config.pop("quantization", None) + model = whisper.Whisper(whisper.ModelDimensions(**config), dtype) + for name in ("weights.safetensors", "model.safetensors", "weights.npz"): + if (path / name).exists(): + weights = mx.load(str(path / name)) + break + else: + raise SystemExit(f"no weights file in {path}") + if quantization is not None: + nn.quantize( + model, + **quantization, + class_predicate=lambda p, m: isinstance(m, (nn.Linear, nn.Embedding)) + and f"{p}.scales" in weights, + ) + model.update(tree_unflatten(list(weights.items()))) + mx.eval(model.parameters()) + return model + + +def read_clip(path: Path) -> np.ndarray: + clip = miniaudio.decode_file( + str(path), + output_format=miniaudio.SampleFormat.FLOAT32, + nchannels=1, + sample_rate=audio.SAMPLE_RATE, + ) + return np.asarray(clip.samples, dtype=np.float32) + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--model", type=Path, required=True) + ap.add_argument("--audio", type=Path, required=True) + ap.add_argument("--out", type=Path, required=True) + ap.add_argument("--language", default=None) + ap.add_argument("--tokenizer-out", type=Path, default=None) + args = ap.parse_args() + + model = load_model(args.model) + samples = read_clip(args.audio) + # transcribe(): mel over the clip plus 30 s of padding, first window. + mel = audio.log_mel_spectrogram( + mx.array(samples), n_mels=model.dims.n_mels, padding=audio.N_SAMPLES + ) + mel = audio.pad_or_trim(mel[: audio.N_FRAMES], audio.N_FRAMES, axis=-2)[None] + mel = mel.astype(mx.float32) + + options = decoding.DecodingOptions( + language=args.language, temperature=0.0, without_timestamps=True, fp16=True + ) + result = decoding.decode(model, mel.astype(mx.float16), options)[0] + tokenizer = get_tokenizer( + model.is_multilingual, + num_languages=model.num_languages, + language=result.language if model.is_multilingual else None, + task="transcribe", + ) + prompt = list(tokenizer.sot_sequence_including_notimestamps) + tokens = prompt + list(result.tokens) + + features = model.encoder(mel.astype(mx.float16)) + logits, _, _ = model.decoder(mx.array([tokens]), features) + logits = logits[0].astype(mx.float32) + + text = tokenizer.decode(result.tokens) + mx.save_safetensors( + str(args.out), + { + "audio": mx.array(samples), + "mel": mel, + "tokens": mx.array(tokens, dtype=mx.int32), + "prompt_len": mx.array([len(prompt)], dtype=mx.int32), + "logits": logits, + }, + metadata={ + "text": text, + "language": result.language or "", + "model": str(args.model), + "audio_file": args.audio.name, + }, + ) + print(json.dumps({"text": text, "language": result.language, "tokens": tokens})) + + if args.tokenizer_out is not None: + encoding = get_encoding( + "multilingual" if model.is_multilingual else "gpt2", + num_languages=model.num_languages, + ) + specials = {name: encoding.encode_single_token(name) for name in encoding.special_tokens_set} + args.tokenizer_out.write_text( + json.dumps( + { + "n_vocab": model.dims.n_vocab, + "n_vocab_encoding": encoding.n_vocab, + "special": specials, + "texts": CORPUS, + "ids": [encoding.encode_ordinary(t) for t in CORPUS], + }, + ensure_ascii=False, + indent=1, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/src/models/config.rs b/src/models/config.rs index fea868ec79..2b64e1f55b 100644 --- a/src/models/config.rs +++ b/src/models/config.rs @@ -253,7 +253,8 @@ where /// the accessors below rather than failing deserialization, which matters for a /// family that reads the block out of an inherited sub-config. /// -/// Used by: `crate::models::deepseek::ModelArgs` (issue #975) +/// Used by: `crate::models::deepseek::ModelArgs` (issue #975), +/// `crate::models::whisper::WhisperQuantization::from_config` #[derive(Debug, Clone, Default, Deserialize)] pub struct QuantizationArgs { #[serde(default)] @@ -295,7 +296,8 @@ impl QuantizationArgs { /// /// Used by: `crate::models::deepseek::ModelArgs::quantization_mode` /// (issue #975), which is also the family that adopted this whole - /// struct rather than declaring another private `Quantization` + /// struct rather than declaring another private `Quantization`; + /// `crate::models::whisper::WhisperQuantization::from_config` pub fn get_mode(&self) -> Result<&str, String> { let mode = self.mode.as_deref().unwrap_or("affine"); mlxcel_core::layers::validate_quantization_mode(mode)?; diff --git a/src/models/sanitize.rs b/src/models/sanitize.rs index 6ee5fbb0b3..983df5b9fc 100644 --- a/src/models/sanitize.rs +++ b/src/models/sanitize.rs @@ -3076,7 +3076,9 @@ pub fn warn_bf16_precision() { /// Used by: load_text_weights, load_vlm_weights_common, Florence-2 (called /// directly from `Florence2Model::load`, `Florence2TextModel::load`, and /// `Florence2DaViT::load`, each of which skips the conversion when the -/// checkpoint declares quantization metadata) +/// checkpoint declares quantization metadata), and Whisper +/// (`WhisperModel::load`, which skips it when `config.json` declares a +/// non-null MLX `quantization` block) #[must_use] pub fn convert_bf16_weights(weights: &mut mlxcel_core::weights::WeightMap) -> bool { convert_bf16_weights_with_keep(weights, |_| false) diff --git a/src/models/whisper/decoder.rs b/src/models/whisper/decoder.rs index 6c0ac18d61..1cde4af8d1 100644 --- a/src/models/whisper/decoder.rs +++ b/src/models/whisper/decoder.rs @@ -16,15 +16,15 @@ //! masked self-attention and cross-attention to the encoder output, a final //! LayerNorm, and tied output logits. -use mlxcel_core::layers::{Embedding, LayerNorm}; +use mlxcel_core::layers::{LayerNorm, UnifiedEmbedding}; use mlxcel_core::weights::WeightMap; use mlxcel_core::{MlxArray, UniquePtr}; -use super::WhisperDims; use super::layers::{KvCache, ResidualAttentionBlock, additive_causal_mask}; +use super::{WhisperDims, WhisperQuantization}; pub(crate) struct TextDecoder { - token_embedding: Embedding, + token_embedding: UnifiedEmbedding, positional_embedding: UniquePtr, blocks: Vec, ln: LayerNorm, @@ -37,8 +37,19 @@ impl TextDecoder { weights: &WeightMap, dims: &WhisperDims, dtype: i32, + quant: WhisperQuantization, ) -> Result { - let token_embedding = Embedding::from_weights(weights, "decoder.token_embedding")?; + // Packed when the checkpoint ships `decoder.token_embedding.scales` + // (the reference quantizes it as an `nn.Embedding`); its `as_linear` + // then runs the tied output head as a quantized matmul, as + // `QuantizedEmbedding.as_linear` does upstream. + let token_embedding = UnifiedEmbedding::from_weights( + weights, + "decoder.token_embedding", + quant.group_size, + quant.bits, + ) + .map_err(|e| format!("Whisper decoder.token_embedding: {e}"))?; let positional_embedding = weights .get("decoder.positional_embedding") .map(|w| mlxcel_core::copy(w)) @@ -51,6 +62,7 @@ impl TextDecoder { &format!("decoder.blocks.{i}"), dims.n_text_head, true, + quant, )?); } diff --git a/src/models/whisper/decoding.rs b/src/models/whisper/decoding.rs index 28092fc07f..cde9e0ae5b 100644 --- a/src/models/whisper/decoding.rs +++ b/src/models/whisper/decoding.rs @@ -217,7 +217,11 @@ mod tests { "normalizer": null, "pre_tokenizer": null, "post_processor": null, "decoder": null, "model": {"type": "BPE", "dropout": null, "unk_token": null, "continuing_subword_prefix": null, "end_of_word_suffix": null, "fuse_unk": false, "byte_fallback": false, "vocab": {"a": 0, " ": 1, "b": 2}, "merges": []} }"#; - WhisperTokenizer::from_tokenizer(Tokenizer::from_bytes(json.as_bytes()).unwrap()).unwrap() + WhisperTokenizer::from_tokenizer( + Tokenizer::from_bytes(json.as_bytes()).unwrap(), + crate::models::whisper::tokenizer::MULTILINGUAL_MIN_N_VOCAB, + ) + .unwrap() } #[test] diff --git a/src/models/whisper/encoder.rs b/src/models/whisper/encoder.rs index c564b80444..370dabf221 100644 --- a/src/models/whisper/encoder.rs +++ b/src/models/whisper/encoder.rs @@ -20,8 +20,8 @@ use mlxcel_core::layers::LayerNorm; use mlxcel_core::weights::WeightMap; use mlxcel_core::{MlxArray, UniquePtr}; -use super::WhisperDims; use super::layers::ResidualAttentionBlock; +use super::{WhisperDims, WhisperQuantization}; fn conv_weight(weights: &WeightMap, key: &str) -> Result, String> { weights @@ -65,6 +65,7 @@ impl AudioEncoder { weights: &WeightMap, dims: &WhisperDims, dtype: i32, + quant: WhisperQuantization, ) -> Result { let positional_data = sinusoids(dims.n_audio_ctx as usize, dims.n_audio_state as usize); let positional = @@ -78,6 +79,7 @@ impl AudioEncoder { &format!("encoder.blocks.{i}"), dims.n_audio_head, false, + quant, )?); } diff --git a/src/models/whisper/layers.rs b/src/models/whisper/layers.rs index 2160cfedec..12a560ef79 100644 --- a/src/models/whisper/layers.rs +++ b/src/models/whisper/layers.rs @@ -19,10 +19,12 @@ //! reuse the same [`MultiHeadAttention`] and [`ResidualAttentionBlock`] here, //! differing only in whether the cross-attention sublayer is present. -use mlxcel_core::layers::{LayerNorm, Linear}; +use mlxcel_core::layers::{LayerNorm, UnifiedLinear}; use mlxcel_core::weights::WeightMap; use mlxcel_core::{MlxArray, UniquePtr}; +use super::WhisperQuantization; + /// Per-sublayer key/value cache. Holds `[batch, length, n_state]` tensors that /// are appended to (self-attention) or computed once (cross-attention). pub(crate) struct KvCache { @@ -30,8 +32,17 @@ pub(crate) struct KvCache { pub v: UniquePtr, } -fn linear(weights: &WeightMap, prefix: &str) -> Result { - Linear::from_weights(weights, prefix) +/// A projection that is quantized when the checkpoint ships `{prefix}.scales` +/// and dense otherwise, matching the reference `nn.quantize` class predicate +/// (`isinstance(m, nn.Linear) and f"{p}.scales" in weights`). The dense branch +/// is the plain `Linear` this port always built. +fn linear( + weights: &WeightMap, + prefix: &str, + quant: WhisperQuantization, +) -> Result { + UnifiedLinear::from_weights(weights, prefix, quant.group_size, quant.bits) + .map_err(|e| format!("Whisper {prefix}: {e}")) } fn layer_norm(weights: &WeightMap, prefix: &str) -> Result { @@ -109,20 +120,25 @@ fn qkv_attention( /// automatically because [`Linear`] treats `.bias` as optional. pub(crate) struct MultiHeadAttention { n_head: i32, - query: Linear, - key: Linear, - value: Linear, - out: Linear, + query: UnifiedLinear, + key: UnifiedLinear, + value: UnifiedLinear, + out: UnifiedLinear, } impl MultiHeadAttention { - fn from_weights(weights: &WeightMap, prefix: &str, n_head: i32) -> Result { + fn from_weights( + weights: &WeightMap, + prefix: &str, + n_head: i32, + quant: WhisperQuantization, + ) -> Result { Ok(Self { n_head, - query: linear(weights, &format!("{prefix}.query"))?, - key: linear(weights, &format!("{prefix}.key"))?, - value: linear(weights, &format!("{prefix}.value"))?, - out: linear(weights, &format!("{prefix}.out"))?, + query: linear(weights, &format!("{prefix}.query"), quant)?, + key: linear(weights, &format!("{prefix}.key"), quant)?, + value: linear(weights, &format!("{prefix}.value"), quant)?, + out: linear(weights, &format!("{prefix}.out"), quant)?, }) } @@ -175,8 +191,8 @@ pub(crate) struct ResidualAttentionBlock { attn_ln: LayerNorm, cross_attn: Option, cross_attn_ln: Option, - mlp1: Linear, - mlp2: Linear, + mlp1: UnifiedLinear, + mlp2: UnifiedLinear, mlp_ln: LayerNorm, } @@ -186,6 +202,7 @@ impl ResidualAttentionBlock { prefix: &str, n_head: i32, cross_attention: bool, + quant: WhisperQuantization, ) -> Result { let (cross_attn, cross_attn_ln) = if cross_attention { ( @@ -193,6 +210,7 @@ impl ResidualAttentionBlock { weights, &format!("{prefix}.cross_attn"), n_head, + quant, )?), Some(layer_norm(weights, &format!("{prefix}.cross_attn_ln"))?), ) @@ -200,12 +218,17 @@ impl ResidualAttentionBlock { (None, None) }; Ok(Self { - attn: MultiHeadAttention::from_weights(weights, &format!("{prefix}.attn"), n_head)?, + attn: MultiHeadAttention::from_weights( + weights, + &format!("{prefix}.attn"), + n_head, + quant, + )?, attn_ln: layer_norm(weights, &format!("{prefix}.attn_ln"))?, cross_attn, cross_attn_ln, - mlp1: linear(weights, &format!("{prefix}.mlp1"))?, - mlp2: linear(weights, &format!("{prefix}.mlp2"))?, + mlp1: linear(weights, &format!("{prefix}.mlp1"), quant)?, + mlp2: linear(weights, &format!("{prefix}.mlp2"), quant)?, mlp_ln: layer_norm(weights, &format!("{prefix}.mlp_ln"))?, }) } diff --git a/src/models/whisper/mod.rs b/src/models/whisper/mod.rs index c162bbee92..cc100b77bf 100644 --- a/src/models/whisper/mod.rs +++ b/src/models/whisper/mod.rs @@ -18,10 +18,17 @@ //! autoregressive text decoder whose blocks cross-attend to the encoder output. //! The decoder is steered by multilingual transcribe/translate task tokens. //! -//! This first port targets non-quantized (fp16/f32) MLX checkpoints and greedy -//! decoding. The weight loader also accepts the HuggingFace key layout so either -//! export of a checkpoint loads. Quantized checkpoints, beam search, and -//! word-level timestamps are tracked as follow-ups. +//! This first port targets fp16/f32 MLX checkpoints and greedy decoding. The +//! weight loader also accepts the HuggingFace key layout so either export of a +//! checkpoint loads. Quantized MLX exports (the `mlx-community/whisper-*-4bit` +//! and `-8bit` conversions) load too: every projection and the tied token +//! embedding that carries a `.scales` sibling runs through the unified +//! quantized layers, the same way the reference `nn.quantize` class predicate +//! picks them, and the convolutions and positional tables stay dense. Those +//! exports ship the openai/whisper `multilingual.tiktoken` or `gpt2.tiktoken` +//! rank file instead of a `tokenizer.json`; the tokenizer module builds the +//! byte-level BPE from it. Beam search and word-level timestamps are tracked as +//! follow-ups. mod decoder; mod decoding; @@ -37,6 +44,7 @@ use serde_json::Value; use mlxcel_core::weights::WeightMap; use crate::audio::whisper_mel; +use crate::models::config::QuantizationArgs; use decoder::TextDecoder; use encoder::AudioEncoder; @@ -64,6 +72,96 @@ fn config_i32(config: &Value, keys: &[&str]) -> Option { .map(|v| v as i32) } +/// Affine quantization parameters of an MLX Whisper export, read from the +/// `quantization` object of `config.json`. +/// +/// mlx-whisper and the mlx-audio converters write `{"group_size": 64, "bits": +/// 4}` (or `8`) there and quantize every `nn.Linear` / `nn.Embedding` whose +/// shapes allow it. The values only matter for modules that actually ship a +/// `.scales` tensor: [`mlxcel_core::layers::UnifiedLinear`] and +/// [`mlxcel_core::layers::UnifiedEmbedding`] fall back to the dense layer for +/// every other prefix, so a dense checkpoint (no `quantization` object) gets +/// MLX's `nn.quantize` defaults and loads exactly as before. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct WhisperQuantization { + pub group_size: i32, + pub bits: i32, +} + +impl WhisperQuantization { + /// What a checkpoint without a `quantization` object gets: MLX's own + /// `nn.quantize` defaults. Inert for a dense checkpoint, which has no + /// `.scales` tensor for the unified layers to pick up. + pub(crate) const DENSE: Self = Self { + group_size: 64, + bits: 4, + }; + + /// The `quantization` object of `config.json`, if it declares one: absent + /// and `null` both mean a dense checkpoint. [`Self::from_config`] reads + /// this block, and [`WhisperModel::load`] keys the bf16 -> f16 policy on + /// it, so the two never disagree about whether a checkpoint is quantized. + fn declared_block(config: &Value) -> Option<&Value> { + config.get("quantization").filter(|q| !q.is_null()) + } + + /// Read the `quantization` object of a (sanitized) `config.json` through + /// the shared [`QuantizationArgs`] spelling of the MLX block. + /// + /// An absent object, or an absent field, falls back to [`Self::DENSE`]. + /// A field that is not an integer that fits in `i32`, or that is out of + /// the range MLX can pack, is an error: the unified layers take the + /// declared group size on trust, so silently substituting a default would + /// dequantize the whole model on the wrong stride instead of failing the + /// load. A declared `mode` must be affine, the only scheme the MLX Whisper + /// converters write; the unified layers would otherwise infer a + /// block-float layout the reference loader never builds for this family. + pub(crate) fn from_config(config: &Value) -> Result { + let Some(quant) = Self::declared_block(config) else { + return Ok(Self::DENSE); + }; + let args: QuantizationArgs = serde_json::from_value(quant.clone()).map_err(|e| { + anyhow!("Whisper config.json `quantization` block {quant} is malformed: {e}") + })?; + let (group_size, bits) = (args.get_group_size(), args.get_bits()); + mlxcel_core::layers::validate_quantization_params(group_size, bits) + .map_err(|e| anyhow!("Whisper {e}"))?; + let mode = args.get_mode().map_err(|e| anyhow!("Whisper {e}"))?; + if mode != "affine" { + return Err(anyhow!( + "Whisper quantization.mode {mode:?} is not supported; MLX Whisper exports are \ + affine (group_size/bits with .scales and .biases)" + )); + } + Ok(Self { group_size, bits }) + } +} + +/// Compute dtype of a loaded Whisper checkpoint: the dtype of the token +/// embedding table, or of its `.scales` plane when the table is packed. +/// +/// The encoder casts the mel spectrogram to this dtype and the decoder builds +/// its causal mask in it. A quantized export stores the table as packed +/// `uint32` words, which would make every activation an integer tensor, so the +/// scales (written in the checkpoint's float dtype, `float16` for every +/// mlx-community conversion) stand in for it. Falls back to `float16`, the +/// dtype the reference transcribes in, when neither tensor is present. +fn checkpoint_dtype(weights: &WeightMap) -> i32 { + let is_float = |dtype: i32| { + dtype == mlxcel_core::dtype::FLOAT16 + || dtype == mlxcel_core::dtype::BFLOAT16 + || dtype == mlxcel_core::dtype::FLOAT32 + }; + [ + "decoder.token_embedding.weight", + "decoder.token_embedding.scales", + ] + .into_iter() + .filter_map(|key| weights.get(key).map(|w| mlxcel_core::array_dtype(w))) + .find(|&dtype| is_float(dtype)) + .unwrap_or(mlxcel_core::dtype::FLOAT16) +} + impl WhisperDims { /// Parse from a (sanitized) `config.json` value, accepting native MLX field /// names or the HuggingFace `WhisperConfig` names. @@ -127,32 +225,33 @@ pub struct WhisperModel { impl WhisperModel { /// Load a Whisper checkpoint directory (config.json + safetensors + - /// tokenizer.json). + /// tokenizer.json, or the openai/whisper `multilingual.tiktoken` / + /// `gpt2.tiktoken` rank file the MLX exports ship instead). pub fn load(model_path: &Path) -> Result { - let config_path = model_path.join("config.json"); - let config_str = std::fs::read_to_string(&config_path) - .map_err(|e| anyhow!("Failed to read {config_path:?}: {e}"))?; - let config_str = super::sanitize_config_json(&config_str); - let config: Value = serde_json::from_str(&config_str) - .map_err(|e| anyhow!("Failed to parse Whisper config: {e}"))?; + let config = read_config(model_path)?; let dims = WhisperDims::from_config(&config)?; + let quant = WhisperQuantization::from_config(&config)?; let mut weights = mlxcel_core::weights::load_weights_from_dir(model_path) .map_err(|e| anyhow!("Failed to load Whisper weights: {e}"))?; sanitize_whisper_weights(&mut weights); // Apple Silicon precision policy: bf16 -> f16 for non-quantized weights. - let _ = super::convert_bf16_weights(&mut weights); + // A quantized export keeps its tensors as written, like the reference + // loader, so its scales and dense tensors stay in one dtype. Only a + // declared MLX `quantization` block counts: `"quantization": null` (or + // a Hugging Face `quantization_config`, which this loader does not + // read) leaves a dense checkpoint on the dense policy, as before. + if WhisperQuantization::declared_block(&config).is_none() { + let _ = super::convert_bf16_weights(&mut weights); + } - let dtype = weights - .get("decoder.token_embedding.weight") - .map(|w| mlxcel_core::array_dtype(w)) - .unwrap_or(mlxcel_core::dtype::FLOAT16); + let dtype = checkpoint_dtype(&weights); - let encoder = AudioEncoder::from_weights(&weights, &dims, dtype) + let encoder = AudioEncoder::from_weights(&weights, &dims, dtype, quant) .map_err(|e| anyhow!("Failed to build Whisper encoder: {e}"))?; - let decoder = TextDecoder::from_weights(&weights, &dims, dtype) + let decoder = TextDecoder::from_weights(&weights, &dims, dtype, quant) .map_err(|e| anyhow!("Failed to build Whisper decoder: {e}"))?; - let tokenizer = WhisperTokenizer::from_dir(model_path)?; + let tokenizer = WhisperTokenizer::from_dir(model_path, dims.n_vocab)?; Ok(Self { dims, @@ -234,6 +333,32 @@ impl WhisperModel { } } +/// Read and parse a Whisper checkpoint's (sanitized) `config.json`. +fn read_config(model_path: &Path) -> Result { + let config_path = model_path.join("config.json"); + let config_str = std::fs::read_to_string(&config_path) + .map_err(|e| anyhow!("Failed to read {config_path:?}: {e}"))?; + let config_str = super::sanitize_config_json(&config_str); + serde_json::from_str(&config_str).map_err(|e| anyhow!("Failed to parse Whisper config: {e}")) +} + +/// The byte-level BPE of a Whisper checkpoint directory that ships the +/// openai/whisper rank file instead of a `tokenizer.json`, sized by the +/// `n_vocab` its `config.json` declares. +/// +/// The server loads a tokenizer from the checkpoint directory before it wires +/// the speech-to-text slot (`/tokenize`, `/detokenize` and the startup +/// missing-tokenizer check read it). The generic `.tiktoken` loader there reads +/// the HunYuan / Kimi K3 rank-file families, refuses the `=` placeholder line +/// of `multilingual.tiktoken`, and would number the Whisper special tokens +/// wrongly even if it did not, so a Whisper directory takes this path instead. +/// +/// Used by: `crate::tokenizer::load_tokenizer` +pub(crate) fn rank_file_tokenizer_for_dir(model_path: &Path) -> Result { + let dims = WhisperDims::from_config(&read_config(model_path)?)?; + tokenizer::rank_file_tokenizer(model_path, dims.n_vocab) +} + /// Pad the waveform with trailing silence (zeros) up to a whole number of 30 s /// windows. /// @@ -343,9 +468,13 @@ fn sanitize_whisper_weights(weights: &mut WeightMap) { *weights = remapped; } +#[cfg(test)] +mod real_tests; + #[cfg(test)] mod tests { use super::*; + use mlxcel_core::UniquePtr; use serde_json::json; #[test] @@ -479,4 +608,373 @@ mod tests { .collect(); assert_eq!(starts, vec![0.0, 30.0, 60.0]); } + + #[test] + fn quantization_defaults_and_reads_the_mlx_block() { + let dense = json!({ "n_vocab": 51865 }); + assert_eq!( + WhisperQuantization::from_config(&dense).unwrap(), + WhisperQuantization::DENSE + ); + assert_eq!( + WhisperQuantization::from_config(&json!({ "quantization": null })).unwrap(), + WhisperQuantization::DENSE + ); + let q4 = json!({ "quantization": { "group_size": 64, "bits": 4 } }); + assert_eq!( + WhisperQuantization::from_config(&q4).unwrap(), + WhisperQuantization { + group_size: 64, + bits: 4 + } + ); + let q8 = json!({ "quantization": { "group_size": 32, "bits": 8, "mode": "affine" } }); + assert_eq!( + WhisperQuantization::from_config(&q8).unwrap(), + WhisperQuantization { + group_size: 32, + bits: 8 + } + ); + // A partial block keeps the default for the missing field. + let bits_only = json!({ "quantization": { "bits": 8 } }); + assert_eq!( + WhisperQuantization::from_config(&bits_only).unwrap(), + WhisperQuantization { + group_size: 64, + bits: 8 + } + ); + // The extremes MLX can still pack are accepted. + let edge = json!({ "quantization": { "group_size": 1, "bits": 32 } }); + assert!(WhisperQuantization::from_config(&edge).is_ok()); + + // Only a declared block marks a quantized export (and so skips the + // bf16 -> f16 conversion): absent, `null` and a Hugging Face + // `quantization_config` keep the dense policy. + assert!(WhisperQuantization::declared_block(&dense).is_none()); + assert!(WhisperQuantization::declared_block(&json!({ "quantization": null })).is_none()); + let hf = json!({ "quantization_config": { "quant_method": "bitsandbytes" } }); + assert!(WhisperQuantization::declared_block(&hf).is_none()); + assert_eq!( + WhisperQuantization::declared_block(&q4), + q4.get("quantization") + ); + assert!(WhisperQuantization::declared_block(&json!({ "quantization": {} })).is_some()); + } + + #[test] + fn quantization_refuses_values_that_would_mis_stride_the_model() { + for (block, want) in [ + (json!({ "group_size": 0, "bits": 4 }), "group_size"), + (json!({ "group_size": 64, "bits": 0 }), "bits"), + (json!({ "group_size": 64, "bits": 33 }), "bits"), + (json!({ "group_size": "64", "bits": 4 }), "malformed"), + (json!({ "group_size": 64, "bits": 4.5 }), "malformed"), + ( + json!({ "group_size": 4294967360i64, "bits": 4 }), + "malformed", + ), + ( + json!({ "group_size": 32, "bits": 4, "mode": "mxfp4" }), + "not supported", + ), + ( + json!({ "group_size": 64, "bits": 4, "mode": "Affine" }), + "mode", + ), + (json!(4), "malformed"), + ] { + let err = WhisperQuantization::from_config(&json!({ "quantization": block })) + .unwrap_err() + .to_string(); + assert!(err.contains(want), "{block}: {err}"); + } + } + + fn tensor(values: &[f32], shape: &[i32], dtype: i32) -> UniquePtr { + mlxcel_core::astype(&mlxcel_core::from_slice_f32(values, shape), dtype) + } + + #[test] + fn checkpoint_dtype_reads_the_scales_of_a_packed_embedding() { + use mlxcel_core::dtype::{BFLOAT16, FLOAT16, FLOAT32, UINT32}; + let mut weights = WeightMap::new(); + assert_eq!(checkpoint_dtype(&weights), FLOAT16); + + weights.insert( + "decoder.token_embedding.weight".into(), + tensor(&[1.0; 4], &[2, 2], FLOAT32), + ); + assert_eq!(checkpoint_dtype(&weights), FLOAT32); + + // Packed table: the uint32 words are not a compute dtype. + weights.insert( + "decoder.token_embedding.weight".into(), + tensor(&[1.0; 4], &[2, 2], UINT32), + ); + assert_eq!(checkpoint_dtype(&weights), FLOAT16); + weights.insert( + "decoder.token_embedding.scales".into(), + tensor(&[1.0; 2], &[2, 1], BFLOAT16), + ); + assert_eq!(checkpoint_dtype(&weights), BFLOAT16); + } + + /// Deterministic values in `[-scale, scale)` from a 64-bit LCG. + fn lcg(n: usize, seed: u64, scale: f32) -> Vec { + let mut state = seed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (0..n) + .map(|_| { + state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + ((state >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * scale + }) + .collect() + } + + /// An evaluated MLX array as a safetensors view. + struct RawTensor { + dtype: safetensors::Dtype, + shape: Vec, + data: Vec, + } + + impl RawTensor { + fn of(arr: &mlxcel_core::MlxArray) -> Self { + mlxcel_core::eval(arr); + let dtype = match mlxcel_core::array_dtype(arr) { + mlxcel_core::dtype::FLOAT16 => safetensors::Dtype::F16, + mlxcel_core::dtype::FLOAT32 => safetensors::Dtype::F32, + mlxcel_core::dtype::UINT32 => safetensors::Dtype::U32, + other => panic!("unexpected dtype {other}"), + }; + Self { + dtype, + shape: mlxcel_core::array_shape(arr) + .iter() + .map(|&d| d as usize) + .collect(), + data: mlxcel_core::array_to_raw_bytes(arr), + } + } + } + + impl safetensors::View for &RawTensor { + fn dtype(&self) -> safetensors::Dtype { + self.dtype + } + fn shape(&self) -> &[usize] { + &self.shape + } + fn data(&self) -> std::borrow::Cow<'_, [u8]> { + self.data.as_slice().into() + } + fn data_len(&self) -> usize { + self.data.len() + } + } + + const TINY_STATE: i32 = 64; + const TINY_N_VOCAB: i32 = 51865; + + /// A one-layer Whisper with random f16 weights, written twice: as an MLX + /// 4-bit export (every projection and the token embedding packed, as + /// `nn.quantize` packs them) and as the dense twin holding exactly the + /// dequantized values. Both directories carry a synthetic + /// `multilingual.tiktoken` and no `tokenizer.json`, like the mlx-community + /// exports. + fn write_tiny_pair(quant_dir: &Path, dense_dir: &Path) { + use mlxcel_core::dtype::FLOAT16; + let s = TINY_STATE; + let mut dense: Vec<(String, UniquePtr)> = Vec::new(); + let mut seed = 1u64; + let mut rand = |shape: &[i32], scale: f32| { + seed += 1; + let n = shape.iter().product::() as usize; + tensor(&lcg(n, seed, scale), shape, FLOAT16) + }; + let mut linears: Vec = Vec::new(); + let mut push_block = |dense: &mut Vec<(String, UniquePtr)>, + prefix: &str, + cross: bool| { + let mut attns = vec!["attn"]; + if cross { + attns.push("cross_attn"); + } + for attn in attns { + for proj in ["query", "key", "value", "out"] { + let name = format!("{prefix}.{attn}.{proj}"); + dense.push((format!("{name}.weight"), rand(&[s, s], 0.2))); + if proj != "key" { + dense.push((format!("{name}.bias"), rand(&[s], 0.05))); + } + linears.push(name); + } + dense.push((format!("{prefix}.{attn}_ln.weight"), rand(&[s], 1.0))); + dense.push((format!("{prefix}.{attn}_ln.bias"), rand(&[s], 0.1))); + } + for (name, shape) in [("mlp1", [4 * s, s]), ("mlp2", [s, 4 * s])] { + dense.push((format!("{prefix}.{name}.weight"), rand(&shape, 0.2))); + dense.push((format!("{prefix}.{name}.bias"), rand(&[shape[0]], 0.05))); + linears.push(format!("{prefix}.{name}")); + } + dense.push((format!("{prefix}.mlp_ln.weight"), rand(&[s], 1.0))); + dense.push((format!("{prefix}.mlp_ln.bias"), rand(&[s], 0.1))); + }; + push_block(&mut dense, "encoder.blocks.0", false); + push_block(&mut dense, "decoder.blocks.0", true); + dense.push(("encoder.conv1.weight".into(), rand(&[s, 3, 80], 0.1))); + dense.push(("encoder.conv1.bias".into(), rand(&[s], 0.05))); + dense.push(("encoder.conv2.weight".into(), rand(&[s, 3, s], 0.1))); + dense.push(("encoder.conv2.bias".into(), rand(&[s], 0.05))); + dense.push(("encoder.ln_post.weight".into(), rand(&[s], 1.0))); + dense.push(("encoder.ln_post.bias".into(), rand(&[s], 0.1))); + dense.push(( + "decoder.token_embedding.weight".into(), + rand(&[TINY_N_VOCAB, s], 0.5), + )); + dense.push(("decoder.positional_embedding".into(), rand(&[16, s], 0.1))); + dense.push(("decoder.ln.weight".into(), rand(&[s], 1.0))); + dense.push(("decoder.ln.bias".into(), rand(&[s], 0.1))); + linears.push("decoder.token_embedding".into()); + + let (group_size, bits) = (64, 4); + let mut quant: Vec<(String, UniquePtr)> = Vec::new(); + let mut twin: Vec<(String, UniquePtr)> = Vec::new(); + for (key, value) in dense { + let Some(prefix) = key + .strip_suffix(".weight") + .filter(|p| linears.iter().any(|l| l == p)) + else { + twin.push((key.clone(), mlxcel_core::copy(&value))); + quant.push((key, value)); + continue; + }; + let q = mlxcel_core::quantize_weights(&value, group_size, bits); + let (w, scales, biases) = ( + mlxcel_core::quantized_weights_w(&q), + mlxcel_core::quantized_weights_scales(&q), + mlxcel_core::quantized_weights_biases(&q), + ); + // SAFETY: `biases` outlives the call. + let deq = unsafe { + mlxcel_core::dequantize( + &w, + &scales, + biases.as_ref().unwrap() as *const _, + group_size, + bits, + "affine", + ) + }; + twin.push((key.clone(), mlxcel_core::astype(&deq, FLOAT16))); + quant.push((format!("{prefix}.scales"), scales)); + quant.push((format!("{prefix}.biases"), biases)); + quant.push((key, w)); + } + + let dims = json!({ + "n_mels": 80, "n_audio_ctx": 8, "n_audio_state": s, "n_audio_head": 2, + "n_audio_layer": 1, "n_vocab": TINY_N_VOCAB, "n_text_ctx": 16, "n_text_state": s, + "n_text_head": 2, "n_text_layer": 1, "model_type": "whisper" + }); + for (dir, tensors, quantized) in [(quant_dir, &quant, true), (dense_dir, &twin, false)] { + let mut config = dims.clone(); + if quantized { + config["quantization"] = json!({ "group_size": group_size, "bits": bits }); + } + std::fs::write(dir.join("config.json"), config.to_string()).unwrap(); + let raw: Vec<(String, RawTensor)> = tensors + .iter() + .map(|(k, v)| (k.clone(), RawTensor::of(v))) + .collect(); + let views: Vec<(&str, &RawTensor)> = raw.iter().map(|(k, v)| (k.as_str(), v)).collect(); + safetensors::serialize_to_file(views, None, &dir.join("model.safetensors")).unwrap(); + tokenizer::tests::write_rank_file(dir, "multilingual.tiktoken", 50257); + } + } + + /// Logits `[seq, n_vocab]` (f32) of the decoder over `tokens` for one mel. + fn tiny_logits(model: &WhisperModel, mel: &mlxcel_core::MlxArray, tokens: &[i32]) -> Vec { + let features = model.encoder.forward(mel); + let toks = mlxcel_core::from_slice_i32(tokens, &[1, tokens.len() as i32]); + let n = model.decoder.num_layers(); + let mut self_caches: Vec> = (0..n).map(|_| None).collect(); + let mut cross_caches: Vec> = (0..n).map(|_| None).collect(); + let logits = + model + .decoder + .forward(&toks, &features, 0, &mut self_caches, &mut cross_caches); + let logits = mlxcel_core::astype(&logits, mlxcel_core::dtype::FLOAT32); + mlxcel_core::eval(&logits); + mlxcel_core::array_to_raw_bytes(&logits) + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect() + } + + #[test] + fn quantized_mlx_export_loads_and_matches_its_dequantized_twin() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let quant_dir = tempfile::tempdir().unwrap(); + let dense_dir = tempfile::tempdir().unwrap(); + write_tiny_pair(quant_dir.path(), dense_dir.path()); + + // No tokenizer.json in either directory: the rank file is the tokenizer. + let quant = WhisperModel::load(quant_dir.path()).expect("load the 4-bit export"); + let dense = WhisperModel::load(dense_dir.path()).expect("load the dense twin"); + assert_eq!(quant.dtype, mlxcel_core::dtype::FLOAT16); + assert_eq!(dense.dtype, mlxcel_core::dtype::FLOAT16); + assert_eq!(quant.tokenizer.sot, 50258); + assert!(quant.tokenizer.multilingual); + + let mel = tensor( + &lcg(16 * 80, 99, 1.0), + &[1, 16, 80], + mlxcel_core::dtype::FLOAT16, + ); + let tokens = quant.tokenizer.initial_tokens(Some("en"), false); + assert_eq!(tokens, vec![50258, 50259, 50359, 50363]); + let q = tiny_logits(&quant, &mel, &tokens); + let d = tiny_logits(&dense, &mel, &tokens); + assert_eq!(q.len(), tokens.len() * TINY_N_VOCAB as usize); + assert!(q.iter().all(|v| v.is_finite())); + + // The packed matmuls and the dense ones over the same dequantized + // values differ only in f16 accumulation order. + let scale = d.iter().fold(0f32, |m, v| m.max(v.abs())); + let max_diff = q + .iter() + .zip(&d) + .fold(0f32, |m, (a, b)| m.max((a - b).abs())); + assert!(scale > 1.0, "degenerate logits: max |logit| {scale}"); + assert!( + max_diff <= 0.02 * scale, + "4-bit logits drift from the dequantized twin: max diff {max_diff} vs max |logit| {scale}" + ); + for (pos, (qr, dr)) in q + .chunks_exact(TINY_N_VOCAB as usize) + .zip(d.chunks_exact(TINY_N_VOCAB as usize)) + .enumerate() + { + let argmax = |row: &[f32]| { + row.iter() + .enumerate() + .fold( + (0, f32::NEG_INFINITY), + |b, (i, &v)| if v > b.1 { (i, v) } else { b }, + ) + .0 + }; + assert_eq!( + argmax(qr), + argmax(dr), + "position {pos}: greedy pick differs" + ); + } + } } diff --git a/src/models/whisper/real_tests.rs b/src/models/whisper/real_tests.rs new file mode 100644 index 0000000000..21fd22769c --- /dev/null +++ b/src/models/whisper/real_tests.rs @@ -0,0 +1,295 @@ +// Copyright 2025-2026 Lablup Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Real-checkpoint parity against mlx-whisper, ignored by default. +//! +//! `scripts/whisper_mlx_reference.py` writes the reference for one checkpoint +//! and one clip. Point the tests at both: +//! +//! ```text +//! MLXCEL_TEST_WHISPER_DIR= \ +//! MLXCEL_TEST_WHISPER_REFERENCE= \ +//! MLXCEL_TEST_WHISPER_TOKENIZER_REFERENCE= \ +//! cargo test --lib models::whisper::real_tests -- --ignored --nocapture +//! ``` +//! +//! `MLXCEL_TEST_WHISPER_HF_TOKENIZER` may name an openai/whisper +//! `tokenizer.json` to compare the vocabulary built from the rank file against, +//! id by id. + +use std::collections::HashMap; +use std::path::PathBuf; + +use super::WhisperModel; +use super::decoding::transcribe_segment; +use super::layers::KvCache; +use super::tokenizer::{is_multilingual_vocab, tokenizer_from_tiktoken}; + +fn env_path(name: &str) -> Option { + std::env::var_os(name) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) +} + +/// The tensors and metadata `scripts/whisper_mlx_reference.py` writes. +struct Reference { + audio: Vec, + mel: Vec, + mel_shape: Vec, + tokens: Vec, + prompt_len: usize, + logits: Vec, + text: String, + language: String, +} + +fn read_reference(path: &PathBuf) -> Reference { + let bytes = std::fs::read(path).expect("read the reference"); + let (_, header) = safetensors::SafeTensors::read_metadata(&bytes).expect("reference header"); + let meta = header.metadata().clone().unwrap_or_default(); + let file = safetensors::SafeTensors::deserialize(&bytes).expect("reference tensors"); + let f32s = |name: &str| -> (Vec, Vec) { + let t = file + .tensor(name) + .unwrap_or_else(|_| panic!("reference has no {name}")); + assert_eq!(t.dtype(), safetensors::Dtype::F32, "{name}"); + let values = t + .data() + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(); + (values, t.shape().iter().map(|&d| d as i32).collect()) + }; + let i32s = |name: &str| -> Vec { + let t = file + .tensor(name) + .unwrap_or_else(|_| panic!("reference has no {name}")); + assert_eq!(t.dtype(), safetensors::Dtype::I32, "{name}"); + t.data() + .chunks_exact(4) + .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect() + }; + let (audio, _) = f32s("audio"); + let (mel, mel_shape) = f32s("mel"); + let (logits, _) = f32s("logits"); + Reference { + audio, + mel, + mel_shape, + tokens: i32s("tokens"), + prompt_len: i32s("prompt_len")[0] as usize, + logits, + text: meta.get("text").cloned().unwrap_or_default(), + language: meta.get("language").cloned().unwrap_or_default(), + } +} + +fn host_f32(arr: &mlxcel_core::MlxArray) -> Vec { + let arr = mlxcel_core::astype(arr, mlxcel_core::dtype::FLOAT32); + mlxcel_core::eval(&arr); + mlxcel_core::array_to_raw_bytes(&arr) + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect() +} + +/// Index and value of the largest entry, and the gap to the runner-up. +fn top2(row: &[f32]) -> (usize, f32) { + let (mut best, mut first, mut second) = (0, f32::NEG_INFINITY, f32::NEG_INFINITY); + for (i, &v) in row.iter().enumerate() { + if v > first { + (best, second, first) = (i, first, v); + } else if v > second { + second = v; + } + } + (best, first - second) +} + +/// Greedy tokens, detected language and decoded text equal mlx-whisper's on +/// the same mel window, the teacher-forced logits agree on every decided +/// position, and transcribing the clip through mlxcel's own front end gives +/// the same text. +#[test] +#[ignore = "needs MLXCEL_TEST_WHISPER_DIR and MLXCEL_TEST_WHISPER_REFERENCE"] +fn greedy_decode_and_logits_match_mlx_whisper() { + let _guard = crate::models::embedding_test_support::mlx_test_guard(); + let (Some(dir), Some(reference)) = ( + env_path("MLXCEL_TEST_WHISPER_DIR"), + env_path("MLXCEL_TEST_WHISPER_REFERENCE"), + ) else { + eprintln!("skipping: MLXCEL_TEST_WHISPER_DIR / MLXCEL_TEST_WHISPER_REFERENCE unset"); + return; + }; + let model = WhisperModel::load(&dir).expect("load the checkpoint"); + let r = read_reference(&reference); + let n_vocab = model.dims.n_vocab; + + let mel = mlxcel_core::from_slice_f32(&r.mel, &r.mel_shape); + let mel = mlxcel_core::astype(&mel, model.dtype); + let features = model.encoder.forward(&mel); + + let (generated, language) = transcribe_segment( + &model.decoder, + &features, + &model.tokenizer, + n_vocab, + model.dims.n_text_ctx, + None, + false, + ) + .expect("greedy decode"); + let want = &r.tokens[r.prompt_len..]; + eprintln!( + "greedy: {} tokens (reference {}), language {language:?} (reference {:?})", + generated.len(), + want.len(), + r.language + ); + assert_eq!(generated, want, "greedy tokens differ from mlx-whisper"); + if is_multilingual_vocab(n_vocab) { + assert_eq!(language.as_deref(), Some(r.language.as_str())); + } else { + assert_eq!(language, None, "an English-only model detects no language"); + } + let prompt = model.tokenizer.initial_tokens(language.as_deref(), false); + assert_eq!(prompt, &r.tokens[..r.prompt_len], "decoder prompt differs"); + let text = model.tokenizer.decode_text(&generated); + eprintln!("text: {text:?}"); + assert_eq!(text, r.text, "decoded text differs from mlx-whisper"); + + // Teacher-forced logits over the reference prompt + tokens. + let n = model.decoder.num_layers(); + let mut self_caches: Vec> = (0..n).map(|_| None).collect(); + let mut cross_caches: Vec> = (0..n).map(|_| None).collect(); + let tokens = mlxcel_core::from_slice_i32(&r.tokens, &[1, r.tokens.len() as i32]); + let logits = model + .decoder + .forward(&tokens, &features, 0, &mut self_caches, &mut cross_caches); + let ours = host_f32(&logits); + assert_eq!(ours.len(), r.logits.len(), "logit shape differs"); + let width = n_vocab as usize; + let (mut max_diff, mut sum_diff, mut decided, mut agree) = (0f32, 0f64, 0, 0); + for (pos, (a, b)) in ours + .chunks_exact(width) + .zip(r.logits.chunks_exact(width)) + .enumerate() + { + let diff = a.iter().zip(b).fold(0f32, |m, (x, y)| m.max((x - y).abs())); + sum_diff += f64::from(diff); + max_diff = max_diff.max(diff); + let ((ia, _), (ib, gap)) = (top2(a), top2(b)); + if pos + 1 >= r.prompt_len && gap > 0.5 { + decided += 1; + agree += usize::from(ia == ib); + assert_eq!( + ia, ib, + "position {pos}: argmax differs (reference gap {gap})" + ); + } + } + let positions = r.tokens.len(); + eprintln!( + "logits over {positions} positions: max |diff| {max_diff:.4}, mean per-position max \ + {:.4}; argmax agrees on {agree}/{decided} decided positions", + sum_diff / positions as f64 + ); + + // The whole clip through mlxcel's own log-mel front end. + let transcript = model + .transcribe(&r.audio, None, false) + .expect("transcribe the clip"); + eprintln!("transcribe: {:?}", transcript.text); + assert_eq!( + transcript.text.trim(), + r.text.trim(), + "end-to-end text differs" + ); +} + +/// The tokenizer built from the checkpoint's rank file numbers every special +/// token and encodes a multilingual corpus exactly as tiktoken does, and, when +/// an openai/whisper `tokenizer.json` is given, spells every id the same. +#[test] +#[ignore = "needs MLXCEL_TEST_WHISPER_DIR and MLXCEL_TEST_WHISPER_TOKENIZER_REFERENCE"] +fn tiktoken_vocab_matches_tiktoken() { + let (Some(dir), Some(reference)) = ( + env_path("MLXCEL_TEST_WHISPER_DIR"), + env_path("MLXCEL_TEST_WHISPER_TOKENIZER_REFERENCE"), + ) else { + eprintln!( + "skipping: MLXCEL_TEST_WHISPER_DIR / MLXCEL_TEST_WHISPER_TOKENIZER_REFERENCE unset" + ); + return; + }; + let r: serde_json::Value = + serde_json::from_slice(&std::fs::read(&reference).expect("read")).expect("json"); + let n_vocab = r["n_vocab"].as_i64().expect("n_vocab") as i32; + let name = if is_multilingual_vocab(n_vocab) { + "multilingual.tiktoken" + } else { + "gpt2.tiktoken" + }; + let started = std::time::Instant::now(); + let tok = tokenizer_from_tiktoken(&dir.join(name), n_vocab).expect("build the tokenizer"); + eprintln!("built from {name} in {:?}", started.elapsed()); + assert_eq!( + tok.get_vocab_size(true) as i64, + r["n_vocab_encoding"].as_i64().unwrap() + ); + + let special: HashMap = + serde_json::from_value(r["special"].clone()).expect("special map"); + for (token, &id) in &special { + assert_eq!(tok.token_to_id(token), Some(id), "{token}"); + } + let texts = r["texts"].as_array().unwrap(); + let ids = r["ids"].as_array().unwrap(); + for (text, want) in texts.iter().zip(ids) { + let text = text.as_str().unwrap(); + let want: Vec = serde_json::from_value(want.clone()).unwrap(); + let got = tok.encode(text, false).unwrap().get_ids().to_vec(); + assert_eq!(got, want, "encode {text:?}"); + assert_eq!(tok.decode(&got, false).unwrap(), text, "decode {text:?}"); + } + eprintln!( + "{} specials and {} corpus strings match tiktoken", + special.len(), + texts.len() + ); + + if let Some(hf) = env_path("MLXCEL_TEST_WHISPER_HF_TOKENIZER") { + let hf = tokenizers::Tokenizer::from_file(&hf).expect("load the HF tokenizer.json"); + let mut differing = Vec::new(); + for id in 0..n_vocab as u32 { + let (a, b) = (tok.id_to_token(id), hf.id_to_token(id)); + if a != b { + differing.push((id, a, b)); + } + } + eprintln!("ids spelled differently from tokenizer.json: {differing:?}"); + // openai/whisper renamed `<|nocaptions|>` to `<|nospeech|>`, and the + // English-only Hugging Face files still spell Hebrew with the old + // `iw` code; both predate the rank-file numbering they share. Nothing + // else may differ. + let renamed = [("<|nospeech|>", "<|nocaptions|>"), ("<|he|>", "<|iw|>")]; + assert!( + differing.iter().all(|(_, a, b)| renamed + .iter() + .any(|(x, y)| a.as_deref() == Some(*x) && b.as_deref() == Some(*y))), + "{differing:?}" + ); + } +} diff --git a/src/models/whisper/tokenizer.rs b/src/models/whisper/tokenizer.rs index dd6effdf34..9165a94482 100644 --- a/src/models/whisper/tokenizer.rs +++ b/src/models/whisper/tokenizer.rs @@ -18,12 +18,17 @@ //! //! The byte-level BPE itself is loaded from the checkpoint's `tokenizer.json`; //! this module resolves the special token ids on top of it and precomputes the -//! suppression sets. +//! suppression sets. MLX exports that ship no `tokenizer.json` carry the +//! openai/whisper rank file instead (`multilingual.tiktoken`, or `gpt2.tiktoken` +//! for the English-only models); [`tokenizer_from_tiktoken`] builds the same +//! byte-level BPE from it, with the special tokens numbered the way +//! openai/whisper's `get_encoding` numbers them. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashMap}; use std::path::Path; use anyhow::{Result, anyhow}; +use base64::Engine; use tokenizers::Tokenizer; /// Language codes in their canonical Whisper order. The id of `<|{code}|>` is @@ -39,6 +44,26 @@ pub(crate) const LANGUAGES: &[&str] = &[ "ha", "ba", "jw", "su", "yue", ]; +/// Smallest `n_vocab` of a multilingual checkpoint. The reference reads the +/// language capability off the vocabulary size (`Whisper.is_multilingual`: +/// `n_vocab >= 51865`): the English-only models have 51864 ids and the +/// multilingual ones 51865 (v1/v2) or 51866 (v3, which adds `<|yue|>`). +pub(crate) const MULTILINGUAL_MIN_N_VOCAB: i32 = 51865; + +/// `n_vocab - num_languages - is_multilingual` for every Whisper checkpoint +/// (the reference `Whisper.num_languages`): the BPE ranks plus every special +/// token except the language tags. +const N_VOCAB_WITHOUT_LANGUAGES: i32 = 51765; + +/// Number of `<|t.tt|>` timestamp tokens, 0.00 to 30.00 in 0.02 s steps. +const TIMESTAMP_TOKENS: usize = 1501; + +/// Whether a checkpoint with this `n_vocab` is multilingual, as the reference +/// decides it. +pub(crate) fn is_multilingual_vocab(n_vocab: i32) -> bool { + n_vocab >= MULTILINGUAL_MIN_N_VOCAB +} + /// Special-token ids and suppression sets resolved against a checkpoint's BPE. pub(crate) struct WhisperTokenizer { tokenizer: Tokenizer, @@ -57,7 +82,11 @@ pub(crate) struct WhisperTokenizer { /// First token produced by encoding a single space (suppressed on the first /// generated step). `None` if it could not be resolved. pub blank: Option, - /// True when the checkpoint carries language tags (multilingual model). + /// True for a multilingual model: its vocabulary is multilingual-sized + /// ([`is_multilingual_vocab`]) and the tokenizer carries language tags. An + /// English-only model's tokenizer still numbers the language tags (they + /// sit below the timestamp tokens in every Whisper vocabulary), but the + /// model was never trained on them, so it gets no language or task token. pub multilingual: bool, /// Resolved `(code, id)` pairs for every available language tag. pub language_ids: Vec<(&'static str, i32)>, @@ -68,16 +97,24 @@ pub(crate) struct WhisperTokenizer { impl WhisperTokenizer { /// Load the byte-level BPE from `/tokenizer.json` and resolve the - /// Whisper special tokens on top of it. - pub(crate) fn from_dir(model_path: &Path) -> Result { + /// Whisper special tokens on top of it. A directory without + /// `tokenizer.json` falls back to the openai/whisper rank file the MLX + /// exports ship: `multilingual.tiktoken` for a multilingual `n_vocab`, + /// `gpt2.tiktoken` for an English-only one. + pub(crate) fn from_dir(model_path: &Path, n_vocab: i32) -> Result { let path = model_path.join("tokenizer.json"); - let tokenizer = Tokenizer::from_file(&path) - .map_err(|e| anyhow!("Failed to load Whisper tokenizer from {path:?}: {e}"))?; - Self::from_tokenizer(tokenizer) + let tokenizer = if path.exists() { + Tokenizer::from_file(&path) + .map_err(|e| anyhow!("Failed to load Whisper tokenizer from {path:?}: {e}"))? + } else { + rank_file_tokenizer(model_path, n_vocab)? + }; + Self::from_tokenizer(tokenizer, n_vocab) } - /// Resolve the special tokens against an already-built tokenizer. - pub(crate) fn from_tokenizer(tokenizer: Tokenizer) -> Result { + /// Resolve the special tokens against an already-built tokenizer for a + /// model with `n_vocab` output ids. + pub(crate) fn from_tokenizer(tokenizer: Tokenizer, n_vocab: i32) -> Result { let tid = |s: &str| tokenizer.token_to_id(s).map(|v| v as i32); let sot = tid("<|startoftranscript|>") @@ -96,7 +133,7 @@ impl WhisperTokenizer { .iter() .filter_map(|&code| tid(&format!("<|{code}|>")).map(|id| (code, id))) .collect(); - let multilingual = !language_ids.is_empty(); + let multilingual = is_multilingual_vocab(n_vocab) && !language_ids.is_empty(); let blank = encode_first(&tokenizer, " "); let non_speech = non_speech_tokens(&tokenizer); @@ -166,6 +203,304 @@ impl WhisperTokenizer { } } +/// The byte-level BPE of a checkpoint directory that ships the openai/whisper +/// rank file its `n_vocab` needs (`multilingual.tiktoken` or `gpt2.tiktoken`) +/// instead of a `tokenizer.json`. +/// +/// Used by: [`WhisperTokenizer::from_dir`] and, through +/// `crate::models::whisper::rank_file_tokenizer_for_dir`, the server's +/// chat-front tokenizer (`crate::tokenizer::load_tokenizer`). +pub(crate) fn rank_file_tokenizer(model_path: &Path, n_vocab: i32) -> Result { + let name = tiktoken_file_name(n_vocab); + let tiktoken = model_path.join(name); + if !tiktoken.exists() { + return Err(anyhow!( + "Whisper checkpoint {model_path:?} has no tokenizer: expected tokenizer.json or the \ + openai/whisper {name} rank file" + )); + } + tokenizer_from_tiktoken(&tiktoken, n_vocab) +} + +/// Rank file an MLX export ships for a model with `n_vocab` output ids. +fn tiktoken_file_name(n_vocab: i32) -> &'static str { + if is_multilingual_vocab(n_vocab) { + "multilingual.tiktoken" + } else { + "gpt2.tiktoken" + } +} + +/// The Whisper special tokens in id order, numbered from the first id after +/// the BPE ranks. Mirrors openai/whisper's `get_encoding`: end-of-text and +/// start-of-transcript, the first `num_languages` language tags, the task and +/// control tokens, then the 1501 timestamps. +fn whisper_special_tokens(num_languages: usize) -> Vec { + let mut specials = Vec::with_capacity(2 + num_languages + 6 + TIMESTAMP_TOKENS); + specials.push("<|endoftext|>".to_string()); + specials.push("<|startoftranscript|>".to_string()); + specials.extend( + LANGUAGES[..num_languages] + .iter() + .map(|code| format!("<|{code}|>")), + ); + for token in [ + "<|translate|>", + "<|transcribe|>", + "<|startoflm|>", + "<|startofprev|>", + "<|nospeech|>", + "<|notimestamps|>", + ] { + specials.push(token.to_string()); + } + // Same `f"<|{i * 0.02:.2f}|>"` as the reference: both format the f64 + // product exactly, so the spellings agree. + specials.extend((0..TIMESTAMP_TOKENS).map(|i| format!("<|{:.2}|>", i as f64 * 0.02))); + specials +} + +/// GPT-2's reversible byte-to-character table: printable bytes map to +/// themselves and the rest to code points from U+0100 up, which is the alphabet +/// a byte-level BPE vocabulary is spelled in. +fn byte_level_alphabet() -> [char; 256] { + let mut table = ['\0'; 256]; + let mut next = 256u32; + for byte in 0..=255u8 { + let printable = matches!(byte, b'!'..=b'~' | 0xA1..=0xAC | 0xAE..=0xFF); + let code = if printable { + u32::from(byte) + } else { + let code = next; + next += 1; + code + }; + table[usize::from(byte)] = char::from_u32(code).expect("code point below U+0200"); + } + table +} + +/// Parse an openai/whisper `.tiktoken` rank file (` ` per +/// line) into the token bytes indexed by rank. +/// +/// The ranks must be exactly `0..n` with no token repeated: they are the token +/// ids, and the special tokens are numbered from `n`, so a gap or a duplicate +/// would shift every id after it. +/// +/// `multilingual.tiktoken` ends with `= 50256`: a bare padding character that +/// Python's lenient `base64.b64decode` reads as the empty byte string. It holds +/// GPT-2's old `<|endoftext|>` id so that the Whisper special tokens start at +/// 50257, and the Hugging Face `tokenizer.json` of the same models spells id +/// 50256 as the empty string too. A token of nothing but `=` is therefore the +/// empty token here; strict base64 rejects it. +/// +/// `max_ranks` is how many ranks the model's `n_vocab` leaves before its +/// special tokens. A rank at or above it is refused before the table grows, +/// so a corrupt or hostile line such as `YQ== 99999999999` (or a rank of +/// `usize::MAX`) cannot size an allocation or overflow `rank + 1`; the table +/// never holds more than `max_ranks` entries. +fn parse_tiktoken_ranks(path: &Path, max_ranks: usize) -> Result>> { + let content = std::fs::read_to_string(path) + .map_err(|e| anyhow!("Failed to read Whisper tokenizer {path:?}: {e}"))?; + let mut by_rank: Vec>> = Vec::new(); + let mut seen: HashMap, usize> = HashMap::new(); + for (line_no, line) in content.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let bad = |what: &str| anyhow!("{path:?} line {}: {what}", line_no + 1); + let mut parts = line.split_whitespace(); + let (Some(token), Some(rank), None) = (parts.next(), parts.next(), parts.next()) else { + return Err(bad("expected ` `")); + }; + let bytes = if token.bytes().all(|b| b == b'=') { + Vec::new() + } else { + base64::engine::general_purpose::STANDARD + .decode(token) + .map_err(|e| bad(&format!("invalid base64 token: {e}")))? + }; + let rank: usize = rank + .parse() + .map_err(|e| bad(&format!("invalid rank {rank:?}: {e}")))?; + if rank >= max_ranks { + return Err(bad(&format!( + "rank {rank} is out of range: n_vocab leaves room for {max_ranks} ranks \ + (0..={}) before the special tokens", + max_ranks.saturating_sub(1) + ))); + } + if rank >= by_rank.len() { + by_rank.resize(rank + 1, None); + } + if by_rank[rank].is_some() { + return Err(bad(&format!("rank {rank} appears twice"))); + } + if let Some(previous) = seen.insert(bytes.clone(), rank) { + return Err(bad(&format!( + "token already has rank {previous}, cannot also have rank {rank}" + ))); + } + by_rank[rank] = Some(bytes); + } + if by_rank.is_empty() { + return Err(anyhow!("{path:?} has no BPE ranks")); + } + by_rank + .into_iter() + .enumerate() + .map(|(rank, bytes)| bytes.ok_or_else(|| anyhow!("{path:?} has no token for rank {rank}"))) + .collect() +} + +/// Build the byte-level BPE tokenizer of an openai/whisper `.tiktoken` rank +/// file for a model with `n_vocab` output ids. +/// +/// The vocabulary is the rank table spelled in the GPT-2 byte alphabet, and +/// the merges are recovered from the ranks the way Hugging Face converts a +/// tiktoken encoding (`TikTokenConverter`): every split of a token into two +/// shorter tokens is a merge, ordered by the rank of the merged token, so the +/// lowest-rank pair merges first as in tiktoken's own BPE loop. `ignore_merges` +/// takes a whole pre-tokenized piece straight from the vocabulary, as tiktoken +/// does. The pre-tokenizer is the byte-level GPT-2 split, which is the +/// `pat_str` of openai/whisper's `get_encoding`. Recovering the merges costs one +/// hash lookup per split point, `O(sum of token lengths squared)` over about +/// 50k short tokens. +/// +/// The special tokens follow at `n_ranks..`, in [`whisper_special_tokens`] +/// order, with `num_languages = n_vocab - 51765 - is_multilingual` language +/// tags. The total must equal `n_vocab`; a rank file that belongs to a +/// different vocabulary is refused rather than left to shift every special id. +pub(crate) fn tokenizer_from_tiktoken(path: &Path, n_vocab: i32) -> Result { + let multilingual = is_multilingual_vocab(n_vocab); + let num_languages = n_vocab - N_VOCAB_WITHOUT_LANGUAGES - i32::from(multilingual); + let num_languages = usize::try_from(num_languages) + .ok() + .filter(|n| (1..=LANGUAGES.len()).contains(n)) + .ok_or_else(|| { + anyhow!( + "Whisper n_vocab {n_vocab} implies {num_languages} language tokens; a Whisper \ + vocabulary has 1 to {} (n_vocab {} to {})", + LANGUAGES.len(), + N_VOCAB_WITHOUT_LANGUAGES + 1, + N_VOCAB_WITHOUT_LANGUAGES + LANGUAGES.len() as i32 + 1 + ) + })?; + + let specials = whisper_special_tokens(num_languages); + // n_vocab is at least 51766 here and the specials number about 1.6k, so + // the subtraction cannot underflow; checked anyway. + let max_ranks = usize::try_from(n_vocab) + .ok() + .and_then(|n| n.checked_sub(specials.len())) + .ok_or_else(|| { + anyhow!( + "Whisper n_vocab {n_vocab} has no room for its {} special tokens", + specials.len() + ) + })?; + let ranks = parse_tiktoken_ranks(path, max_ranks)?; + let total = ranks.len() + specials.len(); + if i64::try_from(total).ok() != Some(i64::from(n_vocab)) { + return Err(anyhow!( + "{path:?} has {} BPE ranks; with the {} Whisper special tokens that is {total} ids, \ + but config.json declares n_vocab {n_vocab}", + ranks.len(), + specials.len() + )); + } + + byte_level_bpe_from_ranks(&ranks, &specials) + .map_err(|e| anyhow!("Failed to build the Whisper tokenizer from {path:?}: {e}")) +} + +/// Assemble a byte-level BPE `Tokenizer` from a tiktoken rank table (token +/// bytes indexed by rank) plus `specials`, which take the ids after the last +/// rank in order. See [`tokenizer_from_tiktoken`] for how the merges are +/// recovered. +fn byte_level_bpe_from_ranks(ranks: &[Vec], specials: &[String]) -> Result { + let alphabet = byte_level_alphabet(); + let spell = + |bytes: &[u8]| -> String { bytes.iter().map(|&b| alphabet[usize::from(b)]).collect() }; + let rank_of: HashMap<&[u8], usize> = ranks + .iter() + .enumerate() + .map(|(rank, bytes)| (bytes.as_slice(), rank)) + .collect(); + + let mut vocab = serde_json::Map::with_capacity(ranks.len()); + // (merged rank, left rank, right rank): sorting the tuples orders the + // merges by the merged token's rank, then by the halves' ranks, which is + // the order `TikTokenConverter` emits. + let mut merges: Vec<(usize, usize, usize)> = Vec::new(); + for (rank, bytes) in ranks.iter().enumerate() { + vocab.insert(spell(bytes), serde_json::Value::from(rank)); + for split in 1..bytes.len() { + let (left, right) = bytes.split_at(split); + if let (Some(&l), Some(&r)) = (rank_of.get(left), rank_of.get(right)) { + merges.push((rank, l, r)); + } + } + } + merges.sort_unstable(); + let merges: Vec = merges + .into_iter() + .map(|(_, l, r)| serde_json::json!([spell(&ranks[l]), spell(&ranks[r])])) + .collect(); + + let added_tokens: Vec = specials + .iter() + .enumerate() + .map(|(i, content)| { + serde_json::json!({ + "id": ranks.len() + i, + "content": content, + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true, + }) + }) + .collect(); + + let spec = serde_json::json!({ + "version": "1.0", + "truncation": null, + "padding": null, + "added_tokens": added_tokens, + "normalizer": null, + "pre_tokenizer": { + "type": "ByteLevel", + "add_prefix_space": false, + "trim_offsets": true, + "use_regex": true, + }, + "post_processor": null, + "decoder": { + "type": "ByteLevel", + "add_prefix_space": true, + "trim_offsets": true, + "use_regex": true, + }, + "model": { + "type": "BPE", + "dropout": null, + "unk_token": null, + "continuing_subword_prefix": null, + "end_of_word_suffix": null, + "fuse_unk": false, + "byte_fallback": false, + "ignore_merges": true, + "vocab": vocab, + "merges": merges, + }, + }); + let bytes = serde_json::to_vec(&spec).map_err(|e| anyhow!("{e}"))?; + Tokenizer::from_bytes(bytes).map_err(|e| anyhow!("{e}")) +} + /// Encode `text` and return its first token id (used for the blank/space token). fn encode_first(tokenizer: &Tokenizer, text: &str) -> Option { tokenizer @@ -274,7 +609,7 @@ fn build_suppress_set( } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::*; /// Build a synthetic tokenizer that carries the Whisper special tokens as @@ -341,7 +676,7 @@ mod tests { let en = want("<|en|>").unwrap(); let ko = want("<|ko|>").unwrap(); - let tok = WhisperTokenizer::from_tokenizer(raw).expect("resolve"); + let tok = WhisperTokenizer::from_tokenizer(raw, MULTILINGUAL_MIN_N_VOCAB).expect("resolve"); assert_eq!(tok.sot, sot); assert_eq!(tok.eot, eot); assert_eq!(tok.transcribe, transcribe); @@ -367,7 +702,7 @@ mod tests { id("<|translate|>"), id("<|notimestamps|>"), ); - let tok = WhisperTokenizer::from_tokenizer(raw).expect("resolve"); + let tok = WhisperTokenizer::from_tokenizer(raw, MULTILINGUAL_MIN_N_VOCAB).expect("resolve"); // transcribe, Korean hint assert_eq!( tok.initial_tokens(Some("ko"), false), @@ -386,7 +721,7 @@ mod tests { fn suppress_set_includes_task_and_start_tokens() { let raw = synthetic_tokenizer(); let translate = raw.token_to_id("<|translate|>").unwrap() as i32; - let tok = WhisperTokenizer::from_tokenizer(raw).expect("resolve"); + let tok = WhisperTokenizer::from_tokenizer(raw, MULTILINGUAL_MIN_N_VOCAB).expect("resolve"); assert!(tok.suppress.contains(&tok.sot)); assert!(tok.suppress.contains(&tok.transcribe)); assert!(tok.suppress.contains(&translate)); @@ -405,7 +740,8 @@ mod tests { #[test] fn decode_text_drops_special_and_timestamp_tokens() { - let tok = WhisperTokenizer::from_tokenizer(synthetic_tokenizer()).expect("resolve"); + let tok = WhisperTokenizer::from_tokenizer(synthetic_tokenizer(), MULTILINGUAL_MIN_N_VOCAB) + .expect("resolve"); // Mix text tokens (ids below eot: "a"=0, "b"=2) with specials/timestamps. let ids = vec![ tok.sot, @@ -421,4 +757,382 @@ mod tests { "special tokens must not survive decode: {text:?}" ); } + + #[test] + fn multilingual_follows_the_model_vocab_like_the_reference() { + // Every Whisper vocabulary numbers the language tags, the English-only + // one included, so the tags alone cannot tell the two apart. The + // reference reads it off `n_vocab` (`>= 51865`); one id below the + // boundary is an English-only model and gets no language or task + // token in its prompt. + let id = |s: &str| synthetic_tokenizer().token_to_id(s).unwrap() as i32; + let (sot, en, tr, nts) = ( + id("<|startoftranscript|>"), + id("<|en|>"), + id("<|transcribe|>"), + id("<|notimestamps|>"), + ); + let english = + WhisperTokenizer::from_tokenizer(synthetic_tokenizer(), MULTILINGUAL_MIN_N_VOCAB - 1) + .expect("resolve"); + assert!(!english.multilingual); + assert_eq!(english.initial_tokens(Some("ko"), false), vec![sot, nts]); + assert_eq!(english.initial_tokens(None, true), vec![sot, nts]); + + let multi = + WhisperTokenizer::from_tokenizer(synthetic_tokenizer(), MULTILINGUAL_MIN_N_VOCAB) + .expect("resolve"); + assert!(multi.multilingual); + assert_eq!(multi.initial_tokens(None, false), vec![sot, en, tr, nts]); + assert!(is_multilingual_vocab(51866)); + assert!(!is_multilingual_vocab(0)); + } + + #[test] + fn byte_alphabet_is_gpt2s_reversible_table() { + let table = byte_level_alphabet(); + // Printable ASCII maps to itself; space and the control bytes move up + // past U+00FF in byte order. + assert_eq!(table[usize::from(b'a')], 'a'); + assert_eq!(table[usize::from(b'!')], '!'); + assert_eq!(table[0], '\u{100}'); + assert_eq!(table[usize::from(b' ')], '\u{120}'); // "Ġ" + assert_eq!(table[usize::from(b'\n')], '\u{10A}'); // "Ċ" + assert_eq!(table[0xAD], '\u{143}'); + assert_eq!(table[0xFF], '\u{FF}'); + let unique: BTreeSet = table.iter().copied().collect(); + assert_eq!(unique.len(), 256, "the table must be a bijection"); + } + + /// Rank table: every byte at its own value, then the given multi-byte + /// tokens in order. + fn ranks_with(extra: &[&[u8]]) -> Vec> { + let mut ranks: Vec> = (0..=255u8).map(|b| vec![b]).collect(); + ranks.extend(extra.iter().map(|t| t.to_vec())); + ranks + } + + fn ids(tokenizer: &Tokenizer, text: &str) -> Vec { + tokenizer.encode(text, false).unwrap().get_ids().to_vec() + } + + #[test] + fn recovered_merges_apply_the_lowest_rank_pair_first() { + // Ranks 256.. are the extra tokens. With "bc" (256) below "ab" (257), + // "abc" (not in the vocabulary) merges b+c first: [a, bc]. tiktoken's + // loop merges the adjacent pair whose concatenation ranks lowest. + let bc_first = byte_level_bpe_from_ranks(&ranks_with(&[b"bc", b"ab"]), &[]).unwrap(); + assert_eq!(ids(&bc_first, "abc"), vec![u32::from(b'a'), 256]); + // Swapping the two ranks flips the split: [ab, c]. + let ab_first = byte_level_bpe_from_ranks(&ranks_with(&[b"ab", b"bc"]), &[]).unwrap(); + assert_eq!(ids(&ab_first, "abc"), vec![256, u32::from(b'c')]); + // A merged token keeps merging: "abcb" goes b+c, then a+bc, to + // [abc, b]; and a whole pre-tokenized piece in the vocabulary is taken + // as is. + let three = byte_level_bpe_from_ranks(&ranks_with(&[b"bc", b"ab", b"abc"]), &[]).unwrap(); + assert_eq!(ids(&three, "abcb"), vec![258, u32::from(b'b')]); + assert_eq!(ids(&three, "cab"), vec![u32::from(b'c'), 257]); + assert_eq!(ids(&three, "abc"), vec![258]); + } + + #[test] + fn byte_level_bpe_round_trips_spaces_and_multibyte_text() { + let ranks = ranks_with(&[b" h", b"\xc3\xa9"]); + let specials = vec!["<|endoftext|>".to_string(), "<|x|>".to_string()]; + let tok = byte_level_bpe_from_ranks(&ranks, &specials).unwrap(); + // The GPT-2 split keeps the leading space on the word. + assert_eq!(ids(&tok, " hé"), vec![256, 257]); + assert_eq!(ids(&tok, " "), vec![u32::from(b' ')]); + assert_eq!(tok.decode(&[256, 257], true).unwrap(), " hé"); + // Specials take the ids after the ranks and are skipped on decode. + assert_eq!(tok.token_to_id("<|endoftext|>"), Some(258)); + assert_eq!(tok.token_to_id("<|x|>"), Some(259)); + assert_eq!(tok.decode(&[258, 256, 259], true).unwrap(), " h"); + // An empty table still builds (nothing to merge). + assert!(byte_level_bpe_from_ranks(&[], &[]).is_ok()); + } + + #[test] + fn special_token_table_matches_get_encoding() { + let specials = whisper_special_tokens(99); + assert_eq!(specials.len(), 2 + 99 + 6 + TIMESTAMP_TOKENS); + assert_eq!(specials[0], "<|endoftext|>"); + assert_eq!(specials[1], "<|startoftranscript|>"); + assert_eq!(specials[2], "<|en|>"); + assert_eq!(specials[100], "<|su|>"); + assert_eq!(specials[101], "<|translate|>"); + assert_eq!(specials[106], "<|notimestamps|>"); + assert_eq!(specials[107], "<|0.00|>"); + assert_eq!(specials[108], "<|0.02|>"); + assert_eq!(specials[107 + 1500], "<|30.00|>"); + let v3 = whisper_special_tokens(100); + assert_eq!(v3[101], "<|yue|>"); + assert_eq!(whisper_special_tokens(1)[2], "<|en|>"); + // Every timestamp prints like Python's "%.2f" of the f64 product: two + // decimals, never the float's full expansion (0.07000000000000001). + for (i, t) in specials[107..].iter().enumerate() { + let value = t + .strip_prefix("<|") + .and_then(|t| t.strip_suffix("|>")) + .unwrap(); + let (whole, frac) = value.split_once('.').unwrap(); + assert_eq!(frac.len(), 2, "{t}"); + assert_eq!( + whole.parse::().unwrap() * 100 + frac.parse::().unwrap(), + 2 * i + ); + } + assert_eq!(specials[107 + 7], "<|0.14|>"); + assert_eq!(specials[107 + 1449], "<|28.98|>"); + } + + /// Write a `.tiktoken` file of `n_ranks` ranks shaped like openai/whisper's: + /// the 256 single bytes, then two-byte tokens in byte order. Named + /// `multilingual.tiktoken`, its last rank is the `=` (empty token) + /// placeholder the real file ends with. Also used by the loader tests in + /// `super`. + pub(in crate::models::whisper) fn write_rank_file( + dir: &Path, + name: &str, + n_ranks: usize, + ) -> std::path::PathBuf { + let engine = base64::engine::general_purpose::STANDARD; + let placeholder = name == "multilingual.tiktoken"; + let real = n_ranks - usize::from(placeholder); + let mut out = String::new(); + let mut rank = 0usize; + for b in 0..=255u8 { + out.push_str(&format!("{} {rank}\n", engine.encode([b]))); + rank += 1; + } + 'pairs: for a in 0..=255u8 { + for b in 0..=255u8 { + if rank == real { + break 'pairs; + } + out.push_str(&format!("{} {rank}\n", engine.encode([a, b]))); + rank += 1; + } + } + if placeholder { + out.push_str(&format!("= {rank}\n")); + } + let path = dir.join(name); + std::fs::write(&path, out).unwrap(); + path + } + + #[test] + fn tiktoken_vocab_numbers_the_specials_like_openai_whisper() { + let dir = tempfile::tempdir().unwrap(); + // multilingual.tiktoken: 50257 ranks; v1/v2 (99 languages) and v3 + // (100) share it. + let path = write_rank_file(dir.path(), "multilingual.tiktoken", 50257); + let tok = tokenizer_from_tiktoken(&path, 51865).unwrap(); + assert_eq!(tok.get_vocab_size(true), 51865); + let id = |s: &str| tok.token_to_id(s); + assert_eq!(id("<|endoftext|>"), Some(50257)); + assert_eq!(id("<|startoftranscript|>"), Some(50258)); + assert_eq!(id("<|en|>"), Some(50259)); + assert_eq!(id("<|su|>"), Some(50357)); + assert_eq!(id("<|yue|>"), None); + assert_eq!(id("<|translate|>"), Some(50358)); + assert_eq!(id("<|transcribe|>"), Some(50359)); + assert_eq!(id("<|nospeech|>"), Some(50362)); + assert_eq!(id("<|notimestamps|>"), Some(50363)); + assert_eq!(id("<|0.00|>"), Some(50364)); + assert_eq!(id("<|30.00|>"), Some(51864)); + // The placeholder rank sits just below the specials and decodes to "". + assert_eq!(tok.id_to_token(50256).as_deref(), Some("")); + assert_eq!(tok.decode(&[104, 50256, 105], false).unwrap(), "hi"); + + let whisper = WhisperTokenizer::from_tokenizer(tok, 51865).unwrap(); + assert!(whisper.multilingual); + assert_eq!(whisper.language_ids.len(), 99); + assert_eq!(whisper.blank, Some(i32::from(b' '))); + + let v3 = tokenizer_from_tiktoken(&path, 51866).unwrap(); + assert_eq!(v3.token_to_id("<|yue|>"), Some(50358)); + assert_eq!(v3.token_to_id("<|translate|>"), Some(50359)); + assert_eq!(v3.token_to_id("<|0.00|>"), Some(50365)); + + // gpt2.tiktoken: one rank fewer (no <|endoftext|> rank); English-only. + let gpt2 = write_rank_file(dir.path(), "gpt2.tiktoken", 50256); + let en = tokenizer_from_tiktoken(&gpt2, 51864).unwrap(); + assert_eq!(en.token_to_id("<|endoftext|>"), Some(50256)); + assert_eq!(en.token_to_id("<|notimestamps|>"), Some(50362)); + assert_eq!(en.token_to_id("<|0.00|>"), Some(50363)); + let en = WhisperTokenizer::from_tokenizer(en, 51864).unwrap(); + assert!(!en.multilingual); + assert_eq!( + en.initial_tokens(None, false), + vec![en.sot, en.no_timestamps] + ); + } + + #[test] + fn tiktoken_vocab_refuses_a_size_mismatch_and_impossible_n_vocab() { + let dir = tempfile::tempdir().unwrap(); + let gpt2 = write_rank_file(dir.path(), "gpt2.tiktoken", 50256); + // The English-only rank file under a multilingual model is one id short. + let err = tokenizer_from_tiktoken(&gpt2, 51865) + .unwrap_err() + .to_string(); + assert!( + err.contains("51864 ids") && err.contains("n_vocab 51865"), + "{err}" + ); + // num_languages = n_vocab - 51765 - multilingual must be 1..=100. + for n_vocab in [0, 51765, 51867, i32::MAX] { + let err = tokenizer_from_tiktoken(&gpt2, n_vocab) + .unwrap_err() + .to_string(); + assert!(err.contains("language tokens"), "{n_vocab}: {err}"); + } + // The one-language boundary is accepted when the sizes add up. + let one = write_rank_file(dir.path(), "one.tiktoken", 50256); + assert!(tokenizer_from_tiktoken(&one, 51766).is_ok()); + } + + #[test] + fn tiktoken_rank_file_rejects_malformed_tables() { + let dir = tempfile::tempdir().unwrap(); + let engine = base64::engine::general_purpose::STANDARD; + let (a, b) = (engine.encode("a"), engine.encode("b")); + let cases = [ + ("empty", String::new(), "no BPE ranks"), + ("gap", format!("{a} 0\n{b} 2\n"), "no token for rank 1"), + ( + "dup-rank", + format!("{a} 0\n{b} 0\n"), + "rank 0 appears twice", + ), + ("dup-token", format!("{a} 0\n{a} 1\n"), "already has rank 0"), + ("base64", "@@@ 0\n".to_string(), "invalid base64"), + ("rank", format!("{a} x\n"), "invalid rank"), + ("columns", format!("{a} 0 extra\n"), "expected"), + ("one-column", format!("{a}\n"), "expected"), + ("no-token", " 0\n".to_string(), "expected"), + ("two-empty", "= 0\n== 1\n".to_string(), "already has rank 0"), + ("padding-inside", format!("{a}=x 0\n"), "invalid base64"), + ]; + for (name, content, want) in cases { + let path = dir.path().join(name); + std::fs::write(&path, content).unwrap(); + let err = parse_tiktoken_ranks(&path, 8).unwrap_err().to_string(); + assert!(err.contains(want), "{name}: {err}"); + } + // Blank lines are skipped, ranks may arrive out of order, and a bare + // `=` is the empty placeholder token openai/whisper's file ends with. + let path = dir.path().join("ok"); + std::fs::write(&path, format!("\n{b} 1\n\n{a} 0\n= 2\n")).unwrap(); + assert_eq!( + parse_tiktoken_ranks(&path, 8).unwrap(), + vec![b"a".to_vec(), b"b".to_vec(), Vec::new()] + ); + // The bound itself: the last rank that fits is accepted, the next one + // (and anything up to usize::MAX) is refused on its own line. + assert_eq!(parse_tiktoken_ranks(&path, 3).unwrap().len(), 3); + let err = parse_tiktoken_ranks(&path, 2).unwrap_err().to_string(); + assert!( + err.contains("line 5") && err.contains("rank 2 is out of range"), + "{err}" + ); + for rank in [8, 99_999_999_999, usize::MAX] { + std::fs::write(&path, format!("{a} 0\n{b} {rank}\n")).unwrap(); + let err = parse_tiktoken_ranks(&path, 8).unwrap_err().to_string(); + assert!( + err.contains(&format!("rank {rank} is out of range")) + && err.contains("room for 8 ranks (0..=7)"), + "{rank}: {err}" + ); + } + // A zero bound refuses every rank, including 0. + let err = parse_tiktoken_ranks(&path, 0).unwrap_err().to_string(); + assert!(err.contains("rank 0 is out of range"), "{err}"); + } + + /// Append `line` to a full-size synthetic `multilingual.tiktoken` and + /// build it for n_vocab 51865 (50257 ranks + 1608 specials). + fn build_with_extra_rank_line(line: &str) -> Result { + let dir = tempfile::tempdir().unwrap(); + let path = write_rank_file(dir.path(), "multilingual.tiktoken", 50257); + let mut content = std::fs::read_to_string(&path).unwrap(); + content.push_str(line); + content.push('\n'); + std::fs::write(&path, content).unwrap(); + tokenizer_from_tiktoken(&path, 51865) + } + + #[test] + fn tiktoken_rank_beyond_n_vocab_is_refused_before_it_sizes_the_table() { + // A single line with a huge rank used to resize the table to + // rank + 1 entries (terabytes) and abort the process. + for rank in ["99999999999", "50257"] { + let err = build_with_extra_rank_line(&format!("YQ== {rank}")) + .err() + .unwrap() + .to_string(); + assert!( + err.contains(&format!("rank {rank} is out of range")) + && err.contains("room for 50257 ranks (0..=50256)"), + "{rank}: {err}" + ); + } + // One past u64: not a rank at all. + let err = build_with_extra_rank_line("YQ== 18446744073709551616") + .err() + .unwrap() + .to_string(); + assert!(err.contains("invalid rank"), "{err}"); + } + + #[test] + fn tiktoken_rank_usize_max_is_refused_without_overflow() { + // `rank + 1` used to wrap to 0 for usize::MAX (or panic with overflow + // checks), and the table was then indexed out of bounds. + let err = build_with_extra_rank_line(&format!("YQ== {}", usize::MAX)) + .err() + .unwrap() + .to_string(); + assert!( + err.contains(&format!("rank {} is out of range", usize::MAX)), + "{err}" + ); + } + + #[test] + fn from_dir_prefers_tokenizer_json_then_the_rank_file_the_vocab_needs() { + let dir = tempfile::tempdir().unwrap(); + // Nothing to load: the error names the file this vocabulary needs. + let err = WhisperTokenizer::from_dir(dir.path(), 51865) + .err() + .unwrap() + .to_string(); + assert!( + err.contains("tokenizer.json") && err.contains("multilingual.tiktoken"), + "{err}" + ); + let err = WhisperTokenizer::from_dir(dir.path(), 51864) + .err() + .unwrap() + .to_string(); + assert!(err.contains("gpt2.tiktoken"), "{err}"); + + write_rank_file(dir.path(), "multilingual.tiktoken", 50257); + let tok = WhisperTokenizer::from_dir(dir.path(), 51865).unwrap(); + assert_eq!(tok.sot, 50258); + + // A tokenizer.json beside it wins, as it always did. + synthetic_tokenizer() + .save(dir.path().join("tokenizer.json"), false) + .unwrap(); + let tok = WhisperTokenizer::from_dir(dir.path(), 51865).unwrap(); + assert_eq!( + tok.sot, + synthetic_tokenizer() + .token_to_id("<|startoftranscript|>") + .unwrap() as i32 + ); + } } diff --git a/src/tokenizer/mod.rs b/src/tokenizer/mod.rs index ea75cd9112..51dd14a75e 100644 --- a/src/tokenizer/mod.rs +++ b/src/tokenizer/mod.rs @@ -2484,6 +2484,16 @@ pub fn load_tokenizer(model_path: &Path) -> Result { return Ok(MlxcelTokenizer::SentencePiece(sp_tokenizer)); } + // A Whisper MLX export ships the openai/whisper rank file + // (`multilingual.tiktoken` / `gpt2.tiktoken`) instead of tokenizer.json. + // Its layout is neither tiktoken family below: the generic loader fails on + // its `=` placeholder line and would misnumber the Whisper special tokens. + if read_config_model_type(model_path).as_deref() == Some("whisper") { + return Ok(MlxcelTokenizer::HuggingFace( + crate::models::whisper::rank_file_tokenizer_for_dir(model_path)?, + )); + } + // Fall back to tiktoken (.tiktoken files) if let Some(tiktoken_path) = find_tiktoken_file(model_path) { let tokenizer = TiktokenTokenizer::from_file(&tiktoken_path, model_path)?; @@ -2725,6 +2735,80 @@ mod tests { } } + /// Write a Whisper MLX export's tokenizer side: `config.json` and a rank + /// file shaped like openai/whisper's (256 single bytes, two-byte tokens, + /// and for `multilingual.tiktoken` the closing `=` placeholder rank). + fn write_whisper_rank_file_dir( + dir: &std::path::Path, + n_vocab: i32, + name: &str, + n_ranks: usize, + ) { + use base64::Engine; + let engine = base64::engine::general_purpose::STANDARD; + let placeholder = name == "multilingual.tiktoken"; + let real = n_ranks - usize::from(placeholder); + let singles = (0..=255u8).map(|b| vec![b]); + let pairs = (0..=255u8).flat_map(|a| (0..=255u8).map(move |b| vec![a, b])); + let mut out: String = singles + .chain(pairs) + .take(real) + .enumerate() + .map(|(rank, token)| format!("{} {rank}\n", engine.encode(token))) + .collect(); + if placeholder { + out.push_str(&format!("= {real}\n")); + } + std::fs::write(dir.join(name), out).unwrap(); + let config = serde_json::json!({ + "model_type": "whisper", "n_mels": 80, "n_audio_ctx": 1500, "n_audio_state": 384, + "n_audio_head": 6, "n_audio_layer": 4, "n_vocab": n_vocab, "n_text_ctx": 448, + "n_text_state": 384, "n_text_head": 6, "n_text_layer": 4, + "quantization": { "group_size": 64, "bits": 4 } + }); + std::fs::write(dir.join("config.json"), config.to_string()).unwrap(); + } + + /// A Whisper MLX export (`mlx-community/whisper-*-4bit`) ships + /// `multilingual.tiktoken` or `gpt2.tiktoken` and no `tokenizer.json`. The + /// server's tokenizer must load it with openai/whisper's numbering instead + /// of sending it to the HunYuan rank-file reader, which stopped the server + /// at startup on the file's `= 50256` placeholder line. + #[test] + fn load_tokenizer_reads_a_whisper_rank_file() { + let dir = temp_dir("whisper-multilingual"); + write_whisper_rank_file_dir(&dir, 51865, "multilingual.tiktoken", 50257); + let tokenizer = load_tokenizer(&dir).expect("a Whisper rank file must load"); + let hf = tokenizer.hf_tokenizer().expect("HuggingFace backend"); + assert_eq!(hf.token_to_id("<|endoftext|>"), Some(50257)); + assert_eq!(hf.token_to_id("<|startoftranscript|>"), Some(50258)); + assert_eq!(hf.token_to_id("<|en|>"), Some(50259)); + assert_eq!(hf.token_to_id("<|notimestamps|>"), Some(50363)); + assert_eq!(hf.get_vocab_size(true), 51865); + let ids = hf.encode(" hi", false).unwrap().get_ids().to_vec(); + assert_eq!(hf.decode(&ids, false).unwrap(), " hi"); + + let en = temp_dir("whisper-english"); + write_whisper_rank_file_dir(&en, 51864, "gpt2.tiktoken", 50256); + let tokenizer = load_tokenizer(&en).expect("an English-only rank file must load"); + let hf = tokenizer.hf_tokenizer().expect("HuggingFace backend"); + assert_eq!(hf.token_to_id("<|endoftext|>"), Some(50256)); + assert_eq!(hf.token_to_id("<|notimestamps|>"), Some(50362)); + + // The rank file the vocabulary needs is missing: a Whisper error, not + // the HunYuan reader on whatever `.tiktoken` happens to be there. + let wrong = temp_dir("whisper-wrong-file"); + write_whisper_rank_file_dir(&wrong, 51865, "gpt2.tiktoken", 50256); + let err = load_tokenizer(&wrong) + .err() + .expect("no multilingual.tiktoken"); + assert!(err.to_string().contains("multilingual.tiktoken"), "{err}"); + + for path in [dir, en, wrong] { + let _ = std::fs::remove_dir_all(path); + } + } + /// `add_prefix_space` and `add_bos_token` from `tokenizer_config.json` are /// honored, and a special listed in both `vocab.json` and /// `added_tokens_decoder` under the same id (Lille's layout) is accepted From fe471641f86caa9d01939d5b9b50251ef2888629 Mon Sep 17 00:00:00 2001 From: Jeongkyu Shin Date: Fri, 4 Dec 2026 18:53:35 +0900 Subject: [PATCH 2/2] fix(whisper): bound rank-file size and token length The rank-file parser already refused out-of-range ranks, but it read the whole file into memory with no limit, and merge recovery hashes every split of every token, so one very long base64 line costs time quadratic in its length. openai/whisper's rank files are about 0.8 MiB and their longest token is 128 bytes (gpt2.tiktoken) or 33 (multilingual.tiktoken). parse_tiktoken_ranks now reads at most 16 MiB (detected by reading one byte past the cap, not from metadata), refuses a decoded token longer than 256 bytes on its own line, and reports invalid UTF-8 as an error. A new test covers the token cap boundary, the file cap and non-UTF-8 input. Refs #3746 --- src/models/whisper/tokenizer.rs | 67 ++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/src/models/whisper/tokenizer.rs b/src/models/whisper/tokenizer.rs index 9165a94482..125b7c2803 100644 --- a/src/models/whisper/tokenizer.rs +++ b/src/models/whisper/tokenizer.rs @@ -58,6 +58,18 @@ const N_VOCAB_WITHOUT_LANGUAGES: i32 = 51765; /// Number of `<|t.tt|>` timestamp tokens, 0.00 to 30.00 in 0.02 s steps. const TIMESTAMP_TOKENS: usize = 1501; +/// Largest `.tiktoken` rank file read. openai/whisper's `multilingual.tiktoken` +/// and `gpt2.tiktoken` are about 0.8 MiB; anything twenty times that is not a +/// Whisper vocabulary and is refused before it is read into memory. +const MAX_TIKTOKEN_FILE_BYTES: u64 = 16 * 1024 * 1024; + +/// Longest decoded token accepted from a rank file. The longest token in +/// `gpt2.tiktoken` is 128 bytes and in `multilingual.tiktoken` 33. Merge +/// recovery hashes every split of every token, so the cost is quadratic in the +/// token length; this cap keeps a hostile file from turning one long line into +/// minutes of hashing. +const MAX_TIKTOKEN_TOKEN_BYTES: usize = 256; + /// Whether a checkpoint with this `n_vocab` is multilingual, as the reference /// decides it. pub(crate) fn is_multilingual_vocab(n_vocab: i32) -> bool { @@ -300,8 +312,23 @@ fn byte_level_alphabet() -> [char; 256] { /// `usize::MAX`) cannot size an allocation or overflow `rank + 1`; the table /// never holds more than `max_ranks` entries. fn parse_tiktoken_ranks(path: &Path, max_ranks: usize) -> Result>> { - let content = std::fs::read_to_string(path) + use std::io::Read; + let file = std::fs::File::open(path) + .map_err(|e| anyhow!("Failed to read Whisper tokenizer {path:?}: {e}"))?; + // Read one byte past the cap so an oversized file is detected without + // trusting the metadata length (which a FIFO or a growing file lacks). + let mut raw = Vec::new(); + file.take(MAX_TIKTOKEN_FILE_BYTES + 1) + .read_to_end(&mut raw) .map_err(|e| anyhow!("Failed to read Whisper tokenizer {path:?}: {e}"))?; + if raw.len() as u64 > MAX_TIKTOKEN_FILE_BYTES { + return Err(anyhow!( + "Whisper tokenizer {path:?} is larger than {MAX_TIKTOKEN_FILE_BYTES} bytes; \ + an openai/whisper rank file is under 1 MiB" + )); + } + let content = String::from_utf8(raw) + .map_err(|e| anyhow!("Whisper tokenizer {path:?} is not UTF-8: {e}"))?; let mut by_rank: Vec>> = Vec::new(); let mut seen: HashMap, usize> = HashMap::new(); for (line_no, line) in content.lines().enumerate() { @@ -321,6 +348,12 @@ fn parse_tiktoken_ranks(path: &Path, max_ranks: usize) -> Result>> { .decode(token) .map_err(|e| bad(&format!("invalid base64 token: {e}")))? }; + if bytes.len() > MAX_TIKTOKEN_TOKEN_BYTES { + return Err(bad(&format!( + "token is {} bytes; a Whisper BPE token is at most {MAX_TIKTOKEN_TOKEN_BYTES}", + bytes.len() + ))); + } let rank: usize = rank .parse() .map_err(|e| bad(&format!("invalid rank {rank:?}: {e}")))?; @@ -1052,6 +1085,38 @@ pub(super) mod tests { assert!(err.contains("rank 0 is out of range"), "{err}"); } + #[test] + fn tiktoken_rank_file_bounds_file_and_token_size() { + let dir = tempfile::tempdir().unwrap(); + let engine = base64::engine::general_purpose::STANDARD; + let path = dir.path().join("tokens"); + // The longest token accepted is MAX_TIKTOKEN_TOKEN_BYTES; one byte + // more is refused on its own line, before merge recovery sees it. + let longest = engine.encode(vec![b'-'; MAX_TIKTOKEN_TOKEN_BYTES]); + std::fs::write(&path, format!("{longest} 0\n")).unwrap(); + assert_eq!(parse_tiktoken_ranks(&path, 8).unwrap()[0].len(), 256); + let too_long = engine.encode(vec![b'-'; MAX_TIKTOKEN_TOKEN_BYTES + 1]); + std::fs::write(&path, format!("{longest} 0\n{too_long} 1\n")).unwrap(); + let err = parse_tiktoken_ranks(&path, 8).unwrap_err().to_string(); + assert!( + err.contains("line 2") && err.contains("token is 257 bytes"), + "{err}" + ); + // A file past the size cap is refused before it is parsed, even when + // every line would be valid. + let big = dir.path().join("big"); + let line = format!("{} 0\n", engine.encode("a")); + let copies = (MAX_TIKTOKEN_FILE_BYTES as usize / line.len()) + 1; + std::fs::write(&big, line.repeat(copies)).unwrap(); + let err = parse_tiktoken_ranks(&big, 8).unwrap_err().to_string(); + assert!(err.contains("larger than"), "{err}"); + // Invalid UTF-8 is an error, not a panic. + let bin = dir.path().join("bin"); + std::fs::write(&bin, [0xFFu8, 0xFE, b' ', b'0', b'\n']).unwrap(); + let err = parse_tiktoken_ranks(&bin, 8).unwrap_err().to_string(); + assert!(err.contains("not UTF-8"), "{err}"); + } + /// Append `line` to a full-size synthetic `multilingual.tiktoken` and /// build it for n_vocab 51865 (50257 ranks + 1608 specials). fn build_with_extra_rank_line(line: &str) -> Result {