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: serve an installed MLX checkpoint whose config drops its vision sub-config (#10977)
Long Yixingb7d4a62d630f
diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.pyindex a9ee3e4ec03..76711015b1d 100644--- a/studio/backend/core/inference/local_model_resolver.py+++ b/studio/backend/core/inference/local_model_resolver.py@@ -355,16 +355,8 @@ def _local_gguf_entry(# A LoRA directory can carry a copied config.json and tokenizer beside these, and ModelConfig would then resolve its# base model and fetch weights this resolver promises never to download._ADAPTER_MARKERS = ("adapter_config.json", "adapter_model.safetensors", "adapter_model.bin")-# The multimodal sub-configs the repo's own vision detector reads, which is what tells a served VLM apart from a plain-# seq2seq wearing the same architecture suffix.-_MULTIMODAL_CONFIG_KEYS = (- "vision_config",- "img_processor",- "image_token_index",- "projector_config",- "audio_config",-)_SUPPORTED_CONDITIONAL_AUDIO_MODEL_TYPES = frozenset({"csm", "whisper"})+_MODALITY_KEY_WORDS = frozenset({"vision", "image", "img", "audio", "video", "projector"})def _read_json(path):@@ -436,7 +428,7 @@ def _has_safetensors_weights(load_dir) -> bool:return False-def _is_generative_chat_config(config: dict) -> bool:+def _is_generative_chat_config(load_dir, config: dict) -> bool:"""Whether a config.json describes a checkpoint the chat loader can generate with."""architectures = config.get("architectures")# model_type cannot stand in for the list: transformers' causal mapping lists bert and bart@@ -449,13 +441,33 @@ def _is_generative_chat_config(config: dict) -> bool:return Trueif not any(name.endswith("ForConditionalGeneration") for name in names):return False- # ForConditionalGeneration is overloaded: T5 and BART wear it too, and the serving path has no AutoModelForSeq2SeqLM- # branch, so require a multimodal sub-config.- if any(key in config for key in _MULTIMODAL_CONFIG_KEYS):- return True- # whisper is the audio model rather than wearing one, so it carries no such sub-config. the MLX worker refuses ASR- # and TTS outright, so only a Transformers host serves these.- return not _host_serves_mlx() and _model_type_is_audio(config.get("model_type"))+ # These are the audio model rather than wearing one, so they declare no modality below and the+ # classifier further down refuses them; chat serves them through the transcription path instead.+ if _model_type_is_audio(config.get("model_type")):+ return not _host_serves_mlx()+ # T5 and BART wear the suffix too, and udop-large shows modality cannot separate them.+ if config.get("is_encoder_decoder") is True:+ return False+ if not _config_declares_multimodality(config):+ return False+ # The model picker's own classifier; its None means inconclusive, which must not qualify here.+ from hub.services.models.common import _local_transformers_can_chat++ return _local_transformers_can_chat(load_dir) is True+++def _config_declares_multimodality(config: dict) -> bool:+ """Whether a config declares a non-text modality, by whole key words: substrings admit ``revision``."""+ import re++ for key in config:+ if not isinstance(key, str):+ continue+ if key == "text_config":+ return True+ if _MODALITY_KEY_WORDS & set(re.split(r"[^a-z0-9]+", key.lower())):+ return True+ return Falsedef _model_type_is_audio(model_type) -> bool:@@ -495,10 +507,13 @@ def _config_is_servable_here(load_dir, config: dict) -> bool:# trust_remote_code needs an approval fingerprint a switch has not got; read as data only.for name in REMOTE_CODE_CONFIG_FILES:candidate = config if name == "config.json" else _read_json(load_dir / name)+ if not isinstance(candidate, dict):+ continue# truthiness like the consent gate's _config_has_auto_map: an empty map runs nothing.- if isinstance(candidate, dict) and candidate.get("auto_map"):+ # model_file runs repo code too and bypasses trust_remote_code: MLX loaders exec_module it.+ if candidate.get("auto_map") or candidate.get("model_file"):return False- return _is_generative_chat_config(config)+ return _is_generative_chat_config(load_dir, config)def _host_can_serve_minimax_music3() -> bool:diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex de1fc6d8a8b..3dfd8fefb0c 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -8376,16 +8376,42 @@ def _raw_body_model(body) -> Optional[str]:return body.get("model") if isinstance(body, dict) else None-async def _available_model_ids() -> list[str]:- """Sorted ids a /v1 request may name, from the catalog ``GET /v1/models``- serves, so an error and the listing can't disagree."""+def _catalog_object_ids(objects: list[dict]) -> list[str]:+ """Ids to offer a chat caller. Task-carrying rows are dropped for the reason+ _chat_servable_ids drops them, or the error names the model it just refused."""return sorted(mid- for mid in (m.get("id") for m in await _openai_catalog_objects())+ for mid in (m.get("id") for m in objects if m.get("task") is None)if isinstance(mid, str) and mid)+def _chat_servable_ids(objects: list[dict]) -> set[str]:+ """Casefolded ids the chat endpoints can serve: a media, speech or TTS row carries a ``task``."""+ return {+ obj["id"].casefold()+ for obj in objects+ if isinstance(obj.get("id"), str) and obj["id"] and obj.get("task") is None+ }+++async def _downloaded_model_ids() -> set[str]:+ """Casefolded ids of every complete model in the local catalog, read before the servability+ filter so an id here and absent from the chat listing is downloaded but withheld. Filtered for+ visibility, or it would report another account's inventory."""+ catalog = await _cached_local_catalog()+ if account_access.managed_account():+ catalog = await asyncio.to_thread(account_access.filter_model_rows, catalog)+ ids = set()+ for info in catalog:+ if getattr(info, "partial", False):+ continue+ cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))+ if isinstance(cid, str) and cid:+ ids.add(cid.casefold())+ return ids++def _format_available_models(ids: list[str]) -> str:if not ids:return ""@@ -8414,8 +8440,48 @@ async def _unavailable_model_message(requested_model: str) -> str:f"The model '{base_id}' is downloaded, but the quant '{wanted}' is not. "f"Available quants: {', '.join(variants)}.")- available = _format_available_models(await _available_model_ids())+ # One build, two views: each _openai_catalog_objects() call re-probes quants through the resolver.+ catalog_objects = await _openai_catalog_objects()+ available = _format_available_models(_catalog_object_ids(catalog_objects))+ requested = requested_model.strip()+ base, sep, _tag = requested.rpartition(":")+ # The branch above only fires for an indexed repo with variants, so test the base too.+ candidates = [requested.casefold()] + (+ [base.strip().casefold()] if sep and base.strip() else []+ )+ # The advertised ids too, not just the catalog's raw model_id: a task row can be advertised+ # under an alias (_stt_model_objects() lists "tiny" for unsloth/whisper-tiny), and a request+ # naming what GET /v1/models showed is a request for something that IS on this machine.+ downloaded = await _downloaded_model_ids() | {+ obj["id"].casefold()+ for obj in catalog_objects+ if isinstance(obj.get("id"), str) and obj["id"]+ }+ servable = _chat_servable_ids(catalog_objects)+ withheld = next((c for c in candidates if c in downloaded and c not in servable), None)+ if withheld is not None:+ named = requested if withheld == requested.casefold() else base.strip()+ # No "load it in Studio to find out": one of the two reasons a checkpoint lands here is a+ # truthy `model_file`, which _config_is_servable_here refuses because the MLX loaders+ # exec_module it, and the Studio consent gate does not cover that key (it reads+ # trust_remote_code and auto_map only, utils/security/consent.py). Sending the caller+ # down that path would run exactly the code this refusal exists to stop.+ message = (+ f"The model '{named}' is downloaded, but this server cannot serve it here: it is not a "+ "chat model this backend loads, or it needs custom code an API request cannot approve."+ )+ return f"{message} Available models: {available}." if available else messageif not available:+ if downloaded:+ # Something is on this machine, it just is not a chat model the backend loads.+ # `downloaded`, not `catalog_objects`: a resolver-withheld checkpoint (auto_map,+ # model_file, encoder-decoder) never enters the catalog at all, so testing the+ # catalog would claim an empty machine on a full one.+ return (+ f"The model '{requested_model}' is not downloaded on this server, and none of "+ "the downloaded models is a chat model. Download one in Unsloth Studio, "+ "or list what is here with GET /v1/models."+ )return (f"The model '{requested_model}' is not downloaded on this server, and no ""models are downloaded yet. Download one in Unsloth Studio."diff --git a/studio/backend/tests/test_openai_auto_download.py b/studio/backend/tests/test_openai_auto_download.pyindex 0e4bce536f7..003af402826 100644--- a/studio/backend/tests/test_openai_auto_download.py+++ b/studio/backend/tests/test_openai_auto_download.py@@ -2046,3 +2046,190 @@ def test_speech_download_admission(hub, monkeypatch, sidecar, probe, code):if probe is Noneelse [("unsloth/tts-GGUF", "model-Q8_0-00001-of-00002.gguf", None, hub["info"].sha)])+++def _unavailable_message(+ requested,+ *,+ downloaded,+ servable,+ monkeypatch,+ rows = None,+ listing = None,+):+ """``_unavailable_model_message`` against a catalog holding *downloaded* and a+ ``GET /v1/models`` listing holding *servable*.++ ``rows`` and ``listing`` override either side with explicit objects, for the cases where the+ shape matters rather than the ids: a scanner row that carries no ``model_id``, a partial+ download, or a row listed under a non-chat ``task``.+ """+ from types import SimpleNamespace++ async def _catalog():+ if rows is not None:+ return rows+ return [SimpleNamespace(model_id = mid, id = mid, path = f"/models/{mid}") for mid in downloaded]++ async def _objects():+ if listing is not None:+ return listing+ return [{"id": mid} for mid in servable]++ monkeypatch.setattr(inference_route, "_cached_local_catalog", _catalog)+ monkeypatch.setattr(inference_route, "_openai_catalog_objects", _objects)+ monkeypatch.setattr(+ resolver, "describe_local_miss", lambda name: (resolver.MISS_MODEL_NOT_FOUND, ())+ )+ return asyncio.run(inference_route._unavailable_model_message(requested))+++def test_a_downloaded_but_unservable_model_is_not_reported_as_missing(monkeypatch):+ """The reported confusion: an installed model that this backend withholds was told it was not+ downloaded, which sends the caller to download something they already have."""+ message = _unavailable_message(+ "ornith-ai/Ornith-1.5-35B-A3B-MLX-4bit",+ # Last, not first: a lookup that only ever reads row zero would pass either way.+ downloaded = ["unsloth/A-GGUF", "org/Other", "ornith-ai/Ornith-1.5-35B-A3B-MLX-4bit"],+ servable = ["unsloth/A-GGUF"],+ monkeypatch = monkeypatch,+ )+ assert "is not downloaded" not in message+ assert "is downloaded, but this server cannot serve it" in message+ # Still says what can serve the request.+ assert "unsloth/A-GGUF" in message+++def test_a_model_that_is_really_absent_still_says_it_is_not_downloaded(monkeypatch):+ message = _unavailable_message(+ "some-org/never-fetched",+ downloaded = ["unsloth/A-GGUF"],+ servable = ["unsloth/A-GGUF"],+ monkeypatch = monkeypatch,+ )+ assert "is not downloaded on this server" in message+ assert "cannot serve it" not in message+++def test_the_downloaded_check_ignores_id_case(monkeypatch):+ """Scan folders and the HF cache disagree about case, and the resolver index is casefolded, so+ a case-variant request must not read as a model nobody downloaded."""+ message = _unavailable_message(+ "Ornith-AI/Ornith-1.5-35B-A3B-MLX-4bit",+ downloaded = ["ornith-ai/ornith-1.5-35b-a3b-mlx-4bit"],+ servable = [],+ monkeypatch = monkeypatch,+ )+ assert "is downloaded, but this server cannot serve it" in message+++def test_a_loaded_model_is_never_called_unservable(monkeypatch):+ """Anything the listing serves is not withheld, so the servable set is what decides, not the+ catalog alone."""+ message = _unavailable_message(+ "unsloth/A-GGUF",+ downloaded = ["unsloth/A-GGUF"],+ servable = ["unsloth/A-GGUF"],+ monkeypatch = monkeypatch,+ )+ assert "cannot serve it" not in message+++def _row(+ *,+ model_id = None,+ id = None,+ path = "/models/x",+ partial = False,+):+ from types import SimpleNamespace+ return SimpleNamespace(model_id = model_id, id = id, path = path, partial = partial)+++def test_a_scanner_row_without_a_model_id_still_counts_as_downloaded(monkeypatch):+ """The ./models and LM Studio scanners report an absolute path as the id and set no model_id,+ so the public-id fallback is what names those rows. Without it a scanned model reads as one+ nobody downloaded."""+ message = _unavailable_message(+ "Ornith-1.5-35B-A3B-MLX-4bit",+ downloaded = [],+ servable = [],+ rows = [_row(id = "/srv/models/Ornith-1.5-35B-A3B-MLX-4bit")],+ monkeypatch = monkeypatch,+ )+ assert "is downloaded, but this server cannot serve it here" in message+ # And never the host path the row was keyed by.+ assert "/srv/" not in message+++def test_a_partial_download_is_not_called_downloaded(monkeypatch):+ """An interrupted download is not something this server has, and blaming its architecture would+ send the caller away from the thing that actually fixes it."""+ message = _unavailable_message(+ "org/Half-Fetched",+ downloaded = [],+ servable = [],+ rows = [_row(model_id = "org/Half-Fetched", partial = True)],+ monkeypatch = monkeypatch,+ )+ assert "cannot serve it here" not in message+ assert "is not downloaded on this server" in message+++def test_a_quant_tagged_name_still_gets_the_downloaded_diagnosis(monkeypatch):+ """The wrong-quant branch only fires for an indexed repo carrying variants, so a tagged name+ reaches here whenever the repo is withheld, and the tag must not hide that it is on disk."""+ for tag in (":Q4_K_M", ":latest"):+ message = _unavailable_message(+ f"org/Withheld{tag}",+ downloaded = ["org/Withheld"],+ servable = [],+ monkeypatch = monkeypatch,+ )+ assert "is downloaded, but this server cannot serve it here" in message, tag+ assert "org/Withheld'" in message, tag+++def test_a_model_listed_only_for_another_task_is_not_called_available(monkeypatch):+ """Whisper on an MLX host is listed for transcription and withheld from the chat loader, so the+ listing alone would report it available for a chat request it cannot answer."""+ message = _unavailable_message(+ "openai/whisper-tiny",+ downloaded = ["openai/whisper-tiny"],+ servable = [],+ listing = [{"id": "openai/whisper-tiny", "task": "automatic-speech-recognition"}],+ monkeypatch = monkeypatch,+ )+ assert "is downloaded, but this server cannot serve it here" in message+++def test_the_diagnosis_does_not_report_a_model_this_account_cannot_see(monkeypatch):+ """The raw catalog spans every account's private directories. Confirming "that one is+ downloaded" for a row the listing filters out would disclose another account's inventory."""++ def _only_granted(rows, **_kw):+ return [row for row in rows if getattr(row, "model_id", None) == "org/Granted"]++ monkeypatch.setattr(inference_route.account_access, "managed_account", lambda: True)+ monkeypatch.setattr(inference_route.account_access, "filter_model_rows", _only_granted)++ hidden = _unavailable_message(+ "someone-else/Private",+ downloaded = [],+ servable = [],+ rows = [_row(model_id = "org/Granted"), _row(model_id = "someone-else/Private")],+ monkeypatch = monkeypatch,+ )+ assert "is downloaded" not in hidden+ assert "is not downloaded on this server" in hidden++ # The other direction: a row the filter keeps must still be diagnosed, or a managed account is+ # told nothing it owns is downloaded.+ granted = _unavailable_message(+ "org/Granted",+ downloaded = [],+ servable = [],+ rows = [_row(model_id = "org/Granted"), _row(model_id = "someone-else/Private")],+ monkeypatch = monkeypatch,+ )+ assert "is downloaded, but this server cannot serve it here" in granteddiff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 60f0cc1167b..aac411611c9 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -6053,11 +6053,20 @@ def _wire_unloaded_chat(*,enabled,catalog = ("org/A-GGUF", "org/B-GGUF"),+ downloaded = (),):# Nothing loaded, so a chat request hits "no model loaded". Pin the catalog for determinism.async def _catalog():return [{"id": mid} for mid in catalog]+ # _downloaded_model_ids reads the LOCAL catalog, which _openai_catalog_objects does not+ # cover: unpinned, these tests would answer from whatever the host has downloaded.+ async def _local_catalog():+ return [+ type("_Row", (), {"model_id": mid, "id": mid, "partial": False})() for mid in downloaded+ ]++ monkeypatch.setattr(inference_route, "_cached_local_catalog", _local_catalog)monkeypatch.setattr(settings, "get_openai_auto_switch_enabled", lambda: enabled)monkeypatch.setattr(resolver, "resolve_local_gguf", lambda _m, **_kw: None)monkeypatch.setattr(@@ -6135,6 +6144,58 @@ def test_chat_wrong_quant_lists_the_local_quants(monkeypatch):assert "Q4_K_M, Q8_0" in detail+def _wire_withheld_chat(monkeypatch, *, objects, downloaded):+ async def _catalog():+ return list(objects)++ _wire_unloaded_chat(monkeypatch, enabled = True, downloaded = downloaded)+ monkeypatch.setattr(inference_route, "_openai_catalog_objects", _catalog)+++def test_chat_withheld_model_is_not_offered_back_as_available(monkeypatch):+ # A downloaded Whisper row is withheld from chat, so listing it as an alternative would+ # name the model the same sentence just refused.+ _wire_withheld_chat(+ monkeypatch,+ objects = [+ {"id": "org/A-GGUF"},+ {"id": "openai/whisper-large-v3", "task": "automatic-speech-recognition"},+ ],+ downloaded = ("org/A-GGUF", "openai/whisper-large-v3"),+ )+ status, detail = _chat_error(_chat_request(model = "openai/whisper-large-v3"))+ assert status == 404+ assert "cannot serve it here" in detail+ assert "Available models: org/A-GGUF." in detail+ assert detail.count("openai/whisper-large-v3") == 1+++def test_chat_absent_model_with_only_task_rows_says_no_chat_model_is_here(monkeypatch):+ # Whisper is downloaded, so "no models are downloaded yet" would contradict GET /v1/models.+ _wire_withheld_chat(+ monkeypatch,+ objects = [{"id": "openai/whisper-large-v3", "task": "automatic-speech-recognition"}],+ downloaded = ("openai/whisper-large-v3",),+ )+ status, detail = _chat_error(_chat_request(model = "org/nope-GGUF"))+ assert status == 404+ assert "none of the downloaded models is a chat model" in detail+ assert "no models are downloaded yet" not in detail+++def test_chat_withheld_model_with_no_chat_rows_offers_nothing(monkeypatch):+ # Every row is task-specific, so there is no chat model to offer at all.+ _wire_withheld_chat(+ monkeypatch,+ objects = [{"id": "openai/whisper-large-v3", "task": "automatic-speech-recognition"}],+ downloaded = ("openai/whisper-large-v3",),+ )+ status, detail = _chat_error(_chat_request(model = "openai/whisper-large-v3"))+ assert status == 404+ assert "cannot serve it here" in detail+ assert "Available models" not in detail++def test_chat_error_unchanged_when_auto_switch_off(monkeypatch):# Toggle off: nothing resolved, so keep the pre-existing status and text, hint included._wire_unloaded_chat(monkeypatch, enabled = False)@@ -9913,7 +9974,8 @@ def test_a_whisper_checkpoint_is_switchable(tmp_path):path = _local_checkpoint(tmp_path, "whisper-large-v3")info = SimpleNamespace(id = str(path), path = str(path))(path / "config.json").write_text(- '{"architectures": ["WhisperForConditionalGeneration"], "model_type": "whisper"}'+ '{"architectures": ["WhisperForConditionalGeneration"], "model_type": "whisper",'+ ' "is_encoder_decoder": true}')assert resolver.local_servable_model(info) == (False, ())assert resolver._model_type_is_audio("whisper") is True@@ -9947,7 +10009,8 @@ def test_an_mlx_host_does_not_advertise_an_asr_checkpoint(tmp_path, monkeypatch)path = _local_checkpoint(tmp_path, "whisper-large-v3")info = SimpleNamespace(id = str(path), path = str(path))(path / "config.json").write_text(- '{"architectures": ["WhisperForConditionalGeneration"], "model_type": "whisper"}'+ '{"architectures": ["WhisperForConditionalGeneration"], "model_type": "whisper",'+ ' "is_encoder_decoder": true}')monkeypatch.setattr(resolver, "_host_serves_mlx", lambda: True)assert resolver.local_servable_model(info) is None@@ -9959,6 +10022,135 @@ def test_an_mlx_host_does_not_advertise_an_asr_checkpoint(tmp_path, monkeypatch)assert resolver.local_servable_model(info) == (False, ())+def test_a_conditional_checkpoint_with_no_vision_sub_config_is_switchable(tmp_path, monkeypatch):+ """A conversion that drops the vision tower keeps the parent's multimodal architecture name+ but loses the sub-config, so demanding one withheld a checkpoint both workers load. Shape+ taken from ornith-ai/Ornith-1.5-35B-A3B-MLX-4bit, whose weights hold only language_model.*+ and whose config carries image_token_id and text_config but no vision_config at all."""+ path = _local_checkpoint(tmp_path, "Ornith-MLX-4bit")+ info = SimpleNamespace(id = str(path), path = str(path))+ (path / "config.json").write_text(+ '{"architectures": ["Qwen3_5MoeForConditionalGeneration"],'+ ' "model_type": "qwen3_5_moe", "image_token_id": 151655, "text_config": {}}'+ )+ for mlx_host in (True, False):+ monkeypatch.setattr(resolver, "_host_serves_mlx", lambda mlx_host = mlx_host: mlx_host)+ assert resolver.local_servable_model(info) == (False, ()), mlx_host+ # The marker is matched by shape, not against a list of names, which is what the fixed list+ # got wrong: the checkpoint spells it image_token_id and the list named image_token_index.+ for marker in (+ '"image_token_id": 151655', # the spelling the reported checkpoint uses, alone+ '"image_token_index": 1',+ '"vision_config": {}',+ '"video_token_id": 2',+ '"img_processor": {}', # matched on the word, so a shortened spelling still counts+ ):+ (path / "config.json").write_text(+ '{"architectures": ["Qwen3_5MoeForConditionalGeneration"],'+ ' "model_type": "qwen3_5_moe", %s}' % marker+ )+ assert resolver.local_servable_model(info) == (False, ()), marker+ # A terse config with no modality marker at all reads exactly like a text seq2seq, so it stays+ # refused rather than being guessed at.+ (path / "config.json").write_text(+ '{"architectures": ["Qwen3_5MoeForConditionalGeneration"], "model_type": "qwen3_5_moe"}'+ )+ assert resolver.local_servable_model(info) is None+++def test_a_multimodal_encoder_decoder_is_not_switchable(tmp_path):+ """Declaring a modality does not make a checkpoint servable here: microsoft/udop-large is an+ encoder-decoder carrying image_size, and the serving path has no AutoModelForSeq2SeqLM branch.+ The flag is what refuses it, since the modality marker is satisfied."""+ path = _local_checkpoint(tmp_path, "udop-large")+ info = SimpleNamespace(id = str(path), path = str(path))+ (path / "config.json").write_text(+ '{"architectures": ["UdopForConditionalGeneration"], "model_type": "udop",'+ ' "is_encoder_decoder": true, "image_size": 224}'+ )+ assert resolver.local_servable_model(info) is None+ # The flag is what refuses it: the same shape without one is indistinguishable from a served+ # VLM and the marker decides. Not spelled udop, so this turns on the flag rather than on the+ # shared classifier's current view of that family.+ (path / "config.json").write_text(+ '{"architectures": ["SomeVlmForConditionalGeneration"], "model_type": "some_vlm",'+ ' "image_size": 224}'+ )+ assert resolver.local_servable_model(info) == (False, ())+++def test_a_revision_key_does_not_pass_as_a_modality_marker(tmp_path):+ """The marker is matched on whole words: `revision` ends in one, is common in a saved config,+ and would otherwise admit every text seq2seq that carries it."""+ path = _local_checkpoint(tmp_path, "t5-with-revision")+ info = SimpleNamespace(id = str(path), path = str(path))+ (path / "config.json").write_text(+ '{"architectures": ["T5ForConditionalGeneration"], "model_type": "t5",'+ ' "revision": "main"}'+ )+ assert resolver.local_servable_model(info) is None++[email protected]("mlx_host", [True, False])[email protected]("architecture", ["LlamaForCausalLM", "Qwen3_5MoeForConditionalGeneration"])+def test_a_config_declaring_model_file_is_not_switchable(+ tmp_path, monkeypatch, architecture, mlx_host+):+ """model_file is the other key that runs code out of the checkpoint, and unlike auto_map it+ does not pass through trust_remote_code at all: mlx_lm/utils.py and mlx_vlm/utils.py both+ exec_module the named file before dispatching on model_type. An unattended switch grants no+ approval, so it is refused on the same boundary as auto_map."""+ monkeypatch.setattr(resolver, "_host_serves_mlx", lambda: mlx_host)+ path = _local_checkpoint(tmp_path, "CustomModelFile")+ info = SimpleNamespace(id = str(path), path = str(path))+ (path / "custom.py").write_text("raise SystemExit('should never be executed')")+ base = (+ '{"architectures": ["%s"], "model_type": "qwen3_5_moe", "vision_config": {}%%s}'+ % architecture+ )+ (path / "config.json").write_text(base % "")+ assert resolver.local_servable_model(info) == (False, ())+ (path / "config.json").write_text(base % ', "model_file": "custom.py"')+ assert resolver.local_servable_model(info) is None+ # Empty names no file, so it runs nothing, like the auto_map rule just below.+ (path / "config.json").write_text(base % ', "model_file": ""')+ assert resolver.local_servable_model(info) == (False, ())+++def test_a_conditional_family_the_model_picker_refuses_is_not_switchable(tmp_path):+ """The resolver used to re-derive the category from architecture strings and drifted from the+ classifier behind the picker's can_chat, which is how an installed checkpoint could be offered+ in the UI and be unknown to the API. The conditional branch defers to that classifier now, so+ the families it refuses are refused here without being restated.++ Only that branch. The resolver is deliberately not a subset overall: the causal fast path does+ not consult the classifier, and the audio branch serves whisper on a Transformers host though+ the classifier calls it unchattable."""+ from hub.services.models.common import _local_transformers_can_chat++ path = _local_checkpoint(tmp_path, "Shared")+ info = SimpleNamespace(id = str(path), path = str(path))+ refused_by_picker = 0+ for config in (+ '{"architectures": ["Qwen3_5MoeForConditionalGeneration"], "model_type": "qwen3_5_moe",'+ ' "vision_config": {}}',+ '{"architectures": ["MusicgenForConditionalGeneration"], "model_type": "musicgen",'+ ' "audio_encoder": {}}',+ '{"architectures": ["BlipForConditionalGeneration"], "model_type": "blip",'+ ' "vision_config": {}}',+ '{"architectures": ["Gemma3ForConditionalGeneration"], "model_type": "gemma3",'+ ' "vision_config": {}}',+ ):+ (path / "config.json").write_text(config)+ picker_can_chat = _local_transformers_can_chat(path) is True+ servable = resolver.local_servable_model(info) is not None+ if not picker_can_chat:+ refused_by_picker += 1+ assert not servable, config+ # musicgen and blip, so the subset assertion above is not vacuous.+ assert refused_by_picker == 2++def test_an_empty_auto_map_is_not_remote_code(tmp_path):"""The consent gate reads auto_map for truthiness (_config_has_auto_map inutils/security/consent.py), so an empty or null mapping names no implementation and@@ -10966,6 +11158,55 @@ def test_speech_probe_refuses_remote_code(monkeypatch, audio_type, allowed):)+def test_chat_withheld_model_named_by_its_advertised_alias(monkeypatch):+ # _stt_model_objects advertises "tiny" while the catalog row is unsloth/whisper-tiny, so a+ # request naming what GET /v1/models showed must read as downloaded, not as absent.+ _wire_withheld_chat(+ monkeypatch,+ objects = [+ {"id": "org/A-GGUF"},+ {"id": "tiny", "task": "automatic-speech-recognition"},+ ],+ downloaded = ("org/A-GGUF", "unsloth/whisper-tiny"),+ )+ status, detail = _chat_error(_chat_request(model = "tiny"))+ assert status == 404+ assert "cannot serve it here" in detail+ assert "not downloaded on this server" not in detail+++def test_chat_absent_model_with_only_resolver_withheld_checkpoints(monkeypatch):+ # A checkpoint the resolver withholds never enters the catalog, so testing catalog_objects+ # would claim an empty machine on a full one.+ _wire_withheld_chat(+ monkeypatch,+ objects = [],+ downloaded = ("org/has-auto-map",),+ )+ status, detail = _chat_error(_chat_request(model = "org/nope-GGUF"))+ assert status == 404+ assert "none of the downloaded models is a chat model" in detail+ assert "no models are downloaded yet" not in detail+++def test_chat_withheld_model_does_not_send_the_caller_to_load_it(monkeypatch):+ # One reason a checkpoint is withheld is a truthy model_file, which the MLX loaders+ # exec_module and the Studio consent gate does not cover, so the refusal must not point+ # the caller at a manual load.+ _wire_withheld_chat(+ monkeypatch,+ objects = [+ {"id": "org/A-GGUF"},+ {"id": "org/custom-code", "task": "automatic-speech-recognition"},+ ],+ downloaded = ("org/A-GGUF", "org/custom-code"),+ )+ status, detail = _chat_error(_chat_request(model = "org/custom-code"))+ assert status == 404+ assert "cannot serve it here" in detail+ assert "Unsloth Studio" not in detail++def test_preset_reasoning_budget_rejects_booleans():from routes.chat_history import ChatPresetLoadConfigwith pytest.raises(ValueError, match = "Expected a number, got a boolean"):