Repository navigation
feat(whisper): load quantized MLX exports and the openai/whisper rank-file tokenizer - #3748
Open
Jaeyeong-CHOI wants to merge 1 commit into
Open
Jaeyeong-CHOI wants to merge 1 commit into
Jaeyeong-CHOI wants to merge 1 commit into
Conversation
…-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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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'smultilingual.tiktoken/gpt2.tiktokeninstead of atokenizer.json. None of them could be served: the server exited at startup on the rank file, the Whisper loader requiredtokenizer.json, and the projections and token embedding were built as dense layers over the packeduint32planes (#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-*.enincluded, 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)UnifiedLinear, and the tied token embedding aUnifiedEmbedding, so a module that ships.scalesruns as a quantized matmul (the tied head included, throughas_linear). This is the referencenn.quantizeclass predicate (isinstance(m, (nn.Linear, nn.Embedding)) and f"{p}.scales" in weights). A module without.scalestakes the same denseLinear/Embeddingas before; the convolutions and positional tables are untouched.WhisperQuantization::from_configreads thequantizationblock through the sharedconfig::QuantizationArgs. Absent block or field: MLX'snn.quantizedefaults (inert for a dense checkpoint). A malformed field, an out-of-rangegroup_size/bits(validate_quantization_params), or a mode other thanaffinefails the load.decoder.token_embedding.weight, which isuint32in a packed export, so the mel spectrogram was cast touint32.checkpoint_dtypefalls back to the table's.scalesdtype, thenfloat16.quantizationblock counts:"quantization": nullor a Hugging Facequantization_configalone 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)tokenizer.json,tokenizer_from_tiktokenbuilds the byte-level BPE frommultilingual.tiktoken(multilingualn_vocab) orgpt2.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'sTikTokenConverterdoes: every split of a token into two tokens, ordered by the merged token's rank.ignore_mergesis set, and the pre-tokenizer is the byte-level GPT-2 split, which is openai/whisper'spat_str. The special tokens follow openai/whisper'sget_encodingorder, withnum_languages = n_vocab - 51765 - is_multilingual. A rank file whose size does not add up ton_vocabis refused, and so is a rank at or aboven_vocabminus the specials, on its own line and before it can size the rank table (a line likeYQ== 99999999999would otherwise ask for terabytes, and a rank ofusize::MAXwould overflowrank + 1).multilingual.tiktokenends with= 50256, a bare padding character that Python's lenientb64decodereads as the empty token. It keeps GPT-2's old<|endoftext|>id so that the specials start at 50257, and the HFtokenizer.jsonspells 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 amodel_type: "whisper"directory withouttokenizer.jsonto this builder. Before, it went to the HunYuan/KimiTiktokenTokenizer, 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.WhisperTokenizer.multilingualnow follows the referenceWhisper.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. Onopenai/whisper-tiny.enand the test clip, main (with no language hint) detects Lingala and prompts<|startoftranscript|><|ln|><|transcribe|><|notimestamps|>. Thegpt2.tiktokenpath needs the reference rule as well, to number its ids.Docs and tests
docs/audio-api.mdanddocs/supported-models.mddrop the "quantized Whisper weights are not yet supported" statements and describe the rank-file fallback.CHANGELOG.mdis not edited; it is written at release time.scripts/whisper_mlx_reference.pywrites an mlx-whisper reference (mel window, greedy tokens, teacher-forced logits, a tiktoken corpus), andsrc/models/whisper/real_tests.rs(ignored by default) checks a checkpoint against it.Deviations
gpt2.tiktokenpath needs to number its ids and which also changes the prompt of an English-onlytokenizer.jsoncheckpoint (see Verification). It is a separate issue because it affects dense checkpoints too; it stays in this PR becausewhisper-tiny.en-4bitcannot match the reference without it.load_modelreadsweights.safetensors/weights.npz, while these exports name the filemodel.safetensors, so the reference script assembles the model the same wayload_modeldoes from whichever file exists.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:
mlx-community/whisper-tiny-4bit064afea920b0373f8e19d51dc698bfbb91f501ffmlx-community/whisper-tiny-8bit76e06d3401d6652722b71dcb155691d8015ce61cmlx-community/whisper-base-4bit50e8af4ebba739430129a6ab975a9b368a9a2fc4mlx-community/whisper-base-8bita6f6355aba6b77681c614ee1eb40264230bf76e7mlx-community/whisper-small-4bit1ac90abbb1b2f53863bfd2a483a3c31d792c3e5bmlx-community/whisper-large-v3-turbo-4bit0f058d38170d183f9fdee07908f5b515d91793a8mlx-community/whisper-tiny.en-4bitbeed452b81d37155b5380c562d1b2b9f4a71f807openai/whisper-tiny169d4a4341b33bc18d8881c4b69c2e104e1cc0afopenai/whisper-tiny.en87c7102498dcde7456f24cfd30239ca606ed9063mlx-community/whisper-tiny-asr-4bit(mlx-audio layout)282762aa4ccd9e7cc995a294f3e5b56e65a2bd58Before (main 9402cf8).
mlxcel serve -m <dir>, thenPOST /v1/audio/transcriptionswithtests/fixtures/audio/speech.flacas a 16 kHz WAV:openai/whisper-tiny(control)whisper-tiny-4bit,-8bit,base-4bit,-8bit,small-4bit,large-v3-turbo-4bitError: Invalid symbol 61, offset 0.whisper-tiny.en-4bittokenizer.jsonnot found); 503whisper-tiny-asr-4bit(quantized, shipstokenizer.json)[conv] Invalid input array with type uint32whisper-tiny-4bitwhisper-tiny-4bitweights +openai/whisper-tiny'stokenizer.jsonopenai/whisper-tiny.en... fat mutton pieces to be ladled out in thick peppered flower-fatened sauce.)For
openai/whisper-tiny.enthe 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.) andmodels::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_tableaborts the test process (memory allocation of 2400000000000 bytes failed, SIGABRT) on the lineYQ== 99999999999, andtiktoken_rank_usize_max_is_refused_without_overflowpanics (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 tree62111d0e, which differs from this commit only by aCHANGELOG.mdentry since removed;cargo fmt --checkand thescripts/cichecks were rerun ondd3abfee.POST /tokenizewith{"content": " Hello world, 안녕하세요."}onmlx-community/whisper-tiny-4bitreturns[2425, 1002, 11, 19289, 13], tiktoken's ids for the string. The quantized transcripts are the texts mlx-whisper produces, below.openai/whisper-tiny.ennow 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 toWhisperForConditionalGeneration.generate. On main the library decode generates 36 tokens after the Lingala prompt, and the text differs from transformers'.speech.flac(scripts/whisper_mlx_reference.py, thensrc/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.transcribetexten)The end-to-end column runs
WhisperModel::transcribeon the clip through mlxcel's own log-mel front end and compares the text with mlx-whisper's.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 againstopenai/whisper-tiny's andopenai/whisper-tiny.en'stokenizer.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.openai/whisper-tinyon 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 atokenizer.jsonloads, and the server text foropenai/whisper-tinyis unchanged on this commit.models::whisper31 passed, 2 ignored (the real-checkpoint tests);tokenizer::168 passed, 5 ignored;models::config3,models::sanitize106,server::whisper_stt3,server::routes::transcription_compat18, 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-onlyMLXCEL_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_guardflags onlysrc/vision/encoders/nemotron_h_nano_omni_tests.rs:276 pos_embed_resample_runs_in_f32, andstep3p7_parity::text_decode_delegates_sequence_local_native_batchingfails atassertion failed: !wrapper.supports_padded_prefill(). Neither test touches Whisper. The MLX-evaluating Whisper tests takemlx_test_guard()first, so the guard test does not flag them.origin/main9402cf8 (git merge-tree).Commands:
Review checklist
n_vocab51864 / 51865 / 51866 (English-only / v1-v2 / v3) and the impossible ones: 0, 51765 (no language), 51867 (101 languages) andi32::MAX. The one-language vocabulary (51766) is accepted.=placeholder.99999999999,usize::MAXand a bound of 0, and a rank pastu64is not a number. Throughtokenizer_from_tiktokenon a full-size file (bound 50257 for n_vocab 51865): 50257,99999999999andusize::MAXare refused. The table never grows past the bound, so memory isO(n_vocab)whatever the file says.[a, bc]or[ab, c]depending on which pair ranks lower).quantizationis tested absent,null, partial (and only a non-null block marks the export as quantized for the bf16 policy;null,{}and a Hugging Facequantization_configare 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.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).linearinwhisper/layers.rsand the token embedding are Whisper-local; nothing outsidemodels::whisperbuilds them.WhisperTokenizer::{from_dir, from_tokenizer}has callers only inmodels::whisper.load_tokenizer's new branch fires only formodel_type: "whisper", aftertokenizer.jsonandtokenizer.model, so no other family's resolution order changes.find_tiktoken_file/TiktokenTokenizerare untouched.UnifiedLinear/UnifiedEmbedding/QuantizationArgs/convert_bf16_weightsare used, not changed. TheUsed by:lists ofQuantizationArgsandconvert_bf16_weightsgained Whisper. Whisper does not useconfig_has_quantization_metadata: that predicate is also true for"quantization": nulland for a Hugging Facequantization_config, so the bf16 gate reads the same declared blockWhisperQuantization::from_configreads.tokenizer_from_tiktoken.WhisperModel::loadis kept and extended. The generic "No tokenizer found ..." message is unchanged, because a Whisper directory now gets its own error namingtokenizer.jsonand the rank file it needs.cargo fmt --all -- --checkpasses on the committed tree.Limits
mlx-community/whisper-large-v3-turbo(weights.safetensors),whisper-small-mlx,whisper-large-v3-mlxand the quantizedwhisper-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.whisper-*-asr-*bit: quantizedmodel.safetensors, Hugging Face config fields,tokenizer.json), onlywhisper-tiny-asr-4bitwas run, through the server; its text equalswhisper-tiny-4bit's. It was not compared with a reference on its own.#[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.