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
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""adopt_load_intent_if_matched short-circuits a duplicate /load so the just-spawned server survives."""
from __future__ import annotations
import inspect
import sys
import types as _types
from pathlib import Path
import pytest
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
_structlog_stub = _types.ModuleType("structlog")
_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")
sys.modules.setdefault("structlog", _structlog_stub)
_httpx_stub = _types.ModuleType("httpx")
for _exc in (
"ConnectError",
"TimeoutException",
"ReadTimeout",
"ReadError",
"RemoteProtocolError",
"CloseError",
):
setattr(_httpx_stub, _exc, type(_exc, (Exception,), {}))
_httpx_stub.Timeout = type("T", (), {"__init__": lambda s, *a, **k: None})
_httpx_stub.Client = type(
"C",
(),
{
"__init__": lambda s, **kw: None,
"__enter__": lambda s: s,
"__exit__": lambda s, *a: None,
},
)
# Stub only when httpx is not installed: setdefault ignores an un-imported real httpx, and this
# stub lacks Response, breaking starlette.testclient for every later module.
try:
import httpx # noqa: F401
except ImportError:
sys.modules.setdefault("httpx", _httpx_stub)
from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend
from models.inference import (
InferenceStatusResponse,
LoadRequest,
LoadResponse,
ValidateModelRequest,
)
class _FakeProcess:
"""Stand-in for subprocess.Popen so atexit cleanup doesn't crash."""
def terminate(self):
pass
def wait(self, timeout = None):
return 0
def kill(self):
pass
def poll(self):
return 0
def _loaded_backend(**overrides):
backend = LlamaCppBackend()
backend._process = _FakeProcess() # is_loaded only checks is not None
backend._healthy = True
backend._model_identifier = "owner/repo"
backend._hf_variant = "Q4_K_M"
backend._requested_n_ctx = 8192
backend._cache_type_kv = None
backend._reasoning_budget = -1
backend._reasoning_budget_message = ""
backend._speculative_type = None
backend._requested_spec_mode = "auto"
backend._chat_template_override = None
backend._is_vision = False
backend._extra_args = None
backend._extra_args_source = None
backend._gguf_path = None
for key, value in overrides.items():
setattr(backend, key, value)
return backend
def _matches(backend: LlamaCppBackend, **kwargs) -> bool:
return backend.adopt_load_intent_if_matched(GgufLoadIntent(**kwargs))
def test_already_in_target_state_uses_gguf_path_when_present(tmp_path):
gguf_file = tmp_path / "model.Q4_K_M.gguf"
gguf_file.write_bytes(b"")
backend = _loaded_backend(
_hf_variant = "Q4_K_M",
_gguf_path = str(gguf_file),
)
assert (
_matches(
backend,
gguf_path = str(gguf_file),
model_identifier = "owner/repo",
hf_variant = None,
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = None,
is_vision = False,
)
is True
)
def test_already_loaded_model_reloads_when_selected_binary_changes():
backend = _loaded_backend()
backend._binary_changed_since_launch = lambda: True
assert (
_matches(
backend,
gguf_path = None,
model_identifier = "owner/repo",
hf_variant = "Q4_K_M",
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = None,
is_vision = False,
)
is False
)
def test_already_in_target_state_rejects_different_gguf_path(tmp_path):
a = tmp_path / "a.gguf"
a.write_bytes(b"")
b = tmp_path / "b.gguf"
b.write_bytes(b"")
backend = _loaded_backend(_gguf_path = str(a))
assert (
_matches(
backend,
gguf_path = str(b),
model_identifier = "owner/repo",
hf_variant = None,
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = None,
is_vision = False,
)
is False
)
def test_already_in_target_state_falls_back_to_hf_variant_for_hf_loads():
backend = _loaded_backend(_hf_variant = "Q4_K_M", _gguf_path = None)
assert (
_matches(
backend,
gguf_path = None,
model_identifier = "owner/repo",
hf_variant = "Q8_0",
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = None,
is_vision = False,
)
is False
)
def test_already_in_target_state_hf_same_variant_matches():
backend = _loaded_backend(_hf_variant = "Q4_K_M", _gguf_path = None)
assert (
_matches(
backend,
gguf_path = None,
model_identifier = "owner/repo",
hf_variant = "Q4_K_M",
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = None,
is_vision = False,
)
is True
)
def test_already_in_target_state_none_extras_inherits_stored():
backend = _loaded_backend(_extra_args = ["--top-k", "20"])
assert (
_matches(
backend,
gguf_path = None,
model_identifier = "owner/repo",
hf_variant = "Q4_K_M",
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = None,
is_vision = False,
)
is True
)
def test_already_in_target_state_empty_extras_forces_reload_when_stored():
backend = _loaded_backend(_extra_args = ["--top-k", "20"])
assert (
_matches(
backend,
gguf_path = None,
model_identifier = "owner/repo",
hf_variant = "Q4_K_M",
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = [],
is_vision = False,
)
is False
)
def test_already_in_target_state_explicit_extras_match():
backend = _loaded_backend(_extra_args = ["--top-k", "20"])
assert (
_matches(
backend,
gguf_path = None,
model_identifier = "owner/repo",
hf_variant = "Q4_K_M",
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = ["--top-k", "20"],
is_vision = False,
)
is True
)
def test_extra_args_source_default_is_none():
backend = LlamaCppBackend()
assert backend.extra_args_source is None
def test_reasoning_budget_schema_contract():
request = LoadRequest(model_path = "owner/repo")
assert request.reasoning_budget == -1
assert request.reasoning_budget_message == ""
assert LoadRequest(model_path = "owner/repo", reasoning_budget = 0).reasoning_budget == 0
with pytest.raises(ValueError):
LoadRequest(model_path = "owner/repo", reasoning_budget = -2)
with pytest.raises(ValueError, match = "8192-byte"):
LoadRequest(model_path = "owner/repo", reasoning_budget_message = "😀" * 2_049)
with pytest.raises(ValueError, match = "NUL"):
LoadRequest(model_path = "owner/repo", reasoning_budget_message = "bad\0message")
padded = LoadRequest(model_path = "owner/repo", reasoning_budget_message = " PAD ")
assert padded.reasoning_budget_message == " PAD "
load = LoadResponse(status = "loaded", model = "m", display_name = "m", inference = {})
status = InferenceStatusResponse()
assert (load.reasoning_budget, load.reasoning_budget_message) == (-1, "")
assert (status.reasoning_budget, status.reasoning_budget_message) == (-1, "")
def test_reasoning_budget_is_part_of_backend_dedupe():
backend = _loaded_backend(
_reasoning_budget = 64,
_reasoning_budget_message = "limit",
_requested_reasoning_budget = 64,
_requested_reasoning_budget_message = "limit",
)
common = dict(
model_identifier = "owner/repo",
hf_variant = "Q4_K_M",
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = None,
is_vision = False,
reasoning_budget = 64,
reasoning_budget_message = "limit",
)
assert _matches(backend, **common) is True
assert _matches(backend, **{**common, "reasoning_budget": 32}) is False
flags = ["--reasoning-budget", "64", "--reasoning-budget-message", "limit"]
backend = _loaded_backend(
_reasoning_budget = 64,
_reasoning_budget_message = "limit",
_requested_reasoning_budget = 64,
_requested_reasoning_budget_message = "limit",
_extra_args = flags,
)
assert (
_matches(
backend,
**{
**common,
"reasoning_budget": -1,
"reasoning_budget_message": "",
"extra_args": flags,
},
)
is True
)
def test_reasoning_budget_state_resets_on_unload():
backend = _loaded_backend(_reasoning_budget = 64, _reasoning_budget_message = "limit")
backend.unload_model()
assert backend.reasoning_budget == -1
assert backend.reasoning_budget_message == ""
def test_load_wires_reasoning_args_and_respawn_snapshot():
source = inspect.getsource(LlamaCppBackend.load_model)
assert "_build_reasoning_budget_flags(" in source
assert "reasoning_budget = intent.reasoning_budget" in source
assert "reasoning_budget_message = intent.reasoning_budget_message" in source
assert source.index("validate_reasoning_budget_capabilities") < source.index(
"self._kill_process()"
)
def test_route_checks_reasoning_budget_capabilities_before_teardown():
route_source = (Path(__file__).resolve().parent.parent / "routes" / "inference.py").read_text(
encoding = "utf-8"
)
preflight = route_source.index("backend.validate_reasoning_budget_capabilities")
diffusion_rejection = route_source.index(
"Reasoning Budget settings are not supported for DiffusionGemma models."
)
unknown_rejection = route_source.index(
"Reasoning Budget settings cannot be applied until this GGUF is"
)
teardown = route_source.index("# Point of no return for the GGUF path")
assert preflight < teardown
assert diffusion_rejection < teardown
assert unknown_rejection < teardown
class TestRepeatLoadMatchesTheEffectiveCache:
"""A repeat /load compares effective cache types, so a cache set via env or extras is not a mismatch."""
@staticmethod
def _backend_running(effective):
"""Stub backend holding only the per-axis cache pair the live child was launched with."""
from core.inference.llama_cpp import LlamaCppBackend
b = LlamaCppBackend.__new__(LlamaCppBackend)
b._effective_cache_types = effective
return b
@pytest.mark.parametrize(
"extras,managed",
[
(["--cache-type-k", "q8_0", "--cache-type-v", "q8_0"], None),
(["--cache-type-k", "q4_0", "--cache-type-v", "f16"], None),
([], "q8_0"),
([], None),
],
)
def test_the_same_request_resolves_to_the_running_pair(self, extras, managed):
from core.inference.llama_cpp import _planned_main_cache_types
planned = _planned_main_cache_types(managed, extras)
running = self._backend_running(planned)
assert running._effective_cache_types == _planned_main_cache_types(managed, extras)
def test_a_changed_cache_still_reloads(self):
from core.inference.llama_cpp import _planned_main_cache_types
running = self._backend_running(("q8_0", "q8_0"))
assert running._effective_cache_types != _planned_main_cache_types(
None, ["--cache-type-k", "f16", "--cache-type-v", "f16"]
)
def test_the_matcher_compares_the_pair_not_the_managed_scalar(self):
"""Source-pinned: the scalar cannot describe an extras-only or env cache,
so reintroducing it here would bring the spurious reload back."""
import inspect
from core.inference.llama_cpp import LlamaCppBackend
src = "".join(inspect.getsource(LlamaCppBackend._runtime_matches_intent).split())
assert "self._requested_cache_types!=_planned_main_cache_types(" in src
assert "_norm(self._cache_type_kv)!=_norm(intent.cache_type_kv)" not in src
def test_a_launch_time_rewrite_does_not_force_a_reload(self):
"""Compare requested cache types; a launch-time f16 rewrite would force reloads."""
from core.inference.llama_cpp import (
LlamaCppBackend,
_effective_main_cache_types,
_planned_main_cache_types,
)
extras = ["--cache-type-k", "q8_0", "--cache-type-v", "q8_0"]
asked = _planned_main_cache_types(None, extras)
cmd = ["llama-server", "-m", "/x.gguf", *extras]
b = LlamaCppBackend.__new__(LlamaCppBackend)
b._architecture = None
launched = _effective_main_cache_types(
LlamaCppBackend._reset_quantized_v_cache(
cmd, "this build has no --flash-attn", mla = False, draft_mla = None
),
{},
)
assert asked == ("q8_0", "q8_0")
assert launched == ("q8_0", "f16"), launched
b._requested_cache_types = asked
assert b._requested_cache_types == _planned_main_cache_types(None, extras)
def test_the_requested_pair_is_recorded_next_to_the_effective_one(self):
"""Both are recorded on the same success path, so one cannot drift."""
import inspect
from core.inference.llama_cpp import LlamaCppBackend
load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
assert "self._effective_cache_types=_effective_main_cache_types(" in load
assert "self._requested_cache_types=_planned_cache_pair" in load
@pytest.mark.parametrize("model", [LoadRequest, ValidateModelRequest])
def test_reasoning_budget_rejects_booleans(model):
# bool subclasses int and pydantic is lax, so `true` would launch a one-token budget.
with pytest.raises(ValueError, match = "Expected a number, got a boolean"):
model(model_path = "unsloth/x", reasoning_budget = True)
assert model(model_path = "unsloth/x", reasoning_budget = 1).reasoning_budget == 1
def test_the_reuse_check_compares_the_request_not_the_environment():
"""An inherited LLAMA_ARG_THINK_BUDGET* cannot be sent or cleared by any request, so comparing
the live EFFECTIVE value against a resolved request tore down a healthy server on every load."""
source = inspect.getsource(LlamaCppBackend._runtime_matches_intent)
assert "self._requested_reasoning_budget" in source
assert (
"resolve_reasoning_budget_with_env" not in source
), "the reuse check must not fold the environment into the request"
launch = inspect.getsource(LlamaCppBackend.load_model)
assert "self._requested_reasoning_budget = reasoning_budget" in launch
# Only a conclusive 'unsupported' probe may drop the flag; the child still applies the env.
assert "reasoning_budget_probe_inconclusive" in launch
def test_requested_reasoning_budget_is_reported_separately():
from models.inference import InferenceStatusResponse
fields = InferenceStatusResponse.model_fields
for name in ("requested_reasoning_budget", "requested_reasoning_budget_message"):
assert name in fields, name
assert fields["requested_reasoning_budget"].default == -1
assert fields["requested_reasoning_budget_message"].default == ""
def test_an_inherited_env_budget_does_not_force_a_reload():
"""The live EFFECTIVE value carries LLAMA_ARG_THINK_BUDGET*, which no request can send or
clear. Comparing against it tore down a healthy server on every load and never converged."""
backend = _loaded_backend(
_reasoning_budget = 512,
_reasoning_budget_message = "from env",
_requested_reasoning_budget = -1,
_requested_reasoning_budget_message = "",
)
assert (
_matches(
backend,
model_identifier = "owner/repo",
hf_variant = "Q4_K_M",
n_ctx = 8192,
cache_type_kv = None,
speculative_type = None,
chat_template_override = None,
extra_args = None,
is_vision = False,
reasoning_budget = -1,
reasoning_budget_message = "",
)
is True
)
def test_canonical_model_identity_resolves_snapshot_to_repo():
from routes.inference import _canonical_model_identity
snapshot = "/models--unsloth--Qwen3.8-27B-GGUF/snapshots/abc123"
assert _canonical_model_identity(snapshot) == "unsloth/qwen3.8-27b-gguf"
def test_canonical_model_identity_folds_repo_id_case():
from routes.inference import _canonical_model_identity
assert _canonical_model_identity("unsloth/Qwen3.8-27B-GGUF") == "unsloth/qwen3.8-27b-gguf"
def test_canonical_model_identity_reads_windows_snapshot_path():
from routes.inference import _canonical_model_identity
snapshot = r"C:\hub\models--unsloth--Qwen3.8-27B-GGUF\snapshots\abc123"
assert _canonical_model_identity(snapshot) == "unsloth/qwen3.8-27b-gguf"
def test_canonical_model_identity_empty_and_none():
from routes.inference import _canonical_model_identity
assert _canonical_model_identity("") == ""
assert _canonical_model_identity(None) == ""
def test_canonical_model_identity_keeps_other_local_paths():
from routes.inference import _canonical_model_identity
assert _canonical_model_identity("/models/my-model.gguf") == "/models/my-model.gguf"
assert _canonical_model_identity("/models--org--name/x.gguf") == "/models--org--name/x.gguf"
def test_inheritance_works_when_stored_is_snapshot_and_load_is_repo():
"""Extras stored under a snapshot path still reach a JIT auto-switch load of the same repo id."""
from routes.inference import _resolve_inherited_extra_args
class FakeRequest:
model_path = "unsloth/Qwen3.8-27B-GGUF"
gguf_variant = None
llama_extra_args = None
model_fields_set = set()
class FakeConfig:
is_gguf = True
gguf_variant = "ud-q6_k_l"
identifier = "unsloth/Qwen3.8-27B-GGUF"
class FakeBackend:
extra_args = ["--rope-scaling", "yarn", "-c", "300000"]
extra_args_source = ("/models--unsloth--Qwen3.8-27B-GGUF/snapshots/abc123", "ud-q6_k_l")
import routes.inference as _routes
_get_llama_cpp_backend_orig = _routes.get_llama_cpp_backend
_routes.get_llama_cpp_backend = lambda: FakeBackend()
try:
result = _resolve_inherited_extra_args(
FakeRequest(), FakeConfig(), "unsloth/Qwen3.8-27B-GGUF", None
)
assert result == [
"--rope-scaling",
"yarn",
"-c",
"300000",
], f"Expected inherited extras but got: {result}"
finally:
_routes.get_llama_cpp_backend = _get_llama_cpp_backend_orig
def test_inheritance_works_when_case_differs():
"""A stored snapshot/repo with different casing than the load model_identifier
still inherits extras for the same Hub GGUF + same variant."""
from routes.inference import _resolve_inherited_extra_args
class FakeRequest:
model_path = "unsloth/Qwen3.8-27B-GGUF"
gguf_variant = None
llama_extra_args = None
model_fields_set = set()
class FakeConfig:
is_gguf = True
gguf_variant = "ud-q6_k_l"
identifier = "unsloth/Qwen3.8-27B-GGUF"
class FakeBackend:
extra_args = ["--rope-scaling", "yarn", "-c", "300000"]
extra_args_source = ("/models--Unsloth--Qwen3.8-27B-GGUF/snapshots/abc123", "ud-q6_k_l")
import routes.inference as _routes
_get_llama_cpp_backend_orig = _routes.get_llama_cpp_backend
_routes.get_llama_cpp_backend = lambda: FakeBackend()
try:
result = _resolve_inherited_extra_args(
FakeRequest(), FakeConfig(), "unsloth/qwen3.8-27b-gguf", None
)
assert result == [
"--rope-scaling",
"yarn",
"-c",
"300000",
], f"Expected inherited extras for case-variant match, got: {result}"
finally:
_routes.get_llama_cpp_backend = _get_llama_cpp_backend_orig
def test_inheritance_refuses_different_repo():
"""Different repo ids must not inherit extras."""
from routes.inference import _resolve_inherited_extra_args
class FakeRequest:
model_path = "different/repo"
gguf_variant = None
llama_extra_args = None
model_fields_set = set()
class FakeConfig:
is_gguf = True
gguf_variant = None
identifier = "different/repo"
class FakeBackend:
extra_args = ["--rope-scaling", "yarn"]
extra_args_source = ("/models--unsloth--Qwen3.8-27B-GGUF/snapshots/abc123", "ud-q6_k_l")
import routes.inference as _routes
_get_llama_cpp_backend_orig = _routes.get_llama_cpp_backend
_routes.get_llama_cpp_backend = lambda: FakeBackend()
try:
result = _resolve_inherited_extra_args(FakeRequest(), FakeConfig(), "different/repo", None)
assert result == [], f"Expected empty extras for cross-model, got: {result}"
finally:
_routes.get_llama_cpp_backend = _get_llama_cpp_backend_orig
def test_inheritance_refuses_different_variant():
"""Different variants must not inherit extras."""
from routes.inference import _resolve_inherited_extra_args
class FakeRequest:
model_path = "unsloth/Qwen3.8-27B-GGUF"
gguf_variant = "Q4_K_M"
llama_extra_args = None
model_fields_set = set()
class FakeConfig:
is_gguf = True
gguf_variant = "Q4_K_M"
identifier = "unsloth/Qwen3.8-27B-GGUF"
class FakeBackend:
extra_args = ["--rope-scaling", "yarn"]
extra_args_source = ("/models--unsloth--Qwen3.8-27B-GGUF/snapshots/abc123", "q6_k_l")
import routes.inference as _routes
_get_llama_cpp_backend_orig = _routes.get_llama_cpp_backend
_routes.get_llama_cpp_backend = lambda: FakeBackend()
try:
result = _resolve_inherited_extra_args(
FakeRequest(), FakeConfig(), "unsloth/Qwen3.8-27B-GGUF", None
)
assert result == [], f"Expected empty extras for variant mismatch, got: {result}"
finally:
_routes.get_llama_cpp_backend = _get_llama_cpp_backend_orig
def test_explicit_empty_extras_still_clears():
"""An explicit [] still clears extras regardless of identity match."""
from routes.inference import _resolve_inherited_extra_args
class FakeRequest:
model_path = "unsloth/Qwen3.8-27B-GGUF"
gguf_variant = None
llama_extra_args = []
model_fields_set = set()
class FakeConfig:
is_gguf = True
gguf_variant = None
identifier = "unsloth/Qwen3.8-27B-GGUF"
class FakeBackend:
extra_args = ["--rope-scaling", "yarn"]
extra_args_source = ("unsloth/Qwen3.8-27B-GGUF", "ud-q6_k_l")
import routes.inference as _routes
_get_llama_cpp_backend_orig = _routes.get_llama_cpp_backend
_routes.get_llama_cpp_backend = lambda: FakeBackend()
try:
result = _resolve_inherited_extra_args(
FakeRequest(), FakeConfig(), "unsloth/Qwen3.8-27B-GGUF", None
)
assert result is None
finally:
_routes.get_llama_cpp_backend = _get_llama_cpp_backend_orig
def test_missing_extra_args_source_refuses_without_raising():
"""Extras with no recorded source are not inherited, and the refusal log must not raise."""
from routes.inference import _resolve_inherited_extra_args
import routes.inference as _routes
class FakeRequest:
model_path = "unsloth/Qwen3.8-27B-GGUF"
gguf_variant = None
llama_extra_args = None
model_fields_set = set()
class FakeConfig:
is_gguf = True
gguf_variant = "ud-q6_k_l"
identifier = "unsloth/Qwen3.8-27B-GGUF"
original = _routes.get_llama_cpp_backend
try:
for source in (None, (None, "ud-q6_k_l"), ("", None)):
class FakeBackend:
extra_args = ["--rope-scaling", "yarn"]
extra_args_source = source
_routes.get_llama_cpp_backend = lambda: FakeBackend()
result = _resolve_inherited_extra_args(
FakeRequest(), FakeConfig(), "unsloth/Qwen3.8-27B-GGUF", None
)
assert result == [], (source, result)
finally:
_routes.get_llama_cpp_backend = original