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
Stop unsloth chat and unsloth inference switching a loaded GGUF to a different quant (#11855)
Nilay1f186c6824ea
diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.pyindex 5ab50a56883..6399bd35e66 100644--- a/unsloth_cli/_inference.py+++ b/unsloth_cli/_inference.py@@ -870,6 +870,7 @@ class HttpChatBackend:self._base = base_urlself._token = tokenself.reply_hit_token_limit = False+ self.gguf_variant: Optional[str] = Nonedef _request(self,@@ -921,6 +922,10 @@ class HttpChatBackend:payload["speculative_type"] = speculative_typeif spec_draft_n_max is not None:payload["spec_draft_n_max"] = spec_draft_n_max+ resident_variant = self._resident_gguf_variant(model)+ if resident_variant:+ payload["gguf_variant"] = resident_variant+ self.gguf_variant = resident_varianttry:# Read the body, don't close at the headers: a slow load commits its 200 early and pads until# done, so closing here would generate mid-load and discard the only report of a late failure.@@ -932,6 +937,32 @@ class HttpChatBackend:typer.echo(f"Model load failed: {exc}", err = True)raise typer.Exit(code = 1)+ def _resident_gguf_variant(self, model: str) -> Optional[str]:+ if model.lower().endswith(".gguf"):+ return None+ try:+ with self._request("GET", "/api/inference/status", timeout = 30) as response:+ status = json.loads(response.read())+ except Exception:+ return None+ if not isinstance(status, dict) or not status.get("is_gguf"):+ return None+ # A local load's active_model is only its basename.+ loaded = status.get("model_identifier") or status.get("active_model")+ if not loaded:+ return None+ loaded = str(loaded)+ if model == status.get("model_identifier"):+ same = True+ elif os.path.exists(model):+ # Mirrors the server's _same_loaded_identifier.+ same = os.path.normcase(model) == os.path.normcase(loaded)+ else:+ # The server loads an ownerless id as unsloth/<id> (ModelConfig.from_identifier).+ requested = model if "/" in model else f"unsloth/{model}"+ same = requested.casefold() == loaded.casefold()+ return status.get("gguf_variant") if same else None+def stream(self,messages: list,diff --git a/unsloth_cli/commands/chat.py b/unsloth_cli/commands/chat.pyindex 93f497a1307..f5fb38e5ab5 100644--- a/unsloth_cli/commands/chat.py+++ b/unsloth_cli/commands/chat.py@@ -327,6 +327,15 @@ def chat(chat_backend = load_chat_backend(model, model_config = model_config, **load_opts)name = model_config.display_name or model+ # Name the quant the server kept, not the local pick (a local dir's display name is a file stem).+ kept = getattr(chat_backend, "gguf_variant", None) if server_mode else None+ picked = getattr(model_config, "gguf_variant", None)+ if kept and kept != picked:+ if picked:+ base = name.removesuffix(f" ({picked})")+ else:+ base = model.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1]+ name = f"{base} ({kept})"show_thinking = thinkcompare_mode = comparemessages = []diff --git a/unsloth_cli/tests/test_inference_chat.py b/unsloth_cli/tests/test_inference_chat.pyindex 8d6933ebf0d..8dfd908ecd3 100644--- a/unsloth_cli/tests/test_inference_chat.py+++ b/unsloth_cli/tests/test_inference_chat.py@@ -1346,7 +1346,7 @@ def test_http_backend_load_forwards_gguf_runtime_options(monkeypatch):llama_extra_args = ["--top-k", "20"],)- assert requests == [+ assert [r for r in requests if r[0] == "POST"] == [("POST","/api/inference/load",@@ -1386,7 +1386,116 @@ def test_http_backend_load_sends_explicit_false_tensor_parallel(monkeypatch):tensor_parallel = False,)- assert requests[0][2]["tensor_parallel"] is False+ assert requests[-1][2]["tensor_parallel"] is False+++class _FakeStatusResponse:+ def __init__(self, status) -> None:+ self._body = json.dumps(status).encode()++ def __enter__(self):+ return self++ def __exit__(self, *exc) -> None:+ pass++ def read(self) -> bytes:+ return self._body+++_RESIDENT_Q8 = {+ "is_gguf": True,+ "active_model": "unsloth/Qwen3-0.6B-GGUF",+ "model_identifier": "unsloth/Qwen3-0.6B-GGUF",+ "gguf_variant": "Q8_0",+}+++ ("model", "status", "expected"),+ [+ ("unsloth/Qwen3-0.6B-GGUF", _RESIDENT_Q8, "Q8_0"),+ ("unsloth/qwen3-0.6b-gguf", _RESIDENT_Q8, "Q8_0"),+ ("unsloth/Qwen3-1.7B-GGUF", _RESIDENT_Q8, None),+ (+ "/models/Qwen3-0.6B-Q4_K_M.gguf",+ {**_RESIDENT_Q8, "model_identifier": "/models/Qwen3-0.6B-Q4_K_M.gguf"},+ None,+ ),+ (+ "Qwen3-0.6B-GGUF",+ {+ **_RESIDENT_Q8,+ "active_model": "Qwen3-0.6B-GGUF",+ "model_identifier": "/models/Qwen3-0.6B-GGUF",+ },+ None,+ ),+ (+ "Qwen3-0.6B-GGUF",+ {**_RESIDENT_Q8, "active_model": "Qwen3-0.6B-GGUF", "model_identifier": None},+ None,+ ),+ ("Qwen3-0.6B-GGUF", _RESIDENT_Q8, "Q8_0"),+ ("C:\\Models\\Foo", {**_RESIDENT_Q8, "model_identifier": "C:\\Models\\Foo"}, "Q8_0"),+ ("unsloth/Qwen3-0.6B-GGUF", {**_RESIDENT_Q8, "model_identifier": None}, "Q8_0"),+ ("unsloth/Qwen3-0.6B-GGUF", {**_RESIDENT_Q8, "is_gguf": False}, None),+ ("unsloth/Qwen3-0.6B-GGUF", None, None),+ ],+)+def test_http_backend_load_keeps_the_resident_quant(monkeypatch, model, status, expected):+ """A bare repo id lets the server auto-pick a quant, evicting the one already serving it."""+ backend = HttpChatBackend("http://localhost:8888", "token")+ loads = []++ def fake_request(+ method,+ path,+ payload = None,+ timeout = None,+ ):+ if path == "/api/inference/status":+ if status is None:+ raise OSError("status unavailable")+ return _FakeStatusResponse(status)+ loads.append(payload)+ return _FakeLoadResponse()++ monkeypatch.setattr(backend, "_request", fake_request)++ backend.ensure_loaded(model, hf_token = None, max_seq_length = 4096, load_in_4bit = None)++ assert len(loads) == 1+ assert loads[0].get("gguf_variant") == expected+++def test_http_backend_load_keeps_the_resident_quant_across_windows_path_spellings(monkeypatch):+ import ntpath++ import unsloth_cli._inference as inference++ backend = HttpChatBackend("http://localhost:8888", "token")+ resident = {**_RESIDENT_Q8, "active_model": "Foo", "model_identifier": "C:\\Models\\Foo"}+ loads = []++ def fake_request(+ method,+ path,+ payload = None,+ timeout = None,+ ):+ if path == "/api/inference/status":+ return _FakeStatusResponse(resident)+ loads.append(payload)+ return _FakeLoadResponse()++ monkeypatch.setattr(backend, "_request", fake_request)+ monkeypatch.setattr(inference.os.path, "exists", lambda p: True)+ monkeypatch.setattr(inference.os.path, "normcase", ntpath.normcase)++ backend.ensure_loaded("c:/models/foo", hf_token = None, max_seq_length = 4096, load_in_4bit = None)++ assert loads[0].get("gguf_variant") == "Q8_0"# ── A load slower than the proxy timer (see routes/inference.py _tunnel_safe_json) ──@@ -1989,10 +2098,68 @@ def test_server_load_sends_load_in_4bit_only_when_typed(monkeypatch, command, flresult = CliRunner().invoke(app, [*argv, *flags], input = "/exit\n")assert result.exit_code == 0, result.output+ payloads = [p for p in payloads if p is not None]assert len(payloads) == 1assert payloads[0].get("load_in_4bit", "omitted") == expected+ ("model", "display_name", "picked", "resident", "banner"),+ [+ (+ "unsloth/Qwen3-0.6B-GGUF",+ "Qwen3-0.6B-GGUF (UD-Q4_K_XL)",+ "UD-Q4_K_XL",+ _RESIDENT_Q8,+ "Qwen3-0.6B-GGUF (Q8_0)",+ ),+ (+ "/models/Qwen3-0.6B-GGUF",+ "Qwen3-0.6B-Q4_K_M",+ None,+ {**_RESIDENT_Q8, "model_identifier": "/models/Qwen3-0.6B-GGUF"},+ "Qwen3-0.6B-GGUF (Q8_0)",+ ),+ ],+)+def test_server_chat_banner_names_the_kept_quant(+ monkeypatch, model, display_name, picked, resident, banner+):+ from unsloth_cli import _inference++ class _GgufConfig(_FakeConfig):+ is_gguf = True+ is_lora = False++ _GgufConfig.display_name = display_name+ _GgufConfig.gguf_variant = picked++ def fake_request(+ self,+ method,+ path,+ payload = None,+ timeout = None,+ ):+ if path == "/api/inference/status":+ return _FakeStatusResponse(resident)+ return _FakeLoadResponse()++ monkeypatch.delenv("UNSLOTH_STUDIO_URL", raising = False)+ monkeypatch.setattr(_inference, "find_studio_server", lambda: "http://127.0.0.1:8888")+ monkeypatch.setattr(_inference, "verify_studio_identity", lambda base: True)+ monkeypatch.setattr(_inference, "_studio_token", lambda: "token")+ monkeypatch.setattr(HttpChatBackend, "_request", fake_request)+ monkeypatch.setattr(chatmod, "load_chat_backend", lambda *a, **k: pytest.fail("loaded locally"))+ monkeypatch.setattr(chatmod, "resolve_model_config", lambda *a, **k: _GgufConfig())+ monkeypatch.setattr(chatmod, "_compare_needs_second_model", lambda: False)++ result = CliRunner().invoke(_chat_app(), [model], input = "/exit\n")++ assert result.exit_code == 0, result.output+ assert f"Chatting with {banner}" in result.output++@pytest.mark.parametrize("command", ["chat", "inference"])def test_local_load_still_gets_a_load_in_4bit_bool(monkeypatch, command):module, app, argv = _command_and_argv(command)