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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Support audio input in Studio chat on Apple Silicon (#7699)
Long Yixing2419ff199365
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex e78bf1be8dd..e2324924249 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -1400,11 +1400,13 @@ class InferenceBackend:min_p,max_new_tokens,repetition_penalty,+ use_adapter: Optional[Union[bool, str]] = None,cancel_event = None,) -> Generator[str, None, None]:"""Audio-input (ASR) generation: takes an audio numpy array, streams text.Uses processor.apply_chat_template with audio embedded in messages (Gemma 3n pattern).+ use_adapter: see _apply_adapter_state; None leaves the loaded state alone."""import threadingimport numpy as np@@ -1473,6 +1475,9 @@ class InferenceBackend:def generate_fn():with self._generation_lock:try:+ # As in the text path: apply under the lock so Base-vs-LoRA+ # compare doesn't run the adapter on both sides (None = no-op).+ self._apply_adapter_state(use_adapter)model.generate(**generation_kwargs)except Exception as e:err["msg"] = str(e)diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 2b300a32b1d..b1e1d1afab7 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -16,6 +16,7 @@ from core.inference.chat_template_helpers import (ReasoningChannelNormalizer,normalize_reasoning_snapshots,)+from utils.models.model_config import is_audio_input_typefrom loggers import get_loggerlogger = get_logger(__name__)@@ -97,7 +98,13 @@ def _mlx_vlm_model_config(model):return (configs[0] if configs else None), None-def _render_registered_vlm_prompt(processor, model, messages, num_images):+def _render_registered_vlm_prompt(+ processor,+ model,+ messages,+ num_images,+ num_audios = 0,+):"""Render through mlx-vlm when it declares a formatter for this model."""from mlx_vlm import prompt_utils@@ -113,12 +120,97 @@ def _render_registered_vlm_prompt(processor, model, messages, num_images):messages,add_generation_prompt = True,num_images = num_images,+ num_audios = num_audios,)if isinstance(rendered, str) and rendered.strip():return renderedraise RuntimeError("mlx-vlm's registered renderer returned an empty prompt.")+# Rate the chat route decodes uploads to; mlx-vlm does not resample arrays.+_AUDIO_INPUT_SAMPLE_RATE = 16000+_AUDIO_PROBE_MESSAGES = [{"role": "user", "content": "audio"}]+++def _classify_mlx_audio_type(+ model,+ processor,+ is_vision,+ config_audio_type = None,+):+ """audio_type for the model entry: "audio_vlm" (omni audio input; is_audio+ stays False — it means TTS and redirects in the chat route) or None.++ The checkpoint's own capability comes from unsloth_zoo, which answers it by+ observing whether audio content changes what the processor returns. Two+ things stay here because they are this backend's, not the checkpoint's: the+ waveform arrives at the rate the chat route decodes to, and the prompt is+ rendered through mlx-vlm's registry, where some families accept an audio+ count and silently drop it. The rendered prompt is what the capability call+ probes with, so a family whose marker only its own template emits is judged+ on the real thing.++ This probe speaks for "audio_vlm" and nothing else, so `config_audio_type`+ (the pre-load answer from detect_audio_type) is carried through untouched+ whenever the probe has no standing:++ * a non-vision checkpoint is never asked, so a TTS codec ("snac", "dac",+ "bicodec", "csm") or Whisper keeps the classification it arrived with —+ the worker mirrors this entry over the pre-load config, so returning a+ bare None here would silently strip the chat route's TTS redirect;+ * a probe that could not run (absent or older unsloth_zoo, a raising or+ unrecognised capability result) leaves the pre-load answer standing+ rather than downgrading a model on the strength of a missing+ dependency.++ Only a probe that actually ran and answered may retract "audio_vlm".+ """++ def _probe_says_no():+ # Authoritative for audio_vlm only; anything else passes through.+ return None if config_audio_type == "audio_vlm" else config_audio_type++ if not is_vision or processor is None:+ return config_audio_type+ # All of it inside the guard: a model load must never fail on a probe.+ # BaseException because any escape here aborts the load.+ try:+ from unsloth_zoo.mlx.utils import (+ audio_extractor_sampling_rate,+ audio_input_capability,+ )++ if audio_extractor_sampling_rate(processor) != _AUDIO_INPUT_SAMPLE_RATE:+ logger.info(+ "MLX audio input unavailable: feature extractor is not %d Hz, and "+ "the chat route decodes uploads to that rate.",+ _AUDIO_INPUT_SAMPLE_RATE,+ )+ return _probe_says_no()+ args = (processor, model, _AUDIO_PROBE_MESSAGES, 0)+ marked = _render_registered_vlm_prompt(*args, num_audios = 1)+ if not marked or marked == _render_registered_vlm_prompt(*args, num_audios = 0):+ logger.info(+ "MLX audio input unavailable: mlx-vlm's renderer for this family "+ "places no audio marker."+ )+ return _probe_says_no()+ capability = audio_input_capability(model, processor, texts = marked)+ if capability.capable:+ return "audio_vlm"+ logger.info("MLX audio input unavailable for this model: %s", capability.reason)+ return _probe_says_no()+ except BaseException as exc:+ logger.info(+ "MLX audio capability check did not run (%s); keeping the pre-load "+ "classification %r. Audio input needs an unsloth_zoo release providing "+ "audio_input_capability.",+ type(exc).__name__,+ config_audio_type,+ )+ return config_audio_type++def _count_vlm_images(content):if isinstance(content, list):return sum(_count_vlm_images(item) for item in content)@@ -621,6 +713,12 @@ class MLXInferenceBackend:self._processor = Noneself._is_vlm = False+ _audio_type = _classify_mlx_audio_type(+ model,+ self._processor,+ is_vision,+ config_audio_type = getattr(config, "audio_type", None),+ )self.active_model_name = model_nameself.models[model_name] = {# Per-model token for the native-template fallback (matches transformers).@@ -636,9 +734,10 @@ class MLXInferenceBackend:"base_model": getattr(config, "base_model", None)if getattr(config, "is_lora", False)else None,- "is_audio": False,- "audio_type": None,- "has_audio_input": False,+ # Mirrors utils.models.model_config semantics (is_audio == TTS).+ "is_audio": _audio_type is not None and _audio_type != "audio_vlm",+ "audio_type": _audio_type,+ "has_audio_input": is_audio_input_type(_audio_type),"context_length": runtime_context_length(self._model, max_seq_length),}# Capture chat_template_info for the worker IPC reply and route capability classification.@@ -1177,6 +1276,85 @@ class MLXInferenceBackend:_stream_vlm_snapshots(), chat_target, cancel_event, tools = tools)+ def generate_audio_input_response(+ self,+ messages,+ system_prompt,+ audio_array,+ max_new_tokens = 512,+ use_adapter = None,+ cancel_event = None,+ **_sampler,+ ):+ """Audio-input chat (omni models): waveform in, incremental text deltas+ out (the audio route forwards deltas, unlike the snapshot-diffing+ text/vision paths). Greedy, so the worker's sampler kwargs go unused."""+ entry = self.models.get(self.active_model_name) or {}+ if entry.get("audio_type") != "audio_vlm":+ raise RuntimeError(+ "Audio input is not supported for this model on the MLX backend: "+ "no verified audio-capable tower/processor was detected at load."+ )++ from mlx_vlm import stream_generate as vlm_stream++ # Only the CURRENT user turn may caption the audio; never older history.+ user_text = ""+ for msg in reversed(messages or []):+ if isinstance(msg, dict) and msg.get("role") == "user":+ user_text = content_to_text(msg.get("content") or "").strip()+ break+ if not user_text:+ user_text = "Please transcribe this audio."+ if not system_prompt:+ system_prompt = "You are an assistant that transcribes speech accurately."++ audio_messages = [+ {"role": "system", "content": [{"type": "text", "text": system_prompt}]},+ {"role": "user", "content": [{"type": "audio"}, {"type": "text", "text": user_text}]},+ ]+ prompt = _render_registered_vlm_prompt(+ self._processor,+ self._model,+ audio_messages,+ num_images = 0,+ num_audios = 1,+ )+ if prompt is None:+ raise RuntimeError(+ "mlx-vlm has no registered prompt renderer for this model family; "+ "cannot build an audio prompt."+ )++ logger.info("MLX audio-input generating: prompt_len=%d", len(prompt))+ # Hold the adapter state for the whole stream, as text and vision do,+ # so Base-vs-LoRA compare doesn't run the adapter on both sides.+ with self._generation_lock, _temporary_mlx_adapter_state(self._model, use_adapter):+ final_response = None+ try:+ for response in vlm_stream(+ self._model,+ self._processor,+ prompt,+ audio = [audio_array],+ max_tokens = max_new_tokens,+ temperature = 0.0,+ ):+ final_response = response+ token_text = response.text if hasattr(response, "text") else str(response)+ if token_text:+ yield token_text+ if cancel_event and cancel_event.is_set():+ break+ finally:+ if final_response is not None:+ self.last_generation_stats = _build_generation_stats(+ getattr(final_response, "prompt_tokens", 0),+ getattr(final_response, "prompt_tps", 0.0),+ getattr(final_response, "generation_tokens", 0),+ getattr(final_response, "generation_tps", 0.0),+ )+def generate_with_adapter_control(self,use_adapter = None,diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex 8b6edd66e37..44e30aca189 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -2019,6 +2019,7 @@ class InferenceOrchestrator:min_p: float = 0.0,max_new_tokens: int = 512,repetition_penalty: float = 1.0,+ use_adapter: Optional[Union[bool, str]] = None,cancel_event = None,) -> Generator[str, None, None]:"""Audio input generation (e.g. Gemma 3n) — streams text tokens."""@@ -2033,6 +2034,7 @@ class InferenceOrchestrator:min_p = min_p,max_new_tokens = max_new_tokens,repetition_penalty = repetition_penalty,+ use_adapter = use_adapter,cancel_event = cancel_event,)@@ -2048,6 +2050,7 @@ class InferenceOrchestrator:min_p: float = 0.0,max_new_tokens: int = 512,repetition_penalty: float = 1.0,+ use_adapter: Optional[Union[bool, str]] = None,cancel_event = None,) -> Generator[str, None, None]:"""Shared inner logic for audio input generation (Whisper + ASR)."""@@ -2090,6 +2093,9 @@ class InferenceOrchestrator:"max_new_tokens": max_new_tokens,"repetition_penalty": repetition_penalty,}+ # As in the text path: key stays absent unless the caller selected one.+ if use_adapter is not None:+ cmd["use_adapter"] = use_adapter# Same shared-queue hazard as _generate_inner: see _direct_reader.read_one, drain, release_mailbox = self._direct_reader(request_id)diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex e0d66c5f48d..9a1ec35f0fc 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -431,6 +431,10 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:model_info["context_length"] = int(_context_length)except Exception as _ctx_exc:logger.warning("context_length forward failed: %s", _ctx_exc)+ # Backend post-load audio classification outranks pre-load config.+ model_info.update(+ {k: _entry[k] for k in ("is_audio", "audio_type", "has_audio_input") if k in _entry}+ )# Forward chat_template_info so the parent can classify capabilities.try:_tpl_info = _entry.get("chat_template_info")@@ -709,23 +713,31 @@ def _handle_generate_audio_input(backend, cmd: dict, resp_queue: Any, cancel_eveaudio_type = cmd.get("audio_type")if audio_type == "whisper":+ if not hasattr(backend, "generate_whisper_response"):+ # MLX has no ASR path; report it instead of a raw AttributeError.+ raise RuntimeError("Whisper transcription is not supported on the MLX backend yet.")generator = backend.generate_whisper_response(audio_array = audio_array,cancel_event = cancel_event,)else:- generator = backend.generate_audio_input_response(- messages = cmd.get("messages", []),- system_prompt = cmd.get("system_prompt", ""),- audio_array = audio_array,- temperature = cmd.get("temperature", 0.7),- top_p = cmd.get("top_p", 0.9),- top_k = cmd.get("top_k", 40),- min_p = cmd.get("min_p", 0.0),- max_new_tokens = cmd.get("max_new_tokens", 512),- repetition_penalty = cmd.get("repetition_penalty", 1.0),- cancel_event = cancel_event,- )+ audio_kwargs = {+ "messages": cmd.get("messages", []),+ "system_prompt": cmd.get("system_prompt", ""),+ "audio_array": audio_array,+ "temperature": cmd.get("temperature", 0.7),+ "top_p": cmd.get("top_p", 0.9),+ "top_k": cmd.get("top_k", 40),+ "min_p": cmd.get("min_p", 0.0),+ "max_new_tokens": cmd.get("max_new_tokens", 512),+ "repetition_penalty": cmd.get("repetition_penalty", 1.0),+ "cancel_event": cancel_event,+ }+ # Forward only when present, as the "generate" branch does.+ use_adapter = cmd.get("use_adapter")+ if use_adapter is not None:+ audio_kwargs["use_adapter"] = use_adapter+ generator = backend.generate_audio_input_response(**audio_kwargs)logger.info("Starting audio input generation for request_id=%s", request_id)@@ -960,6 +972,25 @@ def run_inference_process(if _drain_skip_generate(cmd, resp_queue, drain_event):continue_handle_generate(backend, cmd, resp_queue, cancel_event)+ elif cmd_type == "generate_audio_input":+ # Drain discipline as in "generate" (see that branch).+ if _drain_skip_generate(cmd, resp_queue, drain_event):+ continue+ cancel_event.clear()+ if _drain_skip_generate(cmd, resp_queue, drain_event):+ continue+ _handle_generate_audio_input(backend, cmd, resp_queue, cancel_event)+ elif cmd_type == "generate_audio":+ # No TTS here, but codec checkpoints still reach this loop+ # (dispatch is by device). Answer, or the parent waits 120s.+ _send_response(+ resp_queue,+ {+ "type": "audio_error",+ "request_id": cmd.get("request_id"),+ "error": "Text-to-speech is not supported on the MLX backend yet.",+ },+ )elif cmd_type == "share_object":_handle_share_object(backend, cmd, resp_queue)elif cmd_type == "load":@@ -989,6 +1020,18 @@ def run_inference_process()elif cmd_type == "shutdown":return+ else:+ # As in the GPU loop: dropping a command silently costs the+ # caller its whole timeout.+ logger.warning("Unknown MLX command type: %s", cmd_type)+ _send_response(+ resp_queue,+ {+ "type": "error",+ "request_id": cmd.get("request_id"),+ "error": f"Unknown command type: {cmd_type}",+ },+ )except Exception as exc:logger.error("MLX command error (%s): %s", cmd_type, exc)_send_response(diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex c7868cae728..afefc3f0002 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -6401,9 +6401,10 @@ async def _load_model_impl(is_lora = config.is_lora,is_gguf = False,is_local_model = config.is_local,- is_audio = config.is_audio,- audio_type = config.audio_type,- has_audio_input = config.has_audio_input,+ # Post-load classification (mirrored from the worker) wins here.+ is_audio = _model_info.get("is_audio", config.is_audio),+ audio_type = _model_info.get("audio_type", config.audio_type),+ has_audio_input = _model_info.get("has_audio_input", config.has_audio_input),inference = inference_config,requires_trust_remote_code = _requires_rc,supports_reasoning = _sf_flags["supports_reasoning"],@@ -9525,6 +9526,8 @@ async def openai_chat_completions(min_p = payload.min_p,max_new_tokens = _effective_max_tokens(payload) or 2048,repetition_penalty = payload.repetition_penalty,+ # Compare sends audio_base64 and use_adapter in one body.+ use_adapter = payload.use_adapter,cancel_event = cancel_event,)diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex 3d20dd4bcc5..c933a1e9ef9 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -1,5 +1,6 @@# SPDX-License-Identifier: AGPL-3.0-only+import contextlibimport jsonimport subprocessimport sys@@ -1457,3 +1458,357 @@ def test_mlx_prompt_cache_only_stores_verifiable_prefix_coverage(monkeypatch):history.insert("key", list(range(30)), [plain])assert tuple(range(30)) in history._lru.entries["key"]+++# ── Tests: audio-input capability + generation ───────────────────────+++def _audio_model(module_paths = ("audio_tower",), model_type = "gemma3n"):+ """Model stub shaped like a loaded mlx-vlm tree (families nest differently)."""+ return SimpleNamespace(+ config = {"model_type": model_type},+ named_modules = lambda: [(p, object()) for p in module_paths],+ )+++def _audio_processor(sr = 16000, extractor = True):+ fe = {"feature_extractor": SimpleNamespace(sampling_rate = sr)} if extractor else {}+ return SimpleNamespace(tokenizer = _DummyTokenizer(), **fe)+++ ("processor", "renders", "capable", "expected"),+ [+ (_audio_processor(), True, True, "audio_vlm"),+ (_audio_processor(), False, True, None), # our renderer places no marker+ (_audio_processor(), True, False, None), # zoo refuses the checkpoint+ (_audio_processor(extractor = False), True, True, None), # no rate to read+ (_audio_processor(sr = 24000), True, True, None), # route decodes 16 kHz+ (None, True, True, None), # text-only load+ ],+)+def test_mlx_audio_classification(monkeypatch, processor, renders, capable, expected):+ """Studio keeps the rate and rendering gates; the checkpoint answer is zoo's."""+ from core.inference import mlx_inference++ seen = {}++ def _render(+ _proc,+ _model,+ _messages,+ _num_images,+ num_audios = 0,+ ):+ return "P<audio>" if (num_audios and renders) else "P"++ def _capability(+ model,+ proc,+ texts = None,+ ):+ seen["texts"] = texts+ return SimpleNamespace(capable = capable, reason = "stub")++ fake_utils = types.ModuleType("unsloth_zoo.mlx.utils")+ fake_utils.audio_input_capability = _capability+ fake_utils.audio_extractor_sampling_rate = lambda proc: getattr(+ getattr(proc, "feature_extractor", None), "sampling_rate", None+ )+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.utils", fake_utils)+ monkeypatch.setattr(mlx_inference, "_render_registered_vlm_prompt", _render)++ audio_type = mlx_inference._classify_mlx_audio_type(+ _audio_model(), processor, processor is not None+ )+ assert audio_type == expected+ # audio_vlm keeps is_audio (the TTS flag) False → TTS redirect can't fire.+ assert (audio_type is not None and audio_type != "audio_vlm") is False+ # The capability call is probed with OUR rendered prompt.+ if expected == "audio_vlm":+ assert seen["texts"] == "P<audio>"+++ "capability",+ [+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("zoo blew up")),+ lambda *a, **k: (_ for _ in ()).throw(KeyboardInterrupt()),+ lambda *a, **k: SimpleNamespace(), # older/newer API: no .capable+ lambda *a, **k: None,+ ],+)+def test_mlx_audio_classification_survives_a_broken_dependency(monkeypatch, capability):+ """A probe must never fail a model load, whatever the dependency does.++ unsloth_zoo is pinned by a floor, so a version whose capability call raises+ or returns another shape has to degrade to "no audio", not abort the load.+ """+ from core.inference import mlx_inference++ fake_utils = types.ModuleType("unsloth_zoo.mlx.utils")+ fake_utils.audio_input_capability = capability+ fake_utils.audio_extractor_sampling_rate = lambda proc: 16000+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.utils", fake_utils)+ monkeypatch.setattr(+ mlx_inference,+ "_render_registered_vlm_prompt",+ lambda *a, num_audios = 0: "P<audio>" if num_audios else "P",+ )++ assert mlx_inference._classify_mlx_audio_type(_audio_model(), _audio_processor(), True) is None+++def test_mlx_audio_classification_survives_an_absent_dependency(monkeypatch):+ """The import itself is inside the guard: no zoo, no audio, still a load."""+ from core.inference import mlx_inference++ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.utils", None)+ assert mlx_inference._classify_mlx_audio_type(_audio_model(), _audio_processor(), True) is None++[email protected]("codec", ["snac", "dac", "bicodec", "csm", "whisper"])+def test_mlx_audio_classification_keeps_a_classification_it_cannot_judge(monkeypatch, codec):+ """A TTS codec or Whisper is never a vision model, so the probe never runs.++ The worker mirrors this entry over the pre-load config, so returning a bare+ None here would strip is_audio from a codec checkpoint mlx-lm loads happily+ (Orpheus/Llasa/Spark-TTS are plain llama/qwen2), and the chat route's TTS+ redirect would stop firing.+ """+ from core.inference import mlx_inference++ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.utils", None)+ assert (+ mlx_inference._classify_mlx_audio_type(+ _audio_model(),+ None,+ False,+ config_audio_type = codec,+ )+ == codec+ )+++ "capability",+ [+ None, # dependency absent entirely+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("zoo blew up")),+ lambda *a, **k: SimpleNamespace(), # older/newer API: no .capable+ ],+)+def test_mlx_audio_capability_survives_a_probe_that_could_not_run(monkeypatch, capability):+ """An unjudgeable probe defers; it does not retract audio_vlm.++ Every currently released unsloth_zoo lands here, so treating "could not look"+ as a verified negative would hide the upload control the pre-load detection+ had already earned.+ """+ from core.inference import mlx_inference++ if capability is None:+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.utils", None)+ else:+ fake_utils = types.ModuleType("unsloth_zoo.mlx.utils")+ fake_utils.audio_input_capability = capability+ fake_utils.audio_extractor_sampling_rate = lambda proc: 16000+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.utils", fake_utils)+ monkeypatch.setattr(+ mlx_inference,+ "_render_registered_vlm_prompt",+ lambda *a, num_audios = 0: "P<audio>" if num_audios else "P",+ )++ assert (+ mlx_inference._classify_mlx_audio_type(+ _audio_model(),+ _audio_processor(),+ True,+ config_audio_type = "audio_vlm",+ )+ == "audio_vlm"+ )+++def test_mlx_audio_probe_that_answered_no_still_retracts_audio_vlm(monkeypatch):+ """The corrective direction survives: a real negative downgrades."""+ from core.inference import mlx_inference++ fake_utils = types.ModuleType("unsloth_zoo.mlx.utils")+ fake_utils.audio_input_capability = lambda *a, **k: SimpleNamespace(+ capable = False, reason = "processor drops audio"+ )+ fake_utils.audio_extractor_sampling_rate = lambda proc: 16000+ monkeypatch.setitem(sys.modules, "unsloth_zoo.mlx.utils", fake_utils)+ monkeypatch.setattr(+ mlx_inference,+ "_render_registered_vlm_prompt",+ lambda *a, num_audios = 0: "P<audio>" if num_audios else "P",+ )++ assert (+ mlx_inference._classify_mlx_audio_type(+ _audio_model(),+ _audio_processor(),+ True,+ config_audio_type = "audio_vlm",+ )+ is None+ )+++ ("model_type", "places_marker"),+ [+ ("gemma3n", True),+ ("gemma4", True),+ ("phi4mm", True),+ ("minicpmo", True),+ ("qwen3_omni_moe", False),+ ],+)+def test_mlx_vlm_renderer_audio_marker_contract(model_type, places_marker):+ """Pins which mlx-vlm message builders honour num_audios.++ This is the message-construction layer, not the final template render:+ qwen3_omni_moe is registered but its formatter drops audio here, so+ classifying on registry membership alone would advertise a model whose+ prompt can never carry an audio marker.+ """+ pu = pytest.importorskip("mlx_vlm.prompt_utils")+ render = lambda n: pu.apply_chat_template(+ None,+ {"model_type": model_type},+ "hi",+ num_images = 0,+ num_audios = n,+ return_messages = True,+ )+ assert (render(1) != render(0)) is places_marker+++def test_mlx_generate_audio_input_deltas_and_reject(monkeypatch):+ from core.inference import mlx_inference+ from core.inference.mlx_inference import MLXInferenceBackend++ calls = {}++ stats = dict(prompt_tokens = 3, prompt_tps = 1.0, generation_tokens = 3, generation_tps = 1.0)++ def _fake_stream(model, processor, prompt, **kwargs):+ calls["kwargs"] = kwargs+ for text in ("H", "e", "l"):+ yield SimpleNamespace(text = text, **stats)++ def _fake_render(+ processor,+ model,+ messages,+ num_images = 0,+ num_audios = 0,+ ):+ calls["audios"], calls["messages"] = num_audios, messages+ return "P<audio>"++ fake_vlm = types.ModuleType("mlx_vlm")+ fake_vlm.stream_generate = _fake_stream+ monkeypatch.setitem(sys.modules, "mlx_vlm", fake_vlm)+ monkeypatch.setattr(mlx_inference, "_render_registered_vlm_prompt", _fake_render)++ backend = MLXInferenceBackend.__new__(MLXInferenceBackend)+ backend._generation_lock = __import__("threading").Lock()+ backend._model, backend._processor = _audio_model(), _audio_processor()+ backend.active_model_name = "m"+ backend.last_generation_stats = None+ backend.models, audio = {"m": {"audio_type": "audio_vlm"}}, [0.0, 0.1, -0.1]+ turn = [{"role": "user", "content": "what is said?"}]+ args = dict(messages = turn, system_prompt = "", audio_array = audio, max_new_tokens = 64)++ # Deltas (never cumulative "HHeHel"); waveform passthrough; greedy parity.+ assert list(backend.generate_audio_input_response(**args)) == ["H", "e", "l"]+ assert calls["kwargs"]["audio"] == [audio] and calls["kwargs"]["temperature"] == 0.0+ assert calls["audios"] == 1 and backend.last_generation_stats is not None++ # Audio-only current turn → transcribe default, never older-turn text.+ args["messages"] = [+ {"role": "user", "content": "old unrelated question"},+ {"role": "user", "content": [{"type": "audio"}]},+ ]+ list(backend.generate_audio_input_response(**args))+ assert "Please transcribe this audio." in str(calls["messages"])+ assert "old unrelated question" not in str(calls["messages"])++ backend.models["m"]["audio_type"] = None+ with pytest.raises(RuntimeError, match = "not supported .* MLX"):+ next(backend.generate_audio_input_response(**args))+++def test_mlx_audio_input_honors_adapter_selection(monkeypatch):+ """Base-vs-LoRA compare sends audio_base64 and use_adapter in one body.++ The audio stream has to enter _temporary_mlx_adapter_state like the text and+ vision paths, or the base side silently runs the loaded adapter.+ """+ from core.inference import mlx_inference+ from core.inference.mlx_inference import MLXInferenceBackend++ seen = {}++ @contextlib.contextmanager+ def _fake_adapter_state(model, use_adapter):+ seen["use_adapter"] = use_adapter+ seen["entered"] = True+ yield+ seen["exited"] = True++ def _fake_stream(model, processor, prompt, **kwargs):+ seen["inside"] = seen.get("entered") and not seen.get("exited")+ yield SimpleNamespace(+ text = "x",+ prompt_tokens = 1,+ prompt_tps = 1.0,+ generation_tokens = 1,+ generation_tps = 1.0,+ )++ fake_vlm = types.ModuleType("mlx_vlm")+ fake_vlm.stream_generate = _fake_stream+ monkeypatch.setitem(sys.modules, "mlx_vlm", fake_vlm)+ monkeypatch.setattr(+ mlx_inference,+ "_render_registered_vlm_prompt",+ lambda *a, num_images = 0, num_audios = 0: "P<audio>",+ )+ monkeypatch.setattr(mlx_inference, "_temporary_mlx_adapter_state", _fake_adapter_state)++ backend = MLXInferenceBackend.__new__(MLXInferenceBackend)+ backend._generation_lock = __import__("threading").Lock()+ backend._model, backend._processor = _audio_model(), _audio_processor()+ backend.active_model_name = "m"+ backend.last_generation_stats = None+ backend.models = {"m": {"audio_type": "audio_vlm"}}++ list(+ backend.generate_audio_input_response(+ messages = [{"role": "user", "content": "hi"}],+ system_prompt = "",+ audio_array = [0.0],+ max_new_tokens = 8,+ use_adapter = False,+ )+ )+ assert seen["use_adapter"] is False+ # Held for the whole stream, and restored afterwards.+ assert seen["inside"] is True and seen["exited"] is True+++def test_worker_forwards_use_adapter_on_the_audio_command():+ """The wire carries the selection only when the caller set it."""+ import inspect++ from core.inference import worker++ src = inspect.getsource(worker._handle_generate_audio_input)+ assert 'cmd.get("use_adapter")' in src+ assert '"use_adapter"' in srcdiff --git a/studio/backend/tests/test_mlx_worker_audio_commands.py b/studio/backend/tests/test_mlx_worker_audio_commands.pynew file mode 100644index 00000000000..33fcb4d5388--- /dev/null+++ b/studio/backend/tests/test_mlx_worker_audio_commands.py@@ -0,0 +1,120 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The MLX command loop must answer audio commands it cannot serve.++MLXInferenceBackend implements neither TTS nor Whisper, and inference dispatch+is by device rather than by modality, so a codec-TTS or Whisper checkpoint on+Apple Silicon reaches this loop. A dropped command costs the caller its whole+120s deadline (`InferenceOrchestrator.generate_audio_response`), so every+command has to produce a reply.+"""++import queue as _queue+from types import SimpleNamespace++import pytest++from core.inference import worker+++class _CmdQueue:+ """Feeds a fixed script, then behaves like an idle mp.Queue."""++ def __init__(self, cmds):+ self._cmds = list(cmds)++ def get(self, timeout = None):+ if self._cmds:+ return self._cmds.pop(0)+ raise _queue.Empty+++class _RespQueue:+ def __init__(self):+ self.sent = []++ def put(self, item, *a, **k):+ self.sent.append(item)+++def _run_mlx_loop(monkeypatch, cmds):+ """Drive the real MLX command loop with the init short-circuited."""+ from utils.hardware import hardware as _hw++ monkeypatch.setenv("ENVIRONMENT_TYPE", "development")+ monkeypatch.setattr(worker, "is_apple_silicon", lambda: True)+ monkeypatch.setattr(worker, "apply_gpu_ids", lambda *a, **k: None)+ monkeypatch.setattr(worker, "_recorded_local_base", lambda m: (None, False))+ monkeypatch.setattr(worker, "_hub_targets_are_local", lambda *a, **k: True)+ monkeypatch.setattr(worker, "_activate_transformers_version", lambda *a, **k: None)+ monkeypatch.setattr(worker, "_handle_load", lambda *a, **k: None)+ monkeypatch.setattr(_hw, "detect_hardware", lambda *a, **k: None)+ monkeypatch.setattr(_hw, "DEVICE", _hw.DeviceType.MLX)++ import core.inference.mlx_inference as mlx_mod++ monkeypatch.setattr(mlx_mod, "MLXInferenceBackend", lambda *a, **k: SimpleNamespace())++ from loggers.config import LogConfig++ monkeypatch.setattr(LogConfig, "setup_logging", staticmethod(lambda *a, **k: None))++ resp = _RespQueue()+ worker.run_inference_process(+ cmd_queue = _CmdQueue([*cmds, {"type": "shutdown"}]),+ resp_queue = resp,+ cancel_event = SimpleNamespace(is_set = lambda: False, clear = lambda: None, set = lambda: None),+ config = {"model_name": "unsloth/orpheus-3b-0.1-ft"},+ )+ return resp.sent+++def test_mlx_loop_refuses_a_tts_command_instead_of_dropping_it(monkeypatch):+ """`generate_audio` has no MLX handler. Falling through leaves the parent+ blocked for the full 120s deadline with nothing to report."""+ sent = _run_mlx_loop(monkeypatch, [{"type": "generate_audio", "request_id": "r1"}])++ errors = [m for m in sent if m.get("type") in ("audio_error", "error")]+ assert errors, f"the TTS command produced no reply at all: {sent}"+ assert (+ errors[0]["request_id"] == "r1"+ ), "the reply must carry the request_id or the direct-reader mailbox drops it"+ assert "MLX" in errors[0]["error"]+++def test_mlx_loop_reports_an_unknown_command(monkeypatch):+ """Terminal branch, matching the GPU loop: never drop a command silently."""+ sent = _run_mlx_loop(monkeypatch, [{"type": "generate_video", "request_id": "r2"}])++ errors = [m for m in sent if m.get("type") == "error"]+ assert errors, f"the unknown command produced no reply at all: {sent}"+ assert errors[0]["request_id"] == "r2"+ assert "generate_video" in errors[0]["error"]+++def test_whisper_on_a_backend_without_asr_explains_itself(monkeypatch):+ """The bare AttributeError names an internal method; the user needs the reason."""+ backend = SimpleNamespace() # no generate_whisper_response+ resp = _RespQueue()++ worker._handle_generate_audio_input(+ backend,+ {"request_id": "r3", "audio_data": [0.0, 0.0], "audio_type": "whisper"},+ resp,+ SimpleNamespace(is_set = lambda: False),+ )++ errors = [m for m in resp.sent if m.get("type") == "gen_error"]+ assert errors, resp.sent+ assert "not supported on the MLX backend" in errors[0]["error"]+ assert "attribute" not in errors[0]["error"].lower()++[email protected]("cmd_type", ["generate_audio", "generate_video"])+def test_every_mlx_command_gets_exactly_one_reply(monkeypatch, cmd_type):+ """One reply, not zero and not a duplicate that would confuse the mailbox."""+ sent = _run_mlx_loop(monkeypatch, [{"type": cmd_type, "request_id": "r4"}])++ addressed = [m for m in sent if m.get("request_id") == "r4"]+ assert len(addressed) == 1, addresseddiff --git a/studio/backend/tests/test_orchestrator_unload_cancel.py b/studio/backend/tests/test_orchestrator_unload_cancel.pyindex 7963b71e8e8..54f6f2bde99 100644--- a/studio/backend/tests/test_orchestrator_unload_cancel.py+++ b/studio/backend/tests/test_orchestrator_unload_cancel.py@@ -348,17 +348,15 @@ def test_worker_drain_skip_emits_cancelled_gen_done_when_draining():def test_worker_generate_branches_check_drain_before_clearing_cancel():- # Both worker command loops (MLX fast-path + GPU) must consult the drain skip- # before clearing cancel_event and running, so a queued generate can't clear an- # unload-initiated cancel and run the outgoing model to completion. Each loop- # checks the drain twice -- once before the clear and once after -- so a- # drain+cancel pair that lands in the window between them is still caught.+ # Guarded branches check the drain skip before clearing cancel_event and+ # again after, so a queued command can't erase an unload's cancel. Three+ # today: MLX generate + generate_audio_input, and GPU generate.import inspectfrom core.inference import workersrc = inspect.getsource(worker.run_inference_process)- assert src.count("_drain_skip_generate(cmd, resp_queue, drain_event)") == 4+ assert src.count("_drain_skip_generate(cmd, resp_queue, drain_event)") == 6def test_worker_generate_rechecks_drain_after_clearing_cancel():diff --git a/studio/backend/tests/test_pr7699_worker_audio_mirror.py b/studio/backend/tests/test_pr7699_worker_audio_mirror.pynew file mode 100644index 00000000000..c9927129c38--- /dev/null+++ b/studio/backend/tests/test_pr7699_worker_audio_mirror.py@@ -0,0 +1,111 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The MLX post-load audio mirror must not strip a classification the pre-load+config already earned.++`_handle_load` mirrors the backend entry's is_audio/audio_type/has_audio_input+over the pre-load ModelConfig values. The MLX probe only ever speaks for+"audio_vlm", so for every other audio family (snac/csm/bicodec/dac TTS, whisper+ASR) the mirror has to be a no-op. Otherwise the chat route's TTS redirect+(`model_info.get("is_audio") and audio_type != "whisper"`) and the whisper guard+stop firing on Apple Silicon, and the checkpoint is served as a plain text model+that streams raw codec tokens into chat.+"""++import sys+from types import SimpleNamespace++import pytest++from core.inference import worker+from core.inference.mlx_inference import _classify_mlx_audio_type+from utils.models.model_config import is_audio_input_type+++class _Q:+ def __init__(self):+ self.sent = []++ def put(self, item, *a, **k):+ self.sent.append(item)+++def _mlx_entry_for(mc):+ """The entry MLXInferenceBackend.load_model records for a non-vision+ checkpoint, built from the real classifier rather than a hand-written+ expectation."""+ resolved = _classify_mlx_audio_type(+ SimpleNamespace(),+ None,+ mc.is_vision,+ config_audio_type = mc.audio_type,+ )+ return {+ "is_audio": resolved is not None and resolved != "audio_vlm",+ "audio_type": resolved,+ "has_audio_input": is_audio_input_type(resolved),+ }+++def _drive_handle_load(monkeypatch, mc):+ """Run _handle_load against a stub MLX backend, return the emitted model_info."""+ backend = SimpleNamespace(+ device = "mlx",+ active_model_name = mc.identifier,+ models = {mc.identifier: _mlx_entry_for(mc)},+ load_model = lambda **kw: True,+ )++ monkeypatch.setattr(worker, "_build_model_config", lambda cfg: mc)+ monkeypatch.setattr(worker, "_run_security_gates", lambda *a, **k: True)+ monkeypatch.setattr(worker, "_resolve_lora_4bit", lambda mc_, v: False)+ monkeypatch.setattr(worker, "_needs_nemotron_trust", lambda *a, **k: False)++ fake_xet = type(sys)("utils.hf_xet_fallback")+ fake_xet.start_watchdog = lambda **k: SimpleNamespace(set = lambda: None)+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake_xet)++ q = _Q()+ worker._handle_load(backend, {"model_name": mc.identifier}, q)++ loaded = [m for m in q.sent if m.get("type") == "loaded"]+ assert loaded, f"no loaded response: {q.sent}"+ assert loaded[0].get("success"), loaded[0]+ return loaded[0]["model_info"]+++def _mc(audio_type, is_audio, has_audio_input):+ return SimpleNamespace(+ identifier = "unsloth/orpheus-3b-0.1-ft",+ display_name = "orpheus",+ is_vision = False,+ is_lora = False,+ base_model = None,+ is_audio = is_audio,+ audio_type = audio_type,+ has_audio_input = has_audio_input,+ )++[email protected]("codec", ["snac", "csm", "bicodec", "dac"])+def test_tts_classification_survives_the_mlx_post_load_mirror(monkeypatch, codec):+ """A TTS checkpoint is never a vision model, so the audio_vlm probe never+ ran. Mirroring its silence over the config would drop the TTS redirect and+ serve raw codec tokens as chat text."""+ info = _drive_handle_load(monkeypatch, _mc(codec, is_audio = True, has_audio_input = False))++ assert info["audio_type"] == codec, (+ f"MLX load reclassified a {codec} TTS checkpoint as {info['audio_type']!r}; "+ "the chat route's TTS redirect will no longer fire."+ )+ assert info["is_audio"] is True+++def test_whisper_classification_survives_the_mlx_post_load_mirror(monkeypatch):+ """Same for ASR: losing audio_type='whisper' drops both the audio-input+ route and the "Whisper models require audio input" guard."""+ info = _drive_handle_load(monkeypatch, _mc("whisper", is_audio = False, has_audio_input = True))++ assert info["audio_type"] == "whisper"+ assert info["has_audio_input"] is Truediff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex 73ec0a415ea..25a091bb748 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -556,6 +556,7 @@ _VLM_ARCH_SUFFIXES = ("ForVisionText2Text",)_CURATED_REMOTE_VLM_TYPES = frozenset({"phi3_v",+ "phi4mm","llava","llava_next","llava_onevision",diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 5d36597634a..1b09176032b 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -27,6 +27,7 @@ import {reasoningCapsFromLoad,tryAdoptServerActiveModel,} from "../lib/apply-inference-status-to-store";+import { syncModelCapabilities } from "../hooks/use-chat-model-runtime";import {clampReasoningEffortToLevels,getExternalMaxOutputTokens,@@ -1786,19 +1787,13 @@ async function autoLoadSmallestModel(): Promise<{? loadResp.context_length ?? 131072: effectiveMaxSeqLength,});- const autoModel: ChatModelSummary = {- id: loadedModelId,- name: loadResp.display_name ?? candidate.id,- isVision: loadResp.is_vision ?? false,- isLora: loadResp.is_lora ?? false,- isGguf: loadResp.is_gguf ?? candidate.kind === "gguf",- isAudio: loadResp.is_audio ?? false,- audioType: loadResp.audio_type ?? null,- hasAudioInput: loadResp.has_audio_input ?? false,- };- if (!store.models.some((m) => m.id === loadedModelId)) {- store.setModels([...store.models, autoModel]);- }+ // Upsert: a pre-load catalog entry has no backend-derived audio+ // capability, and the load response is the authority on it.+ syncModelCapabilities(loadedModelId, {+ ...loadResp,+ display_name: loadResp.display_name ?? candidate.id,+ is_gguf: loadResp.is_gguf ?? candidate.kind === "gguf",+ });if (candidate.kind === "gguf") {// Keep an explicit Manual+Auto context pin the load just applied (so a// later Apply doesn't silently revert it to auto-fit sizing), mirroringdiff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.tsindex fedb0fa9c46..6c1e07b0fd1 100644--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts@@ -114,7 +114,20 @@ function ensureActiveModelInStoreList(checkpointId: string,): void {const store = useChatRuntimeStore.getState();- if (store.models.some((model) => model.id === checkpointId)) {+ const caps = {+ isAudio: status.is_audio ?? false,+ audioType: status.audio_type ?? null,+ hasAudioInput: status.has_audio_input ?? false,+ };+ const existing = store.models.find((model) => model.id === checkpointId);+ if (existing) {+ // Backend capability outranks catalog metadata, and adoption has no later+ // syncModelCapabilities call. Write only on an actual change.+ if (Object.entries(caps).some(([k, v]) => existing[k as keyof typeof caps] !== v)) {+ store.setModels(+ store.models.map((m) => (m.id === checkpointId ? { ...m, ...caps } : m)),+ );+ }return;}const summary: ChatModelSummary = {@@ -123,9 +136,7 @@ function ensureActiveModelInStoreList(isVision: status.is_vision ?? false,isLora: false,isGguf: status.is_gguf ?? false,- isAudio: status.is_audio ?? false,- audioType: status.audio_type ?? null,- hasAudioInput: status.has_audio_input ?? false,+ ...caps,};store.setModels([...store.models, summary]);}diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex ca6d85b30eb..6b9a5fc5af3 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -75,8 +75,8 @@ def test_autoload_records_backend_loaded_model_identity():autoload = autoload.split("\n try {", 1)[0]assert "const loadedModelId = loadResp.model || modelPath" in autoloadassert "setCheckpoint(loadedModelId," in autoload- assert "id: loadedModelId" in autoload- assert "m.id === loadedModelId" in autoload+ # syncModelCapabilities upserts the summary, matching on the id it is handed.+ assert "syncModelCapabilities(loadedModelId," in autoloaddef test_chat_autoload_toast_is_persistent_and_dismissible():