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.

Stop unsloth chat and unsloth inference reloading a 16-bit model in 4-bit (#11477)

Nilay3c3475ef5361
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index f65b5d24dd0..2b7dec0330a 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -15204,6 +15204,19 @@ def _mlx_runtime_settings_match(backend, request) -> bool:
) == (request.chat_template_override or None)
+def _inherit_resident_load_in_4bit(backend, request, model_identifier: str) -> None:
+ """An omitted load_in_4bit keeps the resident precision, not the 4-bit default."""
+ if "load_in_4bit" in (getattr(request, "model_fields_set", set()) or set()):
+ return
+ if not _same_loaded_identifier(backend.active_model_name, model_identifier):
+ return
+ resident = (backend.models.get(backend.active_model_name, {}) or {}).get(
+ "load_in_4bit_requested"
+ )
+ if resident is not None:
+ request.load_in_4bit = bool(resident)
+
+
def _non_gguf_runtime_settings_match(backend, request) -> bool:
"""Whether the resident non-GGUF model already runs the request's load settings.
@@ -15938,6 +15951,7 @@ async def _load_model_impl(
await asyncio.to_thread(acquire_for_request, CHAT)
return reused
if not (request.gguf_variant or is_direct_gguf_request):
+ _inherit_resident_load_in_4bit(backend, request, model_identifier)
if (
_same_loaded_identifier(backend.active_model_name, model_identifier)
and _mlx_runtime_settings_match(backend, request)
diff --git a/studio/backend/tests/test_non_gguf_reload_settings.py b/studio/backend/tests/test_non_gguf_reload_settings.py
index 6fc1de14871..ee6eb41433c 100644
--- a/studio/backend/tests/test_non_gguf_reload_settings.py
+++ b/studio/backend/tests/test_non_gguf_reload_settings.py
@@ -218,3 +218,43 @@ class TestNonGgufStatusReportsWhatTheLoadAskedFor:
response = self._status_for(monkeypatch, {"max_seq_length_requested": requested})
assert response.requested_context_length == published
+
+
+class TestOmittedPrecisionKeepsTheResidentOne:
+ """A CLI load that leaves load_in_4bit out must not requantize a 16-bit model when
+ another setting, such as the context, forces the reload."""
+
+ def test_same_model_inherits_the_resident_precision(self):
+ request = _Request(max_seq_length = 0)
+ inference_route._inherit_resident_load_in_4bit(
+ _loaded(load_in_4bit = False), request, RESIDENT
+ )
+ assert request.load_in_4bit is False
+
+ def test_explicit_precision_wins(self):
+ request = _Request(load_in_4bit = True)
+ inference_route._inherit_resident_load_in_4bit(
+ _loaded(load_in_4bit = False), request, RESIDENT
+ )
+ assert request.load_in_4bit is True
+
+ def test_other_model_keeps_the_default(self):
+ request = _Request()
+ inference_route._inherit_resident_load_in_4bit(
+ _loaded(load_in_4bit = False), request, "unsloth/Llama-3.2-1B-Instruct"
+ )
+ assert request.load_in_4bit is True
+
+ def test_unrecorded_resident_keeps_the_default(self):
+ request = _Request()
+ inference_route._inherit_resident_load_in_4bit(_Backend({}), request, RESIDENT)
+ assert request.load_in_4bit is True
+
+ def test_pydantic_request_reuses_after_inheriting(self):
+ from models.inference import LoadRequest
+
+ backend = _loaded(load_in_4bit = False)
+ request = LoadRequest(model_path = RESIDENT)
+ inference_route._inherit_resident_load_in_4bit(backend, request, RESIDENT)
+ assert request.load_in_4bit is False
+ assert inference_route._non_gguf_runtime_settings_match(backend, request)
diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.py
index 999f0f9f1b5..6e76b6c1291 100644
--- a/unsloth_cli/_inference.py
+++ b/unsloth_cli/_inference.py
@@ -899,9 +899,10 @@ class HttpChatBackend:
"model_path": model,
"hf_token": hf_token,
"max_seq_length": max_seq_length,
- "load_in_4bit": load_in_4bit,
"tensor_parallel": tensor_parallel,
}
+ if load_in_4bit is not None:
+ payload["load_in_4bit"] = load_in_4bit
if llama_extra_args:
payload["llama_extra_args"] = llama_extra_args
if speculative_type is not None:
@@ -1002,6 +1003,14 @@ class HttpChatBackend:
pass
+def server_load_opts(ctx, load_opts: dict) -> dict:
+ """Drop an untyped --load-in-4bit so the server can keep a resident model's precision."""
+ opts = dict(load_opts)
+ if ctx.get_parameter_source("load_in_4bit").name != "COMMANDLINE":
+ opts["load_in_4bit"] = None
+ return opts
+
+
def connect_studio_server(
model: str,
*,
diff --git a/unsloth_cli/commands/chat.py b/unsloth_cli/commands/chat.py
index 6f32b0c6cab..be6a86178ca 100644
--- a/unsloth_cli/commands/chat.py
+++ b/unsloth_cli/commands/chat.py
@@ -20,6 +20,7 @@ from unsloth_cli._inference import (
raise_on_streamed_error,
render_columns,
resolve_model_config,
+ server_load_opts,
stream_markdown,
visible_text,
)
@@ -158,6 +159,7 @@ def _pick_model(console) -> str:
def chat(
+ ctx: typer.Context,
model: Optional[str] = typer.Argument(
None, help = "HF model id or local path. Omit to pick one of your local models."
),
@@ -192,7 +194,12 @@ def chat(
"and MLX, and 2048 on the transformers backend. A value that differs from a "
"running Unsloth server's reloads the model.",
),
- load_in_4bit: bool = typer.Option(True, "--load-in-4bit/--no-load-in-4bit"),
+ load_in_4bit: bool = typer.Option(
+ True,
+ "--load-in-4bit/--no-load-in-4bit",
+ help = "Load the model in 4-bit. Left unset, a running Unsloth server that already "
+ "has this model loaded keeps its precision.",
+ ),
tensor_parallel: bool = typer.Option(
False,
"--tensor-parallel/--no-tensor-parallel",
@@ -301,7 +308,9 @@ def chat(
# Prefer a running Unsloth server: instant starts, model shared with the UI.
chat_backend = (
- None if (no_server or is_mlx_distributed) else connect_studio_server(model, **load_opts)
+ None
+ if (no_server or is_mlx_distributed)
+ else connect_studio_server(model, **server_load_opts(ctx, load_opts))
)
server_mode = chat_backend is not None
if server_mode and should_print:
diff --git a/unsloth_cli/commands/inference.py b/unsloth_cli/commands/inference.py
index 53372ad1a07..93af7697a0e 100644
--- a/unsloth_cli/commands/inference.py
+++ b/unsloth_cli/commands/inference.py
@@ -14,11 +14,13 @@ from unsloth_cli._inference import (
mlx_distributed_info,
mlx_distributed_uses_mpi,
raise_on_streamed_error,
+ server_load_opts,
stream_to_stdout,
)
def inference(
+ ctx: typer.Context,
model: str = typer.Argument(..., help = "HF model id or local path."),
prompt: str = typer.Argument(..., help = "Prompt to send to the model."),
hf_token: Optional[str] = typer.Option(
@@ -54,7 +56,12 @@ def inference(
"and MLX, and 2048 on the transformers backend. A value that differs from a "
"running Unsloth server's reloads the model.",
),
- load_in_4bit: bool = typer.Option(True, "--load-in-4bit/--no-load-in-4bit"),
+ load_in_4bit: bool = typer.Option(
+ True,
+ "--load-in-4bit/--no-load-in-4bit",
+ help = "Load the model in 4-bit. Left unset, a running Unsloth server that already "
+ "has this model loaded keeps its precision.",
+ ),
tensor_parallel: bool = typer.Option(
False,
"--tensor-parallel/--no-tensor-parallel",
@@ -130,7 +137,9 @@ def inference(
if spec_draft_n_max is not None:
load_opts["spec_draft_n_max"] = spec_draft_n_max
chat_backend = (
- None if (no_server or is_mlx_distributed) else connect_studio_server(model, **load_opts)
+ None
+ if (no_server or is_mlx_distributed)
+ else connect_studio_server(model, **server_load_opts(ctx, load_opts))
)
if chat_backend is None:
chat_backend = load_chat_backend(model, **load_opts)
diff --git a/unsloth_cli/tests/test_inference_chat.py b/unsloth_cli/tests/test_inference_chat.py
index f045f2ce43f..32d7e1a8026 100644
--- a/unsloth_cli/tests/test_inference_chat.py
+++ b/unsloth_cli/tests/test_inference_chat.py
@@ -1858,7 +1858,7 @@ def test_chat_forwards_gguf_runtime_options_to_loader(monkeypatch):
{
"hf_token": None,
"max_seq_length": 0,
- "load_in_4bit": True,
+ "load_in_4bit": None,
"tensor_parallel": True,
"speculative_type": "dspark",
"spec_draft_n_max": 3,
@@ -1911,7 +1911,7 @@ def test_inference_forwards_gguf_runtime_options_to_loader(monkeypatch):
{
"hf_token": None,
"max_seq_length": 0,
- "load_in_4bit": True,
+ "load_in_4bit": None,
"tensor_parallel": True,
"speculative_type": "dspark",
"spec_draft_n_max": 3,
@@ -1923,6 +1923,83 @@ def test_inference_forwards_gguf_runtime_options_to_loader(monkeypatch):
assert closed == [True]
+def _command_and_argv(command):
+ from unsloth_cli.commands import inference as infermod
+ return {
+ "chat": (chatmod, _chat_app(), ["fake-model"]),
+ "inference": (infermod, _inference_app(), ["fake-model", "hello"]),
+ }[command]
+
+
[email protected]("command", ["chat", "inference"])
+ ("flags", "expected"),
+ [([], "omitted"), (["--load-in-4bit"], True), (["--no-load-in-4bit"], False)],
+)
+def test_server_load_sends_load_in_4bit_only_when_typed(monkeypatch, command, flags, expected):
+ """An untyped default must not make the server reload a 16-bit model in 4-bit."""
+ from unsloth_cli import _inference
+
+ module, app, argv = _command_and_argv(command)
+ payloads = []
+
+ def fake_request(
+ self,
+ method,
+ path,
+ payload = None,
+ timeout = None,
+ ):
+ payloads.append(payload)
+ 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(HttpChatBackend, "stream", lambda self, *a, **k: iter(["answer"]))
+ monkeypatch.setattr(module, "load_chat_backend", lambda *a, **k: pytest.fail("loaded locally"))
+ if command == "chat":
+ monkeypatch.setattr(chatmod, "resolve_model_config", lambda *a, **k: _FakeConfig())
+ monkeypatch.setattr(chatmod, "_compare_needs_second_model", lambda: False)
+
+ result = CliRunner().invoke(app, [*argv, *flags], input = "/exit\n")
+
+ assert result.exit_code == 0, result.output
+ assert len(payloads) == 1
+ assert payloads[0].get("load_in_4bit", "omitted") == expected
+
+
[email protected]("command", ["chat", "inference"])
+def test_local_load_still_gets_a_load_in_4bit_bool(monkeypatch, command):
+ module, app, argv = _command_and_argv(command)
+ loads = []
+
+ class _FakeBackend:
+ def stream(self, *a, **k):
+ return iter(["answer"])
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(module, "connect_studio_server", lambda *a, **k: None)
+ monkeypatch.setattr(
+ module,
+ "load_chat_backend",
+ lambda model, **kwargs: (loads.append(kwargs["load_in_4bit"]), _FakeBackend())[1],
+ )
+ if command == "chat":
+ monkeypatch.setattr(chatmod, "resolve_model_config", lambda *a, **k: _FakeConfig())
+ monkeypatch.setattr(chatmod, "_compare_needs_second_model", lambda: False)
+
+ for flags in ([], ["--no-load-in-4bit"]):
+ result = CliRunner().invoke(app, [*argv, *flags], input = "/exit\n")
+ assert result.exit_code == 0, result.output
+
+ assert loads == [True, False]
+
+
@pytest.mark.parametrize("command", ["chat", "inference"])
def test_local_load_forwards_the_unrequested_context_sentinel(monkeypatch, command):
"""No server: the sentinel reaches the loader, so each backend picks its own window.