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
Studio: fix GGUF image-capability detection for API auto-switch and audio-only projectors (#8807)
Long Yixing11f59ebb30e6
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 6f3b337465e..8c5f923a8b1 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -3791,6 +3791,8 @@ class LlamaCppBackend:# Audio INPUT capability (distinct from _is_audio, which is TTS output).self._has_audio_input: bool = Falseself._mmproj_has_audio: bool = False # clip.has_audio_encoder, set at load+ # clip.has_vision_encoder, set at load; True keeps an undeclared projector capable.+ self._mmproj_accepts_image: bool = True# Monotonic timestamp set in _kill_process; read by load_model# to decide whether to wait for the VRAM reclaim to finish.self._last_kill_monotonic: float = 0.0@@ -3829,7 +3831,9 @@ class LlamaCppBackend:@propertydef is_vision(self) -> bool:- return self._is_vision+ """Whether this model takes image input; ``_is_vision`` only records that a+ projector was attached, which happens for audio input too."""+ return self._is_vision and self._mmproj_accepts_image@propertydef is_diffusion(self) -> bool:@@ -14584,17 +14588,19 @@ class LlamaCppBackend:# LLAMA_ARG_MMPROJ misses launch_mmproj_path, so probe that too,# but never one the unpinnable guard just dropped.self._mmproj_has_audio = False- _audio_probe = launch_mmproj_path or (+ self._mmproj_accepts_image = True+ _mmproj_probe = launch_mmproj_path or ("" if _pv_mmproj_unpinnable else (os.environ.get("LLAMA_ARG_MMPROJ") or ""))- if launch_mmproj_path or os.path.isfile(_audio_probe):+ if launch_mmproj_path or os.path.isfile(_mmproj_probe):try:- from utils.models.gguf_metadata import (- read_mmproj_audio_capability,- )- self._mmproj_has_audio = bool(read_mmproj_audio_capability(_audio_probe))+ from utils.models.gguf_metadata import mmproj_capabilities++ has_audio, accepts_image = mmproj_capabilities(_mmproj_probe)+ self._mmproj_has_audio = has_audio+ self._mmproj_accepts_image = accepts_imageexcept Exception as e:- logger.debug(f"mmproj audio-capability read failed: {e}")+ logger.debug(f"mmproj capability read failed: {e}")# Gated like every other optional flag, but failing OPEN: these# are emitted on every launch, so an unreadable --help keeps@@ -17431,6 +17437,7 @@ class LlamaCppBackend:self._audio_probed = Falseself._has_audio_input = Falseself._mmproj_has_audio = False+ self._mmproj_accepts_image = Trueself._port = Noneself._healthy = Falseself._context_length = Nonediff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex 50c1ee73763..a66c39e0938 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Optionalfrom loggers import get_logger+from utils.models.gguf_metadata import mmproj_accepts_imagelogger = get_logger(__name__)_GGUF_MODEL_INFO_TIMEOUT_SECONDS = 5.0@@ -925,9 +926,11 @@ def list_local_gguf_variants(if h3_bundle_repo and not _is_selectable_repo_gguf(h3_bundle_repo, file.name):continueif is_mmproj_filename(file.name):- # A projector llama.cpp cannot open is not vision support.+ # An empty projector is an interrupted download; an audio-only one is not vision.try:- has_vision = has_vision or file.stat().st_size > 0+ has_vision = has_vision or (+ file.stat().st_size > 0 and mmproj_accepts_image(str(file))+ )except OSError:passcontinuediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 1a502467df5..919a87a9448 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -4830,18 +4830,31 @@ def _switch_model_for_payload(payload) -> str:return payload.model if "model" in payload.model_fields_set else _RELOAD_ONLY_MODEL-def _target_is_vision(load_path: str) -> bool:+def _target_is_vision(+ load_path: str,+ gguf_variant: Optional[str] = None,+ need_image: bool = True,+) -> bool:# A local GGUF's vision capability is its companion mmproj, a filesystem check# (no model load). Matches the loaded backend's is_vision, so rejecting a swap- # here can't differ from the post-load guard. Thread the ambient HF token so the- # probe keeps the capability-probe invariant (the resolver only yields local- # paths, where the token is unused, but the rule requires it regardless).+ # here can't differ from the post-load guard, hence the quant. An audio request+ # needs that projector too but not a vision tower, so it asks with need_image+ # False. Thread the ambient HF token so the probe keeps the capability-probe+ # invariant (the resolver only yields local paths, where the token is unused,+ # but the rule requires it regardless).from utils.models.model_config import is_vision_modeltry:# Deliberately unguarded: the resolver only yields local paths, so this returns# from the mmproj filesystem branch without touching the hub. A reachability# probe here would add seconds per request and prevent nothing.- return bool(is_vision_model(load_path, hf_token = os.environ.get("HF_TOKEN")))+ return bool(+ is_vision_model(+ load_path,+ hf_token = os.environ.get("HF_TOKEN"),+ gguf_variant = gguf_variant,+ require_image = need_image,+ )+ )except Exception as exc:# Detection failure: don't block the swap, let the load decide.logger.debug("auto-switch: vision probe failed for %s: %s", load_path, exc)@@ -5476,6 +5489,7 @@ async def _maybe_auto_switch_model(current_subject: str,*,require_vision: bool = False,+ require_image: bool = True,) -> None:"""Load a downloaded local GGUF named by an OpenAI request when auto-switch is on.@@ -5484,7 +5498,9 @@ async def _maybe_auto_switch_model(compat); a miss only reaches the network when auto-download is also on, andeven then only for ``namespace/name`` ids. ``require_vision`` rejects a swapto a text-only target before it runs, so an image request can't evict the- resident vision model only to 400 afterwards.+ resident vision model only to 400 afterwards; ``require_image`` is what makes+ that rejection modality-aware, since an audio request needs the projector but+ not a vision tower."""from utils.openai_auto_switch_settings import (get_openai_auto_switch_enabled,@@ -5637,7 +5653,7 @@ async def _maybe_auto_switch_model(if (require_visionand resolved is not None- and not await asyncio.to_thread(_target_is_vision, target_id)+ and not await asyncio.to_thread(_target_is_vision, target_id, variant, require_image)):raise HTTPException(status_code = 400,@@ -12648,6 +12664,7 @@ async def openai_chat_completions(# Parse once and reuse below._pre_parsed = None_needs_vision = False+ _needs_image = Falseif _automatic_model_load_may_run():_pre_parsed = _extract_content_parts(payload.messages)if not _pre_parsed[1]:@@ -12745,16 +12762,18 @@ async def openai_chat_completions(if payload.stream and _wants_multiple_choices(payload):_raise_unsupported_n("streaming chat completions")# Audio input rides the same companion-mmproj projector as vision, so a- # text-only target can't serve it either; guard both before the switch.- _needs_vision = (- bool(_pre_parsed[2]) or _request_has_image(payload) or bool(payload.audio_base64)- )+ # text-only target can't serve it either; guard both before the switch. An+ # audio-only request asks for the projector alone, since an audio model's+ # projector carries no vision tower.+ _needs_image = bool(_pre_parsed[2]) or _request_has_image(payload)+ _needs_vision = _needs_image or bool(payload.audio_base64)await _maybe_auto_switch_model(_switch_model_for_payload(payload),request,current_subject,require_vision = _needs_vision,+ require_image = _needs_image,)llama_backend = get_llama_cpp_backend()diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex 3bc9d822d7f..881d1814c65 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -1122,6 +1122,73 @@ def test_a_projector_at_the_snapshot_root_serves_a_quant_in_a_subdirectory(monkeassert row["has_vision"] is True+def test_an_audio_only_projector_in_the_cache_is_not_vision(monkeypatch, tmp_path):+ """ultravox, Voxtral and Qwen3-ASR ship a projector for audio input, so reading the row's+ badge off the projector's presence claims an image button the model cannot honour."""+ import struct++ def _projector(path: Path, *keys: str) -> None:+ """A minimal GGUF declaring the given ``clip.has_*_encoder`` bools, no tensors."""+ kvs = b"".join(+ struct.pack("<Q", len(key))+ + key.encode()+ + struct.pack("<I", 7)+ + struct.pack("<?", True)+ for key in keys+ )+ path.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, len(keys)) + kvs)++ active = tmp_path / "active"+ repo_dir = active / "models--Org--Audio"+ snapshot = repo_dir / "snapshots" / ("d" * 40)+ snapshot.mkdir(parents = True)+ (snapshot / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)+ _projector(snapshot / "mmproj-F16.gguf", "clip.has_audio_encoder")+ (repo_dir / "refs").mkdir(parents = True)+ (repo_dir / "refs" / "main").write_text("d" * 40, encoding = "utf-8")++ repo = _repo(+ "Org/Audio",+ [],+ repo_dir,+ revisions = [+ SimpleNamespace(+ files = [+ _file("Model-Q4_K_M.gguf", 256),+ _file("mmproj-F16.gguf", 256),+ ],+ snapshot_path = snapshot,+ )+ ],+ )+ monkeypatch.setattr(+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]+ )+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)+ monkeypatch.setattr(+ "hub.utils.gguf.iter_hf_cache_snapshots", lambda repo_id, root = None: [snapshot]+ )++ def _row():+ return {+ c["repo_id"]: c+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))[+ "cached"+ ]+ }["Org/Audio"]++ assert _row()["has_vision"] is False++ # Control: the same snapshot, with a vision tower declared, is vision support.+ _projector(snapshot / "mmproj-F16.gguf", "clip.has_vision_encoder")+ assert _row()["has_vision"] is True++ # A projector serving both modalities declares both (Qwen2.5-Omni), so the row cannot be+ # read off the audio claim alone.+ _projector(snapshot / "mmproj-F16.gguf", "clip.has_audio_encoder", "clip.has_vision_encoder")+ assert _row()["has_vision"] is True++def test_vision_is_read_from_the_cache_root_holding_the_row(monkeypatch, tmp_path):"""The same repo can sit in several cache roots, and the row describes one copy: a duplicateelsewhere is a download the load never reaches, so it cannot answer for this row's projector."""diff --git a/studio/backend/tests/test_gguf_image_capability.py b/studio/backend/tests/test_gguf_image_capability.pynew file mode 100644index 00000000000..da44ac9b3a9--- /dev/null+++ b/studio/backend/tests/test_gguf_image_capability.py@@ -0,0 +1,92 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A loaded GGUF reports image input only when its projector has a vision tower.++An mmproj is attached for audio input too (ultravox, Voxtral, Qwen3-ASR), so reporting+``_is_vision`` as image support offers an image button the model cannot honour and sends+the image to llama-server instead of returning the typed 400.+"""++from __future__ import annotations++import inspect+import sys+import types as _types+from pathlib import Path++import pytest+++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)+++def _stub_modules_ctx():+ """Stub only the heavy deps llama_cpp imports that are not already available."""+ from unittest.mock import patch++ _loggers_stub = _types.ModuleType("loggers")+ _loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+ _structlog_stub = _types.ModuleType("structlog")+ _structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")+ _httpx_stub = _types.ModuleType("httpx")+ for _exc in ("ConnectError", "TimeoutException", "ReadTimeout", "ReadError"):+ setattr(_httpx_stub, _exc, type(_exc, (Exception,), {}))+ _httpx_stub.Timeout = type("T", (), {"__init__": lambda s, *a, **k: None})+ _httpx_stub.Client = type(+ "C",+ (),+ {+ "__init__": lambda s, **kw: None,+ "__enter__": lambda s: s,+ "__exit__": lambda s, *a: None,+ },+ )+ overrides = {+ name: stub+ for name, stub in (+ ("loggers", _loggers_stub),+ ("structlog", _structlog_stub),+ ("httpx", _httpx_stub),+ )+ if name not in sys.modules+ }+ return patch.dict(sys.modules, overrides)+++def _backend():+ with _stub_modules_ctx():+ from core.inference.llama_cpp import LlamaCppBackend+ return LlamaCppBackend()+++ "accepts_image, expected",+ [(True, True), (False, False)],+)+def test_projector_modality_decides_reported_image_input(accepts_image, expected):+ backend = _backend()+ backend._is_vision = True # a projector is attached, which is what the launch asks+ backend._mmproj_accepts_image = accepts_image+ assert backend.is_vision is expected+++def test_a_model_without_a_projector_takes_no_image():+ backend = _backend()+ backend._is_vision = False+ backend._mmproj_accepts_image = True # the default for "nothing was read"+ assert backend.is_vision is False+++def test_the_load_reads_both_capabilities_from_the_projector_it_attaches():+ """The read cannot be reached without spawning llama-server, so pin it in the source:+ both flags must come from one call on the same probed path, or the pair can describe+ two files."""+ with _stub_modules_ctx():+ from core.inference.llama_cpp import LlamaCppBackend+ src = inspect.getsource(LlamaCppBackend.load_model)+ assert "has_audio, accepts_image = mmproj_capabilities(_mmproj_probe)" in src+ assert "self._mmproj_has_audio = has_audio" in src+ assert "self._mmproj_accepts_image = accepts_image" in srcdiff --git a/studio/backend/tests/test_gguf_metadata.py b/studio/backend/tests/test_gguf_metadata.pyindex ec0330ce054..872103f20eb 100644--- a/studio/backend/tests/test_gguf_metadata.py+++ b/studio/backend/tests/test_gguf_metadata.py@@ -12,6 +12,7 @@ from typing import Iterable, Mappingfrom utils.models.gguf_metadata import (is_mmproj_by_metadata,+ mmproj_accepts_image,pairing_score,read_gguf_context_length,read_gguf_general_metadata,@@ -414,3 +415,42 @@ def test_mmproj_audio_capability_missing_or_non_gguf(tmp_path: Path):junk = tmp_path / "garbage.gguf"junk.write_bytes(b"not a gguf header at all")assert read_mmproj_audio_capability(str(junk)) is None+++# --- mmproj_accepts_image ----------------------------------------------+++def _projector(tmp_path: Path, **bools) -> str:+ return str(+ _write_synthetic_gguf(+ tmp_path / "mmproj.gguf", {"general.type": "mmproj"}, extra_bools = bools+ )+ )+++def test_accepts_image_when_vision_declared(tmp_path: Path):+ """A projector declaring vision accepts images, whatever it says about audio."""+ assert mmproj_accepts_image(_projector(tmp_path, **{"clip.has_vision_encoder": True})) is True+++def test_audio_only_projector_is_not_a_vision_tower(tmp_path: Path):+ """ultravox / Voxtral / Qwen3-ASR: audio declared, vision key absent."""+ assert mmproj_accepts_image(_projector(tmp_path, **{"clip.has_audio_encoder": True})) is False+++def test_dual_projector_still_accepts_images(tmp_path: Path):+ """Qwen2.5-Omni declares both, which is what makes a lone audio claim evidence."""+ p = _projector(tmp_path, **{"clip.has_vision_encoder": True, "clip.has_audio_encoder": True})+ assert mmproj_accepts_image(p) is True+++def test_projector_declaring_neither_stays_image_capable(tmp_path: Path):+ """An unreadable or older convert must not be refused: the load decides."""+ assert mmproj_accepts_image(_projector(tmp_path)) is True+ assert mmproj_accepts_image(str(tmp_path / "nope.gguf")) is True+++def test_declared_audio_false_is_not_an_audio_claim(tmp_path: Path):+ """A vision projector writing audio=False is still a vision tower."""+ p = _projector(tmp_path, **{"clip.has_vision_encoder": True, "clip.has_audio_encoder": False})+ assert mmproj_accepts_image(p) is Truediff --git a/studio/backend/tests/test_gguf_variants_local_resolution.py b/studio/backend/tests/test_gguf_variants_local_resolution.pyindex d37816d7e10..27e08585b2e 100644--- a/studio/backend/tests/test_gguf_variants_local_resolution.py+++ b/studio/backend/tests/test_gguf_variants_local_resolution.py@@ -72,6 +72,27 @@ def test_direct_gguf_file_in_marked_dir_still_lists_siblings(in_tmp_cwd):assert all(v.downloaded for v in response.variants)+def test_an_audio_only_projector_does_not_flag_vision(in_tmp_cwd):+ """The picker badge reads this flag, and ultravox / Voxtral / Qwen3-ASR ship a+ projector for audio input only."""+ import struct++ (in_tmp_cwd / "config.json").write_text("{}")+ (in_tmp_cwd / "model-Q4_K_M.gguf").write_bytes(b"GGUF")+ key = "clip.has_audio_encoder"+ (in_tmp_cwd / "mmproj-F16.gguf").write_bytes(+ struct.pack("<IIQQ", 0x46554747, 3, 0, 1)+ + struct.pack("<Q", len(key))+ + key.encode()+ + struct.pack("<I", 7)+ + struct.pack("<?", True)+ )++ response = _variants(os.fspath(in_tmp_cwd / "model-Q4_K_M.gguf"))+ assert [v.quant for v in response.variants] == ["Q4_K_M"]+ assert response.has_vision is False++@pytest.mark.parametrize("relpath",[diff --git a/studio/backend/tests/test_metal_paravirtual_guard.py b/studio/backend/tests/test_metal_paravirtual_guard.pyindex 4390cb05796..eab6ce2787f 100644--- a/studio/backend/tests/test_metal_paravirtual_guard.py+++ b/studio/backend/tests/test_metal_paravirtual_guard.py@@ -630,16 +630,17 @@ def test_a_text_only_gguf_is_unaffected_either_way():def test_the_drop_precedes_everything_the_projector_feeds():"""launch_mmproj_path drives the --mmproj flag, the mmproj VRAM budget and the- audio-encoder probe, so clearing it later would launch a projector the guard believes- it dropped (or offer audio input that is gone)."""+ capability probe, so clearing it later would launch a projector the guard believes+ it dropped (or offer audio or image input that is gone)."""src = _load_model_source()gate_at = src.index("_pv_mmproj_unpinnable = bool(")assert gate_at < src.index('cmd.extend(["--mmproj", launch_mmproj_path])')assert gate_at < src.index("self._mmproj_vram_bytes(launch_mmproj_path)")# The probe reads launch_mmproj_path, or the env projector only if the gate dropped- # nothing, so both the gate and that choice precede it.- assert gate_at < src.index("_audio_probe = launch_mmproj_path or (")- assert gate_at < src.index("read_mmproj_audio_capability(_audio_probe)")+ # nothing, so both the gate and that choice precede it. It answers audio input and+ # image input alike, so a dropped projector cannot leave either advertised.+ assert gate_at < src.index("_mmproj_probe = launch_mmproj_path or (")+ assert gate_at < src.index("mmproj_capabilities(_mmproj_probe)")# ...and the session flag the frontend reads follows the same variable.assert "self._is_vision = effective_is_vision" in srcdiff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex c8e423fc781..c46eb17250c 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -3142,7 +3142,11 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):# Codex P2: a chat request carrying audio_base64 must guard the target before the# switch -- audio rides the same companion mmproj as vision -- so a text-only# target can't be loaded and evict the working audio model. Assert the handler- # flags require_vision so the hook's multimodal probe runs.+ # flags require_vision so the hook's multimodal probe runs, and that it asks for+ # the projector alone: an audio model's projector carries no vision tower, so+ # requiring one would refuse the very models that serve the request.+ from models.inference import ChatMessage, ImageContentPart, ImageUrl+class _Reached(Exception):pass@@ -3154,8 +3158,9 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):subject,*,require_vision = False,+ require_image = True,):- captured["require_vision"] = require_vision+ captured.update(require_vision = require_vision, require_image = require_image)raise _Reached()monkeypatch.setattr(settings, "get_openai_auto_switch_enabled", lambda: True)@@ -3163,7 +3168,18 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):payload = _chat_request(model = "org/B-GGUF", audio_base64 = "AAAA")with pytest.raises(_Reached):asyncio.run(inference_route.openai_chat_completions(payload, object(), "tester"))- assert captured["require_vision"] is True+ assert captured == {"require_vision": True, "require_image": False}++ # An image in the same request does need the vision tower.+ img = ImageContentPart(type = "image_url", image_url = ImageUrl(url = "data:image/png;base64,AAAA"))+ payload = _chat_request(+ model = "org/B-GGUF",+ audio_base64 = "AAAA",+ messages = [ChatMessage(role = "user", content = [img])],+ )+ with pytest.raises(_Reached):+ asyncio.run(inference_route.openai_chat_completions(payload, object(), "tester"))+ assert captured == {"require_vision": True, "require_image": True}def test_completions_rejects_object_prompt_before_switch(monkeypatch):@@ -3277,7 +3293,7 @@ def test_require_vision_rejects_text_target_before_switch(monkeypatch):backend = backend,recorder = rec,)- monkeypatch.setattr(inference_route, "_target_is_vision", lambda _p: False)+ monkeypatch.setattr(inference_route, "_target_is_vision", lambda _p, _v = None, _i = True: False)with pytest.raises(HTTPException) as exc:asyncio.run(inference_route._maybe_auto_switch_model(@@ -3298,13 +3314,101 @@ def test_require_vision_allows_vision_target(monkeypatch):backend = backend,recorder = rec,)- monkeypatch.setattr(inference_route, "_target_is_vision", lambda _p: True)+ monkeypatch.setattr(inference_route, "_target_is_vision", lambda _p, _v = None, _i = True: True)asyncio.run(inference_route._maybe_auto_switch_model("org/B-GGUF", object(), "t", require_vision = True))assert len(rec.calls) == 1 # vision target still switches+def test_an_audio_only_target_still_switches_for_an_audio_request(monkeypatch, tmp_path):+ # End to end through the real probe: a Voxtral-style snapshot whose projector+ # declares audio and no vision tower must still be swapped in for an audio+ # request, or the model that can serve it is exactly the one refused.+ import struct++ key = "clip.has_audio_encoder"+ (tmp_path / "Voxtral-Mini-3B-Q4_K_M.gguf").write_bytes(b"\0" * 32)+ (tmp_path / "mmproj-F16.gguf").write_bytes(+ struct.pack("<IIQQ", 0x46554747, 3, 0, 1)+ + struct.pack("<Q", len(key))+ + key.encode()+ + struct.pack("<I", 7)+ + struct.pack("<?", True)+ )+ backend = _FakeBackend("org/A-GGUF")+ rec = _LoadRecorder(backend)+ _wire(+ monkeypatch,+ enabled = True,+ resolves_to = (str(tmp_path), "Q4_K_M", "org/B-GGUF"),+ backend = backend,+ recorder = rec,+ )+ asyncio.run(+ inference_route._maybe_auto_switch_model(+ "org/B-GGUF", object(), "t", require_vision = True, require_image = False+ )+ )+ assert len(rec.calls) == 1+++def test_require_vision_probes_the_quant_the_load_will_open(monkeypatch):+ # The resolver hands the gate a directory plus the quant to load, so the probe must+ # see the same pair the load does (#8772).+ backend = _FakeBackend("org/A-GGUF")+ rec = _LoadRecorder(backend)+ _wire(+ monkeypatch,+ enabled = True,+ resolves_to = ("/cache/snap", "UD-Q4_K_XL", "org/B-GGUF"),+ backend = backend,+ recorder = rec,+ )+ probed: list[tuple] = []+ monkeypatch.setattr(+ inference_route,+ "_target_is_vision",+ lambda path, variant = None, need_image = True: probed.append((path, variant, need_image))+ or True,+ )+ asyncio.run(+ inference_route._maybe_auto_switch_model("org/B-GGUF", object(), "t", require_vision = True)+ )+ assert probed == [("/cache/snap", "UD-Q4_K_XL", True)]+++def test_an_audio_request_is_not_refused_for_want_of_a_vision_tower(tmp_path):+ # ultravox / Voxtral / Qwen3-ASR serve audio through a projector with no vision+ # tower, so gating their swap on image capability would 400 a request they can+ # serve, for as long as the model is not already resident.+ import struct++ key = "clip.has_audio_encoder"+ (tmp_path / "Voxtral-Mini-3B-Q4_K_M.gguf").write_bytes(b"\0" * 32)+ (tmp_path / "mmproj-F16.gguf").write_bytes(+ struct.pack("<IIQQ", 0x46554747, 3, 0, 1)+ + struct.pack("<Q", len(key))+ + key.encode()+ + struct.pack("<I", 7)+ + struct.pack("<?", True)+ )++ assert inference_route._target_is_vision(str(tmp_path), None, False) is True+ assert inference_route._target_is_vision(str(tmp_path), None, True) is False+++def test_target_is_vision_reads_a_subdir_quants_projector(tmp_path):+ # End to end through the real probe: a repo filing every quant under a subdir has no+ # weight file at the snapshot root for the root-level detector to find.+ variant_dir = tmp_path / "UD-Q4_K_XL"+ variant_dir.mkdir()+ (variant_dir / "Qwen3-VL-235B-UD-Q4_K_XL.gguf").write_bytes(b"\0" * 32)+ (tmp_path / "mmproj-F32.gguf").write_bytes(b"\0" * 32)++ assert inference_route._target_is_vision(str(tmp_path), "UD-Q4_K_XL") is True++def test_require_vision_ignores_reload_stash(monkeypatch):# The reload-stash path restores the model the request was already using; the# modality check applies only to an explicit resolver target, not a restore.@@ -3318,7 +3422,7 @@ def test_require_vision_ignores_reload_stash(monkeypatch):monkeypatch.setattr(kw, "_inflight", 0)monkeypatch.setattr(kw, "_last_unloaded_model", ("/cache/snap/A", "Q4_K_M", "org/A-GGUF"))monkeypatch.setattr(- inference_route, "_target_is_vision", lambda _p: False+ inference_route, "_target_is_vision", lambda _p, _v = None, _i = True: False) # would reject if used# 404 because the restored A is not the requested B, whose quant makes it a real reference.with pytest.raises(HTTPException):diff --git a/studio/backend/tests/test_vision_cache.py b/studio/backend/tests/test_vision_cache.pyindex 688cd526648..aa68f2e5e5c 100644--- a/studio/backend/tests/test_vision_cache.py+++ b/studio/backend/tests/test_vision_cache.py@@ -13,6 +13,7 @@ pattern used by ``detect_audio_type()``. These tests verify:* Exceptions that fall back to False are cached."""+import structimport sysimport types as _typesfrom pathlib import Path@@ -141,10 +142,17 @@ class TestVisionCacheSubprocessPath:# --- Local GGUF capability path ---+def _projector_declaring(path: Path, key: str) -> Path:+ """A minimal GGUF carrying one ``clip.has_*_encoder`` bool, no tensors."""+ kv = struct.pack("<Q", len(key)) + key.encode() + struct.pack("<I", 7) + struct.pack("<?", True)+ path.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + kv)+ return path++class TestLocalGgufVisionDetection:- """``detect_mmproj_file`` skips a zero-byte projector as an interrupted download, so every- projector fixture here is written non-empty; the byte content itself is never read (there is- no GGUF header, so pairing falls back to the filename)."""+ """Every projector fixture is non-empty, since ``detect_mmproj_file`` skips a zero-byte one+ as an interrupted download; those built by ``_projector_declaring`` also carry a header,+ because the capability they assert is read from it."""@patch("utils.models.model_config._is_vision_model_subprocess",@@ -231,6 +239,88 @@ class TestLocalGgufVisionDetection:assert config.gguf_mmproj_file == str(mmproj.resolve())mock_subprocess.assert_not_called()+ def test_an_audio_only_projector_is_not_a_vision_model(self, tmp_path):+ """ultravox / Voxtral / Qwen3-ASR ship a projector for audio input; offering images+ for it is a capability the model does not have."""+ model = tmp_path / "Voxtral-Mini-3B-2507-Q4_K_M.gguf"+ model.write_bytes(b"\0" * 32)+ _projector_declaring(tmp_path / "mmproj-F16.gguf", "clip.has_audio_encoder")++ assert is_vision_model(str(model)) is False++ def test_a_projector_declaring_vision_is_still_a_vision_model(self, tmp_path):+ model = tmp_path / "Qwen3-VL-8B-Instruct-Q4_K_M.gguf"+ model.write_bytes(b"\0" * 32)+ _projector_declaring(tmp_path / "mmproj-F16.gguf", "clip.has_vision_encoder")++ assert is_vision_model(str(model)) is True++ @patch(+ "utils.models.model_config._is_vision_model_subprocess",+ side_effect = AssertionError("GGUF must not use Transformers vision detection"),+ )+ def test_named_quant_in_a_subdir_reads_the_snapshot_projector(self, mock_subprocess, tmp_path):+ """A repo whose quants all live under a per-quant subdir has no weight file at the+ snapshot root, which is the only place the root-level detector looks (#8772)."""+ variant_dir = tmp_path / "UD-Q4_K_XL"+ variant_dir.mkdir()+ (variant_dir / "Qwen3-VL-235B-UD-Q4_K_XL-00001-of-00002.gguf").write_bytes(b"\0" * 32)+ (variant_dir / "Qwen3-VL-235B-UD-Q4_K_XL-00002-of-00002.gguf").write_bytes(b"\0" * 32)+ (tmp_path / "mmproj-F32.gguf").write_bytes(b"\0" * 32)++ assert is_vision_model(str(tmp_path), gguf_variant = "UD-Q4_K_XL") is True+ mock_subprocess.assert_not_called()++ @patch(+ "utils.models.model_config._is_vision_model_subprocess",+ side_effect = AssertionError("GGUF must not use Transformers vision detection"),+ )+ def test_named_quant_in_a_subdir_without_a_projector_is_text_only(+ self, mock_subprocess, tmp_path+ ):+ variant_dir = tmp_path / "UD-Q4_K_XL"+ variant_dir.mkdir()+ (variant_dir / "Qwen3-235B-UD-Q4_K_XL.gguf").write_bytes(b"\0" * 32)++ assert is_vision_model(str(tmp_path), gguf_variant = "UD-Q4_K_XL") is False+ mock_subprocess.assert_not_called()++ @pytest.mark.parametrize(+ "variant, expected",+ [("Q4_K_M", True), ("Q8_0", False)],+ )+ def test_each_quant_answers_what_a_load_of_that_quant_would_see(+ self, tmp_path, variant, expected+ ):+ """One quant keeps the projector beside it and the other does not, so a probe that+ reads any quant of the directory answers one of them wrongly."""+ variant_dir = tmp_path / "Q4_K_M"+ variant_dir.mkdir()+ (variant_dir / "Qwen3-VL-8B-Instruct-Q4_K_M.gguf").write_bytes(b"\0" * 32)+ (variant_dir / "mmproj-F16.gguf").write_bytes(b"\0" * 32)+ (tmp_path / "Qwen3-VL-8B-Instruct-Q8_0.gguf").write_bytes(b"\0" * 32)++ config = ModelConfig.from_identifier(str(tmp_path), gguf_variant = variant)++ assert config is not None+ assert config.is_vision is expected+ assert is_vision_model(str(tmp_path), gguf_variant = variant) is expected++ @patch("utils.models.model_config._is_vision_model_uncached", return_value = False)+ def test_a_quant_that_is_not_on_disk_is_not_answered_by_another_one(+ self, mock_uncached, tmp_path+ ):+ """A load of an absent quant resolves no GGUF at all, so neither may the probe: the+ projector beside the quant that IS on disk says nothing about the one asked for."""+ (tmp_path / "Qwen3-VL-8B-Instruct-Q8_0.gguf").write_bytes(b"\0" * 32)+ (tmp_path / "mmproj-F16.gguf").write_bytes(b"\0" * 32)++ config = ModelConfig.from_identifier(str(tmp_path), gguf_variant = "UD-Q4_K_XL")++ assert config is not None+ assert config.is_gguf is False+ assert is_vision_model(str(tmp_path), gguf_variant = "UD-Q4_K_XL") is False+# --- Exception handling: cache the False fallback ---diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.pyindex 749f2c92341..d4d7b4bcd95 100644--- a/studio/backend/utils/models/gguf_metadata.py+++ b/studio/backend/utils/models/gguf_metadata.py@@ -496,6 +496,31 @@ def read_mmproj_audio_capability(path: str) -> Optional[bool]:return _read_gguf_bool(path, "clip.has_audio_encoder")+def read_mmproj_vision_capability(path: str) -> Optional[bool]:+ """``clip.has_vision_encoder`` from an mmproj GGUF: ``True``/``False`` if+ present, ``None`` if absent/unreadable."""+ return _read_gguf_bool(path, "clip.has_vision_encoder")+++def mmproj_capabilities(path: str) -> Tuple[bool, bool]:+ """``(declares_audio_encoder, accepts_image)`` for the projector at *path*.++ A projector serving both modalities declares both (Qwen2.5-Omni), so an audio-only+ declaration (ultravox, Voxtral, Qwen3-ASR) is evidence of no vision tower. One+ declaring neither -- an older convert, or a file this reader could not open -- is+ unknown rather than audio-only and stays image-capable.+ """+ vision = read_mmproj_vision_capability(path)+ audio = read_mmproj_audio_capability(path)+ return audio is True, (vision is True or audio is not True)+++def mmproj_accepts_image(path: str) -> bool:+ """Whether images may be sent to the model this projector serves; see+ :func:`mmproj_capabilities`."""+ return mmproj_capabilities(path)[1]++def is_mmproj_by_metadata(meta: Optional[Dict[str, str]]) -> Optional[bool]:"""True/False from ``general.type``; None means fall back to filename."""if not meta:diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex d47996bf10a..596bdd30dde 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -19,6 +19,7 @@ from utils.paths import (from utils.utils import without_hf_authfrom utils.models.gguf_metadata import (is_mmproj_by_metadata,+ mmproj_accepts_image,pairing_score,read_gguf_general_metadata,)@@ -943,21 +944,36 @@ def is_vision_model(hf_token: Optional[str] = None,local_files_only: bool = False,revision: Optional[str] = None,+ gguf_variant: Optional[str] = None,+ require_image: bool = True,) -> bool:"""Detect VLMs via the config architecture (works for fine-tunes); transformers-5.xmodels are checked in a .venv_t5/ subprocess. Cached per (model_name, token,local_files_only, revision) minus transient failures; local_files_only is in the- key so an offline probe never shares an online entry."""+ key so an offline probe never shares an online entry.++ ``gguf_variant`` picks the quant out of a directory, so the probe reads the weight+ file the load will open. ``require_image=False`` asks only for a companion projector,+ which is what an audio request needs: audio input rides the same file."""# Local GGUF models are served by llama-server, so multimodal capability comes from a# companion mmproj, not a Transformers config. Do not cache: a projector may be added# beside an existing weight file after it was first inspected.if is_local_path(model_name):local_path = normalize_path(model_name)- gguf_file = detect_gguf_model(local_path)+ # Same rule as ModelConfig.from_identifier: variant lookup is directory-only, and+ # detect_gguf_model reads only the directory root, which holds no weights in a+ # repo that files every quant under a per-quant subdir.+ if gguf_variant and Path(local_path).is_dir():+ gguf_file = _find_local_gguf_by_variant(local_path, gguf_variant)+ else:+ gguf_file = detect_gguf_model(local_path)if gguf_file:companion_root = _local_gguf_companion_search_root(local_path, gguf_file)mmproj_file = detect_mmproj_file(gguf_file, search_root = companion_root)- is_vision = mmproj_file is not None+ # An audio-only projector serves this model's audio input, never an image.+ is_vision = mmproj_file is not None and (+ not require_image or mmproj_accepts_image(mmproj_file)+ )logger.debug("Local GGUF vision check for '%s': mmproj=%s, is_vision=%s",gguf_file,