Skip to content

feat(whisper): load quantized MLX exports and the openai/whisper rank-file tokenizer - #3748

Open
Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/whisper-quantized-mlx-community
Open

Jaeyeong-CHOI wants to merge 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/whisper-quantized-mlx-community

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

Closes #3746. Closes #3747.

The Whisper exports that mlx-audio-plus wrote to mlx-community (whisper-{tiny,base,small}-{4bit,8bit}, whisper-large-v3-turbo-4bit, whisper-tiny.en-4bit) are affine-quantized and ship openai/whisper's multilingual.tiktoken / gpt2.tiktoken instead of a tokenizer.json. None of them could be served: the server exited at startup on the rank file, the Whisper loader required tokenizer.json, and the projections and token embedding were built as dense layers over the packed uint32 planes (#3746). This PR loads them, with greedy output equal to mlx-whisper on every size tested.

It also fixes #3747: English-only checkpoints, the dense openai/whisper-*.en included, were treated as multilingual, so transcription detected a language and prompted with it. The rank-file tokenizer needs the same rule to number the English-only vocabulary, which is why both are in one PR.

What changed

Quantized weights (src/models/whisper/{mod,layers,decoder,encoder}.rs)

  • Every attention projection and MLP linear is a UnifiedLinear, and the tied token embedding a UnifiedEmbedding, so a module that ships .scales runs as a quantized matmul (the tied head included, through as_linear). This is the reference nn.quantize class predicate (isinstance(m, (nn.Linear, nn.Embedding)) and f"{p}.scales" in weights). A module without .scales takes the same dense Linear / Embedding as before; the convolutions and positional tables are untouched.
  • WhisperQuantization::from_config reads the quantization block through the shared config::QuantizationArgs. Absent block or field: MLX's nn.quantize defaults (inert for a dense checkpoint). A malformed field, an out-of-range group_size / bits (validate_quantization_params), or a mode other than affine fails the load.
  • The compute dtype was read from decoder.token_embedding.weight, which is uint32 in a packed export, so the mel spectrogram was cast to uint32. checkpoint_dtype falls back to the table's .scales dtype, then float16.
  • A quantized export skips the bf16 to f16 conversion, like Florence-2 and the reference loader. Only a declared quantization block counts: "quantization": null or a Hugging Face quantization_config alone keeps a dense checkpoint on the dense policy, as on main. The seven exports tested here store f16 scales and dense tensors, so this only matters for a bf16 export.

