Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: transcribe with downloaded MLX speech-to-text models on Apple Silicon (#13443)

Daniel Hancf6e3e337206
diff --git a/studio/backend/core/inference/stt_mlx.py b/studio/backend/core/inference/stt_mlx.py
new file mode 100644
index 00000000000..99b4ce196cc
--- /dev/null
+++ b/studio/backend/core/inference/stt_mlx.py
@@ -0,0 +1,58 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Speech-to-text checkpoints the Transformers dictation engine runs through mlx-audio (Apple Silicon,
+which gets mlx-audio with mlx-vlm). Chosen by config model_type: mlx-audio loads both mlx-community
+quants and the original safetensors. Whisper keeps its Transformers path."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+from pathlib import Path
+
+# Families proven end to end through the dictation worker; mlx-audio knows more.
+MLX_STT_MODEL_TYPES = frozenset({"qwen3_asr"})
+
+
+_found = False
+
+
+def mlx_stt_available() -> bool:
+ # Only a hit is kept: the MLX self-repair can install mlx-audio while Studio runs.
+ global _found
+ if not _found:
+ from utils.hardware.hardware import is_apple_silicon
+ try:
+ _found = is_apple_silicon() and importlib.util.find_spec("mlx_audio") is not None
+ except (ImportError, ValueError):
+ _found = False
+ return _found
+
+
+def is_mlx_stt_config(config: object) -> bool:
+ if not isinstance(config, dict):
+ return False
+ model_type = config.get("model_type")
+ if not isinstance(model_type, str) or model_type.strip().lower() not in MLX_STT_MODEL_TYPES:
+ return False
+ # Qwen3-ForcedAligner shares model_type qwen3_asr but needs a transcript to align, not audio alone.
+ thinker = config.get("thinker_config")
+ if isinstance(thinker, dict) and thinker.get("model_type") == "qwen3_forced_aligner":
+ return False
+ return mlx_stt_available()
+
+
+def ships_custom_code(snapshot: Path) -> bool:
+ # mlx-audio loads the tokenizer with trust_remote_code=True, so a repo's own Python would run.
+ snapshot = Path(snapshot)
+ if any(snapshot.rglob("*.py")):
+ return True
+ for name in ("config.json", "tokenizer_config.json", "preprocessor_config.json"):
+ try:
+ data = json.loads((snapshot / name).read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ continue
+ if isinstance(data, dict) and "auto_map" in data:
+ return True
+ return False
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index b90f56a45ef..b4bb238caca 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -345,8 +345,18 @@ def resolve_model_repo(model_id: str) -> str:
def can_translate(model: Optional[str]) -> bool:
"""Whether Whisper's translate task works on this id. The turbo checkpoints were fine-tuned for transcription
- only and answer in the source language when asked to translate."""
- return "turbo" not in (model or DEFAULT_STT_MODEL).lower()
+ only and answer in the source language when asked to translate, as do mlx-audio checkpoints."""
+ if "turbo" in (model or DEFAULT_STT_MODEL).lower():
+ return False
+ from core.inference.stt_mlx import mlx_stt_available
+
+ if not model or model in STT_MODELS or not mlx_stt_available():
+ return True
+ try:
+ snapshot = _find_complete_cached_snapshot(model)
+ except Exception: # noqa: BLE001 - an unreadable id is refused later, by the load
+ return True
+ return snapshot is None or _is_whisper_config(_read_json_object(snapshot / "config.json"))
def _is_whisper_config(config: object) -> bool:
@@ -489,11 +499,16 @@ def _safe_snapshot_for_revision(repo: str, revision: str) -> Optional[Path]:
return candidate_resolved
+def _is_servable_config(config: object) -> bool:
+ from core.inference.stt_mlx import is_mlx_stt_config
+ return _is_whisper_config(config) or is_mlx_stt_config(config)
+
+
def _snapshot_usable(model_id: str, snapshot: Path) -> bool:
if not _snapshot_is_complete(snapshot):
return False
if model_id not in STT_MODELS:
- return _is_whisper_config(_read_json_object(snapshot / "config.json"))
+ return _is_servable_config(_read_json_object(snapshot / "config.json"))
return True
@@ -1435,18 +1450,25 @@ class WhisperSttSidecar:
holding memory that nothing else knows about: dropping it here is what would let this failed
load read as nothing resident.
"""
+ from core.inference.stt_mlx import is_mlx_stt_config
from core.inference.stt_transformers_worker import (
InProcessWhisperEngine,
SttWorkerSpawnError,
WhisperWorker,
)
+ mlx = is_mlx_stt_config(_read_json_object(Path(snapshot_path) / "config.json"))
worker = WhisperWorker()
try:
# start() kills its own child on any failure, including cancellation.
- worker.start(str(snapshot_path), device, _dtype_name(dtype), cancel_event)
+ if mlx:
+ worker.start(
+ str(snapshot_path), device, _dtype_name(dtype), cancel_event, runtime = "mlx"
+ )
+ else:
+ worker.start(str(snapshot_path), device, _dtype_name(dtype), cancel_event)
except SttWorkerSpawnError as exc:
- if device != "cpu":
+ if device != "cpu" or mlx:
raise
logger.warning(
"No dictation worker process could be started (%s); "
@@ -1503,10 +1525,18 @@ class WhisperSttSidecar:
if model_id in STT_MODELS:
return _CachedSttSnapshot(path = snapshot_path, is_multilingual = True)
- if not _is_whisper_config(_read_json_object(snapshot_path / "config.json")):
+ config = _read_json_object(snapshot_path / "config.json")
+ if not _is_servable_config(config):
raise SttModelCompatibilityError(
f"STT model '{model_id}' is not a compatible Transformers Whisper model."
)
+ if not _is_whisper_config(config):
+ from core.inference.stt_mlx import ships_custom_code
+ if ships_custom_code(snapshot_path):
+ raise SttModelCompatibilityError(
+ f"STT model '{model_id}' ships its own code, which dictation does not run."
+ )
+ return _CachedSttSnapshot(path = snapshot_path, is_multilingual = None)
generation_config = _read_json_object(snapshot_path / "generation_config.json")
is_multilingual = generation_config.get("is_multilingual")
if isinstance(is_multilingual, bool):
diff --git a/studio/backend/core/inference/stt_transformers_worker.py b/studio/backend/core/inference/stt_transformers_worker.py
index 07129f8d4f9..cf66290e003 100644
--- a/studio/backend/core/inference/stt_transformers_worker.py
+++ b/studio/backend/core/inference/stt_transformers_worker.py
@@ -170,6 +170,89 @@ def transcribe_window(
return (text[0] if text else ""), consumed
+class _MlxSttModel:
+ def __init__(self, model) -> None:
+ self.model = model
+
+
+def load_mlx_stt(
+ snapshot_path: str,
+ device: str,
+ cancel_event = None,
+) -> _MlxSttModel:
+ from core.inference.stt_mlx import ships_custom_code
+ from core.inference.stt_sidecar import SttModelCompatibilityError
+
+ if ships_custom_code(snapshot_path):
+ raise SttModelCompatibilityError(
+ "This dictation model ships its own code, which is not run."
+ )
+ import mlx.core as mx
+ from mlx_audio.stt import load
+
+ if device == "cpu":
+ mx.set_default_device(mx.cpu)
+ model = load(str(snapshot_path))
+ _raise_if_cancelled(cancel_event)
+ return _MlxSttModel(model)
+
+
+# Whisper language codes -> the names Qwen3-ASR lists in config.support_languages.
+_MLX_LANGUAGE_NAMES = {
+ "ar": "Arabic",
+ "cs": "Czech",
+ "da": "Danish",
+ "de": "German",
+ "el": "Greek",
+ "en": "English",
+ "es": "Spanish",
+ "fa": "Persian",
+ "fi": "Finnish",
+ "fr": "French",
+ "hi": "Hindi",
+ "hu": "Hungarian",
+ "id": "Indonesian",
+ "it": "Italian",
+ "ja": "Japanese",
+ "ko": "Korean",
+ "mk": "Macedonian",
+ "ms": "Malay",
+ "nl": "Dutch",
+ "pl": "Polish",
+ "pt": "Portuguese",
+ "ro": "Romanian",
+ "ru": "Russian",
+ "sv": "Swedish",
+ "th": "Thai",
+ "tl": "Filipino",
+ "tr": "Turkish",
+ "vi": "Vietnamese",
+ "yue": "Cantonese",
+ "zh": "Chinese",
+}
+
+
+def _mlx_language(model, code: Optional[str]) -> Optional[str]:
+ """The checkpoint's own name for a Whisper language code, or None to let it detect one."""
+ name = _MLX_LANGUAGE_NAMES.get(code or "", "").lower()
+ supported = getattr(getattr(model, "config", None), "support_languages", None) or []
+ return next((lang for lang in supported if name and str(lang).lower() == name), None)
+
+
+def transcribe_mlx_window(
+ engine: _MlxSttModel,
+ pcm: bytes,
+ language: Optional[str] = None,
+) -> tuple:
+ import numpy as np
+
+ segment = np.frombuffer(pcm, dtype = np.float32)
+ hint = _mlx_language(engine.model, language)
+ result = engine.model.generate(segment, **({"language": hint} if hint else {}))
+ text = getattr(result, "text", result)
+ return (text if isinstance(text, str) else ""), len(segment)
+
+
def _complete_segment_indices(tokens: list, generation_config) -> tuple:
# whisper's long-form seek decodes a segment cut off by the window again from the next window
timestamp_begin = generation_config.no_timestamps_token_id + 1
@@ -271,7 +354,18 @@ def run_stt_worker(
continue
kind = command.get("type")
try:
- if kind == "load":
+ if kind == "load" and command.get("runtime") == "mlx":
+ engine = load_mlx_stt(command["snapshot_path"], command["device"], cancel_event)
+ _send(
+ resp_queue,
+ {
+ "type": "loaded",
+ "device": command["device"],
+ "is_multilingual": None,
+ "supports_timestamps": False,
+ },
+ )
+ elif kind == "load":
model, processor = load_whisper(
command["snapshot_path"],
command["device"],
@@ -297,13 +391,20 @@ def run_stt_worker(
if engine is None:
raise SttWorkerError("The dictation worker has no model loaded.")
cancellable = bool(command.get("cancellable"))
- text, consumed = transcribe_window(
- engine[0],
- engine[1],
- command["audio"],
- command.get("generate_kwargs") or {},
- cancel_event if cancellable else None,
- )
+ if isinstance(engine, _MlxSttModel):
+ text, consumed = transcribe_mlx_window(
+ engine,
+ command["audio"],
+ (command.get("generate_kwargs") or {}).get("language"),
+ )
+ else:
+ text, consumed = transcribe_window(
+ engine[0],
+ engine[1],
+ command["audio"],
+ command.get("generate_kwargs") or {},
+ cancel_event if cancellable else None,
+ )
if cancellable and cancel_event.is_set():
from core.inference.stt_sidecar import SttTranscriptionCancelledError
raise SttTranscriptionCancelledError("Transcription cancelled.")
@@ -369,6 +470,7 @@ class WhisperWorker:
device: str,
dtype_name: str,
cancel_event: Optional[threading.Event] = None,
+ runtime: Optional[str] = None,
) -> None:
"""Spawn the child and load the model, or raise having killed it."""
from utils.hf_cache_settings import child_environment_for_spawn, get_hf_cache_paths
@@ -444,14 +546,15 @@ class WhisperWorker:
"STT worker started (pid=%s) for %s on %s", _spawned_proc.pid, snapshot_path, device
)
try:
- self._send(
- {
- "type": "load",
- "snapshot_path": str(snapshot_path),
- "device": device,
- "dtype": dtype_name,
- }
- )
+ load_command = {
+ "type": "load",
+ "snapshot_path": str(snapshot_path),
+ "device": device,
+ "dtype": dtype_name,
+ }
+ if runtime is not None:
+ load_command["runtime"] = runtime
+ self._send(load_command)
response = self._await("loaded", _LOAD_TIMEOUT_SECONDS, cancel_event, "load")
except BaseException as exc:
# Classify before close(), which reaps the child and drops the handle.
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index bf0cb3310f9..133058c70f3 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -1019,6 +1019,22 @@ def _is_whisper_model_config(config: object) -> bool:
)
+def _is_mlx_stt_model_config(config: object) -> bool:
+ try:
+ from core.inference.stt_mlx import is_mlx_stt_config
+ return is_mlx_stt_config(config)
+ except Exception: # noqa: BLE001 -- a classification failure never hides a row
+ return False
+
+
+def _ships_custom_code(snapshot: Path) -> bool:
+ try:
+ from core.inference.stt_mlx import ships_custom_code
+ return ships_custom_code(snapshot)
+ except Exception: # noqa: BLE001 -- unreadable: dictation refuses it at load anyway
+ return True
+
+
def _read_model_card_frontmatter(path: Path) -> dict:
try:
text = path.read_text(encoding = "utf-8")
@@ -1052,6 +1068,9 @@ def _cached_model_local_metadata(repo_path: Path, snapshot: Optional[Path] = Non
config = _read_json_object(snapshot / "config.json")
if _is_whisper_model_config(config):
result["_hidden_stt"] = True
+ elif _is_mlx_stt_model_config(config) and not _ships_custom_code(snapshot):
+ result["_hidden_stt"] = True
+ result["_mlx_stt"] = True
tts_audio_type = detect_local_tts_audio_type(snapshot)
if tts_audio_type is not None:
result["_tts_audio_type"] = tts_audio_type
@@ -1145,6 +1164,7 @@ def _scan_cached_models(
else _cached_model_local_metadata(repo_path, load_snapshot)
)
is_whisper_stt = local_metadata.pop("_hidden_stt", False)
+ is_mlx_stt = local_metadata.pop("_mlx_stt", False)
tts_audio_type = local_metadata.pop("_tts_audio_type", None)
# Scoped to the row's snapshot, so an incomplete newer revision cannot flip can_chat.
download_partial = hf_cache_scan.is_snapshot_partial(
@@ -1185,7 +1205,11 @@ def _scan_cached_models(
else _cached_row_task(repo_info, gguf = False, selected = load_snapshot)
)
)
- if is_whisper_stt:
+ if is_mlx_stt:
+ # The Transcribe picker admits non-Whisper speech rows by this name, on a Mac only.
+ local_metadata["pipeline_tag"] = "automatic-speech-recognition"
+ local_metadata["library_name"] = "mlx-audio"
+ elif is_whisper_stt:
local_metadata["pipeline_tag"] = "automatic-speech-recognition"
local_metadata["library_name"] = "transformers"
tags = list(local_metadata.get("tags", []))
diff --git a/studio/backend/tests/test_stt_mlx.py b/studio/backend/tests/test_stt_mlx.py
new file mode 100644
index 00000000000..f6b57470e40
--- /dev/null
+++ b/studio/backend/tests/test_stt_mlx.py
@@ -0,0 +1,414 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""mlx-audio speech-to-text checkpoints on the Transformers dictation engine (Apple Silicon)."""
+
+import json
+import queue
+import sys
+import threading
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+
+import core.inference.stt_mlx as stt_mlx
+import core.inference.stt_sidecar as stt_sidecar_module
+import core.inference.stt_transformers_worker as worker_module
+from core.inference.stt_sidecar import SttModelCompatibilityError, WhisperSttSidecar
+
+_REPO = "mlx-community/Qwen3-ASR-0.6B-8bit"
+_QWEN3_ASR_CONFIG = {"model_type": "qwen3_asr", "quantization": {"group_size": 64, "bits": 8}}
+
+_FAKE_MLX_AUDIO = """
+from pathlib import Path
+from types import SimpleNamespace
+
+
+class _Model:
+ config = SimpleNamespace(support_languages = ["Chinese", "English", "French"])
+
+ def __init__(self, path):
+ self.repo_dir = Path(path).parts[-3]
+
+ def generate(self, audio, language = None):
+ said = f" in {language}" if language else ""
+ return SimpleNamespace(text = f"heard {len(audio)} samples from {self.repo_dir}{said}")
+
+def load(path):
+ if "broken" in str(path):
+ raise RuntimeError("mlx-audio could not read this checkpoint")
+ return _Model(str(path))
+"""
+
+_FAKE_MLX_CORE = """
+cpu = "cpu"
+default_device = None
+
+def set_default_device(device):
+ global default_device
+ default_device = device
+"""
+
+
+def mlx_host(monkeypatch):
+ monkeypatch.setattr(stt_mlx, "mlx_stt_available", lambda: True)
+
+
+def _write_snapshot(hub, repo, config):
+ snapshot = hub / f"models--{repo.replace('/', '--')}" / "snapshots" / ("c" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "config.json").write_text(json.dumps(config))
+ (snapshot / "preprocessor_config.json").write_text("{}")
+ (snapshot / "vocab.json").write_text("{}")
+ (snapshot / "merges.txt").write_text("")
+ (snapshot / "model.safetensors").write_bytes(b"w" * 8)
+ return snapshot
+
+
+def _install_fake_mlx(tmp_path, monkeypatch):
+ """Importable stand-ins for mlx and mlx-audio, on a path a spawned child also sees."""
+ root = tmp_path / "fake_site"
+ (root / "mlx").mkdir(parents = True)
+ (root / "mlx" / "__init__.py").write_text("")
+ (root / "mlx" / "core.py").write_text(_FAKE_MLX_CORE)
+ (root / "mlx_audio" / "stt").mkdir(parents = True)
+ (root / "mlx_audio" / "__init__.py").write_text("")
+ (root / "mlx_audio" / "stt" / "__init__.py").write_text(_FAKE_MLX_AUDIO)
+ monkeypatch.syspath_prepend(str(root))
+ for name in ("mlx", "mlx.core", "mlx_audio", "mlx_audio.stt"):
+ monkeypatch.delitem(sys.modules, name, raising = False)
+
+
+def test_mlx_stt_is_unavailable_off_apple_silicon(monkeypatch):
+ import utils.hardware.hardware as hardware
+
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)
+ monkeypatch.setattr(stt_mlx, "_found", False)
+ assert stt_mlx.mlx_stt_available() is False
+ assert stt_mlx.is_mlx_stt_config(_QWEN3_ASR_CONFIG) is False
+
+
+def test_mlx_stt_needs_mlx_audio_installed(monkeypatch):
+ import importlib.util
+
+ import utils.hardware.hardware as hardware
+
+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: True)
+ monkeypatch.setattr(stt_mlx, "_found", False)
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ assert stt_mlx.mlx_stt_available() is False
+ # The repair installs it later in the same process: the next check sees it, then keeps it.
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: object())
+ assert stt_mlx.mlx_stt_available() is True
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ assert stt_mlx.mlx_stt_available() is True
+
+
+def test_only_listed_families_and_never_whisper_go_to_mlx(mlx_host):
+ assert stt_mlx.is_mlx_stt_config(_QWEN3_ASR_CONFIG) is True
+ assert stt_mlx.is_mlx_stt_config({"model_type": "Qwen3_ASR"}) is True
+ assert stt_mlx.is_mlx_stt_config({"model_type": "whisper"}) is False
+ assert stt_mlx.is_mlx_stt_config({"model_type": "qwen3"}) is False
+ assert stt_mlx.is_mlx_stt_config({}) is False
+ aligner = {"model_type": "qwen3_asr", "thinker_config": {"model_type": "qwen3_forced_aligner"}}
+ assert stt_mlx.is_mlx_stt_config(aligner) is False
+ asr = {"model_type": "qwen3_asr", "thinker_config": {"model_type": "qwen3_asr"}}
+ assert stt_mlx.is_mlx_stt_config(asr) is True
+ assert stt_mlx.is_mlx_stt_config(None) is False
+
+
+def test_a_cached_mlx_checkpoint_is_downloaded_only_where_mlx_audio_runs(monkeypatch, tmp_path):
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ snapshot = _write_snapshot(tmp_path / "hub", _REPO, _QWEN3_ASR_CONFIG)
+
+ monkeypatch.setattr(stt_mlx, "mlx_stt_available", lambda: False)
+ assert stt_sidecar_module.is_model_downloaded(_REPO) is False
+ with pytest.raises(Exception):
+ WhisperSttSidecar(keep_alive_seconds = 0)._ensure_model_downloaded(_REPO)
+
+ monkeypatch.setattr(stt_mlx, "mlx_stt_available", lambda: True)
+ assert stt_sidecar_module.is_model_downloaded(_REPO) is True
+ cached = WhisperSttSidecar(keep_alive_seconds = 0)._ensure_model_downloaded(_REPO)
+ assert cached.path == snapshot.resolve()
+ assert cached.is_multilingual is None
+
+
+def test_a_non_whisper_non_mlx_checkpoint_is_still_refused(mlx_host, monkeypatch, tmp_path):
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ snapshot = _write_snapshot(tmp_path / "hub", "someone/wav2vec2", {"model_type": "wav2vec2"})
+ assert stt_sidecar_module.is_model_downloaded("someone/wav2vec2") is False
+ # Past the cache lookup, the compatibility check refuses it too.
+ monkeypatch.setattr(
+ stt_sidecar_module, "_find_complete_cached_snapshot", lambda _model: snapshot
+ )
+ with pytest.raises(SttModelCompatibilityError):
+ WhisperSttSidecar(keep_alive_seconds = 0)._ensure_model_downloaded("someone/wav2vec2")
+
+
+ ("config", "runtime"), [(_QWEN3_ASR_CONFIG, "mlx"), ({"model_type": "whisper"}, None)]
+)
+def test_build_model_asks_the_worker_for_mlx_only_for_an_mlx_checkpoint(
+ mlx_host, monkeypatch, tmp_path, config, runtime
+):
+ (tmp_path / "config.json").write_text(json.dumps(config))
+ starts = []
+
+ class FakeWorker:
+ def start(self, *args, **kwargs):
+ starts.append((args, kwargs))
+
+ monkeypatch.setattr(worker_module, "WhisperWorker", FakeWorker)
+ WhisperSttSidecar(keep_alive_seconds = 0)._build_model(
+ str(tmp_path), "mps", "float32", threading.Event()
+ )
+ ((args, kwargs),) = starts
+ assert args[:2] == (str(tmp_path), "mps")
+ assert kwargs == ({"runtime": runtime} if runtime else {})
+
+
+def test_an_mlx_checkpoint_never_falls_back_to_the_in_process_whisper_engine(
+ mlx_host, monkeypatch, tmp_path
+):
+ (tmp_path / "config.json").write_text(json.dumps(_QWEN3_ASR_CONFIG))
+
+ class NoSpawn:
+ def start(self, *args, **kwargs):
+ raise worker_module.SttWorkerSpawnError("sandboxed")
+
+ monkeypatch.setattr(worker_module, "WhisperWorker", NoSpawn)
+ with pytest.raises(worker_module.SttWorkerSpawnError):
+ WhisperSttSidecar(keep_alive_seconds = 0)._build_model(
+ str(tmp_path), "cpu", "float32", threading.Event()
+ )
+
+
+def test_child_loads_and_transcribes_an_mlx_checkpoint(monkeypatch, tmp_path):
+ _install_fake_mlx(tmp_path, monkeypatch)
+ monkeypatch.setattr(
+ worker_module,
+ "load_whisper",
+ lambda *_a, **_k: pytest.fail("Whisper must not load an mlx checkpoint"),
+ )
+ cmd_queue: queue.Queue = queue.Queue()
+ resp_queue: queue.Queue = queue.Queue()
+ for command in (
+ {
+ "type": "load",
+ "snapshot_path": "/hub/models--a--b/snapshots/x",
+ "device": "cpu",
+ "dtype": "float32",
+ "runtime": "mlx",
+ },
+ {
+ "type": "transcribe",
+ "audio": np.zeros(320, dtype = np.float32).tobytes(),
+ "generate_kwargs": {"language": "en", "num_beams": 5},
+ "cancellable": True,
+ },
+ {"type": "shutdown"},
+ ):
+ cmd_queue.put(command)
+ worker_module.run_stt_worker(
+ cmd_queue = cmd_queue, resp_queue = resp_queue, cancel_event = threading.Event()
+ )
+ responses = []
+ while not resp_queue.empty():
+ responses.append(resp_queue.get_nowait())
+
+ assert responses == [
+ {"type": "loaded", "device": "cpu", "is_multilingual": None, "supports_timestamps": False},
+ {"type": "text", "text": "heard 320 samples from models--a--b in English", "consumed": 320},
+ {"type": "shutdown_ack"},
+ ]
+ import mlx.core
+
+ assert mlx.core.default_device == "cpu"
+
+
+def spawned_mlx_host(mlx_host, monkeypatch, tmp_path):
+ """A real spawned worker with mlx-audio stood in; torch and PyAV are not needed on that path."""
+ _install_fake_mlx(tmp_path, monkeypatch)
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ monkeypatch.setitem(sys.modules, "torch", SimpleNamespace(float32 = "float32"))
+ monkeypatch.setattr(stt_sidecar_module, "ensure_stt_available", lambda: None)
+ monkeypatch.setattr(stt_sidecar_module, "_pick_device", lambda _p = None: ("cpu", "float32"))
+ return tmp_path / "hub"
+
+
+def test_a_spawned_worker_transcribes_a_cached_mlx_checkpoint_end_to_end(spawned_mlx_host):
+ """The real spawn child, the sidecar's windowing and residency."""
+ _write_snapshot(spawned_mlx_host, _REPO, _QWEN3_ASR_CONFIG)
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ try:
+ with sidecar._lock:
+ text = sidecar._transcribe_decoded(
+ _REPO, np.zeros(45 * 16000, dtype = np.float32), {"language": "en"}
+ )
+ assert sidecar.loaded_model == _REPO
+ finally:
+ sidecar.unload()
+
+ # 45 s of silence: one 30 s window, then the 15 s rest.
+ assert text == (
+ "heard 480000 samples from models--mlx-community--Qwen3-ASR-0.6B-8bit in English "
+ "heard 240000 samples from models--mlx-community--Qwen3-ASR-0.6B-8bit in English"
+ )
+ assert sidecar.loaded_model is None
+
+
+def test_an_mlx_load_failure_reaches_the_caller(spawned_mlx_host):
+ _write_snapshot(spawned_mlx_host, "someone/broken-asr", _QWEN3_ASR_CONFIG)
+
+ sidecar = WhisperSttSidecar(keep_alive_seconds = 0)
+ with pytest.raises(Exception, match = "mlx-audio could not read this checkpoint"):
+ sidecar.load("someone/broken-asr")
+ assert sidecar.loaded_model is None
+
+
+def test_the_inventory_lists_a_cached_mlx_checkpoint_as_speech_to_text(mlx_host, tmp_path):
+ from hub.services.models.cache_inventory import (
+ _cache_inventory_fields,
+ _cached_model_local_metadata,
+ )
+
+ snapshot = _write_snapshot(tmp_path / "hub", _REPO, _QWEN3_ASR_CONFIG)
+ metadata = _cached_model_local_metadata(snapshot.parent.parent, snapshot)
+ assert metadata.get("_hidden_stt") is True
+ assert metadata.get("_mlx_stt") is True
+ fields = _cache_inventory_fields(_REPO, "safetensors", stt_only = True)
+ assert fields["capabilities"]["can_chat"] is False
+
+
+def test_the_inventory_leaves_the_checkpoint_alone_off_a_mac(monkeypatch, tmp_path):
+ from hub.services.models.cache_inventory import _cached_model_local_metadata
+
+ monkeypatch.setattr(stt_mlx, "mlx_stt_available", lambda: False)
+ snapshot = _write_snapshot(tmp_path / "hub", _REPO, _QWEN3_ASR_CONFIG)
+ metadata = _cached_model_local_metadata(snapshot.parent.parent, snapshot)
+ assert "_hidden_stt" not in metadata
+ assert "_mlx_stt" not in metadata
+
+
[email protected]("on_mac", [True, False])
+def test_the_cache_scan_row_is_speech_to_text_only_on_a_mac(monkeypatch, tmp_path, on_mac):
+ from hub.services.models import cache_inventory
+
+ monkeypatch.setattr(stt_mlx, "mlx_stt_available", lambda: on_mac)
+ snapshot = _write_snapshot(tmp_path / "hub", _REPO, _QWEN3_ASR_CONFIG)
+ (snapshot / "README.md").write_text("---\nlibrary_name: mlx-audio\n---\n", encoding = "utf-8")
+ repo_path = snapshot.parent.parent
+ files = [
+ SimpleNamespace(file_name = name, size_on_disk = size, blob_path = None)
+ for name, size in (("config.json", 12), ("model.safetensors", 90_000_000))
+ ]
+ repo = SimpleNamespace(
+ repo_id = _REPO,
+ repo_type = "model",
+ repo_path = repo_path,
+ revisions = [SimpleNamespace(files = files)],
+ )
+ monkeypatch.setattr(
+ cache_inventory, "all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan, "is_snapshot_partial", lambda *_a, **_k: False
+ )
+ monkeypatch.setattr(cache_inventory, "_cached_model_snapshot_path", lambda _path: snapshot)
+
+ (row,) = cache_inventory._scan_cached_models(active_hub_cache = repo_path.parent)
+
+ if on_mac:
+ assert row["task"] == "automatic-speech-recognition"
+ assert row["library_name"] == "mlx-audio"
+ assert row["capabilities"]["can_chat"] is False
+ else:
+ assert row["task"] != "automatic-speech-recognition"
+
+
+ "plant",
+ [
+ lambda snap: (snap / "tokenization_evil.py").write_text("raise SystemExit"),
+ lambda snap: (snap / "tokenizer_config.json").write_text(
+ json.dumps({"auto_map": {"AutoTokenizer": ["evil.Tok", None]}})
+ ),
+ lambda snap: (snap / "config.json").write_text(
+ json.dumps({**_QWEN3_ASR_CONFIG, "auto_map": {"AutoConfig": "other/repo--x.C"}})
+ ),
+ ],
+)
+def test_a_checkpoint_that_ships_its_own_code_is_refused_before_any_load(
+ mlx_host, monkeypatch, tmp_path, plant
+):
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ plant(_write_snapshot(tmp_path / "hub", _REPO, _QWEN3_ASR_CONFIG))
+ with pytest.raises(SttModelCompatibilityError, match = "ships its own code"):
+ WhisperSttSidecar(keep_alive_seconds = 0)._ensure_model_downloaded(_REPO)
+
+
+def test_the_child_refuses_custom_code_even_if_asked(tmp_path, monkeypatch):
+ (tmp_path / "custom.py").write_text("")
+ monkeypatch.setitem(sys.modules, "mlx_audio", None)
+ with pytest.raises(stt_sidecar_module.SttModelCompatibilityError):
+ worker_module.load_mlx_stt(str(tmp_path), "cpu")
+
+
+def test_an_mlx_checkpoint_cannot_translate(mlx_host, monkeypatch, tmp_path):
+ monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ _write_snapshot(tmp_path / "hub", _REPO, _QWEN3_ASR_CONFIG)
+ _write_snapshot(tmp_path / "hub", "someone/whisper-x", {"model_type": "whisper"})
+
+ assert stt_sidecar_module.can_translate(_REPO) is False
+ assert stt_sidecar_module.can_translate("someone/whisper-x") is True
+ assert stt_sidecar_module.can_translate("small") is True
+ assert stt_sidecar_module.can_translate("large-v3-turbo") is False
+
+
+def test_translation_is_untouched_off_a_mac(monkeypatch, tmp_path):
+ monkeypatch.setattr(stt_mlx, "mlx_stt_available", lambda: False)
+ monkeypatch.setattr(
+ stt_sidecar_module,
+ "_find_complete_cached_snapshot",
+ lambda _m: pytest.fail("no cache lookup off a Mac"),
+ )
+ assert stt_sidecar_module.can_translate(_REPO) is True
+
+
+ ("code", "hint"),
+ [("fr", "French"), ("en", "English"), ("sw", None), (None, None), ("zz", None), ("ja", None)],
+)
+def test_the_chosen_language_reaches_mlx_only_when_the_checkpoint_knows_it(code, hint):
+ seen = {}
+
+ class Model:
+ config = SimpleNamespace(support_languages = ["English", "French"])
+
+ def generate(self, audio, **kwargs):
+ seen.update(kwargs)
+ return SimpleNamespace(text = "ok")
+
+ engine = worker_module._MlxSttModel(Model())
+ pcm = np.zeros(160, dtype = np.float32).tobytes()
+ assert worker_module.transcribe_mlx_window(engine, pcm, code) == ("ok", 160)
+ assert seen == ({"language": hint} if hint else {})
+
+
+def test_the_inventory_does_not_offer_a_checkpoint_that_ships_its_own_code(mlx_host, tmp_path):
+ from hub.services.models.cache_inventory import _cached_model_local_metadata
+
+ snapshot = _write_snapshot(tmp_path / "hub", _REPO, _QWEN3_ASR_CONFIG)
+ (snapshot / "tokenization_custom.py").write_text("")
+ metadata = _cached_model_local_metadata(snapshot.parent.parent, snapshot)
+ assert "_mlx_stt" not in metadata
+ assert "_hidden_stt" not in metadata
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
index beb437618f2..6c114b49e3f 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/audio-picker-policy.ts
@@ -255,6 +255,21 @@ export function audioPickIsRoutable({
});
}
+/** The backend names on-device speech checkpoints it runs through mlx-audio by that library, Mac only. */
+export function macMlxSttRowIsRunnable({
+ isMac,
+ isStt,
+ isGguf,
+ libraryName,
+}: {
+ isMac: boolean;
+ isStt: boolean;
+ isGguf: boolean;
+ libraryName?: string | null;
+}): boolean {
+ return isMac && isStt && !isGguf && libraryName?.toLowerCase() === "mlx-audio";
+}
+
/** The macOS audio runtime can execute TTS only through llama.cpp GGUF. Curated families may
* expose a non-GGUF canonical row because Audio resolves it to a published GGUF sibling. */
export function macTtsHubRowIsRunnable({
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index dbb7733dc22..27bb762a6f0 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -172,6 +172,7 @@ import {
curatedAudioInventoryTask,
filesystemRowsSupportedForTask,
localAudioRowIsUndecodableGguf,
+ macMlxSttRowIsRunnable,
macTtsHubRowIsRunnable,
nativeAudioCheckpointIsLoadable,
shouldDiscoverCommunityModels,
@@ -4345,7 +4346,7 @@ export function HubModelPicker({
(isUnslothRepoId(c.repo_id) && !c.single_file) ||
((c.task === "automatic-speech-recognition" ||
c.task === "text-to-speech") &&
- communityAudioRowIsRunnable({
+ (communityAudioRowIsRunnable({
isStt: c.task === "automatic-speech-recognition",
isTts: c.task === "text-to-speech",
isGguf: false,
@@ -4353,7 +4354,13 @@ export function HubModelPicker({
tags: c.tags,
libraryName: c.library_name,
audioType: c.audio_type,
- }) &&
+ }) ||
+ macMlxSttRowIsRunnable({
+ isMac,
+ isStt: c.task === "automatic-speech-recognition",
+ isGguf: false,
+ libraryName: c.library_name,
+ })) &&
macTtsHubRowIsRunnable({
isMac,
isTts: c.task === "text-to-speech",
@@ -4654,6 +4661,12 @@ export function HubModelPicker({
meta.source === "exported" ||
meta.source === "local",
...(hubEvidenceById.get(id) ?? {}),
+ }) &&
+ !macMlxSttRowIsRunnable({
+ isMac,
+ isStt: pickedTask === "automatic-speech-recognition",
+ isGguf: Boolean(meta.isGguf || meta.ggufFilename),
+ libraryName: cachedModels.find((c) => c.repo_id === id)?.library_name,
})
) {
// Loading it here would evict the chat model for a repo neither surface can run.
@@ -4677,7 +4690,7 @@ export function HubModelPicker({
}
onSelectProp(id, meta);
},
- [task, diffusionTaskById, hubEvidenceById, navigateToPage, onSelectProp],
+ [task, diffusionTaskById, hubEvidenceById, navigateToPage, onSelectProp, isMac, cachedModels],
);
// Fine-tuned models for the On Device section: flat, query-filtered, newest first.
diff --git a/studio/frontend/tests/audio-picker-policy.test.ts b/studio/frontend/tests/audio-picker-policy.test.ts
index ab9d802b5d0..3b08b47369f 100644
--- a/studio/frontend/tests/audio-picker-policy.test.ts
+++ b/studio/frontend/tests/audio-picker-policy.test.ts
@@ -12,6 +12,7 @@ import {
curatedAudioInventoryMatches,
curatedAudioInventoryTask,
filesystemRowsSupportedForTask,
+ macMlxSttRowIsRunnable,
macTtsHubRowIsRunnable,
localAudioRowIsUndecodableGguf,
speechGgufIsUndecodable,
@@ -361,6 +362,30 @@ test("cached runnable community audio survives the Audio on-device trust gate",
);
});
+test("an on-device mlx-audio speech-to-text row is runnable on a Mac only", () => {
+ const row = { isStt: true, isGguf: false, libraryName: "mlx-audio" };
+ assert.equal(macMlxSttRowIsRunnable({ ...row, isMac: true }), true);
+ assert.equal(macMlxSttRowIsRunnable({ ...row, isMac: false }), false);
+ assert.equal(macMlxSttRowIsRunnable({ ...row, isMac: true, isStt: false }), false);
+ assert.equal(macMlxSttRowIsRunnable({ ...row, isMac: true, isGguf: true }), false);
+ assert.equal(
+ macMlxSttRowIsRunnable({ ...row, isMac: true, libraryName: "transformers" }),
+ false,
+ );
+ assert.equal(macMlxSttRowIsRunnable({ ...row, isMac: true, libraryName: null }), false);
+ // Only the cached on-device gate admits them: a Hub row cannot be downloaded for this engine.
+ assert.match(
+ pickerSource,
+ /communityAudioRowIsRunnable\(\{[\s\S]*\}\) \|\|\s*macMlxSttRowIsRunnable\(\{[\s\S]*isMac,[\s\S]*isStt: c\.task === "automatic-speech-recognition",[\s\S]*libraryName: c\.library_name/,
+ );
+ // The Chat-to-Audio handoff asks the same gate, on the cached row's library.
+ assert.match(
+ pickerSource,
+ /\.\.\.\(hubEvidenceById\.get\(id\) \?\? \{\}\),\s*\}\) &&\s*!macMlxSttRowIsRunnable\(\{[\s\S]*libraryName: cachedModels\.find\(\(c\) => c\.repo_id === id\)\?\.library_name,\s*\}\)\s*\) \{/,
+ );
+ assert.equal(pickerSource.split("macMlxSttRowIsRunnable(").length - 1, 2);
+});
+
test("Chat-to-Audio handoff preserves the live Hub task", () => {
// pickedTask, not meta.pipelineTag: a cached row carries no tag, so ASR would read as TTS.
assert.match(