Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions docs/audio-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,17 @@ 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.

**Supported audio input.** The dedicated Whisper worker currently accepts WAV only. Audio is decoded with the shared WAV reader, converted to mono, and resampled to 16 kHz before the log-mel front-end. MP3 and FLAC are supported by the Phi-4 Multimodal and Gemma 3n chat-model paths described below, but are not converted before they reach the standalone Whisper worker.

**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

Expand Down
2 changes: 1 addition & 1 deletion docs/supported-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
8 changes: 8 additions & 0 deletions scripts/ci/check_env_var_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
186 changes: 186 additions & 0 deletions scripts/whisper_mlx_reference.py
Original file line number Diff line number Diff line change
@@ -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) <<quote>> {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()
6 changes: 4 additions & 2 deletions src/models/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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)?;
Expand Down
4 changes: 3 additions & 1 deletion src/models/sanitize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 16 additions & 4 deletions src/models/whisper/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<MlxArray>,
blocks: Vec<ResidualAttentionBlock>,
ln: LayerNorm,
Expand All @@ -37,8 +37,19 @@ impl TextDecoder {
weights: &WeightMap,
dims: &WhisperDims,
dtype: i32,
quant: WhisperQuantization,
) -> Result<Self, String> {
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))
Expand All @@ -51,6 +62,7 @@ impl TextDecoder {
&format!("decoder.blocks.{i}"),
dims.n_text_head,
true,
quant,
)?);
}

Expand Down
6 changes: 5 additions & 1 deletion src/models/whisper/decoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
4 changes: 3 additions & 1 deletion src/models/whisper/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<UniquePtr<MlxArray>, String> {
weights
Expand Down Expand Up @@ -65,6 +65,7 @@ impl AudioEncoder {
weights: &WeightMap,
dims: &WhisperDims,
dtype: i32,
quant: WhisperQuantization,
) -> Result<Self, String> {
let positional_data = sinusoids(dims.n_audio_ctx as usize, dims.n_audio_state as usize);
let positional =
Expand All @@ -78,6 +79,7 @@ impl AudioEncoder {
&format!("encoder.blocks.{i}"),
dims.n_audio_head,
false,
quant,
)?);
}

Expand Down
Loading
Loading