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.

47.1 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""MTP reserve = draft KV plus separate drafter weights, sized from GGUF dims; no GPU or I/O."""

from __future__ import annotations

import inspect
import os
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)

sys.modules.setdefault("structlog", _types.ModuleType("structlog"))

# Only stub httpx if missing: a stub shadows huggingface_hub.errors and leaks via sys.modules.
try:
    import httpx as _httpx_real  # noqa: F401
except ImportError:
    _httpx_stub = _types.ModuleType("httpx")
    for _exc_name in (
        "ConnectError",
        "TimeoutException",
        "ReadTimeout",
        "ReadError",
        "RemoteProtocolError",
        "CloseError",
        "HTTPError",
        "RequestError",
    ):
        setattr(_httpx_stub, _exc_name, type(_exc_name, (Exception,), {}))
    _httpx_stub.Timeout = type("Timeout", (), {"__init__": lambda self, *a, **kw: None})
    _httpx_stub.Response = type("Response", (), {})
    _httpx_stub.Client = type(
        "Client",
        (),
        {
            "__init__": lambda self, **kw: None,
            "__enter__": lambda self: self,
            "__exit__": lambda self, *a: None,
        },
    )
    sys.modules["httpx"] = _httpx_stub

from core.inference.llama_cpp import (  # noqa: E402
    _CTX_FIT_VRAM_FRACTION,
    LlamaCppBackend,
    _extra_args_draft_cache_types,
    _extra_args_draft_device_pin,
    _extra_args_draft_offloaded_to_cpu,
    _extra_args_mtp_draft_path,
    _extra_args_n_ubatch,
    _extra_args_requests_mtp,
    _extra_args_requests_separate_draft,
    _extra_args_spec_draft_n_max,
    _effective_tensor_parallel,
    _env_main_cache_type_for_budget,
    _effective_main_cache_types,
    _extra_args_main_cache_type_for_budget,
    _flash_attn_enabled_from_args,
    _kv_bytes_per_elem,
    _tensor_parallel_matches_loaded,
)
from core.inference.llama_server_args import _env_split_mode_is_tensor  # noqa: E402

MIB = 1024 * 1024
GIB = 1024**3


def _make_backend(
    *,
    nextn = 1,
    n_kv_heads = 4,
    n_heads = 24,
    kv_key_length = 256,
    kv_value_length = 256,
    embedding_length = 5120,
    n_layers = 65,
    native_ctx = 262144,
):
    """Qwen3.6-27B-MTP-class backend (embedded head) with the MTP-math dims."""
    b = LlamaCppBackend.__new__(LlamaCppBackend)
    b._nextn_predict_layers = nextn
    b._n_kv_heads = n_kv_heads
    b._n_heads = n_heads
    b._kv_key_length = kv_key_length
    b._kv_value_length = kv_value_length
    b._embedding_length = embedding_length
    b._n_layers = n_layers
    b._context_length = native_ctx
    b._shared_kv_layers = 0
    b._kv_lora_rank = None
    b._sliding_window = None
    b._sliding_window_pattern = None
    b._ssm_inner_size = 6144
    b._full_attention_interval = 4
    b._key_length_mla = None
    b._n_kv_heads_by_layer = None
    b._kv_key_length_swa = None
    b._kv_value_length_swa = None
    b._draft_backend_cache = None
    b._mtp_draft_compute_bytes = lambda *args, **kwargs: 0
    return b


class _StubDrafter:
    """Stand-in for a separate drafter backend (no GGUF I/O)."""

    def __init__(self, kv_per_token):
        self._kv_per_token = kv_per_token
        self._architecture = "gemma3"

    def _can_estimate_kv(self):
        return True

    def _estimate_kv_cache_bytes(
        self,
        n_ctx,
        cache_type = None,
        n_parallel = 1,
        **_k,
    ):
        bpe = _kv_bytes_per_elem(cache_type)
        return 0 if n_ctx <= 0 else int(n_ctx * self._kv_per_token * bpe / 2.0 * n_parallel)


class TestEmbeddedDraftKv:
    def test_scales_linearly_with_context(self):
        b = _make_backend()
        kv_8k = b._mtp_draft_kv_bytes(8192)
        kv_16k = b._mtp_draft_kv_bytes(16384)
        kv_64k = b._mtp_draft_kv_bytes(65536)
        assert kv_8k and kv_16k and kv_64k
        assert kv_16k == pytest.approx(2 * kv_8k)
        assert kv_64k == pytest.approx(8 * kv_8k)

    def test_value_matches_dim_formula_f16(self):
        b = _make_backend()
        ctx = 131072
        expected = int(1 * 4 * 512 * 2.0 * ctx)
        assert b._mtp_draft_kv_bytes(ctx) == expected
        assert b._mtp_draft_kv_bytes(ctx) / MIB == pytest.approx(512, abs = 1)

    def test_scales_with_nextn_predict_layers(self):
        one = _make_backend(nextn = 1)._mtp_draft_kv_bytes(65536)
        two = _make_backend(nextn = 2)._mtp_draft_kv_bytes(65536)
        assert two == pytest.approx(2 * one)

    def test_unaligned_context_follows_runtime_stream_padding(self):
        b = _make_backend()
        bytes_per_cell = b._mtp_draft_kv_bytes(256) // 256
        unified = b._mtp_draft_kv_bytes(5000, n_parallel = 3, kv_unified = True)
        separate = b._mtp_draft_kv_bytes(5000, n_parallel = 3, kv_unified = False)
        assert unified == 5120 * bytes_per_cell
        assert separate == 5376 * bytes_per_cell

    def test_embedded_draft_kv_floored_at_f16(self):
        # Single-layer head: quantized draft KV fits less than f16 (llama.cpp#24102), so floor at f16.
        b = _make_backend()
        f16 = b._mtp_draft_kv_bytes(65536, draft_cache_type_k = "f16", draft_cache_type_v = "f16")
        q8 = b._mtp_draft_kv_bytes(65536, draft_cache_type_k = "q8_0", draft_cache_type_v = "q8_0")
        q4 = b._mtp_draft_kv_bytes(65536, draft_cache_type_k = "q4_0", draft_cache_type_v = "q4_0")
        f32 = b._mtp_draft_kv_bytes(65536, draft_cache_type_k = "f32", draft_cache_type_v = "f32")
        assert q8 == f16 and q4 == f16
        assert f32 == pytest.approx(f16 * 2.0)

    def test_draft_kv_split_axes_no_under_reserve(self):
        b = _make_backend()
        both_q4 = b._mtp_draft_kv_bytes(
            131072, draft_cache_type_k = "q4_0", draft_cache_type_v = "q4_0"
        )
        k_only = b._mtp_draft_kv_bytes(131072, draft_cache_type_k = "q4_0")
        both_f16 = b._mtp_draft_kv_bytes(131072, draft_cache_type_k = "f16", draft_cache_type_v = "f16")
        assert both_q4 == k_only == both_f16

    def test_flash_attn_off_uses_model_wide_v_width(self):
        b = _make_backend(n_layers = 2)
        b._n_kv_heads_by_layer = [4, 1]
        b._sliding_window_pattern = [False, True]
        b._kv_value_length_swa = 2048
        ctx = 4096
        expected_per_cell = 4 * 256 * 2 + 1 * 2048 * 2
        assert b._mtp_draft_kv_bytes(ctx, flash_attn = False) == ctx * expected_per_cell

    def test_none_when_dims_missing(self):
        assert _make_backend(nextn = 0)._mtp_draft_kv_bytes(65536) is None
        assert _make_backend(kv_key_length = None)._mtp_draft_kv_bytes(65536) is None
        assert _make_backend()._mtp_draft_kv_bytes(0) is None


class TestSeparateDrafter:
    def test_uses_drafter_kv_and_weights(self, monkeypatch):
        b = _make_backend(nextn = None)
        stub = _StubDrafter(kv_per_token = 2000)
        monkeypatch.setattr(b, "_draft_backend_for", lambda path: stub)
        ctx = 65536
        kv = b._mtp_draft_kv_bytes(ctx, drafter_path = "/m/draft.gguf")
        assert kv == stub._estimate_kv_cache_bytes(ctx)
        total = b._estimate_mtp_overhead_bytes(
            ctx, drafter_path = "/m/draft.gguf", draft_weights_bytes = GIB
        )
        assert total == kv + GIB

    def test_drafter_kv_scales_with_context(self, monkeypatch):
        b = _make_backend(nextn = None)
        monkeypatch.setattr(b, "_draft_backend_for", lambda path: _StubDrafter(2000))
        a = b._mtp_draft_kv_bytes(16384, drafter_path = "/m/d.gguf")
        c = b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf")
        assert c == pytest.approx(4 * a)

    def test_gemma4_assistant_shares_target_kv(self, monkeypatch):
        b = _make_backend(nextn = None)
        stub = _StubDrafter(kv_per_token = 2000)
        stub._architecture = "gemma4-assistant"
        monkeypatch.setattr(b, "_draft_backend_for", lambda path: stub)

        assert (
            b._mtp_draft_kv_bytes(
                65536,
                drafter_path = "/m/mtp-gemma4.gguf",
                swa_full = True,
            )
            == 0
        )
        assert (
            b._estimate_mtp_overhead_bytes(
                65536,
                drafter_path = "/m/mtp-gemma4.gguf",
                draft_weights_bytes = GIB,
                swa_full = True,
            )
            == GIB
        )

    def test_drafter_kv_scales_with_parallel_slots(self, monkeypatch):
        # The drafter shares --parallel slots, so sliding-window drafter KV grows per slot.
        b = _make_backend(nextn = None)
        monkeypatch.setattr(b, "_draft_backend_for", lambda path: _StubDrafter(2000))
        one = b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf", n_parallel = 1)
        four = b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf", n_parallel = 4)
        assert four == pytest.approx(4 * one)
        ov1 = b._estimate_mtp_overhead_bytes(
            65536, drafter_path = "/m/d.gguf", draft_weights_bytes = GIB, n_parallel = 1
        )
        ov4 = b._estimate_mtp_overhead_bytes(
            65536, drafter_path = "/m/d.gguf", draft_weights_bytes = GIB, n_parallel = 4
        )
        assert (ov4 - GIB) == pytest.approx(4 * (ov1 - GIB))

    def test_none_when_drafter_unreadable(self, monkeypatch):
        b = _make_backend(nextn = None)
        monkeypatch.setattr(b, "_draft_backend_for", lambda path: None)
        assert b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf") is None
        assert b._estimate_mtp_overhead_bytes(65536, drafter_path = "/m/d.gguf") is None

    def test_keeps_weights_when_drafter_kv_unsizable(self, monkeypatch):
        b = _make_backend(nextn = None)
        monkeypatch.setattr(b, "_draft_backend_for", lambda path: None)
        assert b._mtp_draft_kv_bytes(65536, drafter_path = "/m/d.gguf") is None
        assert (
            b._estimate_mtp_overhead_bytes(
                65536, drafter_path = "/m/d.gguf", draft_weights_bytes = 3 * GIB
            )
            == 3 * GIB
        )
        assert b._estimate_mtp_overhead_bytes(65536, drafter_path = "/m/d.gguf") is None


class TestOverheadTotal:
    def test_equals_draft_kv_for_embedded(self):
        b = _make_backend()
        for ctx in (16384, 65536, 131072):
            assert b._estimate_mtp_overhead_bytes(ctx) == b._mtp_draft_kv_bytes(ctx)

    def test_does_not_depend_on_n_max(self):
        b = _make_backend()
        assert b._estimate_mtp_overhead_bytes(
            65536, spec_draft_n_max = 2
        ) == b._estimate_mtp_overhead_bytes(65536, spec_draft_n_max = 6)

    def test_none_when_draft_kv_unsizable(self):
        assert _make_backend(nextn = 0)._estimate_mtp_overhead_bytes(65536) is None

    def test_includes_separate_drafter_weights(self):
        b = _make_backend()
        base = b._estimate_mtp_overhead_bytes(65536)
        with_w = b._estimate_mtp_overhead_bytes(65536, draft_weights_bytes = GIB)
        assert with_w - base == GIB

    @pytest.mark.parametrize(
        "ctx,measured_draft_kv_mib",
        # Measured 27B MTP delta minus the headroom-covered ~500 MiB verify buffer.
        [(16384, 64), (65536, 256), (131072, 512)],
    )
    def test_draft_kv_matches_measured(self, ctx, measured_draft_kv_mib):
        b = _make_backend()
        pred = b._estimate_mtp_overhead_bytes(ctx) / MIB
        assert pred == pytest.approx(measured_draft_kv_mib, abs = 2)

    @pytest.mark.parametrize(
        "ctx,target_kv_mib,draft_kv_mib",
        [
            (4096, 256, 16),
            (16384, 1024, 64),
            (65536, 4096, 256),
            (131072, 8192, 512),
        ],
    )
    def test_hybrid_mtp_matches_target_and_draft_context_across_lengths(
        self, ctx, target_kv_mib, draft_kv_mib
    ):
        b = _make_backend(n_layers = 65)
        b._ssm_state_size = 128
        b._ssm_group_count = 16
        b._ssm_conv_kernel = 4
        base = b._mamba_recurrent_state_bytes(n_parallel = 4)
        target = b._estimate_kv_cache_bytes(ctx, "f16", n_parallel = 4)
        draft_kv = b._mtp_draft_kv_bytes(ctx, n_parallel = 4)

        assert base / MIB == pytest.approx(598.5)
        assert target == base + target_kv_mib * MIB
        assert draft_kv == draft_kv_mib * MIB
        assert (
            b._estimate_mtp_overhead_bytes(
                ctx,
                spec_draft_n_max = 2,
                n_parallel = 4,
            )
            == draft_kv + 2 * base
        )

    def test_a_separate_drafter_pays_the_same_target_rollback_state(self, monkeypatch):
        # Rollback copies sit in the target for every draft-model type except draft-simple.
        b = _make_backend(n_layers = 65)
        b._ssm_state_size = 128
        b._ssm_group_count = 16
        b._ssm_conv_kernel = 4
        stub = _StubDrafter(kv_per_token = 2000)
        monkeypatch.setattr(b, "_draft_backend_for", lambda path: stub)
        base = b._mamba_recurrent_state_bytes(n_parallel = 4)
        draft_kv = stub._estimate_kv_cache_bytes(4096, n_parallel = 4)
        assert base > 0

        assert (
            b._estimate_mtp_overhead_bytes(
                4096,
                drafter_path = "/m/d.gguf",
                spec_draft_n_max = 2,
                n_parallel = 4,
            )
            == draft_kv + 2 * base
        )
        assert (
            b._estimate_mtp_overhead_bytes(
                4096,
                drafter_path = "/m/d.gguf",
                spec_draft_n_max = 2,
                n_parallel = 4,
                target_rollback = False,
            )
            == draft_kv
        )


class TestFitContextWithMtp:
    def _fit_backend(self, kv_per_token = 325_000):
        b = _make_backend()
        b._can_estimate_kv = lambda: True
        b._estimate_kv_cache_bytes = lambda n, _t = None, **_k: 0 if n <= 0 else n * kv_per_token
        return b

    def test_overhead_fn_lowers_context(self):
        b = self._fit_backend()
        avail_mib = 24_000
        model = 8 * GIB
        without = b._fit_context_to_vram(131072, avail_mib, model)
        with_mtp = b._fit_context_to_vram(
            131072,
            avail_mib,
            model,
            mtp_overhead_fn = lambda c: b._estimate_mtp_overhead_bytes(c) or 0,
        )
        assert 0 < with_mtp < without

    def test_quantized_embedded_draft_kv_does_not_inflate_context(self):
        b = self._fit_backend()
        avail_mib, model = 24_000, 8 * GIB
        f16 = b._fit_context_to_vram(
            131072,
            avail_mib,
            model,
            mtp_overhead_fn = lambda c: (
                b._estimate_mtp_overhead_bytes(
                    c, draft_cache_type_k = "f16", draft_cache_type_v = "f16"
                )
                or 0
            ),
        )
        q4 = b._fit_context_to_vram(
            131072,
            avail_mib,
            model,
            mtp_overhead_fn = lambda c: (
                b._estimate_mtp_overhead_bytes(
                    c, draft_cache_type_k = "q4_0", draft_cache_type_v = "q4_0"
                )
                or 0
            ),
        )
        assert 0 < q4 == f16

    def test_no_mtp_unchanged(self):
        b = self._fit_backend()
        avail_mib, model = 24_000, 8 * GIB
        a = b._fit_context_to_vram(131072, avail_mib, model)
        bb = b._fit_context_to_vram(
            131072, avail_mib, model, mtp_engaged = False, mtp_overhead_fn = None
        )
        assert a == bb

    def test_chosen_context_actually_fits_budget(self):
        b = self._fit_backend()
        avail_mib, model = 24_000, 8 * GIB
        fn = lambda c: b._estimate_mtp_overhead_bytes(c) or 0  # noqa: E731
        ctx = b._fit_context_to_vram(131072, avail_mib, model, mtp_overhead_fn = fn)
        budget = avail_mib * MIB * _CTX_FIT_VRAM_FRACTION
        assert model + b._estimate_kv_cache_bytes(ctx) + fn(ctx) <= budget


class TestExtraArgsMtpDetection:
    @pytest.mark.parametrize(
        "args,expected",
        [
            (["--spec-type", "draft-mtp"], True),
            (["--spec-type", "mtp"], True),
            (["--spec-type", "ngram-mod,draft-mtp"], True),
            (["--spec-type=draft-mtp"], True),
            (["--spec_type=draft-mtp"], True),
            (["--spec-type", "ngram-mod"], False),
            (["--spec-default"], False),
            (["-c", "131072"], False),
            (None, False),
            ([], False),
        ],
    )
    def test_requests_mtp(self, args, expected):
        assert _extra_args_requests_mtp(args, env = {}) is expected

    def test_requests_mtp_env(self):
        assert _extra_args_requests_mtp([], env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}) is True
        assert _extra_args_requests_mtp([], env = {"LLAMA_ARG_SPEC_TYPE": "ngram-mod,mtp"}) is True
        assert _extra_args_requests_mtp([], env = {"LLAMA_ARG_SPEC_TYPE": "draft-simple"}) is False
        assert _extra_args_requests_mtp([], env = {"LLAMA_ARG_SPEC_TYPE": "none"}) is False

    def test_requests_mtp_effective_spec_type(self):
        # llama.cpp accumulates spec types (env first, then CLI appends), so count every source.
        env_mtp = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
        assert (
            _extra_args_requests_mtp(
                ["--spec-type", "draft-mtp", "--spec-type", "ngram-mod"], env = {}
            )
            is True
        )
        assert _extra_args_requests_mtp(["--spec-type", "ngram-mod"], env = env_mtp) is True
        assert _extra_args_requests_mtp(["--spec-type", "none"], env = env_mtp) is True
        assert (
            _extra_args_requests_mtp(
                ["--spec-type", "ngram-mod", "--spec-type", "draft-mtp"], env = {}
            )
            is True
        )
        assert _extra_args_requests_mtp(["--spec-type", "ngram-mod"], env = {}) is False
        assert (
            _extra_args_requests_separate_draft(
                ["--spec-type", "draft-simple", "--spec-type", "ngram-mod"], env = {}
            )
            is True
        )
        assert (
            _extra_args_requests_separate_draft(
                ["--spec-type", "ngram-mod"], env = {"LLAMA_ARG_SPEC_TYPE": "draft-simple"}
            )
            is True
        )
        assert _extra_args_requests_separate_draft(["--spec-type", "ngram-mod"], env = {}) is False

    @pytest.mark.parametrize(
        "args,expected",
        [
            (["--spec-type", "draft-simple"], True),
            (["--spec-type", "draft-eagle3"], True),
            (["--spec-type=draft-eagle3"], True),
            (["--spec-type", "draft-mtp"], False),
            (["--spec-type", "ngram-mod"], False),
            (["-c", "4096"], False),
            (None, False),
        ],
    )
    def test_requests_separate_draft(self, args, expected):
        assert _extra_args_requests_separate_draft(args, env = {}) is expected

    def test_requests_separate_draft_env(self):
        assert (
            _extra_args_requests_separate_draft([], env = {"LLAMA_ARG_SPEC_TYPE": "draft-simple"})
            is True
        )
        assert (
            _extra_args_requests_separate_draft([], env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"})
            is False
        )

    def test_load_model_reserves_for_non_mtp_draft_modes(self):
        # Whitespace-stripped so the source check survives formatter line-wrapping.
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "_user_draft_via_extras" in compact
        assert "_extra_args_requests_separate_draft(extra_args" in compact
        assert "or_user_draft_via_extras" in compact
        # No env={} here: env=None lets an env-only LLAMA_ARG_SPEC_DRAFT_MODEL engage the reserve.
        assert "bool(_extra_args_mtp_draft_path(extra_args))" in compact

    def test_env_only_drafter_engages_separate_draft_reserve(self, monkeypatch):
        monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_MODEL", "/large.gguf")
        monkeypatch.delenv("LLAMA_ARG_SPEC_DRAFT_HF_REPO", raising = False)
        ea = ["--spec-type", "draft-simple"]
        assert _extra_args_requests_separate_draft(ea, env = {}) is True
        assert _extra_args_mtp_draft_path(ea) == "/large.gguf"
        assert _extra_args_mtp_draft_path([], env = dict(os.environ)) == "/large.gguf"

    def test_the_fit_reads_the_env_only_when_the_extras_own_the_spec_type(self):
        # llama.cpp appends spec types, so the launch scrubs LLAMA_ARG_SPEC_TYPE when Unsloth owns it.
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "_spec_env:Mapping[str,str]=_child_spec_env(extra_args)" in compact
        assert "_extra_args_requests_mtp(extra_args,env=_spec_env)" in compact
        assert "ornot_extra_args_set_spec_type(extra_args):" in compact
        assert "env.pop(_pv_spec_var,None)" in compact

    def test_spec_default_does_not_clear_an_inherited_spec_type(self):
        # --spec-default appends NGRAM_MOD rather than replacing, so an inherited type still counts.
        env_mtp = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
        assert _extra_args_requests_mtp(["--spec-default"], env = env_mtp) is True
        assert (
            _extra_args_requests_separate_draft(
                ["--spec-default"], env = {"LLAMA_ARG_SPEC_TYPE": "draft-simple"}
            )
            is True
        )
        assert _extra_args_requests_mtp(["--spec-default"], env = {}) is False
        assert _extra_args_requests_separate_draft(["--spec-default"], env = {}) is False
        assert (
            _extra_args_requests_mtp(["--spec-default", "--spec-type", "draft-mtp"], env = {}) is True
        )

    def test_load_model_drafter_budget_precedence(self):
        # Drafter precedence: CLI extras, then mtp_draft_path, then env (only if it survives the scrub).
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "_cli_draft_for_budget=_extra_args_mtp_draft_path(extra_args,env={})" in compact
        assert "_env_draft_for_budget=_extra_args_mtp_draft_path([],env=_spec_env)" in compact
        assert "_cli_draft_for_budgetor_studio_draft_for_budgetor_env_draft_for_budget" in compact

    def test_load_model_drops_cpu_offloaded_drafter_from_budget(self):
        # A CPU-offloaded separate drafter uses no GPU; an embedded head stays on GPU only if it runs.
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert (
            "_draft_on_cpu=_extra_args_draft_offloaded_to_cpu(extra_args,env=os.environ)" in compact
        )
        assert "if_draft_on_cpu:_mtp_draft_for_budget=None" in compact
        assert "_draft_cpu_no_embedded=_draft_on_cpuand(" in compact
        assert "ornotself._nextn_predict_layers)" in compact
        assert "not_draft_cpu_no_embedded" in compact

    def test_load_model_keeps_flat_reserve_for_unsized_draft_kv(self):
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "_mtp_kv_unsized" in compact
        assert "mtp_overhead_fnisNoneor_mtp_kv_unsized" in compact

    def test_load_model_ranks_subsets_by_active_pin_fraction(self):
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "usable=_gpu_usable(g,frac)" in compact
        assert "_gpu_rank(g,pin_fraction," in compact
        assert "_gpu_rank(g,_vram_frac-_flat_mtp_reserve," in compact
        assert "_vram_frac=_active_vram_fraction()" in compact

    @pytest.mark.parametrize(
        "args,expected",
        [
            (["--spec-draft-ngl", "0"], True),
            (["-ngld", "0"], True),
            (["--spec-draft-ngl=0"], True),
            (["--spec_draft_ngl=0"], True),
            (["--n-gpu-layers-draft", "0"], True),
            (["--spec-draft-ngl", "20"], False),
            (["--spec-draft-device", "none"], True),
            (["--spec-draft-device", "CPU"], True),
            (["-devd", "cpu,none"], True),
            (["--spec-draft-device", "CUDA0"], False),
            (["--spec-draft-device", "CUDA0,CPU"], False),
            (["-c", "4096"], False),
            (None, False),
            # last-wins: only the final value of each flag counts
            (["--spec-draft-ngl", "0", "--spec-draft-ngl", "-1"], False),
            (["--spec-draft-ngl", "-1", "--spec-draft-ngl", "0"], True),
            (["--spec-draft-device", "CUDA0", "--spec-draft-device", "none"], True),
            (["--spec-draft-device", "none", "--spec-draft-device", "CUDA0"], False),
        ],
    )
    def test_draft_offloaded_to_cpu(self, args, expected):
        assert _extra_args_draft_offloaded_to_cpu(args, env = {}) is expected

    def test_draft_offloaded_to_cpu_env(self):
        assert (
            _extra_args_draft_offloaded_to_cpu([], env = {"LLAMA_ARG_N_GPU_LAYERS_DRAFT": "0"})
            is True
        )
        assert (
            _extra_args_draft_offloaded_to_cpu([], env = {"LLAMA_ARG_N_GPU_LAYERS_DRAFT": "-1"})
            is False
        )
        assert (
            _extra_args_draft_offloaded_to_cpu(
                ["--spec-draft-ngl", "-1"], env = {"LLAMA_ARG_N_GPU_LAYERS_DRAFT": "0"}
            )
            is False
        )
        assert _extra_args_draft_offloaded_to_cpu([], env = {}) is False

    @pytest.mark.parametrize(
        "args,expected",
        [
            (None, None),
            ([], None),
            (["-c", "4096"], None),
            (["--spec-draft-device", "cpu"], None),
            (["--spec-draft-device", "CPU,none"], None),
            (["-devd", "none"], None),
            (["--spec-draft-device", "CUDA1"], "CUDA1"),
            (["--device-draft", "Vulkan2"], "Vulkan2"),
            (["--spec_draft_device", "Vulkan1"], "Vulkan1"),
            (["-devd", "CUDA0,CPU"], "CUDA0,CPU"),
            (["--spec-draft-device=Vulkan3"], "Vulkan3"),
            (["--device_draft=Vulkan4"], "Vulkan4"),
            (["--spec-draft-device", "CUDA1", "--spec-draft-device", "cpu"], None),
            (["--spec-draft-device", "cpu", "--spec-draft-device", "CUDA1"], "CUDA1"),
        ],
    )
    def test_draft_device_pin(self, args, expected):
        assert _extra_args_draft_device_pin(args) == expected

    @pytest.mark.parametrize(
        "args,expected",
        [
            (["--spec-draft-n-max", "4"], 4),
            (["--spec-draft-n-max=6"], 6),
            (["--spec_draft_n_max=6"], 6),
            (["--spec-type", "draft-mtp", "--spec-draft-n-max", "3"], 3),
            (["--spec-draft-n-max", "2", "--spec-draft-n-max", "5"], 5),
            (["--spec-draft-n-max", "notanint"], None),
            (["-c", "4096"], None),
            (None, None),
            (["--draft-max", "6"], 6),
            (["--draft-max=4"], 4),
            (["--spec-type", "draft-mtp", "--draft-max", "6"], 6),
            (["--spec-draft-n-max", "2", "--draft-max", "5"], 5),
        ],
    )
    def test_spec_draft_n_max(self, args, expected):
        assert _extra_args_spec_draft_n_max(args) == expected

    @pytest.mark.parametrize(
        "args,expected",
        [
            (["--model-draft", "/m/draft.gguf"], "/m/draft.gguf"),
            (["--spec-draft-model", "/m/draft.gguf"], "/m/draft.gguf"),
            (["-md", "/m/draft.gguf"], "/m/draft.gguf"),
            (["--model-draft=/m/draft.gguf"], "/m/draft.gguf"),
            (["--model_draft=/m/draft.gguf"], "/m/draft.gguf"),
            (["--model-draft", "--spec-type"], None),
            (["-c", "4096"], None),
            (None, None),
        ],
    )
    def test_mtp_draft_path(self, args, expected):
        assert _extra_args_mtp_draft_path(args, env = {}) == expected

    @pytest.mark.parametrize(
        "args,expected",
        [
            (["--spec-draft-hf", "big/repo:Q8_0"], "big/repo:Q8_0"),
            (["-hfd", "big/repo"], "big/repo"),
            (["-hfrd", "big/repo"], "big/repo"),
            (["--hf-repo-draft=big/repo"], "big/repo"),
        ],
    )
    def test_mtp_draft_path_hf_flags(self, args, expected):
        assert _extra_args_mtp_draft_path(args, env = {}) == expected

    def test_mtp_draft_path_env_fallback(self):
        assert (
            _extra_args_mtp_draft_path([], env = {"LLAMA_ARG_SPEC_DRAFT_MODEL": "/m/e.gguf"})
            == "/m/e.gguf"
        )
        assert _extra_args_mtp_draft_path([], env = {"LLAMA_ARG_SPEC_DRAFT_HF_REPO": "x/y"}) == "x/y"
        assert (
            _extra_args_mtp_draft_path(
                ["-md", "/m/cli.gguf"], env = {"LLAMA_ARG_SPEC_DRAFT_HF_REPO": "x/y"}
            )
            == "/m/cli.gguf"
        )

    @pytest.mark.parametrize(
        "args,expected",
        [
            (["--cache-type-k-draft", "q8_0"], ("q8_0", None)),
            (["--spec-draft-type-k", "q4_0"], ("q4_0", None)),
            (["-ctkd", "q8_0"], ("q8_0", None)),
            (["--cache-type-v-draft", "q4_0"], (None, "q4_0")),
            (["--cache-type-k-draft", "q4_0", "--cache-type-v-draft", "q8_0"], ("q4_0", "q8_0")),
            (["--cache-type-k-draft=q8_0"], ("q8_0", None)),
            (["--cache_type_k_draft=q8_0"], ("q8_0", None)),
            (["--cache-type-k", "q8_0"], (None, None)),
            (["-c", "4096"], (None, None)),
            (None, (None, None)),
        ],
    )
    def test_draft_cache_types(self, args, expected):
        assert _extra_args_draft_cache_types(args, env = {}) == expected

    def test_draft_cache_types_env_fallback(self):
        assert _extra_args_draft_cache_types(
            [], env = {"LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K": "q8_0"}
        ) == ("q8_0", None)
        assert _extra_args_draft_cache_types(
            [],
            env = {
                "LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K": "q8_0",
                "LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V": "q4_0",
            },
        ) == ("q8_0", "q4_0")
        assert _extra_args_draft_cache_types(
            ["-ctkd", "q4_0"], env = {"LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K": "q8_0"}
        ) == ("q4_0", None)

    @pytest.mark.parametrize(
        "args,expected",
        [
            (["--ubatch-size", "1024"], 1024),
            (["-ub", "4096"], 2048),
            (["--ubatch-size", "0"], 2048),
            (["--batch-size", "256", "--ubatch-size", "0"], 256),
            (["--batch-size", "-1"], 512),
            (["--ubatch-size", "-1"], 2048),
            (["--ubatch-size=512"], 512),
            (["--ubatch_size=512"], 512),
            (["--batch-size", "256"], 256),
            (["--batch_size=256"], 256),
            (["-b", "256", "-ub", "1024"], 256),
            (["-b", "4096"], 512),
            (["--ubatch", "2048"], None),
            (["-c", "4096"], None),
            (None, None),
        ],
    )
    def test_n_ubatch(self, args, expected):
        assert _extra_args_n_ubatch(args, env = {}) == expected

    def test_n_ubatch_signed_values_cap_at_context(self):
        assert (
            _extra_args_n_ubatch(
                ["--batch-size", "-1", "--ubatch-size", "-1"],
                env = {},
                n_ctx = 4096,
            )
            == 4096
        )

    @pytest.mark.parametrize(
        "args,expected",
        [
            (None, True),
            (["--flash-attn", "off"], False),
            (["--flash-attn", "disabled"], False),
            (["--flash-attn", "false"], False),
            (["--flash-attn", "0"], False),
            (["--flash-attn=off"], False),
            (["--flash-attn=disabled"], False),
            (["--flash-attn=false"], False),
            (["--flash-attn=0"], False),
            (["--flash_attn", "off"], False),
            (["-fa", "off", "--flash-attn", "auto"], True),
            (["-fa", "off", "--flash-attn", "-1"], True),
            (["-fa", "off", "--flash-attn", "enabled"], True),
            (["-fa", "off", "--flash-attn=true"], True),
            (["-fa", "off", "--flash-attn=1"], True),
            (["--flash-attn", "off", "-fa"], True),
        ],
    )
    def test_flash_attn_last_value_wins(self, args, expected):
        assert _flash_attn_enabled_from_args(args, env = {}) is expected

    @pytest.mark.parametrize(
        "value,expected",
        [
            ("off", False),
            ("disabled", False),
            ("false", False),
            ("0", False),
            ("on", True),
            ("auto", True),
            ("garbage", True),
        ],
    )
    def test_flash_attn_env_applies(self, value, expected):
        env = {"LLAMA_ARG_FLASH_ATTN": value}
        assert _flash_attn_enabled_from_args([], env = env) is expected
        assert _flash_attn_enabled_from_args(["-fa", "on"], env = env) is True
        assert _flash_attn_enabled_from_args(["-fa", "off"], env = env) is False

    def test_effective_main_cache_types_follow_env_then_cli(self):
        env = {
            "LLAMA_ARG_CACHE_TYPE_K": "f32",
            "LLAMA_ARG_CACHE_TYPE_V": "q4_0",
        }
        assert _effective_main_cache_types([], env) == ("f32", "q4_0")
        assert _effective_main_cache_types(["--cache-type-v", "f16"], env) == ("f32", "f16")

    def test_n_ubatch_env_fallback(self):
        # Env applies first, then CLI overrides per axis, then llama.cpp caps ubatch at batch size.
        assert _extra_args_n_ubatch([], env = {"LLAMA_ARG_UBATCH": "4096"}) == 2048
        assert _extra_args_n_ubatch([], env = {"LLAMA_ARG_BATCH": "256"}) == 256
        assert (
            _extra_args_n_ubatch(
                [],
                env = {
                    "LLAMA_ARG_BATCH": "1024",
                    "LLAMA_ARG_UBATCH": "4096",
                },
            )
            == 1024
        )
        assert _extra_args_n_ubatch(["-ub", "1024"], env = {"LLAMA_ARG_UBATCH": "4096"}) == 1024
        assert (
            _extra_args_n_ubatch(
                ["-b", "1024"],
                env = {
                    "LLAMA_ARG_BATCH": "256",
                    "LLAMA_ARG_UBATCH": "4096",
                },
            )
            == 1024
        )
        assert _extra_args_n_ubatch([], env = {"LLAMA_ARG_UBATCH": "notint"}) is None

    def test_env_main_cache_type_for_budget(self):
        assert _env_main_cache_type_for_budget(env = {}) is None
        assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "f32"}) == "f32"
        assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_V": "F32"}) == "f32"
        assert (
            _env_main_cache_type_for_budget(
                env = {"LLAMA_ARG_CACHE_TYPE_K": "f32", "LLAMA_ARG_CACHE_TYPE_V": "f16"}
            )
            == "f32"
        )
        # Adopt a quantized env type only when both axes are; else the f16 axis would be under-reserved.
        assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "q4_0"}) is None
        assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_V": "q8_0"}) is None
        assert (
            _env_main_cache_type_for_budget(
                env = {"LLAMA_ARG_CACHE_TYPE_K": "q4_0", "LLAMA_ARG_CACHE_TYPE_V": "q4_0"}
            )
            == "q4_0"
        )
        assert (
            _env_main_cache_type_for_budget(
                env = {"LLAMA_ARG_CACHE_TYPE_K": "q4_0", "LLAMA_ARG_CACHE_TYPE_V": "q8_0"}
            )
            == "q8_0"
        )
        assert (
            _env_main_cache_type_for_budget(
                env = {"LLAMA_ARG_CACHE_TYPE_K": "q8_0", "LLAMA_ARG_CACHE_TYPE_V": "f32"}
            )
            == "f32"
        )
        assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "f16"}) is None
        assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "wat"}) is None

    def test_load_model_adopts_env_main_cache_type(self):
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "_extra_args_main_cache_type_for_budget(extra_args)" in compact
        assert "ifcache_type_kvisNone:" in compact
        assert "cache_type_kv=_env_main_cache_type_for_budget()" in compact

    def test_env_split_mode_is_tensor(self):
        assert _env_split_mode_is_tensor(env = {}) is False
        assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "tensor"}) is True
        assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "Tensor"}) is True
        assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "layer"}) is False
        assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "row"}) is False
        assert _env_split_mode_is_tensor(env = {"LLAMA_ARG_SPLIT_MODE": "none"}) is False

    def test_effective_tensor_parallel_env_flip(self):
        tensor_env = {"LLAMA_ARG_SPLIT_MODE": "tensor"}
        assert _effective_tensor_parallel(None, False, env = tensor_env) is True
        assert _effective_tensor_parallel(["--split-mode", "layer"], False, env = tensor_env) is False
        assert _effective_tensor_parallel(["--split-mode", "tensor"], False, env = {}) is True
        assert _effective_tensor_parallel(None, True, env = {}) is True
        assert _effective_tensor_parallel(None, False, env = {}) is False
        assert (
            _effective_tensor_parallel(None, False, env = {"LLAMA_ARG_SPLIT_MODE": "layer"}) is False
        )

    def test_tensor_parallel_matches_loaded_env_downgrade(self):
        # A server downgraded to layer must still match an env-only tensor request, or it reloads forever.
        tensor_env = {"LLAMA_ARG_SPLIT_MODE": "tensor"}
        assert _tensor_parallel_matches_loaded(None, False, True, env = tensor_env) is True
        assert _tensor_parallel_matches_loaded(None, False, False, env = tensor_env) is True
        assert _tensor_parallel_matches_loaded(None, False, False, env = {}) is True
        assert _tensor_parallel_matches_loaded(None, False, True, env = {}) is False
        assert _tensor_parallel_matches_loaded(None, True, False, env = {}) is False
        assert _tensor_parallel_matches_loaded(None, True, True, env = {}) is True
        assert (
            _tensor_parallel_matches_loaded(["--split-mode", "layer"], False, True, env = tensor_env)
            is False
        )

    def test_extra_args_main_cache_type_heavier_axis(self):
        H = _extra_args_main_cache_type_for_budget
        assert H(["--cache-type-k", "f32", "--cache-type-v", "f16"]) == "f32"
        assert H(["--cache-type-v", "f16", "--cache-type-k", "f32"]) == "f32"
        assert H(["--cache-type-k=f32", "--cache-type-v=f16"]) == "f32"
        assert H(["-ctk", "q4_0", "-ctv", "q8_0"]) == "q8_0"
        assert H(["--cache-type-k", "q8_0"]) == "q8_0"
        assert H(["-c", "4096"]) is None
        assert H(None) is None

    def test_load_model_budgets_heavier_asymmetric_cache_axis(self):
        load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "_extra_args_main_cache_type_for_budget(extra_args)" in load

    def test_load_model_tensor_skips_reserve_for_cpu_drafter(self):
        # CPU drafter: suppress the flat reserve, but a Hybrid Mamba target's rollback state stays on GPU.
        load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "if(_flat_mtp_engagesandnot_draft_cpu_no_embedded)" in load
        assert "_mtp_reserves_gpu=_mtp_will_engageandnot_draft_cpu_no_embedded" in load
        assert "mtp_engaged=_mtp_reserves_gpu" in load
        assert "_mtp_gpu_bytes_remain=_mtp_reserves_gpuormtp_overhead_fnisnotNone" in load
        assert "ifnot_mtp_gpu_bytes_remain:" in load

    def test_load_model_adopts_env_tensor_split_mode(self):
        load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "tensor_parallel=_effective_tensor_parallel(extra_args,tensor_parallel)" in load
        helper = "".join(inspect.getsource(_effective_tensor_parallel).split())
        assert "notresolved" in helper
        assert "parse_split_mode_override(extra_args)isNone" in helper
        assert "_env_split_mode_is_tensor(env)" in helper

    def test_load_model_does_not_emit_env_only_cache_type(self):
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "cache_type_kv=_env_main_cache_type_for_budget()" in compact
        assert "_cache_type_from_env=cache_type_kvisnotNone" in compact
        assert "andnot_cache_type_from_env" in compact

    def test_load_model_clears_inherited_split_mode_on_layer(self):
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "self._reconcile_split_mode_env(env,tensor_parallel=tensor_parallel)" in compact
        for sm in ("none", "row", "tensor", " Row "):
            env = {"LLAMA_ARG_SPLIT_MODE": sm, "LLAMA_ARG_TENSOR_SPLIT": "1,1", "X": "1"}
            LlamaCppBackend._reconcile_split_mode_env(env, tensor_parallel = False)
            assert env == {"X": "1"}, sm
        env = {"LLAMA_ARG_SPLIT_MODE": "layer", "LLAMA_ARG_TENSOR_SPLIT": "1,1"}
        LlamaCppBackend._reconcile_split_mode_env(env, tensor_parallel = False)
        assert env == {"LLAMA_ARG_SPLIT_MODE": "layer", "LLAMA_ARG_TENSOR_SPLIT": "1,1"}

    def test_load_model_clears_tensor_split_env_in_tensor_mode(self):
        env = {"LLAMA_ARG_SPLIT_MODE": "tensor", "LLAMA_ARG_TENSOR_SPLIT": "1,1"}
        LlamaCppBackend._reconcile_split_mode_env(env, tensor_parallel = True)
        assert env == {"LLAMA_ARG_SPLIT_MODE": "tensor"}

    def test_load_model_layer_compute_buffer_fallback(self):
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "if_compute_buffer_pipeline<=0:" in compact
        # RHS only so the match survives formatter parens; unique in load_model (other use is MiB).
        assert "self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB*1024*1024" in compact

    def test_load_model_passes_unsized_mtp_reserve_to_tensor_planner(self):
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "_tp_unsized_mtp_reserve=" in compact
        assert "(_mtp_reserves_gpuand_mtp_kv_unsized)" in compact
        assert "mtp_flat_reserve_bytes=_tp_unsized_mtp_reserve" in compact

    def test_pool_budget_sums_per_gpu_usable(self):
        compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        assert "def_pool_budget_mib(subset,frac):" in compact
        assert "sum(max(0.0,_gpu_usable(g,frac))forginsubset)" in compact
        assert "def_pool_total(" not in compact
        assert "budget_frac=1.0" in compact


def test_qwen36_class_regression_picks_lower_ctx_with_mtp():
    """A 24 GB card with MTP must auto-pick a strictly lower context than without it."""
    b = _make_backend()
    b._can_estimate_kv = lambda: True
    b._estimate_kv_cache_bytes = lambda n, _t = None, **_k: 0 if n <= 0 else int(n * 66_000)
    avail_mib = 24_000
    model = int(17.9 * GIB)  # UD-Q4_K_XL weights
    no_mtp = b._fit_context_to_vram(262144, avail_mib, model)
    with_mtp = b._fit_context_to_vram(
        262144,
        avail_mib,
        model,
        mtp_overhead_fn = lambda c: b._estimate_mtp_overhead_bytes(c) or 0,
    )
    assert 0 < with_mtp < no_mtp


def test_mtp_draft_budget_prefers_user_extras_drafter():
    # A user --model-draft is appended last and wins at launch, so the budget sizes it first.
    compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
    assert "_cli_draft_for_budget=_extra_args_mtp_draft_path(extra_args,env={})" in compact
    assert "_cli_draft_for_budgetor_studio_draft_for_budgetor_env_draft_for_budget" in compact
    assert "_extra_args_mtp_draft_path(extra_args)ormtp_draft_path" not in compact


class TestUnemittableCacheTypeFallsBackToTheEnvBudget:
    """An unemittable cache type is never passed, so the child inherits the env type; price that."""

    @staticmethod
    def _budget_type(cache_type_kv, env):
        """Extras, then the field, then a heavier inherited env decide the reserved cache type."""
        from core.inference.llama_cpp import (
            _VALID_CACHE_TYPES,
            _env_main_cache_type_for_budget,
        )

        resolved = cache_type_kv
        if resolved is not None and resolved.strip().lower() not in _VALID_CACHE_TYPES:
            resolved = None
        if resolved is None:
            resolved = _env_main_cache_type_for_budget(env)
        return resolved

    def test_an_unknown_type_does_not_shadow_a_heavier_inherited_env(self):
        """q3_K is not emittable, so the child runs inherited f32; budgeting q3_K prices it at the
        2.0 unknown default of _kv_bytes_per_elem, a 2x under-reservation with no --fit valve."""
        env = {"LLAMA_ARG_CACHE_TYPE_K": "f32", "LLAMA_ARG_CACHE_TYPE_V": "f32"}
        assert self._budget_type("q3_K", env) == "f32"

    def test_an_emittable_type_still_wins_over_the_env(self):
        """Emitted q8_0 overrides the env on both axes, so the budget must price it (#8939)."""
        env = {"LLAMA_ARG_CACHE_TYPE_K": "f32", "LLAMA_ARG_CACHE_TYPE_V": "f32"}
        assert self._budget_type("q8_0", env) == "q8_0"

    def test_an_unknown_type_with_no_env_is_left_at_the_f16_default(self):
        assert self._budget_type("q3_K", {}) is None

    def test_the_loader_applies_the_guard_before_the_env_adoption(self):
        """Source-pinned: the guard must precede env adoption, or the unemittable string stays."""
        load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
        guard = load.find("notin_VALID_CACHE_TYPES")
        adopt = load.find("cache_type_kv=_env_main_cache_type_for_budget()")
        assert guard != -1, "the unemittable-type guard is gone"
        assert adopt != -1
        assert guard < adopt, (guard, adopt)


class TestAnUnsetInheritedCacheAxisIsStillF16:
    """Unset cache axes count as f16 in the max, so one quantized axis cannot carry the scalar alone."""

    @staticmethod
    def _budget(env):
        from core.inference.llama_cpp import _env_main_cache_type_for_budget
        return _env_main_cache_type_for_budget(env)

    @pytest.mark.parametrize("var", ["LLAMA_ARG_CACHE_TYPE_K", "LLAMA_ARG_CACHE_TYPE_V"])
    def test_one_quantized_axis_alone_does_not_adopt_a_lighter_scalar(self, var):
        """Either order gives (q4_0, f16), whose heavier axis f16 is already conservative."""
        assert self._budget({var: "q4_0"}) is None
        assert self._budget({var: "q8_0"}) is None

    @pytest.mark.parametrize("var", ["LLAMA_ARG_CACHE_TYPE_K", "LLAMA_ARG_CACHE_TYPE_V"])
    def test_one_heavier_axis_alone_is_still_adopted(self, var):
        """f32 on one axis outweighs the f16 default on the other, so it must be budgeted."""
        assert self._budget({var: "f32"}) == "f32"

    def test_both_axes_quantized_is_adopted(self):
        assert (
            self._budget(
                {
                    "LLAMA_ARG_CACHE_TYPE_K": "q4_0",
                    "LLAMA_ARG_CACHE_TYPE_V": "q4_0",
                }
            )
            == "q4_0"
        )

    def test_an_asymmetric_quantized_pair_takes_the_heavier_axis(self):
        assert (
            self._budget(
                {
                    "LLAMA_ARG_CACHE_TYPE_K": "q4_0",
                    "LLAMA_ARG_CACHE_TYPE_V": "q8_0",
                }
            )
            == "q8_0"
        )

    def test_nothing_set_is_still_none(self):
        assert self._budget({}) is None
        assert self._budget({"LLAMA_ARG_CACHE_TYPE_K": "f16"}) is None

    def test_the_under_reservation_it_prevents(self):
        """When key_length > value_length, the swap puts the cheap type on the larger tensor."""
        from core.inference.llama_cpp import _effective_main_cache_types

        env = {"LLAMA_ARG_CACHE_TYPE_V": "q4_0"}
        assert _effective_main_cache_types(None, env) == ("f16", "q4_0")
        assert self._budget(env) is None