Skip to content

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

Studio: reuse the cached GGUF work a load request has already done (#8771)

oobabooga92c8ea9c2135
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index bf71dcc8fa8..6956d2d38be 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -151,6 +151,8 @@ class GgufLoadIntent:
model_identifier: str
gguf_path: Optional[str] = None
+ # A cached file and every shard's byte count, already verified for this repo and variant.
+ verified_gguf: Optional[tuple[str, str, str, tuple[tuple[str, int], ...]]] = None
mmproj_path: Optional[str] = None
mtp_draft_path: Optional[str] = None
dspark_draft_path: Optional[str] = None
@@ -1500,6 +1502,31 @@ def _cached_variant_candidates(
logger.debug(f"Cache lookup for variant failed: {e}")
+def _cached_variant_sizes(
+ repo_id: str, hf_variant: str, main_path: str
+) -> Optional[tuple[tuple[str, int], ...]]:
+ """Sorted ``(filename, size)`` pairs for the cached variant copy at ``main_path``.
+
+ None when no complete cached copy resolves to that path. ``_cached_variant_candidates``
+ owns the shard set and every read is local, so recording this and comparing it later
+ catches a truncated, resized or dropped file without a Hub lookup.
+ """
+ target = os.path.abspath(main_path)
+ for cached_main, main, shards, snap in _cached_variant_candidates(repo_id, hf_variant):
+ if os.path.abspath(cached_main) != target:
+ continue
+ try:
+ return tuple(
+ sorted(
+ (name, os.path.getsize(snap.joinpath(*name.replace("\\", "/").split("/"))))
+ for name in (main, *shards)
+ )
+ )
+ except OSError:
+ return None
+ return None
+
+
def _cached_candidate_matches_revision_size(
repo_id: str, candidate: tuple[str, str, list[str], Path], hf_token: Optional[str]
) -> bool:
@@ -8319,6 +8346,44 @@ class LlamaCppBackend:
probe._read_gguf_metadata(gguf_path)
return probe._non_chat_gguf_refusal(gguf_path)
+ @classmethod
+ def _verified_cached_gguf(cls, intent, hf_repo, hf_variant) -> Optional[str]:
+ """Return a carried file only if it still matches the load and active cache."""
+ verified = getattr(intent, "verified_gguf", None)
+ if not verified:
+ return None
+ try:
+ repo, variant, path, sizes = verified
+ except (TypeError, ValueError):
+ return None
+ if (repo or "").lower() != (hf_repo or "").lower():
+ return None
+ if (variant or "").lower() != (hf_variant or "").lower():
+ return None
+ if not path:
+ return None
+ try:
+ if not Path(path).is_file():
+ return None
+ from utils.hf_cache_settings import get_hf_cache_paths
+ hub_cache = Path(os.path.abspath(get_hf_cache_paths().hub_cache))
+ except Exception: # noqa: BLE001 -- an unreadable cache setting is not a reusable path
+ return None
+ # Cache settings can change while a load is in flight.
+ try:
+ if not Path(os.path.abspath(path)).is_relative_to(hub_cache):
+ return None
+ except (OSError, ValueError):
+ return None
+ # Recheck the recorded byte count of every shard against the set this
+ # snapshot still holds. Both are local, so reuse still avoids Hub calls.
+ try:
+ if _cached_variant_sizes(_resolve_repo_id_casing(repo), variant, path) != sizes:
+ return None
+ except OSError:
+ return None
+ return path
+
@classmethod
def non_chat_gguf_refusal_for_intent(cls, intent) -> Optional[str]:
"""The header verdict for a resolved load intent, or None.
@@ -8335,6 +8400,11 @@ class LlamaCppBackend:
return cls._non_chat_gguf_refusal_for_path(gguf_path, identifier)
if hf_repo:
hf_variant = getattr(intent, "hf_variant", None)
+ verified = cls._verified_cached_gguf(intent, hf_repo, hf_variant)
+ if verified:
+ verdict = cls._non_chat_gguf_refusal_for_path(verified, identifier)
+ cls._hand_over_route_verdict(hf_repo, hf_variant, verdict)
+ return verdict
# Same offline window as the download: the probe asks the Hub before reading
# any local header, and those calls would otherwise wait out their retry
# backoff on an unreachable Hub.
@@ -12948,11 +13018,18 @@ class LlamaCppBackend:
)
hf_repo = _resolved_repo
with _hf_offline_if_unreachable():
- model_path = _preflight_model_path or self._download_gguf(
- hf_repo = hf_repo,
- hf_variant = hf_variant,
- hf_token = hf_token,
- )
+ model_path = _preflight_model_path
+ if model_path is None:
+ # Revalidate the carried file before skipping download resolution.
+ model_path = self._verified_cached_gguf(intent, hf_repo, hf_variant)
+ if model_path:
+ logger.info("Reusing verified cached GGUF: %s", model_path)
+ if model_path is None:
+ model_path = self._download_gguf(
+ hf_repo = hf_repo,
+ hf_variant = hf_variant,
+ hf_token = hf_token,
+ )
# Auto-download mmproj for vision models unless opted out.
if is_vision and not mmproj_path and not extra_args_disable_mmproj(extra_args):
mmproj_path = self._download_mmproj(
@@ -16936,8 +17013,10 @@ class LlamaCppBackend:
self._requested_n_batch = intent.n_batch
self._requested_n_ubatch = intent.n_ubatch
# Commit the known-good snapshot + whether MTP+tensor is live, then
- # watch this load for a mid-generation crash.
- self._last_load_intent = intent
+ # watch this load for a mid-generation crash. The verified-cache hint is
+ # dropped: a respawn replays this snapshot arbitrarily later, so recovery
+ # re-resolves the file instead of trusting a path this request verified.
+ self._last_load_intent = replace(intent, verified_gguf = None)
self._mtp_runtime_fallback_active = _mtp_active_for_launched_server
self._start_mtp_crash_watchdog()
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 47f62190aec..4bcd0da59eb 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -7095,6 +7095,7 @@ def _resolve_gguf_load_intent(
hf_repo = config.gguf_hf_repo,
hf_variant = config.gguf_variant,
hf_token = request.hf_token,
+ verified_gguf = getattr(config, "gguf_verified", None),
)
else:
if native_grant_backed:
diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.py
index bce7e496d67..34b1d739521 100644
--- a/studio/backend/tests/test_gguf_load_cache_reuse.py
+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py
@@ -646,6 +646,37 @@ class TestCachedGgufForLoadProbe:
class TestLoadHubDownloadExclusion:
+ def test_remote_intent_carries_the_verified_cache_hint(self):
+ from models.inference import LoadRequest
+
+ route = _load_route_module(
+ "inference_route_module_for_verified_cache_hint",
+ "routes/inference.py",
+ )
+ verified = (REPO, VARIANT, "/cached/model.gguf", ((MAIN, 123),))
+ config = SimpleNamespace(
+ identifier = REPO,
+ gguf_hf_repo = REPO,
+ gguf_variant = VARIANT,
+ gguf_verified = verified,
+ is_vision = False,
+ )
+
+ intent = route._resolve_gguf_load_intent(
+ config,
+ LoadRequest(model_path = REPO, gguf_variant = VARIANT),
+ native_grant_backed = False,
+ chat_template_override = None,
+ extra_args = None,
+ placement = SimpleNamespace(
+ resolved_gpu_ids = None,
+ gpu_ids_are_vulkan_ordinals = None,
+ ),
+ n_parallel = 1,
+ )
+
+ assert intent.verified_gguf == verified
+
def test_resident_local_directory_intent_uses_variant_until_path_is_resolved(self):
from models.inference import LoadRequest
diff --git a/studio/backend/tests/test_gguf_variant_preflight.py b/studio/backend/tests/test_gguf_variant_preflight.py
index 84ab7649fba..539be0f498d 100644
--- a/studio/backend/tests/test_gguf_variant_preflight.py
+++ b/studio/backend/tests/test_gguf_variant_preflight.py
@@ -1,10 +1,14 @@
"""An explicit --gguf-variant that exists nowhere must be rejected by
ModelConfig.from_identifier, before the load path unloads the resident model."""
+from pathlib import Path
+from types import SimpleNamespace
+
import huggingface_hub
import pytest
import core.inference.llama_cpp as llama_cpp
+import utils.hf_cache_settings as hf_cache_settings
import utils.models.model_config as mc
from utils.models.model_config import GgufVariantInfo, ModelConfig
@@ -40,6 +44,28 @@ def remote_gguf_repo(monkeypatch):
monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kwargs: None)
+def hub_cache(tmp_path, monkeypatch):
+ """Point the active Hub cache at a temp root."""
+ monkeypatch.setattr(
+ hf_cache_settings, "get_hf_cache_paths", lambda: SimpleNamespace(hub_cache = tmp_path)
+ )
+ return tmp_path
+
+
+def _cached(
+ root: Path,
+ name: str,
+ payload: bytes = b"cached",
+) -> Path:
+ """Write a GGUF into a snapshot of ``REPO`` under the active Hub cache."""
+ snapshot = root / f"models--{REPO.replace('/', '--')}" / "snapshots" / ("a" * 40)
+ snapshot.mkdir(parents = True, exist_ok = True)
+ path = snapshot / name
+ path.write_bytes(payload)
+ return path
+
+
def test_unknown_variant_rejected_before_load(remote_gguf_repo):
with pytest.raises(ValueError) as exc_info:
ModelConfig.from_identifier(REPO, gguf_variant = "NOPE_Q9")
@@ -61,11 +87,13 @@ def test_variant_match_is_case_insensitive(remote_gguf_repo):
assert config.gguf_variant == "q4_k_m"
-def test_variant_only_in_verified_local_cache_accepted(remote_gguf_repo, monkeypatch):
+def test_variant_only_in_verified_local_cache_accepted(remote_gguf_repo, monkeypatch, tmp_path):
+ cached = tmp_path / "Llama-3.2-1B-Instruct-OLD_Q2.gguf"
+ cached.write_bytes(b"cached")
monkeypatch.setattr(
llama_cpp,
"cached_gguf_for_load",
- lambda repo, variant, **kwargs: "/cache/Llama-3.2-1B-Instruct-OLD_Q2.gguf",
+ lambda repo, variant, **kwargs: str(cached),
)
config = ModelConfig.from_identifier(REPO, gguf_variant = "OLD_Q2")
assert config is not None
@@ -117,3 +145,107 @@ def test_no_variant_still_autoselects(remote_gguf_repo):
config = ModelConfig.from_identifier(REPO)
assert config is not None
assert config.gguf_variant in {"Q4_K_M", "Q8_0"}
+
+
+def test_a_verified_cached_copy_is_carried_to_the_load(remote_gguf_repo, monkeypatch, hub_cache):
+ """Config carries the cached file it already verified."""
+ name = "Llama-3.2-1B-Instruct-Q8_0.gguf"
+ cached = _cached(hub_cache, name)
+ 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_verified == (
+ REPO,
+ "Q8_0",
+ str(cached),
+ ((name, cached.stat().st_size),),
+ )
+
+
+def test_every_shard_of_a_verified_cached_copy_is_measured(
+ remote_gguf_repo, monkeypatch, hub_cache
+):
+ """A split copy carries all of its shards, not just the one the load opens."""
+ shards = {
+ f"Llama-3.2-1B-Instruct-Q8_0-0000{n}-of-00003.gguf": b"x" * (10 + n) for n in (1, 2, 3)
+ }
+ written = {name: _cached(hub_cache, name, payload) for name, payload in shards.items()}
+ main = written["Llama-3.2-1B-Instruct-Q8_0-00001-of-00003.gguf"]
+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: str(main))
+
+ config = ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0")
+ assert config.gguf_verified == (
+ REPO,
+ "Q8_0",
+ str(main),
+ tuple(sorted((name, len(payload)) for name, payload in shards.items())),
+ )
+
+
+def test_a_cached_copy_outside_the_variant_set_is_not_carried(
+ remote_gguf_repo, monkeypatch, hub_cache
+):
+ """Nothing is carried when the shard set cannot be derived for the path."""
+ loose = hub_cache / "Llama-3.2-1B-Instruct-Q8_0.gguf"
+ loose.write_bytes(b"cached")
+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: str(loose))
+
+ assert ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0").gguf_verified is None
+
+
+def test_a_verified_cached_copy_settles_the_variant_without_a_second_listing(
+ remote_gguf_repo, monkeypatch, tmp_path
+):
+ """A verified cached file proves the requested variant exists."""
+ listings = []
+ cached = tmp_path / "old.gguf"
+ cached.write_bytes(b"cached")
+
+ def counting_list_repo_files(repo_id, token = None):
+ listings.append(repo_id)
+ return list(REPO_FILES)
+
+ monkeypatch.setattr(huggingface_hub, "list_repo_files", counting_list_repo_files)
+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: str(cached))
+
+ config = ModelConfig.from_identifier(REPO, gguf_variant = "OLD_Q2")
+ assert config.gguf_variant == "OLD_Q2"
+ assert listings == [], "a verified cached file still cost a repo listing"
+
+ # Nothing cached: the listing runs and still rejects a variant it does not name.
+ listings.clear()
+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kw: None)
+ with pytest.raises(ValueError, match = "OLD_Q2"):
+ ModelConfig.from_identifier(REPO, gguf_variant = "OLD_Q2")
+ assert listings == [REPO]
+
+
+def test_the_auto_selected_variant_carries_its_own_verified_copy(
+ remote_gguf_repo, monkeypatch, hub_cache
+):
+ """No explicit variant means config picks one, and that pick is what the load asks for."""
+ asked = []
+
+ def fake_cached_gguf_for_load(repo, variant, **kw):
+ asked.append((repo, variant, kw.get("verify_sizes")))
+ return str(_cached(hub_cache, f"Llama-3.2-1B-Instruct-{variant}.gguf"))
+
+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", fake_cached_gguf_for_load)
+
+ config = ModelConfig.from_identifier(REPO)
+ assert config.gguf_variant in {"Q4_K_M", "Q8_0"}
+ assert asked == [(REPO, config.gguf_variant, True)]
+ name = f"Llama-3.2-1B-Instruct-{config.gguf_variant}.gguf"
+ cached = hub_cache / f"models--{REPO.replace('/', '--')}" / "snapshots" / ("a" * 40) / name
+ assert config.gguf_verified == (
+ REPO,
+ config.gguf_variant,
+ str(cached),
+ ((name, cached.stat().st_size),),
+ )
+
+
+def test_nothing_is_carried_when_no_cached_copy_verifies(remote_gguf_repo):
+ """A first-time download has no cached path to carry."""
+ assert ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0").gguf_verified is None
+ assert ModelConfig.from_identifier(REPO).gguf_verified is None
diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.py
index 3c60c60eba5..51a6150273f 100644
--- a/studio/backend/tests/test_gpu_memory_mode.py
+++ b/studio/backend/tests/test_gpu_memory_mode.py
@@ -718,7 +718,10 @@ def test_remote_vulkan_diffusion_preflight_runs_before_teardown(monkeypatch):
preflight = src.index("_preflight_model_path = self._download_gguf(")
teardown = src.index("# ── Phase 1: kill old process")
assert preflight < teardown
- assert "model_path = _preflight_model_path or self._download_gguf(" in src
+ # Phase 2 uses the preflight result before falling back to a download.
+ phase_two = src.index("model_path = _preflight_model_path", teardown)
+ download = src.index("model_path = self._download_gguf(", teardown)
+ assert phase_two < download
def test_local_vulkan_diffusion_preflight_runs_before_teardown():
diff --git a/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.py b/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.py
index 2dffed5eee7..e08756c14f1 100644
--- a/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.py
+++ b/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import contextlib
import inspect
import struct
+from dataclasses import replace
from pathlib import Path
import pytest
@@ -621,3 +622,382 @@ def test_a_handoff_for_another_model_is_not_taken(monkeypatch):
hf_repo = "owner/a", hf_variant = "Q8_0", hf_token = None, model_identifier = "owner/a"
)
assert calls == ["owner/a", "owner/b", "owner/a"]
+
+
+# Cached GGUF reuse
+
+
+def _intent(**changes) -> GgufLoadIntent:
+ base = dict(
+ model_identifier = "owner/model",
+ hf_repo = "owner/model",
+ hf_variant = "Q4_K_M",
+ )
+ base.update(changes)
+ return GgufLoadIntent(**base)
+
+
+def _hub_cache(monkeypatch, root):
+ """Point the active Hub cache at ``root``."""
+ import types as _types
+
+ import utils.hf_cache_settings as hf_cache_settings
+
+ monkeypatch.setattr(
+ hf_cache_settings,
+ "get_hf_cache_paths",
+ lambda: _types.SimpleNamespace(hub_cache = Path(root)),
+ )
+
+
+def _cached_gguf(root: Path, name: str, payload: bytes) -> Path:
+ """Create a cached GGUF under ``root``."""
+ snapshot = root / "models--owner--model" / "snapshots" / ("a" * 40)
+ snapshot.mkdir(parents = True, exist_ok = True)
+ path = snapshot / name
+ path.write_bytes(payload)
+ return path
+
+
+def _verified(
+ path: Path,
+ repo: str = "owner/model",
+ variant: str = "Q4_K_M",
+):
+ """What config resolution carries for a cached copy it just verified."""
+ return (
+ repo,
+ variant,
+ str(path),
+ llama_cpp_module._cached_variant_sizes(repo, variant, str(path)),
+ )
+
+
+def test_a_verified_cached_file_is_judged_without_resolving_it_again(monkeypatch, tmp_path):
+ """The probe reuses the file verified during config resolution."""
+ _hub_cache(monkeypatch, tmp_path)
+ cached = _cached_gguf(tmp_path, "ltx-2-19b-dev-Q4_K_M.gguf", _gguf_bytes(arch = "ltxv"))
+
+ def _no_hub(*_a, **_k):
+ raise AssertionError("the probe went back to the Hub for a file it was handed")
+
+ monkeypatch.setattr(llama_cpp_module, "_resolve_variant_gguf_files", _no_hub)
+ monkeypatch.setattr(llama_cpp_module, "cached_gguf_for_load", _no_hub)
+ monkeypatch.setattr(diffusion_compat, "_read_gguf_header", _no_hub)
+
+ intent = _intent(verified_gguf = _verified(cached))
+ verdict = LlamaCppBackend.non_chat_gguf_refusal_for_intent(intent)
+ assert verdict is not None and "Video page" in verdict
+
+ # The verdict is also handed to the in-load probe.
+ assert (
+ LlamaCppBackend._remote_non_chat_gguf_refusal(
+ hf_repo = "owner/model",
+ hf_variant = "Q4_K_M",
+ hf_token = None,
+ model_identifier = None,
+ )
+ == verdict
+ )
+
+
+def test_a_chat_gguf_carried_the_same_way_is_still_not_refused(monkeypatch, tmp_path):
+ _hub_cache(monkeypatch, tmp_path)
+ cached = _cached_gguf(tmp_path, "chat-Q4_K_M.gguf", _gguf_bytes(arch = "llama"))
+
+ def _no_hub(*_a, **_k):
+ raise AssertionError("the probe went back to the Hub for a file it was handed")
+
+ monkeypatch.setattr(llama_cpp_module, "_resolve_variant_gguf_files", _no_hub)
+ monkeypatch.setattr(llama_cpp_module, "cached_gguf_for_load", _no_hub)
+
+ intent = _intent(verified_gguf = _verified(cached))
+ assert LlamaCppBackend.non_chat_gguf_refusal_for_intent(intent) is None
+
+
+def test_a_carried_path_is_only_used_for_the_repo_and_variant_it_was_verified_for(
+ monkeypatch, tmp_path
+):
+ """A carried path is valid only for its verified repo and variant."""
+ _hub_cache(monkeypatch, tmp_path)
+ cached = _cached_gguf(tmp_path, "model-Q4_K_M.gguf", b"GGUF")
+ verified = _verified(cached)
+ take = LlamaCppBackend._verified_cached_gguf
+
+ assert take(_intent(verified_gguf = verified), "owner/model", "Q4_K_M") == str(cached)
+ # Repo and variant matching is case-insensitive.
+ assert take(_intent(verified_gguf = verified), "Owner/Model", "Q4_K_M") == str(cached)
+ assert take(_intent(verified_gguf = verified), "owner/model", "q4_k_m") == str(cached)
+
+ # Other repos and variants fall back to normal resolution.
+ assert take(_intent(verified_gguf = verified), "owner/model", "Q8_0") is None
+ assert take(_intent(verified_gguf = verified), "other/model", "Q4_K_M") is None
+ assert take(_intent(verified_gguf = verified), "owner/model", None) is None
+
+ # Missing or malformed values are ignored.
+ assert take(_intent(), "owner/model", "Q4_K_M") is None
+ assert take(_intent(verified_gguf = ("owner/model",)), "owner/model", "Q4_K_M") is None
+ assert (
+ take(
+ _intent(verified_gguf = ("owner/model", "Q4_K_M", str(cached))),
+ "owner/model",
+ "Q4_K_M",
+ )
+ is None
+ )
+ assert take(_intent(verified_gguf = "just-a-path"), "owner/model", "Q4_K_M") is None
+
+
+def test_a_file_deleted_between_the_request_and_the_launch_is_not_reused(monkeypatch, tmp_path):
+ """A deleted carried file must not be reused."""
+ _hub_cache(monkeypatch, tmp_path)
+ cached = _cached_gguf(tmp_path, "model-Q4_K_M.gguf", b"GGUF")
+ intent = _intent(verified_gguf = _verified(cached))
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") == str(cached)
+
+ cached.unlink()
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") is None
+
+ # A directory at the path is not a model either.
+ cached.mkdir()
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") is None
+
+
+def test_a_file_truncated_after_config_resolution_is_not_reused(monkeypatch, tmp_path):
+ _hub_cache(monkeypatch, tmp_path)
+ cached = _cached_gguf(tmp_path, "model-Q4_K_M.gguf", b"GGUF payload")
+ intent = _intent(verified_gguf = _verified(cached))
+
+ cached.write_bytes(b"GGUF")
+
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") is None
+
+
+def test_an_incomplete_shard_set_after_config_resolution_is_not_reused(monkeypatch, tmp_path):
+ _hub_cache(monkeypatch, tmp_path)
+ main = _cached_gguf(
+ tmp_path,
+ "model-Q4_K_M-00001-of-00002.gguf",
+ b"first shard",
+ )
+ sibling = _cached_gguf(
+ tmp_path,
+ "model-Q4_K_M-00002-of-00002.gguf",
+ b"second shard",
+ )
+ intent = _intent(verified_gguf = _verified(main))
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") == str(main)
+
+ sibling.unlink()
+
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") is None
+
+
+def test_a_shard_truncated_after_config_resolution_is_not_reused(monkeypatch, tmp_path):
+ """A shard that shrinks is as unusable as one that disappears.
+
+ The shard set alone only proves the siblings exist, so the carried value records
+ every shard's byte count and Phase 2 rechecks all of them.
+ """
+ _hub_cache(monkeypatch, tmp_path)
+ main = _cached_gguf(tmp_path, "model-Q4_K_M-00001-of-00003.gguf", b"first shard")
+ second = _cached_gguf(tmp_path, "model-Q4_K_M-00002-of-00003.gguf", b"second shard")
+ _cached_gguf(tmp_path, "model-Q4_K_M-00003-of-00003.gguf", b"third shard")
+ intent = _intent(verified_gguf = _verified(main))
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") == str(main)
+
+ second.write_bytes(b"sec")
+
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") is None
+
+ # A shard that grows past its recorded size is a different set too.
+ second.write_bytes(b"second shard and more")
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") is None
+
+
+def test_the_probe_falls_back_to_resolving_when_nothing_usable_is_carried(monkeypatch, tmp_path):
+ """An unusable carried file falls back to normal resolution."""
+ missing = tmp_path / "gone-Q4_K_M.gguf"
+ header = _gguf_bytes(arch = "flux")
+ requests: list[tuple[str, str]] = []
+
+ monkeypatch.setattr(
+ llama_cpp_module,
+ "_resolve_variant_gguf_files",
+ lambda *_a, **_k: ("model-Q4_K_M.gguf", []),
+ )
+ monkeypatch.setattr(llama_cpp_module, "cached_gguf_for_load", lambda *_a, **_k: None)
+ monkeypatch.setattr(
+ diffusion_compat,
+ "_read_gguf_header",
+ lambda repo_id, gguf_filename, hf_token: (
+ requests.append((repo_id, gguf_filename)) or header
+ ),
+ )
+
+ _hub_cache(monkeypatch, tmp_path)
+ intent = _intent(verified_gguf = ("owner/model", "Q4_K_M", str(missing), 123))
+ verdict = LlamaCppBackend.non_chat_gguf_refusal_for_intent(intent)
+ assert verdict is not None and "Images page" in verdict
+ assert requests == [("owner/model", "model-Q4_K_M.gguf")]
+
+
+def test_the_launch_reuses_the_carried_file_instead_of_resolving_it_again():
+ """The launch checks the carried file before downloading."""
+ src = inspect.getsource(llama_cpp_module.LlamaCppBackend.load_model)
+ teardown = src.index("# ── Phase 1: kill old process")
+ reuse = src.index("self._verified_cached_gguf(intent, hf_repo, hf_variant)")
+ # Search after teardown to skip the placement preflight download.
+ download = src.index("model_path = self._download_gguf(", teardown)
+ assert teardown < reuse < download, "the carried file is not consulted before the download"
+
+
+def test_a_carried_path_outside_the_active_cache_is_not_reused(monkeypatch, tmp_path):
+ """A carried path must remain inside the active Hub cache."""
+ old_root, new_root = tmp_path / "old", tmp_path / "new"
+ _hub_cache(monkeypatch, old_root)
+ cached = _cached_gguf(old_root, "model-Q4_K_M.gguf", b"GGUF")
+ intent = _intent(verified_gguf = _verified(cached))
+
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") == str(cached)
+
+ # Moving the cache leaves the old file readable but no longer active.
+ new_root.mkdir()
+ _hub_cache(monkeypatch, new_root)
+ assert cached.is_file()
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") is None
+
+ # Restoring the cache root makes the file valid again.
+ _hub_cache(monkeypatch, old_root)
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") == str(cached)
+
+ # Reject paths outside the cache and unreadable cache settings.
+ loose = tmp_path / "loose-Q4_K_M.gguf"
+ loose.write_bytes(b"GGUF")
+ loose_intent = _intent(verified_gguf = _verified(loose))
+ assert LlamaCppBackend._verified_cached_gguf(loose_intent, "owner/model", "Q4_K_M") is None
+
+ import utils.hf_cache_settings as hf_cache_settings
+
+ def _unreadable():
+ raise RuntimeError("cache settings unavailable")
+
+ monkeypatch.setattr(hf_cache_settings, "get_hf_cache_paths", _unreadable)
+ assert LlamaCppBackend._verified_cached_gguf(intent, "owner/model", "Q4_K_M") is None
+
+
+def test_the_probe_resolves_normally_when_the_cache_moved_under_it(monkeypatch, tmp_path):
+ """A moved cache falls back to normal resolution."""
+ old_root, new_root = tmp_path / "old", tmp_path / "new"
+ new_root.mkdir()
+ cached = _cached_gguf(old_root, "model-Q4_K_M.gguf", _gguf_bytes(arch = "ltxv"))
+ _hub_cache(monkeypatch, new_root)
+
+ requests: list[tuple[str, str]] = []
+ monkeypatch.setattr(
+ llama_cpp_module,
+ "_resolve_variant_gguf_files",
+ lambda *_a, **_k: ("model-Q4_K_M.gguf", []),
+ )
+ monkeypatch.setattr(llama_cpp_module, "cached_gguf_for_load", lambda *_a, **_k: None)
+ monkeypatch.setattr(
+ diffusion_compat,
+ "_read_gguf_header",
+ lambda repo_id, gguf_filename, hf_token: (
+ requests.append((repo_id, gguf_filename)) or _gguf_bytes(arch = "ltxv")
+ ),
+ )
+
+ intent = _intent(verified_gguf = _verified(cached))
+ verdict = LlamaCppBackend.non_chat_gguf_refusal_for_intent(intent)
+ assert verdict is not None and "Video page" in verdict
+ assert requests == [("owner/model", "model-Q4_K_M.gguf")]
+
+
+def test_the_launch_opens_the_carried_file_instead_of_resolving_it(monkeypatch, tmp_path):
+ """Phase 2 opens the carried file; with nothing carried it resolves and verifies again."""
+ _hub_cache(monkeypatch, tmp_path)
+ cached = _cached_gguf(tmp_path, "m-Q4_K_M.gguf", _gguf_bytes(arch = "llama"))
+
+ def _load(verified) -> list[str]:
+ order: list[str] = []
+ backend = LlamaCppBackend()
+ # A route ask no load came for is still handed over for this key.
+ monkeypatch.setattr(LlamaCppBackend, "_route_verdict_handoff", None)
+ _repo_load(monkeypatch, backend, order)
+ monkeypatch.setattr(
+ backend, "_download_gguf", lambda **_k: order.append("download") or str(cached)
+ )
+ monkeypatch.setattr(
+ diffusion_compat, "_read_gguf_header", lambda *_a, **_k: _gguf_bytes(arch = "llama")
+ )
+
+ def _stop(**_kwargs):
+ raise RuntimeError("stop here")
+
+ # The first companion fetch past the download decision, so the load stops there.
+ monkeypatch.setattr(backend, "_download_mtp", _stop)
+ with pytest.raises(RuntimeError, match = "stop here"):
+ backend.load_model(_intent(verified_gguf = verified))
+ return order
+
+ assert _load(_verified(cached)) == ["kill"]
+ assert _load(None) == ["kill", "download"]
+
+
+def _launchable_backend(monkeypatch) -> LlamaCppBackend:
+ """A backend whose launch succeeds without a real llama-server."""
+
+ class _Process:
+ pid = 123
+ stdout = ()
+ returncode = None
+
+ def poll(self):
+ return None
+
+ def terminate(self):
+ return None
+
+ def wait(self, timeout = None):
+ return None
+
+ def kill(self):
+ return None
+
+ backend = LlamaCppBackend()
+ backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"
+ backend._get_gpu_memory = lambda _binary = None, **_kw: []
+ backend._get_gpu_free_memory = lambda _binary = None, **_kw: []
+ backend._read_gguf_metadata = lambda _path: None
+ backend._can_estimate_kv = lambda: False
+ backend._get_gguf_size_bytes = lambda _path: 1024
+ backend._resolve_launch_mmproj_path = lambda **_kwargs: None
+ backend._record_server_pid = lambda _pid: None
+ backend._clear_server_pid = lambda: None
+ backend._llama_server_env_for_binary = lambda _binary: {}
+ backend._wait_for_health = lambda timeout: True
+ backend.probe_server_capabilities = lambda _binary: {"found": True}
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: False)
+ )
+ monkeypatch.setattr(llama_cpp_module.subprocess, "Popen", lambda cmd, **_kw: _Process())
+ return backend
+
+
+def test_the_snapshot_kept_for_a_respawn_carries_no_verified_file(monkeypatch, tmp_path):
+ """_respawn_if_dead replays this snapshot arbitrarily later, so it holds no path this
+ request happened to verify: recovery resolves and verifies the file again."""
+ gguf = tmp_path / "m-Q4_K_M.gguf"
+ gguf.write_bytes(_gguf_bytes(arch = "llama"))
+ intent = GgufLoadIntent(
+ model_identifier = "owner/model",
+ gguf_path = str(gguf),
+ hf_variant = "Q4_K_M",
+ verified_gguf = _verified(gguf),
+ )
+
+ backend = _launchable_backend(monkeypatch)
+ assert backend.load_model(intent) is True
+ # Only the hint is dropped; everything else the replay needs survives.
+ assert backend.last_load_intent == replace(intent, verified_gguf = None)
diff --git a/studio/backend/tests/test_parallel_slots_per_load.py b/studio/backend/tests/test_parallel_slots_per_load.py
index e6c4d1e2b96..11fbd4ea11b 100644
--- a/studio/backend/tests/test_parallel_slots_per_load.py
+++ b/studio/backend/tests/test_parallel_slots_per_load.py
@@ -228,7 +228,7 @@ def test_load_model_commits_requested_from_intent():
src = inspect.getsource(LlamaCppBackend.load_model)
commit = src.find("self._requested_n_parallel = max(1, int(intent.n_parallel))")
healthy = src.find("self._healthy = True\n", 0, commit if commit != -1 else None)
- snapshot = src.find("self._last_load_intent = intent")
+ snapshot = src.find("self._last_load_intent = replace(intent")
assert commit != -1, "load_model must commit the requested slot count"
assert healthy != -1 and healthy < commit < snapshot
diff --git a/studio/backend/tests/test_tp_vision_regression.py b/studio/backend/tests/test_tp_vision_regression.py
index 03270c08370..e0657e803f4 100644
--- a/studio/backend/tests/test_tp_vision_regression.py
+++ b/studio/backend/tests/test_tp_vision_regression.py
@@ -554,7 +554,7 @@ def test_layer_preserve_hint_replayed_on_respawn():
respawn keeps the downgraded model multi-GPU (Codex review on #6659)."""
src = inspect.getsource(LlamaCppBackend.load_model)
assert "preserve_multi_gpu_on_layer = intent.preserve_multi_gpu_on_layer" in src
- assert "self._last_load_intent = intent" in src
+ assert "self._last_load_intent = replace(intent" in src
def test_should_record_tensor_split_abort_decision():
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index 596bdd30dde..ad5fd1ea485 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -3597,6 +3597,9 @@ class ModelConfig:
audio_type: Optional[str] = None # Audio codec type: 'snac', 'csm', 'bicodec', 'dac'
has_audio_input: bool = False # Accepts audio input (ASR/speech understanding)
gguf_file: Optional[str] = None # Full path to the .gguf file (local mode)
+ # ``(repo, variant, path, sizes)`` for a GGUF verified during config resolution;
+ # ``sizes`` covers that file and every shard beside it.
+ gguf_verified: Optional[tuple[str, str, str, tuple[tuple[str, int], ...]]] = None
gguf_mmproj_file: Optional[str] = None # Full path to the mmproj .gguf file (vision projection)
gguf_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)
@@ -3833,33 +3836,32 @@ class ModelConfig:
# list_gguf_variants() detects vision & resolves the variant
variants, has_vision = list_gguf_variants(identifier, hf_token = hf_token)
variant = gguf_variant
+ verified_file: Optional[str] = None
if variant:
from core.inference.llama_cpp import (
_gguf_files_for_variant,
cached_gguf_for_load,
)
- # Reject before the load path unloads the resident model.
- # Only a live, complete repo listing can prove the variant
- # absent; without one, let the load path resolve it. The
- # cache escape mirrors the load path's own reuse predicate.
- try:
- from huggingface_hub import list_repo_files
- repo_files = list_repo_files(identifier, token = hf_token)
- except Exception:
- repo_files = None
- if (
- repo_files
- and not _gguf_files_for_variant(repo_files, variant)
- and not cached_gguf_for_load(
- identifier, variant, verify_sizes = True, hf_token = hf_token
- )
- ):
- available = ", ".join(v.quant for v in variants)
- raise ValueError(
- f"GGUF variant '{variant}' not found in {identifier}. "
- f"Available variants: {available}"
- )
+ # A verified cached file also proves that the requested variant exists.
+ verified_file = cached_gguf_for_load(
+ identifier, variant, verify_sizes = True, hf_token = hf_token
+ )
+ if verified_file is None:
+ # Reject before the load path unloads the resident model.
+ # Only a live, complete repo listing can prove the variant
+ # absent; without one, let the load path resolve it.
+ try:
+ from huggingface_hub import list_repo_files
+ repo_files = list_repo_files(identifier, token = hf_token)
+ except Exception:
+ repo_files = None
+ if repo_files and not _gguf_files_for_variant(repo_files, variant):
+ available = ", ".join(v.quant for v in variants)
+ raise ValueError(
+ f"GGUF variant '{variant}' not found in {identifier}. "
+ f"Available variants: {available}"
+ )
if not variant: # auto-select best quant
# ROOT rows when there are any. _pick_best_gguf keeps whichever filename it
# met first among equals, so an LTX-style listing that puts distilled/...-Q6_K
@@ -3881,6 +3883,27 @@ class ModelConfig:
else:
variant = "Q4_K_M" # Fallback — llama-server's own default
+ from core.inference.llama_cpp import cached_gguf_for_load
+
+ verified_file = cached_gguf_for_load(
+ identifier, variant, verify_sizes = True, hf_token = hf_token
+ )
+
+ verified_gguf = None
+ if verified_file:
+ from core.inference.llama_cpp import (
+ _cached_variant_sizes,
+ _resolve_repo_id_casing,
+ )
+
+ # Every shard's byte count, so the load can spot damage from here
+ # on without asking the Hub again.
+ sizes = _cached_variant_sizes(
+ _resolve_repo_id_casing(identifier), variant, verified_file
+ )
+ if sizes:
+ verified_gguf = (identifier, variant, verified_file, sizes)
+
display_name = f"{identifier.split('/')[-1]} ({variant})"
logger.info(
f"Detected remote GGUF repo '{identifier}', "
@@ -3896,6 +3919,7 @@ class ModelConfig:
is_lora = False,
is_gguf = True,
gguf_file = None,
+ gguf_verified = verified_gguf,
gguf_hf_repo = identifier,
gguf_variant = variant,
)