Tokenizer (src/models/whisper/tokenizer.rs, src/tokenizer/mod.rs)

  • Without tokenizer.json, tokenizer_from_tiktoken builds the byte-level BPE from multilingual.tiktoken (multilingual n_vocab) or gpt2.tiktoken (English-only). The vocabulary is the rank table in the GPT-2 byte alphabet. Merges are recovered from the ranks the way Hugging Face's TikTokenConverter does: every split of a token into two tokens, ordered by the merged token's rank. ignore_merges is set, and the pre-tokenizer is the byte-level GPT-2 split, which is openai/whisper's pat_str. The special tokens follow openai/whisper's get_encoding order, with num_languages = n_vocab - 51765 - is_multilingual. A rank file whose size does not add up to n_vocab is refused, and so is a rank at or above n_vocab minus the specials, on its own line and before it can size the rank table (a line like YQ== 99999999999 would otherwise ask for terabytes, and a rank of usize::MAX would overflow rank + 1).
  • multilingual.tiktoken ends with = 50256, a bare padding character that Python's lenient b64decode reads as the empty token. It keeps GPT-2's old <|endoftext|> id so that the specials start at 50257, and the HF tokenizer.json spells id 50256 as "" too. The parser accepts a token made only of = as the empty token.
  • crate::tokenizer::load_tokenizer (the server's startup tokenizer, also used by /tokenize) sends a model_type: "whisper" directory without tokenizer.json to this builder. Before, it went to the HunYuan/Kimi TiktokenTokenizer, which failed on the placeholder line (Error: Invalid symbol 61, offset 0., which stopped the server) and would have numbered the specials with the HunYuan table anyway.
  • (fix(audio): English-only Whisper checkpoints (openai/whisper-*.en) are prompted as multilingual, so a language is detected and the transcript changes #3747) WhisperTokenizer.multilingual now follows the reference Whisper.is_multilingual (n_vocab >= 51865) as well as the presence of language tags. Every Whisper vocabulary numbers the language tags, the English-only one included, so under the previous "has language tags" rule an English-only model detected a language and got a language and a task token. On openai/whisper-tiny.en and the test clip, main (with no language hint) detects Lingala and prompts <|startoftranscript|><|ln|><|transcribe|><|notimestamps|>. The gpt2.tiktoken path needs the reference rule as well, to number its ids.

Docs and tests

  • docs/audio-api.md and docs/supported-models.md drop the "quantized Whisper weights are not yet supported" statements and describe the rank-file fallback. CHANGELOG.md is not edited; it is written at release time.
  • scripts/whisper_mlx_reference.py writes an mlx-whisper reference (mel window, greedy tokens, teacher-forced logits, a tiktoken corpus), and src/models/whisper/real_tests.rs (ignored by default) checks a checkpoint against it.

Deviations

Verification

Hardware: NVIDIA GB10 (sm_121), CUDA 13.0, driver 580.178.04. Reference: mlx 0.32.4, mlx-whisper 0.4.3, tiktoken 0.14.0; transformers 5.20.2 / torch 2.11.0 (CPU) for the Hugging Face checkpoints.

Checkpoints:

Checkpoint Revision
mlx-community/whisper-tiny-4bit 064afea920b0373f8e19d51dc698bfbb91f501ff
mlx-community/whisper-tiny-8bit 76e06d3401d6652722b71dcb155691d8015ce61c
mlx-community/whisper-base-4bit 50e8af4ebba739430129a6ab975a9b368a9a2fc4
mlx-community/whisper-base-8bit a6f6355aba6b77681c614ee1eb40264230bf76e7
mlx-community/whisper-small-4bit 1ac90abbb1b2f53863bfd2a483a3c31d792c3e5b
mlx-community/whisper-large-v3-turbo-4bit 0f058d38170d183f9fdee07908f5b515d91793a8
mlx-community/whisper-tiny.en-4bit beed452b81d37155b5380c562d1b2b9f4a71f807
openai/whisper-tiny 169d4a4341b33bc18d8881c4b69c2e104e1cc0af
openai/whisper-tiny.en 87c7102498dcde7456f24cfd30239ca606ed9063
mlx-community/whisper-tiny-asr-4bit (mlx-audio layout) 282762aa4ccd9e7cc995a294f3e5b56e65a2bd58

Before (main 9402cf8). mlxcel serve -m <dir>, then POST /v1/audio/transcriptions with tests/fixtures/audio/speech.flac as a 16 kHz WAV:

Checkpoint main this PR
openai/whisper-tiny (control) 200 200, same text
whisper-tiny-4bit, -8bit, base-4bit, -8bit, small-4bit, large-v3-turbo-4bit server exits: Error: Invalid symbol 61, offset 0. 200
whisper-tiny.en-4bit starts; Whisper load fails (tokenizer.json not found); 503 200
whisper-tiny-asr-4bit (quantized, ships tokenizer.json) first request aborts: [conv] Invalid input array with type uint32 200, same text as whisper-tiny-4bit
whisper-tiny-4bit weights + openai/whisper-tiny's tokenizer.json first request aborts: same 200
openai/whisper-tiny.en 200, text differs from transformers (... fat mutton pieces to be ladled out in thick peppered flower-fatened sauce.) 200, transformers' text

For openai/whisper-tiny.en the server does not log the prompt; decoding the same clip through the library on main shows <|startoftranscript|><|ln|><|transcribe|><|notimestamps|> (Lingala detected) and 36 generated tokens, the same text as main's server. This PR prompts <|startoftranscript|><|notimestamps|>.

The new checkpoint-free tests fail before the fix with only the tests added. On main: tokenizer::tests::load_tokenizer_reads_a_whisper_rank_file (a Whisper rank file must load: Invalid symbol 61, offset 0.) and models::whisper::tests::quantized_mlx_export_loads_and_matches_its_dequantized_twin (Failed to load Whisper tokenizer from ".../tokenizer.json": No such file or directory).

The two rank-bound tests, run against this branch without the bound (the rank-file parser as it was before the check was added): tiktoken_rank_beyond_n_vocab_is_refused_before_it_sizes_the_table aborts the test process (memory allocation of 2400000000000 bytes failed, SIGABRT) on the line YQ== 99999999999, and tiktoken_rank_usize_max_is_refused_without_overflow panics (index out of bounds: the len is 0 but the index is 18446744073709551615).

After (this commit, tree dd3abfee). The builds, tests, gate, probes and parity runs below were done on tree 62111d0e, which differs from this commit only by a CHANGELOG.md entry since removed; cargo fmt --check and the scripts/ci checks were rerun on dd3abfee.

  • Server: every row of the table above returns 200 (11/11 checkpoints). POST /tokenize with {"content": " Hello world, 안녕하세요."} on mlx-community/whisper-tiny-4bit returns [2425, 1002, 11, 19289, 13], tiktoken's ids for the string. The quantized transcripts are the texts mlx-whisper produces, below. openai/whisper-tiny.en now gives the transformers 5.20.2 greedy text (... fat-mutton pieces to be ladled out and thick, peppered flower-fattened sauce.), with its 39 tokens equal to WhisperForConditionalGeneration.generate. On main the library decode generates 36 tokens after the Lingala prompt, and the text differs from transformers'.
  • Parity with mlx-whisper 0.4.3 on the first 30 s window of speech.flac (scripts/whisper_mlx_reference.py, then src/models/whisper/real_tests.rs). mlxcel encodes the reference's mel window and decodes greedily with language detection. "Decided" means the reference's top-1 / top-2 logit gap is above 0.5 at a position that predicts a generated token or end-of-text.
Checkpoint Greedy tokens Language Decoded text and end-to-end transcribe text Teacher-forced logits, max abs diff (mean of per-position max) Argmax on decided positions
tiny-4bit 35 = 35 en = en equal 0.297 (0.066) 34/34
tiny-8bit 38 = 38 en = en equal 0.359 (0.067) 37/37
base-4bit 37 = 37 en = en equal 0.109 (0.046) 38/38
base-8bit 38 = 38 en = en equal 0.109 (0.038) 37/37
small-4bit 38 = 38 en = en equal 0.063 (0.029) 37/37
large-v3-turbo-4bit 41 = 41 en = en equal 0.262 (0.158) 42/42
tiny.en-4bit 43 = 43 English-only, none detected (mlx-whisper reports en) equal 0.063 (0.029) 42/42

The end-to-end column runs WhisperModel::transcribe on the clip through mlxcel's own log-mel front end and compares the text with mlx-whisper's.

  • Tokenizer, per rank file: every special token id and the ids of a 12-string corpus (English punctuation and contractions, Korean, Japanese, Chinese, Cyrillic and accented Latin, music symbols and brackets, emoji, whitespace runs, a URL) equal tiktoken's encoding from mlx_whisper.tokenizer.get_encoding, and decode round-trips. The specials are 1608 for n_vocab 51864/51865 and 1609 for large-v3-turbo's 51866. Built against openai/whisper-tiny's and openai/whisper-tiny.en's tokenizer.json, every one of the 51865 / 51864 ids is spelled the same except <|nospeech|> (HF: <|nocaptions|>) and, in the English-only file, <|he|> (HF: <|iw|>). Building the tokenizer from the rank file takes 190 to 227 ms per load.
  • Dense path unchanged: with a temporary dump test, the encoder features, greedy tokens and teacher-forced logits of openai/whisper-tiny on the clip are byte-identical between main and this branch (11,017,492 bytes). Its 38 greedy tokens equal transformers' as well. The dump was taken before the rank bound and the bf16-gate change were added; neither changes what a float32 checkpoint with a tokenizer.json loads, and the server text for openai/whisper-tiny is unchanged on this commit.
  • Unit tests: models::whisper 31 passed, 2 ignored (the real-checkpoint tests); tokenizer:: 168 passed, 5 ignored; models::config 3, models::sanitize 106, server::whisper_stt 3, server::routes::transcription_compat 18, all passed.
  • cargo fmt --all -- --check, cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: clean. scripts/ci/check_used_by.py (OK, 57 of 78 annotated), check_used_by_test.sh, check_env_var_docs.py (the four test-only MLXCEL_TEST_WHISPER_* names are allowlisted), check_binary_assets.py, check_cross_repo_refs.py, check_windows_reserved_paths.py, check_native_env_writes.py: OK.
  • make verify-test-cuda (--test-threads=1, MLX_ENABLE_TF32=0): 18,907 passed, 2 failed, 580 ignored. The two failures also fail on unmodified main 9402cf8: mlx_test_guard_coverage::mlx_evaluating_lib_tests_take_mlx_test_guard flags only src/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32, and step3p7_parity::text_decode_delegates_sequence_local_native_batching fails at assertion failed: !wrapper.supports_padded_prefill(). Neither test touches Whisper. The MLX-evaluating Whisper tests take mlx_test_guard() first, so the guard test does not flag them.
  • The commit merges cleanly onto origin/main 9402cf8 (git merge-tree).

Commands:

python scripts/whisper_mlx_reference.py --model <ckpt> --audio tests/fixtures/audio/speech.flac \
    --out ref.safetensors --tokenizer-out tok.json            # add --language en for tiny.en
MLXCEL_TEST_WHISPER_DIR=<ckpt> MLXCEL_TEST_WHISPER_REFERENCE=ref.safetensors \
MLXCEL_TEST_WHISPER_TOKENIZER_REFERENCE=tok.json \
MLXCEL_TEST_WHISPER_HF_TOKENIZER=<openai/whisper-tiny>/tokenizer.json \
    cargo test --profile test-fast --features cuda --lib models::whisper::real_tests -- --ignored --nocapture
mlxcel serve -m <ckpt> --port 18731
curl -F file=@speech.wav -F model=whisper http://127.0.0.1:18731/v1/audio/transcriptions

Review checklist

  • Boundaries.
    • n_vocab 51864 / 51865 / 51866 (English-only / v1-v2 / v3) and the impossible ones: 0, 51765 (no language), 51867 (101 languages) and i32::MAX. The one-language vocabulary (51766) is accepted.
    • A rank file one id short is refused. The rank-file parser is tested on an empty file, a rank gap, a duplicate rank, a duplicate token, two empty tokens, bad base64, a bad rank, the wrong column count, out-of-order ranks and the = placeholder.
    • Rank values: the last rank the bound allows is accepted and the next one is refused; so are 99999999999, usize::MAX and a bound of 0, and a rank past u64 is not a number. Through tokenizer_from_tiktoken on a full-size file (bound 50257 for n_vocab 51865): 50257, 99999999999 and usize::MAX are refused. The table never grows past the bound, so memory is O(n_vocab) whatever the file says.
    • The BPE builder is tested on an empty table. Merge order is checked both ways round ("abc" splits [a, bc] or [ab, c] depending on which pair ranks lower).
    • quantization is tested absent, null, partial (and only a non-null block marks the export as quantized for the bf16 policy; null, {} and a Hugging Face quantization_config are checked), at the extremes MLX packs (group 1, 32 bits) and out of range (group 0, bits 0 and 33). Malformed types (string, float, > i32) are refused, and so are non-affine and misspelled modes.
    • The dtype fallback is tested with no table, a float table, a packed table without scales, and bf16 scales.
  • Large inputs. Recovering the merges is one hash lookup per split point of each token, O(sum of token lengths squared), over 50k tokens of at most a few dozen bytes. It runs once per load and measured 190 to 227 ms on GB10, end to end. The server builds the tokenizer twice at startup (its own tokenizer and the Whisper worker's).
  • Other callers.
    • linear in whisper/layers.rs and the token embedding are Whisper-local; nothing outside models::whisper builds them. WhisperTokenizer::{from_dir, from_tokenizer} has callers only in models::whisper.
    • load_tokenizer's new branch fires only for model_type: "whisper", after tokenizer.json and tokenizer.model, so no other family's resolution order changes. find_tiktoken_file / TiktokenTokenizer are untouched.
    • UnifiedLinear / UnifiedEmbedding / QuantizationArgs / convert_bf16_weights are used, not changed. The Used by: lists of QuantizationArgs and convert_bf16_weights gained Whisper. Whisper does not use config_has_quantization_metadata: that predicate is also true for "quantization": null and for a Hugging Face quantization_config, so the bf16 gate reads the same declared block WhisperQuantization::from_config reads.
    • The rank-file parser and its bound have one caller, tokenizer_from_tiktoken.
  • CHANGELOG not edited (written at release time).
  • Comments and messages. The module comment and the two docs that said quantized checkpoints are a follow-up now describe what loads; no other explanatory comment was removed. The bf16 comment in WhisperModel::load is kept and extended. The generic "No tokenizer found ..." message is unchanged, because a Whisper directory now gets its own error naming tokenizer.json and the rank file it needs.
  • Formatting. cargo fmt --all -- --check passes on the committed tree.

Limits

  • Measured on CUDA (GB10) only; Metal was not run.
  • Greedy decoding and one English clip. The multilingual tokenizer is checked against tiktoken on a corpus, but no non-English audio was transcribed, and translation was not run on the quantized checkpoints.
  • Only affine exports; a declared non-affine mode is refused at load.
  • The most downloaded MLX Whisper repositories are the older mlx-whisper conversions: mlx-community/whisper-large-v3-turbo (weights.safetensors), whisper-small-mlx, whisper-large-v3-mlx and the quantized whisper-large-v3-turbo-q4 (weights.npz). They ship no tokenizer file, and mlxcel reads only *.safetensors, so they still do not load (by reading the loader; not run). mlx-whisper reads the rank files bundled in its Python package for these.
  • Of the mlx-audio layout (whisper-*-asr-*bit: quantized model.safetensors, Hugging Face config fields, tokenizer.json), only whisper-tiny-asr-4bit was run, through the server; its text equals whisper-tiny-4bit's. It was not compared with a reference on its own.
  • The real-checkpoint tests are #[ignore]d and need a reference generated with mlx-whisper; the checkpoint-free tests cover the loader, the tokenizer builder and the server tokenizer path.

…-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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant