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: find a hand-added mmproj when the GGUF repo publishes none (#9365)
yzxcj797874fb67c4089
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 0f4bc5cc686..52f3d8b6458 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -19528,6 +19528,9 @@ class LlamaCppBackend:if attempt < 2:cancel_event.wait(2**attempt)+ # Captured before the cache fallback can name a file the live revision dropped.+ listed_live = (target is not None) if listing_answered else None+if target is None:try:from utils.models.model_config import _iter_hf_cache_snapshots@@ -19551,6 +19554,8 @@ class LlamaCppBackend:and (listing_answered or target is not None)):outcome["listed"] = target is not None+ if outcome is not None and not cancel_event.is_set() and listed_live is not None:+ outcome["listed_live"] = listed_liveif target is None or cancel_event.is_set():# The listing is the only step that can fail this far in.if target is None and listing_failed and not cancel_event.is_set():@@ -19599,6 +19604,7 @@ class LlamaCppBackend:# absence rather than reloading on every Apply.if outcome is not None:outcome["listed"] = False+ outcome["listed_live"] = Falsereturn Nonetry:logger.info(f"Downloading {label}: {hf_repo}/{target}")@@ -19665,16 +19671,45 @@ class LlamaCppBackend:path, or None if none exists. ``cancel_event`` overrides``self._cancel_event`` (defaults to it). ``near_path`` prefers acopy co-located with the main GGUF's cache snapshot.++ Falls back to a projector hand-added beside the cached weight, only+ when the live listing says the repo publishes none (#9286)."""- return self._download_companion_gguf(+ cancel_event = cancel_event if cancel_event is not None else self._cancel_event+ if cancel_event.is_set():+ return None++ outcome: dict = {}+ resolved = self._download_companion_gguf(hf_repo = hf_repo,hf_token = hf_token,pick = _pick_mmproj,label = "mmproj",cancel_event = cancel_event,near_path = near_path,+ outcome = outcome,)+ if resolved is not None:+ # An interrupted zero-byte copy must not shadow a working projector.+ try:+ if Path(resolved).stat().st_size > 0:+ return resolved+ except OSError:+ return resolved+ logger.info("Ignoring an empty mmproj resolved for %s: %s", hf_repo, resolved)+ elif outcome.get("listed_live") is True:+ # The repo publishes one and the fetch dropped: retry next Apply rather+ # than launch a hand-added file in its place. Offline still falls back.+ return None+ if not near_path or cancel_event.is_set():+ return None+ from utils.models.model_config import _hf_cached_local_mmproj++ cached = _hf_cached_local_mmproj(near_path)+ if cached is not None:+ logger.info("Reusing hand-added mmproj from the HF cache: %s", cached)+ return cacheddef _cached_repo_mtp_drafter(self,@@ -32592,6 +32627,9 @@ class LlamaCppBackend:if _launched_frac is not None and float(_launched_frac) != _active_frac:logger.info("VRAM budget changed since launch; forcing a reload")return False+ if self._hand_added_projector_since_launch(candidate_extra_args):+ logger.info("A projector was added beside the cached weight; forcing a reload")+ return Falseif not self._runtime_matches_intent(intent, candidate_extra_args):return Falseself._record_matching_gpu_request(@@ -32599,6 +32637,28 @@ class LlamaCppBackend:)return True+ def _hand_added_projector_since_launch(self, extra_args: list) -> bool:+ """A text-only -hf launch whose repo publishes no projector, with one now+ dropped beside the cached weight (#9286). Without this the next Apply dedupes+ onto the projector-less server until Studio restarts."""+ last = getattr(self, "_last_load_intent", None)+ if (+ self._is_vision+ or self._disable_vision+ or not self._hf_repo+ or not self._gguf_path+ or last is None+ or last.is_vision+ or extra_args_disable_mmproj(extra_args)+ ):+ return False+ try:+ from utils.models.model_config import _hf_cached_local_mmproj+ return _hf_cached_local_mmproj(self._gguf_path) is not None+ except Exception as exc:+ logger.debug("Hand-added mmproj probe failed: %s", exc)+ return False+def matches_load_source(self, intent: GgufLoadIntent) -> bool:"""Whether the resident model has the intent's identity and weights."""if not self.is_loaded or (self._model_identifier or "").lower() != (diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex b85efd55f12..59a47c95e20 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -11906,32 +11906,33 @@ def _effective_load_in_4bit(config: ModelConfig, requested: bool) -> bool:return load_in_4bit+def _projector_survives_vision_off(mmproj_path: str) -> bool:+ """Whether the Vision switch leaves *mmproj_path* loaded (audio-only projectors+ stay). Unreadable reads as image-capable, hence suppressed, matching the loader."""+ try:+ from utils.models.gguf_metadata import mmproj_accepts_image+ return not mmproj_accepts_image(str(mmproj_path))+ except Exception as exc:+ logger.debug(f"mmproj capability read failed: {exc}")+ return False++def _load_keeps_a_projector(config, *, disable_vision: bool) -> bool:"""Whether the launch will actually open a projector for *config*.- The Vision switch turns IMAGES off, and llama_cpp.py keeps an audio-only- projector regardless because there is no image tower in it to drop. Only the- file's own metadata distinguishes the two, so this answers precisely when the- file is already on disk. A projector that is not (a remote repo, nothing- downloaded yet) reads as kept: the callers use this to decide whether the load- needs the GPU, and over-claiming is recoverable where under-claiming is not.+ Answers precisely when the file is on disk. A projector that is not (a remote+ repo, nothing downloaded yet) reads as kept: the callers use this to decide+ whether the load needs the GPU, and over-claiming is recoverable where+ under-claiming is not."""if not getattr(config, "is_vision", False):return Falseif not disable_vision:return True- mmproj = getattr(config, "gguf_mmproj_file", None)- if not mmproj:- return True- try:- from utils.models.gguf_metadata import mmproj_accepts_image-- # Image-capable means the switch really does suppress it. Unreadable reads- # as image-capable upstream, which matches what the loader will do with it.- return not mmproj_accepts_image(str(mmproj))- except Exception as exc:- logger.debug(f"mmproj capability read failed: {exc}")- return False+ mmproj = getattr(config, "gguf_mmproj_file", None) or getattr(+ config, "gguf_local_mmproj_file", None+ )+ return True if not mmproj else _projector_survives_vision_off(str(mmproj))def _remote_gguf_companion_bytes(@@ -11944,6 +11945,7 @@ def _remote_gguf_companion_bytes(include_dflash: bool = False,dspark_first: bool = False,weight_bytes: int = 0,+ local_mmproj_bytes: int = 0,) -> int:"""Bytes of companion GGUFs the requested launch keeps resident. 0 on error.@@ -11967,7 +11969,7 @@ def _remote_gguf_companion_bytes(# A refused token must not zero the companion bytes and slip past the training budget.info = call_hub_with_anonymous_retry(model_info, hf_token, repo, files_metadata = True)- total = 0+ listed_mmproj_bytes = 0mtp_bytes = 0dspark_candidates: list[tuple[str, int]] = []dflash_sizes: dict[str, int] = {}@@ -11987,7 +11989,7 @@ def _remote_gguf_companion_bytes(if include_mtp and is_root_mtp:mtp_bytes += sizeelif include_mmproj and "mmproj" in base:- total += size+ listed_mmproj_bytes += sizeif include_dspark and _is_dspark_drafter_path(name):dspark_candidates.append((name, size))# Root level only, exactly as _download_dflash's picker is: a nested@@ -12019,6 +12021,8 @@ def _remote_gguf_companion_bytes(# target too, so the guard stops charging for the oversized candidates the# fetch itself now refuses.dflash_bytes = dflash_budget_bytes(dflash_sizes, _gguf_extra_shards, weight_bytes)+ # Alternatives, never both: the fetch uses the local one only when none is listed.+ total = max(int(local_mmproj_bytes), listed_mmproj_bytes)if not dspark_first:return total + mtp_bytes + dspark_bytes + dflash_bytesif dspark_families:@@ -12040,7 +12044,7 @@ def _remote_gguf_companion_bytes(return total + mtp_bytesexcept Exception as e:logger.warning(f"Could not size GGUF companions for {repo}: {e}")- return 0+ return int(local_mmproj_bytes)# What an unreadable remote drafter costs the guard. Sized to the largest drafter@@ -13092,17 +13096,9 @@ def _estimate_gguf_required_gb(_sized_attrs = []elif disable_vision:_dv_mmproj = _mmproj_override or getattr(config, "gguf_mmproj_file", None)- _dv_opens_projector = False- if _dv_mmproj:- try:- from utils.models.gguf_metadata import mmproj_accepts_image-- # Kept for audio, so its bytes stay charged. An unreadable file- # reads as image-capable upstream, hence suppressed and uncharged,- # which matches what the loader will then do with it.- _dv_opens_projector = not mmproj_accepts_image(str(_dv_mmproj))- except Exception as _dv_exc:- logger.debug(f"mmproj capability read failed: {_dv_exc}")+ _dv_opens_projector = bool(_dv_mmproj) and _projector_survives_vision_off(+ str(_dv_mmproj)+ )if not _dv_opens_projector:_sized_attrs = []# A --mmproj in the extras last-wins at the child: the launch emits Studio's@@ -13252,6 +13248,16 @@ def _estimate_gguf_required_gb(main_bytes = selected.size_bytes if selected is not None else Noneif main_bytes is None:return None+ _local_mmproj = getattr(config, "gguf_local_mmproj_file", None)+ _local_mmproj_bytes = 0+ # A --mmproj in the extras replaces it and is charged on its own.+ if (+ _local_mmproj+ and _mmproj_override is None+ and not extra_args_disable_mmproj(llama_extra_args)+ ):+ if not disable_vision or _projector_survives_vision_off(str(_local_mmproj)):+ _local_mmproj_bytes = LlamaCppBackend._get_gguf_size_bytes(str(_local_mmproj))companions = _remote_gguf_companion_bytes(repo,hf_token = hf_token,@@ -13275,6 +13281,8 @@ def _estimate_gguf_required_gb(# What the DFlash bound measures candidates against, so the guard stops# charging for weights the fetch refuses as too big to be a drafter.weight_bytes = int(main_bytes or 0),+ # Hand-added (#9286): invisible to the listing, still resident.+ local_mmproj_bytes = _local_mmproj_bytes,# ... except where the listing settles it. Auto launches exactly# one drafter, in a fixed order, so once the listing says which# kinds the repo has, charging the losers is not caution, it is a@@ -13656,7 +13664,10 @@ def _localized_estimate_config(config: ModelConfig, gguf_path: str) -> ModelConfsearch_root = _local_gguf_companion_search_root(gguf_path, gguf_path)try:if getattr(local, "is_vision", False) and not local.gguf_mmproj_file:- local.gguf_mmproj_file = detect_mmproj_file(gguf_path, search_root)+ # A hand-added one may sit above the snapshot, past this search root (#9286).+ local.gguf_mmproj_file = detect_mmproj_file(gguf_path, search_root) or getattr(+ local, "gguf_local_mmproj_file", None+ )if not local.gguf_mtp_file:local.gguf_mtp_file = detect_mtp_file(gguf_path, search_root)if not local.gguf_dspark_file:diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.pyindex 76c13bf7b64..526d1632ce3 100644--- a/studio/backend/tests/test_gguf_load_cache_reuse.py+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py@@ -730,6 +730,134 @@ class TestLoadReusesCachedCopy:assert out == str(snap / "mmproj-F16.gguf")+ def test_companion_reuses_a_projector_at_the_hf_repo_root(self, hf_cache):+ """A repo that publishes none falls back to a hand-added one (#9286)."""+ backend = LlamaCppBackend()+ snap = _build_cache(hf_cache, REPO, {MAIN: 4})+ projector = snap.parent.parent / "mmproj-F16.gguf"+ projector.write_bytes(b"mmproj")++ with patch("huggingface_hub.list_repo_files", lambda *_a, **_k: [MAIN]):+ out = backend._download_mmproj(hf_repo = REPO, near_path = str(snap / MAIN))++ assert out == str(projector)++ def test_a_published_projector_still_wins_over_the_repo_root(self, hf_cache):+ """The fallback runs last, so a repo that ships one resolves as it did before."""+ backend = LlamaCppBackend()+ snap = _build_cache(hf_cache, REPO, {MAIN: 4})+ (snap.parent.parent / "mmproj-F16.gguf").write_bytes(b"mmproj")++ with patch.object(backend, "_download_companion_gguf", return_value = "/remote/image.gguf"):+ out = backend._download_mmproj(hf_repo = REPO, near_path = str(snap / MAIN))++ assert out == "/remote/image.gguf"++ def test_a_dropped_fetch_of_a_published_projector_does_not_fall_back(self, hf_cache):+ """The repo lists one, so None is a dropped fetch: no fallback."""+ backend = LlamaCppBackend()+ snap = _build_cache(hf_cache, REPO, {MAIN: 4})+ (snap.parent.parent / "mmproj-F16.gguf").write_bytes(b"mmproj")++ def _drop(*_args, **_kwargs):+ raise OSError("connection reset")++ with (+ patch("huggingface_hub.list_repo_files", lambda *_a, **_k: [MAIN, "mmproj-F16.gguf"]),+ patch("core.inference.llama_cpp.hf_hub_download_with_xet_fallback", _drop),+ ):+ assert backend._download_mmproj(hf_repo = REPO, near_path = str(snap / MAIN)) is None++ def test_a_stale_cached_name_does_not_pass_for_a_published_projector(self, hf_cache):+ """Only an older snapshot names a projector; the live listing has none."""+ backend = LlamaCppBackend()+ snap = _build_cache(hf_cache, REPO, {MAIN: 4})+ _build_cache(hf_cache, REPO, {"mmproj-F16.gguf": 2}, snapshot_sha = "b" * 40)+ projector = snap.parent.parent / "mmproj-kquant.gguf"+ projector.write_bytes(b"mmproj")++ def _gone(*_args, **_kwargs):+ raise OSError("404 for a file this revision no longer publishes")++ with (+ patch("huggingface_hub.list_repo_files", lambda *_a, **_k: [MAIN]),+ patch("core.inference.llama_cpp.hf_hub_download_with_xet_fallback", _gone),+ ):+ out = backend._download_mmproj(hf_repo = REPO, near_path = str(snap / MAIN))++ assert out == str(projector)++ def test_an_empty_resolved_projector_does_not_shadow_the_repo_root(self, hf_cache):+ """A zero-byte resolved copy is not returned."""+ backend = LlamaCppBackend()+ snap = _build_cache(hf_cache, REPO, {MAIN: 4})+ empty = snap.parent.parent / "stale-mmproj.gguf"+ empty.write_bytes(b"")+ projector = snap.parent.parent / "mmproj-F16.gguf"+ projector.write_bytes(b"mmproj")++ with patch.object(backend, "_download_companion_gguf", return_value = str(empty)):+ out = backend._download_mmproj(hf_repo = REPO, near_path = str(snap / MAIN))++ assert out == str(projector)++ def test_an_empty_published_projector_still_reaches_the_repo_root(self, hf_cache):+ """A zero-byte listed copy falls back: the next Apply would not heal it."""+ backend = LlamaCppBackend()+ snap = _build_cache(hf_cache, REPO, {MAIN: 4})+ empty = snap.parent.parent / "published-mmproj.gguf"+ empty.write_bytes(b"")+ projector = snap.parent.parent / "mmproj-F16.gguf"+ projector.write_bytes(b"mmproj")++ def _resolve_empty(+ *_a,+ outcome = None,+ **_k,+ ):+ if outcome is not None:+ outcome["listed_live"] = True+ outcome["listed"] = True+ return str(empty)++ with patch.object(backend, "_download_companion_gguf", _resolve_empty):+ out = backend._download_mmproj(hf_repo = REPO, near_path = str(snap / MAIN))++ assert out == str(projector)++ def test_an_unanswered_listing_still_reaches_the_repo_root(self, hf_cache):+ """An unanswered (offline) listing still falls back."""+ backend = LlamaCppBackend()+ snap = _build_cache(hf_cache, REPO, {MAIN: 4})+ projector = snap.parent.parent / "mmproj-F16.gguf"+ projector.write_bytes(b"mmproj")++ def _unreachable(*_args, **_kwargs):+ raise OSError("name resolution failed")++ with patch("huggingface_hub.list_repo_files", _unreachable):+ out = backend._download_mmproj(hf_repo = REPO, near_path = str(snap / MAIN))++ assert out == str(projector)++ def test_companion_cancelled_before_scanning_cached_projectors(self, hf_cache):+ backend = LlamaCppBackend()+ snap = _build_cache(hf_cache, REPO, {MAIN: 4})+ cancel_event = threading.Event()+ cancel_event.set()++ with patch(+ "utils.models.model_config.detect_mmproj_file",+ side_effect = AssertionError("cancelled lookup scanned the cache"),+ ):+ out = backend._download_mmproj(+ hf_repo = REPO,+ near_path = str(snap / MAIN),+ cancel_event = cancel_event,+ )++ assert out is None+def test_companion_finds_snapshot_through_hf_symlink(self, hf_cache):backend = LlamaCppBackend()snap = _build_cache(hf_cache, REPO, {})diff --git a/studio/backend/tests/test_gguf_metadata.py b/studio/backend/tests/test_gguf_metadata.pyindex 38c8e009eda..d7e6d4cb7f7 100644--- a/studio/backend/tests/test_gguf_metadata.py+++ b/studio/backend/tests/test_gguf_metadata.py@@ -370,6 +370,11 @@ def test_is_mmproj_by_metadata_signals():assert is_mmproj_by_metadata({"general.basename": "foo"}) is Noneassert is_mmproj_by_metadata({}) is Noneassert is_mmproj_by_metadata(None) is None+ # llama.cpp's projector arch; ggml-org's SmolVLM projector says "clip-vision".+ assert is_mmproj_by_metadata({"general.architecture": "clip", "general.type": "clip-vision"})+ assert (+ is_mmproj_by_metadata({"general.architecture": "llama", "general.type": "model"}) is False+ )# --- pairing_score -----------------------------------------------------diff --git a/studio/backend/tests/test_gguf_variant_preflight.py b/studio/backend/tests/test_gguf_variant_preflight.pyindex 7a5e4e2f74e..a3e775d6fdd 100644--- a/studio/backend/tests/test_gguf_variant_preflight.py+++ b/studio/backend/tests/test_gguf_variant_preflight.py@@ -162,6 +162,108 @@ def test_a_verified_cached_copy_is_carried_to_the_load(remote_gguf_repo, monkeyp)+def test_a_verified_cached_copy_uses_a_projector_beside_it(+ remote_gguf_repo, monkeypatch, hub_cache+):+ """#9286: a projector beside the cached weight flips the config to vision."""+ name = "Llama-3.2-1B-Instruct-Q8_0.gguf"+ cached = _cached(hub_cache, name)+ projector = cached.parent / "mmproj-F16.gguf"+ projector.write_bytes(b"mmproj")+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: str(cached))++ config = ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0")++ assert config.is_vision is True+ # Carried for the training guard only: the launch resolves its own beside the weight.+ assert config.gguf_local_mmproj_file == str(projector.resolve())+ assert config.gguf_mmproj_file is None+++def test_a_verified_cached_copy_uses_its_repo_root_projector(+ remote_gguf_repo, monkeypatch, hub_cache+):+ """A projector dropped in models--<repo>/ is found."""+ name = "Llama-3.2-1B-Instruct-Q8_0.gguf"+ cached = _cached(hub_cache, name)+ projector = cached.parent.parent.parent / "mmproj-F16.gguf"+ projector.write_bytes(b"mmproj")+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: str(cached))++ config = ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0")++ assert config.is_vision is True+ assert config.gguf_local_mmproj_file == str(projector.resolve())+ assert config.gguf_mmproj_file is None+++def test_audio_only_repo_root_projector_still_triggers_companion_loading(+ remote_gguf_repo, monkeypatch, hub_cache+):+ """An audio-only projector flips the flag too; the loader reads its kind later."""+ name = "Llama-3.2-1B-Instruct-Q8_0.gguf"+ cached = _cached(hub_cache, name)+ projector = cached.parent.parent.parent / "mmproj-F16.gguf"+ projector.write_bytes(b"audio")+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: str(cached))+ monkeypatch.setattr(mc, "mmproj_accepts_image", lambda _path: False)++ config = ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0")++ assert config.is_vision is True+ assert config.gguf_mmproj_file is None+++def test_a_sibling_repos_projector_is_not_borrowed(remote_gguf_repo, monkeypatch, hub_cache):+ """The cache root and sibling repos stay invisible."""+ name = "Llama-3.2-1B-Instruct-Q8_0.gguf"+ cached = _cached(hub_cache, name)+ sibling = hub_cache / "models--someone--Other-GGUF"+ sibling.mkdir()+ (sibling / "mmproj-F16.gguf").write_bytes(b"mmproj")+ (hub_cache / "mmproj-F16.gguf").write_bytes(b"mmproj")+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: str(cached))++ config = ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0")++ assert config.gguf_local_mmproj_file is None+ assert config.is_vision is False+++def test_nothing_is_named_before_a_quant_of_the_repo_is_cached(+ remote_gguf_repo, monkeypatch, hub_cache+):+ """No weight to pair against yet."""+ repo_root = hub_cache / f"models--{REPO.replace('/', '--')}"+ repo_root.mkdir()+ (repo_root / "mmproj-F16.gguf").write_bytes(b"mmproj")+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: None)++ config = ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0")++ assert config.gguf_verified is None+ assert config.gguf_local_mmproj_file is None+ assert config.is_vision is False+++def test_a_published_projector_does_not_reach_the_local_lookup(+ remote_gguf_repo, monkeypatch, hub_cache+):+ """A repo that lists a projector never runs the walk."""+ name = "Llama-3.2-1B-Instruct-Q8_0.gguf"+ cached = _cached(hub_cache, name)+ (cached.parent.parent.parent / "mmproj-F16.gguf").write_bytes(b"mmproj")+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: str(cached))+ monkeypatch.setattr(+ mc, "list_gguf_variants", lambda identifier, hf_token = None: (list(VARIANTS), True)+ )++ config = ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0")++ assert config.is_vision is True+ assert config.gguf_local_mmproj_file is None++def test_every_shard_of_a_verified_cached_copy_is_measured(remote_gguf_repo, monkeypatch, hub_cache):diff --git a/studio/backend/tests/test_memory_estimate.py b/studio/backend/tests/test_memory_estimate.pyindex bbc47b04986..01cef6d0d5f 100644--- a/studio/backend/tests/test_memory_estimate.py+++ b/studio/backend/tests/test_memory_estimate.py@@ -697,6 +697,14 @@ class TestLocalizedEstimateConfig:config = _local_config(gqa_gguf)assert ri._localized_estimate_config(config, gqa_gguf) is config+ def test_a_hand_added_projector_above_the_snapshot_is_priced(self, gqa_gguf, tmp_path):+ # #9286: the projector sits in models--<repo>/, past the localizer's search root.+ projector = tmp_path / "mmproj-F16.gguf"+ projector.write_bytes(b"x")+ config = _repo_config(is_vision = True, gguf_local_mmproj_file = str(projector))+ local = ri._localized_estimate_config(config, gqa_gguf)+ assert local.gguf_mmproj_file == str(projector)+def test_repo_config_is_copied_never_mutated(self, gqa_gguf):# The original is sitting in _estimate_config_cache for the TTL, shared by# every later tick of the slider. A half-localized config escaping intodiff --git a/studio/backend/tests/test_mmproj_hf_cache_root.py b/studio/backend/tests/test_mmproj_hf_cache_root.pynew file mode 100644index 00000000000..26ac728c12a--- /dev/null+++ b/studio/backend/tests/test_mmproj_hf_cache_root.py@@ -0,0 +1,190 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Hand-added projector lookup for a remote (-hf) load over its HF cache repo (#9286)."""++from __future__ import annotations++import struct+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++from utils.models.model_config import ( # noqa: E402+ _hf_cache_repo_dir,+ _hf_cached_local_mmproj,+ _local_gguf_companion_search_root,+ detect_mmproj_file,+)++_GGUF_MAGIC = 0x46554747+++def _gguf_with_general(path: Path, fields: dict) -> Path:+ body = b""+ for k, v in fields.items():+ kb = k.encode("utf-8")+ vb = v.encode("utf-8")+ body += struct.pack("<Q", len(kb)) + kb+ body += struct.pack("<I", 8)+ body += struct.pack("<Q", len(vb)) + vb+ header = struct.pack("<IIQQ", _GGUF_MAGIC, 3, 0, len(fields))+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_bytes(header + body)+ return path+++def _hf_repo(tmp_path: Path, repo_name: str = "models--org--Model-GGUF") -> tuple[Path, Path]:+ repo = tmp_path / repo_name+ snapshot = repo / "snapshots" / "deadbeef"+ snapshot.mkdir(parents = True)+ weight = _gguf_with_general(+ snapshot / "model-Q4_K_M.gguf",+ {"general.name": "Model", "general.basename": "Model", "general.architecture": "qwen3vl"},+ )+ return repo, weight+++def _projector(path: Path, basename: str | None = None) -> Path:+ fields = {"general.type": "mmproj", "general.architecture": "qwen3vl"}+ if basename is not None:+ fields["general.basename"] = basename+ return _gguf_with_general(path, fields)+++def test_the_repo_dir_is_named_from_a_cached_weight(tmp_path):+ repo, weight = _hf_repo(tmp_path)++ assert _hf_cache_repo_dir(str(weight)) == str(repo)+++def test_a_quant_subdir_still_names_the_repo_dir(tmp_path):+ repo, weight = _hf_repo(tmp_path)+ quant_dir = weight.parent / "Q4_K_M"+ quant_dir.mkdir()+ weight = weight.rename(quant_dir / weight.name)++ assert _hf_cache_repo_dir(str(weight)) == str(repo)+++def test_a_plain_layout_names_no_repo_dir(tmp_path):+ model_dir = tmp_path / "MyModel"+ model_dir.mkdir()+ weight = _gguf_with_general(+ model_dir / "model.gguf", {"general.name": "Model", "general.architecture": "qwen3vl"}+ )++ assert _hf_cache_repo_dir(str(weight)) is None+ # And the lookup degrades to the weight's own directory rather than refusing.+ projector = _projector(model_dir / "mmproj-F16.gguf")+ assert _hf_cached_local_mmproj(str(weight)) == str(projector.resolve())+++def test_a_projector_beside_the_weight_is_found(tmp_path):+ """Where Studio's own Reveal in Folder lands, so the likeliest placement."""+ _repo, weight = _hf_repo(tmp_path)+ projector = _projector(weight.parent / "mmproj-kquant.gguf")++ assert _hf_cached_local_mmproj(str(weight)) == str(projector.resolve())+++def test_a_projector_at_the_repo_root_is_found(tmp_path):+ """Found one or two levels above the snapshot."""+ repo, weight = _hf_repo(tmp_path)+ projector = _projector(repo / "mmproj-kquant.gguf")++ assert _hf_cached_local_mmproj(str(weight)) == str(projector.resolve())+++def test_a_projector_in_the_snapshots_container_is_found(tmp_path):+ repo, weight = _hf_repo(tmp_path)+ projector = _projector(repo / "snapshots" / "mmproj-kquant.gguf")++ assert _hf_cached_local_mmproj(str(weight)) == str(projector.resolve())+++def test_a_sibling_repo_and_the_cache_root_stay_out_of_reach(tmp_path):+ """Never above models--<repo>: no borrowing another repo's projector."""+ _repo, weight = _hf_repo(tmp_path)+ sibling, _sibling_weight = _hf_repo(tmp_path, "models--org--Other-GGUF")+ _projector(sibling / "mmproj-kquant.gguf")+ _projector(tmp_path / "mmproj-kquant.gguf")++ assert _hf_cached_local_mmproj(str(weight)) is None+++def test_a_projector_for_another_model_is_refused(tmp_path):+ """Widening the walk widens what can be mispaired, so metadata still decides."""+ repo, weight = _hf_repo(tmp_path)+ _projector(repo / "mmproj-kquant.gguf", basename = "SomeOtherModel")++ assert _hf_cached_local_mmproj(str(weight)) is None+++def test_the_snapshots_own_projector_wins_when_the_far_one_cannot_pair(tmp_path):+ repo, weight = _hf_repo(tmp_path)+ _projector(repo / "mmproj-kquant.gguf", basename = "SomeOtherModel")+ near = _projector(weight.parent / "mmproj-F16.gguf", basename = "Model")++ assert _hf_cached_local_mmproj(str(weight)) == str(near.resolve())+++def test_an_empty_projector_is_not_named(tmp_path):+ """An interrupted copy is a file llama-server cannot open."""+ repo, weight = _hf_repo(tmp_path)+ (repo / "mmproj-kquant.gguf").write_bytes(b"")++ assert _hf_cached_local_mmproj(str(weight)) is None+++def test_a_local_selection_keeps_the_root_it_always_had(tmp_path):+ """The local-selection search root is unchanged."""+ repo, weight = _hf_repo(tmp_path)+ _projector(repo / "mmproj-kquant.gguf")++ root = _local_gguf_companion_search_root(str(weight.parent), str(weight))+ assert root == str(weight.parent)+ assert detect_mmproj_file(str(weight), search_root = root) is None+++def _resident(weight: Path, **overrides):+ from types import SimpleNamespace++ from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend++ state = dict(+ _is_vision = False,+ _disable_vision = False,+ _hf_repo = "org/Model-GGUF",+ _gguf_path = str(weight),+ _last_load_intent = GgufLoadIntent(model_identifier = "org/Model-GGUF", is_vision = False),+ )+ state.update(overrides)+ backend = SimpleNamespace(**state)+ return lambda extras = (): LlamaCppBackend._hand_added_projector_since_launch(+ backend, list(extras)+ )+++def test_a_projector_dropped_after_a_text_only_load_forces_a_reload(tmp_path):+ _repo, weight = _hf_repo(tmp_path)+ probe = _resident(weight)+ assert probe() is False++ _projector(weight.parent / "mmproj-F16.gguf")+ assert probe() is True+ assert probe(["--no-mmproj"]) is False+++def test_the_reload_trigger_leaves_other_residents_alone(tmp_path):+ from core.inference.llama_cpp import GgufLoadIntent++ _repo, weight = _hf_repo(tmp_path)+ _projector(weight.parent / "mmproj-F16.gguf")++ assert _resident(weight, _is_vision = True)() is False+ assert _resident(weight, _disable_vision = True)() is False+ assert _resident(weight, _hf_repo = None)() is False+ vision_intent = GgufLoadIntent(model_identifier = "org/Model-GGUF", is_vision = True)+ assert _resident(weight, _last_load_intent = vision_intent)() is Falsediff --git a/studio/backend/tests/test_mmproj_placement_policy.py b/studio/backend/tests/test_mmproj_placement_policy.pyindex cfeb3428475..621b439fa44 100644--- a/studio/backend/tests/test_mmproj_placement_policy.py+++ b/studio/backend/tests/test_mmproj_placement_policy.py@@ -35,6 +35,7 @@ from routes.inference import (_estimate_gguf_required_gb,_guard_chat_load_against_training,_llama_runtime_fields,+ _load_keeps_a_projector,_LoadPlacement,)@@ -761,6 +762,125 @@ def test_a_remote_projector_of_unknown_kind_is_charged_to_the_guard(tmp_path):assert seen.get("include_mmproj") is True+def test_the_training_guard_charges_a_hand_added_repo_root_projector(tmp_path):+ """A hand-added projector is charged though the listing cannot see it."""+ projector = tmp_path / "mmproj-F16.gguf"+ projector.write_bytes(b"\x00" * (3 * MIB))+ seen = {}++ def fake_companions(+ repo,+ *,+ hf_token,+ include_mmproj,+ local_mmproj_bytes = 0,+ **kw,+ ):+ seen["local_mmproj_bytes"] = local_mmproj_bytes+ # What the real helper returns when the repo lists no projector of its own.+ return max(int(local_mmproj_bytes), 0)++ config = SimpleNamespace(+ gguf_file = None,+ gguf_mmproj_file = None,+ gguf_local_mmproj_file = str(projector),+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ gguf_hf_repo = "unsloth/some-vl-GGUF",+ gguf_variant = "UD-Q4_K_XL",+ is_vision = True,+ )+ variant = SimpleNamespace(quant = "UD-Q4_K_XL", size_bytes = 4 * GIB)++ with (+ patch("routes.inference._remote_gguf_companion_bytes", fake_companions),+ patch(+ "utils.models.model_config.list_gguf_variants",+ lambda *a, **k: ([variant], False),+ ),+ ):+ charged = _estimate_gguf_required_gb(config)++ assert seen.get("local_mmproj_bytes") == 3 * MIB+ assert charged is not None and charged > 4 * GIB / (1024**3)+++ "kwargs,accepts_image,charged,label",+ [+ ({}, True, True, "no switch charges it"),+ ({"disable_vision": True}, True, False, "the switch suppresses an image tower"),+ ({"disable_vision": True}, False, True, "an audio encoder survives the switch"),+ ({"llama_extra_args": ["--no-mmproj"]}, True, False, "the extras opt-out resolves none"),+ ],+)+def test_the_guard_asks_the_local_projector_whether_the_launch_opens_it(+ tmp_path, kwargs, accepts_image, charged, label+):+ """A local projector the Vision switch suppresses is not charged."""+ projector = tmp_path / "mmproj-F16.gguf"+ projector.write_bytes(b"\x00" * (3 * MIB))+ seen = {}++ def fake_companions(+ repo,+ *,+ hf_token,+ include_mmproj,+ local_mmproj_bytes = 0,+ **kw,+ ):+ seen["local_mmproj_bytes"] = local_mmproj_bytes+ return max(int(local_mmproj_bytes), 0)++ config = SimpleNamespace(+ gguf_file = None,+ gguf_mmproj_file = None,+ gguf_local_mmproj_file = str(projector),+ gguf_mtp_file = None,+ gguf_dspark_file = None,+ gguf_dflash_file = None,+ gguf_hf_repo = "unsloth/some-vl-GGUF",+ gguf_variant = "UD-Q4_K_XL",+ is_vision = True,+ )+ variant = SimpleNamespace(quant = "UD-Q4_K_XL", size_bytes = 4 * GIB)+ import utils.models.gguf_metadata as _meta++ with (+ patch("routes.inference._remote_gguf_companion_bytes", fake_companions),+ patch.object(_meta, "mmproj_accepts_image", lambda _p: accepts_image),+ patch(+ "utils.models.model_config.list_gguf_variants",+ lambda *a, **k: ([variant], False),+ ),+ ):+ _estimate_gguf_required_gb(config, **kwargs)++ assert seen.get("local_mmproj_bytes") == (3 * MIB if charged else 0), label+++def test_gpu_ownership_reads_the_remote_configs_own_projector(tmp_path):+ """A suppressed local image tower does not claim the GPU."""+ projector = tmp_path / "mmproj-F16.gguf"+ projector.write_bytes(b"\x00" * MIB)+ config = SimpleNamespace(+ is_vision = True,+ gguf_mmproj_file = None,+ gguf_local_mmproj_file = str(projector),+ )+ import utils.models.gguf_metadata as _meta++ with patch.object(_meta, "mmproj_accepts_image", lambda _p: True):+ assert _load_keeps_a_projector(config, disable_vision = True) is False+ assert _load_keeps_a_projector(config, disable_vision = False) is True++ # An audio encoder has no image tower to drop, so the switch leaves it loaded.+ with patch.object(_meta, "mmproj_accepts_image", lambda _p: False):+ assert _load_keeps_a_projector(config, disable_vision = True) is True++def _ambient_mmproj(tmp_path, monkeypatch):ambient = tmp_path / "ambient-mmproj.gguf"ambient.write_bytes(b"\x00" * (1 * MIB))diff --git a/studio/backend/utils/models/gguf_metadata.py b/studio/backend/utils/models/gguf_metadata.pyindex 70778969377..0eaa07ab37e 100644--- a/studio/backend/utils/models/gguf_metadata.py+++ b/studio/backend/utils/models/gguf_metadata.py@@ -914,9 +914,15 @@ def mmproj_accepts_image(path: str) -> bool:def is_mmproj_by_metadata(meta: Optional[Dict[str, str]]) -> Optional[bool]:- """True/False from ``general.type``; None means fall back to filename."""+ """True/False from ``general.type``; None means fall back to filename.++ ``general.architecture == "clip"`` is llama.cpp's projector arch and wins: older+ converters wrote ``general.type`` values like ``clip-vision`` (#9286).+ """if not meta:return None+ if (meta.get("general.architecture") or "").lower() == "clip":+ return Truet = meta.get("general.type")if t is None:return Nonediff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex cedda199bfd..05091d54486 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -2992,6 +2992,27 @@ def _local_gguf_companion_search_root(selected_path: str, gguf_file: str) -> strreturn str(search_dir)+def _hf_cache_repo_dir(weight_path: str) -> Optional[str]:+ """The ``models--<repo>`` dir *weight_path* was cached into, or None elsewhere.++ Never wider than the weight's own repo, so a sibling repo's projector stays out of+ reach. Case-insensitive: cache resolution finds a weight in any case variant.+ """+ for directory in Path(weight_path).parents:+ parent = directory.parent+ if parent.name.casefold() == "snapshots" and parent.parent.name.casefold().startswith(+ "models--"+ ):+ return str(parent.parent)+ return None+++def _hf_cached_local_mmproj(weight_path: str) -> Optional[str]:+ """A hand-added projector in *weight_path*'s snapshot, ``snapshots/`` or+ ``models--<repo>/``, or None (#9286). Metadata pairing decides between them."""+ return detect_mmproj_file(weight_path, search_root = _hf_cache_repo_dir(weight_path))++def _snapshot_selection_key(snapshot: Path) -> tuple[float, str]:"""Order snapshots by mtime, then by resolved path.@@ -4247,6 +4268,8 @@ class ModelConfig:# ``sizes`` covers that file and every shard beside it.gguf_verified: Optional[tuple[str, str, str, tuple[tuple[str, int], ...]]] = Nonegguf_mmproj_file: Optional[str] = None # Full path to the mmproj .gguf file (vision projection)+ # Remote (-hf) only: hand-added projector for VRAM accounting, never passed to llama-server.+ gguf_local_mmproj_file: Optional[str] = Nonegguf_mtp_file: Optional[str] = None # Full path to the separate MTP drafter (local mode)gguf_dspark_file: Optional[str] = None # Full path to a DSpark sidecar (local mode)gguf_dflash_file: Optional[str] = None # Full path to a DFlash sidecar (local mode)@@ -4667,6 +4690,12 @@ class ModelConfig:if sizes:verified_gguf = (identifier, variant, verified_file, sizes)+ # A projector hand-added beside the cached weight (#9286).+ local_mmproj: Optional[str] = None+ if not has_vision and verified_file:+ local_mmproj = _hf_cached_local_mmproj(verified_file)+ has_vision = local_mmproj is not None+display_name = f"{identifier.split('/')[-1]} ({variant})"# Debug: from_identifier is re-resolved on every validate, estimate and# load. The load path announces the model it actually starts.@@ -4685,6 +4714,7 @@ class ModelConfig:is_gguf = True,gguf_file = None,gguf_verified = verified_gguf,+ gguf_local_mmproj_file = local_mmproj,gguf_hf_repo = identifier,gguf_variant = variant,)