Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: simplify the GGUF loading backend (#7663)
oobabooga957b99429913
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 909bc42bb7c..b381df2dffe 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -25,6 +25,7 @@ import sysimport threadingimport timeimport uuid+from dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import (Callable,@@ -128,6 +129,45 @@ class _LlamaStreamCancelled(Exception):"""Internal signal for an expected client/request cancellation."""+@dataclass(frozen = True)+class GgufLoadIntent:+ """Immutable caller intent replayed by retries and recovery."""++ model_identifier: str+ gguf_path: Optional[str] = None+ mmproj_path: Optional[str] = None+ mtp_draft_path: Optional[str] = None+ hf_repo: Optional[str] = None+ hf_variant: Optional[str] = None+ hf_token: Optional[str] = None+ is_vision: bool = False+ n_ctx: int = 4096+ chat_template_override: Optional[str] = None+ cache_type_kv: Optional[str] = None+ speculative_type: Optional[str] = None+ spec_draft_n_max: Optional[int] = None+ tensor_parallel: bool = False+ gpu_memory_mode: Literal["auto", "manual"] = "auto"+ gpu_layers: int = -1+ n_cpu_moe: int = 0+ tensor_split: Optional[tuple[float, ...]] = None+ gpu_ids: Optional[tuple[int, ...]] = None+ gpu_ids_are_vulkan_ordinals: Optional[bool] = None+ n_threads: Optional[int] = None+ n_parallel: int = 1+ extra_args: Optional[tuple[str, ...]] = None+ preserve_multi_gpu_on_layer: bool = False+ compare_mtp_draft: bool = False++ def __post_init__(self):+ for key in ("tensor_split", "gpu_ids", "extra_args"):+ value = getattr(self, key)+ if value is not None:+ object.__setattr__(self, key, tuple(value))+ if self.gpu_ids == ():+ object.__setattr__(self, "gpu_ids", None)++# Shared so the from_identifier preflight and the load-time raise stay in sync.LLAMA_SERVER_NOT_FOUND_DETAIL = ("This is a GGUF model, but the llama.cpp runtime (llama-server) is not "@@ -1502,22 +1542,21 @@ def _with_gguf_load_marker(load: Callable):"""Keep an HF repo marked for the full synchronous load call."""@functools.wraps(load)- def wrapped(self, *args, **kwargs):- hf_repo = kwargs.get("hf_repo")+ def wrapped(self, intent: GgufLoadIntent):+ hf_repo = intent.hf_repowith gguf_load_in_flight(hf_repo):if hf_repo and _hub_download_blocks_gguf_load(hf_repo,- kwargs.get("hf_variant"),+ intent.hf_variant,require_mmproj = bool(- kwargs.get("is_vision")- and not extra_args_disable_mmproj(kwargs.get("extra_args"))+ intent.is_vision and not extra_args_disable_mmproj(intent.extra_args)),- hf_token = kwargs.get("hf_token"),+ hf_token = intent.hf_token,):raise RuntimeError(f"'{hf_repo}' is currently being downloaded by the download manager")- return load(self, *args, **kwargs)+ return load(self, intent)return wrapped@@ -2577,9 +2616,8 @@ class LlamaCppBackend:self._extra_args: Optional[List[str]] = Noneself._extra_args_source: Optional[tuple[str, Optional[str]]] = Noneself._requested_n_ctx: int = 0- # Raw kwargs of the last healthy load, for the MTP-crash reload. Memory-only- # (carries hf_token, never logged); single-flight via the lock below.- self._last_load_kwargs: Optional[dict] = None+ # Last healthy caller intent for crash recovery. Memory-only and never logged.+ self._last_load_intent: Optional[GgufLoadIntent] = Noneself._mtp_runtime_fallback_lock = threading.Lock()self._mtp_runtime_fallback_in_progress = False# Background watchdog so an MTP+tensor crash recovers even when no request@@ -3056,11 +3094,134 @@ class LlamaCppBackend:self._requested_gpu_ids = [sorted(int(x) for x in gpu_ids)[0]] if gpu_ids else Noneelse:self._requested_gpu_ids = sorted(int(x) for x in gpu_ids) if gpu_ids else None- if self._last_load_kwargs is not None:- self._last_load_kwargs["gpu_ids"] = (- list(self._requested_gpu_ids) if self._requested_gpu_ids else None+ if self._last_load_intent is not None:+ self._last_load_intent = replace(+ self._last_load_intent,+ gpu_ids = tuple(self._requested_gpu_ids) if self._requested_gpu_ids else None,)+ @property+ def last_load_intent(self) -> Optional[GgufLoadIntent]:+ return self._last_load_intent++ def _runtime_matches_intent(+ self, intent: GgufLoadIntent, effective_extra_args: Optional[list[str]]+ ) -> bool:+ """Whether active runtime settings satisfy one resolved caller intent."""+ if self._requested_n_ctx != int(intent.n_ctx):+ return False+ if not self._is_diffusion and self._requested_n_parallel != max(1, int(intent.n_parallel)):+ return False++ def _norm(value):+ if value is None:+ return None+ if isinstance(value, str):+ value = value.strip().lower()+ return value or None+ return value++ if _norm(self._cache_type_kv) != _norm(intent.cache_type_kv):+ return False++ extra_args = list(effective_extra_args) if effective_extra_args is not None else None+ if not _tensor_parallel_matches_loaded(+ extra_args, intent.tensor_parallel, self._tensor_parallel+ ):+ return False+ if (+ self._layer_preserves_tensor_intent+ and not _effective_tensor_parallel(extra_args, intent.tensor_parallel)+ and not intent.preserve_multi_gpu_on_layer+ ):+ return False++ if self._is_diffusion:+ requested_ngl = _diffusion_manual_ngl(intent.gpu_memory_mode, intent.gpu_layers)+ if requested_ngl != self.diffusion_requested_ngl:+ return False+ # A split dropped by an older shim still matches until the shim gains+ # --ngl support, at which point the same request should apply it.+ if (+ requested_ngl is not None+ and self._gpu_layers != requested_ngl+ and self.diffusion_split_supported()+ ):+ return False+ else:+ if self._swa_full != _swa_full_from_args_or_env(extra_args):+ return False+ if self._gpu_memory_mode != intent.gpu_memory_mode:+ return False+ if intent.gpu_memory_mode == "manual" and (+ self._gpu_layers != intent.gpu_layers+ or (+ intent.gpu_layers >= 0+ and (+ self._n_cpu_moe != intent.n_cpu_moe+ or (tuple(self._tensor_split) if self._tensor_split else None)+ != (intent.tensor_split or None)+ )+ )+ ):+ return False++ if not self.matches_gpu_ids(list(intent.gpu_ids) if intent.gpu_ids else None):+ return False++ spec_owned_by_extra_args = _extra_args_set_spec_type(extra_args)+ speculative_type = (+ None+ if spec_owned_by_extra_args+ else _canonicalize_spec_mode(intent.speculative_type) or "auto"+ )+ backend_spec = self._requested_spec_mode+ if spec_owned_by_extra_args:+ if backend_spec is not None:+ return False+ elif speculative_type != (backend_spec or "auto"):+ return False+ if (+ intent.gguf_path is None+ and self._spec_fallback_reason == "drafter_not_found"+ and speculative_type in ("auto", "mtp", "mtp+ngram")+ and not spec_owned_by_extra_args+ ):+ return False+ compared_draft_n_max = self._spec_draft_n_max+ if self._spec_fallback_reason == "runtime_error" and self._last_load_intent is not None:+ # The MTP-free recovery clears the runtime value but retains the+ # user's prior value in its intent. Only a changed value should retry MTP.+ compared_draft_n_max = self._last_load_intent.spec_draft_n_max+ if (+ (self._speculative_type == "draft-mtp" or self._spec_fallback_reason == "runtime_error")+ and intent.spec_draft_n_max is not None+ and intent.spec_draft_n_max != (compared_draft_n_max or 0)+ ):+ return False+ 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 ()):+ return False+ if (intent.gguf_path is not None or intent.compare_mtp_draft) and speculative_type in (+ "auto",+ "mtp",+ "mtp+ngram",+ ):+ try:+ 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+ )+ except OSError:+ return False+ if requested_draft != loaded_draft:+ return False+ return True+@propertydef n_layers(self) -> Optional[int]:"""Model layer count (GGUF block_count), or None if unknown."""@@ -7284,84 +7445,32 @@ class LlamaCppBackend:self._stdout_thread.start()@_with_gguf_load_marker- def load_model(- self,- *,- # Local mode: pass a path to a .gguf file- gguf_path: Optional[str] = None,- # Vision projection (mmproj) for local vision models- mmproj_path: Optional[str] = None,- # Separate MTP drafter for local Gemma loads (HF loads auto-resolve it)- mtp_draft_path: Optional[str] = None,- # HF mode: let llama-server download via -hf "repo:quant"- hf_repo: Optional[str] = None,- hf_variant: Optional[str] = None,- hf_token: Optional[str] = None,- # Common- model_identifier: str,- is_vision: bool = False,- n_ctx: int = 4096,- chat_template_override: Optional[str] = None,- cache_type_kv: Optional[str] = None,- speculative_type: Optional[str] = None,- spec_draft_n_max: Optional[int] = None,- tensor_parallel: bool = False,- gpu_memory_mode: Literal["auto", "manual"] = "auto",- gpu_layers: int = -1,- n_cpu_moe: int = 0,- tensor_split: Optional[List[float]] = None,- # Explicit GPU placement pool (issue #7164). None/[] = auto-select;- # the fitter may pin the smallest subset of this pool that fits.- gpu_ids: Optional[List[int]] = None,- gpu_ids_are_vulkan_ordinals: Optional[bool] = None,- n_threads: Optional[int] = None,- n_gpu_layers: Optional[int] = None, # caller compat, unused- n_parallel: int = 1,- extra_args: Optional[List[str]] = None,- # Route-level tensor->layer fallback retry: keep the layer split multi-GPU.- preserve_multi_gpu_on_layer: bool = False,- ) -> bool:- """Start llama-server with a GGUF model.-- Two modes:- - Local: ``gguf_path="/path/to/model.gguf"`` → uses ``-m``- - HF: ``hf_repo="...-GGUF", hf_variant="Q4_K_M"`` → uses ``-hf``-- Returns True if the server started and the health check passed.- """- # Raw load inputs so the runtime MTP-crash reload can replay this model- # without MTP. Committed to _last_load_kwargs only on a healthy load.- _pending_load_kwargs = {- "gguf_path": gguf_path,- "mmproj_path": mmproj_path,- "mtp_draft_path": mtp_draft_path,- "hf_repo": hf_repo,- "hf_variant": hf_variant,- "hf_token": hf_token,- "model_identifier": model_identifier,- "is_vision": is_vision,- "n_ctx": n_ctx,- "chat_template_override": chat_template_override,- "cache_type_kv": cache_type_kv,- "speculative_type": speculative_type,- "spec_draft_n_max": spec_draft_n_max,- "tensor_parallel": tensor_parallel,- # GPU-memory placement: replayed on respawn so a server SIGKILL'd by- # GPU/RAM pressure reloads onto the same devices with the same- # offload, not the auto defaults.- "gpu_memory_mode": gpu_memory_mode,- "gpu_layers": gpu_layers,- "n_cpu_moe": n_cpu_moe,- "tensor_split": list(tensor_split) if tensor_split is not None else None,- "gpu_ids": list(gpu_ids) if gpu_ids is not None else None,- "gpu_ids_are_vulkan_ordinals": gpu_ids_are_vulkan_ordinals,- "n_threads": n_threads,- "n_gpu_layers": n_gpu_layers,- "n_parallel": n_parallel,- "extra_args": list(extra_args) if extra_args is not None else None,- # Replayed by _respawn_if_dead so a downgraded model stays multi-GPU.- "preserve_multi_gpu_on_layer": preserve_multi_gpu_on_layer,- }+ def load_model(self, intent: GgufLoadIntent) -> bool:+ """Start llama-server from one immutable load intent."""+ gguf_path = intent.gguf_path+ mmproj_path = intent.mmproj_path+ mtp_draft_path = intent.mtp_draft_path+ hf_repo = intent.hf_repo+ hf_variant = intent.hf_variant+ hf_token = intent.hf_token+ model_identifier = intent.model_identifier+ is_vision = intent.is_vision+ n_ctx = intent.n_ctx+ chat_template_override = intent.chat_template_override+ cache_type_kv = intent.cache_type_kv+ speculative_type = intent.speculative_type+ spec_draft_n_max = intent.spec_draft_n_max+ tensor_parallel = intent.tensor_parallel+ gpu_memory_mode = intent.gpu_memory_mode+ gpu_layers = intent.gpu_layers+ n_cpu_moe = intent.n_cpu_moe+ tensor_split = list(intent.tensor_split) if intent.tensor_split is not None else None+ gpu_ids = list(intent.gpu_ids) if intent.gpu_ids is not None else None+ gpu_ids_are_vulkan_ordinals = intent.gpu_ids_are_vulkan_ordinals+ n_threads = intent.n_threads+ n_parallel = intent.n_parallel+ extra_args = list(intent.extra_args) if intent.extra_args is not None else None+ preserve_multi_gpu_on_layer = intent.preserve_multi_gpu_on_layer# Serialise the whole load so concurrent /load calls never leave two# llama-server processes alive (#5401 / #5161). Doesn't block /unload.with self._serial_load_lock:@@ -7371,27 +7480,7 @@ class LlamaCppBackend:raise RuntimeError("llama.cpp is updating; try again in a moment.")# Duplicate /load that raced past the route check: do nothing if the# live server already satisfies this request.- if self._already_in_target_state(- gguf_path = gguf_path,- mtp_draft_path = mtp_draft_path,- model_identifier = model_identifier,- hf_variant = hf_variant,- n_ctx = n_ctx,- cache_type_kv = cache_type_kv,- speculative_type = speculative_type,- spec_draft_n_max = spec_draft_n_max,- tensor_parallel = tensor_parallel,- gpu_memory_mode = gpu_memory_mode,- gpu_layers = gpu_layers,- n_cpu_moe = n_cpu_moe,- tensor_split = tensor_split,- gpu_ids = gpu_ids,- chat_template_override = chat_template_override,- extra_args = extra_args,- is_vision = is_vision,- n_parallel = n_parallel,- preserve_multi_gpu_on_layer = preserve_multi_gpu_on_layer,- ):+ if self.adopt_load_intent_if_matched(intent):logger.info(f"load_model: backend already in target state for "f"'{model_identifier}', skipping reload"@@ -9810,10 +9899,10 @@ class LlamaCppBackend: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.- self._requested_n_parallel = max(1, int(_pending_load_kwargs["n_parallel"]))+ self._requested_n_parallel = max(1, int(intent.n_parallel))# Commit the known-good snapshot + whether MTP+tensor is live, then# watch this load for a mid-generation crash.- self._last_load_kwargs = _pending_load_kwargs+ self._last_load_intent = intentself._mtp_runtime_fallback_active = _mtp_active_for_launched_serverself._start_mtp_crash_watchdog()@@ -9995,6 +10084,13 @@ class LlamaCppBackend:effective_mode = canonical_mode or "auto"self._requested_spec_mode = effective_mode+ if effective_mode == "off":+ return flags+ if effective_mode == "ngram-simple":+ flags.extend(["--spec-type", "ngram-simple"])+ self._speculative_type = "ngram-simple"+ return flags+ caps = self.probe_server_capabilities(binary)def _resolved_draft_n_max() -> int:# User override wins; else platform default (the B200 / x86@@ -10008,7 +10104,6 @@ class LlamaCppBackend:def _emit_mtp(*, chain_ngram: bool) -> bool:"""Append --spec-type mtp[/draft-mtp][,ngram-mod] + n-max."""- caps = self.probe_server_capabilities(binary)mtp_token = caps.get("mtp_token") if caps else Noneif not mtp_token:inconclusive = bool(caps.get("mtp_probe_inconclusive")) if caps else True@@ -10065,8 +10160,7 @@ class LlamaCppBackend:def _emit_ngram_mod() -> bool:"""Append --spec-type ngram-mod + flag-set knobs."""- ngram_caps = self.probe_server_capabilities(binary)- ngram_knobs = _build_ngram_mod_flags(ngram_caps)+ ngram_knobs = _build_ngram_mod_flags(caps)flags.extend(["--spec-type", "ngram-mod"])if not ngram_knobs:logger.warning(@@ -10085,66 +10179,43 @@ class LlamaCppBackend:"falling back. Check network or run `unsloth studio update`.",model_identifier,)- if self.probe_server_capabilities(binary).get("supports_ngram_mod"):+ if caps.get("supports_ngram_mod"):_emit_ngram_mod()else:flags.append("--spec-default")self._speculative_type = "default"self._spec_fallback_reason = "drafter_not_found"- if effective_mode == "off":- return flags # nothing to emit- if effective_mode == "ngram-simple":- flags.extend(["--spec-type", "ngram-simple"])- self._speculative_type = "ngram-simple"- return flagsif effective_mode == "ngram":_emit_ngram_mod()return flags- if effective_mode == "mtp":+ if effective_mode in ("mtp", "mtp+ngram"):+ chain_ngram = effective_mode == "mtp+ngram"if not is_mtp_model:- # No head and no drafter: llama-server aborts on draft-mtp- # instead of no-op'ing, so default back.- logger.warning(- "MTP requested but this GGUF has no MTP head or drafter; "- "loading without speculative decoding."- )- flags.append("--spec-default")- self._speculative_type = "default"- return flags- if _mtp_drafter_missing:- # Drafterless: draft-mtp would abort llama-server, so fall back.- _fallback_drafter_not_found()- return flags- if _mtp_too_small:- logger.warning(- f"Forcing MTP on a {_mtp_size_b:.1f}B model; "- "the bench shows draft-mtp regresses below 3B. "- "Engaging anyway (user override)."- )- _emit_mtp(chain_ngram = False)- return flags- if effective_mode == "mtp+ngram":- if not is_mtp_model:- # No head/drafter: keep the ngram half (needs no head),- # drop the draft-mtp chain that would abort the server.- logger.warning(- "MTP+Ngram requested but this GGUF has no MTP head or "- "drafter; loading ngram-mod only."- )- _emit_ngram_mod()+ if chain_ngram:+ logger.warning(+ "MTP+Ngram requested but this GGUF has no MTP head or "+ "drafter; loading ngram-mod only."+ )+ _emit_ngram_mod()+ else:+ logger.warning(+ "MTP requested but this GGUF has no MTP head or drafter; "+ "loading without speculative decoding."+ )+ flags.append("--spec-default")+ self._speculative_type = "default"return flagsif _mtp_drafter_missing:- # No head/drafter: keep ngram-mod, drop the draft-mtp chain._fallback_drafter_not_found()return flagsif _mtp_too_small:logger.warning(- f"Forcing MTP+Ngram on a {_mtp_size_b:.1f}B model; "- "the bench shows the chain regresses below 3B. "+ f"Forcing {effective_mode.upper()} on a {_mtp_size_b:.1f}B model; "+ "the bench shows MTP regresses below 3B. ""Engaging anyway (user override).")- _emit_mtp(chain_ngram = True)+ _emit_mtp(chain_ngram = chain_ngram)return flags# effective_mode == "auto": the promotion path. llama.cpp #22673:@@ -10156,8 +10227,7 @@ class LlamaCppBackend:# mtp+ngram (handled above) still engage; UNSLOTH_MLA_MTP_ENABLED=1# re-enables this promotion once upstream optimizes the path.self._spec_fallback_reason = "mla_mtp_disabled"- _mla_caps = self.probe_server_capabilities(binary)- if _mla_caps.get("supports_ngram_mod"):+ if caps.get("supports_ngram_mod"):logger.info("Auto: MLA embedded-MTP model detected; llama.cpp's MLA/DSA ""MTP path is slower than no speculation, so using ngram-mod "@@ -10184,7 +10254,7 @@ class LlamaCppBackend:# the binary supports it.if _mtp_drafter_missing:_fallback_drafter_not_found()- elif self.probe_server_capabilities(binary).get("supports_ngram_mod"):+ elif caps.get("supports_ngram_mod"):logger.info(f"MTP GGUF detected but model size {_mtp_size_b:.1f}B ""is below the 3B speedup threshold; using ngram-mod "@@ -10206,190 +10276,35 @@ class LlamaCppBackend:self._speculative_type = "default"return flags- def _already_in_target_state(- self,- *,- model_identifier: str,- hf_variant: Optional[str],- n_ctx: int,- cache_type_kv: Optional[str],- speculative_type: Optional[str],- chat_template_override: Optional[str],- extra_args: Optional[List[str]],- is_vision: bool,- gguf_path: Optional[str] = None,- spec_draft_n_max: Optional[int] = None,- tensor_parallel: bool = False,- gpu_memory_mode: Literal["auto", "manual"] = "auto",- gpu_layers: int = -1,- n_cpu_moe: int = 0,- tensor_split: Optional[List[float]] = None,- gpu_ids: Optional[List[int]] = None,- mtp_draft_path: Optional[str] = None,- n_parallel: int = 1,- preserve_multi_gpu_on_layer: bool = False,- ) -> bool:- """True iff the live server already satisfies these load kwargs.-- Mirrors ``routes/inference.py:_request_matches_loaded_settings`` but- compares raw kwargs so ``load_model`` can short-circuit a duplicate- /load that raced past the route-level check (#5401).- """- if not self.is_loaded:- return False- if (self._model_identifier or "").lower() != (model_identifier or "").lower():- return False- # Direct-file loads pass hf_variant=None while the backend stores an- # extracted filename label; compare paths to keep the guard symmetric.- if gguf_path is not None and self._gguf_path:- try:- if Path(self._gguf_path).resolve() != Path(gguf_path).resolve():- return False- except OSError:- return False- elif (self._hf_variant or "").lower() != (hf_variant or "").lower():- return False- if self._requested_n_ctx != int(n_ctx):+ def adopt_load_intent_if_matched(self, intent: GgufLoadIntent) -> bool:+ """Match live state and adopt the caller's compatible GPU placement."""+ if not self.matches_load_source(intent):return False-- def _norm(value):- if value is None:- return None- if isinstance(value, str):- stripped = value.strip().lower()- return stripped or None- return value-- if _norm(self._cache_type_kv) != _norm(cache_type_kv):- return False- # Reconcile a user --split-mode in extras AND an inherited tensor- # LLAMA_ARG_SPLIT_MODE env, but only against a server that actually- # launched tensor: if load_model downgraded to layer split it scrubbed- # the child env, so the env must not force an endless reload of a healthy- # server. An identical request would downgrade the same way.- if not _tensor_parallel_matches_loaded(extra_args, tensor_parallel, self._tensor_parallel):- return False- # Preserved tensor->layer fallback + an EXPLICIT tensor drop: reload so- # placement re-selects instead of keeping the all-GPU mask (mirrors the route,- # #6659). preserve_multi_gpu_on_layer carries the route's carry-forward decision- # (True for an implicit same-settings reload), so those still dedupe -- the HF- # auto-pick / local-dir flows skip the route guard and only reach here.- if (- self._layer_preserves_tensor_intent- and not _effective_tensor_parallel(extra_args, tensor_parallel)- and not preserve_multi_gpu_on_layer- ):- return False-- # The diffusion runner takes the layer split but ignores the MoE/split knobs, so- # only the GPU pick and the effective --ngl matter here.- if self._is_diffusion:- # Compare the EFFECTIVE split, not the raw mode: a standing manual preference- # would reload forever, while raw gpu_layers would miss that Auto(-1) and- # Unsloth mode both mean "runner default".- requested_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers)- if requested_ngl != self.diffusion_requested_ngl:- return False- # An identical ask whose split was DROPPED at launch (old shim) still dedupes,- # unless the shim has gained --ngl since (zoo upgraded mid-session), in which- # case the reload finally applies it.- if (- requested_ngl is not None- and self._gpu_layers != requested_ngl- and self.diffusion_split_supported()- ):- return False- else:- requested_extra_args = extra_args if extra_args is not None else self._extra_args- if self._swa_full != _swa_full_from_args_or_env(requested_extra_args):- return False- # A GPU-memory-mode flip (Unsloth / manual) must always reload.- if self._gpu_memory_mode != gpu_memory_mode:- return False- # Requested-vs-requested (like n_ctx): comparing the effective count- # would reload forever whenever the fitter launched fewer slots.- if self._requested_n_parallel != max(1, int(n_parallel)):- return False- # Manual: a layer-count change always reloads (covers Auto(-1) <-> a- # pinned count); MoE/split only matter with an explicit offload.- if gpu_memory_mode == "manual" and (- self._gpu_layers != gpu_layers- or (- gpu_layers >= 0- and (- self._n_cpu_moe != n_cpu_moe- or (self._tensor_split or None) != (tensor_split or None)- )- )- ):- return False- # A changed GPU pick must reload. Regular GGUF accepts either the raw- # requested placement pool or the effective status-echoed subset;- # diffusion compares its normalized single-device pick.- if not self.matches_gpu_ids(gpu_ids):- return False-- # Compare on the canonical requested mode. With --spec-type in- # extra_args the backend stores None; mirror that here.- if _extra_args_set_spec_type(extra_args):- req_mode = None- else:- req_mode = _canonicalize_spec_mode(speculative_type) or "auto"- backend_mode = self._requested_spec_mode- if req_mode != backend_mode:- return False-- # Prior HF load fell back with drafter_not_found; a same-settings reload- # must retry the download in load_model, not dedupe to the stale fallback- # (HF loads resolve the drafter there, so gguf_path is None here).- if (- self._spec_fallback_reason == "drafter_not_found"- and gguf_path is None- and req_mode in ("auto", "mtp", "mtp+ngram")- ):- return False-- # spec_draft_n_max only matters when an MTP variant is engaged. Compare- # on the resolved spec so an Auto request promoted to draft-mtp still- # bounces a reload when n_max changes.- if (- self._speculative_type == "draft-mtp"- and spec_draft_n_max is not None- and int(spec_draft_n_max) != (self._spec_draft_n_max or 0)- ):- return False-- if (self._chat_template_override or None) != (chat_template_override or None):+ effective_extra_args = (+ list(intent.extra_args) if intent.extra_args is not None else self._extra_args+ )+ candidate_extra_args = list(effective_extra_args) if effective_extra_args else []+ if intent.extra_args is not None and intent.gpu_ids is not None:+ candidate_extra_args = self._strip_device_extra_args(candidate_extra_args)+ if not self._runtime_matches_intent(intent, candidate_extra_args):return False+ self._record_matching_gpu_request(+ list(intent.gpu_ids) if intent.gpu_ids is not None else None+ )+ return True- # A drafter appearing/disappearing next to a local GGUF changes the- # launch command (--model-draft) when the mode can use it; without- # this, adding mtp-*.gguf after a load is deduped away and MTP can't- # engage short of an unload. HF loads resolve the drafter inside- # load_model (gguf_path is None here), so only local paths compare;- # the route-level probe covers HF cache repos. No sub-3B gate: both- # sides come from the same config detection, so a sub-3B mismatch- # only happens when a drafter genuinely appeared (one benign reload,- # then the stored path converges).- if (- gguf_path is not None- and req_mode in ("auto", "mtp", "mtp+ngram")- and (mtp_draft_path or None) != (self._mtp_draft_path or None)+ def matches_load_source(self, intent: GgufLoadIntent) -> bool:+ """Whether the resident model has the intent's identity and weights."""+ if not self.is_loaded or (self._model_identifier or "").lower() != (+ intent.model_identifier.lower()):return False-- # extra_args=None means "no opinion" (inherit handled at the route- # layer); only an explicit list forces equality.- if extra_args is not None:- current = list(self._extra_args) if self._extra_args is not None else []- candidate = list(extra_args)- # Compare the same device-stripped extras that load_model persisted.- if gpu_ids is not None:- candidate = self._strip_device_extra_args(candidate)- if candidate != current:+ if intent.gguf_path is not None and self._gguf_path:+ try:+ return Path(self._gguf_path).resolve() == Path(intent.gguf_path).resolve()+ except OSError:return False- self._record_matching_gpu_request(gpu_ids)- return True+ return (self._hf_variant or "").lower() == (intent.hf_variant or "").lower()def _classify_gpu_offload(self, expected_gpu: bool, detected_gpus: list[tuple[int, int]]@@ -10493,7 +10408,7 @@ class LlamaCppBackend:self._hf_repo = Noneself._mtp_draft_path = Noneself._spec_fallback_reason = None- self._last_load_kwargs = None+ self._last_load_intent = Noneself._mtp_runtime_fallback_active = Falseself._hf_variant = Noneself._is_vision = False@@ -11323,16 +11238,15 @@ class LlamaCppBackend:return False# Read before claiming: a raise after the claim strands the flag, and nothing# else clears it, blocking every later respawn.- kwargs = self._last_load_kwargs+ snapshot = self._last_load_intentproc = self._process- if not kwargs or proc is None:+ if snapshot is None or proc is None:return False# Single-flight: the first failure claims the reload.with self._mtp_runtime_fallback_lock:if self._mtp_runtime_fallback_in_progress:return Falseself._mtp_runtime_fallback_in_progress = True- snapshot = dict(kwargs)def _recover():try:@@ -11351,7 +11265,7 @@ class LlamaCppBackend:)# Re-check under the load lock (RLock allows the nested# load_model) so a newer load isn't clobbered by this stale replay.- requested_mode = snapshot.get("speculative_type")+ requested_mode = snapshot.speculative_typewith self._serial_load_lock:if self._cancel_event.is_set():logger.info("MTP-crash reload skipped: load was cancelled/unloaded.")@@ -11359,16 +11273,21 @@ class LlamaCppBackend:if self._process is not proc:logger.info("MTP-crash reload skipped: a newer load is already active.")return- if self._last_load_kwargs != snapshot:+ if self._last_load_intent != snapshot:logger.info("MTP-crash reload skipped: load settings changed.")return- snapshot["speculative_type"] = "off"# Drop user/env MTP too: append a last-wins --spec-default.- _ea = list(snapshot.get("extra_args") or [])- if _extra_args_requests_mtp(_ea, env = os.environ):- _ea.append("--spec-default")- snapshot["extra_args"] = _ea- self.load_model(**snapshot)+ 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)+ fallback = replace(+ snapshot,+ speculative_type = "off",+ extra_args = fallback_extra_args,+ )+ self.load_model(fallback)# 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)@@ -11932,8 +11851,8 @@ class LlamaCppBackend:if self._cancel_event.is_set():logger.info("Respawn skipped: the model was unloaded.")return False- kwargs = dict(self._last_load_kwargs or {})- if not kwargs:+ intent = self._last_load_intent+ if intent is None:return Falseepoch = self._unload_epochself._healthy = False@@ -11942,7 +11861,7 @@ class LlamaCppBackend:f"(code {proc.returncode}); respawning to recover the session")try:- started = bool(self.load_model(**kwargs))+ started = bool(self.load_model(intent))except Exception as exc:logger.error(f"Failed to respawn llama-server: {exc}")return Falsediff --git a/studio/backend/hub/utils/llm_assist.py b/studio/backend/hub/utils/llm_assist.pyindex 00edb204c5a..a44157bf46f 100644--- a/studio/backend/hub/utils/llm_assist.py+++ b/studio/backend/hub/utils/llm_assist.py@@ -162,18 +162,17 @@ def _run_multi_pass_advisor(variant = os.environ.get("UNSLOTH_HELPER_MODEL_VARIANT", DEFAULT_HELPER_MODEL_VARIANT)backend = Nonetry:- from core.inference.llama_cpp import LlamaCppBackend+ from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackendbackend = LlamaCppBackend()started = time.monotonic()- if not backend.load_model(+ intent = GgufLoadIntent(+ model_identifier = f"hub-advisor:{repo}:{variant}",hf_repo = repo,hf_variant = variant,- model_identifier = f"hub-advisor:{repo}:{variant}",- is_vision = False,n_ctx = 2048,- n_gpu_layers = -1,- ):+ )+ if not backend.load_model(intent):return Nonelogger.info("Hub advisor model loaded in %.1fs", time.monotonic() - started)diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex aa0ff6c9770..36296074ca2 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -454,18 +454,10 @@ class GenerateRequest(BaseModel):image_base64: Optional[str] = Field(None, description = "Base64 encoded image for vision models")-class LoadResponse(BaseModel):- """Response after loading a model"""+class _InferenceRuntimeFields(BaseModel):+ """Runtime fields shared by load and status responses."""- status: str = Field(..., description = "Load status")- model: str = Field(..., description = "Model identifier")- display_name: str = Field(..., description = "Display name of the model")is_vision: bool = Field(False, description = "Whether model is a vision model")- is_lora: bool = Field(False, description = "Whether model is a LoRA adapter")- is_gguf: bool = Field(False, description = "Whether model is a GGUF model (llama.cpp)")- is_local_model: bool = Field(- False, description = "Whether the loaded model came from a local filesystem path"- )is_diffusion: bool = Field(False, description = "Whether model is a block-diffusion model (DiffusionGemma)")@@ -479,9 +471,6 @@ class LoadResponse(BaseModel):is_audio: bool = Field(False, description = "Whether model is a TTS audio model")audio_type: Optional[str] = Field(None, description = "Audio codec type: snac, csm, bicodec, dac")has_audio_input: bool = Field(False, description = "Whether model accepts audio input (ASR)")- inference: dict = Field(- ..., description = "Inference parameters (temperature, top_p, top_k, min_p)"- )requires_trust_remote_code: bool = Field(False,description = "Whether the model defaults require trust_remote_code to be enabled for loading.",@@ -607,6 +596,22 @@ class LoadResponse(BaseModel):)+class LoadResponse(_InferenceRuntimeFields):+ """Response after loading a model"""++ status: str = Field(..., description = "Load status")+ model: str = Field(..., description = "Model identifier")+ display_name: str = Field(..., description = "Display name of the model")+ is_lora: bool = Field(False, description = "Whether model is a LoRA adapter")+ is_gguf: bool = Field(False, description = "Whether model is a GGUF model (llama.cpp)")+ is_local_model: bool = Field(+ False, description = "Whether the loaded model came from a local filesystem path"+ )+ inference: dict = Field(+ ..., description = "Inference parameters (temperature, top_p, top_k, min_p)"+ )++class UnloadResponse(BaseModel):"""Response after unloading a model"""@@ -642,7 +647,7 @@ class LoadProgressResponse(BaseModel):fraction: float = Field(0.0, description = "bytes_loaded / bytes_total, clamped to 0..1.")-class InferenceStatusResponse(BaseModel):+class InferenceStatusResponse(_InferenceRuntimeFields):"""Current inference backend status"""active_model: Optional[str] = Field(@@ -652,117 +657,20 @@ class InferenceStatusResponse(BaseModel):None,description = "Loadable identifier for the active model.",)- is_vision: bool = Field(False, description = "Whether the active model is a vision model")is_gguf: bool = Field(False, description = "Whether the active model is a GGUF model (llama.cpp)")is_local_model: bool = Field(False, description = "Whether the active model came from a local filesystem path")- is_diffusion: bool = Field(- False, description = "Whether the active model is a block-diffusion model (DiffusionGemma)"- )- diffusion_requested_ngl: Optional[int] = Field(- None,- description = "GPU-layer count the diffusion runner was ASKED for, when that differs "- "from what it applied: an unsloth_zoo shim without --ngl drops the split and runs "- "Auto, so gpu_layers reports -1 while this reports the standing request. None for "- "non-diffusion models and whenever the ask and the applied split agree.",- )gguf_variant: Optional[str] = Field(None, description = "GGUF quantization variant (e.g. Q4_K_M)")- is_audio: bool = Field(False, description = "Whether the active model is a TTS audio model")- audio_type: Optional[str] = Field(None, description = "Audio codec type: snac, csm, bicodec, dac")- has_audio_input: bool = Field(False, description = "Whether model accepts audio input (ASR)")loading: List[str] = Field(default_factory = list, description = "Models currently being loaded")loaded: List[str] = Field(default_factory = list, description = "Models currently loaded")inference: Optional[Dict[str, Any]] = Field(None, description = "Recommended inference parameters for the active model")- requires_trust_remote_code: bool = Field(- False,- description = "Whether the active model requires trust_remote_code to be enabled for loading.",- )- supports_reasoning: bool = Field(- False, description = "Whether the active model supports reasoning/thinking mode"- )- reasoning_style: Literal["enable_thinking", "reasoning_effort", "enable_thinking_effort"] = (- Field(- "enable_thinking",- description = "Reasoning control style: 'enable_thinking' (boolean), 'reasoning_effort' (low|medium|high), or 'enable_thinking_effort' (on/off gate plus an effort level, e.g. GLM-5.2 high|max)",- )- )- reasoning_effort_levels: List[str] = Field(- default_factory = list,- description = "Discrete reasoning_effort levels the template offers when reasoning_style is 'enable_thinking_effort' (e.g. ['high', 'max']); empty otherwise",- )- reasoning_always_on: bool = Field(- False, description = "Whether reasoning is always on (not toggleable)"- )- supports_preserve_thinking: bool = Field(- False,- description = "Whether the active model's template understands the optional preserve_thinking kwarg",- )- supports_tools: bool = Field(- False, description = "Whether the active model supports tool calling"- )- context_length: Optional[int] = Field(None, description = "Context length of the active model")- max_context_length: Optional[int] = Field(- None,- description = "Maximum context length currently available for the active model",- )- native_context_length: Optional[int] = Field(- None,- description = "Model's native context length from GGUF metadata (not capped by VRAM)",- )- cache_type_kv: Optional[str] = Field(- None,- description = (- "KV cache quantization dtype "- "(e.g. 'f16', 'bf16', 'q8_0', 'q4_0', 'q4_1', 'q5_0', 'q5_1', 'iq4_nl', 'f32'), "- "or None for default"- ),- )- chat_template: Optional[str] = Field(- None, description = "Model's default chat template (Jinja2 source), if any"- )chat_template_override: Optional[str] = Field(None,description = "Active chat template override applied at load time, or None if model is using its default",)- speculative_type: Optional[str] = Field(- None,- description = (- "Canonical UI-facing requested speculative decoding mode "- "('auto' / 'mtp' / 'ngram' / 'mtp+ngram' / 'off' / "- "'ngram-simple'), round-tripped from the original LoadRequest. "- "None when no model is loaded."- ),- )- spec_draft_n_max: Optional[int] = Field(- None,- description = (- "Active --spec-draft-n-max for MTP speculative decoding, or "- "None when the platform default is in effect."- ),- )- tensor_parallel: bool = Field(- False,- description = "Whether tensor-parallel split (--split-mode tensor) is active.",- )- gpu_memory_mode: Literal["auto", "manual"] = Field(- "auto",- description = "Active GPU memory strategy ('auto' or 'manual').",- )- gpu_layers: int = Field(- -1,- description = "Manual mode: requested --gpu-layers value (-1 = Auto/--fit, or when not manual).",- )- n_cpu_moe: int = Field(- 0,- description = "Manual mode: MoE expert layers pinned to CPU (--n-cpu-moe); 0 = none.",- )- tensor_split: Optional[List[float]] = Field(- None,- description = "Manual mode: relative model share per GPU (--tensor-split); None = default (split by free VRAM).",- )requested_context_length: Optional[int] = Field(None,description = (@@ -771,42 +679,6 @@ class InferenceStatusResponse(BaseModel):"context_length only exposes the resolved value. None for non-GGUF."),)- n_layers: Optional[int] = Field(- None,- description = "Model's layer count (GGUF block_count), for the manual gpu-layers ceiling.",- )- n_moe_layers: int = Field(- 0,- description = "Model's MoE expert-layer count (the n_cpu_moe ceiling); 0 if not an MoE model.",- )- gpu_ids: Optional[List[int]] = Field(- None,- description = "Effective GPU indices the model is using after fit-time narrowing, or None for automatic selection.",- )- requested_gpu_ids: Optional[List[int]] = Field(- None,- description = (- "GPU placement pool requested by the user before fit-time narrowing, "- "or None for automatic selection."- ),- )- requested_parallel_slots: Optional[int] = Field(- None,- description = (- "Parallel decode slots the active load was invoked with (per-load "- "n_parallel, else the server-wide --parallel default). None when "- "no GGUF model is loaded and for the diffusion runner, which "- "ignores --parallel."- ),- )- parallel_slots: Optional[int] = Field(- None,- description = (- "Serving slots the active llama-server actually runs (--parallel "- "after any fit-time slot reduction). None when no GGUF model is "- "loaded and for the diffusion runner, which ignores --parallel."- ),- )llama_cpp_supports_mtp: bool = Field(True,description = (diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 17d4ff35675..c7868cae728 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -14,7 +14,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request, statusfrom fastapi.encoders import jsonable_encoderfrom fastapi.responses import StreamingResponse, JSONResponse, Responsefrom starlette.requests import ClientDisconnect-from typing import Any, Callable, List, Literal, Optional, Union+from typing import Any, Callable, List, NamedTuple, Optional, Unionimport jsonimport httpxfrom loggers import get_logger@@ -22,6 +22,7 @@ import asyncioimport threadingimport weakreffrom contextlib import ExitStack+from dataclasses import replaceimport re as _re@@ -1001,14 +1002,13 @@ if str(backend_path) not in sys.path:try:from core.inference import get_inference_backendfrom core.inference.llama_cpp import (+ GgufLoadIntent,LlamaCppBackend,_DEFAULT_FIRST_TOKEN_TIMEOUT_S,_DEFAULT_MAX_TOKENS_FLOOR,_DEFAULT_STREAM_STALL_TIMEOUT_S,- _canonicalize_spec_mode,_extra_args_draft_device_pin,_extra_args_n_ubatch,- _extra_args_set_spec_type,_hf_offline_if_unreachable,_hf_offline_if_unreachable_for,_kv_bytes_per_elem,@@ -1019,7 +1019,6 @@ try:)from core.inference.llama_server_args import (_effective_tensor_parallel,- _tensor_parallel_matches_loaded,extra_args_disable_mmproj,parse_gpu_layers_override,parse_split_mode_override,@@ -1051,14 +1050,13 @@ except ImportError:sys.path.insert(0, str(parent_backend))from core.inference import get_inference_backendfrom core.inference.llama_cpp import (+ GgufLoadIntent,LlamaCppBackend,_DEFAULT_FIRST_TOKEN_TIMEOUT_S,_DEFAULT_MAX_TOKENS_FLOOR,_DEFAULT_STREAM_STALL_TIMEOUT_S,- _canonicalize_spec_mode,_extra_args_draft_device_pin,_extra_args_n_ubatch,- _extra_args_set_spec_type,_hf_offline_if_unreachable,_hf_offline_if_unreachable_for,_kv_bytes_per_elem,@@ -1069,7 +1067,6 @@ except ImportError:)from core.inference.llama_server_args import (_effective_tensor_parallel,- _tensor_parallel_matches_loaded,extra_args_disable_mmproj,parse_gpu_layers_override,parse_split_mode_override,@@ -1824,6 +1821,7 @@ async def _aiter_llama_stream_items(from models.inference import (+ _InferenceRuntimeFields,LoadRequest,UnloadRequest,TranscribeRequest,@@ -3421,26 +3419,19 @@ def _native_gguf_companion_usable(gguf_path: str | None,*,mtp_search_root: str | Path | None = None,+ log_rejection: bool = False,) -> bool:"""Whether a native load would accept this MTP drafter, as a predicate forreload dedup. Same rules, so the two cannot disagree."""try:_validate_native_mtp_drafter(companion_path, gguf_path, mtp_search_root = mtp_search_root)- except HTTPException:+ except HTTPException as exc:+ if log_rejection:+ logger.warning("Dropping MTP drafter for native load: %s", exc.detail)return Falsereturn True-def _normalise_settings_str(value: Optional[str]) -> Optional[str]:- """Lowercase + strip a settings string, mapping blank/None to None."""- if value is None:- return None- if isinstance(value, str):- stripped = value.strip().lower()- return stripped or None- return value--def _should_strip_split_mode(request: LoadRequest, backend_extra: Optional[list[str]]) -> bool:"""Whether an inherited --split-mode (and its coupled --tensor-split) shouldbe stripped on reload.@@ -3504,59 +3495,125 @@ def _is_explicit_tensor_drop(request: LoadRequest) -> bool:return override is not None and override.strip().lower() != "tensor"-def _parallel_slot_echo(llama_backend: LlamaCppBackend) -> dict:- """requested/effective parallel-slot fields for /load and /status echoes.+def _llama_runtime_fields(llama_backend: LlamaCppBackend) -> dict:+ """Runtime state shared by load, dedupe, and status; duplicates echo active settings."""+ fields = {+ name: getattr(llama_backend, name, getattr(llama_backend, f"_{name}", None))+ for name in _InferenceRuntimeFields.model_fields+ if hasattr(llama_backend, name) or hasattr(llama_backend, f"_{name}")+ }+ fields.update(+ speculative_type = llama_backend.requested_spec_mode,+ requested_parallel_slots = (+ None if llama_backend.is_diffusion else llama_backend.requested_parallel_slots+ ),+ parallel_slots = (+ None if llama_backend.is_diffusion else llama_backend.effective_parallel_slots+ ),+ )+ unresolved = (+ set(_InferenceRuntimeFields.model_fields) - fields.keys() - {"requires_trust_remote_code"}+ )+ if unresolved:+ raise AttributeError(+ f"GGUF backend is missing runtime response fields: {sorted(unresolved)}"+ )+ return fields- The diffusion runner ignores ``--parallel`` and never commits a count, so it- reports None like the non-GGUF paths; echoing the reset placeholder 1 would- fabricate an "invoked with 1 slot"."""- if llama_backend.is_diffusion:- return {"requested_parallel_slots": None, "parallel_slots": None}- return {- "requested_parallel_slots": llama_backend.requested_parallel_slots,- "parallel_slots": llama_backend.effective_parallel_slots,++def _gguf_load_response(+ llama_backend: LlamaCppBackend,+ status: str,+ model: str,+ *,+ display_name: Optional[str] = None,+ is_local_model: bool,+ inference_identifier: Optional[str] = None,+) -> LoadResponse:+ return LoadResponse(+ status = status,+ model = model,+ display_name = display_name or model,+ is_lora = False,+ is_gguf = True,+ is_local_model = is_local_model,+ inference = load_inference_config(+ inference_identifier or llama_backend.model_identifier or model+ ),+ **_llama_runtime_fields(llama_backend),+ )+++def _gguf_request_intent(+ source: GgufLoadIntent,+ request: LoadRequest,+ *,+ chat_template_override: Optional[str],+ extra_args: Optional[list[str]],+ gpu_ids: Optional[list[int]],+ n_parallel: int,+ **changes,+) -> GgufLoadIntent:+ settings = {+ name: getattr(request, name)+ for name in vars(source)+ if hasattr(request, name) and (name != "hf_token" or source.hf_repo)}+ settings.update(+ n_ctx = request.max_seq_length,+ chat_template_override = chat_template_override,+ extra_args = extra_args,+ gpu_ids = gpu_ids,+ n_parallel = n_parallel,+ )+ settings.update(changes)+ return replace(source, **settings)-def _request_matches_loaded_settings(+def _mtp_draft_for_path(+ gguf_path: Optional[str],+ native_grant_backed: bool,+ *,+ log_native_fallback: bool = False,+) -> Optional[str]:+ if not gguf_path:+ return None+ root = _local_gguf_companion_search_root(gguf_path, gguf_path)+ rejected = False+ accept = None+ if native_grant_backed:++ def accept(candidate):+ nonlocal rejected+ usable = _native_gguf_companion_usable(+ candidate,+ gguf_path,+ mtp_search_root = root,+ log_rejection = log_native_fallback,+ )+ rejected |= not usable+ return usable++ detected = detect_mtp_file(+ gguf_path,+ search_root = root,+ accept = accept,+ )+ if log_native_fallback and rejected and detected:+ logger.info("Using MTP subdirectory drafter for native load: %s", detected)+ return detected+++def _active_gguf_intent(request: LoadRequest,llama_backend: LlamaCppBackend,- effective_chat_template_override: Optional[str] = None,- requested_parallel_slots: Optional[int] = None,- native_grant_backed: bool = False,-) -> bool:- """True iff every runtime setting on the request matches the loaded server.- Caller has already checked model+variant+is_loaded. See #5401.-- ``effective_chat_template_override`` is the resolved template that will be- launched (user override, else a bundled family template such as the- gemma-4 override), so the dedup compares against what the backend actually- holds rather than the raw request field. Defaults to the request field for- callers that do not resolve a bundled override.-- ``requested_parallel_slots`` is the resolved count the load would use- (per-load ``n_parallel``, else the server-wide default); None skips it."""- # Compare requested n_ctx (not effective) so VRAM-cap doesn't mask an- # Auto-vs-explicit slider flip.- if request.max_seq_length != llama_backend.requested_n_ctx:- return False- # Requested-vs-requested for the same reason: the fitter may launch fewer- # slots. Diffusion ignores --parallel, so a change there must not reload.- if (- requested_parallel_slots is not None- and not llama_backend.is_diffusion- and int(requested_parallel_slots) != llama_backend.requested_parallel_slots- ):- return False- if _normalise_settings_str(request.cache_type_kv) != _normalise_settings_str(- llama_backend.cache_type_kv- ):- return False- # Reconcile a user --split-mode in extras into the effective tensor state.- # When the request omits llama_extra_args ("inherit"), compare using the- # stored extras stripped the way the reload strips them, so an extras-driven- # tensor load isn't seen as a mismatch that needlessly reloads the server.- backend_extra = list(llama_backend.extra_args) if llama_backend.extra_args else []+ *,+ model_identifier: str,+ chat_template_override: Optional[str],+ n_parallel: int,+ native_grant_backed: bool,+) -> GgufLoadIntent:+ backend_extra = list(llama_backend.extra_args or ())effective_extra = (request.llama_extra_argsif request.llama_extra_args is not None@@ -3567,182 +3624,31 @@ def _request_matches_loaded_settings(strip_offload = request.gpu_memory_mode == "manual",))- if not llama_backend.is_diffusion and llama_backend.swa_full != _swa_full_from_args_or_env(- effective_extra- ):- return False- if not _tensor_parallel_matches_loaded(- effective_extra, request.tensor_parallel, llama_backend.tensor_parallel- ):- return False- # The diffusion runner takes the layer split but ignores the MoE/split knobs, so only- # the GPU pick and the effective --ngl matter for it.- if llama_backend.is_diffusion:- # Compare the EFFECTIVE split, not the raw mode: a standing manual preference would- # reload forever, while raw gpu_layers would miss that Auto(-1) and Unsloth mode both- # mean "runner default". And compare against what the runner was ASKED for, not what- # it applied: without --ngl the two differ and the same request mismatches forever.- from core.inference.llama_cpp import _diffusion_manual_ngl-- loaded_ngl = llama_backend.diffusion_requested_ngl- requested_ngl = _diffusion_manual_ngl(request.gpu_memory_mode, request.gpu_layers)- if requested_ngl != loaded_ngl:- return False- # A dropped split (old shim) still dedupes, unless the shim has gained --ngl- # since (zoo upgraded mid-session). Mirrors _already_in_target_state.- if (- requested_ngl is not None- and llama_backend.gpu_layers != requested_ngl- and llama_backend.diffusion_split_supported()- ):- return False- else:- if request.gpu_memory_mode != llama_backend.gpu_memory_mode:- return False- # Manual: a layer-count change always reloads; MoE/split only matter with- # an explicit offload (gpu_layers >= 0), so a leftover value under Auto- # must not force one. Mirrors LlamaCppBackend._already_in_target_state.- if request.gpu_memory_mode == "manual" and (- request.gpu_layers != llama_backend.gpu_layers- or (- request.gpu_layers >= 0- and (- request.n_cpu_moe != llama_backend.n_cpu_moe- or (request.tensor_split or None) != (llama_backend.tensor_split or None)- )- )- ):- return False- # A regular GGUF may narrow the requested placement pool. Accept either the- # original request or the effective status-echoed subset; diffusion keeps- # its single-device normalization.- if not llama_backend.matches_gpu_ids(request.gpu_ids):- return False- # Preserved tensor->layer fallback (both report tensor=off, so the check above- # matches): if the user now explicitly drops tensor intent, reload so placement- # re-selects instead of keeping the all-GPU mask (#6659). The effective check- # includes the env, so an env-only tensor (LLAMA_ARG_SPLIT_MODE=tensor) that- # can't actually be dropped falls through to the env-downgrade match, not a loop.- if llama_backend.layer_preserves_tensor_intent and _is_explicit_tensor_drop(request):- return False- # Spec decoding works on vision models too (MTP is mmproj-compatible,- # llama.cpp #22673; the old ``not is_vision`` gate is gone), so compare- # the real requested mode -- coercing vision to ``off`` here used to- # swallow every spec-mode change on a vision model as already_loaded.- req_mode = _canonicalize_spec_mode(request.speculative_type) or "auto"- backend_mode = llama_backend.requested_spec_mode or "auto"- if req_mode != backend_mode:- return False- # Prior HF load fell back with drafter_not_found: a same-settings reload must- # retry the download, not dedupe to the stale fallback. HF only (hf_repo set);- # local/native loads have no download to retry (handled by the path compare).- if (- llama_backend.hf_repo- and llama_backend.spec_fallback_reason == "drafter_not_found"- and req_mode in ("auto", "mtp", "mtp+ngram")- and not _extra_args_set_spec_type(effective_extra)- ):- return False- # spec_draft_n_max only matters with an MTP variant; None means "platform- # default" and matches whatever the backend chose.- if backend_mode in ("mtp", "mtp+ngram") and request.spec_draft_n_max is not None:- if int(request.spec_draft_n_max) != (llama_backend.spec_draft_n_max or 0):- return False- _effective_cto = (- effective_chat_template_override- if effective_chat_template_override is not None- else request.chat_template_override+ source = llama_backend.last_load_intent or GgufLoadIntent(+ model_identifier = model_identifier,+ gguf_path = None if llama_backend.hf_repo else llama_backend.gguf_path,+ hf_repo = llama_backend.hf_repo,+ hf_variant = llama_backend.hf_variant,+ )+ return _gguf_request_intent(+ source,+ request,+ model_identifier = model_identifier,+ # A repo or directory variant has not been resolved to a file yet. Do+ # not inherit the resident file or source matching would compare that+ # file with itself and ignore a requested quant switch.+ gguf_path = source.gguf_path if model_identifier.lower().endswith(".gguf") else None,+ hf_variant = request.gguf_variant or source.hf_variant,+ chat_template_override = chat_template_override,+ extra_args = effective_extra,+ gpu_ids = request.gpu_ids,+ n_parallel = n_parallel,+ preserve_multi_gpu_on_layer = (+ llama_backend.layer_preserves_tensor_intent and not _is_explicit_tensor_drop(request)+ ),+ mtp_draft_path = _mtp_draft_for_path(llama_backend.gguf_path, native_grant_backed),+ compare_mtp_draft = True,)- if (_effective_cto or None) != (llama_backend.chat_template_override or None):- return False- # llama_extra_args=None means "inherit"; only an explicit differing list- # forces a reload. On the inherit path, refuse to match if stored extras- # contain any shadow flag, so the reload path strips them rather than- # leaving a stale override in effect. (backend_extra computed above.)- if request.llama_extra_args is None:- # Mirror the reload's conditional strips, so a preserved non-tensor mode- # (row/none/layer) isn't seen as stale and doesn't trigger a needless- # reload of a healthy server, while an inherited offload/ratio flag that- # the reload *would* strip is correctly seen as stale.- if (- backend_extra- and strip_shadowing_flags(- backend_extra,- strip_split_mode = _should_strip_split_mode(request, backend_extra),- strip_tensor_split = _should_strip_tensor_split(request),- strip_offload = request.gpu_memory_mode == "manual",- )- != backend_extra- ):- return False- else:- # Compare against the managed flags that load_model actually persisted.- _strip_dev = bool(request.gpu_ids)- _request_extra = (- strip_shadowing_flags(- request.llama_extra_args,- strip_context = False,- strip_cache = False,- strip_spec = False,- strip_template = False,- strip_split_mode = False,- strip_device = _strip_dev,- )- if _strip_dev- else list(request.llama_extra_args)- )- if _request_extra != backend_extra:- return False- # A separate drafter (Gemma's root mtp-*.gguf) appearing or disappearing- # next to the loaded weights changes the launch command (--model-draft),- # so a duplicate /load must reload rather than dedupe. Always compare the- # detected vs stored drafter when the mode can use one and the user does- # not own --spec-type: the resolved-path compare is cheap and handles all- # four cases (both None -> match; one None -> reload; equal -> match;- # different -> reload), including a drafter deleted out from under a- # running server. Runs last: it stats the filesystem, so every pure-memory- # comparison above short-circuits first. Resolve both sides since the- # stored launch path may be a snapshot symlink while detect_mtp_file- # returns the resolved blob.- if req_mode in ("auto", "mtp", "mtp+ngram") and llama_backend.gguf_path:- effective_extras = (- request.llama_extra_args- if request.llama_extra_args is not None- else llama_backend.extra_args- )- if not _extra_args_set_spec_type(effective_extras):- companion_root = _local_gguf_companion_search_root(- llama_backend.gguf_path, llama_backend.gguf_path- )- detected = detect_mtp_file(llama_backend.gguf_path, search_root = companion_root)- if native_grant_backed:- # Mirror the load path's choice, or the comparison is against a- # drafter that never launched. A native grant cannot reach a- # root drafter outside it, so the load falls back to the MTP/- # copy and, failing that, to no drafter at all. An ordinary- # load reaches the root drafter, so it keeps root-first- # detection and reloads when one appears.- def _usable(candidate: str) -> bool:- return _native_gguf_companion_usable(- candidate, llama_backend.gguf_path, mtp_search_root = companion_root- )-- if detected and not _usable(detected):- detected = detect_mtp_file(- llama_backend.gguf_path,- search_root = companion_root,- skip_root = True,- accept = _usable,- )- stored = llama_backend.mtp_draft_path- try:- detected_resolved = Path(detected).resolve() if detected else None- stored_resolved = Path(stored).resolve() if stored else None- except OSError:- return False- if detected_resolved != stored_resolved:- return False- return Truedef _resolve_model_identifier_for_request(@@ -5182,22 +5088,94 @@ async def _resolve_gguf_gpu_ids_for_request(return resolved, ids_are_vulkan_ordinals+class _LoadPlacement(NamedTuple):+ requested_gpu_ids: Optional[List[int]]+ resolved_gpu_ids: Optional[List[int]]+ gpu_ids_are_vulkan_ordinals: bool+ diffusion_kind: Optional[bool]+++def _resolve_parallel_slots(request, fastapi_request: Optional[Request]) -> int:+ if request.n_parallel is not None:+ return request.n_parallel+ state = getattr(getattr(fastapi_request, "app", None), "state", None)+ return getattr(state, "llama_parallel_slots", 1)+++async def _prepare_load_placement(+ config: ModelConfig,+ request: LoadRequest | ValidateModelRequest,+ extra_args: Optional[list[str]],+) -> _LoadPlacement:+ requested = request.gpu_ids or None+ if not config.is_gguf:+ return _LoadPlacement(requested, None, False, False)+ diffusion_kind = _classify_diffusion_gguf(config)+ resolved, is_vulkan = await _resolve_gguf_gpu_ids_for_request(+ config, requested, diffusion_kind = diffusion_kind+ )+ _reject_draft_device_with_gpu_ids(resolved, extra_args, gpu_ids_are_vulkan_ordinals = is_vulkan)+ return _LoadPlacement(requested, resolved, is_vulkan, diffusion_kind)+++def _resolve_gguf_load_intent(+ config: ModelConfig,+ request: LoadRequest,+ *,+ native_grant_backed: bool,+ chat_template_override: Optional[str],+ extra_args: Optional[list[str]],+ placement: _LoadPlacement,+ n_parallel: int,+) -> GgufLoadIntent:+ """Resolve source, companions, settings, and placement into one load value."""+ if config.gguf_hf_repo:+ source = GgufLoadIntent(+ model_identifier = config.identifier,+ hf_repo = config.gguf_hf_repo,+ hf_variant = config.gguf_variant,+ hf_token = request.hf_token,+ )+ else:+ if native_grant_backed:+ if config.gguf_mmproj_file:+ _validate_native_gguf_companion(+ config.gguf_mmproj_file, config.gguf_file, "vision companion"+ )+ if config.gguf_mtp_file:+ config.gguf_mtp_file = _mtp_draft_for_path(+ config.gguf_file,+ True,+ log_native_fallback = True,+ )+ source = GgufLoadIntent(+ model_identifier = config.identifier,+ gguf_path = config.gguf_file,+ mmproj_path = config.gguf_mmproj_file,+ mtp_draft_path = config.gguf_mtp_file,+ hf_variant = config.gguf_variant,+ )++ return _gguf_request_intent(+ source,+ request,+ chat_template_override = chat_template_override,+ extra_args = extra_args,+ gpu_ids = placement.resolved_gpu_ids,+ n_parallel = n_parallel,+ is_vision = config.is_vision,+ gpu_ids_are_vulkan_ordinals = placement.gpu_ids_are_vulkan_ordinals,+ )++def _guard_chat_load_against_training(config: ModelConfig,+ request: LoadRequest | ValidateModelRequest,*,- model_identifier: str,- hf_token: Optional[str],load_in_4bit: bool,- max_seq_length: int,- requested_gpu_ids: Optional[List[int]],+ placement: _LoadPlacement,llama_extra_args: Optional[list[str]] = None,n_parallel: int = 1,- cache_type_kv: Optional[str] = None,- tensor_parallel: bool = False,- gpu_memory_mode: Literal["auto", "manual"] = "auto",- gpu_layers: int = -1,- gpu_ids_are_vulkan_ordinals: bool = False,- diffusion_kind: Optional[bool] | object = _DIFFUSION_KIND_UNSET,) -> None:"""Protect active training from automatically placed chat-model loads.@@ -5213,6 +5191,9 @@ def _guard_chat_load_against_training(from core.training import get_training_backendfrom routes.training_vram import can_load_chat_during_training+ requested_gpu_ids = placement.requested_gpu_ids+ gpu_ids_are_vulkan_ordinals = placement.gpu_ids_are_vulkan_ordinals+ diffusion_kind = placement.diffusion_kindtry:if not get_training_backend().is_training_active():return@@ -5223,14 +5204,14 @@ def _guard_chat_load_against_training(from core.inference.llama_cpp import _diffusion_manual_ngl, _scale_diffusion_required_gbis_gguf = bool(getattr(config, "is_gguf", False))- if diffusion_kind is _DIFFUSION_KIND_UNSET:- diffusion_kind = _classify_diffusion_gguf(config) if is_gguf else False- if is_gguf and gpu_memory_mode == "manual" and diffusion_kind is False:+ if is_gguf and request.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(gpu_memory_mode, gpu_layers) if is_gguf else None+ diffusion_ngl = (+ _diffusion_manual_ngl(request.gpu_memory_mode, request.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.# Guard what will run, not what was asked, or a zero-layer request skips the VRAM@@ -5289,13 +5270,13 @@ def _guard_chat_load_against_training(required_override_gb = (_estimate_gguf_required_gb(config,- hf_token = hf_token,- max_seq_length = max_seq_length,+ hf_token = request.hf_token,+ max_seq_length = request.max_seq_length,llama_extra_args = llama_extra_args,n_parallel = n_parallel,- cache_type_kv = cache_type_kv,+ cache_type_kv = request.cache_type_kv,tensor_parallel = (- _effective_tensor_parallel(llama_extra_args, tensor_parallel)+ _effective_tensor_parallel(llama_extra_args, request.tensor_parallel)and (is_vulkan_backendor LlamaCppBackend._effective_gpu_count(requested_gpu_ids) >= 2@@ -5337,10 +5318,10 @@ def _guard_chat_load_against_training(vulkan_free_vram_gb = {}ok, info = can_load_chat_during_training(- model_name = model_identifier,- hf_token = hf_token,+ model_name = getattr(config, "identifier", request.model_path),+ hf_token = request.hf_token,load_in_4bit = load_in_4bit,- max_seq_length = max_seq_length,+ max_seq_length = request.max_seq_length,requested_gpu_ids = requested_gpu_ids,is_gguf = is_gguf,gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,@@ -5927,97 +5908,44 @@ async def _load_model_impl(backend = await asyncio.to_thread(get_inference_backend)llama_backend = get_llama_cpp_backend()- # Resolve the slot count once (per-load field, else the server-wide- # --parallel default) so the dedupe, the training guard and the load- # kwargs all size against what launches. app.state stays the launch- # intent / admission fallback; getattr because direct callers have no app.- _app_state = getattr(getattr(fastapi_request, "app", None), "state", None)- _n_parallel = (- request.n_parallel- if request.n_parallel is not None- else getattr(_app_state, "llama_parallel_slots", 1)- )+ # Resolve once so dedupe, admission and launch use the same slot count.+ _n_parallel = _resolve_parallel_slots(request, fastapi_request)- is_direct_gguf_request = model_identifier.lower().endswith(".gguf")- if request.gguf_variant or is_direct_gguf_request:- gguf_variant_matches = is_direct_gguf_request or bool(- llama_backend.hf_variant- and request.gguf_variant- and llama_backend.hf_variant.lower() == request.gguf_variant.lower()+ def _reuse_loaded_gguf(+ intent: GgufLoadIntent, *, display_name: Optional[str] = None+ ) -> Optional[LoadResponse]:+ if not (+ llama_backend.adopt_load_intent_if_matched(intent)+ and getattr(llama_backend, "_audio_probed", True)+ ):+ return None+ api_monitor.discard(_load_event)+ logger.info("Model already loaded (GGUF): %s, skipping reload", model_log_label)+ return _gguf_load_response(+ llama_backend,+ "already_loaded",+ model_log_label if native_grant_backed else llama_backend.model_identifier,+ display_name = model_log_label if native_grant_backed else display_name,+ is_local_model = _loaded_is_local_model(+ llama_backend, native_grant_backed, llama_backend.model_identifier+ ),)- if (- llama_backend.is_loaded- and gguf_variant_matches- and llama_backend.model_identifier- and llama_backend.model_identifier.lower() == model_identifier.lower()- # Match runtime settings so Apply isn't dropped (#5401).- and _request_matches_loaded_settings(++ is_direct_gguf_request = model_identifier.lower().endswith(".gguf")+ if llama_backend.is_loaded and (request.gguf_variant or is_direct_gguf_request):+ reused = _reuse_loaded_gguf(+ _active_gguf_intent(request,llama_backend,- effective_chat_template_override,- requested_parallel_slots = _n_parallel,+ model_identifier = model_identifier,+ chat_template_override = effective_chat_template_override,+ n_parallel = _n_parallel,native_grant_backed = native_grant_backed,)- # Skip if a prior audio probe failed -- let load_model retry.- and getattr(llama_backend, "_audio_probed", True)- ):- llama_backend._record_matching_gpu_request(request.gpu_ids)- # Nothing was loaded, so the monitor must not show a load row.- api_monitor.discard(_load_event)- logger.info(- "Model already loaded (GGUF): "- f"{model_log_label} variant={request.gguf_variant or llama_backend.hf_variant}, skipping reload"- )- inference_config = load_inference_config(llama_backend.model_identifier)-- _gguf_audio = getattr(llama_backend, "_audio_type", None)- _gguf_is_audio = getattr(llama_backend, "_is_audio", False)- return LoadResponse(- status = "already_loaded",- model = model_log_label- if native_grant_backed- else llama_backend.model_identifier,- display_name = model_log_label- if native_grant_backed- else llama_backend.model_identifier,- is_vision = llama_backend._is_vision,- is_lora = False,- is_gguf = True,- is_local_model = _loaded_is_local_model(- llama_backend, native_grant_backed, llama_backend.model_identifier- ),- is_diffusion = llama_backend.is_diffusion,- diffusion_requested_ngl = llama_backend.diffusion_requested_ngl,- is_audio = _gguf_is_audio,- audio_type = _gguf_audio,- has_audio_input = getattr(llama_backend, "_has_audio_input", False),- inference = inference_config,- # GGUF loads via llama.cpp: auto_map never executes, so inert (matches validate_model).- requires_trust_remote_code = False,- context_length = llama_backend.context_length,- max_context_length = llama_backend.max_context_length,- native_context_length = llama_backend.native_context_length,- supports_reasoning = llama_backend.supports_reasoning,- reasoning_style = llama_backend.reasoning_style,- reasoning_effort_levels = llama_backend.reasoning_effort_levels,- reasoning_always_on = llama_backend.reasoning_always_on,- supports_preserve_thinking = llama_backend.supports_preserve_thinking,- supports_tools = llama_backend.supports_tools,- chat_template = llama_backend.chat_template,- speculative_type = llama_backend.requested_spec_mode,- spec_draft_n_max = llama_backend.spec_draft_n_max,- tensor_parallel = llama_backend.tensor_parallel,- gpu_memory_mode = llama_backend.gpu_memory_mode,- gpu_layers = llama_backend.gpu_layers,- n_cpu_moe = llama_backend.n_cpu_moe,- tensor_split = llama_backend.tensor_split,- n_layers = llama_backend.n_layers,- n_moe_layers = llama_backend.n_moe_layers,- gpu_ids = llama_backend.gpu_ids,- requested_gpu_ids = llama_backend.requested_gpu_ids,- **_parallel_slot_echo(llama_backend),- )- else:+ )+ if reused is not None:+ return reused+ if not (request.gguf_variant or is_direct_gguf_request):if (backend.active_model_nameand backend.active_model_name.lower() == model_identifier.lower()@@ -6065,19 +5993,6 @@ async def _load_model_impl(chat_template = _chat_template,)- # Past every already_loaded fast return, so this really will replace the running model: gate- # it on the chats that would stop. Refusal only, so a non-forced swap fails fast; the checks- # between here and the teardown (identifier, GPU, training guard, downloads) can still- # reject the load, and cancelling now would stop every chat for a model that never loads.- # Auto-switch passes no hook and keeps its current behaviour.- if on_reload_confirmed is not None:- on_reload_confirmed(cancel = False)-- # Destructive cancel still owed at the teardown below, so it can be deferred past every- # remaining check; the drains key off this. Only a forced swap cancels: unforced already- # 409'd above, auto-switch has no hook.- cancel_pending = on_reload_confirmed is not None and bool(request.force_cancel_active)-# is_lora auto-detected from adapter_config.json on disk/HF.# Probe wrap so offline loads skip 30-60s of soft-failed network checks before# the worker starts. Off-loop: the guard can spend seconds on DNS plus a HEAD and@@ -6110,27 +6025,52 @@ async def _load_model_impl(effective_chat_template_override,)- # Normalize gpu_ids: empty list means auto-selection, same as None- effective_gpu_ids = request.gpu_ids if request.gpu_ids else None- gpu_ids_are_vulkan_ordinals = False- diffusion_kind = _classify_diffusion_gguf(config) if config.is_gguf else False-# Invalid GPU IDs must fail before the training coexistence guard.- gguf_gpu_ids: Optional[List[int]] = None+ placement = await _prepare_load_placement(config, request, extra_llama_args)+ gguf_intent: Optional[GgufLoadIntent] = None+ _tensor_intent_overall = Falseif config.is_gguf:- (- gguf_gpu_ids,- gpu_ids_are_vulkan_ordinals,- ) = await _resolve_gguf_gpu_ids_for_request(+ gguf_intent = _resolve_gguf_load_intent(config,- effective_gpu_ids,- diffusion_kind = diffusion_kind,+ request,+ native_grant_backed = native_grant_backed,+ chat_template_override = effective_chat_template_override,+ extra_args = extra_llama_args,+ placement = placement,+ n_parallel = _n_parallel,)- _reject_draft_device_with_gpu_ids(- gguf_gpu_ids,- extra_llama_args,- gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,+ same_loaded_model = llama_backend.matches_load_source(gguf_intent)+ if same_loaded_model and config.gguf_hf_repo and llama_backend.gguf_path:+ gguf_intent = replace(+ gguf_intent,+ mtp_draft_path = _mtp_draft_for_path(llama_backend.gguf_path, False),+ compare_mtp_draft = True,+ )+ _effective_tensor = _effective_tensor_parallel(+ extra_llama_args, request.tensor_parallel+ )+ _tensor_intent_overall = _effective_tensor or _carry_preserved_tensor_intent(+ preserved = getattr(llama_backend, "layer_preserves_tensor_intent", False),+ same_model = same_loaded_model,+ explicit_drop = _is_explicit_tensor_drop(request),+ )+ gguf_intent = replace(+ gguf_intent,+ preserve_multi_gpu_on_layer = (_tensor_intent_overall and not _effective_tensor),+ )+ reused = _reuse_loaded_gguf(+ gguf_intent,+ display_name = config.display_name,)+ if reused is not None:+ return reused++ # Config-resolved dedupe must run first: a duplicate must not refuse/cancel active chats.+ # Refusal is non-destructive; defer forced cancellation past every remaining rejection.+ if on_reload_confirmed is not None:+ on_reload_confirmed(cancel = False)+ cancel_pending = on_reload_confirmed is not None and bool(request.force_cancel_active)+if not config.is_gguf and _mlx_distributed_launch_detected():raise HTTPException(status_code = 400,@@ -6173,19 +6113,11 @@ async def _load_model_impl((model_identifier, config.identifier, getattr(config, "base_model", None)),_guard_chat_load_against_training,config,- model_identifier = model_identifier,- hf_token = request.hf_token,+ request,load_in_4bit = effective_load_in_4bit,- max_seq_length = request.max_seq_length,- requested_gpu_ids = effective_gpu_ids,+ placement = placement,llama_extra_args = extra_llama_args,n_parallel = _n_parallel,- cache_type_kv = request.cache_type_kv,- tensor_parallel = bool(request.tensor_parallel),- gpu_memory_mode = request.gpu_memory_mode,- gpu_layers = request.gpu_layers,- gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,- diffusion_kind = diffusion_kind,)# ── GGUF path: load via llama-server ──────────────────────@@ -6256,153 +6188,31 @@ async def _load_model_impl(unsloth_backend.unload_model, unsloth_backend.active_model_name)- # Route to HF or local mode based on config. Run in a thread so the- # event loop stays free for progress polling and other requests- # during the (potentially long) GGUF download + llama-server start.-- # Load kwargs common to HF and local modes; the two differ only by- # the model-source args (hf_repo/-token vs gguf_path/mmproj).- _common_load_kwargs = dict(- model_identifier = config.identifier,- is_vision = config.is_vision,- n_ctx = request.max_seq_length,- chat_template_override = effective_chat_template_override,- cache_type_kv = request.cache_type_kv,- speculative_type = request.speculative_type,- spec_draft_n_max = request.spec_draft_n_max,- gpu_memory_mode = request.gpu_memory_mode,- gpu_layers = request.gpu_layers,- n_cpu_moe = request.n_cpu_moe,- tensor_split = request.tensor_split,- gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,- n_parallel = _n_parallel,- # Issue #7164: explicit GPU pin resolved to physical ids above.- gpu_ids = gguf_gpu_ids,- )- if config.gguf_hf_repo:- # HF mode: download via huggingface_hub then start llama-server- _source_load_kwargs = dict(- hf_repo = config.gguf_hf_repo,- hf_variant = config.gguf_variant,- hf_token = request.hf_token,- )- else:- # Local mode: llama-server loads via -m <path>- if native_grant_backed:- if config.gguf_mmproj_file:- _validate_native_gguf_companion(- config.gguf_mmproj_file, config.gguf_file, "vision companion"- )- if config.gguf_mtp_file:- # The drafter is optional (unlike mmproj for a vision- # model): drop it rather than fail the load.- mtp_search_root = _local_gguf_companion_search_root(- config.gguf_file, config.gguf_file- )-- def _mtp_allowed(candidate: str) -> bool:- try:- _validate_native_mtp_drafter(- candidate,- config.gguf_file,- mtp_search_root = mtp_search_root,- )- return True- except HTTPException as exc:- logger.warning(- "Dropping MTP drafter for native load: %s", exc.detail- )- return False-- if not _mtp_allowed(config.gguf_mtp_file):- # The preferred root drafter is out of bounds for a- # grant on a quant subdir, but an MTP/ copy may not- # be. Scan them in preference order rather than- # dropping MTP on the first rejection.- fallback = detect_mtp_file(- config.gguf_file,- search_root = mtp_search_root,- skip_root = True,- accept = _mtp_allowed,- )- if fallback:- logger.info(- "Using MTP subdirectory drafter for native load: %s",- fallback,- )- config.gguf_mtp_file = fallback- _source_load_kwargs = dict(- gguf_path = config.gguf_file,- mmproj_path = config.gguf_mmproj_file,- mtp_draft_path = config.gguf_mtp_file,- # Pass the resolved variant so _extra_args_source keys off- # the same string the inheritance check at the top of /load- # uses (#5401 followup).- hf_variant = config.gguf_variant,- )-- # Tensor intent for this load: the request itself, or a preserved- # multi-GPU layer fallback carried across a reload of the SAME model that- # doesn't drop it (e.g. a ctx-only change), so a fitting model doesn't- # silently collapse to one GPU. Only an explicit non-tensor --split-mode- # override counts as the drop -- the tensor field echo / unrelated extras keep- # the preserved placement; the same-model guard stops a switch-without-unload- # inheriting the prior model's intent.- _explicit_tensor_drop = _is_explicit_tensor_drop(request)- # Compare the resolved config.identifier (what load_model stores), not the- # raw request id: from_identifier normalizes shorthands (adds unsloth/, fixes- # case), so a reload with the shorthand would otherwise miss the match and- # drop the carry-forward. #6659- _same_model_loaded = (- llama_backend.is_loaded- and (llama_backend.model_identifier or "").lower()- == (config.identifier or "").lower()- )- # model_identifier is variant-agnostic for HF repos and dir-level for a- # local multi-variant directory, so also require the loaded quant to match- # (path else variant, mirroring _already_in_target_state) -- otherwise a- # different variant inherits the prior one's preserved intent. #6659- if _same_model_loaded:- if config.gguf_file and llama_backend.gguf_path:- try:- _same_model_loaded = (- Path(llama_backend.gguf_path).resolve()- == Path(config.gguf_file).resolve()- )- except OSError:- _same_model_loaded = False- else:- _same_model_loaded = (llama_backend.hf_variant or "").lower() == (- config.gguf_variant or ""- ).lower()- _tensor_intent_overall = _effective_tensor_parallel(- extra_llama_args, request.tensor_parallel- ) or _carry_preserved_tensor_intent(- preserved = llama_backend.layer_preserves_tensor_intent,- same_model = _same_model_loaded,- explicit_drop = _explicit_tensor_drop,- )+ # Every rejection and source check has completed. The immutable+ # intent resolved before teardown is now the only launch input.+ if gguf_intent is None:+ raise RuntimeError("GGUF load intent was not resolved")+ load_intent = gguf_intent# Run a single load attempt with the given tensor flag + extras.async def _attempt_gguf_load(tensor_parallel: bool, attempt_extra_args: Optional[list[str]]) -> bool:- attempt_kwargs = {- **_common_load_kwargs,- "extra_args": attempt_extra_args,- }- return await asyncio.to_thread(- llama_backend.load_model,- **_source_load_kwargs,- **attempt_kwargs,+ attempt = replace(+ load_intent,+ extra_args = (+ tuple(attempt_extra_args) if attempt_extra_args is not None else None+ ),tensor_parallel = tensor_parallel,- # True on the layer fallback retry (tensor wanted overall but not on- # this attempt): keep multi-GPU. Mirrors the fallback's key.preserve_multi_gpu_on_layer = bool(_tensor_intent_overalland not _effective_tensor_parallel(attempt_extra_args, tensor_parallel)),)+ return await asyncio.to_thread(+ llama_backend.load_model,+ intent = attempt,+ )# Tensor parallelism is arch-gated in llama.cpp and crashes some loads# outright (e.g. Gemma 3n aborts with a GGML_ASSERT). The helper auto-@@ -6451,47 +6261,13 @@ async def _load_model_impl(if _gguf_is_audio:logger.info(f"GGUF model detected as audio: audio_type={_gguf_audio}")- inference_config = load_inference_config(config.identifier)-- return LoadResponse(- status = "loaded",- model = model_log_label if native_grant_backed else config.identifier,+ return _gguf_load_response(+ llama_backend,+ "loaded",+ model_log_label if native_grant_backed else config.identifier,display_name = model_log_label if native_grant_backed else config.display_name,- is_vision = llama_backend.is_vision,- is_lora = False,- is_gguf = True,is_local_model = config.is_local,- is_diffusion = llama_backend.is_diffusion,- diffusion_requested_ngl = llama_backend.diffusion_requested_ngl,- is_audio = _gguf_is_audio,- audio_type = _gguf_audio,- has_audio_input = llama_backend._has_audio_input,- inference = inference_config,- # GGUF loads via llama.cpp: auto_map never executes, so inert (matches validate_model).- requires_trust_remote_code = False,- context_length = llama_backend.context_length,- max_context_length = llama_backend.max_context_length,- native_context_length = llama_backend.native_context_length,- supports_reasoning = llama_backend.supports_reasoning,- reasoning_style = llama_backend.reasoning_style,- reasoning_effort_levels = llama_backend.reasoning_effort_levels,- reasoning_always_on = llama_backend.reasoning_always_on,- supports_preserve_thinking = llama_backend.supports_preserve_thinking,- supports_tools = llama_backend.supports_tools,- cache_type_kv = llama_backend.cache_type_kv,- chat_template = llama_backend.chat_template,- speculative_type = llama_backend.requested_spec_mode,- spec_draft_n_max = llama_backend.spec_draft_n_max,- tensor_parallel = llama_backend.tensor_parallel,- gpu_memory_mode = llama_backend.gpu_memory_mode,- gpu_layers = llama_backend.gpu_layers,- n_cpu_moe = llama_backend.n_cpu_moe,- tensor_split = llama_backend.tensor_split,- n_layers = llama_backend.n_layers,- n_moe_layers = llama_backend.n_moe_layers,- gpu_ids = llama_backend.gpu_ids,- requested_gpu_ids = llama_backend.requested_gpu_ids,- **_parallel_slot_echo(llama_backend),+ inference_identifier = config.identifier,)# ── Standard path: load via Unsloth/transformers ──────────@@ -6549,7 +6325,7 @@ async def _load_model_impl(hf_token = request.hf_token,trust_remote_code = request.trust_remote_code,approved_remote_code_fingerprint = request.approved_remote_code_fingerprint,- gpu_ids = effective_gpu_ids,+ gpu_ids = placement.requested_gpu_ids,subject = current_subject,)@@ -6860,25 +6636,9 @@ async def validate_model(request, config, model_identifier, None)- # Apply the same training coexistence policy as /load before the frontend- # unloads the current model.- effective_gpu_ids = request.gpu_ids if request.gpu_ids else None- gpu_ids_are_vulkan_ordinals = False- diffusion_kind = _classify_diffusion_gguf(config) if config.is_gguf else False- if config.is_gguf:- (- validated_gpu_ids,- gpu_ids_are_vulkan_ordinals,- ) = await _resolve_gguf_gpu_ids_for_request(- config,- effective_gpu_ids,- diffusion_kind = diffusion_kind,- )- _reject_draft_device_with_gpu_ids(- validated_gpu_ids,- effective_extra_args,- gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,- )+ # Apply the same placement policy as /load before the frontend unloads+ # the current model.+ placement = await _prepare_load_placement(config, request, effective_extra_args)effective_load_in_4bit = _effective_load_in_4bit(config, request.load_in_4bit)# Both checks cover the [adapter, base] set (matching the scan route and workers):@@ -6971,28 +6731,11 @@ async def validate_model((model_identifier, config.identifier, getattr(config, "base_model", None)),_guard_chat_load_against_training,config,- model_identifier = model_identifier,- hf_token = request.hf_token,+ request,load_in_4bit = effective_load_in_4bit,- max_seq_length = request.max_seq_length,- requested_gpu_ids = effective_gpu_ids,+ placement = placement,llama_extra_args = effective_extra_args,- n_parallel = (- request.n_parallel- if request.n_parallel is not None- # Same getattr chain as the load path: preflight must size like the load.- else getattr(- getattr(getattr(fastapi_request, "app", None), "state", None),- "llama_parallel_slots",- 1,- )- ),- cache_type_kv = request.cache_type_kv,- tensor_parallel = request.tensor_parallel,- gpu_memory_mode = request.gpu_memory_mode,- gpu_layers = request.gpu_layers,- gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,- diffusion_kind = diffusion_kind,+ n_parallel = _resolve_parallel_slots(request, fastapi_request),)# A selected GGUF loads via llama.cpp: auto_map Python and root pickle weights in a@@ -7073,9 +6816,9 @@ async def validate_model(if native_grant_backedelse getattr(config, "display_name", config.identifier),is_gguf = is_gguf,- is_diffusion = is_gguf and diffusion_kind is True,- # None = unreadable header + no family in the name, not "ordinary GGUF".- diffusion_unknown = is_gguf and diffusion_kind is None,+ is_diffusion = is_gguf and placement.diffusion_kind is True,+ # An unavailable header is inconclusive, not proof of an ordinary GGUF.+ diffusion_unknown = is_gguf and placement.diffusion_kind is None,is_lora = getattr(config, "is_lora", False),is_vision = getattr(config, "is_vision", False),requires_trust_remote_code = requires_trust_remote_code,@@ -7819,7 +7562,6 @@ async def get_status(current_subject: str = Depends(get_current_subject)):# No label registered, so report the clean public id, not the snapshot's sha._display_model_id = _llama_public_model_id(llama_backend) or _display_model_id_inference_cfg = load_inference_config(_model_id) if _model_id else None- _audio_type = getattr(llama_backend, "_audio_type", None)# Don't surface Unsloth's auto-applied bundled family template (e.g. the# gemma-4 override) as a user-authored override: the frontend adopts# status.chat_template_override as editable state and would otherwise@@ -7838,47 +7580,17 @@ async def get_status(current_subject: str = Depends(get_current_subject)):return InferenceStatusResponse(active_model = _display_model_id,model_identifier = None if _native_grant_backed else _model_id,- is_vision = llama_backend.is_vision,is_gguf = True,is_local_model = _loaded_is_local_model(llama_backend, _native_grant_backed, _model_id),- is_diffusion = llama_backend.is_diffusion,- diffusion_requested_ngl = llama_backend.diffusion_requested_ngl,gguf_variant = llama_backend.hf_variant,- is_audio = getattr(llama_backend, "_is_audio", False),- audio_type = _audio_type,- has_audio_input = getattr(llama_backend, "_has_audio_input", False),loading = [],loaded = [_display_model_id] if _display_model_id else [],inference = _inference_cfg,- # GGUF status: auto_map never executes, so inert (matches validate_model).- requires_trust_remote_code = False,- supports_reasoning = llama_backend.supports_reasoning,- reasoning_style = llama_backend.reasoning_style,- reasoning_effort_levels = llama_backend.reasoning_effort_levels,- reasoning_always_on = llama_backend.reasoning_always_on,- supports_preserve_thinking = llama_backend.supports_preserve_thinking,- supports_tools = llama_backend.supports_tools,- chat_template = llama_backend.chat_template,- context_length = llama_backend.context_length,- max_context_length = llama_backend.max_context_length,- native_context_length = llama_backend.native_context_length,- cache_type_kv = llama_backend.cache_type_kv,+ **_llama_runtime_fields(llama_backend),chat_template_override = _reported_chat_template_override,- speculative_type = llama_backend.requested_spec_mode,- spec_draft_n_max = llama_backend.spec_draft_n_max,- tensor_parallel = llama_backend.tensor_parallel,- gpu_memory_mode = llama_backend.gpu_memory_mode,- gpu_layers = llama_backend.gpu_layers,- n_cpu_moe = llama_backend.n_cpu_moe,- tensor_split = llama_backend.tensor_split,requested_context_length = llama_backend.requested_n_ctx,- n_layers = llama_backend.n_layers,- n_moe_layers = llama_backend.n_moe_layers,- gpu_ids = llama_backend.gpu_ids,- requested_gpu_ids = llama_backend.requested_gpu_ids,- **_parallel_slot_echo(llama_backend),llama_cpp_supports_mtp = _supports_mtp,spec_fallback_reason = llama_backend.spec_fallback_reason,llama_cpp_prebuilt_stale = _stale,diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.pyindex 36cb897b9fe..a1f047f0296 100644--- a/studio/backend/tests/test_chat_load_during_training.py+++ b/studio/backend/tests/test_chat_load_during_training.py@@ -489,22 +489,30 @@ class TestChatLoadGuardRoute(unittest.TestCase):gpu_layers = -1,):config = config or SimpleNamespace(is_gguf = False, is_lora = False, path = None)+ placement = self.route._LoadPlacement(+ requested_gpu_ids,+ requested_gpu_ids,+ gpu_ids_are_vulkan_ordinals,+ self.route._classify_diffusion_gguf(config) if config.is_gguf else False,+ )with _stub_guard_deps(training_active = training_active, decision = decision, captured = captured):- self.route._guard_chat_load_against_training(- config,- model_identifier = "unsloth/Qwen3-1.7B",+ request = SimpleNamespace(+ model_path = "unsloth/Qwen3-1.7B",hf_token = None,- load_in_4bit = True,max_seq_length = 0,- requested_gpu_ids = requested_gpu_ids,- llama_extra_args = llama_extra_args,cache_type_kv = cache_type_kv,tensor_parallel = tensor_parallel,gpu_memory_mode = gpu_memory_mode,gpu_layers = gpu_layers,- gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,+ )+ self.route._guard_chat_load_against_training(+ config,+ request,+ load_in_4bit = True,+ placement = placement,+ llama_extra_args = llama_extra_args,)def test_noop_when_training_inactive(self):@@ -772,7 +780,7 @@ class TestChatLoadGuardRoute(unittest.TestCase):def test_gguf_config_passes_is_gguf_and_override(self):captured = []- config = SimpleNamespace(is_gguf = True)+ config = SimpleNamespace(identifier = "unsloth/Canonical-Repo", is_gguf = True)with patch.object(self.route, "_estimate_gguf_required_gb", return_value = 12.5):self._guard(config = config,@@ -782,6 +790,7 @@ class TestChatLoadGuardRoute(unittest.TestCase):)self.assertEqual(captured[0]["is_gguf"], True)self.assertEqual(captured[0]["required_override_gb"], 12.5)+ self.assertEqual(captured[0]["model_name"], config.identifier)def test_vulkan_gguf_estimate_keeps_tensor_cache_coercion(self):config = SimpleNamespace(is_gguf = True)@@ -949,11 +958,11 @@ class TestValidateRefusesDuringTraining(unittest.TestCase):patch.object(self.route,"_guard_chat_load_against_training",- lambda config, **kw: captured.update(kw),+ lambda config, request, **kw: captured.update(request = request, **kw),),):asyncio.run(self.route.validate_model(request, current_subject = "u"))- self.assertEqual(captured.get("gpu_memory_mode"), "manual")+ self.assertEqual(captured["request"].gpu_memory_mode, "manual")def test_validate_forwards_inherited_extras_and_parallel_to_guard(self):# Validate and load must size the same inherited command.@@ -987,14 +996,14 @@ class TestValidateRefusesDuringTraining(unittest.TestCase):patch.object(self.route,"_guard_chat_load_against_training",- lambda config, **kw: captured.update(kw),+ lambda config, request, **kw: captured.update(request = request, **kw),),):asyncio.run(self.route.validate_model(request, current_subject = "u"))self.assertEqual(captured.get("llama_extra_args"), ["-c", "32768"])self.assertIn("n_parallel", captured)- self.assertEqual(captured.get("cache_type_kv"), "f32")- self.assertTrue(captured.get("tensor_parallel"))+ self.assertEqual(captured["request"].cache_type_kv, "f32")+ self.assertTrue(captured["request"].tensor_parallel)def test_metadata_probe_skips_training_guard(self):# Header-only probes allocate no VRAM.@@ -1426,9 +1435,14 @@ class TestLoadModelGuardIntegration(unittest.TestCase):is_loaded = True,model_identifier = "x.gguf",hf_variant = None,+ hf_repo = None,+ gguf_path = None,extra_args = ["--spec-draft-device", "CUDA1"],extra_args_source = ("x.gguf", None),+ last_load_intent = None,+ layer_preserves_tensor_intent = False,is_vulkan_build = lambda: True,+ adopt_load_intent_if_matched = lambda intent: False,)llama.unload_model = MagicMock()cfg = SimpleNamespace(@@ -1456,7 +1470,6 @@ class TestLoadModelGuardIntegration(unittest.TestCase):return_value = ("x.gguf", "x.gguf", False),),patch.object(self.route, "resolve_effective_chat_template_override", return_value = None),- patch.object(self.route, "_request_matches_loaded_settings", return_value = False),patch.object(self.route,"_resolve_gguf_gpu_ids_for_request",diff --git a/studio/backend/tests/test_gemma4_chat_template_override.py b/studio/backend/tests/test_gemma4_chat_template_override.pyindex 9fb24a4cf64..8a1501bebee 100644--- a/studio/backend/tests/test_gemma4_chat_template_override.py+++ b/studio/backend/tests/test_gemma4_chat_template_override.py@@ -299,7 +299,7 @@ def test_already_in_target_state_consistent_with_bundled_override():``chat_template_override`` still matches (no spurious reload), while a raw``None`` would not."""- LlamaCppBackend = _import_backend()+ LlamaCppBackend, GgufLoadIntent = _import_backend()class _FakeProcess:def terminate(self): ...@@ -334,12 +334,16 @@ def test_already_in_target_state_consistent_with_bundled_override():is_vision = False,)# Effective (resolved bundled) override -> already loaded, no reload.- assert backend._already_in_target_state(chat_template_override = BUNDLED, **common) is True+ assert backend.adopt_load_intent_if_matched(+ GgufLoadIntent(chat_template_override = BUNDLED, **common)+ )# Raw None (unresolved) -> false match, would force a needless reload.- assert backend._already_in_target_state(chat_template_override = None, **common) is False+ assert not backend.adopt_load_intent_if_matched(+ GgufLoadIntent(chat_template_override = None, **common)+ )def _import_backend():with _stub_modules_ctx():- from core.inference.llama_cpp import LlamaCppBackend- return LlamaCppBackend+ from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend+ return LlamaCppBackend, GgufLoadIntentdiff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.pyindex 8c5cfedc184..1731479dede 100644--- a/studio/backend/tests/test_gguf_load_cache_reuse.py+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py@@ -14,7 +14,7 @@ import loggingimport sysimport threadingimport types as _types-from contextlib import nullcontext+from contextlib import contextmanager, nullcontextfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import patch@@ -78,6 +78,7 @@ except ImportError:from huggingface_hub import constants as hf_constantsfrom core.inference.llama_cpp import (+ GgufLoadIntent,LlamaCppBackend,cached_gguf_for_load,gguf_load_in_flight,@@ -137,6 +138,35 @@ def _load_route_module(name: str, relative_path: str):return module+def _run_route_load(route, request):+ fastapi_request = SimpleNamespace(+ app = SimpleNamespace(state = SimpleNamespace(llama_parallel_slots = 1))+ )+ return asyncio.run(+ route._load_model_impl(request, fastapi_request, current_subject = "test-user")+ )+++@contextmanager+def _reuse_route(route, backend, response):+ with (+ patch.object(+ route,+ "_resolve_model_identifier_for_request",+ return_value = (REPO, REPO, False),+ ),+ patch.object(route, "resolve_effective_chat_template_override", return_value = None),+ patch.object(route, "_gguf_load_response", return_value = response) as response_mock,+ patch.object(route, "get_llama_cpp_backend", return_value = backend),+ patch.object(+ route,+ "get_inference_backend",+ return_value = SimpleNamespace(active_model_name = None),+ ),+ ):+ yield response_mock++async def _inline_to_thread(func, /, *args, **kwargs):return func(*args, **kwargs)@@ -616,6 +646,164 @@ class TestCachedGgufForLoadProbe:class TestLoadHubDownloadExclusion:+ def test_resident_local_directory_intent_uses_variant_until_path_is_resolved(self):+ from models.inference import LoadRequest++ route = _load_route_module(+ "inference_route_module_for_local_variant_identity",+ "routes/inference.py",+ )+ model_identifier = "/models/local-quants"+ loaded_path = "/models/model.gguf"+ backend = SimpleNamespace(+ extra_args = None,+ gguf_path = loaded_path,+ layer_preserves_tensor_intent = False,+ last_load_intent = GgufLoadIntent(+ model_identifier = model_identifier,+ gguf_path = loaded_path,+ hf_variant = VARIANT,+ ),+ )++ with patch.object(route, "_mtp_draft_for_path", return_value = None):+ intent = route._active_gguf_intent(+ LoadRequest(model_path = model_identifier, gguf_variant = "Q8_0"),+ backend,+ model_identifier = model_identifier,+ chat_template_override = None,+ n_parallel = 1,+ native_grant_backed = False,+ )++ assert intent.gguf_path is None+ assert intent.hf_variant == "Q8_0"++ def test_resident_gguf_reuse_precedes_model_metadata_resolution(self):+ from models.inference import LoadRequest++ route = _load_route_module(+ "inference_route_module_for_resident_fast_path_test",+ "routes/inference.py",+ )+ response = object()+ backend = SimpleNamespace(+ is_loaded = True,+ model_identifier = REPO,+ adopt_load_intent_if_matched = lambda _intent: True,+ _audio_probed = True,+ )+ request = LoadRequest(model_path = REPO, gguf_variant = VARIANT)++ with (+ _reuse_route(route, backend, response),+ patch.object(+ route,+ "ModelConfig",+ SimpleNamespace(+ from_identifier = lambda **_kwargs: (_ for _ in ()).throw(+ AssertionError("resident reuse must not resolve model metadata")+ )+ ),+ ),+ patch.object(route, "_active_gguf_intent", return_value = object()),+ ):+ result = _run_route_load(route, request)++ assert result is response++ def test_post_config_reuse_preserves_resolved_display_name(self):+ from models.inference import LoadRequest++ route = _load_route_module(+ "inference_route_module_for_resolved_display_name_test",+ "routes/inference.py",+ )+ response = object()+ intent = GgufLoadIntent(model_identifier = REPO, gguf_path = "/cached/model.gguf")+ backend = SimpleNamespace(+ is_loaded = True,+ model_identifier = REPO,+ gguf_path = None,+ matches_load_source = lambda _intent: True,+ adopt_load_intent_if_matched = lambda _intent: True,+ _audio_probed = True,+ )+ config = SimpleNamespace(+ identifier = REPO,+ display_name = "Gemma Test (UD-Q4_K_XL)",+ is_gguf = True,+ is_lora = False,+ is_vision = False,+ gguf_hf_repo = None,+ )++ with (+ _reuse_route(route, backend, response) as response_mock,+ patch.object(+ route,+ "ModelConfig",+ SimpleNamespace(from_identifier = lambda **_kwargs: config),+ ),+ patch.object(route, "_resolve_inherited_extra_args", return_value = None),+ patch.object(+ route,+ "_prepare_load_placement",+ return_value = route._LoadPlacement(None, None, False, False),+ ),+ patch.object(route, "_resolve_gguf_load_intent", return_value = intent),+ patch.object(route, "_loaded_is_local_model", return_value = False),+ ):+ result = _run_route_load(route, LoadRequest(model_path = REPO))++ assert result is response+ assert response_mock.call_args.args[1] == "already_loaded"+ assert response_mock.call_args.kwargs["display_name"] == config.display_name++ def test_local_intent_does_not_retain_hf_token(self):+ from models.inference import LoadRequest++ route = _load_route_module(+ "inference_route_module_for_local_intent_token_test",+ "routes/inference.py",+ )+ request = LoadRequest(model_path = "/models/local.gguf", hf_token = "secret")+ common = dict(+ chat_template_override = None,+ extra_args = None,+ gpu_ids = None,+ n_parallel = 1,+ )++ local = route._gguf_request_intent(+ GgufLoadIntent(model_identifier = request.model_path, gguf_path = request.model_path),+ request,+ **common,+ )+ remote = route._gguf_request_intent(+ GgufLoadIntent(model_identifier = REPO, hf_repo = REPO),+ request,+ **common,+ )++ assert local.hf_token is None+ assert remote.hf_token == "secret"++ def test_runtime_response_projection_fails_loudly_on_backend_drift(self):+ route = _load_route_module(+ "inference_route_module_for_runtime_projection_test",+ "routes/inference.py",+ )+ incomplete_backend = SimpleNamespace(+ requested_spec_mode = "auto",+ is_diffusion = False,+ requested_parallel_slots = 1,+ effective_parallel_slots = 1,+ )++ with pytest.raises(AttributeError, match = "runtime response fields"):+ route._llama_runtime_fields(incomplete_backend)+def test_in_flight_marker_counts_and_normalizes_case(self):assert not hf_gguf_load_in_flight(REPO)with gguf_load_in_flight(REPO):@@ -779,7 +967,7 @@ class TestLoadHubDownloadExclusion:class FakeBackend:@_with_gguf_load_marker- def load_model(self, *, hf_repo):+ def load_model(self, intent):started.set()release.wait(timeout = 2)finished.set()@@ -791,7 +979,10 @@ class TestLoadHubDownloadExclusion:return_value = False,):task = asyncio.create_task(- asyncio.to_thread(FakeBackend().load_model, hf_repo = REPO)+ asyncio.to_thread(+ FakeBackend().load_model,+ GgufLoadIntent(model_identifier = REPO, hf_repo = REPO),+ ))assert await asyncio.to_thread(started.wait, 1)task.cancel()@@ -893,6 +1084,8 @@ class TestLoadHubDownloadExclusion:extra_args_source = (REPO, VARIANT),hf_variant = VARIANT,model_identifier = REPO,+ matches_load_source = lambda _intent: False,+ adopt_load_intent_if_matched = lambda _intent: False,)request = LoadRequest(model_path = REPO,diff --git a/studio/backend/tests/test_gguf_reload_inheritance.py b/studio/backend/tests/test_gguf_reload_inheritance.pyindex 5d5f3c5a83e..4aaebd1ceac 100644--- a/studio/backend/tests/test_gguf_reload_inheritance.py+++ b/studio/backend/tests/test_gguf_reload_inheritance.py@@ -3,7 +3,7 @@"""Backend contract for the GGUF reload duplicate-load guard.-``LlamaCppBackend._already_in_target_state`` short-circuits a duplicate /load so+``LlamaCppBackend.adopt_load_intent_if_matched`` short-circuits a duplicate /load soit cannot kill the just-spawned llama-server. Pins local-file identity, theHF-mode hf_variant fallback, and ``extra_args`` None-vs-[] inherit semantics."""@@ -48,7 +48,7 @@ _httpx_stub.Client = type()sys.modules.setdefault("httpx", _httpx_stub)-from core.inference.llama_cpp import LlamaCppBackend+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackendclass _FakeProcess:@@ -87,6 +87,10 @@ def _loaded_backend(**overrides):return backend+def _matches(backend: LlamaCppBackend, **kwargs) -> bool:+ return backend.adopt_load_intent_if_matched(GgufLoadIntent(**kwargs))++# ── Local-file identity via gguf_path ────────────────────────────────@@ -98,7 +102,8 @@ def test_already_in_target_state_uses_gguf_path_when_present(tmp_path):_gguf_path = str(gguf_file),)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = str(gguf_file),model_identifier = "owner/repo",hf_variant = None,@@ -120,7 +125,8 @@ def test_already_in_target_state_rejects_different_gguf_path(tmp_path):b.write_bytes(b"")backend = _loaded_backend(_gguf_path = str(a))assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = str(b),model_identifier = "owner/repo",hf_variant = None,@@ -141,7 +147,8 @@ def test_already_in_target_state_rejects_different_gguf_path(tmp_path):def test_already_in_target_state_falls_back_to_hf_variant_for_hf_loads():backend = _loaded_backend(_hf_variant = "Q4_K_M", _gguf_path = None)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "owner/repo",hf_variant = "Q8_0",@@ -159,7 +166,8 @@ def test_already_in_target_state_falls_back_to_hf_variant_for_hf_loads():def test_already_in_target_state_hf_same_variant_matches():backend = _loaded_backend(_hf_variant = "Q4_K_M", _gguf_path = None)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "owner/repo",hf_variant = "Q4_K_M",@@ -180,7 +188,8 @@ def test_already_in_target_state_hf_same_variant_matches():def test_already_in_target_state_none_extras_inherits_stored():backend = _loaded_backend(_extra_args = ["--top-k", "20"])assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "owner/repo",hf_variant = "Q4_K_M",@@ -198,7 +207,8 @@ def test_already_in_target_state_none_extras_inherits_stored():def test_already_in_target_state_empty_extras_forces_reload_when_stored():backend = _loaded_backend(_extra_args = ["--top-k", "20"])assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "owner/repo",hf_variant = "Q4_K_M",@@ -216,7 +226,8 @@ def test_already_in_target_state_empty_extras_forces_reload_when_stored():def test_already_in_target_state_explicit_extras_match():backend = _loaded_backend(_extra_args = ["--top-k", "20"])assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "owner/repo",hf_variant = "Q4_K_M",diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.pyindex 3757f82240b..86ffa99d588 100644--- a/studio/backend/tests/test_gpu_memory_mode.py+++ b/studio/backend/tests/test_gpu_memory_mode.py@@ -50,7 +50,7 @@ sys.modules.setdefault("structlog", _structlog_stub)import httpx # noqa: F401from core.inference import llama_cpp as llama_cpp_module-from core.inference.llama_cpp import LlamaCppBackend+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackendfrom models.inference import (InferenceStatusResponse,LoadRequest,@@ -157,17 +157,19 @@ def _loaded_backend(gpu_memory_mode: str) -> LlamaCppBackend:def _target_state(backend: LlamaCppBackend, gpu_memory_mode: str) -> bool:- return backend._already_in_target_state(- gguf_path = None,- model_identifier = "owner/repo",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = "auto",- chat_template_override = None,- extra_args = None,- is_vision = False,- gpu_memory_mode = gpu_memory_mode,+ return backend.adopt_load_intent_if_matched(+ GgufLoadIntent(+ gguf_path = None,+ model_identifier = "owner/repo",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = "auto",+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ gpu_memory_mode = gpu_memory_mode,+ ))@@ -313,7 +315,7 @@ def test_route_normalizes_explicit_extras_before_reload_dedupe():normalize = load_impl.index('request = request.model_copy(update = {"llama_extra_args": extra_llama_args})')- dedupe = load_impl.index("and _request_matches_loaded_settings(")+ dedupe = load_impl.index("_reuse_loaded_gguf(")assert preserve < translate < strip < normalize < dedupe@@ -387,20 +389,22 @@ def _target_state_manual(n_cpu_moe,tensor_split = None,):- return backend._already_in_target_state(- gguf_path = None,- model_identifier = "owner/repo",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = "auto",- chat_template_override = None,- extra_args = None,- is_vision = False,- gpu_memory_mode = "manual",- gpu_layers = gpu_layers,- n_cpu_moe = n_cpu_moe,- tensor_split = tensor_split,+ return backend.adopt_load_intent_if_matched(+ GgufLoadIntent(+ gguf_path = None,+ model_identifier = "owner/repo",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = "auto",+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ gpu_memory_mode = "manual",+ gpu_layers = gpu_layers,+ n_cpu_moe = n_cpu_moe,+ tensor_split = tensor_split,+ ))@@ -594,28 +598,6 @@ def test_load_request_accepts_gpu_ids():assert LoadRequest(model_path = "owner/repo").gpu_ids is None[email protected]("model_cls", [LoadResponse, InferenceStatusResponse])-def test_response_models_emit_gpu_ids(model_cls):- if model_cls is LoadResponse:- obj = model_cls(- status = "loaded",- model = "m",- display_name = "m",- inference = {},- gpu_ids = [1],- requested_gpu_ids = [1, 2],- )- else:- obj = model_cls(gpu_ids = [1], requested_gpu_ids = [1, 2])- assert obj.model_dump()["gpu_ids"] == [1]- assert obj.model_dump()["requested_gpu_ids"] == [1, 2]---def test_gguf_load_and_status_responses_include_requested_gpu_pool():- route_src = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")- assert route_src.count("requested_gpu_ids = llama_backend.requested_gpu_ids") == 3--def test_gpu_ids_property_default_and_reset():backend = LlamaCppBackend()assert backend.gpu_ids is None@@ -631,17 +613,19 @@ def test_gpu_ids_property_default_and_reset():def _target_state_gpu_ids(backend, gpu_ids):- return backend._already_in_target_state(- gguf_path = None,- model_identifier = "owner/repo",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = "auto",- chat_template_override = None,- extra_args = None,- is_vision = False,- gpu_ids = gpu_ids,+ return backend.adopt_load_intent_if_matched(+ GgufLoadIntent(+ gguf_path = None,+ model_identifier = "owner/repo",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = "auto",+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ gpu_ids = gpu_ids,+ ))@@ -664,7 +648,10 @@ def test_gpu_ids_reload_detection_accepts_raw_and_effective_pin():backend = _loaded_backend("auto")backend._requested_gpu_ids = [0, 1]backend._gpu_ids = [0]- backend._last_load_kwargs = {"gpu_ids": [0, 1], "model_identifier": "owner/repo"}+ backend._last_load_intent = GgufLoadIntent(+ gpu_ids = [0, 1],+ model_identifier = "owner/repo",+ )# The original request still matches after the fitter narrows it.assert _target_state_gpu_ids(backend, [1, 0]) is True@@ -674,12 +661,34 @@ def test_gpu_ids_reload_detection_accepts_raw_and_effective_pin():# reload do not restore GPU 1 after the user removed it.assert _target_state_gpu_ids(backend, [0]) is Trueassert backend.requested_gpu_ids == [0]- assert backend._last_load_kwargs == {"gpu_ids": [0], "model_identifier": "owner/repo"}+ assert backend._last_load_intent.gpu_ids == (0,)+ assert backend._last_load_intent.model_identifier == "owner/repo"# A genuinely different placement pool still reloads.assert _target_state_gpu_ids(backend, [1]) is Falseassert _target_state_gpu_ids(backend, None) is False+ ("gpu_ids", "expected_ids", "matches"),+ [([], None, False), ([0], (0,), True)],+)+def test_gpu_ids_control_owned_device_extra_args(gpu_ids, expected_ids, matches):+ backend = _loaded_backend("auto")+ if gpu_ids:+ backend._gpu_ids = backend._requested_gpu_ids = [0]+ intent = GgufLoadIntent(+ model_identifier = "owner/repo",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ speculative_type = "auto",+ gpu_ids = gpu_ids,+ extra_args = ["--main-gpu", "1"],+ )++ assert intent.gpu_ids == expected_ids+ assert backend.adopt_load_intent_if_matched(intent) is matches++def test_gpu_ids_reload_detection_collapses_diffusion_to_single_device():# The diffusion runner drives only its single lowest device, so the backend# records [lowest]. A later multi-GPU request that still resolves to that@@ -747,10 +756,12 @@ def test_remote_vulkan_diffusion_rejection_keeps_active_server(monkeypatch):with pytest.raises(ValueError, match = "DiffusionGemma"):backend.load_model(- hf_repo = "owner/model",- hf_variant = "Q4_K_M",- model_identifier = "owner/model",- gpu_ids = [0],+ GgufLoadIntent(+ hf_repo = "owner/model",+ hf_variant = "Q4_K_M",+ model_identifier = "owner/model",+ gpu_ids = [0],+ ))assert killed == []@@ -796,10 +807,12 @@ def test_remote_vulkan_preflight_download_failure_keeps_active_server(monkeypatcwith pytest.raises(type(failure)):backend.load_model(- hf_repo = "owner/model",- hf_variant = "Q4_K_M",- model_identifier = "owner/model",- gpu_ids = [0],+ GgufLoadIntent(+ hf_repo = "owner/model",+ hf_variant = "Q4_K_M",+ model_identifier = "owner/model",+ gpu_ids = [0],+ ))assert order == ["download"], failure@@ -819,9 +832,11 @@ def test_local_vulkan_diffusion_rejection_keeps_active_server(monkeypatch, tmp_pwith pytest.raises(ValueError, match = "DiffusionGemma"):backend.load_model(- gguf_path = str(gguf_path),- model_identifier = "local/diffusion",- gpu_ids = [0],+ GgufLoadIntent(+ gguf_path = str(gguf_path),+ model_identifier = "local/diffusion",+ gpu_ids = [0],+ ))assert killed == []@@ -877,9 +892,11 @@ def test_local_vulkan_pre_teardown_reads_the_real_gguf_header(monkeypatch, tmp_pwith pytest.raises(_ReachedServerStart):backend.load_model(- gguf_path = _write_gguf_header(tmp_path / "chat.gguf", "llama"),- model_identifier = "local/chat",- gpu_ids = [0],+ GgufLoadIntent(+ gguf_path = _write_gguf_header(tmp_path / "chat.gguf", "llama"),+ model_identifier = "local/chat",+ gpu_ids = [0],+ ))assert killed == [True]@@ -892,9 +909,11 @@ def test_local_vulkan_diffusion_header_rejects_before_teardown(monkeypatch, tmp_with pytest.raises(ValueError, match = "DiffusionGemma"):backend.load_model(- gguf_path = _write_gguf_header(tmp_path / "d.gguf", "gemma3", diffusion = True),- model_identifier = "local/diffusion",- gpu_ids = [0],+ GgufLoadIntent(+ gguf_path = _write_gguf_header(tmp_path / "d.gguf", "gemma3", diffusion = True),+ model_identifier = "local/diffusion",+ gpu_ids = [0],+ ))assert killed == []@@ -907,9 +926,11 @@ def test_local_vulkan_missing_gguf_is_reported_before_teardown(monkeypatch, tmp_with pytest.raises(FileNotFoundError):backend.load_model(- gguf_path = str(tmp_path / "absent.gguf"),- model_identifier = "local/missing",- gpu_ids = [0],+ GgufLoadIntent(+ gguf_path = str(tmp_path / "absent.gguf"),+ model_identifier = "local/missing",+ gpu_ids = [0],+ ))assert killed == []@@ -925,15 +946,6 @@ def test_start_diffusion_server_resets_tensor_parallel():assert "self._requested_gpu_ids = list(self._gpu_ids) if self._gpu_ids else None" in src-def test_route_matches_loaded_settings_uses_shared_gpu_pin_matcher():- # Route-level and backend race dedupe must share one normalization path so- # raw, effective, and diffusion pins cannot drift apart.- route_src = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")- match_impl = route_src[route_src.index("def _request_matches_loaded_settings") :]- assert "if not llama_backend.matches_gpu_ids(request.gpu_ids):" in match_impl- assert "llama_backend._record_matching_gpu_request(request.gpu_ids)" in match_impl--# ── Manual tensor split: child enumeration pinned to the picker's order ──────diff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.pyindex 8754b86b18c..02d8b9e29f7 100644--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py@@ -54,6 +54,7 @@ sys.modules.setdefault("httpx", _httpx_stub)import pytestfrom core.inference.llama_cpp import (+ GgufLoadIntent,LlamaCppBackend,_GPU_OFFLOAD_OVERRIDE_FLAGS,_THREAD_OVERRIDE_FLAGS,@@ -69,6 +70,10 @@ from core.inference.llama_cpp import ()+def _matches(backend: LlamaCppBackend, **kwargs) -> bool:+ return backend.adopt_load_intent_if_matched(GgufLoadIntent(**kwargs))++# Synthetic GGUF helper (mirrors test_gguf_metadata.py)._GGUF_MAGIC = 0x46554747@@ -249,7 +254,8 @@ def test_already_in_target_state_matches_when_request_omits_spec_for_mtp_model()# Duplicate /load with no spec must match a running draft-mtp backend.backend = _mtp_backend()assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -267,7 +273,8 @@ def test_already_in_target_state_matches_when_request_omits_spec_for_mtp_model()def test_already_in_target_state_matches_when_request_uses_default_for_mtp_model():backend = _mtp_backend()assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -292,7 +299,8 @@ def test_already_in_target_state_auto_request_matches_auto_backend_for_non_mtp_m_speculative_type = "default",)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.6-27B-GGUF",hf_variant = "Q4_K_M",@@ -310,7 +318,8 @@ def test_already_in_target_state_auto_request_matches_auto_backend_for_non_mtp_mdef test_already_in_target_state_explicit_off_still_mismatches_mtp_backend():backend = _mtp_backend()assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -459,7 +468,8 @@ def test_already_in_target_state_user_spec_type_override_matches_clean_backend()_extra_args = ["--spec-type", "none"],)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -484,7 +494,8 @@ def test_already_in_target_state_local_file_mtp_match(tmp_path):_hf_variant = None,)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = str(gguf),model_identifier = "local-qwen-mtp",hf_variant = None,@@ -504,7 +515,8 @@ def test_already_in_target_state_vision_mtp_match():# with auto/default spec must match a backend already running draft-mtp.backend = _mtp_backend(_is_vision = True)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -522,7 +534,8 @@ def test_already_in_target_state_vision_mtp_match():def test_already_in_target_state_vision_mtp_default_matches():backend = _mtp_backend(_is_vision = True)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -548,7 +561,8 @@ def test_already_in_target_state_vision_off_matches_vision_backend():_requested_spec_mode = "off",)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3-VL-4B-Instruct-GGUF",hf_variant = "Q4_K_M",@@ -1005,62 +1019,66 @@ def test_probe_server_capabilities_caches_by_mtime(tmp_path):# spec_draft_n_max plumbing (first-class --spec-draft-n-max override).+def _draft_n_max_matches(+ backend,+ requested,+ *,+ speculative_type = None,+):+ return _matches(+ backend,+ gguf_path = None,+ model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = speculative_type,+ spec_draft_n_max = requested,+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ )++def test_already_in_target_state_matches_when_draft_n_max_unset():# None on the request means "platform default"; matches any backend.- backend = _mtp_backend(_spec_draft_n_max = None)- assert (- backend._already_in_target_state(- gguf_path = None,- model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = None,- spec_draft_n_max = None,- chat_template_override = None,- extra_args = None,- is_vision = False,- )- is True- )+ assert _draft_n_max_matches(_mtp_backend(_spec_draft_n_max = None), None)def test_already_in_target_state_matches_when_draft_n_max_equals_backend():- backend = _mtp_backend(_spec_draft_n_max = 4)- assert (- backend._already_in_target_state(- gguf_path = None,+ assert _draft_n_max_matches(_mtp_backend(_spec_draft_n_max = 4), 4)+++def test_mtp_draft_n_max_mismatch_survives_active_runtime_state():+ assert not _draft_n_max_matches(_mtp_backend(_spec_draft_n_max = 4), 8, speculative_type = "mtp")+++ ("saved_draft_n_max", "expected_match"),+ [(8, True), (4, False), (None, False)],+)+def test_mtp_draft_n_max_compares_saved_runtime_fallback_intent(saved_draft_n_max, expected_match):+ backend = _mtp_backend(+ _requested_spec_mode = "mtp",+ _speculative_type = None,+ _spec_draft_n_max = None,+ _spec_fallback_reason = "runtime_error",+ _last_load_intent = GgufLoadIntent(model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = None,- spec_draft_n_max = 4,- chat_template_override = None,- extra_args = None,- is_vision = False,- )- is True+ spec_draft_n_max = saved_draft_n_max,+ ),)+ assert _draft_n_max_matches(backend, 8, speculative_type = "mtp") is expected_match-def test_already_in_target_state_mismatches_when_draft_n_max_differs():- backend = _mtp_backend(_spec_draft_n_max = 4)- assert (- backend._already_in_target_state(- gguf_path = None,- model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = None,- spec_draft_n_max = 8,- chat_template_override = None,- extra_args = None,- is_vision = False,- )- is False+def test_mtp_draft_n_max_ignored_when_binary_lacks_mtp():+ backend = _mtp_backend(+ _requested_spec_mode = "mtp",+ _speculative_type = "default",+ _spec_draft_n_max = None,+ _spec_fallback_reason = "binary_no_mtp",)+ assert _draft_n_max_matches(backend, 8, speculative_type = "mtp")def test_already_in_target_state_draft_n_max_ignored_when_not_mtp():@@ -1071,21 +1089,7 @@ def test_already_in_target_state_draft_n_max_ignored_when_not_mtp():_requested_spec_mode = "ngram",_spec_draft_n_max = None,)- assert (- backend._already_in_target_state(- gguf_path = None,- model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = "ngram-mod",- spec_draft_n_max = 8,- chat_template_override = None,- extra_args = None,- is_vision = False,- )- is True- )+ assert _draft_n_max_matches(backend, 8, speculative_type = "ngram-mod")# Sub-3B MTP gate -- tiny dense models regress with the MTP draft head, so@@ -1127,7 +1131,8 @@ def test_already_in_target_state_sub_3b_falls_back_to_ngram_mod_when_supported(m_spec_draft_n_max = None,)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.5-0.8B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -1151,7 +1156,8 @@ def test_already_in_target_state_sub_3b_falls_back_to_off_when_no_ngram(monkeypa_spec_draft_n_max = None,)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.5-0.8B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -1175,7 +1181,8 @@ def test_already_in_target_state_4b_mtp_request_promotes_as_before(monkeypatch):_spec_draft_n_max = None,)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.5-4B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -1200,7 +1207,8 @@ def test_already_in_target_state_2b_falls_back_to_ngram_below_threshold(monkeypa_spec_draft_n_max = None,)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = "unsloth/Qwen3.5-2B-MTP-GGUF",hf_variant = "Q4_K_M",@@ -1770,7 +1778,8 @@ def test_reload_skip_auto_mla_ngram_is_idempotent():_requested_spec_mode = "auto",)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = _GLM_MLA_MODEL,hf_variant = "Q4_K_M",@@ -1794,7 +1803,8 @@ def test_reload_forced_mtp_bounces_auto_mla():_requested_spec_mode = "auto",)assert (- backend._already_in_target_state(+ _matches(+ backend,gguf_path = None,model_identifier = _GLM_MLA_MODEL,hf_variant = "Q4_K_M",@@ -2185,7 +2195,7 @@ def test_already_in_target_state_retries_after_hf_drafter_not_found():_mtp_draft_path = None,_gguf_path = None,)- assert backend._already_in_target_state(**_drafter_not_found_kwargs()) is False+ assert _matches(backend, **_drafter_not_found_kwargs()) is False# 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 ok._already_in_target_state(**_drafter_not_found_kwargs()) is True+ assert _matches(ok, **_drafter_not_found_kwargs()) is Truediff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.pyindex c63f931047e..ddfbf360c85 100644--- a/studio/backend/tests/test_llama_cpp_placement.py+++ b/studio/backend/tests/test_llama_cpp_placement.py@@ -67,7 +67,7 @@ if "httpx" not in sys.modules:)sys.modules["httpx"] = module-from core.inference.llama_cpp import LlamaCppBackend+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend_REAL_POPEN = subprocess.Popen@@ -127,9 +127,11 @@ def _launch(backend, gguf, **load_kwargs):with patch.object(subprocess, "Popen", side_effect = fake_popen):assert backend.load_model(- gguf_path = str(gguf),- model_identifier = "test",- **load_kwargs,+ GgufLoadIntent(+ gguf_path = str(gguf),+ model_identifier = "test",+ **load_kwargs,+ ))return captured@@ -265,9 +267,11 @@ def test_diffusion_does_not_reinterpret_vulkan_ordinals(tmp_path):with pytest.raises(ValueError, match = "no defined mapping"):backend.load_model(- hf_repo = "renamed/model",- hf_variant = "Q4_K_M",- model_identifier = "renamed/model",- speculative_type = "off",- gpu_ids = [1],+ GgufLoadIntent(+ hf_repo = "renamed/model",+ hf_variant = "Q4_K_M",+ model_identifier = "renamed/model",+ speculative_type = "off",+ gpu_ids = [1],+ ))diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex 7f59a2d681b..c52461db2c4 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -24,6 +24,7 @@ if _BACKEND_DIR not in sys.path:from core.inference.llama_cpp import (_MAX_REPROMPTS,_PROVISIONAL_ARGS_MIN_CHARS,+ GgufLoadIntent,LlamaCppBackend,)from core.inference.tool_call_parser import NUDGE_TOOL_CALLS_STATUS@@ -3123,7 +3124,10 @@ def test_a_not_yet_reaped_child_does_not_burn_the_retry(monkeypatch):backend._unload_epoch = 0backend._mtp_runtime_fallback_in_progress = Falsebackend._mtp_runtime_fallback_active = False- backend._last_load_kwargs = {"gguf_path": "/m.gguf"}+ backend._last_load_intent = GgufLoadIntent(+ gguf_path = "/m.gguf",+ model_identifier = "m",+ )backend._model_identifier = "m"dying = backend._processloads: list[dict] = []@@ -3146,8 +3150,8 @@ def test_a_not_yet_reaped_child_does_not_burn_the_retry(monkeypatch):{"status_code": 200, "chunks": [_sse({"content": "Recovered."}), _done()]},)()- def fake_load(**kwargs):- loads.append(kwargs)+ def fake_load(intent):+ loads.append(intent)backend._process = type("Live", (), {"poll": lambda self: None, "returncode": None})()backend._healthy = Truereturn Truediff --git a/studio/backend/tests/test_llm_assist_startup_opt_in.py b/studio/backend/tests/test_llm_assist_startup_opt_in.pyindex e81b1d3775d..6c3f566b90d 100644--- a/studio/backend/tests/test_llm_assist_startup_opt_in.py+++ b/studio/backend/tests/test_llm_assist_startup_opt_in.py@@ -13,10 +13,14 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)+from core.inference import llama_cpp+from core.inference.llama_cpp import GgufLoadIntent+from hub.utils import llm_assist as hub_assistfrom models.datasets import AiAssistMappingRequestfrom routes import datasets as datasets_routefrom routes import settings as settings_routefrom utils import helper_precache_settings+from utils.datasets import llm_assist as dataset_assistdef _install_fake_studio_db(monkeypatch, *, stored = None):@@ -125,3 +129,46 @@ def test_ai_assist_route_still_calls_on_demand_advisor(monkeypatch):"model_type": "text",}]+++def test_helper_backends_load_with_one_intent(monkeypatch):+ loaded = []++ class FakeBackend:+ def load_model(self, intent):+ loaded.append(intent)+ return False++ def unload_model(self):+ return True++ repo, variant = "owner/helper-GGUF", "Q4_K_M"+ monkeypatch.delenv("UNSLOTH_HELPER_MODEL_DISABLE", raising = False)+ monkeypatch.setenv("UNSLOTH_HELPER_MODEL_REPO", repo)+ monkeypatch.setenv("UNSLOTH_HELPER_MODEL_VARIANT", variant)+ monkeypatch.setattr(llama_cpp, "LlamaCppBackend", FakeBackend)++ advisor_kwargs = {"columns": ["text"], "samples": [{"text": "x"}]}+ calls = [+ (lambda: dataset_assist._run_with_helper("prompt"), "helper"),+ (lambda: dataset_assist._run_multi_pass_advisor(**advisor_kwargs), "advisor"),+ (+ lambda: hub_assist._run_multi_pass_advisor(+ **advisor_kwargs,+ dataset_name = None,+ dataset_card = None,+ dataset_metadata = None,+ model_name = None,+ model_type = None,+ ),+ "hub-advisor",+ ),+ ]+ for run, label in calls:+ assert run() is None+ assert loaded.pop() == GgufLoadIntent(+ model_identifier = f"{label}:{repo}:{variant}",+ hf_repo = repo,+ hf_variant = variant,+ n_ctx = 2048,+ )diff --git a/studio/backend/tests/test_mtp_drafter_companion.py b/studio/backend/tests/test_mtp_drafter_companion.pyindex 7262cc380f2..8c857656d57 100644--- a/studio/backend/tests/test_mtp_drafter_companion.py+++ b/studio/backend/tests/test_mtp_drafter_companion.py@@ -410,6 +410,8 @@ def _target_state_kwargs(weight, mtp_draft_path):def test_already_in_target_state_bounces_on_new_drafter(tmp_path):+ from core.inference.llama_cpp import GgufLoadIntent+weight = tmp_path / "gemma-4-12b-it-Q4_K_M.gguf"weight.write_bytes(b"x")drafter = tmp_path / "mtp-gemma-4-12b-it.gguf"@@ -417,10 +419,23 @@ def test_already_in_target_state_bounces_on_new_drafter(tmp_path):# Loaded without a drafter; one now exists on disk -> must reload.b = _loaded_backend(weight, None)- assert not b._already_in_target_state(**_target_state_kwargs(weight, str(drafter)))+ assert not b.adopt_load_intent_if_matched(+ GgufLoadIntent(**_target_state_kwargs(weight, str(drafter)))+ )# Same drafter as launched -> still deduped.b = _loaded_backend(weight, str(drafter))- assert b._already_in_target_state(**_target_state_kwargs(weight, str(drafter)))+ assert b.adopt_load_intent_if_matched(+ GgufLoadIntent(**_target_state_kwargs(weight, str(drafter)))+ )+ intent = dict(+ model_identifier = "local-gemma",+ n_ctx = 4096,+ mtp_draft_path = str(drafter),+ compare_mtp_draft = True,+ )+ assert b.adopt_load_intent_if_matched(GgufLoadIntent(**intent))+ intent["mtp_draft_path"] = None+ assert not b.adopt_load_intent_if_matched(GgufLoadIntent(**intent))def test_detect_gguf_model_rejects_mtp_subdir_copy(tmp_path):diff --git a/studio/backend/tests/test_mtp_vram_budget.py b/studio/backend/tests/test_mtp_vram_budget.pyindex 965c5c9ea24..4074220c6e5 100644--- a/studio/backend/tests/test_mtp_vram_budget.py+++ b/studio/backend/tests/test_mtp_vram_budget.py@@ -986,36 +986,6 @@ class TestExtraArgsMtpDetection:is False)- def test_route_matcher_uses_tensor_parallel_matches_loaded(self):- # Fix: the route duplicate-load matcher must use the downgrade-aware- # helper, or an env-driven tensor server (or its layer downgrade) is- # needlessly reloaded (#6312). Read from disk (importing routes.inference- # drags in heavy deps).- routes_src = (Path(__file__).resolve().parent.parent / "routes" / "inference.py").read_text(- encoding = "utf-8"- )- start = routes_src.index("def _request_matches_loaded_settings")- end = routes_src.index("\ndef ", start + 1)- body = "".join(routes_src[start:end].split())- assert (- "_tensor_parallel_matches_loaded(effective_extra,"- "request.tensor_parallel,llama_backend.tensor_parallel)" in body- )-- def test_route_matcher_retries_after_drafter_not_found(self):- # drafter_not_found must not report "already loaded" or the reload never- # retries the download (#6459). Read source: importing routes pulls deps.- routes_src = (Path(__file__).resolve().parent.parent / "routes" / "inference.py").read_text(- encoding = "utf-8"- )- start = routes_src.index("def _request_matches_loaded_settings")- end = routes_src.index("\ndef ", start + 1)- body = "".join(routes_src[start:end].split())- assert 'llama_backend.spec_fallback_reason=="drafter_not_found"' in body- assert "not_extra_args_set_spec_type(effective_extra)" in body- # HF-only (hf_repo): local/native loads have no download to retry.- assert "llama_backend.hf_repo" in body-def test_extra_args_main_cache_type_heavier_axis(self):# Asymmetric --cache-type-k/-v must budget the heavier axis (extras win# per axis at launch), not the last-wins single type that under-reserves.diff --git a/studio/backend/tests/test_native_context_length.py b/studio/backend/tests/test_native_context_length.pyindex 9417b4c751a..7d64f5a26c8 100644--- a/studio/backend/tests/test_native_context_length.py+++ b/studio/backend/tests/test_native_context_length.py@@ -404,12 +404,13 @@ class TestRouteCompleteness:blocks = self._find_construction_blocks("LoadResponse")gguf_blocks = [b for b in blocks if "is_gguf = True" in b or "is_gguf=True" in b]assert (- len(gguf_blocks) >= 2- ), f"Expected at least 2 GGUF LoadResponse blocks, found {len(gguf_blocks)}"+ len(gguf_blocks) == 1+ ), f"Expected one shared GGUF LoadResponse block, found {len(gguf_blocks)}"for i, block in enumerate(gguf_blocks):assert (- "native_context_length" in block- ), f"GGUF LoadResponse block #{i} missing native_context_length:\n{block[:200]}"+ "_llama_runtime_fields(llama_backend)" in block+ ), f"GGUF LoadResponse block #{i} missing runtime fields:\n{block[:200]}"+ assert "for name in _InferenceRuntimeFields.model_fields" in self._sourcedef test_non_gguf_load_responses_omit_field(self):"""Non-GGUF LoadResponse blocks do not set native_context_length (defaults to None)."""@@ -437,12 +438,11 @@ class TestRouteCompleteness:blocks = self._find_construction_blocks("InferenceStatusResponse")found = Falsefor block in blocks:- if "llama_backend" in block and "native_context_length" in block:+ if "llama_backend" in block and "_llama_runtime_fields(llama_backend)" in block:found = Truebreak- assert (- found- ), "No InferenceStatusResponse block with llama_backend has native_context_length"+ assert found, "No InferenceStatusResponse block with llama_backend has runtime fields"+ assert "for name in _InferenceRuntimeFields.model_fields" in self._sourcedef test_non_gguf_status_path_reports_runtime_context_length(self):"""Non-GGUF InferenceStatusResponse reports context_length from model_info."""diff --git a/studio/backend/tests/test_native_gguf_companion.py b/studio/backend/tests/test_native_gguf_companion.pyindex 3a7b4b0caf1..9d5a07333a4 100644--- a/studio/backend/tests/test_native_gguf_companion.py+++ b/studio/backend/tests/test_native_gguf_companion.py@@ -6,6 +6,7 @@from __future__ import annotationsimport sys+from types import SimpleNamespacefrom pathlib import Pathimport pytest@@ -16,15 +17,49 @@ if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)from routes.inference import _validate_native_gguf_companion-from routes.inference import _request_matches_loaded_settings+from routes.inference import _resolve_gguf_load_intentfrom routes.inference import _validate_native_mtp_drafterfrom routes.inference import _loaded_is_local_model+from routes.inference import _mtp_draft_for_pathfrom routes.inference import _native_gguf_companion_usable-from utils.models.model_config import detect_mtp_file+from utils.models.model_config import _local_gguf_companion_search_root, detect_mtp_filefrom core.inference.llama_cpp import LlamaCppBackendfrom models.inference import LoadRequest+def _request_matches_loaded_settings(+ request,+ backend,+ _template = None,+ native_grant_backed = False,+):+ model_path = backend.gguf_path+ root = _local_gguf_companion_search_root(model_path, model_path)+ draft = detect_mtp_file(model_path, search_root = root)+ config = SimpleNamespace(+ identifier = request.model_path,+ gguf_hf_repo = None,+ gguf_variant = request.gguf_variant,+ gguf_file = model_path,+ gguf_mmproj_file = None,+ gguf_mtp_file = draft,+ is_vision = False,+ )+ intent = _resolve_gguf_load_intent(+ config,+ request,+ native_grant_backed = native_grant_backed,+ chat_template_override = None,+ extra_args = None,+ placement = SimpleNamespace(+ resolved_gpu_ids = None,+ gpu_ids_are_vulkan_ordinals = False,+ ),+ n_parallel = 1,+ )+ return backend._runtime_matches_intent(intent, None)++def _write_pair(tmp_path: Path, folder: str | None = None) -> tuple[Path, Path]:tmp_path.mkdir(parents = True, exist_ok = True)weight = tmp_path / "model.gguf"@@ -364,6 +399,11 @@ def test_native_load_skips_rejected_mtp_candidate_for_next_one(tmp_path):assert detect_mtp_file(str(weight), str(tmp_path), skip_root = True, accept = _usable) == str(larger.resolve())+ assert _mtp_draft_for_path(+ str(weight),+ True,+ log_native_fallback = True,+ ) == str(larger.resolve())def test_native_load_returns_none_when_no_candidate_passes(tmp_path):diff --git a/studio/backend/tests/test_parallel_slots_per_load.py b/studio/backend/tests/test_parallel_slots_per_load.pyindex bd21eff480b..66750b93143 100644--- a/studio/backend/tests/test_parallel_slots_per_load.py+++ b/studio/backend/tests/test_parallel_slots_per_load.py@@ -41,7 +41,7 @@ import httpx # noqa: F401from core.inference import llama_cpp as llama_cpp_modulefrom core.inference.llama_server_args import PARALLEL_MAX, PARALLEL_MIN-from core.inference.llama_cpp import LlamaCppBackend+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackendfrom models.inference import (InferenceStatusResponse,LoadRequest,@@ -100,7 +100,7 @@ def test_validate_request_n_parallel_contract():@pytest.mark.parametrize("model_cls", [LoadResponse, InferenceStatusResponse])-def test_response_models_emit_parallel_slot_fields(model_cls):+def test_response_models_emit_runtime_fields(model_cls):kwargs = (dict(status = "loaded", model = "owner/repo", display_name = "repo", inference = {})if model_cls is LoadResponse@@ -109,9 +109,19 @@ def test_response_models_emit_parallel_slot_fields(model_cls):empty = model_cls(**kwargs).model_dump()assert empty["requested_parallel_slots"] is Noneassert empty["parallel_slots"] is None- dumped = model_cls(**kwargs, requested_parallel_slots = 8, parallel_slots = 4).model_dump()+ assert empty["gpu_ids"] is None+ assert empty["requested_gpu_ids"] is None+ dumped = model_cls(+ **kwargs,+ requested_parallel_slots = 8,+ parallel_slots = 4,+ gpu_ids = [1],+ requested_gpu_ids = [1, 2],+ ).model_dump()assert dumped["requested_parallel_slots"] == 8assert dumped["parallel_slots"] == 4+ assert dumped["gpu_ids"] == [1]+ assert dumped["requested_gpu_ids"] == [1, 2]# ── Shared bounds and their deliberate mirrors ───────────────────────@@ -212,15 +222,13 @@ def test_unload_resets_requested_parallel_slots(backend):assert backend.requested_parallel_slots == 1-def test_load_model_commits_requested_from_pending_kwargs():+def test_load_model_commits_requested_from_intent():# n_parallel may be reduced before the commit, so the requested value must- # come from the pre-reduction pending snapshot.+ # come from the immutable pre-reduction intent.src = inspect.getsource(LlamaCppBackend.load_model)- commit = src.find(- 'self._requested_n_parallel = max(1, int(_pending_load_kwargs["n_parallel"]))'- )+ commit = src.find("self._requested_n_parallel = max(1, int(intent.n_parallel))")healthy = src.find("self._healthy = True\n", 0, commit if commit != -1 else None)- snapshot = src.find("self._last_load_kwargs = _pending_load_kwargs")+ snapshot = src.find("self._last_load_intent = intent")assert commit != -1, "load_model must commit the requested slot count"assert healthy != -1 and healthy < commit < snapshot@@ -245,17 +253,19 @@ def _loaded_backend() -> LlamaCppBackend:def _target_state(backend: LlamaCppBackend, n_parallel: int) -> bool:- return backend._already_in_target_state(- gguf_path = None,- model_identifier = "owner/repo",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = "auto",- chat_template_override = None,- extra_args = None,- is_vision = False,- n_parallel = n_parallel,+ return backend.adopt_load_intent_if_matched(+ GgufLoadIntent(+ gguf_path = None,+ model_identifier = "owner/repo",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = "auto",+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ n_parallel = n_parallel,+ ))@@ -304,58 +314,43 @@ def _load_impl_source() -> str:def test_route_resolves_slots_once_before_dedupe_guard_and_load():load_impl = _load_impl_source()- resolve = load_impl.index("request.n_parallel")- fallback = load_impl.index('getattr(_app_state, "llama_parallel_slots", 1)')- dedupe = load_impl.index("requested_parallel_slots = _n_parallel")+ resolve = load_impl.index("_resolve_parallel_slots(request, fastapi_request)")+ active_intent = load_impl.index("_active_gguf_intent(")+ fast_dedupe = load_impl.rindex("_reuse_loaded_gguf(", 0, active_intent)+ resolved_intent = load_impl.index("_resolve_gguf_load_intent(")+ resolved_dedupe = load_impl.index("_reuse_loaded_gguf(", resolved_intent)guard = load_impl.index("_guard_chat_load_against_training")- # The GGUF launch kwargs, not the guard's own kwarg (which shares the spelling).- load_kwargs = load_impl.index("_common_load_kwargs = dict(")- assert resolve < dedupe, "resolution must precede the reload dedupe"- assert fallback < dedupe- assert resolve < guard < load_kwargs- # Guard and load kwargs share the resolved value; app.state is read once.- assert load_impl.count("n_parallel = _n_parallel") == 2- assert "n_parallel = _n_parallel" in load_impl[load_kwargs : load_kwargs + 800]- assert load_impl.count('getattr(_app_state, "llama_parallel_slots", 1)') == 1- # getattr, so a direct caller without an app cannot raise, and no re-read.+ load_call = load_impl.index("llama_backend.load_model")+ assert resolve < fast_dedupe < active_intent+ assert active_intent < resolved_intent < resolved_dedupe+ assert resolved_dedupe < guard < load_call+ # Both immutable intents and the guard share the value; resolution runs once.+ assert load_impl.count("n_parallel = _n_parallel") == 3+ assert load_impl.count("_resolve_parallel_slots(request, fastapi_request)") == 1assert "fastapi_request.app.state" not in load_impl-def test_route_dedupe_compares_requested_slots_and_skips_diffusion():- match_impl = _route_source()[_route_source().index("def _request_matches_loaded_settings") :]- match_impl = match_impl[: match_impl.index("\ndef ")]- assert "requested_parallel_slots is not None" in match_impl- assert "not llama_backend.is_diffusion" in match_impl- assert "llama_backend.requested_parallel_slots" in match_impl---def test_route_echoes_requested_and_effective_slots():- route_src = _route_source()- # Both /load returns plus the /status GGUF branch, via the shared helper.- assert route_src.count("**_parallel_slot_echo(llama_backend)") == 3--def test_parallel_slot_echo_reports_none_for_diffusion():# Diffusion never commits a count, so echoing the reset placeholder 1 would lie.- from routes.inference import _parallel_slot_echo+ from routes.inference import _llama_runtime_fieldsbackend = _loaded_backend()backend._requested_n_parallel = 8backend._commit_effective_parallel_slots(4)- assert _parallel_slot_echo(backend) == {"requested_parallel_slots": 8, "parallel_slots": 4}+ fields = _llama_runtime_fields(backend)+ assert (fields["requested_parallel_slots"], fields["parallel_slots"]) == (8, 4)backend._is_diffusion = True- assert _parallel_slot_echo(backend) == {- "requested_parallel_slots": None,- "parallel_slots": None,- }+ fields = _llama_runtime_fields(backend)+ assert (fields["requested_parallel_slots"], fields["parallel_slots"]) == (None, None)def test_validate_route_prefers_request_n_parallel():- validate_impl = _route_source()[_route_source().index("async def validate_model") :]- resolve = validate_impl.index("request.n_parallel")- fallback = validate_impl.index('"llama_parallel_slots",')- guard = validate_impl.index("_guard_chat_load_against_training")- assert guard < resolve and guard < fallback, "the guard call resolves the slots inline"+ route_source = _route_source()+ helper = route_source[route_source.index("def _resolve_parallel_slots") :]+ helper = helper[: helper.index("\n\n")]+ assert helper.index("request.n_parallel") < helper.index('"llama_parallel_slots"')+ validate_impl = route_source[route_source.index("async def validate_model") :]+ assert "n_parallel = _resolve_parallel_slots(request, fastapi_request)" in validate_impldef _load_model_source() -> str:@@ -379,7 +374,7 @@ def test_clamp_sits_between_the_echo_and_the_fit():# The echo reports the ask and the fit uses what launches, so the clamp# belongs between the two.src = _load_model_source()- pending = src.index("_pending_load_kwargs")+ pending = src.index("n_parallel = intent.n_parallel")clamp = src.index("supports_kv_unified")estimate = src.index("_estimate")commit = src.index("_commit_effective_parallel_slots")@@ -463,15 +458,22 @@ def _guard_required_gb(classmethod(lambda cls, binary = None: dict(caps or {})),)- inf._guard_chat_load_against_training(- _types.SimpleNamespace(is_gguf = True, gguf_file = gguf_path, identifier = "local/model"),- model_identifier = "local/model",+ config = _types.SimpleNamespace(is_gguf = True, gguf_file = gguf_path, identifier = "local/model")+ request = _types.SimpleNamespace(+ model_path = "local/model",hf_token = None,- load_in_4bit = False,max_seq_length = 8192,- requested_gpu_ids = None,- n_parallel = n_parallel,+ cache_type_kv = None,+ tensor_parallel = False,gpu_memory_mode = "auto",+ gpu_layers = -1,+ )+ inf._guard_chat_load_against_training(+ config,+ request,+ load_in_4bit = False,+ placement = inf._LoadPlacement(None, None, False, inf._classify_diffusion_gguf(config)),+ n_parallel = n_parallel,)return seen["required_override_gb"]diff --git a/studio/backend/tests/test_tensor_parallel.py b/studio/backend/tests/test_tensor_parallel.pyindex 88be5d89760..e0a55f45902 100644--- a/studio/backend/tests/test_tensor_parallel.py+++ b/studio/backend/tests/test_tensor_parallel.py@@ -24,6 +24,7 @@ import sysimport threadingimport timeimport types as _types+from dataclasses import replacefrom pathlib import Pathimport pytest@@ -65,7 +66,11 @@ _httpx_stub.Client = type(sys.modules.setdefault("httpx", _httpx_stub)from core.inference import llama_cpp as llama_cpp_module-from core.inference.llama_cpp import _CTX_FIT_VRAM_FRACTION, LlamaCppBackend+from core.inference.llama_cpp import (+ _CTX_FIT_VRAM_FRACTION,+ GgufLoadIntent,+ LlamaCppBackend,+)from core.inference.llama_server_args import (_effective_tensor_parallel,resolve_tensor_parallel,@@ -180,17 +185,19 @@ def _loaded_backend(tensor_parallel: bool) -> LlamaCppBackend:def _target_state(backend: LlamaCppBackend, tensor_parallel: bool) -> bool:- return backend._already_in_target_state(- gguf_path = None,- model_identifier = "owner/repo",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = "auto",- chat_template_override = None,- extra_args = None,- is_vision = False,- tensor_parallel = tensor_parallel,+ return backend.adopt_load_intent_if_matched(+ GgufLoadIntent(+ gguf_path = None,+ model_identifier = "owner/repo",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = "auto",+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ tensor_parallel = tensor_parallel,+ ))@@ -222,17 +229,19 @@ def test_already_in_target_state_reconciles_split_mode_extras():backend = _loaded_backend(tensor_parallel = True)backend._extra_args = ["--split-mode", "tensor"]assert (- backend._already_in_target_state(- gguf_path = None,- model_identifier = "owner/repo",- hf_variant = "Q4_K_M",- n_ctx = 8192,- cache_type_kv = None,- speculative_type = "auto",- chat_template_override = None,- extra_args = ["--split-mode", "tensor"],- is_vision = False,- tensor_parallel = False,+ backend.adopt_load_intent_if_matched(+ GgufLoadIntent(+ gguf_path = None,+ model_identifier = "owner/repo",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = "auto",+ chat_template_override = None,+ extra_args = ["--split-mode", "tensor"],+ is_vision = False,+ tensor_parallel = False,+ ))is True)@@ -338,12 +347,12 @@ def _recovery_backend() -> LlamaCppBackend:b._speculative_type = "draft-mtp"b._mtp_runtime_fallback_active = Trueb._process = _FakeProcess()- b._last_load_kwargs = {- "model_identifier": "owner/repo",- "tensor_parallel": True,- "speculative_type": "auto",- "n_parallel": 4,- }+ b._last_load_intent = GgufLoadIntent(+ model_identifier = "owner/repo",+ tensor_parallel = True,+ speculative_type = "auto",+ n_parallel = 4,+ )return b@@ -361,8 +370,8 @@ def test_runtime_recovery_reloads_without_mtp(monkeypatch):done = threading.Event()captured = {}- def _fake_load_model(**kwargs):- captured.update(kwargs)+ def _fake_load_model(intent):+ captured.update(vars(intent))done.set()return True@@ -388,7 +397,7 @@ def test_runtime_recovery_reloads_without_mtp(monkeypatch):"mutate",[lambda b: setattr(b, "_mtp_runtime_fallback_active", False),- lambda b: setattr(b, "_last_load_kwargs", None),+ lambda b: setattr(b, "_last_load_intent", None),lambda b: setattr(b, "_process", None),lambda b: b._cancel_event.set(),],@@ -399,7 +408,7 @@ def test_runtime_recovery_skips_when_not_applicable(monkeypatch, mutate):b = _recovery_backend()mutate(b)calls = []- monkeypatch.setattr(b, "load_model", lambda **k: calls.append(k))+ monkeypatch.setattr(b, "load_model", lambda intent: calls.append(intent))assert b._maybe_recover_from_mtp_crash(RuntimeError()) is Falseassert calls == []@@ -435,8 +444,8 @@ def test_runtime_recovery_fires_for_user_env_mtp(monkeypatch):done = threading.Event()captured = {}- def _fake_load_model(**kwargs):- captured.update(kwargs)+ def _fake_load_model(intent):+ captured.update(vars(intent))done.set()return True@@ -450,12 +459,15 @@ 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.b = _recovery_backend()- b._last_load_kwargs = dict(b._last_load_kwargs, extra_args = ["--spec-type", "draft-mtp"])+ b._last_load_intent = replace(+ b._last_load_intent,+ extra_args = ["--spec-type", "draft-mtp"],+ )done = threading.Event()captured = {}- def _fake_load_model(**kwargs):- captured.update(kwargs)+ def _fake_load_model(intent):+ captured.update(vars(intent))done.set()return True@@ -470,10 +482,10 @@ def test_runtime_recovery_restores_requested_mode(monkeypatch):# After the off-reload, /status must show the user's requested mode + the# runtime-error note, not a bare "off" (matches the startup MTP fallback).b = _recovery_backend()- b._last_load_kwargs = dict(b._last_load_kwargs, speculative_type = "mtp")+ b._last_load_intent = replace(b._last_load_intent, speculative_type = "mtp")done = threading.Event()- def _fake_load_model(**kwargs):+ def _fake_load_model(intent):b._requested_spec_mode = "off" # what a real off-reload would leave behinddone.set()return True@@ -495,7 +507,7 @@ def test_runtime_recovery_skips_when_process_replaced(monkeypatch):p1 = _BlockingDeadProc()b._process = p1calls = []- monkeypatch.setattr(b, "load_model", lambda **k: calls.append(k))+ monkeypatch.setattr(b, "load_model", lambda intent: calls.append(intent))assert b._maybe_recover_from_mtp_crash(RuntimeError()) is True # captures p1b._process = _FakeProcess() # a newer load swapped the live processp1.release() # p1 now reports dead -> recovery runs its staleness check@@ -509,9 +521,9 @@ def test_runtime_recovery_skips_when_snapshot_changed(monkeypatch):p1 = _BlockingDeadProc()b._process = p1calls = []- monkeypatch.setattr(b, "load_model", lambda **k: calls.append(k))+ monkeypatch.setattr(b, "load_model", lambda intent: calls.append(intent))assert b._maybe_recover_from_mtp_crash(RuntimeError()) is True- b._last_load_kwargs = dict(b._last_load_kwargs, model_identifier = "other/model")+ b._last_load_intent = replace(b._last_load_intent, model_identifier = "other/model")p1.release()time.sleep(0.6)assert calls == []@@ -523,7 +535,7 @@ def test_runtime_recovery_is_single_flight(monkeypatch):started = threading.Event()release = threading.Event()- def _slow_load(**kwargs):+ def _slow_load(intent):started.set()release.wait(timeout = 5)return True@@ -555,13 +567,12 @@ def test_single_flight_claim_is_released_when_the_reload_cannot_start(monkeypatcassert b._mtp_runtime_fallback_in_progress is False-def test_load_kwargs_are_read_once_before_the_claim(monkeypatch):+def test_load_intent_is_read_once_before_the_claim(monkeypatch):# Gate and snapshot must share one read: reading twice lets an unload null- # _last_load_kwargs in between, so dict(None) raises after the claim and strands- # the flag with no thread alive to clear it.+ # the intent in between and strand the flag with no thread alive to clear it.b = _recovery_backend()- class _CountingKwargs: # data descriptor, so it wins over the instance dict+ class _CountingIntent:def __init__(self, value):self.value = valueself.reads = 0@@ -575,8 +586,8 @@ def test_load_kwargs_are_read_once_before_the_claim(monkeypatch):def __set__(self, obj, value):self.value = value- counter = _CountingKwargs({"model_identifier": "owner/repo"})- monkeypatch.setattr(type(b), "_last_load_kwargs", counter, raising = False)+ counter = _CountingIntent(GgufLoadIntent(model_identifier = "owner/repo"))+ monkeypatch.setattr(type(b), "_last_load_intent", counter, raising = False)class _UnstartedThread: # keep the reload off-thread so only sync reads countdef __init__(self, *args, **kwargs):@@ -593,11 +604,11 @@ def test_load_kwargs_are_read_once_before_the_claim(monkeypatch):def test_respawn_defers_to_an_inflight_mtp_reload(monkeypatch):# "Already recovering" must not read as "not an MTP crash": respawning replays the- # crashing MTP kwargs and aborts the in-flight no-MTP reload on its "newer load" check.+ # crashing MTP intent and aborts the in-flight no-MTP reload on its "newer load" check.b = _recovery_backend()b._mtp_runtime_fallback_in_progress = True- loads: list[dict] = []- monkeypatch.setattr(b, "load_model", lambda **kwargs: loads.append(kwargs) or True)+ loads: list[GgufLoadIntent] = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)assert b._respawn_if_dead() is Falseassert loads == []@@ -606,7 +617,7 @@ def test_respawn_defers_to_an_inflight_mtp_reload(monkeypatch):b._mtp_runtime_fallback_in_progress = Falseb._process.returncode = -9 # only the respawn path logs itassert b._respawn_if_dead() is True- assert [kw.get("speculative_type") for kw in loads] == ["auto"]+ assert [intent.speculative_type for intent in loads] == ["auto"]def test_respawn_does_not_wait_out_the_grace_on_a_replacement(monkeypatch):@@ -628,7 +639,7 @@ def test_respawn_does_not_wait_out_the_grace_on_a_replacement(monkeypatch):b._healthy = Trueb._process.returncode = -9 # only the respawn path logs itlive = _LiveProcess()- loads: list[dict] = []+ loads: list[GgufLoadIntent] = []guard = threading.Lock()all_in_flight = threading.Event()@@ -653,14 +664,14 @@ def test_respawn_does_not_wait_out_the_grace_on_a_replacement(monkeypatch):b.__class__ = _Tracked- def _load(**kwargs):+ def _load(intent):# A real load_model takes seconds, so every caller that lost this child is in# flight before the replacement appears; waiting reproduces that ordering. The# timeout keeps the pre-fix build, where losers cannot read until the lock is# free, from hanging instead of failing.all_in_flight.wait(timeout = 2)with guard:- loads.append(kwargs)+ loads.append(intent)b._process = liveb._healthy = True # the real load_model marks the new server healthyreturn True@@ -718,13 +729,13 @@ class _DyingChild(_FakeProcess):def test_respawn_does_not_resurrect_a_deliberate_unload(monkeypatch):# unload_model() sets _cancel_event before killing, so a request that loses the# connection can watch that deliberate exit through the grace loop and call it a- # crash, with _last_load_kwargs still populated (unload clears it after the kill).+ # crash, with _last_load_intent still populated (unload clears it after the kill).b = _recovery_backend()b._healthy = Trueb._process = _DyingChild()b._cancel_event.set()- loads: list[dict] = []- monkeypatch.setattr(b, "load_model", lambda **kwargs: loads.append(kwargs) or True)+ loads: list[GgufLoadIntent] = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)assert b._respawn_if_dead() is Falseassert loads == [], "resurrected a model the user unloaded"@@ -735,22 +746,22 @@ def test_respawn_rechecks_the_cancel_flag_after_the_grace_wait(monkeypatch):b = _recovery_backend()b._healthy = Trueb._process = _DyingChild(on_death = b._cancel_event.set)- loads: list[dict] = []- monkeypatch.setattr(b, "load_model", lambda **kwargs: loads.append(kwargs) or True)+ loads: list[GgufLoadIntent] = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)assert b._respawn_if_dead() is Falseassert loads == [], "checked the cancel flag only before the wait"def test_respawn_does_not_revert_a_newer_load(monkeypatch):- # A model switch landing while we wait must win; replaying the old kwargs would+ # A model switch landing while we wait must win; replaying the old intent would# swap the user's new model back out.b = _recovery_backend()b._healthy = Truereplacement = _DyingChild(alive_polls = 10**6)b._process = _DyingChild(on_death = lambda: setattr(b, "_process", replacement))- loads: list[dict] = []- monkeypatch.setattr(b, "load_model", lambda **kwargs: loads.append(kwargs) or True)+ loads: list[GgufLoadIntent] = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)b._respawn_if_dead()assert loads == [], "replayed stale kwargs over a newer load"@@ -762,8 +773,8 @@ def test_respawn_still_recovers_an_ordinary_crash(monkeypatch):b = _recovery_backend()b._healthy = Trueb._process = _DyingChild(code = -9)- loads: list[dict] = []- monkeypatch.setattr(b, "load_model", lambda **kwargs: loads.append(kwargs) or True)+ loads: list[GgufLoadIntent] = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)assert b._respawn_if_dead() is Trueassert len(loads) == 1@@ -791,8 +802,8 @@ def test_a_transient_error_against_a_live_server_costs_nothing(monkeypatch):b._healthy = Trueb._process = _NeverReapable()b._port = listener.getsockname()[1]- loads: list[dict] = []- monkeypatch.setattr(b, "load_model", lambda **kwargs: loads.append(kwargs) or True)+ loads: list[GgufLoadIntent] = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)started = time.monotonic()assert b._respawn_if_dead() is True@@ -818,8 +829,8 @@ def test_a_closed_port_still_waits_for_the_child_to_be_reapable(monkeypatch):b._healthy = Trueb._process = _DyingChild(code = -9)b._port = dead_port- loads: list[dict] = []- monkeypatch.setattr(b, "load_model", lambda **kwargs: loads.append(kwargs) or True)+ loads: list[GgufLoadIntent] = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)assert b._respawn_if_dead() is Trueassert len(loads) == 1@@ -839,8 +850,8 @@ def test_socket_fast_path_honours_a_pending_unload(monkeypatch):b._process = _NeverReapable()b._port = listener.getsockname()[1]b._cancel_event.set()- loads: list[dict] = []- monkeypatch.setattr(b, "load_model", lambda **kwargs: loads.append(kwargs) or True)+ loads: list[GgufLoadIntent] = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)assert b._respawn_if_dead() is Falseassert loads == []@@ -851,14 +862,14 @@ def test_socket_fast_path_honours_a_pending_unload(monkeypatch):def test_an_unload_landing_during_the_reload_is_undone(monkeypatch):# The cancel check cannot live under _serial_load_lock alone: unload_model never# takes that lock, so it can land entirely between the check and load_model and- # the captured kwargs then restart a model the user stopped. load_model clears+ # the captured intent then restarts a model the user stopped. load_model clears# _cancel_event on the way in, so _unload_epoch is the surviving evidence.b = _recovery_backend()b._healthy = Trueb._process = _FakeProcess()b._process.returncode = -9- loads: list[dict] = []- monkeypatch.setattr(b, "load_model", lambda **kwargs: loads.append(kwargs) or True)+ loads: list[GgufLoadIntent] = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)unloads: list[int] = []real_unload = b.unload_modeldiff --git a/studio/backend/tests/test_tp_vision_regression.py b/studio/backend/tests/test_tp_vision_regression.pyindex b025cdfe47b..7e5668ef4b1 100644--- a/studio/backend/tests/test_tp_vision_regression.py+++ b/studio/backend/tests/test_tp_vision_regression.py@@ -74,7 +74,7 @@ except ImportError:)sys.modules["httpx"] = _httpx_stub-from core.inference.llama_cpp import LlamaCppBackend # noqa: E402+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend # noqa: E402_GB = 1024**3@@ -418,11 +418,8 @@ def test_tensor_split_layer_min_gpus_bump_requires_tensor_request():def test_layer_fallback_retry_preserves_multi_gpu_intent():- """load_model takes a preserve_multi_gpu_on_layer hint and raises _layer_min_gpus- for it, so the tensor-off fallback retry still spreads a fitting model (#6659)."""- sig = inspect.signature(LlamaCppBackend.load_model)- assert "preserve_multi_gpu_on_layer" in sig.parameters- assert sig.parameters["preserve_multi_gpu_on_layer"].default is False+ """The intent carries the preservation hint into the placement planner."""+ assert GgufLoadIntent.__dataclass_fields__["preserve_multi_gpu_on_layer"].default is Falsefn = _load_model_ast()found = any(isinstance(n, ast.If)@@ -457,14 +454,13 @@ def test_fallback_hint_uses_effective_tensor_request_not_just_toggle():just the toggle, so extra/env-driven tensor users keep multi-GPU (#6659)."""route = Path(_BACKEND_DIR) / "routes" / "inference.py"src = route.read_text(encoding = "utf-8")- idx = src.find("_tensor_intent_overall = _effective_tensor_parallel(")+ idx = src.find("_effective_tensor = _effective_tensor_parallel(")assert idx != -1, "the GGUF load closure must compute tensor intent"block = src[idx : idx + 300]assert "extra_llama_args, request.tensor_parallel" in blockpres = src.find("preserve_multi_gpu_on_layer = bool(")- assert (- "_effective_tensor_parallel(attempt_extra_args, tensor_parallel)" in src[pres : pres + 200]- )+ preserve_block = "".join(src[pres : pres + 300].split())+ assert "_effective_tensor_parallel(attempt_extra_args,tensor_parallel)" in preserve_block# not the toggle-only form this replacedassert ("bool(\n request.tensor_parallel and not tensor_parallel" not in src@@ -489,13 +485,13 @@ def test_preserved_fallback_carried_across_non_drop_reload():switch / explicit drop doesn't inherit it (#6659)."""route = Path(_BACKEND_DIR) / "routes" / "inference.py"src = route.read_text(encoding = "utf-8")- idx = src.find("_tensor_intent_overall = _effective_tensor_parallel(")+ idx = src.find("_effective_tensor = _effective_tensor_parallel(")assert idx != -1- block = src[idx : idx + 400]+ block = src[idx : idx + 500]assert "_carry_preserved_tensor_intent(" in block- assert "preserved = llama_backend.layer_preserves_tensor_intent" in block- assert "same_model = _same_model_loaded" in block- assert "explicit_drop = _explicit_tensor_drop" in block+ assert '"layer_preserves_tensor_intent", False' in block+ assert "same_model = same_loaded_model" in block+ assert "explicit_drop = _is_explicit_tensor_drop(request)" in blockdef test_same_model_guard_checks_path_and_variant():@@ -504,16 +500,12 @@ def test_same_model_guard_checks_path_and_variant():and also matches the loaded quant by path (local multi-variant dir) else variant (HFrepo), so a reload keeps the carry-forward and a different variant doesn't inheritthe prior one's preserved tensor intent (#6659)."""- route = Path(_BACKEND_DIR) / "routes" / "inference.py"- src = route.read_text(encoding = "utf-8")- idx = src.find("_same_model_loaded = (")- assert idx != -1- block = src[idx : idx + 1300]- # Identity compares the normalized config.identifier, not the raw model_identifier.- head = src[idx : idx + 200]- assert "config.identifier" in head and "== (model_identifier" not in head- assert "llama_backend.gguf_path" in block and "config.gguf_file" in block- assert "llama_backend.hf_variant" in block and "config.gguf_variant" in block+ route = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")+ assert "same_loaded_model = llama_backend.matches_load_source(gguf_intent)" in route+ matcher = inspect.getsource(LlamaCppBackend.matches_load_source)+ assert "_model_identifier" in matcher and "intent.model_identifier" in matcher+ assert "_gguf_path" in matcher and "intent.gguf_path" in matcher+ assert "_hf_variant" in matcher and "intent.hf_variant" in matcherdef test_diffusion_load_clears_preserved_tensor_flag():@@ -552,16 +544,11 @@ def test_is_tensor_split_assert_marker():def test_layer_preserve_hint_replayed_on_respawn():- """The preserve hint is in the replay snapshot (_pending_load_kwargs), so a+ """The preserve hint is in the immutable replay intent, so arespawn keeps the downgraded model multi-GPU (Codex review on #6659)."""src = inspect.getsource(LlamaCppBackend.load_model)- pend = src.find("_pending_load_kwargs = {")- assert pend != -1- block = src[pend : src.find("}", pend) + 1]- assert '"preserve_multi_gpu_on_layer": preserve_multi_gpu_on_layer' in block, (- "the layer-preserve hint must be in the replay snapshot so _respawn_if_dead "- "keeps the multi-GPU placement"- )+ assert "preserve_multi_gpu_on_layer = intent.preserve_multi_gpu_on_layer" in src+ assert "self._last_load_intent = intent" in srcdef test_should_record_tensor_split_abort_decision():@@ -641,6 +628,43 @@ def _fallback_loaded_backend(layer_preserves_tensor_intent: bool) -> LlamaCppBacreturn b+def _matches_request(request, backend) -> bool:+ routes = _load_inference_routes_module()+ backend_extra = list(backend.extra_args or ())+ effective_extra = (+ request.llama_extra_args+ if request.llama_extra_args is not None+ else routes.strip_shadowing_flags(+ backend_extra,+ strip_split_mode = routes._should_strip_split_mode(request, backend_extra),+ strip_tensor_split = routes._should_strip_tensor_split(request),+ strip_offload = request.gpu_memory_mode == "manual",+ )+ )+ compare_extra = list(effective_extra or ())+ if request.llama_extra_args is not None and request.gpu_ids:+ compare_extra = backend._strip_device_extra_args(compare_extra)+ intent = GgufLoadIntent(+ model_identifier = backend.model_identifier or request.model_path,+ n_ctx = request.max_seq_length,+ cache_type_kv = request.cache_type_kv,+ speculative_type = request.speculative_type,+ spec_draft_n_max = request.spec_draft_n_max,+ tensor_parallel = request.tensor_parallel,+ gpu_memory_mode = request.gpu_memory_mode,+ gpu_layers = request.gpu_layers,+ n_cpu_moe = request.n_cpu_moe,+ tensor_split = request.tensor_split,+ gpu_ids = request.gpu_ids,+ n_parallel = request.n_parallel or 1,+ extra_args = effective_extra,+ preserve_multi_gpu_on_layer = (+ backend.layer_preserves_tensor_intent and not routes._is_explicit_tensor_drop(request)+ ),+ )+ return backend._runtime_matches_intent(intent, compare_extra)++def test_tensor_off_echo_preserves_multi_gpu_fallback():"""The Unsloth UI always sends tensor_parallel and echoes the /load response'sresolved value, so after a fallback a ctx/settings reload carries tensor_parallel=@@ -648,48 +672,38 @@ def test_tensor_off_echo_preserves_multi_gpu_fallback():preserved multi-GPU placement -- it dedupes (Codex #6659)."""from models.inference import LoadRequest- inference_routes = _load_inference_routes_module()-req = LoadRequest(model_path = "owner/repo", tensor_parallel = False)assert "tensor_parallel" in req.model_fields_set, "the UI always sends the field"# Preserved fallback + bare tensor=false echo: dedupe, keep multi-GPU (no collapse).assert (- inference_routes._request_matches_loaded_settings(- req, _fallback_loaded_backend(layer_preserves_tensor_intent = True)- )- is True+ _matches_request(req, _fallback_loaded_backend(layer_preserves_tensor_intent = True)) is True)# A genuine layer load (no preserved intent): tensor-off also dedupes, no churn.assert (- inference_routes._request_matches_loaded_settings(- req, _fallback_loaded_backend(layer_preserves_tensor_intent = False)- )- is True+ _matches_request(req, _fallback_loaded_backend(layer_preserves_tensor_intent = False)) is True)def test_route_dedupe_reloads_when_swa_full_env_changes(monkeypatch):from models.inference import LoadRequest- inference_routes = _load_inference_routes_module()backend = _fallback_loaded_backend(layer_preserves_tensor_intent = False)monkeypatch.setenv("LLAMA_ARG_SWA_FULL", "1")request = LoadRequest(model_path = "owner/repo")- assert inference_routes._request_matches_loaded_settings(request, backend) is False+ assert _matches_request(request, backend) is Falsedef test_route_dedupe_ignores_swa_full_for_diffusion(monkeypatch):from models.inference import LoadRequest- inference_routes = _load_inference_routes_module()backend = _fallback_loaded_backend(layer_preserves_tensor_intent = False)backend._is_diffusion = Truemonkeypatch.setenv("LLAMA_ARG_SWA_FULL", "1")request = LoadRequest(model_path = "owner/repo")- assert inference_routes._request_matches_loaded_settings(request, backend) is True+ assert _matches_request(request, backend) is Truedef test_explicit_split_mode_layer_extras_reloads_after_multi_gpu_fallback():@@ -697,15 +711,10 @@ def test_explicit_split_mode_layer_extras_reloads_after_multi_gpu_fallback():matches the stored fallback extras but must still reload (reviewer.py P1, #6659)."""from models.inference import LoadRequest- inference_routes = _load_inference_routes_module()-req = LoadRequest(model_path = "owner/repo", llama_extra_args = ["--split-mode", "layer"])assert "llama_extra_args" in req.model_fields_setassert (- inference_routes._request_matches_loaded_settings(- req, _fallback_loaded_backend(layer_preserves_tensor_intent = True)- )- is False+ _matches_request(req, _fallback_loaded_backend(layer_preserves_tensor_intent = True)) is False)@@ -714,15 +723,10 @@ def test_tensor_off_reload_requires_explicit_toggle():by the preserved-fallback reload -- the working server is kept (Codex #6659)."""from models.inference import LoadRequest- inference_routes = _load_inference_routes_module()-req = LoadRequest(model_path = "owner/repo") # tensor_parallel left unsetassert "tensor_parallel" not in req.model_fields_setassert (- inference_routes._request_matches_loaded_settings(- req, _fallback_loaded_backend(layer_preserves_tensor_intent = True)- )- is True+ _matches_request(req, _fallback_loaded_backend(layer_preserves_tensor_intent = True)) is True)@@ -731,17 +735,13 @@ def test_tensor_off_under_env_tensor_does_not_reload_loop(monkeypatch):intent, so the env-aware guard dedupes instead of reload-looping (Codex #6659)."""from models.inference import LoadRequest- inference_routes = _load_inference_routes_module()monkeypatch.setenv("LLAMA_ARG_SPLIT_MODE", "tensor")req = LoadRequest(model_path = "owner/repo", tensor_parallel = False)assert "tensor_parallel" in req.model_fields_set# env still forces tensor -> not a real drop -> dedupe (no reload loop).assert (- inference_routes._request_matches_loaded_settings(- req, _fallback_loaded_backend(layer_preserves_tensor_intent = True)- )- is True+ _matches_request(req, _fallback_loaded_backend(layer_preserves_tensor_intent = True)) is True)@@ -773,15 +773,13 @@ def test_is_explicit_tensor_drop_truth_table():def test_explicit_tensor_drop_uses_shared_helper_in_both_readers():- """Both the already-loaded dedup and the load carry-forward derive the drop from- _is_explicit_tensor_drop, so they agree on what counts as a drop -- a reload for- an unrelated extra still carries the preserved intent rather than collapsing to one- GPU (Codex #6659)."""+ """The resolved intent carries the route's tensor decision into dedupe and load."""src = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")- # Dedup reader (the preserved-fallback reload guard).- assert "layer_preserves_tensor_intent and _is_explicit_tensor_drop(request)" in src- # Load carry-forward reader feeds the same decision into the carry-forward.- assert "_explicit_tensor_drop = _is_explicit_tensor_drop(request)" in src+ assert "explicit_drop = _is_explicit_tensor_drop(request)" in src+ assert "preserve_multi_gpu_on_layer = (" in src+ matcher = inspect.getsource(LlamaCppBackend._runtime_matches_intent)+ assert "self._layer_preserves_tensor_intent" in matcher+ assert "not intent.preserve_multi_gpu_on_layer" in matcherdef test_layer_preserves_tensor_intent_set_only_on_preserved_downgrade():@@ -835,14 +833,17 @@ def test_already_in_target_state_reloads_on_tensor_off_after_fallback():is_vision = False,)# Preserved fallback + EXPLICIT tensor drop -> reload (not already in target state).- assert _backend(True)._already_in_target_state(**kwargs) is False+ assert _backend(True).adopt_load_intent_if_matched(GgufLoadIntent(**kwargs)) is False# Same preserved fallback but an implicit reload that carries the intent forward# (HF auto-pick / local-dir flows skip the route guard and reach here) -> dedupe.assert (- _backend(True)._already_in_target_state(**kwargs, preserve_multi_gpu_on_layer = True) is True+ _backend(True).adopt_load_intent_if_matched(+ GgufLoadIntent(**kwargs, preserve_multi_gpu_on_layer = True)+ )+ is True)# A genuine layer load (no preserved intent) -> dedupe, no churn.- assert _backend(False)._already_in_target_state(**kwargs) is True+ assert _backend(False).adopt_load_intent_if_matched(GgufLoadIntent(**kwargs)) is True# ── route dedup: gpu_ids device strip (#7164/#7188) ───────────────────────────@@ -871,8 +872,6 @@ def test_explicit_gpu_ids_dedupes_when_device_already_stripped():load hits the fast path instead of a needless reload / training 409 (#7188)."""from models.inference import LoadRequest- inference_routes = _load_inference_routes_module()-req = LoadRequest(model_path = "owner/repo",gpu_ids = [0],@@ -881,4 +880,4 @@ def test_explicit_gpu_ids_dedupes_when_device_already_stripped():backend = _dedup_loaded_backend(extra_args = ["--top-k", "5"])backend._gpu_ids = [0]backend._requested_gpu_ids = [0]- assert inference_routes._request_matches_loaded_settings(req, backend) is True+ assert _matches_request(req, backend) is Truediff --git a/studio/backend/utils/datasets/llm_assist.py b/studio/backend/utils/datasets/llm_assist.pyindex c594e883a84..42236b7f8a2 100644--- a/studio/backend/utils/datasets/llm_assist.py+++ b/studio/backend/utils/datasets/llm_assist.py@@ -104,19 +104,18 @@ def _run_with_helper(prompt: str, max_tokens: int = 256) -> Optional[str]:backend = Nonetry:- from core.inference.llama_cpp import LlamaCppBackend+ from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackendbackend = LlamaCppBackend()logger.info(f"Loading helper model: {repo} ({variant})")- ok = backend.load_model(+ intent = GgufLoadIntent(+ model_identifier = f"helper:{repo}:{variant}",hf_repo = repo,hf_variant = variant,- model_identifier = f"helper:{repo}:{variant}",- is_vision = False,n_ctx = 2048,- n_gpu_layers = -1,)+ ok = backend.load_model(intent)if not ok:logger.warning("Helper model failed to start")return None@@ -444,20 +443,19 @@ def _run_multi_pass_advisor(backend = Nonetry:- from core.inference.llama_cpp import LlamaCppBackend+ from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackendbackend = LlamaCppBackend()logger.info(f"Loading advisor model: {repo} ({variant})")t0 = time.monotonic()- ok = backend.load_model(+ intent = GgufLoadIntent(+ model_identifier = f"advisor:{repo}:{variant}",hf_repo = repo,hf_variant = variant,- model_identifier = f"advisor:{repo}:{variant}",- is_vision = False,n_ctx = 2048,- n_gpu_layers = -1,)+ ok = backend.load_model(intent)if not ok:logger.warning("Advisor model failed to start")return Nonediff --git a/tests/studio/test_diffusion_gpu_layers_contract.py b/tests/studio/test_diffusion_gpu_layers_contract.pyindex 38c37894312..bd922e91074 100644--- a/tests/studio/test_diffusion_gpu_layers_contract.py+++ b/tests/studio/test_diffusion_gpu_layers_contract.py@@ -135,11 +135,17 @@ def test_no_gpu_and_no_pick_masks_the_child(llama_cpp):def test_diffusion_load_passes_the_users_split_through():- body = _body("load_model")- start = body.index("_start_diffusion_server(")- call = body[start : body.index(")", body.index("gpu_ids = gpu_ids", start))]- assert "gpu_memory_mode = gpu_memory_mode" in call- assert "gpu_layers = gpu_layers" in call+ call = next(+ node+ for node in ast.walk(_function("load_model"))+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "_start_diffusion_server"+ )+ keywords = {keyword.arg: keyword.value for keyword in call.keywords}+ for name in ("gpu_memory_mode", "gpu_layers"):+ assert isinstance(keywords.get(name), ast.Name)+ assert keywords[name].id == namedef test_diffusion_no_longer_hardcodes_auto_over_the_users_choice():@@ -171,19 +177,15 @@ def _loaded_diffusion(llama_cpp, *, recorded_layers, requested_ngl):return b-def _in_target_state(b, *, mode, layers):- return b._already_in_target_state(- model_identifier = "unsloth/DiffusionGemma-GGUF",- hf_variant = None,- n_ctx = 4096,- cache_type_kv = None,- speculative_type = None,- chat_template_override = None,- extra_args = None,- is_vision = False,- gpu_memory_mode = mode,- gpu_layers = layers,- gpu_ids = [0],+def _in_target_state(llama_cpp, b, *, mode, layers):+ return b.adopt_load_intent_if_matched(+ llama_cpp.GgufLoadIntent(+ model_identifier = "unsloth/DiffusionGemma-GGUF",+ n_ctx = 4096,+ gpu_memory_mode = mode,+ gpu_layers = layers,+ gpu_ids = [0],+ ))@@ -206,20 +208,7 @@ def test_backend_dedup_compares_the_requested_split(llama_cpp, recorded, requested_ngl, mode, layers, expected):b = _loaded_diffusion(llama_cpp, recorded_layers = recorded, requested_ngl = requested_ngl)- assert _in_target_state(b, mode = mode, layers = layers) is expected---def test_route_dedup_compares_the_requested_split():- """The route mirrors the backend guard, so it must read the same field."""- route_src = ROUTE_PATH.read_text(encoding = "utf-8")- route_tree = ast.parse(route_src)- for node in ast.walk(route_tree):- if isinstance(node, ast.FunctionDef) and node.name == "_request_matches_loaded_settings":- body = ast.get_source_segment(route_src, node) or ""- assert "_diffusion_manual_ngl(request.gpu_memory_mode, request.gpu_layers)" in body- assert "llama_backend.diffusion_requested_ngl" in body- return- raise AssertionError("_request_matches_loaded_settings missing")+ assert _in_target_state(llama_cpp, b, mode = mode, layers = layers) is expecteddef test_requested_split_survives_a_shim_without_the_flag(llama_cpp):@@ -261,36 +250,6 @@ def test_probe_falls_back_to_a_substring_scan_on_unparseable_source(llama_cpp, tassert llama_cpp._shim_supports_ngl(["python", str(shim)]) is True-# ── the training guard must not refuse a load that holds no VRAM ──---def test_training_guard_sees_the_layer_count():- """A manual/0 diffusion load places no layers, so it cannot compete with training."""- route_src = ROUTE_PATH.read_text(encoding = "utf-8")- route_tree = ast.parse(route_src)- fn = next(- n- for n in ast.walk(route_tree)- if isinstance(n, ast.FunctionDef) and n.name == "_guard_chat_load_against_training"- )- names = {a.arg for a in fn.args.args} | {a.arg for a in fn.args.kwonlyargs}- assert "gpu_layers" in names- body = ast.get_source_segment(route_src, fn) or ""- assert "diffusion_ngl == 0" in body-- calls = [- n- for n in ast.walk(route_tree)- if isinstance(n, ast.Call)- and any(- isinstance(a, ast.Name) and a.id == "_guard_chat_load_against_training" for a in n.args- )- ]- assert len(calls) == 2, "expected the /load and /validate call sites"- for call in calls:- assert any(kw.arg == "gpu_layers" for kw in call.keywords)--# ── the probe must inspect the file that will be spawned, whatever its name ──@@ -388,12 +347,12 @@ def test_zoo_upgrade_reloads_a_dropped_split(llama_cpp):"""manual/20 against an old shim launched with the default and deduped on theask. Once the shim gains --ngl, the identical ask must reload to apply it."""b = _loaded_diffusion(llama_cpp, recorded_layers = -1, requested_ngl = 20)- assert _in_target_state(b, mode = "manual", layers = 20) is True # shim still old+ assert _in_target_state(llama_cpp, b, mode = "manual", layers = 20) is True # shim still oldb.diffusion_split_supported = lambda: True # zoo upgraded in this session- assert _in_target_state(b, mode = "manual", layers = 20) is False # now applies+ assert _in_target_state(llama_cpp, b, mode = "manual", layers = 20) is False # now appliesb2 = _loaded_diffusion(llama_cpp, recorded_layers = 20, requested_ngl = 20)b2.diffusion_split_supported = lambda: True- assert _in_target_state(b2, mode = "manual", layers = 20) is True # applied: rest+ assert _in_target_state(llama_cpp, b2, mode = "manual", layers = 20) is True # applied: rest# ── the dropped split must reach the client ──@@ -405,38 +364,17 @@ def test_response_models_expose_the_requested_split():encoding = "utf-8")tree = ast.parse(models_src)+ runtime = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.ClassDef) and n.name == "_InferenceRuntimeFields"+ )+ fields = {+ node.target.id+ for node in runtime.body+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name)+ }+ assert "diffusion_requested_ngl" in fieldsfor name in ("LoadResponse", "InferenceStatusResponse"):cls = next(n for n in ast.walk(tree) if isinstance(n, ast.ClassDef) and n.name == name)- fields = {- t.target.id- for t in cls.body- if isinstance(t, ast.AnnAssign) and isinstance(t.target, ast.Name)- }- assert "diffusion_requested_ngl" in fields, f"{name} must report the ask"---def test_every_diffusion_response_also_reports_the_requested_split():- """Wiring, not prose: a new response site that forgets the ask reddens here."""- route_src = ROUTE_PATH.read_text(encoding = "utf-8")- tree = ast.parse(route_src)- sites = 0- for node in ast.walk(tree):- if not isinstance(node, ast.Call):- continue- kwargs = {kw.arg for kw in node.keywords}- # Only responses describing a LOADED model; /validate has no runner yet, so no- # applied-vs-asked split.- if "is_diffusion" not in kwargs or "is_gguf" not in kwargs:- continue- if not any(- isinstance(kw.value, ast.Attribute) and kw.value.attr == "is_diffusion"- for kw in node.keywords- if kw.arg == "is_diffusion"- ):- continue- sites += 1- assert "diffusion_requested_ngl" in kwargs, (- f"response at line {node.lineno} reports is_diffusion from the backend "- "but not diffusion_requested_ngl, so a dropped split cannot survive a refresh"- )- assert sites == 3, f"expected the 2 load sites and the status site, found {sites}"+ assert any(isinstance(base, ast.Name) and base.id == runtime.name for base in cls.bases)diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.pyindex dec4a354d3f..861108cb760 100644--- a/unsloth_cli/_inference.py+++ b/unsloth_cli/_inference.py@@ -447,37 +447,35 @@ def _load_gguf_backend(llama_extra_args: Optional[List[str]] = None,):ensure_studio_backend_path()- from core.inference.llama_cpp import LlamaCppBackend+ from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackendfrom core.inference.tensor_fallback import load_with_tensor_fallbackllama_backend = LlamaCppBackend()extra_args = _validate_llama_extra_args_or_exit(llama_extra_args)- common = dict(+ intent_fields = dict(hf_variant = model_config.gguf_variant,model_identifier = model_config.identifier,is_vision = model_config.is_vision,n_ctx = max_seq_length,)+ if model_config.gguf_hf_repo:+ intent_fields.update(hf_repo = model_config.gguf_hf_repo, hf_token = hf_token)+ else:+ intent_fields.update(+ gguf_path = model_config.gguf_file,+ mmproj_path = model_config.gguf_mmproj_file,+ mtp_draft_path = model_config.gguf_mtp_file,+ )async def _attempt_gguf_load(requested_tensor_parallel: bool, attempt_extra_args: Optional[List[str]]) -> bool:- attempt_common = dict(- common,- tensor_parallel = requested_tensor_parallel,- extra_args = attempt_extra_args,- )- if model_config.gguf_hf_repo:- return llama_backend.load_model(- hf_repo = model_config.gguf_hf_repo,- hf_token = hf_token,- **attempt_common,- )return llama_backend.load_model(- gguf_path = model_config.gguf_file,- mmproj_path = model_config.gguf_mmproj_file,- mtp_draft_path = model_config.gguf_mtp_file,- **attempt_common,+ GgufLoadIntent(+ **intent_fields,+ tensor_parallel = requested_tensor_parallel,+ extra_args = attempt_extra_args,+ ))loaded = asyncio.run(diff --git a/unsloth_cli/tests/test_inference_chat.py b/unsloth_cli/tests/test_inference_chat.pyindex cbb9bb9fa9a..dbb3c7b125c 100644--- a/unsloth_cli/tests/test_inference_chat.py+++ b/unsloth_cli/tests/test_inference_chat.py@@ -663,17 +663,43 @@ def test_deferred_error_helper_defaults_a_missing_status():assert excinfo.value.code == 500-def test_load_gguf_backend_forwards_local_runtime_options(monkeypatch):+ ("source", "expected_source"),+ [+ (+ {"gguf_hf_repo": "org/model-GGUF"},+ {"hf_repo": "org/model-GGUF", "hf_token": "hf_x"},+ ),+ (+ {+ "gguf_hf_repo": None,+ "gguf_file": "/models/model.gguf",+ "gguf_mmproj_file": "/models/mmproj.gguf",+ "gguf_mtp_file": "/models/mtp.gguf",+ },+ {+ "gguf_path": "/models/model.gguf",+ "mmproj_path": "/models/mmproj.gguf",+ "mtp_draft_path": "/models/mtp.gguf",+ },+ ),+ ],+ ids = ("hugging-face", "local"),+)+def test_load_gguf_backend_forwards_source_and_runtime_options(+ monkeypatch, source, expected_source+):import unsloth_cli._inference as inferencecalls = []class _FakeLlamaCppBackend:- def load_model(self, **kwargs):- calls.append(kwargs)+ def load_model(self, intent):+ calls.append(intent)return Truefake_llama_cpp = types.ModuleType("core.inference.llama_cpp")+ fake_llama_cpp.GgufLoadIntent = lambda **kwargs: SimpleNamespace(**kwargs)fake_llama_cpp.LlamaCppBackend = _FakeLlamaCppBackendfake_args = types.ModuleType("core.inference.llama_server_args")fake_args.validate_extra_args = lambda args: list(args or [])@@ -702,7 +728,7 @@ def test_load_gguf_backend_forwards_local_runtime_options(monkeypatch):gguf_variant = "Q4_K_M",identifier = "org/model-GGUF",is_vision = False,- gguf_hf_repo = "org/model-GGUF",+ **source,)backend = inference._load_gguf_backend(@@ -714,16 +740,15 @@ def test_load_gguf_backend_forwards_local_runtime_options(monkeypatch):)assert isinstance(backend, ChatBackend)- assert calls == [+ assert [vars(intent) for intent in calls] == [{- "hf_repo": "org/model-GGUF",- "hf_token": "hf_x","hf_variant": "Q4_K_M","model_identifier": "org/model-GGUF","is_vision": False,"n_ctx": 8192,"tensor_parallel": True,"extra_args": ["--top-k", "20"],+ **expected_source,}]@@ -732,6 +757,7 @@ def test_load_gguf_backend_exits_cleanly_on_invalid_extra_args(monkeypatch):import unsloth_cli._inference as inferencefake_llama_cpp = types.ModuleType("core.inference.llama_cpp")+ fake_llama_cpp.GgufLoadIntent = objectfake_llama_cpp.LlamaCppBackend = objectfake_args = types.ModuleType("core.inference.llama_server_args")@@ -774,11 +800,12 @@ def test_load_gguf_backend_uses_tensor_fallback(monkeypatch):fallback_calls = []class _FakeLlamaCppBackend:- def load_model(self, **kwargs):- calls.append(kwargs)- return kwargs["tensor_parallel"] is False+ def load_model(self, intent):+ calls.append(intent)+ return intent.tensor_parallel is Falsefake_llama_cpp = types.ModuleType("core.inference.llama_cpp")+ fake_llama_cpp.GgufLoadIntent = lambda **kwargs: SimpleNamespace(**kwargs)fake_llama_cpp.LlamaCppBackend = _FakeLlamaCppBackendfake_args = types.ModuleType("core.inference.llama_server_args")fake_args.validate_extra_args = lambda args: list(args or [])@@ -823,8 +850,8 @@ def test_load_gguf_backend_uses_tensor_fallback(monkeypatch):assert isinstance(backend, ChatBackend)assert fallback_calls == [(True, [], "org/model-GGUF")]- assert [call["tensor_parallel"] for call in calls] == [True, False]- assert calls[1]["extra_args"] == ["--split-mode", "layer"]+ assert [intent.tensor_parallel for intent in calls] == [True, False]+ assert calls[1].extra_args == ["--split-mode", "layer"]def test_http_backend_merges_emoji_split_across_deltas(monkeypatch):