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
Validate an explicit GGUF variant before unloading the resident model (#7862)
Nilaye5c55e35773c
diff --git a/studio/backend/tests/test_gguf_variant_preflight.py b/studio/backend/tests/test_gguf_variant_preflight.pynew file mode 100644index 00000000000..84ab7649fba--- /dev/null+++ b/studio/backend/tests/test_gguf_variant_preflight.py@@ -0,0 +1,119 @@+"""An explicit --gguf-variant that exists nowhere must be rejected by+ModelConfig.from_identifier, before the load path unloads the resident model."""++import huggingface_hub+import pytest++import core.inference.llama_cpp as llama_cpp+import utils.models.model_config as mc+from utils.models.model_config import GgufVariantInfo, ModelConfig++REPO = "unsloth/Llama-3.2-1B-Instruct-GGUF"++REPO_FILES = [+ "Llama-3.2-1B-Instruct-Q4_K_M.gguf",+ "Llama-3.2-1B-Instruct-Q8_0.gguf",+]++VARIANTS = [+ GgufVariantInfo(filename = "Llama-3.2-1B-Instruct-Q4_K_M.gguf", quant = "Q4_K_M", size_bytes = 100),+ GgufVariantInfo(filename = "Llama-3.2-1B-Instruct-Q8_0.gguf", quant = "Q8_0", size_bytes = 200),+]+++def remote_gguf_repo(monkeypatch):+ monkeypatch.setattr(+ mc, "detect_gguf_model_remote", lambda identifier, hf_token = None: VARIANTS[0].filename+ )+ monkeypatch.setattr(+ mc, "list_gguf_variants", lambda identifier, hf_token = None: (list(VARIANTS), False)+ )+ monkeypatch.setattr(+ huggingface_hub, "list_repo_files", lambda repo_id, token = None: list(REPO_FILES)+ )+ monkeypatch.setattr(+ llama_cpp.LlamaCppBackend,+ "_find_llama_server_binary",+ staticmethod(lambda *, include_denied = False: "/fake/llama-server"),+ )+ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", lambda repo, variant, **kwargs: None)+++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")+ msg = str(exc_info.value)+ assert "NOPE_Q9" in msg+ assert "Q4_K_M" in msg and "Q8_0" in msg+++def test_known_variant_accepted(remote_gguf_repo):+ config = ModelConfig.from_identifier(REPO, gguf_variant = "Q8_0")+ assert config is not None+ assert config.is_gguf+ assert config.gguf_variant == "Q8_0"+++def test_variant_match_is_case_insensitive(remote_gguf_repo):+ config = ModelConfig.from_identifier(REPO, gguf_variant = "q4_k_m")+ assert config is not None+ assert config.gguf_variant == "q4_k_m"+++def test_variant_only_in_verified_local_cache_accepted(remote_gguf_repo, monkeypatch):+ monkeypatch.setattr(+ llama_cpp,+ "cached_gguf_for_load",+ lambda repo, variant, **kwargs: "/cache/Llama-3.2-1B-Instruct-OLD_Q2.gguf",+ )+ config = ModelConfig.from_identifier(REPO, gguf_variant = "OLD_Q2")+ assert config is not None+ assert config.gguf_variant == "OLD_Q2"+++def test_cache_escape_uses_size_verified_predicate(remote_gguf_repo, monkeypatch):+ calls = {}++ def fake_cached_gguf_for_load(repo, variant, **kwargs):+ calls["repo"] = repo+ calls["kwargs"] = kwargs+ return None++ monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", fake_cached_gguf_for_load)+ with pytest.raises(ValueError):+ ModelConfig.from_identifier(REPO, gguf_variant = "OLD_Q2")+ assert calls["repo"] == REPO+ assert calls["kwargs"].get("verify_sizes") is True+++def test_variant_matching_uncollapsed_repo_file_accepted(remote_gguf_repo, monkeypatch):+ # Same quant label across shards collapses to one GgufVariantInfo; the+ # preflight must still match against every repo file, like the load path.+ monkeypatch.setattr(+ huggingface_hub,+ "list_repo_files",+ lambda repo_id, token = None: [+ "Llama-3.2-1B-Instruct-Q4_K_M-00001-of-00002.gguf",+ "Llama-3.2-1B-Instruct-Q4_K_M-00002-of-00002.gguf",+ ],+ )+ config = ModelConfig.from_identifier(REPO, gguf_variant = "00002-of-00002")+ assert config is not None+ assert config.gguf_variant == "00002-of-00002"+++def test_listing_unavailable_skips_check(remote_gguf_repo, monkeypatch):+ def boom(repo_id, token = None):+ raise ConnectionError("hub unreachable")++ monkeypatch.setattr(huggingface_hub, "list_repo_files", boom)+ config = ModelConfig.from_identifier(REPO, gguf_variant = "NOPE_Q9")+ assert config is not None+ assert config.gguf_variant == "NOPE_Q9"+++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"}diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex 6ac8d9a726c..d3e8ebae3e7 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -3363,6 +3363,33 @@ class ModelConfig:# list_gguf_variants() detects vision & resolves the variantvariants, has_vision = list_gguf_variants(identifier, hf_token = hf_token)variant = gguf_variant+ 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}"+ )if not variant: # auto-select best quantvariant_filenames = [v.filename for v in variants]best = _pick_best_gguf(variant_filenames)diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex bd8fa59ac2f..d9288bc5937 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -1432,6 +1432,14 @@ def _loaded_models(base: str, key: str) -> list:return _http_json("GET", f"{base}/v1/models", key, error = "Couldn't list models").get("data", [])+def _model_still_loaded(base: str, key: str, model_id: object) -> bool:+ try:+ models = _http_json("GET", f"{base}/v1/models", key, timeout = 5).get("data", [])+ except Exception:+ return False+ return any(m.get("id") == model_id and m.get("loaded") is not False for m in models)++_HF_REPO_ID_SEGMENT_RE = re.compile(r"^[A-Za-z0-9._-]+$")@@ -1560,6 +1568,7 @@ def _resolve_model(load_requested = Trueactive = next((m for m in models if m.get("loaded") is not False), None)active_id = active.get("id") if active else None+ announced_switch = Falseif active_id and not _model_id_matches(active_id,requested,@@ -1567,6 +1576,7 @@ def _resolve_model():typer.echo(f"Switching the Unsloth server from {active_id} to {requested}.")typer.echo("This unloads the current model for every attached session.")+ announced_switch = Trueelif active_id and load.gguf_variant:# Same repo id but an explicit quant still replaces the resident# weights; /v1/models has no variant, so ask the status endpoint.@@ -1581,6 +1591,7 @@ def _resolve_model(f"to {requested}:{load.gguf_variant}.")typer.echo("This unloads the current model for every attached session.")+ announced_switch = True# Mirror `unsloth run`'s load knobs; keep the default payload as just# model_path so a bare `--model` load is unchanged.payload = {"model_path": requested}@@ -1596,7 +1607,15 @@ def _resolve_model(payload["gpu_memory_mode"] = load.gpu_memory_modeif load.gpu_memory_mode == "manual":payload["gpu_layers"] = -1- loaded = _load_model_with_progress(base, key, requested, load, payload)+ try:+ loaded = _load_model_with_progress(base, key, requested, load, payload)+ except Exception:+ # The warning above promised an unload; if the server refused the+ # load before evicting anything, say so. Not BaseException: Ctrl+C+ # must stay immediate, without a probe or a survivor claim.+ if announced_switch and _model_still_loaded(base, key, active_id):+ typer.echo(f"Nothing was unloaded; {active_id} is still serving.", err = True)+ raiseif loaded.get("status") == "already_loaded":typer.echo(f"Reusing loaded model: {_display_model_spec(requested, load.gguf_variant)}")# Unsloth registers the model under a canonical id (resolved identifier,diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.pyindex 4f9bbc8e309..9f50b85241d 100644--- a/unsloth_cli/tests/test_start.py+++ b/unsloth_cli/tests/test_start.py@@ -3678,6 +3678,104 @@ def test_resolve_model_same_quant_prints_no_switch_warning(monkeypatch, capsys):assert "Reusing loaded model: owner/model-GGUF:Q8_0" in out+def test_resolve_model_refused_load_reports_survivor(monkeypatch, capsys):+ models = [{"id": "owner/model-GGUF", "loaded": True}]++ def http_json(+ method,+ url,+ key,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if url.endswith("/api/inference/status"):+ return {"is_gguf": True, "gguf_variant": "Q4_K_M"}+ assert url.endswith("/v1/models"), url+ return {"data": models}++ def refuse_load(base, key, model, load, payload):+ typer.echo("Model load failed: GGUF variant 'NOPE_Q9' not found", err = True)+ raise typer.Exit(code = 1)++ monkeypatch.setattr(start, "_loaded_models", lambda base, key: models)+ monkeypatch.setattr(start, "_http_json", http_json)+ monkeypatch.setattr(start, "_load_model_with_progress", refuse_load)++ with pytest.raises(typer.Exit):+ start._resolve_model(+ BASE, "key", "owner/model-GGUF", start.LoadOptions(gguf_variant = "NOPE_Q9")+ )++ captured = capsys.readouterr()+ assert "This unloads the current model" in captured.out+ assert "Nothing was unloaded; owner/model-GGUF is still serving." in captured.err+++def test_resolve_model_interrupt_skips_survivor_probe(monkeypatch, capsys):+ models = [{"id": "owner/model-GGUF", "loaded": True}]+ probes = []++ def http_json(+ method,+ url,+ key,+ payload = None,+ timeout = 30,+ error = None,+ ):+ return {"is_gguf": True, "gguf_variant": "Q4_K_M"}++ def interrupted_load(base, key, model, load, payload):+ raise KeyboardInterrupt++ monkeypatch.setattr(start, "_loaded_models", lambda base, key: models)+ monkeypatch.setattr(start, "_http_json", http_json)+ monkeypatch.setattr(start, "_load_model_with_progress", interrupted_load)+ monkeypatch.setattr(+ start, "_model_still_loaded", lambda base, key, model_id: probes.append(model_id) or True+ )++ with pytest.raises(KeyboardInterrupt):+ start._resolve_model(+ BASE, "key", "owner/model-GGUF", start.LoadOptions(gguf_variant = "Q8_0")+ )++ assert probes == []+ assert "Nothing was unloaded" not in capsys.readouterr().err+++def test_resolve_model_failed_load_stays_quiet_when_model_gone(monkeypatch, capsys):+ models = [{"id": "owner/model-GGUF", "loaded": True}]++ def http_json(+ method,+ url,+ key,+ payload = None,+ timeout = 30,+ error = None,+ ):+ if url.endswith("/api/inference/status"):+ return {"is_gguf": True, "gguf_variant": "Q4_K_M"}+ assert url.endswith("/v1/models"), url+ return {"data": []}++ def failing_load(base, key, model, load, payload):+ raise typer.Exit(code = 1)++ monkeypatch.setattr(start, "_loaded_models", lambda base, key: models)+ monkeypatch.setattr(start, "_http_json", http_json)+ monkeypatch.setattr(start, "_load_model_with_progress", failing_load)++ with pytest.raises(typer.Exit):+ start._resolve_model(+ BASE, "key", "owner/model-GGUF", start.LoadOptions(gguf_variant = "Q8_0")+ )++ assert "Nothing was unloaded" not in capsys.readouterr().err++def test_auto_serves_when_no_server_then_keeps_server(fake_studio, monkeypatch):monkeypatch.setattr(start, "find_studio_server", lambda: None)started = {}