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.

Studio: pin GGUF to CPU on virtualised Metal, clamp parallel slots under MTP (#7717)

Daniel Han29b9cbb984b7
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index ac45d6b8ca1..5cbb5398e44 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -37,6 +37,7 @@ from typing import (
Literal,
Mapping,
MutableMapping,
+ NamedTuple,
Optional,
Union,
)
@@ -157,6 +158,10 @@ class GgufLoadIntent:
n_threads: Optional[int] = None
n_parallel: int = 1
extra_args: Optional[tuple[str, ...]] = None
+ # The route materialises inherited extras from the live server, so the list alone
+ # cannot say whether the caller named it. Duplicate-load checks need the difference:
+ # a launch-time rewrite makes the launched and requested lists diverge.
+ extra_args_inherited: bool = False
preserve_multi_gpu_on_layer: bool = False
compare_mtp_draft: bool = False
@@ -177,6 +182,25 @@ LLAMA_SERVER_NOT_FOUND_DETAIL = (
)
# Shared by the pre-teardown and post-metadata rejections (#7205).
+# Every env var that can put a drafter or spec type into the child. Pre-b8955
+# spellings included: the new names arrived 2026-04-28 and the launchable floor is
+# 2025-08-30, so a build in that window reads the old ones and would keep the drafter.
+_SPEC_ENV_VARS = (
+ "LLAMA_ARG_SPEC_DRAFT_MODEL",
+ "LLAMA_ARG_SPEC_DRAFT_HF_REPO",
+ "LLAMA_ARG_SPEC_TYPE",
+ "LLAMA_ARG_MODEL_DRAFT",
+ "LLAMA_ARG_HFD_REPO",
+)
+
+_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR = (
+ "This Mac's Metal device is virtualised, where offloaded layers can return "
+ "corrupt output, and the installed unsloth_zoo diffusion shim has no --ngl, "
+ "so the zero-layer CPU pin cannot be applied and the runner would use Metal "
+ "anyway. Run 'unsloth studio update' to get a shim with --ngl, or set "
+ "UNSLOTH_ALLOW_PARAVIRTUAL_METAL=1 to keep the GPU on a VM you have verified."
+)
+
_VULKAN_DIFFUSION_GPU_IDS_ERROR = (
"GPU selection (gpu_ids) is not supported for a DiffusionGemma "
"GGUF on a Vulkan llama.cpp build: the diffusion runner selects "
@@ -2017,10 +2041,10 @@ def _flash_attn_enabled_from_args(
def _effective_spec_type(
extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
) -> Optional[str]:
- """The --spec-type llama-server will use: the last CLI --spec-type (or
- --spec-default, which resolves non-MTP), else LLAMA_ARG_SPEC_TYPE. A CLI flag
- overrides the env (matching llama.cpp), so a stale MTP env can't make the
- budget reserve a drafter the launch won't load. None if neither sets it."""
+ """The last --spec-type label a launch carries: final CLI --spec-type (or
+ --spec-default, which resolves non-MTP), else LLAMA_ARG_SPEC_TYPE. A display and
+ comparison label only, NOT what llama.cpp enables: types accumulate there, so ask
+ _extra_args_requests_mtp whether MTP is on. None if neither sets it."""
args = [str(a) for a in extra_args] if extra_args else []
cli_present = False
cli_value: Optional[str] = None
@@ -2040,27 +2064,325 @@ def _effective_spec_type(
return (os.environ if env is None else env).get("LLAMA_ARG_SPEC_TYPE")
+def _child_spec_env(
+ extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
+) -> Mapping[str, str]:
+ """The spec env the child will actually see: empty unless extras name a
+ --spec-type, because the launch scrubs LLAMA_ARG_SPEC_* whenever Unsloth owns the
+ spec block. Predict from this, not os.environ, or you describe a server that is
+ not the one being started."""
+ if not _extra_args_set_spec_type(extra_args):
+ return {}
+ return os.environ if env is None else env
+
+
+def _accumulated_spec_types(
+ extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
+) -> set:
+ """Every speculative type a launch carries, lowercased. Types accumulate rather
+ than replace: llama.cpp applies the env first through the same handler and every
+ --spec-type inserts at the end, so a later flag cannot clear an earlier one (even
+ --spec-type none only appends NONE). Look at all of them, not just the last."""
+ values = []
+ args = [str(a) for a in extra_args] if extra_args else []
+ for i, raw in enumerate(args):
+ _, eq, inline = raw.partition("=")
+ if _flag_name(raw) == "--spec-type":
+ values.append(inline if eq else (args[i + 1] if i + 1 < len(args) else ""))
+ env_value = (os.environ if env is None else env).get("LLAMA_ARG_SPEC_TYPE")
+ if env_value:
+ values.append(env_value)
+ return {p.strip().lower() for v in values for p in v.split(",") if p.strip()}
+
+
def _extra_args_requests_mtp(
extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
) -> bool:
- """True if the effective --spec-type selects MTP (mtp/draft-mtp), so the
- budget must reserve for it."""
- value = _effective_spec_type(extra_args, env)
- if not value:
+ """True if MTP lands in llama.cpp's spec-type vector, so the budget must reserve
+ for it and the slots must clamp. Per _accumulated_spec_types, ANY source counts."""
+ return bool(_accumulated_spec_types(extra_args, env) & {"mtp", "draft-mtp"})
+
+
[email protected]_cache(maxsize = 1)
+def _metal_device_is_paravirtual() -> bool:
+ """True when Metal is a virtualised Apple GPU, whose offload can corrupt output.
+
+ Seen on our own macos-14/15 runners: offload returned an ordered walk through the
+ character set while gpu_layers=0 on the same model, quant and binary was coherent,
+ and MLX stayed correct. It does not reproduce on every build or quant (gemma-3-270m
+ Q4_K_M on b9000 and b10090 was byte identical at gpu_layers 0 and 99), so
+ UNSLOTH_ALLOW_PARAVIRTUAL_METAL=1 keeps the GPU on a VM known good. Physical Apple
+ Silicon never matches.
+
+ Three probes, cheapest first. MLX names the device outright (~40 ms) but is not on
+ every Mac. hw.model then answers the headless case that matters most: measured on
+ macos-14/15, SPDisplaysDataType returns zero bytes on a VM with no display so it
+ cannot see a cloud or CI Mac at all, while hw.model still reports VirtualMac2,1 or
+ VMM-x86_64 against Mac<n>,<n> on real hardware. SPDisplaysDataType stays last for
+ desktop VMs, which do have a display and do name the paravirtual chipset.
+ """
+ if sys.platform != "darwin":
return False
- return any(p.strip().lower() in ("mtp", "draft-mtp") for p in value.split(","))
+ if os.environ.get("UNSLOTH_ALLOW_PARAVIRTUAL_METAL", "").strip().lower() in (
+ "1",
+ "true",
+ "yes",
+ ):
+ logger.info("UNSLOTH_ALLOW_PARAVIRTUAL_METAL set: keeping Metal offload.")
+ return False
+ name = ""
+ try:
+ import mlx.core as mx
+ name = str(mx.device_info().get("device_name") or "")
+ except Exception:
+ name = ""
+ if "paravirtual" not in name.lower():
+ for _probe_cmd, _match in (
+ # VMM-x86_64 is the Intel-guest identifier and contains neither
+ # "virtual" nor "paravirtual"; upstream ships Metal on macOS x64 too.
+ (["sysctl", "-n", "hw.model"], ("virtual", "vmm-")),
+ (["system_profiler", "SPDisplaysDataType"], ("paravirtual",)),
+ ):
+ try:
+ probe = subprocess.run(
+ _probe_cmd,
+ capture_output = True,
+ text = True,
+ timeout = 30,
+ encoding = "utf-8",
+ errors = "replace",
+ )
+ except Exception:
+ continue
+ _out = (probe.stdout or "").lower()
+ if any(m in _out for m in _match):
+ name = f"{name} {probe.stdout}".strip()
+ break
+ _low = name.lower()
+ if "paravirtual" in _low or "virtual" in _low or "vmm-" in _low:
+ logger.warning(
+ "Metal device looks virtualised (%s). Offload can return corrupt output on "
+ "paravirtual Apple GPUs, so GGUF inference will run on CPU. MLX is "
+ "unaffected. Set UNSLOTH_ALLOW_PARAVIRTUAL_METAL=1 to keep the GPU.",
+ name.strip()[:120] or "unknown",
+ )
+ return True
+ return False
+
+
+def _paravirtual_probe_answered(server_caps: Mapping[str, object]) -> bool:
+ """False when the --help probe failed, so every capability read as absent.
+
+ Both companion flags predate the oldest build Studio can launch (--no-mmproj-offload
+ is b5178, --gpu-layers-draft is from 2023, and the base argv already requires b6325),
+ so "capability missing" means the probe did not answer, not that the build lacks it:
+ one malformed inherited LLAMA_ARG_* makes llama-server --help exit non-zero and the
+ all-false result is cached for the process. Dropping the projector or the drafter on
+ that would be a self-inflicted outage, so drops require a conclusive probe and the
+ pins cover the unanswered case.
+ """
+ return not server_caps.get("mtp_probe_inconclusive")
+
+
+def _paravirtual_draft_ngl_flag(server_caps: Mapping[str, object]) -> Optional[str]:
+ """The draft-layer flag to pin with, or None only when the build truly lacks one."""
+ flag = server_caps.get("spec_draft_ngl_flag")
+ if flag:
+ return str(flag)
+ # Unanswered probe: use the spelling every launchable build has had since 2023
+ # rather than treating the drafter as unpinnable.
+ if not _paravirtual_probe_answered(server_caps):
+ return "--gpu-layers-draft"
+ return None
+
+
+def _paravirtual_mmproj_pinnable(server_caps: Mapping[str, object]) -> bool:
+ """True when --no-mmproj-offload can be emitted, including on an unanswered probe."""
+ return bool(
+ server_caps.get("supports_no_mmproj_offload")
+ or not _paravirtual_probe_answered(server_caps)
+ )
+
+
+_OVERRIDE_TENSOR_FLAGS: frozenset = frozenset(
+ {
+ "-ot",
+ "--override-tensor",
+ "-otd",
+ "--override-tensor-draft",
+ "--spec-draft-override-tensor",
+ }
+)
+
+
+def _paravirtual_strip_gpu_overrides(
+ extra_args: Optional[Iterable[str]], *, log_dropped: bool = True
+) -> Optional[List[str]]:
+ """Drop --override-tensor entries that place weights back on the corrupt device.
+
+ ``-ot`` is the one placement flag ``--gpu-layers 0`` cannot answer: llama.cpp applies
+ the override while selecting each weight's buffer type, before any layer is assigned
+ to a device, so ``-ot ".*=Metal"`` puts weights on the virtualised GPU whatever the
+ layer count says. It also accumulates rather than replaces, so a later flag cannot
+ neutralise it; the entry has to go. ``-otd`` does the same for the drafter and would
+ defeat the draft-layer pin.
+
+ Only non-CPU targets are dropped: ``-ot exps=CPU`` moves weights the same way this
+ fallback does, so stripping it would slow the very load it rescues.
+
+ ``log_dropped=False`` for the duplicate-load comparators, which only inspect a
+ request and must not narrate a drop no launch is performing, on every /load.
+ """
+ if not extra_args:
+ return extra_args if extra_args is None else list(extra_args)
+ args = [str(a) for a in extra_args]
+ out: List[str] = []
+ i = 0
+ while i < len(args):
+ tok = args[i]
+ # _flag_name mirrors llama.cpp's underscore folding (arg.cpp does
+ # std::replace(_ -> -) before matching), so --override_tensor is the same flag.
+ base, _, inline = tok.partition("=")
+ if _flag_name(base) in _OVERRIDE_TENSOR_FLAGS:
+ value = inline if inline else (args[i + 1] if i + 1 < len(args) else "")
+ targets = [
+ part.rsplit("=", 1)[-1].strip().lower() for part in value.split(",") if "=" in part
+ ]
+ if targets and all(t == "cpu" for t in targets):
+ out.append(tok)
+ if not inline and i + 1 < len(args):
+ out.append(args[i + 1])
+ elif log_dropped:
+ logger.warning(
+ "Dropping %s %s: this Mac's Metal device is virtualised, so an "
+ "override that keeps weights on it would return corrupt output.",
+ base,
+ value,
+ )
+ i += 1 if inline else 2
+ continue
+ out.append(tok)
+ i += 1
+ return out
+
+
+class ParavirtualPlacement(NamedTuple):
+ """A load request's GPU placement after the virtualised-Metal CPU pin."""
+
+ gpu_memory_mode: Literal["auto", "manual"]
+ gpu_layers: int
+ tensor_parallel: bool
+ tensor_split: Optional[List[float]]
+ n_cpu_moe: int
+ extra_args: Optional[List[str]]
+
+
+def paravirtual_normalized_request(
+ *,
+ gpu_memory_mode: Literal["auto", "manual"] = "auto",
+ gpu_layers: int = -1,
+ tensor_parallel: bool = False,
+ tensor_split: Optional[List[float]] = None,
+ n_cpu_moe: int = 0,
+ extra_args: Optional[Iterable[str]] = None,
+ log_dropped: bool = True,
+) -> ParavirtualPlacement:
+ """Map a requested placement to the one a virtualised Metal device launches.
+
+ Single source of truth for the CPU pin, shared by the launch (load_model) and by
+ BOTH duplicate-load comparators (``_already_in_target_state`` and the route's
+ ``_request_matches_loaded_settings``). The launch records what it normalized, so a
+ comparator judging the RAW request would mismatch its own state and tear down a
+ healthy CPU server on every repeat Apply -- and, with an unbounded reload loop, 409
+ or cancel a live generation.
+
+ Pure, unconditional (callers gate on ``_metal_device_is_paravirtual()``) and
+ idempotent, so re-applying it to a normalized request is a no-op.
+
+ Deliberately NOT keyed on the request already being manual/0: that places the main
+ model on CPU, but the extras are the caller's, and ``-ot ".*=Metal"`` is applied
+ while each weight's buffer type is chosen, before any layer is assigned, so it puts
+ weights back on the corrupt device -- and the route strips only the ``-ngl`` family.
+
+ ``log_dropped=False`` for the comparators, which only inspect a request and must not
+ narrate a rewrite no launch is performing.
+ """
+ normalized = extra_args if extra_args is None else list(extra_args)
+ if normalized:
+ # Extras are appended AFTER the managed --gpu-layers 0 and llama.cpp is
+ # last-wins, so an `-ngl 99` would re-enable the corrupt offload. The route
+ # strips these only in manual mode, so an Auto request still carries them.
+ normalized = strip_shadowing_flags(
+ normalized,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = False,
+ strip_template = False,
+ strip_split_mode = False,
+ strip_offload = True,
+ )
+ # strip_offload covers only the layer-count family; an --override-tensor aimed
+ # at Metal survives it and places weights before any layer assignment.
+ normalized = _paravirtual_strip_gpu_overrides(normalized, log_dropped = log_dropped)
+ return ParavirtualPlacement(
+ gpu_memory_mode = "manual",
+ gpu_layers = 0,
+ # Nothing is left on the GPU to split, and the launch drops these anyway;
+ # normalize here too so the recorded state and the next request agree.
+ tensor_parallel = False,
+ tensor_split = None,
+ n_cpu_moe = 0,
+ extra_args = normalized,
+ )
+
+
+def _paravirtual_split_mode_pin(extra_args: Optional[Iterable[str]]) -> List[str]:
+ """Flags that neutralise a pass-through ``--split-mode`` on a virtualised Mac.
+
+ A user ``--split-mode`` is deliberately allowed (the Tensor Parallelism toggle
+ cannot express row/none), but the paravirtual fallback has already pinned this load
+ to CPU, and the flag is NOT inert at ``--gpu-layers 0``: llama.cpp builds a
+ buffer-type list for every device in ``model->devices`` before any layer is
+ assigned, and n_gpu_layers never reaches that step. So ``-sm row`` throws "device
+ <X> does not support split buffers" on every backend except SYCL
+ (``make_gpu_buft_list``, llama-model.cpp, since ggml-org/llama.cpp#24216 removed
+ CUDA's split buffers), and ``-sm tensor`` throws "LLAMA_SPLIT_MODE_TENSOR not
+ implemented for architecture" for every arch ``llm_arch_supports_sm_tensor``
+ excludes. Either turns the CPU rescue into a server that refuses to start, and the
+ zero-offload mask cannot save it: it writes only CUDA/HIP visibility vars, so the
+ Metal device stays in the list on the one platform this fallback fires on.
+
+ Overridden rather than stripped: llama.cpp is last-wins, so ``layer`` (the default,
+ and a provable no-op at ``--gpu-layers 0`` -- llama-model.cpp computes the split
+ points but never indexes them once ``act_gpu_layers`` is 0) neutralises the mode
+ without rewriting ``extra_args``. The route's duplicate-load comparator compares
+ stored extras verbatim and the UI does not round-trip the extras box, so stripping
+ would leave the two permanently unequal and turn every later Apply into a real model
+ swap. ``--tensor-split`` needs neither treatment for the same never-indexed reason.
+
+ Returns [] when extras set no mode or already set ``layer``.
+ """
+ mode = (parse_split_mode_override(extra_args) or "").strip().lower()
+ if not mode or mode == "layer":
+ return []
+ logger.warning(
+ "Overriding --split-mode %s with the default layer split: this Mac's "
+ "Metal device is virtualised, so the model runs on CPU and a GPU split "
+ "mode would only fail the load.",
+ mode,
+ )
+ return ["--split-mode", "layer"]
def _extra_args_requests_separate_draft(
extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
) -> bool:
- """True if the effective --spec-type selects a non-MTP model draft mode
- (draft-simple/draft-eagle3), which loads a separate draft model the budget
- must reserve (draft-mtp -> _extra_args_requests_mtp; ngram-* load no model)."""
- value = _effective_spec_type(extra_args, env)
- if not value:
- return False
- return any(p.strip().lower() in ("draft-simple", "draft-eagle3") for p in value.split(","))
+ """True if a non-MTP model draft mode (draft-simple/draft-eagle3) is selected, which
+ loads a separate draft model the budget must reserve (draft-mtp ->
+ _extra_args_requests_mtp; ngram-* load no model). Accumulating for the same reason as
+ _extra_args_requests_mtp: a later --spec-default or --spec-type cannot clear an
+ inherited draft-simple, so reading only the last under-reserves the model it loads."""
+ return bool(_accumulated_spec_types(extra_args, env) & {"draft-simple", "draft-eagle3"})
def _extra_args_spec_draft_n_max(extra_args: Optional[Iterable[str]]) -> Optional[int]:
@@ -2111,7 +2433,15 @@ def _extra_args_mtp_draft_path(
if found is not None:
return found
e = os.environ if env is None else env
- return e.get("LLAMA_ARG_SPEC_DRAFT_MODEL") or e.get("LLAMA_ARG_SPEC_DRAFT_HF_REPO") or None
+ return (
+ e.get("LLAMA_ARG_SPEC_DRAFT_MODEL")
+ or e.get("LLAMA_ARG_SPEC_DRAFT_HF_REPO")
+ # Pre-b8955 spellings, live between the launchable floor (2025-08-30) and the
+ # rename (2026-04-28).
+ or e.get("LLAMA_ARG_MODEL_DRAFT")
+ or e.get("LLAMA_ARG_HFD_REPO")
+ or None
+ )
def _extra_args_draft_cache_types(
@@ -2500,6 +2830,11 @@ class LlamaCppBackend:
# Separate MTP drafter launched with the current model; reload-dedup
# key so a drafter that appears next to the weights forces a reload.
self._mtp_draft_path: Optional[str] = None
+ # Drafter this load resolved then deliberately suppressed (virtualised Metal
+ # with no draft-layer flag). The dedup keys on the drafter the caller asked
+ # for, still on disk, so without this the detected path never matches the
+ # launched None and every repeat Apply tears down a healthy server.
+ self._mtp_draft_suppressed_path: Optional[str] = None
# Why MTP was disabled on the last load that asked for it (auto on an
# MTP model, or forced mtp / mtp+ngram), else None. Drives the "update
# llama.cpp" hint in the UI. "binary_no_mtp" / "binary_outdated" ->
@@ -2615,6 +2950,10 @@ class LlamaCppBackend:
# ``_extra_args_source`` records the (model_identifier, hf_variant) the
# stored args came from so the route can refuse cross-model inheritance.
self._extra_args: Optional[List[str]] = None
+ # Extras as REQUESTED, before a launch-time rewrite (the virtualised-Metal
+ # drafter drop strips the spec group), so the duplicate-load comparators can
+ # compare requested-vs-requested like _requested_n_ctx does.
+ self._requested_extra_args: Optional[List[str]] = None
self._extra_args_source: Optional[tuple[str, Optional[str]]] = None
self._requested_n_ctx: int = 0
# Last healthy caller intent for crash recovery. Memory-only and never logged.
@@ -2723,6 +3062,13 @@ class LlamaCppBackend:
def mtp_draft_path(self) -> Optional[str]:
return self._mtp_draft_path
+ @property
+ def mtp_draft_suppressed_path(self) -> Optional[str]:
+ """Drafter the last load resolved and then dropped on purpose, else None.
+ Duplicate-load checks accept it alongside mtp_draft_path so a drafter still on
+ disk does not read as a settings change."""
+ return self._mtp_draft_suppressed_path
+
@property
def spec_fallback_reason(self) -> Optional[str]:
"""Why MTP was disabled on the last MTP-requesting load, else None."""
@@ -2735,6 +3081,19 @@ class LlamaCppBackend:
inheritance."""
return list(self._extra_args) if self._extra_args is not None else None
+ @property
+ def requested_extra_args(self) -> Optional[List[str]]:
+ """Extras the last load was INVOKED with (a copy), before any launch-time
+ rewrite; falls back to the launched list when nothing was rewritten. Keeps a
+ rewrite the caller cannot see (the virtualised-Metal drafter drop) from reading
+ as a settings change in the duplicate-load comparators."""
+ stored = (
+ self._requested_extra_args
+ if self._requested_extra_args is not None
+ else self._extra_args
+ )
+ return list(stored) if stored is not None else None
+
@property
def requested_n_ctx(self) -> int:
"""n_ctx the last load was invoked with (not the effective cap).
@@ -3077,7 +3436,9 @@ class LlamaCppBackend:
"""
if self._is_diffusion:
requested = [sorted(int(x) for x in gpu_ids)[0]] if gpu_ids else None
- return requested == (self._gpu_ids or None)
+ # Raw pick accepted too: a forced-CPU runner records no effective pin, so
+ # without it re-sending the same selection would reload every time.
+ return requested in ((self._gpu_ids or None), (self._requested_gpu_ids or None))
requested = sorted(int(x) for x in gpu_ids) if gpu_ids else None
raw = self._requested_gpu_ids or None
@@ -3126,7 +3487,20 @@ class LlamaCppBackend:
return False
extra_args = list(effective_extra_args) if effective_extra_args is not None else None
- if not _tensor_parallel_matches_loaded(
+ # A request omitting the extras field inherits the LAUNCHED list; anything else is
+ # the caller's own. A launch-time rewrite (drafter drop, MTP crash replay) makes
+ # the two differ, and the equality below wants what the load was INVOKED with.
+ # Judged on the flag, not on value equality: a caller that deliberately sends the
+ # stripped list is clearing the failed drafter and must not read as inheriting it.
+ _invoked_extras = self.requested_extra_args if intent.extra_args_inherited else extra_args
+ # A virtualised Metal device never launches a tensor split (CPU-pinned, and
+ # --split-mode is overridden with the default layer split), so judge the
+ # normalized request there: an extras `-sm tensor`, which the pin deliberately
+ # leaves in place, would otherwise never match.
+ if _metal_device_is_paravirtual():
+ if self._tensor_parallel:
+ return False
+ elif not _tensor_parallel_matches_loaded(
extra_args, intent.tensor_parallel, self._tensor_parallel
):
return False
@@ -3203,7 +3577,7 @@ class LlamaCppBackend:
if (self._chat_template_override or None) != (intent.chat_template_override or None):
return False
- if tuple(extra_args or ()) != tuple(self._extra_args or ()):
+ if tuple(_invoked_extras or ()) != tuple(self.requested_extra_args or ()):
return False
if (intent.gguf_path is not None or intent.compare_mtp_draft) and speculative_type in (
"auto",
@@ -3214,9 +3588,11 @@ class LlamaCppBackend:
requested_draft = (
Path(intent.mtp_draft_path).resolve() if intent.mtp_draft_path else None
)
- loaded_draft = (
- Path(self._mtp_draft_path).resolve() if self._mtp_draft_path else None
- )
+ # A drafter the last load dropped on purpose counts as launched here:
+ # the file is still there, so comparing it against the stored None
+ # would reload the same drafter-free server forever.
+ _loaded = self._mtp_draft_path or self._mtp_draft_suppressed_path
+ loaded_draft = Path(_loaded).resolve() if _loaded else None
except OSError:
return False
if requested_draft != loaded_draft:
@@ -3478,6 +3854,8 @@ class LlamaCppBackend:
"supports_no_cache_prompt": False,
"supports_metrics": False,
"supports_slot_save": False,
+ "supports_no_mmproj_offload": False,
+ "spec_draft_ngl_flag": None,
}
try:
mtime = int(Path(bin_path).stat().st_mtime)
@@ -3499,6 +3877,8 @@ class LlamaCppBackend:
supports_no_cache_prompt = False
supports_metrics = False
supports_slot_save = False
+ supports_no_mmproj_offload = False
+ spec_draft_ngl_flag = None
saw_spec_type = False
probe_ok = False
help_text = ""
@@ -3605,6 +3985,15 @@ class LlamaCppBackend:
supports_no_cache_prompt = _is_real("--no-cache-prompt")
supports_metrics = _is_real("--metrics")
supports_slot_save = _is_real("--slot-save-path")
+ supports_no_mmproj_offload = _is_real("--no-mmproj-offload")
+ # Record WHICH alias this build has: --spec-draft-ngl only landed in
+ # b8955, and a build exposing only --gpu-layers-draft would refuse to
+ # start on the newer name. Long forms only, since the block parser above
+ # skips short aliases, so "-ngld" could never have matched.
+ for _alias in ("--spec-draft-ngl", "--gpu-layers-draft", "--n-gpu-layers-draft"):
+ if _is_real(_alias):
+ spec_draft_ngl_flag = _alias
+ break
except (OSError, subprocess.SubprocessError) as exc:
logger.debug(f"llama-server --help probe failed: {exc}")
saw_spec_type = False
@@ -3641,6 +4030,8 @@ class LlamaCppBackend:
"supports_no_cache_prompt": supports_no_cache_prompt,
"supports_metrics": supports_metrics,
"supports_slot_save": supports_slot_save,
+ "supports_no_mmproj_offload": supports_no_mmproj_offload,
+ "spec_draft_ngl_flag": spec_draft_ngl_flag,
}
cls._capability_cache[cache_key] = info
return info
@@ -6115,6 +6506,12 @@ class LlamaCppBackend:
# (#7574). An older shim has no --ngl, so drop it rather than die in argparse.
manual_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers)
if manual_ngl is not None and not _shim_supports_ngl(shim_cmd):
+ # Dropping a zero-layer split on virtualised Metal undoes the CPU pin:
+ # cpu_only below is torch.cuda only, so it reads 0 on a Mac and the empty
+ # --gpu token still lets the runner use Metal. Only the split keeps weights
+ # off it, so refuse rather than serve possibly corrupt output.
+ if manual_ngl == 0 and _metal_device_is_paravirtual():
+ raise ValueError(_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR)
logger.warning(
"DiffusionGemma: ignoring the %d GPU-layer split; the installed "
"unsloth_zoo shim has no --ngl. Upgrade unsloth_zoo to set the split.",
@@ -6253,11 +6650,15 @@ class LlamaCppBackend:
# The single-device runner records only the lowest selected GPU (chosen
# above), not the whole pick, and clears any explicit pin from a prior
# chat load; a multi-GPU list would misreport placement and mis-dedup.
- self._gpu_ids = [sorted(gpu_ids)[0]] if gpu_ids else None
+ # A zero-layer split on virtualised Metal masks the child's devices outright, so
+ # it pins nothing: record no effective pin, or /status names a device the runner
+ # never used and clearing that pick reloads the same CPU runner.
+ _pv_diffusion_cpu = manual_ngl == 0 and _metal_device_is_paravirtual()
+ self._gpu_ids = [sorted(gpu_ids)[0]] if gpu_ids and not _pv_diffusion_cpu else None
# The frontend prefers requested_gpu_ids when hydrating the picker.
# Diffusion uses only one device, so echo the collapsed effective pin,
# not unused members of the original request.
- self._requested_gpu_ids = list(self._gpu_ids) if self._gpu_ids else None
+ self._requested_gpu_ids = [sorted(gpu_ids)[0]] if gpu_ids else None
if hf_variant:
self._hf_variant = hf_variant
elif gguf_path:
@@ -6278,6 +6679,9 @@ class LlamaCppBackend:
self._gpu_offload_active = not holds_no_gpu
if extra_args is not None:
self._extra_args = list(extra_args)
+ # No spec block to drop here, so launched IS requested; rebind so a
+ # prior GGUF load's record cannot outlive it.
+ self._requested_extra_args = list(extra_args)
self._extra_args_source = (model_identifier, hf_variant)
# The visual server logs "MAXTOK=<N>" with the context budget it actually resolved
# (auto-sized to VRAM). Read it back so the UI context bar shows the real budget.
@@ -7479,6 +7883,71 @@ class LlamaCppBackend:
# so any in-flight load has drained) instead of using a half-swapped one.
if getattr(self, "_llama_update_in_progress", False):
raise RuntimeError("llama.cpp is updating; try again in a moment.")
+
+ # A virtualised Apple GPU corrupts every offloaded layer, so pin GGUF
+ # inference to CPU there; physical Apple Silicon is untouched. Settled
+ # ABOVE the duplicate-load check (and the KV estimates) so the compared
+ # placement is the one that launches: the launch records the normalized
+ # values, so comparing the raw request would miss the fast path and tear
+ # down a healthy CPU server on every repeat Auto /load.
+ # Keyed on the hardware, not the request, and applied whole rather than
+ # only when the request asks for offload: Manual + 0 layers already places
+ # the main model on CPU, but the companions below (mmproj, a separate
+ # drafter) do not read --gpu-layers, and an `-ot ".*=Metal"` the route never
+ # strips would put weights straight back on the corrupt device.
+ # paravirtual_normalized_request is the one definition of that rewrite,
+ # shared with both duplicate-load comparators.
+ _paravirtual_cpu_forced = _metal_device_is_paravirtual()
+ if _paravirtual_cpu_forced:
+ _pv_placement = paravirtual_normalized_request(
+ gpu_memory_mode = gpu_memory_mode,
+ gpu_layers = gpu_layers,
+ tensor_parallel = tensor_parallel,
+ tensor_split = tensor_split,
+ n_cpu_moe = n_cpu_moe,
+ extra_args = extra_args,
+ )
+ if (gpu_memory_mode, gpu_layers) != (
+ _pv_placement.gpu_memory_mode,
+ _pv_placement.gpu_layers,
+ ):
+ logger.warning(
+ "Forcing gpu_layers=0 for %s: this Mac's Metal device is "
+ "virtualised and offloaded layers produce corrupt output.",
+ model_identifier or gguf_path,
+ )
+ if extra_args and _pv_placement.extra_args != list(extra_args):
+ logger.warning(
+ "Dropping offload flags from extra args on a "
+ "virtualised Metal device: %s -> %s",
+ list(extra_args),
+ _pv_placement.extra_args,
+ )
+ if tensor_parallel or tensor_split:
+ logger.info(
+ "Virtualised Metal device: dropping tensor split/parallel "
+ "flags (nothing to split on the GPU)"
+ )
+ gpu_memory_mode = _pv_placement.gpu_memory_mode
+ gpu_layers = _pv_placement.gpu_layers
+ n_cpu_moe = _pv_placement.n_cpu_moe
+ extra_args = _pv_placement.extra_args
+ # Spelled out (not read off _pv_placement, which returns exactly these)
+ # so tests/test_tp_vision_regression.py's TP-drop allowlist sees this site.
+ tensor_parallel = False
+ tensor_split = None
+ # The intent is what the duplicate-load check compares and what a retry
+ # replays, so carry the rewrite into it rather than the raw request.
+ intent = replace(
+ intent,
+ gpu_memory_mode = gpu_memory_mode,
+ gpu_layers = gpu_layers,
+ n_cpu_moe = n_cpu_moe,
+ extra_args = tuple(extra_args) if extra_args is not None else None,
+ tensor_parallel = False,
+ tensor_split = None,
+ )
+
# Duplicate /load that raced past the route check: do nothing if the
# live server already satisfies this request.
if self.adopt_load_intent_if_matched(intent):
@@ -7532,6 +8001,32 @@ class LlamaCppBackend:
)
n_parallel = 1
+ # MTP is documented as single-slot: the model cards ship "-np 1" and say
+ # "-np > 1 [...] not yet supported with MTP". The MTP state is per sequence,
+ # so what breaks at more slots is the draft: unequal per-slot token counts
+ # make split_equal reorder the ubatch while the nextn hidden states are
+ # still read by raw token index, so slots read each other's rows, acceptance
+ # collapses and MTP ends up slower than no speculation. Clamped beside the
+ # --kv-unified clamp so the KV fit matches.
+ # The env counts: llama.cpp appends spec types rather than replacing them
+ # (--spec-type inserts, --spec-default push_backs, enablement is a find over
+ # the vector), so an inherited LLAMA_ARG_SPEC_TYPE=draft-mtp really does
+ # launch MTP and no later flag can clear it.
+ _pv_extras_clamped_slots = 0
+ if n_parallel > 1 and _extra_args_requests_mtp(
+ extra_args, env = _child_spec_env(extra_args)
+ ):
+ # Kept so the paravirtual drafter drop can hand the slots back if it
+ # strips the very spec group this clamped for.
+ _pv_extras_clamped_slots = n_parallel
+ logger.warning(
+ "MTP speculative decoding (--spec-type draft-mtp) does not support "
+ "%d parallel slots; using 1. Load without MTP to serve chats in "
+ "parallel.",
+ n_parallel,
+ )
+ n_parallel = 1
+
# ── Vulkan-ordinal preflight (BEFORE the Phase 1 kill) ────────
# An explicit Vulkan pin the ggml probe never enumerated cannot be honored.
# Validate it ABOVE the kill so an invalid selection leaves the live model
@@ -7554,8 +8049,13 @@ class LlamaCppBackend:
# Classify before killing the healthy server (#7205); Phase 2 reuses this
# path. Diffusion changes the meaning or validity of requested placement,
# so both the remote and the local branch settle it above the teardown.
+ # A zero-layer diffusion pin this shim cannot apply is refused; probe
+ # once here so the HF case can be settled above the teardown as well.
+ _pv_diffusion_unpinnable = bool(
+ _paravirtual_cpu_forced and not self.diffusion_split_supported()
+ )
_preflight_model_path = None
- if hf_repo and (_vulkan_ordinal_pin or _cpu_only_pin):
+ if hf_repo and (_vulkan_ordinal_pin or _cpu_only_pin or _pv_diffusion_unpinnable):
_resolved_repo = _resolve_repo_id_casing(hf_repo)
if _resolved_repo != hf_repo:
logger.info(
@@ -7576,6 +8076,8 @@ class LlamaCppBackend:
if _preflight_is_diffusion:
if _vulkan_ordinal_pin:
raise ValueError(_VULKAN_DIFFUSION_GPU_IDS_ERROR)
+ if _pv_diffusion_unpinnable:
+ raise ValueError(_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR)
elif _cpu_only_pin:
raise ValueError(
f"Requested gpu_ids {list(gpu_ids)} but the llama.cpp build has "
@@ -7593,6 +8095,16 @@ class LlamaCppBackend:
gguf_path,
model_identifier,
)
+ # Same for the unpinnable diffusion split: _start_diffusion_server enforces
+ # it everywhere, but only after the teardown, so settle the local case here
+ # and leave the running server alone.
+ if (
+ _pv_diffusion_unpinnable
+ and gguf_path
+ and not hf_repo
+ and self._gguf_path_is_diffusion(gguf_path, model_identifier)
+ ):
+ raise ValueError(_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR)
# ── Phase 1: kill old process (under lock, fast) ──────────
with self._lock:
@@ -7677,6 +8189,11 @@ class LlamaCppBackend:
# Not a tensor/layer GGUF: clear any preserved-fallback flag from a
# prior load (this path skips the command builder that clears it).
self._layer_preserves_tensor_intent = False
+ # Same reason: a diffusion server never carries a drafter, only unload
+ # clears these, and the dedupe compares the pair, so a stale one
+ # reloads a healthy diffusion server on every Apply.
+ self._mtp_draft_path = None
+ self._mtp_draft_suppressed_path = None
with self._lock:
if self._cancel_event.is_set():
logger.info("Load cancelled before diffusion server start")
@@ -7895,11 +8412,36 @@ class LlamaCppBackend:
model_path = model_path,
mmproj_path = mmproj_path,
)
+ # A virtualised Metal device corrupts the vision encoder too, and
+ # --no-mmproj-offload is the only way to keep it off there (clip.cpp
+ # never reads --gpu-layers). Without that flag the choice is a projector
+ # on the corrupt device or no projector, so drop it: silently encoding
+ # every image from garbage is the failure this fallback exists to stop.
+ # Only when the probe answered: --no-mmproj-offload is from b5178 and
+ # the base argv already needs b6325, so a build that can start here
+ # always has it, and a false capability means the --help probe failed
+ # (see _paravirtual_probe_answered). Dropping vision on that would be a
+ # self-inflicted outage; the pin below covers the unanswered case.
+ _pv_mmproj_unpinnable = bool(
+ launch_mmproj_path
+ and _paravirtual_cpu_forced
+ and _paravirtual_probe_answered(server_caps)
+ and not server_caps.get("supports_no_mmproj_offload")
+ )
+ if _pv_mmproj_unpinnable:
+ logger.warning(
+ "Disabling image/audio input for this session: this Mac's "
+ "Metal device is virtualised and this llama-server build has "
+ "no --no-mmproj-offload, so the vision projector would keep "
+ "running on the device whose output is corrupt. Run 'unsloth "
+ "studio update' to install a build that supports it."
+ )
+ launch_mmproj_path = None
# Need both a resolved mmproj AND the config vision flag; a stray
# mmproj passing the family-name heuristic must not flip a non-VLM
# GGUF into vision mode.
effective_is_vision = bool(launch_mmproj_path) and bool(is_vision)
- if is_vision and not effective_is_vision:
+ if is_vision and not effective_is_vision and not _pv_mmproj_unpinnable:
logger.warning(
"Vision-capable GGUF loaded without a usable mmproj; "
"image input will be disabled for this session"
@@ -8053,16 +8595,10 @@ class LlamaCppBackend:
and _mtp_size_for_fit < _MTP_MIN_SIZE_B
and not bool(mtp_draft_path)
)
- # LLAMA_ARG_SPEC_TYPE only reaches the child when neither extras
- # nor Unsloth emit a spec flag (mode "off", no user --spec-type),
- # since _build_speculative_flags emits one for every other mode.
- # Consult the env for the reserve only then, else a stale MTP env
- # would over-reserve.
- _spec_env: Mapping[str, str] = (
- os.environ
- if (not _extra_args_set_spec_type(extra_args) and _mtp_canonical == "off")
- else {}
- )
+ # The inherited spec env reaches the child only when the extras own
+ # --spec-type; the launch scrubs it otherwise. Reserve against the
+ # env in that case only, where flags and env accumulate and launch.
+ _spec_env: Mapping[str, str] = _child_spec_env(extra_args)
# Extras can run MTP even when Unsloth suppresses its own emission.
_user_mtp_via_extras = _extra_args_requests_mtp(extra_args, env = _spec_env)
# A non-MTP model-based draft mode (draft-simple/draft-eagle3) in
@@ -8145,7 +8681,9 @@ class LlamaCppBackend:
)
else None
)
- _env_draft_for_budget = _extra_args_mtp_draft_path([], env = os.environ)
+ # Same scrubbed view: reserving for an inherited drafter the child
+ # never loads shrinks the context or rejects a placement that fits.
+ _env_draft_for_budget = _extra_args_mtp_draft_path([], env = _spec_env)
_mtp_draft_for_budget = (
_cli_draft_for_budget or _studio_draft_for_budget or _env_draft_for_budget
)
@@ -8890,7 +9428,12 @@ class LlamaCppBackend:
# Status reports the explicit subset the launch actually uses,
# while reload dedupe compares requested_gpu_ids so repeating a
# wider request that fit narrowed does not restart the server.
- if gpu_ids:
+ # A forced-CPU launch carries --device none, so it pins no GPU at all:
+ # echoing the request as effective would report devices the runtime never
+ # touched, and clearing an ineffective pick would then reload a CPU server
+ # that is already in the target state. requested_gpu_ids still holds the
+ # pick, so repeating it keeps matching.
+ if gpu_ids and not _paravirtual_cpu_forced:
effective_pin = gpu_indices if gpu_indices is not None else gpu_ids
self._gpu_ids = sorted(int(idx) for idx in effective_pin)
else:
@@ -9159,6 +9702,85 @@ class LlamaCppBackend:
launch_mtp_draft_path = self._resolve_launch_mtp_path(
mtp_draft_path = mtp_draft_path,
)
+ _pv_suppressed_draft_path: Optional[str] = None
+ _pv_suppressed_spec_extra_args: Optional[List[str]] = None
+ # Same shape as the projector drop above: the CPU pin below needs a
+ # draft-layer flag from the probe, and without one the drafter keeps its
+ # automatic placement on the virtualised device. Unlike the projector
+ # this is throughput, not correctness -- a token is emitted only when the
+ # CPU-side target samples it itself (common_sampler_sample_and_accept_n
+ # pushes the target's own draw and stops at the first mismatch), so a
+ # corrupt drafter can only get its proposals rejected, costing a forward
+ # pass per step for nothing. So drop it, from both sources: Unsloth's
+ # resolved drafter and a user/env one in the extras. The rest of the spec
+ # group goes with it, since a --spec-type needing a draft model
+ # (draft-simple, eagle3) aborts llama-server once the model is gone;
+ # _build_speculative_flags re-derives the drafter-free modes below. A
+ # user who already pinned the drafter (-ngld 0 / --spec-draft-device cpu)
+ # keeps it; the probe only decides whether Unsloth can emit the flag.
+ # And as with the projector, --gpu-layers-draft has existed since 2023,
+ # so a missing flag means the probe failed: on an unanswered probe pin
+ # with the legacy spelling rather than drop.
+ # Keyed on the drafter the launch really loads, not one that merely
+ # exists: a user-owned --spec-type returns early from
+ # _build_speculative_flags, so Unsloth's resolved sibling never becomes
+ # --model-draft and keying on it would strip a drafter-free mode
+ # (--spec-type ngram-mod and its knobs) for a drafter that never
+ # launches. The inherited env counts only where it survives to the child
+ # (the launch scrubs LLAMA_ARG_SPEC_DRAFT_* unless the extras own
+ # --spec-type), or os.environ would drop a drafter that never loads and
+ # take the caller's spec tuning with it.
+ _pv_draft_unpinnable = bool(
+ _paravirtual_cpu_forced
+ and not _paravirtual_draft_ngl_flag(server_caps)
+ and (
+ _extra_args_mtp_draft_path(extra_args, env = _child_spec_env(extra_args))
+ or (launch_mtp_draft_path and not _extra_args_set_spec_type(extra_args))
+ )
+ and not _extra_args_draft_offloaded_to_cpu(extra_args)
+ )
+ if _pv_draft_unpinnable:
+ logger.warning(
+ "Dropping the speculative drafter for this session: this "
+ "Mac's Metal device is virtualised and this llama-server "
+ "build advertises no draft-layer flag, so the drafter would "
+ "keep running on the device whose output is corrupt. Output "
+ "stays correct either way; this only costs speed. Run "
+ "'unsloth studio update' to install a build that supports it."
+ )
+ # Remember what was suppressed: the drafter stays on disk, so caller
+ # and route keep detecting it, and comparing that against the
+ # launched None would reload a healthy server on every repeat Apply.
+ _pv_suppressed_draft_path = launch_mtp_draft_path
+ launch_mtp_draft_path = None
+ if extra_args:
+ # Same reason: record the extras as REQUESTED next to the
+ # launched ones. Both comparators key on the caller's list,
+ # which keeps arriving unchanged, so comparing it against this
+ # rewrite would reload a healthy server on every repeat Apply.
+ _pv_suppressed_spec_extra_args = list(extra_args)
+ extra_args = strip_shadowing_flags(
+ extra_args,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = True,
+ strip_template = False,
+ strip_split_mode = False,
+ )
+ # The slots were clamped for an MTP that just went away, so give
+ # them back. Restored before the spec flags are rebuilt, so the
+ # backstop below re-clamps if Unsloth's own resolution is MTP.
+ if _pv_extras_clamped_slots > 1 and not _extra_args_requests_mtp(
+ extra_args, env = _child_spec_env(extra_args)
+ ):
+ n_parallel = _pv_extras_clamped_slots
+ if "--parallel" in cmd:
+ cmd[cmd.index("--parallel") + 1] = str(n_parallel)
+ logger.info(
+ "Restoring %d parallel slots: the drafter drop left a "
+ "non-MTP server.",
+ n_parallel,
+ )
spec_flags = self._build_speculative_flags(
speculative_type = speculative_type,
spec_draft_n_max = spec_draft_n_max,
@@ -9170,11 +9792,102 @@ class LlamaCppBackend:
mtp_draft_path = launch_mtp_draft_path,
draft_device = _draft_device,
)
+ # _build_speculative_flags judged the stripped list, so a user
+ # --spec-type the drop removed left the requested mode reading "auto"
+ # while the caller's extras still mean "the user owns it" (None).
+ # Restore the requested view, or the spec-mode compare never matches.
+ if _extra_args_set_spec_type(_pv_suppressed_spec_extra_args):
+ self._requested_spec_mode = None
# Remember where the spec block sits so a drafter-load failure
# can be retried with these flags swapped out (see below).
_spec_start = len(cmd)
cmd.extend(spec_flags)
+ # A *separate* drafter does not inherit the main --gpu-layers:
+ # common_base_params_to_speculative overwrites n_gpu_layers with
+ # params.speculative.draft.n_gpu_layers, whose default -1 means auto, so
+ # the drafter would run the corrupt path the CPU pin exists to avoid. An
+ # embedded MTP head needs nothing here: with no draft model that override
+ # is skipped (has_draft is false) and the head follows the main
+ # placement. Probe-gated like the other optional flags so the name
+ # matches the build (-ngld predates --spec-draft-ngl) and an unknown
+ # argument never refuses the start; a build advertising none of them had
+ # its drafter dropped above. extra_args is inspected alongside spec_flags
+ # because a user-owned --spec-type makes _build_speculative_flags return
+ # nothing, leaving their --model-draft unpinned. Emitted after the
+ # pass-through extras below, not here: the parser is last-wins and the
+ # paravirtual strip covers only the *main* offload flags, so a user
+ # -ngld/--spec-draft-ngl would otherwise undo this.
+ _pv_draft_cpu_pin: List[str] = []
+ _pv_mmproj_cpu_pin: List[str] = []
+ _pv_split_mode_pin: List[str] = []
+ # --gpu-layers 0 alone does not keep work off the device: with op_offload
+ # on (the default) ggml_backend_sched still sends ops whose weights sit
+ # in host buffers to a higher-priority backend, and Metal accepts them at
+ # batch >= 32. --device none drops the device from the list outright.
+ _pv_device_pin: List[str] = ["--device", "none"] if _paravirtual_cpu_forced else []
+ if (
+ _paravirtual_cpu_forced
+ # Same env the child will see: when the extras own --spec-type the
+ # launch keeps LLAMA_ARG_SPEC_DRAFT_*, so a drafter named only there
+ # still loads and would take the corrupt device unpinned.
+ and _extra_args_mtp_draft_path(
+ [*spec_flags, *(extra_args or [])], env = _child_spec_env(extra_args)
+ )
+ is not None
+ and _paravirtual_draft_ngl_flag(server_caps)
+ ):
+ # The layer count alone is not enough, for the same reason
+ # --gpu-layers 0 was not: common_base_params_to_speculative replaces
+ # the draft context's device list with the draft one, so the main
+ # --device none never reaches it and an empty draft list leaves every
+ # device visible. --device-draft is spelled the same across the
+ # whole supported range.
+ _pv_draft_cpu_pin = [
+ str(_paravirtual_draft_ngl_flag(server_caps)),
+ "0",
+ "--device-draft",
+ "none",
+ ]
+ logger.warning(
+ "Pinning the speculative drafter to CPU: this Mac's Metal "
+ "device is virtualised."
+ )
+
+ # Emitted after the pass-through extras too, same last-wins reason.
+ if _paravirtual_cpu_forced:
+ _pv_split_mode_pin = _paravirtual_split_mode_pin(extra_args)
+
+ # Backstop for the MTP clamp above, which only sees an explicit
+ # --spec-type in extra_args; speculative_type="auto"/"mtp" is not
+ # resolved until _build_speculative_flags runs, here. The KV fit was
+ # sized for more slots, so this over-reserves, never under-reserves.
+ # Skipped when the user's extras own --spec-type: _build_speculative_flags
+ # emits nothing then, and judging the empty flag list would fall through
+ # to LLAMA_ARG_SPEC_TYPE and clamp a launch that is not MTP at all.
+ _mtp_clamped_slots = 0
+ if (
+ n_parallel > 1
+ and not _extra_args_set_spec_type(extra_args)
+ and _extra_args_requests_mtp(spec_flags, env = _child_spec_env(extra_args))
+ ):
+ try:
+ _np_at = cmd.index("--parallel")
+ except ValueError:
+ _np_at = -1
+ if _np_at >= 0:
+ logger.warning(
+ "%s resolved to MTP speculative decoding, which does not "
+ "support %d parallel slots; using 1.",
+ model_identifier,
+ n_parallel,
+ )
+ cmd[_np_at + 1] = "1"
+ # _commit_effective_parallel_slots reports what launched, so
+ # rebind rather than only patching cmd.
+ _mtp_clamped_slots = n_parallel
+ n_parallel = 1
+
# Apply custom chat template override if provided.
self._chat_template_override = chat_template_override
if chat_template_override:
@@ -9250,6 +9963,22 @@ class LlamaCppBackend:
if launch_mmproj_path and effective_is_vision:
cmd.extend(["--mmproj", launch_mmproj_path])
logger.info(f"Using mmproj for vision: {launch_mmproj_path}")
+ # The projector never reads --gpu-layers: clip.cpp picks a GPU
+ # backend from the boolean mmproj_use_gpu, which defaults true, so
+ # the vision encoder would keep running the corrupt path the CPU pin
+ # exists to avoid and encode every image from garbage. A build that
+ # conclusively lacks the flag never gets here (the projector is
+ # dropped up front); an inconclusive probe still pins, since every
+ # build that can start here has had the flag since b5178. Deferred
+ # past the pass-through extras like the drafter pin, since
+ # --mmproj-offload is a real flag a user can pass and llama.cpp is
+ # last-wins.
+ if _paravirtual_cpu_forced and _paravirtual_mmproj_pinnable(server_caps):
+ _pv_mmproj_cpu_pin = ["--no-mmproj-offload"]
+ logger.warning(
+ "Disabling mmproj GPU offload: this Mac's Metal device "
+ "is virtualised."
+ )
# Option C: --api-key for direct client access when enabled
import secrets as _secrets
@@ -9284,7 +10013,12 @@ class LlamaCppBackend:
# request) for the keep-warm loop, dedupe, and /status, so an explicit
# [0, 1] narrowed to [0] records [0] and /status never echoes an ordinal
# the child never saw. Auto selection (no gpu_ids) stays None (#7239).
- if is_vulkan_backend:
+ if _paravirtual_cpu_forced:
+ # --device none pins nothing, so record no effective pin here either.
+ # Ahead of the backend branches: this is the authoritative record and
+ # would otherwise re-echo the device the child never saw.
+ self._gpu_ids = None
+ elif is_vulkan_backend:
# Only record an EXPLICIT Vulkan pin: an auto pick still narrows +
# pins below, but recording it would misreport an explicit pin and
# make dedupe miss the loaded server; mirrors the CUDA/ROCm branch.
@@ -9333,6 +10067,20 @@ class LlamaCppBackend:
f"Appending user extra args to llama-server: {list(_emit_extra_args)}"
)
+ # Last so it wins: the drafter CPU pin on a virtualised Metal device
+ # is a correctness fix, not a preference, and llama.cpp is last-wins.
+ if _pv_draft_cpu_pin:
+ cmd.extend(_pv_draft_cpu_pin)
+ if _pv_mmproj_cpu_pin:
+ cmd.extend(_pv_mmproj_cpu_pin)
+ # Also last: _zero_offload_keeps_gpu_visible reads the finished cmd, so
+ # the override must be in it before the env block below judges this a
+ # zero-VRAM server.
+ if _pv_split_mode_pin:
+ cmd.extend(_pv_split_mode_pin)
+ if _pv_device_pin:
+ cmd.extend(_pv_device_pin)
+
kv_cache_unified = _kv_unified_from_args(cmd)
logger.info(f"Starting llama-server: {' '.join(self._redacted_cmd_for_log(cmd))}")
@@ -9377,6 +10125,43 @@ class LlamaCppBackend:
env.pop("LLAMA_ARG_DEVICE", None)
env.pop("LLAMA_ARG_MAIN_GPU", None)
+ # The unpinnable-drafter drop above rewrites argv, which cannot reach the
+ # drafter the child picks up from its own env. The spec type goes too,
+ # for the same reason the CLI one did: llama.cpp appends types rather
+ # than replacing them, so an inherited draft-simple would outlive the
+ # model it needs. Unsloth owns the spec block whenever the extras do not
+ # name a --spec-type, and nothing _build_speculative_flags emits can undo
+ # an inherited LLAMA_ARG_SPEC_TYPE (env applied first, then appended), so
+ # a managed non-MTP launch would still start MTP, a crash-recovery replay
+ # could not drop it, and the fit never budgeted the drafter the env adds.
+ # Clearing it makes the emitted flags final. A user-owned --spec-type is
+ # left alone: their flags and the env accumulate, which is what the slot
+ # clamp above reads.
+ if _pv_draft_unpinnable or not _extra_args_set_spec_type(extra_args):
+ for _pv_spec_var in _SPEC_ENV_VARS:
+ env.pop(_pv_spec_var, None)
+
+ # The projector guard has a worse blind spot: it only clears Unsloth's
+ # resolved path, so an inherited LLAMA_ARG_MMPROJ loads a projector the
+ # guard believes it dropped, unpinned and independent of --gpu-layers 0.
+ # LLAMA_ARG_MMPROJ_URL goes too: its download overwrites mmproj.path, so
+ # it outranks even the --mmproj Unsloth emits. Unsloth always passes its
+ # own projector on the command line (with --no-mmproj-offload), so an
+ # inherited one is only ever the corrupt path.
+ if _paravirtual_cpu_forced:
+ for _pv_mmproj_var in ("LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL"):
+ env.pop(_pv_mmproj_var, None)
+ # LLAMA_ARG_OVERRIDE_TENSOR is the one placement var --gpu-layers 0
+ # cannot answer: applied during weight-buft selection, before any
+ # layer is assigned, so it puts weights back on the corrupt Metal
+ # buffer on its own. Same CPU-target rule as the argv strip, so an
+ # inherited exps=CPU override keeps working and only GPU-bound goes.
+ _pv_env_ot = env.get("LLAMA_ARG_OVERRIDE_TENSOR")
+ if _pv_env_ot and not _paravirtual_strip_gpu_overrides(
+ ["-ot", str(_pv_env_ot)]
+ ):
+ env.pop("LLAMA_ARG_OVERRIDE_TENSOR", None)
+
# Windows + full offload: PASSIVE OMP + 2 threads stop
# spin-wait burning CPU. CPU/partial offload keeps default
# OMP parallelism. #5692.
@@ -9583,6 +10368,7 @@ class LlamaCppBackend:
self._gguf_path = model_path
self._hf_repo = hf_repo
self._mtp_draft_path = launch_mtp_draft_path
+ self._mtp_draft_suppressed_path = _pv_suppressed_draft_path
# For local GGUF files, extract variant from filename if absent
if hf_variant:
self._hf_variant = hf_variant
@@ -9652,13 +10438,10 @@ class LlamaCppBackend:
healthy = _spawn_and_wait(_fa_cmd, label = "-noflash")
# MTP from Unsloth's spec flags or the user's (extra_args
- # --spec-type / LLAMA_ARG_SPEC_TYPE). The env reaches the child
- # only when neither emits a spec flag, so consult it only then.
- _launch_spec_env: Mapping[str, str] = (
- os.environ
- if (not _extra_args_set_spec_type(extra_args) and not spec_flags)
- else {}
- )
+ # --spec-type / LLAMA_ARG_SPEC_TYPE). The env survives to the child only
+ # when the extras own --spec-type (the launch scrubs it otherwise), so
+ # anything else would judge a server it is not starting.
+ _launch_spec_env: Mapping[str, str] = _child_spec_env(extra_args)
_spec_requested_mtp = any(
"mtp" in str(t).lower() for t in spec_flags
) or _extra_args_requests_mtp(extra_args, env = _launch_spec_env)
@@ -9759,19 +10542,67 @@ class LlamaCppBackend:
_retry_reason,
)
self._kill_process()
- fallback_cmd = (
- cmd[:_spec_start]
- + ["--spec-default"]
- + cmd[_spec_start + len(spec_flags) :]
- )
- # User/env MTP survives in the tail; llama.cpp takes the last
- # spec flag, so a trailing --spec-default overrides it too.
+ _fb_tail = cmd[_spec_start + len(spec_flags) :]
+ _fb_stripped_extras: Optional[List[str]] = None
+ # Appending --spec-default cannot clear MTP the extras or the env
+ # carry: types accumulate, so it would retry the mode that just
+ # failed and lose a main model that loads fine without it. The
+ # tail loses its spec group and the env goes with it, the same way
+ # the crash replay does it.
if _extra_args_requests_mtp(extra_args, env = _launch_spec_env):
- fallback_cmd.append("--spec-default")
+ _fb_tail = strip_shadowing_flags(
+ _fb_tail,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = True,
+ strip_template = False,
+ strip_split_mode = False,
+ )
+ for _fb_spec_var in _SPEC_ENV_VARS:
+ env.pop(_fb_spec_var, None)
+ _fb_stripped_extras = strip_shadowing_flags(
+ extra_args or [],
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = True,
+ strip_template = False,
+ strip_split_mode = False,
+ )
+ # The extras owned --spec-type, so the clamp that took the slots
+ # was the extras one and _mtp_clamped_slots stayed 0. The strip
+ # above makes this retry genuinely non-MTP, so hand those back
+ # too, or --parallel 1 sticks and the requested-vs-requested
+ # dedupe keeps every later load on the same one-slot server.
+ # Only where no GPU had to admit them: that clamp runs before the
+ # slot fit, so on a GPU box the count was never budgeted and the
+ # retry would size buffers nothing approved.
+ if not _detected_gpus:
+ _mtp_clamped_slots = max(_mtp_clamped_slots, _pv_extras_clamped_slots)
+ fallback_cmd = cmd[:_spec_start] + ["--spec-default"] + _fb_tail
+ # fallback_cmd inherits the MTP slot clamp, but this retry is not
+ # MTP: hand back the slots the KV fit was sized for, or --parallel N
+ # silently serves one chat at a time (and the requested-vs-requested
+ # dedupe makes that stick). Later retries derive from this argv, so
+ # rebind n_parallel now.
+ if _mtp_clamped_slots > 1 and "--parallel" in fallback_cmd:
+ fallback_cmd[fallback_cmd.index("--parallel") + 1] = str(_mtp_clamped_slots)
+ n_parallel = _mtp_clamped_slots
healthy = _spawn_and_wait(fallback_cmd, label = "-retry")
if healthy:
self._speculative_type = "default"
_mtp_active_for_launched_server = False
+ # The record below stores extra_args as what LAUNCHED, but this
+ # server launched without the spec group. Leaving the MTP list
+ # there would have the next inheriting Apply pick it back up and
+ # repeat the crash. Keep it as the requested state only, the way
+ # the runtime-crash replay does.
+ if _fb_stripped_extras is not None:
+ _pv_suppressed_spec_extra_args = (
+ _pv_suppressed_spec_extra_args
+ if _pv_suppressed_spec_extra_args is not None
+ else list(extra_args or [])
+ )
+ extra_args = _fb_stripped_extras
# A too-old llama.cpp can reject a model's --mmproj projector
# (format message or a bare SIGSEGV); retry once text-only.
@@ -9897,6 +10728,17 @@ class LlamaCppBackend:
if gpu_ids is not None
else list(extra_args)
)
+ # Device-stripped the same way, so both comparator sides share a rule.
+ _pv_requested = (
+ _pv_suppressed_spec_extra_args
+ if _pv_suppressed_spec_extra_args is not None
+ else extra_args
+ )
+ self._requested_extra_args = (
+ self._strip_device_extra_args(_pv_requested)
+ if gpu_ids is not None
+ else list(_pv_requested)
+ )
self._extra_args_source = (model_identifier, hf_variant)
self._requested_n_ctx = int(n_ctx)
# Local n_parallel may have been reduced above; the snapshot has the ask.
@@ -10281,6 +11123,36 @@ class LlamaCppBackend:
"""Match live state and adopt the caller's compatible GPU placement."""
if not self.matches_load_source(intent):
return False
+ # The stored state is what LAUNCHED, and on a virtualised Metal device that is
+ # the CPU-pinned rewrite, not the request. Apply the same rewrite here
+ # (idempotent, so load_model's own call is a no-op) or a client that keeps
+ # sending Auto mismatches on every call.
+ if _metal_device_is_paravirtual():
+ (
+ _pv_mode,
+ _pv_layers,
+ _pv_tp,
+ _pv_split,
+ _pv_cpu_moe,
+ _pv_extras,
+ ) = paravirtual_normalized_request(
+ gpu_memory_mode = intent.gpu_memory_mode,
+ gpu_layers = intent.gpu_layers,
+ tensor_parallel = intent.tensor_parallel,
+ tensor_split = list(intent.tensor_split) if intent.tensor_split else None,
+ n_cpu_moe = intent.n_cpu_moe,
+ extra_args = list(intent.extra_args) if intent.extra_args is not None else None,
+ log_dropped = False,
+ )
+ intent = replace(
+ intent,
+ gpu_memory_mode = _pv_mode,
+ gpu_layers = _pv_layers,
+ tensor_parallel = _pv_tp,
+ tensor_split = tuple(_pv_split) if _pv_split else None,
+ n_cpu_moe = _pv_cpu_moe,
+ extra_args = tuple(_pv_extras) if _pv_extras is not None else None,
+ )
effective_extra_args = (
list(intent.extra_args) if intent.extra_args is not None else self._extra_args
)
@@ -10325,8 +11197,13 @@ class LlamaCppBackend:
LLAMA_ARG_SPEC_DRAFT_* env) -- these offload to the GPU regardless of
the main ``--gpu-layers``. A drafter explicitly forced to CPU
(--spec-draft-ngl 0 / --spec-draft-device cpu) doesn't count."""
- if any(str(a).startswith("--mmproj") for a in cmd):
- return True
+ _args = [str(a) for a in cmd]
+ if any(a.startswith("--mmproj") for a in _args):
+ # --no-mmproj-offload clears mmproj_use_gpu and clip.cpp gates the whole
+ # GPU backend on it, so the projector holds no VRAM. Last flag wins.
+ _off = [a for a in _args if a in ("--mmproj-offload", "--no-mmproj-offload")]
+ if not _off or _off[-1] != "--no-mmproj-offload":
+ return True
if _extra_args_mtp_draft_path(cmd, env) is None:
return False
return not _extra_args_draft_offloaded_to_cpu(cmd, env)
@@ -10408,6 +11285,7 @@ class LlamaCppBackend:
self._gguf_path = None
self._hf_repo = None
self._mtp_draft_path = None
+ self._mtp_draft_suppressed_path = None
self._spec_fallback_reason = None
self._last_load_intent = None
self._mtp_runtime_fallback_active = False
@@ -11317,18 +12195,39 @@ class LlamaCppBackend:
if self._last_load_intent != snapshot:
logger.info("MTP-crash reload skipped: load settings changed.")
return
- # Drop user/env MTP too: append a last-wins --spec-default.
+ # Appending --spec-default cannot drop MTP: llama.cpp appends spec
+ # types rather than replacing, so the extras have to lose theirs.
+ # Once they do, Unsloth owns the block and the launch scrubs the
+ # inherited env for the replay too.
+ _ea = list(snapshot.extra_args or ())
fallback_extra_args = snapshot.extra_args
- if _extra_args_requests_mtp(fallback_extra_args, env = os.environ):
- extra_args = list(fallback_extra_args or ())
- extra_args.append("--spec-default")
- fallback_extra_args = tuple(extra_args)
+ if _extra_args_requests_mtp(_ea, env = _child_spec_env(_ea)):
+ fallback_extra_args = tuple(
+ strip_shadowing_flags(
+ _ea,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = True,
+ strip_template = False,
+ strip_split_mode = False,
+ )
+ )
fallback = replace(
snapshot,
speculative_type = "off",
extra_args = fallback_extra_args,
)
self.load_model(fallback)
+ # Same reason the mode is restored below: the replay launched a
+ # stripped list but the caller keeps sending the original, so a
+ # comparator seeing only the stripped one would reload the very MTP
+ # configuration that just crashed.
+ if fallback_extra_args is not snapshot.extra_args:
+ self._requested_extra_args = (
+ self._strip_device_extra_args(_ea)
+ if snapshot.gpu_ids is not None
+ else list(_ea)
+ )
# Restore the requested mode + reason load_model("off") cleared,
# so /status shows the user's mode + note (like the startup fallback).
self._requested_spec_mode = _canonicalize_spec_mode(requested_mode)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index afefc3f0002..97d6e302cad 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1013,9 +1013,11 @@ try:
_hf_offline_if_unreachable_for,
_kv_bytes_per_elem,
_kv_unified_from_args,
+ _metal_device_is_paravirtual,
_planned_main_cache_types,
_swa_full_from_args_or_env,
detect_reasoning_flags,
+ paravirtual_normalized_request,
)
from core.inference.llama_server_args import (
_effective_tensor_parallel,
@@ -1061,9 +1063,11 @@ except ImportError:
_hf_offline_if_unreachable_for,
_kv_bytes_per_elem,
_kv_unified_from_args,
+ _metal_device_is_paravirtual,
_planned_main_cache_types,
_swa_full_from_args_or_env,
detect_reasoning_flags,
+ paravirtual_normalized_request,
)
from core.inference.llama_server_args import (
_effective_tensor_parallel,
@@ -3648,6 +3652,7 @@ def _active_gguf_intent(
),
mtp_draft_path = _mtp_draft_for_path(llama_backend.gguf_path, native_grant_backed),
compare_mtp_draft = True,
+ extra_args_inherited = request.llama_extra_args is None,
)
@@ -5165,6 +5170,7 @@ def _resolve_gguf_load_intent(
n_parallel = n_parallel,
is_vision = config.is_vision,
gpu_ids_are_vulkan_ordinals = placement.gpu_ids_are_vulkan_ordinals,
+ extra_args_inherited = getattr(request, "llama_extra_args", None) is None,
)
@@ -5204,13 +5210,39 @@ def _guard_chat_load_against_training(
from core.inference.llama_cpp import _diffusion_manual_ngl, _scale_diffusion_required_gb
is_gguf = bool(getattr(config, "is_gguf", False))
- if is_gguf and request.gpu_memory_mode == "manual" and (diffusion_kind is False):
+ # load_model pins a GGUF to CPU on a virtualised Metal device, so guard what will run:
+ # sized as the raw Auto request, a CPU-only load is refused over VRAM it never takes.
+ _guard_gpu_memory_mode = request.gpu_memory_mode
+ _guard_gpu_layers = request.gpu_layers
+ _guard_tensor_parallel = request.tensor_parallel
+ _pv_guard_forced_cpu = is_gguf and _metal_device_is_paravirtual()
+ if _pv_guard_forced_cpu:
+ _pv = paravirtual_normalized_request(
+ gpu_memory_mode = request.gpu_memory_mode,
+ gpu_layers = request.gpu_layers,
+ tensor_parallel = request.tensor_parallel,
+ tensor_split = None,
+ n_cpu_moe = 0,
+ extra_args = llama_extra_args,
+ log_dropped = False,
+ )
+ _guard_gpu_memory_mode = _pv.gpu_memory_mode
+ _guard_gpu_layers = _pv.gpu_layers
+ _guard_tensor_parallel = _pv.tensor_parallel
+ llama_extra_args = _pv.extra_args
+ # The pin leaves nothing on the GPU (--device none, no mmproj offload, drafter on CPU),
+ # so there is nothing to budget whatever the GGUF turns out to be. Ahead of the checks
+ # below, which only exempt a CONFIRMED diffusion GGUF and would size an unclassified
+ # remote one as GPU-resident and 409 a load that never touches VRAM.
+ if _pv_guard_forced_cpu:
+ return
+ if is_gguf and _guard_gpu_memory_mode == "manual" and (diffusion_kind is False):
return
# A zero-layer diffusion split places no model layers on any device, so it cannot compete
# with training for VRAM. Mirrors the loader, which folds the same condition into its
# cpu_only (core/inference/llama_cpp.py).
diffusion_ngl = (
- _diffusion_manual_ngl(request.gpu_memory_mode, request.gpu_layers) if is_gguf else None
+ _diffusion_manual_ngl(_guard_gpu_memory_mode, _guard_gpu_layers) if is_gguf else None
)
if diffusion_ngl is not None and diffusion_kind is not False:
# The loader drops the split when the shim has no --ngl and launches GPU-resident.
@@ -5254,11 +5286,19 @@ def _guard_chat_load_against_training(
)
# Size with the count that will actually launch, or a load that fits gets a
- # 409: diffusion never receives --parallel, and load_model clamps to 1 on an
- # llama-server without --kv-unified. An unclassified GGUF keeps the ask.
+ # 409: diffusion never receives --parallel, load_model clamps to 1 on an
+ # llama-server without --kv-unified, and it clamps MTP to 1 as well. An
+ # unclassified GGUF keeps the ask.
if is_gguf and n_parallel > 1:
if diffusion_kind is True:
n_parallel = 1
+ # MTP is deliberately NOT clamped here even though the launch clamps it to one
+ # slot. _estimate_gguf_required_gb counts the drafter file and the main KV, but
+ # not the draft KV, the duplicated target context MLA keeps, or the draft compute
+ # reserve, all of which load_model does budget. Sizing for one slot would drop
+ # the slot KV without replacing it with those, and a guard that under-sizes
+ # evicts the training run it exists to protect: the spare slots stand in for
+ # what is not modelled.
else:
try:
caps = LlamaCppBackend.probe_server_capabilities()
@@ -5276,7 +5316,7 @@ def _guard_chat_load_against_training(
n_parallel = n_parallel,
cache_type_kv = request.cache_type_kv,
tensor_parallel = (
- _effective_tensor_parallel(llama_extra_args, request.tensor_parallel)
+ _effective_tensor_parallel(llama_extra_args, _guard_tensor_parallel)
and (
is_vulkan_backend
or LlamaCppBackend._effective_gpu_count(requested_gpu_ids) >= 2
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index 89f612393cd..f4431afbdf5 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -78,6 +78,29 @@ def _no_background_model_scan(monkeypatch):
monkeypatch.setattr(local_model_resolver, "_scan", (time.monotonic(), {}))
[email protected](autouse = True)
+def _assume_bare_metal(monkeypatch):
+ """Pin the virtualised-Metal detector off so the suite is host independent.
+
+ The dedupe comparators consult real hardware, so on a Mac (and on GitHub's macos
+ runners, which are paravirtual) every test of them would normalize the incoming
+ request and mismatch fixture state that was never normalized. Tests that want the
+ fallback patch it back on.
+ """
+ from core.inference import llama_cpp
+
+ monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
+ # The route rebinds the detector as a module global (its import sits in a module-level
+ # try), so patching llama_cpp alone leaves it on real hardware.
+ try:
+ from routes import inference as routes_inference
+ except Exception: # optional deps absent on some CI legs
+ return
+ monkeypatch.setattr(
+ routes_inference, "_metal_device_is_paravirtual", lambda: False, raising = False
+ )
+
+
@pytest.fixture(scope = "session")
def studio_server(request):
"""Yield ``(base_url, api_key)`` for e2e tests.
diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.py
index 86ffa99d588..7de345f469e 100644
--- a/studio/backend/tests/test_gpu_memory_mode.py
+++ b/studio/backend/tests/test_gpu_memory_mode.py
@@ -943,7 +943,9 @@ def test_start_diffusion_server_resets_tensor_parallel():
# diffusion re-Apply reloads against stale tensor-parallel state.
src = inspect.getsource(llama_cpp_module.LlamaCppBackend._start_diffusion_server)
assert "self._tensor_parallel = False" in src
- assert "self._requested_gpu_ids = list(self._gpu_ids) if self._gpu_ids else None" in src
+ # Still the collapsed single-device pick, but taken from the request rather than the
+ # effective pin, which a forced-CPU launch on virtualised Metal clears.
+ assert "self._requested_gpu_ids = [sorted(gpu_ids)[0]] if gpu_ids else None" in src
# ── Manual tensor split: child enumeration pinned to the picker's order ──────
@@ -1344,3 +1346,14 @@ def test_cmd_companion_ignores_cpu_forced_drafter():
# mmproj still counts even alongside a CPU drafter.
cmd = ["llama-server", "-md", "d.gguf", "--spec-draft-ngl", "0", "--mmproj", "p.gguf"]
assert has(cmd, {}) is True
+
+
+def test_cmd_companion_ignores_a_projector_pinned_off_the_gpu():
+ # --no-mmproj-offload clears mmproj_use_gpu and clip.cpp gates the whole GPU
+ # backend on it, so a CPU-pinned vision server must not look GPU resident.
+ has = LlamaCppBackend._cmd_has_gpu_companion
+ cmd = ["llama-server", "--mmproj", "p.gguf", "--no-mmproj-offload"]
+ assert has(cmd, {}) is False
+ # llama.cpp assigns rather than accumulates for this one, so the last flag wins.
+ cmd = ["llama-server", "--mmproj", "p.gguf", "--no-mmproj-offload", "--mmproj-offload"]
+ assert has(cmd, {}) is True
diff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.py
index 02d8b9e29f7..2e5ba946578 100644
--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py
+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py
@@ -15,6 +15,7 @@ import os
import struct
import sys
import types as _types
+from importlib.util import find_spec as _find_spec
from pathlib import Path
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
@@ -29,27 +30,36 @@ _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,
- },
-)
-sys.modules.setdefault("httpx", _httpx_stub)
+# Real httpx wins when installed: setdefault only checks whether httpx is already
+# imported, not whether it exists, so the stub used to shadow the real module for the
+# rest of the session, and it is a subset (no Response) that blew routes/inference up in
+# combined runs. find_spec rather than an import, so installing the stub stays this
+# module's only side effect on sys.modules. sys.modules is tested first because find_spec
+# raises ValueError on a module already there without a spec (every bare-ModuleType httpx
+# stub in this tree), which would be a collection error rather than one failed test.
+if "httpx" not in sys.modules and _find_spec("httpx") is None:
+ _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.Response = type("Response", (), {})
+ _httpx_stub.Client = type(
+ "C",
+ (),
+ {
+ "__init__": lambda s, **kw: None,
+ "__enter__": lambda s: s,
+ "__exit__": lambda s, *a: None,
+ },
+ )
+ sys.modules["httpx"] = _httpx_stub
import pytest
@@ -2199,3 +2209,42 @@ def test_already_in_target_state_retries_after_hf_drafter_not_found():
# Sanity: with no fallback reason the same request still dedupes (matches).
ok = _mtp_backend(_model_identifier = "unsloth/gemma-4-E4B-it-GGUF", _gguf_path = None)
assert _matches(ok, **_drafter_not_found_kwargs()) is True
+
+
+_MODERN_DRAFT_NGL_HELP = """usage: llama-server [options]
+
+--spec-draft-ngl N layers to offload for the draft model
+--parallel N number of parallel sequences
+"""
+
+_LEGACY_DRAFT_NGL_HELP = """usage: llama-server [options]
+
+-ngld, --gpu-layers-draft N layers to offload for the draft model
+--parallel N number of parallel sequences
+"""
+
+
+@_NEEDS_BASH
+def test_probe_reports_the_draft_ngl_alias_the_build_actually_has(tmp_path):
+ """--spec-draft-ngl only exists from llama.cpp b8955, so a plain "yes" for either
+ alias would make the paravirtual drafter pin emit a name an older build does not
+ know and the server would refuse to start."""
+ modern = _make_fake_llama_server(tmp_path / "modern", _MODERN_DRAFT_NGL_HELP)
+ _clear_caps_cache()
+ assert LlamaCppBackend.probe_server_capabilities(str(modern))["spec_draft_ngl_flag"] == (
+ "--spec-draft-ngl"
+ )
+
+ legacy = _make_fake_llama_server(tmp_path / "legacy", _LEGACY_DRAFT_NGL_HELP)
+ _clear_caps_cache()
+ assert LlamaCppBackend.probe_server_capabilities(str(legacy))["spec_draft_ngl_flag"] == (
+ "--gpu-layers-draft"
+ )
+
+
+@_NEEDS_BASH
+def test_probe_reports_no_draft_ngl_flag_when_the_build_has_neither(tmp_path):
+ """The negative: without it the pin must be skipped, not guessed at."""
+ neither = _make_fake_llama_server(tmp_path / "neither", "usage: llama-server\n\n--parallel N\n")
+ _clear_caps_cache()
+ assert LlamaCppBackend.probe_server_capabilities(str(neither))["spec_draft_ngl_flag"] is None
diff --git a/studio/backend/tests/test_metal_paravirtual_guard.py b/studio/backend/tests/test_metal_paravirtual_guard.py
new file mode 100644
index 00000000000..a7be06b8b32
--- /dev/null
+++ b/studio/backend/tests/test_metal_paravirtual_guard.py
@@ -0,0 +1,2263 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A virtualised Apple GPU must fall back to CPU; a real one must not.
+
+The second half matters most: forcing gpu_layers=0 on every Mac would "fix" the corrupt
+output by throwing away Metal for every real user, so these tests pin the discrimination
+and not just the fallback.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+from dataclasses import asdict
+import sys
+import textwrap
+import types
+
+import pytest
+
+import core.inference.llama_cpp as llama_cpp
+import core.inference.llama_server_args as llama_server_args
+from core.inference.llama_cpp import _metal_device_is_paravirtual
+
+
[email protected](autouse = True)
+def _clear_cache():
+ """The detector is lru_cached so a real machine only pays for the probe once."""
+ _metal_device_is_paravirtual.cache_clear()
+ yield
+ _metal_device_is_paravirtual.cache_clear()
+
+
+def _fake_mlx(device_name: str):
+ module = types.ModuleType("mlx.core")
+ module.device_info = lambda: {"device_name": device_name}
+ parent = types.ModuleType("mlx")
+ parent.core = module
+ return parent, module
+
+
+ "device_name, expected",
+ [
+ ("Apple Paravirtual device", True),
+ ("apple paravirtual device", True), # matching must not be case-sensitive
+ ("Apple M1", False),
+ ("Apple M3 Max", False),
+ ("Apple M4 Pro", False),
+ ],
+)
+def test_only_virtualised_apple_gpus_fall_back(monkeypatch, device_name, expected):
+ monkeypatch.setattr(sys, "platform", "darwin")
+ parent, core = _fake_mlx(device_name)
+ monkeypatch.setitem(sys.modules, "mlx", parent)
+ monkeypatch.setitem(sys.modules, "mlx.core", core)
+ # Inert probe output so this measures the name matching, not system_profiler.
+ monkeypatch.setattr(
+ "core.inference.llama_cpp.subprocess.run",
+ lambda *a, **k: types.SimpleNamespace(stdout = "Chipset Model: Apple M3 Max"),
+ )
+ assert _metal_device_is_paravirtual() is expected
+
+
+def test_non_darwin_never_pays_for_the_probe(monkeypatch):
+ """Linux and Windows short-circuit: there is no Metal to be virtualised."""
+ monkeypatch.setattr(sys, "platform", "linux")
+
+ def explode(*args, **kwargs): # pragma: no cover - must never run
+ raise AssertionError("probed for a Metal device off macOS")
+
+ monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", explode)
+ assert _metal_device_is_paravirtual() is False
+
+
+def test_system_profiler_catches_it_when_mlx_is_absent(monkeypatch):
+ """MLX is not on every Mac; without this fallback a virtualised machine without it
+ would read as bare metal and emit gibberish."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setitem(sys.modules, "mlx", None) # import raises
+ monkeypatch.setattr(
+ "core.inference.llama_cpp.subprocess.run",
+ lambda *a, **k: types.SimpleNamespace(
+ stdout = "Graphics/Displays:\n Apple Paravirtual device:\n Vendor: Apple"
+ ),
+ )
+ assert _metal_device_is_paravirtual() is True
+
+
+def _probe_dispatch(responses):
+ """subprocess.run stub keyed on the probe, so SPDisplaysDataType and hw.model can
+ answer differently."""
+
+ def run(cmd, *a, **k):
+ key = "hw.model" if "sysctl" in cmd[0] else "spdisplays"
+ return types.SimpleNamespace(stdout = responses.get(key, ""))
+
+ return run
+
+
+def test_a_headless_vm_is_caught_when_spdisplays_says_nothing(monkeypatch):
+ """The case the OS fallback exists for and used to miss. Measured on macos-14/15:
+ SPDisplaysDataType returns zero bytes on a VM with no display, so every cloud and CI
+ Mac without MLX read as bare metal and kept the offload that corrupts its output.
+ hw.model still names the machine."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setitem(sys.modules, "mlx", None)
+ monkeypatch.setattr(
+ "core.inference.llama_cpp.subprocess.run",
+ _probe_dispatch({"hw.model": "VirtualMac2,1\n", "spdisplays": ""}),
+ )
+ assert _metal_device_is_paravirtual() is True
+
+
+def test_a_physical_mac_is_not_dragged_down_by_the_model_probe(monkeypatch):
+ """Negative: real hardware reports Mac<n>,<n>, which must not read as virtual."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setitem(sys.modules, "mlx", None)
+ monkeypatch.setattr(
+ "core.inference.llama_cpp.subprocess.run",
+ _probe_dispatch(
+ {
+ "hw.model": "Mac15,3\n",
+ "spdisplays": "Graphics/Displays:\n Apple M3 Max:\n Vendor: Apple",
+ }
+ ),
+ )
+ assert _metal_device_is_paravirtual() is False
+
+
+def test_a_desktop_vm_still_answers_through_spdisplays(monkeypatch):
+ """Negative on the ordering: a VM whose hw.model does not say virtual is still caught
+ by the display probe, so adding hw.model did not narrow the net."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setitem(sys.modules, "mlx", None)
+ monkeypatch.setattr(
+ "core.inference.llama_cpp.subprocess.run",
+ _probe_dispatch(
+ {
+ "hw.model": "Mac14,2\n",
+ "spdisplays": "Graphics/Displays:\n Apple Paravirtual device:",
+ }
+ ),
+ )
+ assert _metal_device_is_paravirtual() is True
+
+
+def test_mlx_short_circuits_before_any_subprocess(monkeypatch):
+ """Negative on cost: MLX answered, so neither probe should spawn. Roughly 40 ms for
+ MLX against 300 ms for SPDisplaysDataType."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ parent, core = _fake_mlx("Apple Paravirtual device")
+ monkeypatch.setitem(sys.modules, "mlx", parent)
+ monkeypatch.setitem(sys.modules, "mlx.core", core)
+
+ def explode(*args, **kwargs): # pragma: no cover - must never run
+ raise AssertionError("spawned a probe after MLX already named the device")
+
+ monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", explode)
+ assert _metal_device_is_paravirtual() is True
+
+
+def test_a_broken_probe_leaves_gpu_offload_alone(monkeypatch):
+ """If neither source can answer, assume a real Mac: guessing "virtualised" would
+ silently drop everyone the probe fails on to CPU."""
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setitem(sys.modules, "mlx", None)
+
+ def explode(*args, **kwargs):
+ raise OSError("system_profiler not found")
+
+ monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", explode)
+ assert _metal_device_is_paravirtual() is False
+
+
+# ── the fallback must actually hold, and must not churn the server ────
+
+
+class _FakeProcess:
+ def poll(self):
+ return None
+
+ def terminate(self):
+ pass
+
+ def wait(self, timeout = None):
+ return 0
+
+
+def _paravirtual(monkeypatch):
+ monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: True)
+
+
+def _load_model_source() -> str:
+ return inspect.getsource(llama_cpp.LlamaCppBackend.load_model)
+
+
+def test_fallback_is_settled_before_the_duplicate_load_check():
+ """The launch records the normalized placement ("manual"/0), so a repeat Auto request
+ must be normalized before comparison, or every duplicate /load tears down a healthy
+ CPU server."""
+ src = _load_model_source()
+ assert src.index("_metal_device_is_paravirtual()") < src.index(
+ "self.adopt_load_intent_if_matched("
+ )
+
+
+def test_repeat_auto_load_does_not_reload_a_healthy_cpu_server(monkeypatch, tmp_path):
+ """End-to-end: the second identical Auto /load must take the fast path."""
+ _paravirtual(monkeypatch)
+ backend = llama_cpp.LlamaCppBackend()
+ backend._process = _FakeProcess()
+ backend._healthy = True
+ backend._audio_probed = True
+ backend._model_identifier = "owner/repo"
+ gguf = tmp_path / "model.gguf"
+ gguf.write_bytes(b"GGUF")
+ backend._gguf_path = str(gguf)
+ backend._requested_n_ctx = 8192
+ backend._requested_n_parallel = 1
+ backend._requested_spec_mode = "auto"
+ # What the first Auto load on a virtualised Mac left behind.
+ backend._gpu_memory_mode = "manual"
+ backend._gpu_layers = 0
+
+ def _never(*args, **kwargs): # pragma: no cover - must never run
+ raise AssertionError("tore down a healthy server on a duplicate /load")
+
+ monkeypatch.setattr(backend, "_find_llama_server_binary", _never)
+ monkeypatch.setattr(backend, "_kill_process", _never)
+
+ assert (
+ backend.load_model(
+ llama_cpp.GgufLoadIntent(
+ model_identifier = "owner/repo",
+ gguf_path = str(gguf),
+ n_ctx = 8192,
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ n_parallel = 1,
+ )
+ )
+ is True
+ )
+
+
+def test_a_pass_through_layer_flag_cannot_re_enable_the_corrupt_offload(monkeypatch):
+ """Auto never strips -ngl at the route, and user extras are appended after the managed
+ --gpu-layers 0, so llama.cpp's last-wins parser would undo the pin."""
+ _paravirtual(monkeypatch)
+ backend = llama_cpp.LlamaCppBackend()
+ seen = {}
+
+ def _capture(intent):
+ captured = asdict(intent)
+ # The intent freezes its sequences into tuples; compare on content.
+ for _key in ("extra_args", "tensor_split", "gpu_ids"):
+ if captured.get(_key) is not None:
+ captured[_key] = list(captured[_key])
+ seen.update(captured)
+ return True
+
+ monkeypatch.setattr(backend, "adopt_load_intent_if_matched", _capture)
+ monkeypatch.setattr(backend, "_apply_detected_audio", lambda _d: True)
+ backend._audio_probed = True
+ backend._healthy = True
+ backend.load_model(
+ llama_cpp.GgufLoadIntent(
+ model_identifier = "owner/repo",
+ gguf_path = "/nonexistent/model.gguf",
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ extra_args = ["-ngl", "99", "--top-k", "40"],
+ )
+ )
+ assert seen["gpu_memory_mode"] == "manual"
+ assert seen["gpu_layers"] == 0
+ assert seen["extra_args"] == ["--top-k", "40"]
+
+
+def test_a_real_mac_keeps_its_offload_flags(monkeypatch):
+ """The stripping is scoped to the fallback: a physical Mac must keep -ngl."""
+ monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
+ backend = llama_cpp.LlamaCppBackend()
+ seen = {}
+
+ def _capture(intent):
+ captured = asdict(intent)
+ # The intent freezes its sequences into tuples; compare on content.
+ for _key in ("extra_args", "tensor_split", "gpu_ids"):
+ if captured.get(_key) is not None:
+ captured[_key] = list(captured[_key])
+ seen.update(captured)
+ return True
+
+ monkeypatch.setattr(backend, "adopt_load_intent_if_matched", _capture)
+ monkeypatch.setattr(backend, "_apply_detected_audio", lambda _d: True)
+ backend._audio_probed = True
+ backend._healthy = True
+ backend.load_model(
+ llama_cpp.GgufLoadIntent(
+ model_identifier = "owner/repo",
+ gguf_path = "/nonexistent/model.gguf",
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ extra_args = ["-ngl", "99"],
+ )
+ )
+ assert seen["gpu_memory_mode"] == "auto"
+ assert seen["extra_args"] == ["-ngl", "99"]
+
+
+def test_gpu_companions_are_pinned_to_cpu_too():
+ """--gpu-layers 0 does not reach them: clip.cpp offloads on the mmproj_use_gpu
+ boolean (default true) and a separate drafter takes
+ params.speculative.draft.n_gpu_layers, default -1 = auto."""
+ src = _load_model_source()
+ assert '"--no-mmproj-offload"' in src
+ # The drafter flag name comes from the probe, never a literal: --spec-draft-ngl only
+ # exists from b8955, and an older build exposing only -ngld would refuse to start.
+ assert (
+ '"--spec-draft-ngl", "0"' not in src
+ ), "hardcoding the flag defeats the capability probe on builds that only have -ngld"
+ assert "_paravirtual_draft_ngl_flag(server_caps)" in src
+
+
+ "caps, drops, pins",
+ [
+ # Conclusive probe, flag genuinely absent: drop, as before.
+ ({"supports_no_mmproj_offload": False, "mtp_probe_inconclusive": False}, True, False),
+ # Conclusive probe, flag present: pin, as before.
+ ({"supports_no_mmproj_offload": True, "mtp_probe_inconclusive": False}, False, True),
+ # Probe never answered: must NOT drop. --no-mmproj-offload is b5178 and the base
+ # argv already needs b6325, so a build that can start here always has it; a false
+ # capability means the probe failed, and dropping vision would be self-inflicted.
+ ({"supports_no_mmproj_offload": False, "mtp_probe_inconclusive": True}, False, True),
+ ],
+)
+def test_a_failed_probe_does_not_cost_the_user_their_projector(caps, drops, pins):
+ mmproj, vision, _warnings = _mmproj_gate(
+ paravirtual = True, caps = caps, mmproj = "/m/mmproj-F32.gguf", is_vision = True
+ )
+ assert (mmproj is None) is drops
+ assert (vision is False) is drops
+ assert llama_cpp._paravirtual_mmproj_pinnable(caps) is pins
+
+
+ "caps, expected",
+ [
+ (
+ {"spec_draft_ngl_flag": "--spec-draft-ngl", "mtp_probe_inconclusive": False},
+ "--spec-draft-ngl",
+ ),
+ (
+ {"spec_draft_ngl_flag": "--gpu-layers-draft", "mtp_probe_inconclusive": False},
+ "--gpu-layers-draft",
+ ),
+ # Unanswered probe falls back to the 2023 spelling rather than reading as
+ # unpinnable, so a failed probe costs speculation nothing.
+ ({"spec_draft_ngl_flag": None, "mtp_probe_inconclusive": True}, "--gpu-layers-draft"),
+ # Conclusive and genuinely absent stays unpinnable.
+ ({"spec_draft_ngl_flag": None, "mtp_probe_inconclusive": False}, None),
+ ],
+)
+def test_the_drafter_pin_falls_back_before_it_gives_up(caps, expected):
+ assert llama_cpp._paravirtual_draft_ngl_flag(caps) == expected
+
+
+def test_a_failed_probe_does_not_cost_the_user_their_drafter():
+ """The drop half of the same decision: an unanswered probe must not drop."""
+ drafter, _extras, _warnings = _drafter_gate(
+ paravirtual = True,
+ caps = {"spec_draft_ngl_flag": None, "mtp_probe_inconclusive": True},
+ drafter = "/m/mtp-model.gguf",
+ extra_args = None,
+ )
+ assert drafter == "/m/mtp-model.gguf"
+
+
+ "extras, kept",
+ [
+ # A GPU-bound override survives --gpu-layers 0: llama.cpp applies it while picking
+ # each weight's buffer type, before any layer is assigned.
+ (["-ot", ".*=Metal"], False),
+ (["-ot=.*=Metal"], False),
+ (["-otd", ".*=Metal"], False),
+ (["--override-tensor", "blk.*=Metal"], False),
+ (["-ot", "exps=CPU,attn=Metal"], False),
+ # Negatives: a CPU target moves weights the same way this fallback does, so
+ # stripping it would slow the load it rescues.
+ (["-ot", "exps=CPU"], True),
+ (["--override-tensor", "blk.*=CPU"], True),
+ (["--top-k", "40"], True),
+ ],
+)
+def test_only_gpu_bound_tensor_overrides_are_dropped(extras, kept):
+ out = llama_cpp._paravirtual_strip_gpu_overrides(extras)
+ assert (out == list(extras)) is kept
+
+
+def test_the_override_strip_leaves_other_extras_alone():
+ """Negative: stripping must not disturb neighbouring arguments."""
+ out = llama_cpp._paravirtual_strip_gpu_overrides(
+ ["--top-k", "40", "-ot", ".*=Metal", "--temp", "0.7"]
+ )
+ assert out == ["--top-k", "40", "--temp", "0.7"]
+
+
+def _load_model_tree() -> ast.AST:
+ return ast.parse(textwrap.dedent(_load_model_source()))
+
+
+def test_the_companion_pins_are_keyed_on_the_hardware_not_the_request():
+ """A caller already asking for Manual + 0 layers needs no placement rewrite, so
+ skipping the whole block for it left _paravirtual_cpu_forced False and silently
+ dropped the mmproj / drafter pins, which do not read --gpu-layers at all."""
+ tree = _load_model_tree()
+ assigns = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == "_paravirtual_cpu_forced" for t in node.targets)
+ ]
+ assert len(assigns) == 1, "the flag must have exactly one source of truth"
+ (assign,) = assigns
+ assert isinstance(assign.value, ast.Call)
+ assert assign.value.func.id == "_metal_device_is_paravirtual"
+
+ # The negative: it must NOT be nested under a test of the requested placement, which
+ # is what made a manual CPU load lose the companion pins.
+ def _mentions(node, names):
+ found = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
+ return names <= found
+
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.If):
+ continue
+ if not _mentions(node.test, {"gpu_memory_mode", "gpu_layers"}):
+ continue
+ nested = [n for stmt in node.body for n in ast.walk(stmt)]
+ assert (
+ assign not in nested
+ ), "_paravirtual_cpu_forced is gated on the requested placement again"
+
+
+def test_a_user_owned_drafter_is_pinned_to_cpu_too():
+ """A user --spec-type makes _build_speculative_flags emit nothing, so their
+ --model-draft never appeared in spec_flags and the drafter kept running corrupt."""
+ user_extras = ["--spec-type", "draft-simple", "--model-draft", "/models/d.gguf"]
+ # Studio emits no spec block at all here, which is why spec_flags alone is blind.
+ backend = llama_cpp.LlamaCppBackend()
+ assert (
+ backend._build_speculative_flags(
+ speculative_type = "auto",
+ spec_draft_n_max = None,
+ extra_args = user_extras,
+ model_identifier = "owner/repo",
+ model_path = None,
+ gpus = False,
+ binary = None,
+ )
+ == []
+ )
+ assert llama_cpp._extra_args_mtp_draft_path([*[], *user_extras]) == "/models/d.gguf"
+ # No drafter anywhere means no pin, so an embedded MTP head (which follows the main
+ # --gpu-layers) is not handed a flag it does not need.
+ assert llama_cpp._extra_args_mtp_draft_path(["--spec-type", "draft-mtp"], {}) is None
+
+ tree = _load_model_tree()
+ calls = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "_extra_args_mtp_draft_path"
+ ]
+ assert calls, "the drafter CPU pin no longer resolves a drafter path"
+ assert any(
+ {n.id for n in ast.walk(call) if isinstance(n, ast.Name)} >= {"spec_flags", "extra_args"}
+ for call in calls
+ ), "the pin still looks at spec_flags only, so a user-owned drafter is missed"
+
+
+def test_the_drafter_cpu_pin_outlives_the_pass_through_extras():
+ """llama.cpp is last-wins and the paravirtual strip covers only the main offload
+ flags, so a user -ngld 99 after a managed --spec-draft-ngl 0 would put the drafter
+ straight back on the corrupt device."""
+ assert "-ngld" not in llama_server_args._OFFLOAD_SHADOWING_FLAGS
+ assert "--spec-draft-ngl" not in llama_server_args._OFFLOAD_SHADOWING_FLAGS
+ # ...and it is not stripped as a spec flag either (the budget parses it).
+ assert "-ngld" not in llama_server_args._SPEC_FLAGS
+ # A trailing value is what wins, which is the parser behaviour being defended.
+ assert (
+ llama_cpp._extra_args_draft_offloaded_to_cpu(["--spec-draft-ngl", "0", "-ngld", "99"], {})
+ is False
+ )
+
+ tree = _load_model_tree()
+ extras_at = pin_at = None
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
+ continue
+ if node.func.attr != "extend":
+ continue
+ names = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
+ if "_emit_extra_args" in names:
+ extras_at = node.lineno
+ if "_pv_draft_cpu_pin" in names:
+ pin_at = node.lineno
+ assert extras_at is not None and pin_at is not None
+ assert pin_at > extras_at, "the drafter CPU pin is emitted before the user extras"
+
+
+# ── a projector that cannot be pinned must not be served at all ───────
+
+
+class _FakeLogger:
+ def __init__(self):
+ self.warnings: list = []
+
+ def warning(self, msg, *args):
+ self.warnings.append(msg % args if args else msg)
+
+ def info(self, msg, *args):
+ pass
+
+
+def _mmproj_gate(
+ *,
+ paravirtual: bool,
+ caps: dict,
+ is_vision: bool = True,
+ mmproj = "/p.gguf",
+):
+ """Run load_model's real projector-resolution statements and report what the launch
+ would see: (mmproj path, vision flag, warnings)."""
+ body = None
+ for node in ast.walk(_load_model_tree()):
+ stmts = getattr(node, "body", None)
+ if not isinstance(stmts, list):
+ continue
+ starts = [
+ i
+ for i, s in enumerate(stmts)
+ if isinstance(s, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == "launch_mmproj_path" for t in s.targets)
+ ]
+ ends = [
+ i
+ for i, s in enumerate(stmts)
+ if isinstance(s, ast.If) and {"is_vision", "effective_is_vision"} <= _names(s.test)
+ ]
+ if starts and ends:
+ body = stmts[starts[0] : ends[0] + 1]
+ break
+ assert body is not None, "the projector-resolution block moved out of load_model"
+ log = _FakeLogger()
+ # Seed from the real module so module-level helpers resolve, rather than re-listing
+ # them by hand and breaking when one is added.
+ scope = {
+ **vars(llama_cpp),
+ "extra_args": None,
+ "extra_args_disable_mmproj": lambda _a: False,
+ "self": types.SimpleNamespace(
+ _resolve_launch_mmproj_path = lambda **_kw: mmproj,
+ ),
+ "model_path": "/m.gguf",
+ "mmproj_path": None,
+ "_paravirtual_cpu_forced": paravirtual,
+ "server_caps": caps,
+ "is_vision": is_vision,
+ "logger": log,
+ }
+ exec(ast.unparse(ast.Module(body = body, type_ignores = [])), scope)
+ return scope["launch_mmproj_path"], scope["effective_is_vision"], log.warnings
+
+
+def test_a_projector_that_cannot_be_pinned_is_dropped():
+ """clip.cpp never reads --gpu-layers, so without --no-mmproj-offload the vision
+ encoder stays on the virtualised device. Serving image embeddings built from corrupt
+ output is the failure being prevented, so drop the projector."""
+ path, vision, warnings = _mmproj_gate(paravirtual = True, caps = {})
+ assert path is None
+ assert vision is False
+ assert any("--no-mmproj-offload" in w for w in warnings), "the reason must be named"
+ assert any("unsloth studio update" in w for w in warnings), "the fix must be named"
+
+
+def test_dropping_the_projector_does_not_double_warn():
+ """The generic "no usable mmproj" line would blame a missing projector for a
+ capability gap, so exactly one explanation reaches the user."""
+ _path, _vision, warnings = _mmproj_gate(paravirtual = True, caps = {})
+ assert len(warnings) == 1, warnings
+
+
+def test_a_pinnable_projector_survives_on_the_same_hardware():
+ """The negative that matters most: a build WITH the flag keeps vision, since
+ --no-mmproj-offload puts the encoder on the CPU where it is correct."""
+ path, vision, warnings = _mmproj_gate(
+ paravirtual = True, caps = {"supports_no_mmproj_offload": True}
+ )
+ assert path == "/p.gguf"
+ assert vision is True
+ assert warnings == []
+
+
+def test_a_real_mac_keeps_vision_on_a_build_without_the_flag():
+ """The drop is scoped to the virtualised device: an old llama.cpp on physical Apple
+ Silicon (or any non-Mac) must keep its projector on the GPU."""
+ path, vision, warnings = _mmproj_gate(paravirtual = False, caps = {})
+ assert path == "/p.gguf"
+ assert vision is True
+ assert warnings == []
+
+
+def test_a_text_only_gguf_is_unaffected_either_way():
+ """No projector to drop, so the guard must not manufacture a warning."""
+ for caps in ({}, {"supports_no_mmproj_offload": True}):
+ path, vision, warnings = _mmproj_gate(
+ paravirtual = True, caps = caps, is_vision = False, mmproj = None
+ )
+ assert path is None
+ assert vision is False
+ assert warnings == []
+
+
+def test_the_drop_precedes_everything_the_projector_feeds():
+ """launch_mmproj_path drives the --mmproj flag, the mmproj VRAM budget and the
+ audio-encoder probe, so clearing it later would launch a projector the guard believes
+ it dropped (or offer audio input that is gone)."""
+ src = _load_model_source()
+ gate_at = src.index("_pv_mmproj_unpinnable = bool(")
+ assert gate_at < src.index('cmd.extend(["--mmproj", launch_mmproj_path])')
+ assert gate_at < src.index("self._mmproj_vram_bytes(launch_mmproj_path)")
+ assert gate_at < src.index("read_mmproj_audio_capability(launch_mmproj_path)")
+ # ...and the session flag the frontend reads follows the same variable.
+ assert "self._is_vision = effective_is_vision" in src
+
+
+# ── a drafter that cannot be pinned must not be launched either ──────
+
+
+def _drafter_gate(
+ *,
+ paravirtual: bool,
+ caps: dict,
+ drafter = "/models/mtp-gemma.gguf",
+ extra_args = None,
+):
+ """Run load_model's real unpinnable-drafter statements and report what the launch
+ would see: (resolved drafter, extra args, warnings)."""
+ body = None
+ for node in ast.walk(_load_model_tree()):
+ stmts = getattr(node, "body", None)
+ if not isinstance(stmts, list):
+ continue
+ starts = [
+ i
+ for i, s in enumerate(stmts)
+ if isinstance(s, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == "_pv_draft_unpinnable" for t in s.targets)
+ ]
+ ends = [
+ i
+ for i, s in enumerate(stmts)
+ if isinstance(s, ast.If)
+ and isinstance(s.test, ast.Name)
+ and s.test.id == "_pv_draft_unpinnable"
+ ]
+ if starts and ends:
+ body = stmts[starts[0] : ends[0] + 1]
+ break
+ assert body is not None, "the unpinnable-drafter block moved out of load_model"
+ log = _FakeLogger()
+ # Seed from the real module so module-level helpers resolve, rather than re-listing
+ # them by hand and breaking when one is added.
+ scope = {
+ **vars(llama_cpp),
+ "_paravirtual_cpu_forced": paravirtual,
+ "server_caps": caps,
+ "launch_mtp_draft_path": drafter,
+ "extra_args": list(extra_args) if extra_args else extra_args,
+ "_extra_args_mtp_draft_path": llama_cpp._extra_args_mtp_draft_path,
+ "_extra_args_draft_offloaded_to_cpu": llama_cpp._extra_args_draft_offloaded_to_cpu,
+ "_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,
+ "_child_spec_env": llama_cpp._child_spec_env,
+ "strip_shadowing_flags": llama_cpp.strip_shadowing_flags,
+ # The slot restore rides in this block; 0 = nothing clamped, so it stays out of
+ # the way of the drafter cases these helpers cover.
+ "_pv_extras_clamped_slots": 0,
+ "n_parallel": 1,
+ "cmd": ["--parallel", "1"],
+ "logger": log,
+ }
+ exec(ast.unparse(ast.Module(body = body, type_ignores = [])), scope)
+ return scope["launch_mtp_draft_path"], scope["extra_args"], log.warnings
+
+
[email protected](autouse = True)
+def _no_inherited_draft_env(monkeypatch):
+ """The drafter parsers fall back to os.environ, so a stray var on the host must not
+ decide these cases."""
+ for var in (
+ "LLAMA_ARG_SPEC_DRAFT_MODEL",
+ "LLAMA_ARG_SPEC_DRAFT_HF_REPO",
+ "LLAMA_ARG_N_GPU_LAYERS_DRAFT",
+ ):
+ monkeypatch.delenv(var, raising = False)
+
+
+def test_a_drafter_that_cannot_be_pinned_is_dropped(monkeypatch):
+ """A separate drafter takes params.speculative.draft.n_gpu_layers (default -1 = auto),
+ not the main --gpu-layers, so without a draft-layer flag it runs full-offload on the
+ virtualised device."""
+ drafter, extras, warnings = _drafter_gate(paravirtual = True, caps = {})
+ assert drafter is None
+ assert any("draft-layer flag" in w for w in warnings), "the reason must be named"
+ assert any("unsloth studio update" in w for w in warnings), "the fix must be named"
+ # Dropping speculation cannot change a single emitted token:
+ # common_sampler_sample_and_accept_n pushes the TARGET model's own draw and stops at
+ # the first draft mismatch, so the warning must not claim the output was wrong.
+ assert not any("corrupt output" in w for w in warnings), warnings
+ assert any("only costs speed" in w for w in warnings), warnings
+ # An env-only drafter needs no drop: with no extras owning --spec-type the launch
+ # scrubs LLAMA_ARG_SPEC_DRAFT_*, so it never loads, and dropping anyway would strip
+ # the caller's own speculative tuning for nothing.
+ monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_MODEL", "/models/env.gguf")
+ tuning = ["--spec-draft-n-max", "6"]
+ drafter, extras, warnings = _drafter_gate(
+ paravirtual = True, caps = {}, drafter = None, extra_args = tuning
+ )
+ assert warnings == []
+ assert extras == tuning
+ # But an env drafter the extras DO keep alive still drops: their --spec-type is what
+ # stops the scrub.
+ owned = ["--spec-type", "draft-simple"]
+ drafter, _extras, warnings = _drafter_gate(
+ paravirtual = True, caps = {}, drafter = None, extra_args = owned
+ )
+ assert any("draft-layer flag" in w for w in warnings), warnings
+
+
+def test_the_drop_takes_a_user_owned_drafter_with_it():
+ """A user --spec-type makes _build_speculative_flags emit nothing, so clearing only
+ Unsloth's resolved path would leave their --model-draft on the device."""
+ extras = ["--spec-type", "draft-simple", "--model-draft", "/models/d.gguf", "--top-k", "40"]
+ drafter, out, warnings = _drafter_gate(
+ paravirtual = True, caps = {}, drafter = None, extra_args = extras
+ )
+ assert drafter is None
+ assert warnings
+ assert llama_cpp._extra_args_mtp_draft_path(out, {}) is None
+ # The spec type leaves with the model it needs, or a kept draft-simple would reach a
+ # llama-server with no draft model to serve it.
+ assert "--spec-type" not in out and "draft-simple" not in out
+ # ...and nothing else is touched.
+ assert out == ["--top-k", "40"]
+
+
+def test_a_drafter_free_spec_mode_keeps_the_speculation_it_asked_for():
+ """A sibling mtp-*.gguf on disk is not a drafter the launch loads: the user owns
+ --spec-type, so _build_speculative_flags returns before emitting --model-draft for
+ it, and n-gram speculation loads no model of its own. Dropping here would cost the
+ user the very mode they asked for (--spec-type and the ngram knobs are one strip
+ group) to protect a drafter that was never going to launch."""
+ extras = [
+ "--spec-type",
+ "ngram-mod",
+ "--spec-ngram-mod-n-max",
+ "5",
+ "--spec-ngram-mod-n-min",
+ "2",
+ "--top-k",
+ "40",
+ ]
+ drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = extras)
+ assert drafter == "/models/mtp-gemma.gguf"
+ assert out == extras
+ assert warnings == []
+
+
+def test_a_sibling_drafter_still_goes_when_unsloth_owns_the_spec_block():
+ """The negative for the case above: with no user --spec-type the resolver may emit
+ --model-draft for the sibling, so it is a real placement and still drops."""
+ drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = ["--top-k", "40"])
+ assert drafter is None
+ assert out == ["--top-k", "40"]
+ assert warnings
+
+
+def test_a_drafter_requiring_mode_still_loses_its_drafter():
+ """draft-simple/draft-eagle3 name a separate model the child really loads, so a
+ user-owned spec type is no exemption: the drafter and the type that needs it both
+ go."""
+ for mode in ("draft-simple", "draft-eagle3"):
+ extras = ["--spec-type", mode, "--model-draft", "/models/d.gguf", "--top-k", "40"]
+ drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = extras)
+ assert drafter is None
+ assert out == ["--top-k", "40"]
+ assert warnings
+
+
+def test_a_drafter_free_mode_that_names_its_own_drafter_still_drops_it():
+ """llama.cpp loads the draft model whenever its path is set, so a --model-draft
+ passed alongside ngram-mod still lands on the corrupt device. The exemption is for a
+ sibling the launch never emits, not for an explicit drafter."""
+ extras = ["--spec-type", "ngram-mod", "--model-draft", "/models/d.gguf"]
+ drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = extras)
+ assert drafter is None
+ assert llama_cpp._extra_args_mtp_draft_path(out, {}) is None
+ assert warnings
+
+
+def test_an_inherited_drafter_env_is_not_exempted_by_a_drafter_free_mode(monkeypatch):
+ """Same through the env the child reads directly: the drafter loads whatever
+ --spec-type says, so it cannot ride out the drop on the mode alone."""
+ monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_MODEL", "/models/env.gguf")
+ drafter, _out, warnings = _drafter_gate(
+ paravirtual = True,
+ caps = {},
+ drafter = None,
+ extra_args = ["--spec-type", "ngram-mod"],
+ )
+ assert drafter is None
+ assert warnings
+
+
+def test_a_real_mac_keeps_the_sibling_and_the_mode_alike():
+ """The exemption changes nothing off the virtualised device: physical Apple Silicon
+ keeps both halves."""
+ extras = ["--spec-type", "ngram-mod", "--model-draft", "/models/d.gguf"]
+ drafter, out, warnings = _drafter_gate(paravirtual = False, caps = {}, extra_args = extras)
+ assert drafter == "/models/mtp-gemma.gguf"
+ assert out == extras
+ assert warnings == []
+
+
+def test_the_env_the_child_inherits_is_dropped_too():
+ """argv cannot un-set LLAMA_ARG_SPEC_DRAFT_MODEL: llama.cpp reads it directly, and
+ appends spec types rather than replacing them, so an inherited draft-simple would
+ outlive the model just removed. The same scrub covers every Unsloth-owned spec
+ block."""
+ src = _load_model_source()
+ for var in (
+ "LLAMA_ARG_SPEC_DRAFT_MODEL",
+ "LLAMA_ARG_SPEC_DRAFT_HF_REPO",
+ "LLAMA_ARG_SPEC_TYPE",
+ # Pre-b8955 spellings, live between the launchable floor and the rename; without
+ # them the drop leaves the drafter in the child env.
+ "LLAMA_ARG_MODEL_DRAFT",
+ "LLAMA_ARG_HFD_REPO",
+ ):
+ assert (
+ var in llama_cpp._SPEC_ENV_VARS
+ ), f"{var} survives the drafter drop into the child env"
+ gate_at = src.index("for _pv_spec_var in _SPEC_ENV_VARS")
+ assert "env.pop(_pv_spec_var, None)" in src[gate_at : gate_at + 200]
+
+
+def test_a_managed_spec_block_clears_the_inherited_spec_env():
+ """Nothing Unsloth emits can undo an inherited LLAMA_ARG_SPEC_TYPE: llama.cpp applies
+ the env first and appends. So a managed non-MTP launch would still run MTP, a
+ crash-recovery replay could not drop it, and the fit never budgeted the drafter the
+ env adds; the launch clears it instead. Extras that own --spec-type keep theirs,
+ since there the two genuinely accumulate."""
+ src = _load_model_source()
+ at = src.index("for _pv_spec_var in _SPEC_ENV_VARS")
+ gate = src[src.rindex("if ", 0, at) : at]
+ assert "not _extra_args_set_spec_type(extra_args)" in gate
+ assert "_pv_draft_unpinnable" in gate
+
+
+def test_the_drafter_drop_hands_back_the_slots_it_no_longer_needs():
+ """The extras-MTP clamp cuts a multi-slot request to one. If the drop then strips
+ that very spec group the server is not speculating at all, and would serve one chat
+ at a time forever: the dedupe records the original ask, so no Apply restores it."""
+ src = _load_model_source()
+ clamp_at = src.index("_pv_extras_clamped_slots = n_parallel")
+ restore_at = src.index("n_parallel = _pv_extras_clamped_slots")
+ assert clamp_at < restore_at
+ # Restored before the spec flags are rebuilt, so the backstop can re-clamp if
+ # Unsloth's own resolution turns out to be MTP.
+ assert restore_at < src.index("spec_flags = self._build_speculative_flags(")
+ # And it only fires once the stripped extras really are non-MTP.
+ assert "not _extra_args_requests_mtp(" in src[restore_at - 400 : restore_at]
+
+
+def test_the_training_guard_sizes_the_cpu_pin_not_the_raw_request():
+ """load_model rewrites a GGUF placement to CPU here, so a guard sizing the raw Auto
+ request could refuse a chat load for VRAM it never takes."""
+ guard_src = inspect.getsource(_routes()._guard_chat_load_against_training)
+ assert "_metal_device_is_paravirtual()" in guard_src
+ assert "paravirtual_normalized_request(" in guard_src
+ # Before the manual/GGUF early return, or the rewrite could not reach it.
+ assert guard_src.index("paravirtual_normalized_request(") < guard_src.index(
+ 'gpu_memory_mode == "manual"'
+ )
+
+
+def test_a_diffusion_split_that_cannot_be_pinned_is_refused():
+ """An older shim without --ngl drops the zero-layer split, and nothing else keeps the
+ diffusion runner off Metal: cpu_only is torch.cuda only, so it reads 0 on a Mac and
+ the empty --gpu token still leaves Metal available. Refuse rather than serve output
+ that may be corrupt."""
+ src = inspect.getsource(llama_cpp.LlamaCppBackend._start_diffusion_server)
+ drop_at = src.index("not _shim_supports_ngl(shim_cmd)")
+ guard = src[drop_at : drop_at + 700]
+ assert "_metal_device_is_paravirtual()" in guard
+ assert "_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR" in guard
+ # Only the zero-layer pin: a non-zero manual split is the user's own placement.
+ assert "manual_ngl == 0" in guard
+ # And it is raised before the warning that would otherwise carry on.
+ assert guard.index("raise ValueError") < guard.index("logger.warning")
+ # The message has to say how to get out of it.
+ msg = llama_cpp._PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR
+ assert "unsloth studio update" in msg
+ assert "UNSLOTH_ALLOW_PARAVIRTUAL_METAL=1" in msg
+ # Settled above the teardown, so a refusal leaves the running server alone.
+ load_src = _load_model_source()
+ assert load_src.index("_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR") < load_src.index(
+ "self._kill_process()"
+ )
+
+
+def test_the_hf_diffusion_refusal_also_lands_above_the_teardown():
+ """The local path settled this before Phase 1, but an HF load has no gguf_path there,
+ so the refusal used to fire only after the healthy server was killed and the model
+ downloaded. The shim probe is cheap, so it gates the preflight too."""
+ src = _load_model_source()
+ probe_at = src.index("_pv_diffusion_unpinnable = bool(")
+ kill_at = src.index("self._kill_process()")
+ assert probe_at < kill_at
+ # The HF branch raises from the preflight classification, above the teardown.
+ hf_raise = src.index("if _pv_diffusion_unpinnable:\n raise ValueError(")
+ assert hf_raise < kill_at
+ # And the preflight download is reached for this case at all.
+ assert "or _pv_diffusion_unpinnable" in src[: src.index("_preflight_is_diffusion =")]
+
+
+def test_the_crash_replay_keeps_the_extras_the_caller_still_sends():
+ """The replay launches a stripped list but the caller keeps sending the original, so
+ a comparator seeing only the stripped one would reload the MTP setup that crashed."""
+ src = inspect.getsource(llama_cpp.LlamaCppBackend._maybe_recover_from_mtp_crash)
+ load_at = src.index("self.load_model(fallback)")
+ restore_at = src.index("self._requested_extra_args = (")
+ assert load_at < restore_at
+ # Only when the strip actually rewrote the list.
+ assert "if fallback_extra_args is not snapshot.extra_args:" in src
+ # Device-stripped the same way the launch records it, so both sides match.
+ assert "self._strip_device_extra_args(_ea)" in src
+
+
+def test_a_pinnable_drafter_survives_on_the_same_hardware():
+ """The negative that matters most: a build WITH a draft-layer flag keeps its drafter,
+ because --spec-draft-ngl 0 puts it on the CPU where it is correct."""
+ extras = ["--model-draft", "/models/d.gguf"]
+ drafter, out, warnings = _drafter_gate(
+ paravirtual = True,
+ caps = {"spec_draft_ngl_flag": "--spec-draft-ngl"},
+ extra_args = extras,
+ )
+ assert drafter == "/models/mtp-gemma.gguf"
+ assert out == extras
+ assert warnings == []
+ # The legacy alias is a supported build too, so it must not lose its drafter.
+ drafter, out, warnings = _drafter_gate(
+ paravirtual = True,
+ caps = {"spec_draft_ngl_flag": "--gpu-layers-draft"},
+ extra_args = extras,
+ )
+ assert drafter == "/models/mtp-gemma.gguf"
+ assert out == extras
+ assert warnings == []
+
+
+ "pin",
+ [
+ ["--spec-draft-ngl", "0"],
+ ["-ngld", "0"],
+ ["--gpu-layers-draft=0"],
+ ["--spec-draft-device", "cpu"],
+ ["--device-draft", "none"],
+ ],
+)
+def test_a_drafter_the_user_already_pinned_is_left_alone(pin):
+ """The probe only decides whether Unsloth can emit the flag. A user who passed one
+ themselves already has the drafter on the CPU, so dropping it would cost speed for
+ nothing."""
+ extras = [*pin, "--model-draft", "/models/d.gguf"]
+ drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = extras)
+ assert drafter == "/models/mtp-gemma.gguf"
+ assert out == extras
+ assert warnings == []
+ # ...and last-wins still decides: a pin the user overrode is no pin at all.
+ overridden = ["--spec-draft-ngl", "0", "-ngld", "99", "--model-draft", "/models/d.gguf"]
+ drafter, _out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = overridden)
+ assert drafter is None
+ assert warnings
+
+
+def test_a_real_mac_keeps_its_drafter():
+ """The drop is scoped to the virtualised device: physical Apple Silicon (or any
+ non-Mac) keeps the drafter on the GPU."""
+ extras = ["--spec-type", "draft-simple", "--model-draft", "/models/d.gguf"]
+ drafter, out, warnings = _drafter_gate(paravirtual = False, caps = {}, extra_args = extras)
+ assert drafter == "/models/mtp-gemma.gguf"
+ assert out == extras
+ assert warnings == []
+
+
+def test_a_load_with_no_separate_drafter_is_unaffected():
+ """Nothing to drop, so no manufactured warning and no stripping the spec group from a
+ load that never had a draft model. An embedded MTP head is exactly that case: with no
+ draft model llama.cpp skips the n_gpu_layers override, so the head already follows
+ --gpu-layers 0."""
+ for caps in ({}, {"spec_draft_ngl_flag": "--spec-draft-ngl"}):
+ extras = ["--spec-type", "draft-mtp", "--spec-draft-n-max", "2"]
+ drafter, out, warnings = _drafter_gate(
+ paravirtual = True, caps = caps, drafter = None, extra_args = extras
+ )
+ assert drafter is None
+ assert out == extras
+ assert warnings == []
+ # ...and neither is a plain text load with no extras at all.
+ drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, drafter = None)
+ assert (drafter, out, warnings) == (None, None, [])
+
+
+def test_mtp_detection_reads_every_accumulated_type():
+ """llama.cpp inserts each --spec-type rather than replacing, and applies the env
+ first, so MTP is on if ANY source names it. Reading only the last left the slot clamp
+ off for a launch that really does run MTP."""
+ f = llama_cpp._extra_args_requests_mtp
+ env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
+ assert f(["--spec-type", "ngram-mod"], env) is True
+ assert f(["--spec-type", "draft-mtp", "--spec-type", "ngram-mod"], {}) is True
+ assert f(["--spec_type=draft-mtp"], {}) is True
+ assert f([], env) is True
+ # Negatives: nothing names MTP, so nothing clamps.
+ assert f(None, {}) is False
+ assert f(["--spec-type", "ngram-mod"], {}) is False
+ assert f(["--spec-default"], {}) is False
+
+
+def test_a_diffusion_load_drops_the_drafter_state_it_inherits():
+ """The diffusion path returns before the assignment that records the drafter, and
+ only unload clears it, so a drafter from the previous load would linger and the dedupe
+ would reload a healthy diffusion server."""
+ src = _load_model_source()
+ at = src.index("self._layer_preserves_tensor_intent = False")
+ tail = src[at : at + 600]
+ assert "self._mtp_draft_path = None" in tail
+ assert "self._mtp_draft_suppressed_path = None" in tail
+ assert at < src.index("return self._start_diffusion_server(")
+
+
+def test_the_drafter_pin_covers_the_device_not_just_the_layers():
+ """common_base_params_to_speculative replaces the draft context's device list with the
+ draft one, so the main --device none never reaches it and an empty draft list leaves
+ every device visible. The layer count alone would leave the drafter on the corrupt
+ device, exactly as --gpu-layers 0 did."""
+ src = _load_model_source()
+ pin_at = src.index("_pv_draft_cpu_pin = [")
+ pin = src[pin_at : src.index("]", pin_at)]
+ assert "--device-draft" in pin
+ assert '"none"' in pin
+ # And the accounting must read that back as a CPU drafter, not a GPU one.
+ cmd = ["llama-server", "-md", "d.gguf", "--gpu-layers-draft", "0", "--device-draft", "none"]
+ assert llama_cpp._extra_args_draft_offloaded_to_cpu(cmd) is True
+ assert llama_cpp.LlamaCppBackend._cmd_has_gpu_companion(cmd, {}) is False
+
+
+def test_the_drafter_drop_precedes_the_flags_it_feeds():
+ """launch_mtp_draft_path becomes --model-draft and extra_args the pass-through tail,
+ so clearing either after _build_speculative_flags ran would launch a drafter the
+ guard believes it dropped."""
+ src = _load_model_source()
+ gate_at = src.index("_pv_draft_unpinnable = bool(")
+ assert gate_at < src.index("spec_flags = self._build_speculative_flags(")
+ assert gate_at < src.index("cmd.extend(str(a) for a in _emit_extra_args)")
+ # The CPU pin is the other half of the same decision, reachable only on a build that
+ # advertises a flag to pin with.
+ assert gate_at < src.index("_pv_draft_cpu_pin = [")
+
+
+# ── a pass-through GPU split mode must not fail the CPU-only load ────
+
+
+ "extra_args, expected",
+ [
+ # `-sm row` throws "device <X> does not support split buffers" in
+ # make_gpu_buft_list for every backend except SYCL, and that runs over
+ # model->devices before any layer is assigned, so --gpu-layers 0 does not save it.
+ # Metal is always in that list: the zero-offload mask writes only CUDA/HIP vars.
+ (["-sm", "row"], ["--split-mode", "layer"]),
+ (["--split-mode", "row"], ["--split-mode", "layer"]),
+ # `-sm tensor` throws "not implemented for architecture" for every arch
+ # llm_arch_supports_sm_tensor excludes, also independently of ngl.
+ (["--top-k", "40", "-sm", "tensor"], ["--split-mode", "layer"]),
+ (["-sm", "none"], ["--split-mode", "layer"]),
+ (["-sm=row"], ["--split-mode", "layer"]),
+ # Negatives: nothing to neutralise means no flag, so no redundant argument.
+ (None, []),
+ ([], []),
+ (["--top-k", "40"], []),
+ (["-sm", "layer"], []),
+ (["--split-mode", "LAYER"], []),
+ # Last-wins, like the parser: a user who already ends on layer is fine.
+ (["-sm", "row", "--split-mode", "layer"], []),
+ # ...and one who ends on row is not, however it started.
+ (["--split-mode", "layer", "-sm", "row"], ["--split-mode", "layer"]),
+ # --tensor-split is genuinely inert at --gpu-layers 0: llama-model.cpp computes
+ # the split points but never indexes them once act_gpu_layers is 0.
+ (["-ts", "3,1"], []),
+ (["--tensor-split", "3,1"], []),
+ ],
+)
+def test_a_pass_through_split_mode_cannot_fail_the_cpu_only_load(extra_args, expected):
+ assert llama_cpp._paravirtual_split_mode_pin(extra_args) == expected
+
+
+def test_the_split_mode_override_is_scoped_to_the_virtualised_mac():
+ """The strongest negative: a real Mac (or any non-Mac) must keep the user's row/none
+ split, so the call site is gated on the detector, not on the zero-layer placement a
+ plain Manual load also has."""
+ tree = _load_model_tree()
+ calls = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "_paravirtual_split_mode_pin"
+ ]
+ assert len(calls) == 1, "expected exactly one split-mode override call site"
+ guarded = False
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.If):
+ continue
+ # Direct body only: an unrelated enclosing `if` must not read as the guard.
+ if not any(calls[0] in ast.walk(stmt) for stmt in node.body):
+ continue
+ assert {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)} == {
+ "_paravirtual_cpu_forced"
+ }, "the split-mode override is no longer gated on the hardware alone"
+ guarded = True
+ assert guarded, "the split-mode override lost its _paravirtual_cpu_forced guard"
+
+
+def test_the_split_mode_override_outlives_the_pass_through_extras():
+ """llama.cpp is last-wins, so an override emitted before the user's extras would be
+ undone by the very flag it exists to neutralise."""
+ # Overridden, not stripped: the route's comparator compares stored extras verbatim
+ # and the UI does not round-trip the extras box, so a strip would make every later
+ # Apply a real model swap.
+ assert "-sm" not in llama_server_args._OFFLOAD_SHADOWING_FLAGS
+ assert "--split-mode" not in llama_server_args._OFFLOAD_SHADOWING_FLAGS
+ # The parser behaviour being relied on.
+ assert llama_server_args.resolve_tensor_parallel(["-sm", "tensor"], False) is True
+ assert (
+ llama_server_args.resolve_tensor_parallel(["-sm", "tensor", "--split-mode", "layer"], False)
+ is False
+ ), "the override must also clear the tensor state the zero-VRAM mask reads"
+
+ tree = _load_model_tree()
+ extras_at = pin_at = None
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
+ continue
+ if node.func.attr != "extend":
+ continue
+ names = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
+ if "_emit_extra_args" in names:
+ extras_at = node.lineno
+ if "_pv_split_mode_pin" in names:
+ pin_at = node.lineno
+ assert extras_at is not None and pin_at is not None
+ assert pin_at > extras_at, "the split-mode override is emitted before the user extras"
+
+
+# ── the MTP slot clamp must follow the flags that actually launch ─────
+
+
+def test_the_clamp_judges_the_env_the_child_will_actually_get():
+ """An inherited draft-mtp does launch MTP, but the launch scrubs it whenever Unsloth
+ owns the spec block, so the slots must survive rather than clamp for a server that
+ will not run MTP. The env counts only when the extras own --spec-type, the one case
+ it reaches the child."""
+ env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
+ # Managed block: scrubbed, so nothing to clamp for.
+ assert llama_cpp._child_spec_env([]) == {}
+ assert llama_cpp._extra_args_requests_mtp([], llama_cpp._child_spec_env([])) is False
+ # Extras own the spec type: their flags and the env accumulate and both launch.
+ extras = ["--spec-type", "ngram-mod"]
+ assert (
+ llama_cpp._extra_args_requests_mtp(extras, llama_cpp._child_spec_env(extras, env)) is True
+ )
+ src = _load_model_source()
+ assert "_child_spec_env(extra_args)" in src
+ assert "_extra_args_requests_mtp(extra_args, env = {})" not in src
+
+
+def test_the_training_guard_does_not_shrink_itself_for_mtp():
+ """The launch clamps MTP to one slot, but the guard's estimate counts only the drafter
+ file and the main KV: not the draft KV, the duplicated target context under MLA, or
+ the draft compute reserve. Sizing for one slot would drop the slot KV without adding
+ those back, and a guard that under-sizes evicts the training run it protects; the
+ unclamped slots stand in for the difference."""
+ route_src = inspect.getsource(_routes())
+ assert "_extra_args_requests_mtp(llama_extra_args" not in route_src
+ # The diffusion and kv-unified clamps stay: neither drops a modelled term.
+ assert "if diffusion_kind is True:" in route_src
+ assert 'caps.get("supports_kv_unified")' in route_src
+
+
+def test_the_backstop_defers_to_a_user_owned_spec_type():
+ """_build_speculative_flags emits nothing when the user owns --spec-type, and judging
+ that empty list would fall through to the env and clamp anyway."""
+ env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
+ assert llama_cpp._extra_args_requests_mtp([], env) is True # why the guard is needed
+ assert llama_cpp._extra_args_set_spec_type(["--spec-type", "ngram-mod"]) is True
+ src = _load_model_source()
+ assert "not _extra_args_set_spec_type(extra_args)" in src
+
+
+# ── ...and give the slots back when MTP never launches ────────────────
+
+
+def _if_block(predicate, tree = None):
+ """The one `if` statement in load_model whose test satisfies `predicate`."""
+ found = [
+ node
+ for node in ast.walk(tree if tree is not None else _load_model_tree())
+ if isinstance(node, ast.If) and predicate(node.test)
+ ]
+ assert len(found) == 1, f"expected exactly one matching block, found {len(found)}"
+ return found[0]
+
+
+def _names(node) -> set:
+ return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
+
+
+def _is_mtp_clamp(test) -> bool:
+ return "spec_flags" in _names(test) and "n_parallel" in _names(test)
+
+
+def _is_slot_restore(test) -> bool:
+ return "_mtp_clamped_slots" in _names(test)
+
+
+def _is_retry_spec_strip(test) -> bool:
+ return "_launch_spec_env" in _names(test)
+
+
+def _run_clamp_then_fallback(
+ *,
+ n_parallel,
+ extra_args,
+ spec_flags,
+ cmd,
+ asked_for = None,
+):
+ """Run the real clamp block, rebuild fallback_cmd the way the MTP retry does, then run
+ the real restore block. Returns the two argvs and the slot count
+ _commit_effective_parallel_slots would receive."""
+ scope = {
+ "n_parallel": n_parallel,
+ "extra_args": extra_args,
+ "spec_flags": spec_flags,
+ "cmd": list(cmd),
+ "_mtp_clamped_slots": 0,
+ "model_identifier": "owner/repo",
+ "logger": llama_cpp.logger,
+ "_extra_args_set_spec_type": llama_cpp._extra_args_set_spec_type,
+ "_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,
+ "_child_spec_env": llama_cpp._child_spec_env,
+ # The pre-fit ask, which the restore must NOT reach for.
+ "_pending_load_kwargs": {"n_parallel": n_parallel if asked_for is None else asked_for},
+ }
+ exec(ast.unparse(_if_block(_is_mtp_clamp)), scope)
+ clamped = list(scope["cmd"])
+ # The retry swaps the spec slice for --spec-default; it sits at this argv's tail.
+ spec_at = len(clamped) - len(spec_flags)
+ scope["fallback_cmd"] = clamped[:spec_at] + ["--spec-default"]
+ exec(ast.unparse(_if_block(_is_slot_restore)), scope)
+ return clamped, scope["fallback_cmd"], scope["n_parallel"]
+
+
+def _cmd(slots: int, spec_flags: list) -> list:
+ return ["llama-server", "-m", "/m.gguf", "--parallel", str(slots), "--kv-unified", *spec_flags]
+
+
+def test_the_mtp_fallback_gets_the_requested_slots_back():
+ """MTP aborts at startup and the retry drops speculative decoding entirely, so that
+ server must not inherit the single slot MTP needed. The KV fit was sized for the full
+ count."""
+ spec = ["--spec-type", "draft-mtp"]
+ clamped, fallback, slots = _run_clamp_then_fallback(
+ n_parallel = 4,
+ extra_args = ["--top-k", "40"],
+ spec_flags = spec,
+ cmd = _cmd(4, spec),
+ )
+ assert clamped[clamped.index("--parallel") + 1] == "1" # MTP itself still gets one
+ assert fallback[fallback.index("--parallel") + 1] == "4"
+ # _commit_effective_parallel_slots reads this, and /status echoes it.
+ assert slots == 4
+
+
+def test_the_startup_retry_drops_the_mtp_the_extras_and_the_env_carry():
+ """A trailing --spec-default cannot override MTP that extras or the env supplied:
+ llama.cpp applies the env first and appends types rather than replacing them, so the
+ retry would relaunch the mode that just failed and lose a main model that loads fine
+ without it. It strips the spec group, and takes the child env with it."""
+ src = _load_model_source()
+ retry = src[
+ src.index("_fb_tail = cmd[_spec_start") : src.index("fallback_cmd = cmd[:_spec_start]")
+ ]
+ assert "_extra_args_requests_mtp(extra_args, env = _launch_spec_env)" in retry
+ assert "strip_spec = True" in retry
+ assert "env.pop(_fb_spec_var, None)" in retry
+ # ...and that strip really removes the group rather than shadowing it.
+ assert llama_cpp.strip_shadowing_flags(
+ ["--spec-type", "draft-mtp", "--top-k", "40"],
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = True,
+ strip_template = False,
+ strip_split_mode = False,
+ ) == ["--top-k", "40"]
+
+
+def test_the_retry_only_hands_back_slots_no_gpu_had_to_admit():
+ """The extras clamp cuts n_parallel to 1 before the GPU slot fit, whose gate needs >1,
+ so on a GPU box that count is never admitted and restoring it would size buffers
+ nothing approved. Off GPU there is nothing to budget, so the slots come back."""
+
+ def _restored(detected_gpus):
+ scope = {
+ "cmd": ["llama-server", "--parallel", "1", "--spec-type", "draft-mtp"],
+ "_spec_start": 3,
+ "spec_flags": [],
+ "_fb_tail": ["--spec-type", "draft-mtp"],
+ "extra_args": ["--spec-type", "draft-mtp"],
+ "_launch_spec_env": {},
+ "env": {},
+ "n_parallel": 1,
+ "_pv_extras_clamped_slots": 4,
+ "_mtp_clamped_slots": 0,
+ "_detected_gpus": detected_gpus,
+ "_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,
+ "strip_shadowing_flags": llama_cpp.strip_shadowing_flags,
+ "_SPEC_ENV_VARS": llama_cpp._SPEC_ENV_VARS,
+ "logger": llama_cpp.logger,
+ }
+ exec(ast.unparse(_if_block(_is_retry_spec_strip)), scope)
+ return scope["_mtp_clamped_slots"]
+
+ assert _restored([]) == 4, "a CPU launch must get its slots back"
+ assert _restored([(0, 8 << 30)]) == 0, "a GPU launch must not restore unbudgeted slots"
+
+
+def test_the_startup_fallback_records_the_extras_it_actually_launched():
+ """The success path stores extra_args as the launched list, but the fallback launched
+ without the spec group. Leaving the MTP list there means the next Apply that omits
+ extras inherits it and repeats the crash, so only the requested state keeps it."""
+ src = _load_model_source()
+ strip_at = src.index("_fb_stripped_extras = strip_shadowing_flags(")
+ swap_at = src.index("extra_args = _fb_stripped_extras")
+ record_at = src.index("self._extra_args = (")
+ assert strip_at < swap_at < record_at, "the swap must land before the launch is recorded"
+ # The original survives as the requested state, which the comparators read.
+ kept = src[src.index("_pv_suppressed_spec_extra_args = (", swap_at - 400) : swap_at]
+ assert "list(extra_args or [])" in kept
+ # Only on a healthy retry: a failed one must not rewrite what was asked for.
+ assert src.index("_mtp_active_for_launched_server = False", 0, swap_at) < swap_at
+
+
+def test_the_extras_own_clamp_comes_back_from_the_startup_retry_too():
+ """Extras owning --spec-type park the displaced slots in _pv_extras_clamped_slots and
+ leave _mtp_clamped_slots at 0. The retry strips that MTP for real now, so a restore
+ reading only _mtp_clamped_slots would leave --parallel 1 forever: _requested_n_parallel
+ still holds the original ask, so every later identical load dedupes onto it."""
+ scope = {
+ "cmd": ["llama-server", "--parallel", "1", "--spec-type", "draft-mtp"],
+ "_spec_start": 3,
+ "spec_flags": [],
+ "_fb_tail": ["--spec-type", "draft-mtp"],
+ "extra_args": ["--spec-type", "draft-mtp"],
+ "_launch_spec_env": {},
+ "env": {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"},
+ "n_parallel": 1,
+ # What the extras clamp displaced, and what the Unsloth-resolved clamp holds.
+ "_pv_extras_clamped_slots": 4,
+ "_mtp_clamped_slots": 0,
+ "_detected_gpus": [], # CPU launch: nothing had to budget the slots
+ "_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,
+ "strip_shadowing_flags": llama_cpp.strip_shadowing_flags,
+ "_SPEC_ENV_VARS": llama_cpp._SPEC_ENV_VARS,
+ "logger": llama_cpp.logger,
+ }
+ exec(ast.unparse(_if_block(_is_retry_spec_strip)), scope)
+ assert scope["env"] == {}, "the child kept the spec env the retry dropped"
+ scope["fallback_cmd"] = ["llama-server", "--parallel", "1", "--spec-default"]
+ exec(ast.unparse(_if_block(_is_slot_restore)), scope)
+ assert scope["fallback_cmd"][scope["fallback_cmd"].index("--parallel") + 1] == "4"
+ assert scope["n_parallel"] == 4
+
+
+def test_the_fallback_gets_back_what_the_fit_sized_not_what_the_user_asked():
+ """_slots_that_fit_on_gpu can already have cut the count before the clamp, so restoring
+ the raw ask would launch a server the VRAM budget never covered."""
+ spec = ["--spec-type", "draft-mtp"]
+ _, fallback, slots = _run_clamp_then_fallback(
+ n_parallel = 4,
+ extra_args = None,
+ spec_flags = spec,
+ cmd = _cmd(4, spec),
+ asked_for = 8,
+ )
+ assert fallback[fallback.index("--parallel") + 1] == "4"
+ assert slots == 4
+
+
+def test_a_single_slot_mtp_load_stays_single_slot_on_the_fallback():
+ """The negative that matters most: nothing was clamped, so nothing is owed."""
+ spec = ["--spec-type", "draft-mtp"]
+ clamped, fallback, slots = _run_clamp_then_fallback(
+ n_parallel = 1,
+ extra_args = None,
+ spec_flags = spec,
+ cmd = _cmd(1, spec),
+ )
+ assert clamped[clamped.index("--parallel") + 1] == "1"
+ assert fallback[fallback.index("--parallel") + 1] == "1"
+ assert slots == 1
+
+
+def test_a_user_owned_spec_type_is_not_handed_slots_it_never_asked_to_lose():
+ """The pre-flight clamp already reduced this load before the KV fit, so the fit is
+ sized for one slot and the backstop never records a debt."""
+ clamped, fallback, slots = _run_clamp_then_fallback(
+ n_parallel = 1,
+ extra_args = ["--spec-type", "draft-mtp"],
+ spec_flags = [],
+ cmd = _cmd(1, []),
+ )
+ assert clamped[clamped.index("--parallel") + 1] == "1"
+ assert fallback[fallback.index("--parallel") + 1] == "1"
+ assert slots == 1
+
+
+def test_a_non_mtp_resolution_keeps_its_slots_end_to_end():
+ """No clamp, so the restore must not touch a count that was already correct."""
+ spec = ["--spec-default"]
+ clamped, fallback, slots = _run_clamp_then_fallback(
+ n_parallel = 4,
+ extra_args = None,
+ spec_flags = spec,
+ cmd = _cmd(4, spec),
+ )
+ assert clamped[clamped.index("--parallel") + 1] == "4"
+ assert fallback[fallback.index("--parallel") + 1] == "4"
+ assert slots == 4
+
+
+def test_the_restore_is_scoped_to_the_retry_that_actually_drops_mtp():
+ """A successful MTP launch, and the FA-off retry that keeps MTP, both stay at one
+ slot: the restore belongs to the --spec-default retry alone."""
+ tree = _load_model_tree()
+ restore = _if_block(_is_slot_restore, tree)
+ owners = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.If)
+ and any(restore in ast.walk(stmt) for stmt in node.body)
+ and "_spec_requested_mtp" in _names(node.test)
+ ]
+ assert len(owners) == 1, "the slot restore left the MTP-fallback branch"
+ assert "healthy" in _names(owners[0].test), "the restore must only run on a failed MTP start"
+ # ...and after the retry argv exists, or it would rewrite nothing.
+ src = _load_model_source()
+ assert src.index("fallback_cmd = cmd[:_spec_start]") < src.index("_mtp_clamped_slots > 1")
+ assert src.index("_mtp_clamped_slots > 1") < src.index("_spawn_and_wait(fallback_cmd")
+
+
+# ── a suppressed drafter must not churn the server it left healthy ───
+
+
+def _loaded_cpu_backend(monkeypatch, tmp_path):
+ """A healthy paravirtual CPU server, plus the drafter still sitting on disk."""
+ _paravirtual(monkeypatch)
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_kill_orphaned_servers", staticmethod(lambda: 0)
+ )
+ backend = llama_cpp.LlamaCppBackend()
+ backend._process = _FakeProcess()
+ backend._healthy = True
+ backend._audio_probed = True
+ backend._model_identifier = "owner/repo"
+ gguf = tmp_path / "model.gguf"
+ gguf.write_bytes(b"GGUF")
+ drafter = tmp_path / "mtp-model.gguf"
+ drafter.write_bytes(b"GGUF")
+ backend._gguf_path = str(gguf)
+ backend._requested_n_ctx = 8192
+ backend._requested_n_parallel = 1
+ backend._requested_spec_mode = "auto"
+ # What the first load on a virtualised Mac left behind.
+ backend._gpu_memory_mode = "manual"
+ backend._gpu_layers = 0
+ return backend, gguf, drafter
+
+
+def _target_state(backend, gguf, **overrides):
+ kwargs = dict(
+ model_identifier = "owner/repo",
+ gguf_path = str(gguf),
+ hf_variant = None,
+ n_ctx = 8192,
+ cache_type_kv = None,
+ speculative_type = None,
+ chat_template_override = None,
+ extra_args = None,
+ is_vision = False,
+ gpu_memory_mode = "manual",
+ gpu_layers = 0,
+ n_parallel = 1,
+ )
+ kwargs.update(overrides)
+ return backend.adopt_load_intent_if_matched(llama_cpp.GgufLoadIntent(**kwargs))
+
+
+def _gpu_pin_recorders():
+ """Every `if` in load_model that writes self._gpu_ids, in source order. load_model
+ records the pin more than once, so judging one site would miss a later overwrite."""
+ tree = _load_model_tree()
+ found = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.If)
+ and any(
+ isinstance(n, ast.Attribute) and n.attr == "_gpu_ids" and isinstance(n.ctx, ast.Store)
+ for stmt in [*node.body, *node.orelse]
+ for n in ast.walk(stmt)
+ )
+ ]
+ assert found, "no _gpu_ids recording block found in load_model"
+ # ast.walk descends into elif chains, so drop the ones that are another's else-branch:
+ # running those on their own would skip the guard that precedes them.
+ nested = {id(alt) for node in found for alt in node.orelse if isinstance(alt, ast.If)}
+ return sorted((n for n in found if id(n) not in nested), key = lambda n: n.lineno)
+
+
+def test_a_forced_cpu_launch_records_no_effective_gpu_pin():
+ """--device none means the runtime uses no GPU, so echoing the requested pick as
+ effective both misreports /status and makes clearing that pick reload a CPU server
+ already in the target state. Runs every recorder in order: the last one wins, and an
+ earlier clear is worth nothing if a later block re-assigns the request."""
+ scope = {
+ "self": types.SimpleNamespace(_gpu_ids = None, _requested_gpu_ids = None),
+ "_paravirtual_cpu_forced": True,
+ "is_vulkan_backend": False,
+ "gpu_ids": [0],
+ "gpu_indices": [0],
+ "_vulkan_pin_ids": None,
+ # The unmatched-ordinal guard clears the pin and raises; inert here.
+ "_vulkan_explicit_unmatched": False,
+ }
+ for node in _gpu_pin_recorders():
+ exec(ast.unparse(node), {}, scope)
+ assert scope["self"]._gpu_ids is None, f"recorder at line {node.lineno} re-pinned a GPU"
+ # The raw pick survives, so repeating it still dedupes; only clearing it changes.
+ backend = llama_cpp.LlamaCppBackend.__new__(llama_cpp.LlamaCppBackend)
+ backend._is_diffusion = False
+ backend._requested_gpu_ids, backend._gpu_ids = [0], None
+ assert backend.matches_gpu_ids([0]) is True
+ assert backend.matches_gpu_ids(None) is True
+
+
+def test_a_forced_cpu_diffusion_runner_records_no_effective_gpu_pin():
+ """A zero-layer split on virtualised Metal masks the child's devices, so the runner
+ uses none of them. Recording the pick anyway made /status name an unused device and
+ made clearing it reload the same CPU runner; the pick still has to round-trip."""
+ src = inspect.getsource(llama_cpp.LlamaCppBackend._start_diffusion_server)
+ assert "_pv_diffusion_cpu = manual_ngl == 0 and _metal_device_is_paravirtual()" in src
+ assert "if gpu_ids and not _pv_diffusion_cpu else None" in src
+
+ backend = llama_cpp.LlamaCppBackend.__new__(llama_cpp.LlamaCppBackend)
+ backend._is_diffusion = True
+ backend._gpu_ids, backend._requested_gpu_ids = None, [1]
+ assert backend.matches_gpu_ids([1]) is True # re-sending the pick must not reload
+ assert backend.matches_gpu_ids(None) is True # nor must clearing it
+ # A runner that really pinned a device still reloads when the pick changes.
+ backend._gpu_ids = backend._requested_gpu_ids = [1]
+ assert backend.matches_gpu_ids([0]) is False
+
+
+def test_a_real_mac_still_records_the_gpu_it_pinned(monkeypatch):
+ """The negative: on physical Apple Silicon the pick is effective and must be echoed."""
+ monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
+ backend = llama_cpp.LlamaCppBackend.__new__(llama_cpp.LlamaCppBackend)
+ backend._is_diffusion = False
+ backend._requested_gpu_ids = backend._gpu_ids = [0]
+ assert backend.matches_gpu_ids(None) is False # dropping a real pin must reload
+
+
+def test_a_suppressed_drafter_does_not_reload_the_server_it_left_healthy(monkeypatch, tmp_path):
+ """The drop clears the launched drafter, but the file stays on disk and the caller
+ keeps supplying it, so comparing against the stored None would respawn the same
+ drafter-free server on every repeat Apply."""
+ backend, gguf, drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
+ backend._mtp_draft_path = None
+ backend._mtp_draft_suppressed_path = str(drafter)
+
+ def _never(*args, **kwargs): # pragma: no cover - must never run
+ raise AssertionError("tore down a healthy server on a duplicate /load")
+
+ monkeypatch.setattr(backend, "_find_llama_server_binary", _never)
+ monkeypatch.setattr(backend, "_kill_process", _never)
+
+ assert (
+ backend.load_model(
+ llama_cpp.GgufLoadIntent(
+ model_identifier = "owner/repo",
+ gguf_path = str(gguf),
+ mtp_draft_path = str(drafter),
+ n_ctx = 8192,
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ n_parallel = 1,
+ )
+ )
+ is True
+ )
+
+
+def test_the_route_dedupe_reads_the_suppressed_drafter_too(monkeypatch, tmp_path):
+ """The route re-detects the sibling before load_model runs, so handling it on the
+ backend path alone would still reload on every Apply."""
+ from models.inference import LoadRequest
+ from routes.inference import _active_gguf_intent
+
+ # _paravirtual alone leaves the route's own binding on real hardware.
+ _paravirtual_everywhere(monkeypatch)
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_kill_orphaned_servers", staticmethod(lambda: 0)
+ )
+ gguf = tmp_path / "model.gguf"
+ gguf.write_bytes(b"GGUF")
+ drafter = tmp_path / "mtp-model.gguf"
+ drafter.write_bytes(b"GGUF")
+ backend = llama_cpp.LlamaCppBackend()
+ backend._process = _FakeProcess()
+ backend._healthy = True
+ backend._model_identifier = str(gguf)
+ backend._gguf_path = str(gguf)
+ backend._requested_n_ctx = 4096
+ backend._requested_n_parallel = 1
+ backend._mtp_draft_path = None
+ backend._mtp_draft_suppressed_path = str(drafter)
+ # What the first load on a virtualised Mac left behind, so this compares against a
+ # server that really launched under the pin.
+ backend._gpu_memory_mode = "manual"
+ backend._gpu_layers = 0
+ request = LoadRequest(model_path = str(gguf), max_seq_length = 4096)
+
+ def _intent():
+ # The route rebuilds the intent from the request, re-detecting the sibling
+ # drafter, so the dedupe has to hold on what it hands the backend.
+ return _active_gguf_intent(
+ request,
+ backend,
+ model_identifier = str(gguf),
+ chat_template_override = None,
+ n_parallel = 1,
+ native_grant_backed = False,
+ )
+
+ assert backend.adopt_load_intent_if_matched(_intent())
+ # Nothing suppressed: a drafter that genuinely appeared must still reload.
+ backend._mtp_draft_suppressed_path = None
+ assert not backend.adopt_load_intent_if_matched(_intent())
+
+
+def test_a_drafter_that_genuinely_appeared_still_reloads(monkeypatch, tmp_path):
+ """The negative that matters most: without a suppression on record, a drafter dropped
+ next to the weights must still force the reload that engages it."""
+ backend, gguf, drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
+ backend._mtp_draft_path = None
+ backend._mtp_draft_suppressed_path = None
+ assert _target_state(backend, gguf, mtp_draft_path = str(drafter)) is False
+
+
+def test_only_the_drafter_that_was_suppressed_dedupes(monkeypatch, tmp_path):
+ """A different drafter, or the suppressed one disappearing, is a real change: the fast
+ path is scoped to the exact file the load decided not to launch."""
+ backend, gguf, drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
+ backend._mtp_draft_path = None
+ backend._mtp_draft_suppressed_path = str(drafter)
+ other = tmp_path / "mtp-other.gguf"
+ other.write_bytes(b"GGUF")
+ assert _target_state(backend, gguf, mtp_draft_path = str(other)) is False
+ assert _target_state(backend, gguf, mtp_draft_path = None) is False
+ # ...and the one that was suppressed still matches.
+ assert _target_state(backend, gguf, mtp_draft_path = str(drafter)) is True
+
+
+def test_the_suppression_does_not_outlive_the_server(monkeypatch, tmp_path):
+ """Unload clears it beside the launched path: a stale record would dedupe the next
+ load of a different model, and an update (the only way to lift the suppression)
+ unloads first."""
+ backend, _gguf, drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
+ backend._mtp_draft_suppressed_path = str(drafter)
+ backend.unload_model()
+ assert backend.mtp_draft_suppressed_path is None
+
+
+def test_a_launched_drafter_records_no_suppression(monkeypatch, tmp_path):
+ """The negative on the recording side: a build that can pin the drafter launches it,
+ so nothing is suppressed and the ordinary comparison applies."""
+ backend, _gguf, _drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
+ assert backend.mtp_draft_suppressed_path is None
+ src = _load_model_source()
+ # Only the unpinnable branch records it, and it records what it is about to clear.
+ assert src.index("_pv_suppressed_draft_path = launch_mtp_draft_path") < src.index(
+ " launch_mtp_draft_path = None"
+ )
+ assert "self._mtp_draft_suppressed_path = _pv_suppressed_draft_path" in src
+
+
+# ── an inherited projector must not slip past the projector guard ────
+
+
+def _mmproj_env_scrub(*, paravirtual: bool) -> dict:
+ """Run load_model's real inherited-projector env scrub and report the child's env."""
+ block = _if_block(
+ lambda test: isinstance(test, ast.Name) and test.id == "_paravirtual_cpu_forced",
+ _mmproj_env_tree(),
+ )
+ scope = {
+ "_paravirtual_cpu_forced": paravirtual,
+ "env": {
+ "LLAMA_ARG_MMPROJ": "/inherited/proj.gguf",
+ "LLAMA_ARG_MMPROJ_URL": "https://example.invalid/proj.gguf",
+ "LLAMA_ARG_THREADS": "8",
+ },
+ }
+ exec(ast.unparse(ast.Module(body = [block], type_ignores = [])), scope)
+ return scope["env"]
+
+
+def _mmproj_env_tree() -> ast.AST:
+ """load_model's statements, narrowed to the ones mentioning _pv_mmproj_var."""
+ keep = [
+ node
+ for node in ast.walk(_load_model_tree())
+ if isinstance(node, ast.If) and "_pv_mmproj_var" in _names(node)
+ ]
+ assert keep, "the inherited-projector env scrub left load_model"
+ return ast.Module(body = keep, type_ignores = [])
+
+
+def test_an_inherited_projector_is_dropped_from_the_child_env():
+ """argv cannot un-set LLAMA_ARG_MMPROJ: llama.cpp reads it directly, so an inherited
+ projector loads on the virtualised device independently of --gpu-layers 0.
+ LLAMA_ARG_MMPROJ_URL goes with it because its download overwrites mmproj.path, so it
+ outranks even the --mmproj Unsloth emits."""
+ env = _mmproj_env_scrub(paravirtual = True)
+ assert "LLAMA_ARG_MMPROJ" not in env
+ assert "LLAMA_ARG_MMPROJ_URL" not in env
+ # ...and nothing else in the inherited env is touched here.
+ assert env == {"LLAMA_ARG_THREADS": "8"}
+
+
+def test_a_real_mac_keeps_its_inherited_projector():
+ """The scrub is scoped to the virtualised device: on physical Apple Silicon (or any
+ non-Mac) the projector runs correctly on the GPU, so a deliberate LLAMA_ARG_MMPROJ
+ must reach llama-server untouched."""
+ env = _mmproj_env_scrub(paravirtual = False)
+ assert env["LLAMA_ARG_MMPROJ"] == "/inherited/proj.gguf"
+ assert env["LLAMA_ARG_MMPROJ_URL"] == "https://example.invalid/proj.gguf"
+
+
+def test_the_env_scrub_lands_before_the_spawn():
+ """The env is built once and handed to Popen, so a scrub after the spawn would leave
+ the projector loaded on the device it just dropped."""
+ src = _load_model_source()
+ scrub = 'for _pv_mmproj_var in ("LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL")'
+ assert src.index(scrub) < src.index("_spawn_and_wait(")
+
+
+# ── one normalization, shared by the launch and both duplicate-load comparators ──
+#
+# The rewrite used to live inside load_model while the comparators judged the RAW
+# request, so a repeat identical Apply mismatched the backend's own recorded state and
+# tore down a healthy CPU server, 409-ing or cancelling an active generation. Every case
+# below carries NON-EMPTY extra_args, the blind spot that let the drafter-drop through.
+
+
+def _routes():
+ """routes/inference.py, imported lazily so the cheap AST tests do not pay for
+ FastAPI."""
+ from routes import inference as routes_inference
+ return routes_inference
+
+
+def _paravirtual_everywhere(monkeypatch):
+ """The route imports the detector by value, so patching only the llama_cpp attribute
+ would leave the route comparator on real hardware."""
+ _paravirtual(monkeypatch)
+ monkeypatch.setattr(_routes(), "_metal_device_is_paravirtual", lambda: True)
+
+
+def _real_mac_everywhere(monkeypatch):
+ monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
+ monkeypatch.setattr(_routes(), "_metal_device_is_paravirtual", lambda: False)
+
+
+def _normalized(**kwargs):
+ return llama_cpp.paravirtual_normalized_request(**kwargs)
+
+
+def test_the_normalizer_pins_every_placement_knob_to_cpu():
+ """The one definition of the rewrite: whatever came in, this is what launches."""
+ out = _normalized(
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ tensor_parallel = True,
+ tensor_split = [0.5, 0.5],
+ n_cpu_moe = 8,
+ extra_args = ["-ngl", "99", "--top-k", "40"],
+ )
+ assert out.gpu_memory_mode == "manual"
+ assert out.gpu_layers == 0
+ assert out.tensor_parallel is False
+ assert out.tensor_split is None
+ assert out.n_cpu_moe == 0
+ assert out.extra_args == ["--top-k", "40"]
+
+
+def test_the_normalizer_is_idempotent():
+ """load_model normalizes, then calls a comparator that normalizes again (and a respawn
+ replays the raw kwargs): a second pass must change nothing."""
+ once = _normalized(
+ gpu_memory_mode = "auto", gpu_layers = -1, extra_args = ["-ot", ".*=Metal", "--top-k", "40"]
+ )
+ twice = _normalized(
+ gpu_memory_mode = once.gpu_memory_mode,
+ gpu_layers = once.gpu_layers,
+ tensor_parallel = once.tensor_parallel,
+ tensor_split = once.tensor_split,
+ n_cpu_moe = once.n_cpu_moe,
+ extra_args = once.extra_args,
+ )
+ assert twice == once
+
+
+def test_the_normalizer_still_runs_for_a_request_that_already_asks_for_cpu():
+ """The severe one: the whole block used to be skipped for Manual + 0 layers, so an
+ --override-tensor in extras (never stripped by the route, and applied while choosing
+ each weight's buffer type, before any layer is assigned) put the weights straight back
+ on the corrupt device."""
+ out = _normalized(
+ gpu_memory_mode = "manual",
+ gpu_layers = 0,
+ extra_args = ["-ot", ".*=Metal", "--top-k", "40"],
+ )
+ assert out.extra_args == ["--top-k", "40"]
+
+
+def test_the_normalizer_keeps_extras_it_has_no_business_touching():
+ """The negatives: a CPU-targeted override does what this fallback does, a --split-mode
+ is neutralised at the launch instead (the comparators compare the stored list
+ verbatim), and "no opinion" must stay None, not become []."""
+ out = _normalized(extra_args = ["-ot", "exps=CPU", "-sm", "row", "--temp", "0.7"])
+ assert out.extra_args == ["-ot", "exps=CPU", "-sm", "row", "--temp", "0.7"]
+ assert _normalized(extra_args = None).extra_args is None
+ assert _normalized(extra_args = []).extra_args == []
+
+
+def test_the_launch_normalizes_a_manual_cpu_request_too(monkeypatch):
+ """End-to-end: the flags reaching the duplicate-load check are the ones that launch,
+ for a request that already said Manual + 0."""
+ _paravirtual(monkeypatch)
+ backend = llama_cpp.LlamaCppBackend()
+ seen = {}
+
+ def _capture(intent):
+ captured = asdict(intent)
+ # The intent freezes its sequences into tuples; compare on content.
+ for _key in ("extra_args", "tensor_split", "gpu_ids"):
+ if captured.get(_key) is not None:
+ captured[_key] = list(captured[_key])
+ seen.update(captured)
+ return True
+
+ monkeypatch.setattr(backend, "adopt_load_intent_if_matched", _capture)
+ monkeypatch.setattr(backend, "_apply_detected_audio", lambda _d: True)
+ backend._audio_probed = True
+ backend._healthy = True
+ backend.load_model(
+ llama_cpp.GgufLoadIntent(
+ model_identifier = "owner/repo",
+ gguf_path = "/nonexistent/model.gguf",
+ gpu_memory_mode = "manual",
+ gpu_layers = 0,
+ n_cpu_moe = 8,
+ tensor_parallel = True,
+ extra_args = ["-ot", ".*=Metal", "--top-k", "40"],
+ )
+ )
+ assert seen["extra_args"] == ["--top-k", "40"]
+ assert seen["n_cpu_moe"] == 0
+ assert seen["tensor_parallel"] is False
+ assert seen["tensor_split"] is None
+
+
+def test_a_real_mac_keeps_its_tensor_override_on_a_manual_cpu_load(monkeypatch):
+ """None of this applies to physical Apple Silicon, where a deliberate -ot must reach
+ llama-server exactly as written."""
+ monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
+ backend = llama_cpp.LlamaCppBackend()
+ seen = {}
+
+ def _capture(intent):
+ captured = asdict(intent)
+ # The intent freezes its sequences into tuples; compare on content.
+ for _key in ("extra_args", "tensor_split", "gpu_ids"):
+ if captured.get(_key) is not None:
+ captured[_key] = list(captured[_key])
+ seen.update(captured)
+ return True
+
+ monkeypatch.setattr(backend, "adopt_load_intent_if_matched", _capture)
+ monkeypatch.setattr(backend, "_apply_detected_audio", lambda _d: True)
+ backend._audio_probed = True
+ backend._healthy = True
+ backend.load_model(
+ llama_cpp.GgufLoadIntent(
+ model_identifier = "owner/repo",
+ gguf_path = "/nonexistent/model.gguf",
+ gpu_memory_mode = "manual",
+ gpu_layers = 0,
+ n_cpu_moe = 8,
+ extra_args = ["-ot", ".*=Metal", "--top-k", "40"],
+ )
+ )
+ assert seen["extra_args"] == ["-ot", ".*=Metal", "--top-k", "40"]
+ assert seen["n_cpu_moe"] == 8
+
+
+def _cpu_server(
+ monkeypatch,
+ tmp_path,
+ *,
+ launched_extras,
+ requested_extras = None,
+):
+ """A healthy paravirtual CPU server that recorded a normalized placement."""
+ monkeypatch.setattr(
+ llama_cpp.LlamaCppBackend, "_kill_orphaned_servers", staticmethod(lambda: 0)
+ )
+ backend = llama_cpp.LlamaCppBackend()
+ backend._process = _FakeProcess()
+ backend._healthy = True
+ backend._audio_probed = True
+ backend._model_identifier = "owner/repo"
+ gguf = tmp_path / "model.gguf"
+ gguf.write_bytes(b"GGUF")
+ backend._gguf_path = str(gguf)
+ backend._requested_n_ctx = 8192
+ backend._requested_n_parallel = 1
+ backend._requested_spec_mode = "auto"
+ backend._gpu_memory_mode = "manual"
+ backend._gpu_layers = 0
+ backend._n_cpu_moe = 0
+ backend._tensor_split = None
+ backend._tensor_parallel = False
+ backend._extra_args = list(launched_extras)
+ backend._requested_extra_args = list(
+ requested_extras if requested_extras is not None else launched_extras
+ )
+ backend._extra_args_source = ("owner/repo", None)
+ return backend, gguf
+
+
+def _route_matches(request, backend):
+ """What the route now does: rebuild the intent from the request, then let the single
+ backend comparator judge it. The dedupe moved off the route in #7663, so this is the
+ route-side path end to end."""
+ intent = _routes()._active_gguf_intent(
+ request,
+ backend,
+ model_identifier = "owner/repo",
+ chat_template_override = None,
+ n_parallel = 1,
+ native_grant_backed = False,
+ )
+ return backend.adopt_load_intent_if_matched(intent)
+
+
+def _load_request(gguf, **overrides):
+ from models.inference import LoadRequest
+
+ fields = dict(
+ model_path = str(gguf),
+ max_seq_length = 8192,
+ speculative_type = "auto",
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ )
+ fields.update(overrides)
+ return LoadRequest(**fields)
+
+
+def test_a_repeat_auto_request_with_extras_matches_the_cpu_server_it_left(monkeypatch, tmp_path):
+ """Both comparators. An API client, a second tab or a saved preset keeps sending Auto:
+ the browser adopting the normalized echo does not cover them, and never covers the
+ extras box, which the UI does not round-trip."""
+ _paravirtual_everywhere(monkeypatch)
+ backend, gguf = _cpu_server(monkeypatch, tmp_path, launched_extras = ["--top-k", "40"])
+ request = _load_request(
+ gguf,
+ llama_extra_args = ["-ngl", "99", "--top-k", "40"],
+ tensor_parallel = True,
+ n_cpu_moe = 8,
+ )
+ assert _route_matches(request, backend) is True
+ assert (
+ _target_state(
+ backend,
+ gguf,
+ speculative_type = "auto",
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ tensor_parallel = True,
+ n_cpu_moe = 8,
+ extra_args = ["-ngl", "99", "--top-k", "40"],
+ )
+ is True
+ )
+
+
+def test_the_same_pair_still_mismatches_on_a_real_mac(monkeypatch, tmp_path):
+ """The negative that keeps the normalization honest: off this hardware an Auto request
+ against a Manual/0 server is a genuine settings change and must reload."""
+ _real_mac_everywhere(monkeypatch)
+ backend, gguf = _cpu_server(monkeypatch, tmp_path, launched_extras = ["--top-k", "40"])
+ request = _load_request(gguf, llama_extra_args = ["--top-k", "40"])
+ assert _route_matches(request, backend) is False
+ assert (
+ _target_state(
+ backend,
+ gguf,
+ speculative_type = "auto",
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ extra_args = ["--top-k", "40"],
+ )
+ is False
+ )
+
+
+def test_a_genuinely_different_extras_box_still_reloads(monkeypatch, tmp_path):
+ """Normalizing must not swallow a real edit: only the offload family and GPU-bound
+ tensor overrides are rewritten, so a changed sampler flag is still a change."""
+ _paravirtual_everywhere(monkeypatch)
+ backend, gguf = _cpu_server(monkeypatch, tmp_path, launched_extras = ["--top-k", "40"])
+ request = _load_request(gguf, llama_extra_args = ["--top-k", "20"])
+ assert _route_matches(request, backend) is False
+ assert (
+ _target_state(
+ backend,
+ gguf,
+ speculative_type = "auto",
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ extra_args = ["--top-k", "20"],
+ )
+ is False
+ )
+
+
+def test_a_tensor_split_mode_in_extras_does_not_reload_a_cpu_server(monkeypatch, tmp_path):
+ """The pin overrides --split-mode at the launch rather than stripping it, so the stored
+ extras still say tensor while nothing tensor ever launched; judging the raw extras
+ would reload on every Apply."""
+ _paravirtual_everywhere(monkeypatch)
+ backend, gguf = _cpu_server(monkeypatch, tmp_path, launched_extras = ["-sm", "tensor"])
+ request = _load_request(gguf, llama_extra_args = ["-sm", "tensor"], tensor_parallel = True)
+ assert _route_matches(request, backend) is True
+ assert (
+ _target_state(
+ backend,
+ gguf,
+ speculative_type = "auto",
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ tensor_parallel = True,
+ extra_args = ["-sm", "tensor"],
+ )
+ is True
+ )
+
+
+def test_a_dropped_drafter_does_not_reload_over_the_extras_it_rewrote(monkeypatch, tmp_path):
+ """The drop strips the whole spec group from extra_args and stores the rewrite, but the
+ caller keeps sending its own list, so comparing launched-vs-requested mismatched on
+ every Apply and reloaded without bound."""
+ _paravirtual_everywhere(monkeypatch)
+ asked = ["--draft-max", "8", "--top-k", "40"]
+ backend, gguf = _cpu_server(
+ monkeypatch, tmp_path, launched_extras = ["--top-k", "40"], requested_extras = asked
+ )
+ request = _load_request(gguf, llama_extra_args = list(asked))
+ assert _route_matches(request, backend) is True
+ assert (
+ _target_state(
+ backend,
+ gguf,
+ speculative_type = "auto",
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ extra_args = list(asked),
+ )
+ is True
+ )
+
+
+def test_an_apply_that_inherits_the_extras_does_not_reload_the_rewritten_server(
+ monkeypatch, tmp_path
+):
+ """The browser never sends llama_extra_args, so the route inherits the LAUNCHED list and
+ the comparison would judge it against the INVOKED one. After the drafter drop those
+ differ by the whole spec group, so every Apply from the UI tore the server down."""
+ _paravirtual_everywhere(monkeypatch)
+ backend, gguf = _cpu_server(
+ monkeypatch,
+ tmp_path,
+ launched_extras = ["--top-k", "40"],
+ requested_extras = ["--draft-max", "8", "--top-k", "40"],
+ )
+ # No llama_extra_args: the inherit path the UI actually takes.
+ assert _route_matches(_load_request(gguf), backend) is True
+ # Control: an Apply that does name its extras is still judged on the invoked list.
+ assert _route_matches(_load_request(gguf, llama_extra_args = ["--top-k", "20"]), backend) is False
+ # And naming exactly the stripped list is a deliberate clear of the failed drafter,
+ # not an inherit: judging it by value would dedupe and strand the user on MTP.
+ assert _route_matches(_load_request(gguf, llama_extra_args = ["--top-k", "40"]), backend) is False
+
+
+def test_an_edited_spec_flag_still_reloads_after_a_dropped_drafter(monkeypatch, tmp_path):
+ """Requested-vs-requested must still notice a real change to the flags the drop
+ removed."""
+ _paravirtual_everywhere(monkeypatch)
+ backend, gguf = _cpu_server(
+ monkeypatch,
+ tmp_path,
+ launched_extras = ["--top-k", "40"],
+ requested_extras = ["--draft-max", "8", "--top-k", "40"],
+ )
+ request = _load_request(gguf, llama_extra_args = ["--draft-max", "4", "--top-k", "40"])
+ assert _route_matches(request, backend) is False
+ assert (
+ _target_state(
+ backend,
+ gguf,
+ speculative_type = "auto",
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ extra_args = ["--draft-max", "4", "--top-k", "40"],
+ )
+ is False
+ )
+
+
+def test_the_requested_extras_default_to_the_launched_ones():
+ """Nothing rewritten means the two records are the same list, so a load that never hits
+ the drop keeps comparing exactly what it compared before."""
+ backend = llama_cpp.LlamaCppBackend()
+ assert backend.requested_extra_args is None
+ backend._extra_args = ["--top-k", "40"]
+ assert backend.requested_extra_args == ["--top-k", "40"]
+ backend._requested_extra_args = ["--draft-max", "8", "--top-k", "40"]
+ assert backend.requested_extra_args == ["--draft-max", "8", "--top-k", "40"]
+ # A copy, like extra_args: a caller mutating the result must not edit state.
+ backend.requested_extra_args.append("--temp")
+ assert backend.requested_extra_args == ["--draft-max", "8", "--top-k", "40"]
+
+
+def test_the_drop_records_the_requested_extras_before_rewriting_them():
+ """The recording contract, mirroring _pv_suppressed_draft_path: capture, then strip."""
+ src = _load_model_source()
+ assert src.index("_pv_suppressed_spec_extra_args = list(extra_args)") < src.index(
+ " strip_spec = True,"
+ )
+ assert "self._requested_extra_args = (" in src
+
+
+def _restore_requested_spec_mode(*, requested_extras):
+ """Run load_model's real spec-mode restore against a backend whose
+ _build_speculative_flags already judged the stripped list."""
+ block = _if_block(
+ lambda test: "_pv_suppressed_spec_extra_args" in _names(test),
+ )
+ backend = llama_cpp.LlamaCppBackend()
+ backend._requested_spec_mode = "auto"
+ scope = {
+ "self": backend,
+ "_pv_suppressed_spec_extra_args": requested_extras,
+ "_extra_args_set_spec_type": llama_cpp._extra_args_set_spec_type,
+ }
+ exec(ast.unparse(ast.Module(body = [block], type_ignores = [])), scope)
+ return backend._requested_spec_mode
+
+
+def test_a_user_owned_spec_type_survives_the_drafter_drop():
+ """The drop removed --spec-type before _build_speculative_flags saw the list, so the
+ backend recorded "auto" while the caller's extras still mean "the user owns it"
+ (None), and the spec-mode compare mismatched forever."""
+ assert (
+ _restore_requested_spec_mode(
+ requested_extras = ["--spec-type", "draft-simple", "--model-draft", "/m/d.gguf"]
+ )
+ is None
+ )
+
+
+def test_the_restore_is_scoped_to_a_drop_that_owned_spec_type():
+ """No drop, or a drop whose extras never set --spec-type, must leave the mode
+ _build_speculative_flags resolved exactly as it is."""
+ assert _restore_requested_spec_mode(requested_extras = None) == "auto"
+ assert _restore_requested_spec_mode(requested_extras = ["--draft-max", "8"]) == "auto"
+
+
+def test_the_route_really_can_deliver_a_manual_cpu_request_carrying_an_override():
+ """The reachability leg for the block above: manual mode owns the offload flags at the
+ route, but that strip is the --gpu-layers family only. An -ot survives it untouched
+ and parse_gpu_layers_override reads nothing from it, so the request arrives as Manual
+ + 0 with a GPU-bound override still in the extras. (An -ngl cannot: the route
+ translates it into gpu_layers first.)"""
+ extras = ["-ot", ".*=Metal", "--top-k", "40"]
+ assert llama_server_args.parse_gpu_layers_override(extras) is None
+ assert (
+ llama_server_args.strip_shadowing_flags(
+ extras,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = False,
+ strip_template = False,
+ strip_split_mode = False,
+ strip_tensor_split = True,
+ strip_offload = True,
+ )
+ == extras
+ )
diff --git a/studio/backend/tests/test_mtp_vram_budget.py b/studio/backend/tests/test_mtp_vram_budget.py
index 4074220c6e5..79e997f4b27 100644
--- a/studio/backend/tests/test_mtp_vram_budget.py
+++ b/studio/backend/tests/test_mtp_vram_budget.py
@@ -462,41 +462,43 @@ class TestExtraArgsMtpDetection:
assert _extra_args_requests_mtp([], env = {"LLAMA_ARG_SPEC_TYPE": "none"}) is False
def test_requests_mtp_effective_spec_type(self):
- # llama.cpp uses the LAST CLI --spec-type and ignores the env when any CLI
- # --spec-type is present. The reserve must track that effective value, not
- # any earlier/MTP-ish one, or it over-reserves a drafter the launch won't
- # load (Finding B).
+ # llama.cpp ACCUMULATES spec types: the env is applied first through the same
+ # handler and each --spec-type inserts at the end, so nothing later clears an
+ # earlier MTP (even --spec-type none only appends NONE) and the reserve has to
+ # count every source.
env_mtp = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
- # Later CLI value overrides an earlier MTP one (last-wins).
assert (
_extra_args_requests_mtp(
["--spec-type", "draft-mtp", "--spec-type", "ngram-mod"], env = {}
)
- is False
+ is True
)
- # A non-MTP CLI flag overrides a stale MTP env.
- assert _extra_args_requests_mtp(["--spec-type", "ngram-mod"], env = env_mtp) is False
- assert _extra_args_requests_mtp(["--spec-type", "none"], env = env_mtp) is False
- # A later MTP CLI value still engages.
+ 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
)
- # Same precedence for separate (draft-simple/eagle3) detection.
+ # The negative that still has to hold: no source names MTP.
+ assert _extra_args_requests_mtp(["--spec-type", "ngram-mod"], env = {}) is False
+ # Separate (draft-simple/eagle3) detection accumulates the same way: the draft
+ # model still loads, so the budget must still reserve for it.
assert (
_extra_args_requests_separate_draft(
["--spec-type", "draft-simple", "--spec-type", "ngram-mod"], env = {}
)
- is False
+ is True
)
assert (
_extra_args_requests_separate_draft(
["--spec-type", "ngram-mod"], env = {"LLAMA_ARG_SPEC_TYPE": "draft-simple"}
)
- is False
+ is True
)
+ # And the negative: ngram-* alone loads no separate model.
+ assert _extra_args_requests_separate_draft(["--spec-type", "ngram-mod"], env = {}) is False
@pytest.mark.parametrize(
"args,expected",
@@ -551,28 +553,33 @@ class TestExtraArgsMtpDetection:
# -> _user_draft_via_extras True; _env_draft_for_budget sizes the drafter.
assert _extra_args_mtp_draft_path([], env = dict(os.environ)) == "/large.gguf"
- def test_load_model_gates_env_spec_type_on_off_mode(self):
- # LLAMA_ARG_SPEC_TYPE only reaches the child when Unsloth emits no spec
- # flag (UI mode "off", no user --spec-type); otherwise the emitted
- # --spec-type/--spec-default overrides the env, so the reserve must not
- # consult it or a stale MTP env over-reserves (Finding F3). Whitespace-
- # stripped so the check survives formatter line-wrapping.
+ def test_the_fit_reads_the_env_only_when_the_extras_own_the_spec_type(self):
+ # An emitted --spec-type/--spec-default cannot override the env, since llama.cpp
+ # appends. So the launch scrubs LLAMA_ARG_SPEC_TYPE whenever Unsloth owns the
+ # spec block, and the reserve consults the env only where it still reaches the
+ # child: the extras own --spec-type, and their flags and the env accumulate.
+ # Whitespace-stripped so the check survives formatter line-wrapping.
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
- assert '_mtp_canonical=="off"' in compact # the env-reaches-child gate
+ 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
+ # The other half: the launch really does clear it for a managed block.
+ assert "ornot_extra_args_set_spec_type(extra_args):" in compact
+ assert "env.pop(_pv_spec_var,None)" in compact
- def test_spec_default_overrides_env_mtp(self):
- # --spec-default is a CLI spec flag (resolves to the model default,
- # non-MTP) that overrides a stale LLAMA_ARG_SPEC_TYPE env, so the reserve
- # must not treat it as MTP (reviewer.py R4).
+ def test_spec_default_does_not_clear_an_inherited_spec_type(self):
+ # --spec-default push_backs NGRAM_MOD rather than replacing the vector, so it
+ # cannot clear an inherited type and the reserve must still count it.
env_mtp = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
- assert _extra_args_requests_mtp(["--spec-default"], env = env_mtp) is False
+ 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 False
+ is True
)
+ # With nothing inherited it stays non-MTP and loads no separate model.
+ assert _extra_args_requests_mtp(["--spec-default"], env = {}) is False
+ assert _extra_args_requests_separate_draft(["--spec-default"], env = {}) is False
# A later --spec-type still wins over an earlier --spec-default.
assert (
_extra_args_requests_mtp(["--spec-default", "--spec-type", "draft-mtp"], env = {}) is True
@@ -581,10 +588,11 @@ class TestExtraArgsMtpDetection:
def test_load_model_drafter_budget_precedence(self):
# The budget sizes the drafter the launch actually loads: CLI extras win,
# then Unsloth's emitted mtp_draft_path (overrides LLAMA_ARG_SPEC_DRAFT_MODEL),
- # then the env drafter -- not the env before Unsloth's (reviewer.py R3).
+ # then the env drafter, and only when the env survives the launch scrub, else it
+ # reserves for a model the child never loads.
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=os.environ)" 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):
diff --git a/studio/backend/tests/test_parallel_slots_per_load.py b/studio/backend/tests/test_parallel_slots_per_load.py
index 66750b93143..3af788ad299 100644
--- a/studio/backend/tests/test_parallel_slots_per_load.py
+++ b/studio/backend/tests/test_parallel_slots_per_load.py
@@ -426,6 +426,7 @@ def _guard_required_gb(
n_parallel: int,
diffusion,
caps = None,
+ llama_extra_args = None,
) -> float:
"""Run the training guard over a local GGUF and return the size it budgeted."""
import routes.inference as inf
@@ -473,6 +474,7 @@ def _guard_required_gb(
request,
load_in_4bit = False,
placement = inf._LoadPlacement(None, None, False, inf._classify_diffusion_gguf(config)),
+ llama_extra_args = llama_extra_args,
n_parallel = n_parallel,
)
return seen["required_override_gb"]
@@ -516,6 +518,37 @@ def test_training_guard_sizes_every_slot_when_kv_unified_exists(monkeypatch, tmp
assert many > one
+def test_training_guard_keeps_the_asked_slots_for_an_explicit_mtp_load(monkeypatch, tmp_path):
+ # load_model does clamp MTP to a single slot, but this estimate counts only the
+ # drafter file and the main KV: not the draft KV, the duplicated target context MLA
+ # keeps, or the draft compute reserve. Sizing for one slot would drop the slot KV
+ # without adding those back, and a guard that under-sizes evicts the training run it
+ # protects, so it keeps the larger number.
+ gguf = _write_swa_gguf(tmp_path / "chat.gguf")
+ mtp = ["--spec-type", "draft-mtp"]
+ new = {"found": True, "supports_kv_unified": True}
+ one = _guard_required_gb(
+ monkeypatch, gguf, n_parallel = 1, diffusion = False, caps = new, llama_extra_args = mtp
+ )
+ many = _guard_required_gb(
+ monkeypatch, gguf, n_parallel = 8, diffusion = False, caps = new, llama_extra_args = mtp
+ )
+ assert many > one
+
+
+def test_training_guard_keeps_slots_when_the_launch_scrubs_the_mtp_env(monkeypatch, tmp_path):
+ # An inherited LLAMA_ARG_SPEC_TYPE=draft-mtp really would launch MTP, since llama.cpp
+ # appends spec types rather than replacing them. But the extras do not own
+ # --spec-type here, so the launch scrubs the env and the server runs the slots asked
+ # for; flattening the budget to one would under-size and let a load past the guard.
+ monkeypatch.setenv("LLAMA_ARG_SPEC_TYPE", "draft-mtp")
+ gguf = _write_swa_gguf(tmp_path / "chat.gguf")
+ new = {"found": True, "supports_kv_unified": True}
+ one = _guard_required_gb(monkeypatch, gguf, n_parallel = 1, diffusion = False, caps = new)
+ many = _guard_required_gb(monkeypatch, gguf, n_parallel = 8, diffusion = False, caps = new)
+ assert many > one
+
+
def test_training_guard_keeps_slots_for_an_unclassified_gguf(monkeypatch, tmp_path):
# None = inconclusive header, so keep the larger estimate rather than
# under-size against training.
diff --git a/studio/backend/tests/test_tensor_parallel.py b/studio/backend/tests/test_tensor_parallel.py
index e0a55f45902..cff33a6b1d0 100644
--- a/studio/backend/tests/test_tensor_parallel.py
+++ b/studio/backend/tests/test_tensor_parallel.py
@@ -457,7 +457,8 @@ def test_runtime_recovery_fires_for_user_env_mtp(monkeypatch):
def test_runtime_recovery_strips_user_mtp_extra_args(monkeypatch):
# A user --spec-type draft-mtp in extra_args must be neutralised on the reload
- # (append a last-wins --spec-default) so MTP can't re-engage and loop.
+ # so MTP can't re-engage and loop. Appending --spec-default cannot do it:
+ # llama.cpp appends spec types rather than replacing, so the flag has to go.
b = _recovery_backend()
b._last_load_intent = replace(
b._last_load_intent,
@@ -475,7 +476,8 @@ def test_runtime_recovery_strips_user_mtp_extra_args(monkeypatch):
assert b._maybe_recover_from_mtp_crash(RuntimeError()) is True
assert done.wait(timeout = 5)
assert captured["speculative_type"] == "off"
- assert captured["extra_args"][-1] == "--spec-default"
+ assert "--spec-type" not in captured["extra_args"]
+ assert "draft-mtp" not in captured["extra_args"]
def test_runtime_recovery_restores_requested_mode(monkeypatch):
diff --git a/studio/backend/tests/test_tp_vision_regression.py b/studio/backend/tests/test_tp_vision_regression.py
index 7e5668ef4b1..03270c08370 100644
--- a/studio/backend/tests/test_tp_vision_regression.py
+++ b/studio/backend/tests/test_tp_vision_regression.py
@@ -143,6 +143,12 @@ _ALLOWED_TP_DROP_GUARDS = {
# launch under the CPU-only GPU mask (no visible devices) aborts the server
# instead of the intended CPU-only load (#6414).
"gpu_memory_mode == 'manual' and gpu_layers == 0",
+ # Virtualised Metal: offloaded layers return corrupt tokens, so the load is rewritten
+ # to manual/0 and nothing is left to split (no multi-GPU given up, a paravirtual Mac
+ # has one emulated device). Guarded on the hardware alone, since the rewrite applies
+ # to every request here, including one already asking for manual/0 (whose extras can
+ # still carry an --override-tensor the route does not strip).
+ "_paravirtual_cpu_forced",
}
diff --git a/tests/studio/test_diffusion_gpu_layers_contract.py b/tests/studio/test_diffusion_gpu_layers_contract.py
index bd922e91074..0329268f63b 100644
--- a/tests/studio/test_diffusion_gpu_layers_contract.py
+++ b/tests/studio/test_diffusion_gpu_layers_contract.py
@@ -43,6 +43,10 @@ def llama_cpp():
# (utils, state, models, hub, auth, storage) for every later test.
if sys.path and sys.path[0] == backend:
sys.path.pop(0)
+ # The dedupe comparators consult the Metal device, so on a Mac (and on the macos
+ # runners, which are paravirtual) they would normalize the request to the CPU pin and
+ # stop matching these fixtures. A private copy, so pinning cannot leak into the app.
+ module._metal_device_is_paravirtual = lambda: False
return module
@@ -211,6 +215,26 @@ def test_backend_dedup_compares_the_requested_split(
assert _in_target_state(llama_cpp, b, mode = mode, layers = layers) is expected
+def test_the_dedupe_compares_the_requested_split_through_the_paravirtual_rewrite():
+ """The single comparator now lives on the backend, so the diffusion split has to be
+ judged on the normalized intent: a virtualised Metal device launches the CPU-pinned
+ rewrite, and comparing the raw ask against it would reload a healthy server forever."""
+ bodies = {
+ node.name: (ast.get_source_segment(SRC, node) or "")
+ for node in ast.walk(TREE)
+ if isinstance(node, ast.FunctionDef)
+ and node.name in ("adopt_load_intent_if_matched", "_runtime_matches_intent")
+ }
+ adopt = bodies["adopt_load_intent_if_matched"]
+ assert "_metal_device_is_paravirtual()" in adopt
+ assert "paravirtual_normalized_request(" in adopt
+ # Normalized before the runtime comparison reads it, or the rewrite changes nothing.
+ assert adopt.index("paravirtual_normalized_request(") < adopt.index("_runtime_matches_intent(")
+ runtime = bodies["_runtime_matches_intent"]
+ assert "_diffusion_manual_ngl(intent.gpu_memory_mode, intent.gpu_layers)" in runtime
+ assert "self.diffusion_requested_ngl" in runtime
+
+
def test_requested_split_survives_a_shim_without_the_flag(llama_cpp):
"""gpu_layers reports what is running; diffusion_requested_ngl reports the ask."""
b = _loaded_diffusion(llama_cpp, recorded_layers = -1, requested_ngl = 20)