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: Fix embedded MTP performance under partial GPU offload (#8875)
oobabooga160922d9fce2
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 40a10eecd3b..10100234e80 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -2543,6 +2543,53 @@ def _child_spec_env(return os.environ if env is None else env+# The speculative types llama.cpp gives the TARGET context recurrent-state rollback+# snapshots for -- n_rs_seq = --spec-draft-n-max, per+# common_params_speculative::need_n_rs_seq. Every draft-model type but draft-simple,+# and both MTP spellings, since which one a build advertises varies.+_TARGET_ROLLBACK_SPEC_TYPES = frozenset(+ {"mtp", "draft-mtp", "draft-eagle3", "draft-dflash", "draft-dspark"}+)+++# Architectures whose TARGET context leaves the embedded MTP/NextN blocks out of+# its KV cache, so block_count must lose them before the target is priced.+#+# This is NOT every architecture that carries {arch}.nextn_predict_layers.+# llama_hparams::n_layer() subtracts nextn everywhere (llama-hparams.cpp:297),+# but llama_kv_cache walks hparams.n_layer_all (llama-kv-cache.cpp:100) and drops+# blocks only through an optional per-arch filter (:169). That filter is installed+# for the hybrids at llama-model.cpp:2289 (Qwen3-Next/Qwen3.5/MiniMax-01 and, via+# is_recr, Nemotron-H), for GLM-DSA and DeepSeek3.2 at :2129, and for the+# STEP35/HY_V3/MIMO2 group at :2356. Everywhere else -- deepseek2, glm4, glm4moe,+# bailingmoe2, cohere2moe, exaone4 -- filter is nullptr and the trailing MTP block+# DOES get target KV, so subtracting it under-reserves.+#+# Fail closed: an arch not named here keeps every block, because over-reserving+# costs context while under-reserving OOMs the load. Recurrent state is the one+# thing that always excludes nextn, llama_memory_recurrent sizing on n_layer()+# directly (llama-memory-recurrent.cpp:29), which is why+# _mamba_recurrent_state_bytes subtracts unconditionally.+_TARGET_KV_EXCLUDES_NEXTN_ARCHS = frozenset(+ {+ # Hybrid attention + recurrent, llama-model.cpp:2289+ "qwen3next",+ "qwen35",+ "qwen35moe",+ "minimax-01",+ "nemotron_h",+ "nemotron_h_moe",+ # MLA/DSA trunk with a dense MTP head, llama-model.cpp:2129+ "glm-dsa",+ "deepseek32",+ # Plain attention trunk with an explicit nextn filter, llama-model.cpp:2356+ "step35",+ "hy_v3",+ "mimo2",+ }+)++def _accumulated_spec_types(extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None) -> set:@@ -3753,6 +3800,7 @@ class LlamaCppBackend:self._kv_value_length_swa: Optional[int] = Noneself._ssm_inner_size: Optional[int] = Noneself._ssm_state_size: Optional[int] = None+ self._ssm_group_count: Optional[int] = Noneself._ssm_conv_kernel: Optional[int] = Noneself._kda_head_dim: Optional[int] = None# Last N layers reuse earlier layers' KV and don't allocate their own@@ -4578,7 +4626,10 @@ class LlamaCppBackend:if ((self._speculative_type in ("draft-mtp", "draft-dspark", "draft-dflash")- or self._spec_fallback_reason == "runtime_error"+ # Auto's Hybrid Mamba partial-offload stand-down engaged nothing, so the+ # types above cannot see it -- yet the depth is what priced the rollback+ # copies that made the placement partial, so a change can re-enable MTP.+ or self._spec_fallback_reason in ("runtime_error", "mtp_partial_offload"))and intent.spec_draft_n_max is not Noneand intent.spec_draft_n_max != (compared_draft_n_max or 0)@@ -4954,6 +5005,7 @@ class LlamaCppBackend:"ngram_mod_flavor": None,"supports_ngram_mod": False,"spec_draft_n_max_flag": None,+ "spec_draft_n_max_default": None,"supports_kv_unified": False,# Fail OPEN, unlike every key above. These three are emitted on# every launch today, so a failed probe must keep emitting them;@@ -4999,6 +5051,7 @@ class LlamaCppBackend:supports_dflash = Falsengram_mod_flavor: Optional[str] = Nonespec_draft_n_max_flag: Optional[str] = None+ spec_draft_n_max_default: Optional[int] = Nonesupports_kv_unified = False# See the fallback dict: these fail open.supports_no_context_shift = True@@ -5181,6 +5234,16 @@ class LlamaCppBackend:spec_draft_n_max_flag = "--spec-draft-n-max"elif _is_real("--draft-max"):spec_draft_n_max_flag = "--draft-max"+ # And the build's OWN default for it, off the same help line. Needed+ # where the extras own --spec-type: Studio emits no depth then, so the+ # child runs on this number and the Hybrid Mamba rollback reserve+ # scales by it. None when the line carries no default.+ if spec_draft_n_max_flag:+ _n_max_default = re.search(+ r"default:\s*(\d+)", blocks.get(spec_draft_n_max_flag) or ""+ )+ if _n_max_default:+ spec_draft_n_max_default = int(_n_max_default.group(1))supports_kv_unified = _is_real("--kv-unified")# Only once the help actually parsed AND `--help` succeeded. Empty@@ -5260,6 +5323,7 @@ class LlamaCppBackend:"ngram_mod_flavor": ngram_mod_flavor,"supports_ngram_mod": ngram_mod_flavor is not None,"spec_draft_n_max_flag": spec_draft_n_max_flag,+ "spec_draft_n_max_default": spec_draft_n_max_default,"supports_kv_unified": supports_kv_unified,"supports_no_context_shift": supports_no_context_shift,"supports_jinja": supports_jinja,@@ -5670,6 +5734,51 @@ class LlamaCppBackend:return not fit_activereturn requested > n_layers+ def _partially_offloads_layers(+ self,+ args: Optional[Iterable[str]],+ env: Optional[Mapping[str, str]] = None,+ fit_implies_partial: bool = True,+ ) -> bool:+ """Whether the effective main-model layer policy is partial GPU offload.++ A concrete layer count owns placement even when ``--fit on`` is present.+ Otherwise ``-1`` (or an omitted count) is partial only while the fitter may+ lower it. Zero is CPU-only rather than partial offload, and keeps CPU MTP,+ and so is a ``--device`` selection naming no GPU: llama.cpp then runs the+ model on the CPU whatever the layer count and the fitter say.++ ``fit_implies_partial`` is what an active fitter is allowed to mean. In Auto+ it is evidence: the planner ran and could not prove the model fits, which is+ why the fitter is on. In Manual mode the planner is skipped by design, so+ ``--fit on`` is a default rather than a verdict and says nothing about+ placement -- pass False there and let a concrete count answer instead.+ """+ n_layers = self.n_layers+ if not n_layers:+ return False+ try:+ requested = parse_gpu_layers_override(args)+ except ValueError:+ return False+ source_env = os.environ if env is None else env+ if _device_selection_is_cpu(args, source_env):+ return False+ if requested is None:+ raw = source_env.get("LLAMA_ARG_N_GPU_LAYERS")+ if raw is not None and raw.strip():+ try:+ requested = int(raw)+ except ValueError:+ requested = None+ if requested == 0:+ return False+ if requested is not None and requested > 0:+ # llama.cpp needs a count above block_count to include the output+ # layer, matching _offloads_every_layer.+ return requested <= n_layers+ return fit_implies_partial and fit_is_effectively_on(args, source_env)+@staticmethoddef _torch_is_rocm(torch) -> bool:"""Whether this torch is a ROCm build. AMD SDK wheels leave@@ -7396,9 +7505,9 @@ class LlamaCppBackend:is the whole reservation at short contexts and the bisection in_fit_context_to_vram cannot shrink it away.- Sizes follow llama_hparams::n_embd_r/n_embd_s. Kimi KDA only: Mamba- needs ssm.group_count, which is not parsed, so those models keep the- previous behaviour rather than get a wrong number.+ Sizes follow llama_hparams::n_embd_r/n_embd_s. This helper covers the+ per-layer KDA layout; Hybrid Mamba uses its architecture-level interval+ and group count in _mamba_recurrent_state_bytes."""if not self._n_kv_heads_by_layer or not self._n_layers or not self._kda_head_dim:return 0@@ -7411,6 +7520,79 @@ class LlamaCppBackend:n_embd_s = head_dim * head_dim * n_headreturn int(n_recurrent * (n_embd_r + n_embd_s) * 4 * max(1, n_parallel))+ def _target_kv_excludes_nextn(self) -> bool:+ """Whether this model's TARGET KV cache skips the embedded MTP blocks.++ See _TARGET_KV_EXCLUDES_NEXTN_ARCHS for why this is per-architecture+ rather than a property of the nextn key.++ A hybrid recurrent header answers yes without consulting that list. Every+ hybrid Mamba architecture llama.cpp accepts a nextn key from -- Qwen3-Next,+ Qwen3.5, Qwen3.5-MoE, Nemotron-H -- is filtered at llama-model.cpp:2289,+ and the recurrent half is sized on n_layer() regardless+ (llama-memory-recurrent.cpp:29), so the ssm dims are sufficient evidence+ and a GGUF whose header names an arch this build has never heard of still+ gets the right answer. Everything else must be named, so an unreadable or+ unknown architecture keeps every block.+ """+ if not self._nextn_predict_layers:+ return False+ if self._ssm_inner_size is not None and self._full_attention_interval is not None:+ return True+ arch = getattr(self, "_architecture", None)+ return bool(arch) and str(arch).strip().lower() in _TARGET_KV_EXCLUDES_NEXTN_ARCHS++ def _mamba_recurrent_state_bytes(+ self,+ n_parallel: int = 1,+ n_rs_seq: int = 0,+ ) -> int:+ """VRAM for Hybrid Mamba conv/SSM state, including rollback copies.++ llama.cpp allocates one f32 recurrent state per parallel sequence. MTP+ additionally keeps ``--spec-draft-n-max`` rollback states per sequence+ while verifying draft tokens, so its allocation is ``1 + n_rs_seq``+ times the base state.+ """+ n_layers_raw = getattr(self, "_n_layers", None)+ d_inner_raw = getattr(self, "_ssm_inner_size", None)+ d_state_raw = getattr(self, "_ssm_state_size", None)+ n_group_raw = getattr(self, "_ssm_group_count", None)+ d_conv_raw = getattr(self, "_ssm_conv_kernel", None)+ fai_raw = getattr(self, "_full_attention_interval", None)+ if not all(+ value is not None+ for value in (+ n_layers_raw,+ d_inner_raw,+ d_state_raw,+ n_group_raw,+ d_conv_raw,+ fai_raw,+ )+ ):+ return 0+ # Excludes the embedded MTP blocks, as _estimate_kv_cache_bytes does and+ # for the same reason: llama.cpp keeps them out of the target's n_layer.+ n_layers = max(+ 0,+ int(n_layers_raw or 0) - int(getattr(self, "_nextn_predict_layers", None) or 0),+ )+ fai = int(fai_raw or 0)+ n_attn = -(-n_layers // fai) if fai > 0 else n_layers+ n_recurrent = max(0, n_layers - n_attn)+ if n_recurrent == 0:+ return 0+ d_inner = int(d_inner_raw or 0)+ d_state = int(d_state_raw or 0)+ n_group = int(n_group_raw or 0)+ d_conv = int(d_conv_raw or 0)+ n_embd_r = max(0, d_conv - 1) * (d_inner + 2 * n_group * d_state)+ n_embd_s = d_state * d_inner+ return int(+ n_recurrent * (n_embd_r + n_embd_s) * 4 * max(1, n_parallel) * max(1, 1 + n_rs_seq)+ )+def _legacy_head_dim(self) -> int:"""Head-dim fallback for GGUFs without explicit key/value dims. Reachedonly via the legacy branch of _can_estimate_kv(), so _embedding_length@@ -7477,7 +7659,15 @@ class LlamaCppBackend:if not self._can_estimate_kv() or n_ctx <= 0:return 0+ # GGUF block_count includes embedded MTP blocks, and llama.cpp keeps+ # those out of the target context for SOME architectures only -- see+ # _TARGET_KV_EXCLUDES_NEXTN_ARCHS. Where it does, their KV lives in the+ # draft context and _mtp_draft_kv_bytes prices it separately; where it+ # does not, the target cache still allocates them and subtracting here+ # would under-reserve.n_layers = self._n_layers # type: ignore[assignment]+ if self._target_kv_excludes_nextn():+ n_layers = max(1, n_layers - (self._nextn_predict_layers or 0))# Gemma 3n / Gemma 4 reuse earlier KV in the last ``shared_kv_layers``# blocks (no cache). Floor at 1 so a bad GGUF can't zero out KV.shared = self._shared_kv_layers or 0@@ -7530,11 +7720,15 @@ class LlamaCppBackend:if self._ssm_inner_size is not None and self._full_attention_interval is not None:fai = self._full_attention_intervaln_attn = -(-n_layers // fai) if fai > 0 else n_layers # ceiling division+ recurrent = self._mamba_recurrent_state_bytes(n_parallel)if key_len is not None and val_len is not None:v_width = n_kv * val_len if flash_attn else self._max_kv_value_width(val_len)- return int(n_attn * total_cells * (n_kv * key_len * bpe_k + v_width * bpe_v))+ return (+ int(n_attn * total_cells * (n_kv * key_len * bpe_k + v_width * bpe_v))+ + recurrent+ )head_dim = self._legacy_head_dim()- return int(n_attn * total_cells * n_kv * 2 * head_dim * bpe_k)+ return int(n_attn * total_cells * n_kv * 2 * head_dim * bpe_k) + recurrent# Path 3: Sliding window (Gemma 2/3/3n/4, gpt-oss, Cohere2 ...). Pattern# from the resolver; if absent, falls through to the legacy 1/4-global@@ -7636,6 +7830,9 @@ class LlamaCppBackend:"_sliding_window","_sliding_window_pattern","_ssm_inner_size",+ "_ssm_state_size",+ "_ssm_group_count",+ "_ssm_conv_kernel","_full_attention_interval","_key_length_mla","_n_kv_heads_by_layer",@@ -7728,19 +7925,24 @@ class LlamaCppBackend:draft_weights_bytes: int = 0,n_parallel: int = 1,mtp_keeps_target_ctx: bool = True,+ target_rollback: bool = True,swa_full: bool = False,kv_unified: bool = True,n_ubatch: Optional[int] = None,flash_attn: bool = True,) -> Optional[int]:"""MTP draft reserve at ``n_ctx`` = draft KV (grows with ctx) + separate-- drafter weights + (MTP + MLA only) a duplicated target KV context. The- verify buffer rides in the ctx-fit headroom (no tuned constant). None when+ drafter weights + target verification state. MLA duplicates the target+ KV context, while Hybrid Mamba adds recurrent rollback copies. The other+ verify buffers ride in the ctx-fit headroom (no tuned constant). None whenthe draft KV can't be sized (caller keeps the flat fallback).``draft_weights_bytes`` is the drafter file size (0 for embedded).``mtp_keeps_target_ctx`` is True for MTP draft modes (which keep theduplicated target context) and False for separate-drafter spec modes- (draft-simple/draft-eagle3), which do not."""+ (draft-simple/draft-eagle3), which do not. ``target_rollback`` is the+ wider set: every draft-model type llama.cpp gives the target n_rs_seq for+ (draft-mtp/eagle3/dflash/dspark), which is all of them but draft-simple.+ Both default to charging, so an unsure caller over-reserves."""draft_kv = self._mtp_draft_kv_bytes(n_ctx,drafter_path = drafter_path,@@ -7775,14 +7977,24 @@ class LlamaCppBackend:n_ubatch = n_ubatch,flash_attn = flash_attn,)+ # Hybrid Mamba targets keep one recurrent state in the normal target+ # context, counted by _estimate_kv_cache_bytes. Verification adds one+ # rollback copy per drafted token, in the TARGET context, so a separate+ # drafter file pays it exactly like the embedded head: ``target_rollback``+ # decides, not ``drafter_path`` (see _TARGET_ROLLBACK_SPEC_TYPES). The+ # dominant hidden cost on Qwen3.5/3.8 at multiple parallel slots.+ target_recurrent_copies = 0+ if target_rollback and spec_draft_n_max > 0:+ base_recurrent = self._mamba_recurrent_state_bytes(n_parallel)+ target_recurrent_copies = base_recurrent * spec_draft_n_maxif draft_kv is None:# KV unsized (exotic/remote drafter): still reserve known weights + any# MLA target copy so a large config can't launch over budget (the small# unsized draft KV rides in the cushion). Nothing known -> None, so the# caller keeps the flat fallback.- total = weights + target_ctx_copy+ total = weights + target_ctx_copy + target_recurrent_copiesreturn total if total > 0 else None- return draft_kv + weights + target_ctx_copy+ return draft_kv + weights + target_ctx_copy + target_recurrent_copies_DEFAULT_N_UBATCH = _DEFAULT_LLAMA_N_UBATCH_COMPUTE_BUFFER_SAFETY = 1.15 # upper-bound margin on the compute-buffer estimate@@ -7790,6 +8002,13 @@ class LlamaCppBackend:_CUDA_CONTEXT_RESERVE_BYTES = 320 * 1024 * 1024 # CUDA ctx + cuBLAS workspace (~330 MiB)_MMPROJ_VRAM_SAFETY = 1.4 # mmproj worst-case buffer vs file size (runtime ~1.3x)_MTP_DRAFT_COMPUTE_BYTES = 224 * 1024 * 1024 # MTP draft decode graph beyond its KV+ # Draft depth to budget when the extras own the spec block and the probe cannot+ # read the build's own default off its --help. Shipped values are 3+ # (common_params_speculative_draft::n_max) and 16; take the deeper, since the+ # Hybrid Mamba rollback copies scale by this and under-reserving them OOMs the+ # load while over-reserving only costs context. Zero cost on any other model,+ # where the recurrent state is nil.+ _UNKNOWN_SPEC_DRAFT_N_MAX = 16# The flash-attn KQ mask + attention scratch grow ~linearly with context; the flat# _estimate_compute_buffer_bytes term only covers ctx -> 0. The per-token rate# depends on the KV cache type: a QUANTIZED cache (q8_0/q5/q4/iq4) needs a@@ -8589,6 +8808,7 @@ class LlamaCppBackend:self._kv_value_length_swa = Noneself._ssm_inner_size = Noneself._ssm_state_size = None+ self._ssm_group_count = Noneself._ssm_conv_kernel = Noneself._kda_head_dim = Noneself._shared_kv_layers = None@@ -8701,6 +8921,7 @@ class LlamaCppBackend:f"{arch}.attention.shared_kv_layers": "shared_kv_layers",f"{arch}.ssm.inner_size": "ssm_inner_size",f"{arch}.ssm.state_size": "ssm_state_size",+ f"{arch}.ssm.group_count": "ssm_group_count",f"{arch}.ssm.conv_kernel": "ssm_conv_kernel",f"{arch}.kda.head_dim": "kda_head_dim",f"{arch}.nextn_predict_layers": "nextn_predict_layers",@@ -13496,6 +13717,13 @@ class LlamaCppBackend:# the same reason as _detected_gpus: the except path (--fit on) falls# through to the launch, which reads it._arch_gate_forced_cpu = False+ # Whether Studio's placement planner actually RAN and came back+ # unable to fit the model. `use_fit` alone cannot answer that: it+ # starts True at its declaration below and is also what the except+ # path restores, so an unfitted `--fit on` is indistinguishable+ # from the default unless the verdict is recorded on its own.+ # Bound before the try for the same reason as _detected_gpus.+ _placement_verdict_partial = Falsetotal_by_idx: dict[int, int] = {}model_size = None # set in the fit try; used by the APU RAM guard# Layer-fallback min GPUs; raised below on a tensor downgrade. Bound@@ -13787,11 +14015,67 @@ class LlamaCppBackend:_user_mtp_via_extrasor (_auto_studio_mtp and _mtp_effective not in ("dspark", "dflash")))+ # The recurrent rollback copies are a WIDER set than that copy+ # (_TARGET_ROLLBACK_SPEC_TYPES): DSpark and DFlash pay them too,+ # and draft-simple is the one engaged draft mode that does not,+ # which is why the pass-through arm reads the types rather than+ # assuming every extras-owned drafter qualifies.+ _target_rollback = bool(+ _auto_studio_mtp+ or _user_mtp_via_extras+ or (+ _user_draft_via_extras+ and _accumulated_spec_types(extra_args, env = _spec_env)+ & _TARGET_ROLLBACK_SPEC_TYPES+ )+ )- # Effective draft depth: extras win (last-wins at launch), else- # the field, else the platform default (2 GPU / 3 CPU).+ # Effective draft depth, by what the CHILD will run on rather than+ # what was asked for: an extras depth wins (last-wins at launch),+ # else the field, else the platform default (2 GPU / 3 CPU)._extra_n_max = _extra_args_spec_draft_n_max(extra_args)- _mtp_eff_n_max = _extra_n_max if _extra_n_max is not None else spec_draft_n_max+ _mtp_eff_n_max = _extra_n_max+ if _mtp_eff_n_max is None and _extra_args_set_spec_type(extra_args):+ # The extras own the spec block, so _build_speculative_flags+ # returns without emitting a depth at all: neither the request+ # field nor the platform default below reaches the child. What+ # does: the inherited env, which survives exactly this case,+ # then the build's own default. The rollback reserve scales by+ # this number, so carrying a request field of 2 into a build+ # that drafts 16 under-reserves by a factor of eight.+ try:+ _depth_caps = _launch_caps(binary) or {}+ except Exception:+ _depth_caps = {}+ # The env twin of whichever depth flag this build carries, and+ # only that one: a legacy build spells the pair --draft-max /+ # LLAMA_ARG_DRAFT_MAX, and a post-rename build ignores the+ # legacy name, so a stale value there must not price its+ # rollback. Both names only where the probe named no flag.+ _depth_flag = _depth_caps.get("spec_draft_n_max_flag")+ if _depth_flag == "--draft-max":+ _env_names = ("LLAMA_ARG_DRAFT_MAX",)+ elif _depth_flag:+ _env_names = ("LLAMA_ARG_SPEC_DRAFT_N_MAX",)+ else:+ _env_names = ("LLAMA_ARG_SPEC_DRAFT_N_MAX", "LLAMA_ARG_DRAFT_MAX")+ _env_n_max = next(+ (v for v in map(_spec_env.get, _env_names) if _is_positive_int(v)),+ None,+ )+ if _env_n_max is not None:+ _mtp_eff_n_max = int(str(_env_n_max).strip())+ else:+ # Never fall through to Studio's platform default here:+ # the child is drafting at the build's number, and a+ # probe that timed out or printed no default still leaves+ # it drafting. Assume the deepest llama.cpp has shipped.+ _mtp_eff_n_max = (+ _depth_caps.get("spec_draft_n_max_default")+ or self._UNKNOWN_SPEC_DRAFT_N_MAX+ )+ elif _mtp_eff_n_max is None:+ _mtp_eff_n_max = spec_draft_n_maxif _mtp_eff_n_max is None:# _detected_gpus (not gpus) so manual -- which empty# gpus to bypass the planner -- keep the GPU draft depth the@@ -13872,6 +14156,7 @@ class LlamaCppBackend:draft_weights_bytes = _mtp_draft_weights,n_parallel = n_parallel,mtp_keeps_target_ctx = _engaged_is_mtp,+ target_rollback = _target_rollback,swa_full = swa_full,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,@@ -13892,6 +14177,7 @@ class LlamaCppBackend:_w: int = _mtp_draft_weights,_np: int = n_parallel,_mtp: bool = _engaged_is_mtp,+ _rollback: bool = _target_rollback,_swa_full: bool = swa_full,_kv_unified: bool = planned_kv_unified,_n_ubatch: Optional[int] = _effective_ubatch,@@ -13906,6 +14192,7 @@ class LlamaCppBackend:draft_weights_bytes = _w,n_parallel = _np,mtp_keeps_target_ctx = _mtp,+ target_rollback = _rollback,swa_full = _swa_full,kv_unified = _kv_unified,n_ubatch = _n_ubatch,@@ -14341,7 +14628,29 @@ class LlamaCppBackend:# displaced does not run. The flat fraction below is gated on# this; the byte-accurate callback was not, so the fit went on# charging VRAM no drafter allocates.- mtp_overhead_fn = None+ # One term survives: a Hybrid Mamba target keeps its own+ # recurrent rollback snapshots for verification, and those sit+ # in the TARGET context, so pinning the drafter to the CPU does+ # not move them. Charge those alone rather than nothing. Flat in+ # ctx, the state being per-slot rather than per-token -- hence+ # the same _np/_n_ubatch keywords the replaced callback takes,+ # so _mtp_bytes can still re-price each slot candidate.+ def _cpu_draft_target_state(+ _ctx: int,+ _np: int = n_parallel,+ _n_ubatch: Optional[int] = _effective_ubatch,+ _n: int = _mtp_eff_n_max,+ _rollback: bool = _target_rollback,+ ) -> int:+ if not _rollback or _n <= 0:+ return 0+ return self._mamba_recurrent_state_bytes(_np) * _n++ mtp_overhead_fn = (+ _cpu_draft_target_state+ if _cpu_draft_target_state(effective_ctx) > 0+ else None+ )_mtp_kv_unsized = False# Flat MTP reserve fraction: used only as the fallback when the@@ -14356,6 +14665,14 @@ class LlamaCppBackend:# CPU-offloaded one (an embedded head stays on GPU). The tensor# path reserves like the layer path; gate both on this._mtp_reserves_gpu = _mtp_will_engage and not _draft_cpu_no_embedded+ # Narrower than that: whether ANY byte reserve survives on the GPU.+ # A CPU-pinned drafter leaves the target's own rollback state behind+ # (the block above keeps it), and the tensor floor has to hold it,+ # tensor mode having no --fit valve and no amount of context+ # shrinking freeing a per-slot allocation. It stays out of+ # _mtp_reserves_gpu because that also charges the draft decode+ # graph, which follows the drafter onto the CPU.+ _mtp_gpu_bytes_remain = _mtp_reserves_gpu or mtp_overhead_fn is not None_flat_mtp_reserve = (_MTP_VRAM_RESERVE_FRACif (_flat_mtp_engages and not _draft_cpu_no_embedded)@@ -14388,8 +14705,9 @@ class LlamaCppBackend:sum(_gpu_usable(g) for g in tp_gpus) - len(tp_gpus) * reserve_mib)_tp_flat_mtp = 2 * 1024**3 # flat reserve when dims unavailable- if not _mtp_reserves_gpu:- # No MTP, or its only drafter is CPU-offloaded (no GPU).+ if not _mtp_gpu_bytes_remain:+ # No MTP, or its only drafter is CPU-offloaded and the+ # target keeps no state of its own (no GPU bytes at all)._tp_mtp_floor = 0elif mtp_overhead_fn is not None and not _mtp_kv_unsized:_tp_mtp_floor = _mtp_bytes(@@ -14818,9 +15136,17 @@ class LlamaCppBackend:# --fit flag state, not "does it fit": off means this subset provably fits.f"GPUs free: {gpus}, selected: {gpu_indices}, --fit: {'on' if use_fit else 'off'}")+ # The planner ran to completion over a real device list and+ # left --fit on, i.e. it could not prove the model fits. THAT+ # is a partial-placement verdict. Set last, so any early+ # return or raise above leaves it False.+ _placement_verdict_partial = bool(_detected_gpus) and bool(use_fit)except Exception as e:logger.warning(f"GPU selection failed ({e}), using --fit on")gpu_indices, use_fit = None, True+ # Not a verdict: this arm never priced anything. Explicit, so+ # the flag cannot survive from a previous load.+ _placement_verdict_partial = Falsetp_tensor_split = Noneeffective_ctx = requested_ctx # fall back to original@@ -15305,6 +15631,27 @@ class LlamaCppBackend:strip_template = False,strip_split_mode = False,)+ # The same view of argv and env the child will get, built with the+ # helpers the launch itself uses so the two cannot drift: manual mode+ # drops the placement vars, and a gpu_ids pin drops the device flags+ # from both. Classifying on the raw extras would read a stale+ # --device none as CPU-only for a load that does offload.+ _spec_placement_env = dict(os.environ)+ if gpu_memory_mode == "manual":+ self._clear_manual_placement_env(_spec_placement_env)+ _spec_placement_extras = extra_args+ if gpu_ids is not None:+ _spec_placement_extras = self._strip_device_extra_args(extra_args)+ self._clear_device_placement_env(_spec_placement_env)+ # A device the launch really carries, and not the CPU spelling of it.+ # Only consulted where the probe found nothing: it is the one remaining+ # way the child can still be pointed at a GPU.+ _spec_device_pick = _extra_args_main_device(+ [*cmd, *(_spec_placement_extras or [])]+ ) or _spec_placement_env.get("LLAMA_ARG_DEVICE")+ _spec_extras_pick_a_gpu = bool(_spec_device_pick) and not _device_selection_is_cpu(+ [*cmd, *(_spec_placement_extras or [])], _spec_placement_env+ )spec_flags = self._build_speculative_flags(speculative_type = speculative_type,spec_draft_n_max = spec_draft_n_max,@@ -15321,6 +15668,46 @@ class LlamaCppBackend:dflash_draft_path = (launch_mtp_draft_path if _spec_canon == "dflash" else None),dflash_fit_sized = not use_fit,drafter_no_vram = _spec_dropped_no_vram,+ embedded_mtp_partial_offload = bool(+ _spec_canon == "auto"+ and self._nextn_predict_layers+ and self._ssm_inner_size is not None+ and self._full_attention_interval is not None+ and not launch_mtp_draft_path+ and not _extra_args_set_spec_type(extra_args)+ # No GPU, nothing to partially offload TO. `--fit on` is also+ # what a CPU-only box and a Metal Mac emit (use_fit starts True+ # and only the planner lowers it), and there the rollback copies+ # cost no VRAM at all -- same reason the helper treats -ngl 0 as+ # CPU-only rather than partial. Those keep the CPU MTP policy.+ # gpu_indices counts too: an explicit pick the VRAM probe could+ # not enumerate still pins the child to those devices, so the+ # launch offloads to them whatever the probe returned. So does+ # a device named in the extras, which is the same flag+ # _device_selection_is_cpu reads for the CPU answer: a failed+ # probe is not evidence of no GPU when the child is pointed at+ # one by hand.+ and (_detected_gpus or gpu_indices or _spec_extras_pick_a_gpu)+ and self._partially_offloads_layers(+ [*cmd, *(_spec_placement_extras or [])],+ _spec_placement_env,+ # Manual mode skips Studio's placement planner (gpus is+ # emptied above), so its --fit on is the default this+ # function starts at, not a finding that the model does+ # not fit. Only Auto's fitter carries that evidence --+ # and only when it actually ran and actually failed to+ # fit, which is what _placement_verdict_partial records.+ # Auto alone is not enough: an empty VRAM probe with a+ # hand-pinned device (Metal0, Vulkan0) satisfies the GPU+ # guard above while every planner branch stayed gated on+ # the empty `gpus`, and the except path restores --fit on+ # having priced nothing. A concrete --gpu-layers count is+ # unaffected; it is independent evidence inside the helper.+ fit_implies_partial = (+ gpu_memory_mode != "manual" and _placement_verdict_partial+ ),+ )+ ),draft_device = _draft_device,)# _build_speculative_flags judged the stripped list, so a user@@ -15767,8 +16154,7 @@ class LlamaCppBackend:# above cannot reach.if _flash_attn_known_off and self._drop_env_quantized_v_cache(env):logger.info(- "Dropped inherited quantized V-cache env: this build has "- "no --flash-attn."+ "Dropped inherited quantized V-cache env: this build has no --flash-attn.")# Reconcile the inherited LLAMA_ARG_* env with Unsloth's final@@ -17122,6 +17508,7 @@ class LlamaCppBackend:dflash_draft_path: Optional[str] = None,dflash_fit_sized: bool = True,drafter_no_vram: bool = False,+ embedded_mtp_partial_offload: bool = False,draft_device: Optional[str] = None,) -> List[str]:"""Return the llama-server flag list for the requested spec mode.@@ -17495,6 +17882,35 @@ class LlamaCppBackend:_emit_mtp(chain_ngram = chain_ngram)return flags+ # Embedded Hybrid Mamba MTP shares the target model's device placement.+ # Under an automatic fit, its rollback states push more target layers to CPU;+ # at a fixed partial layer count, the draft and rollback work still regresses+ # decode. Auto therefore preserves ordinary llama-server performance by+ # disabling speculation. Forced MTP remains available as the explicit override.+ # Only where MTP is the thing being stood down. On a build whose --spec-type+ # has no MTP spelling the emit path below already loads without speculation+ # and names the real cause (binary_no_mtp, with the update affordance), so+ # claiming a placement policy would send the user to force a mode this build+ # cannot run, and "none" is not a value every such build's enum carries.+ if embedded_mtp_partial_offload and caps.get("mtp_token"):+ logger.info(+ "Auto: embedded MTP is disabled because the Hybrid Mamba target "+ "requires partial CPU offload; ordinary decoding is faster at this "+ "placement. Choose MTP explicitly to force it."+ )+ flags.extend(["--spec-type", "none"])+ self._speculative_type = "none"+ self._spec_fallback_reason = "mtp_partial_offload"+ # Record the depth this decision was made at (user override only, as+ # everywhere else). The rollback copies priced into the fit are+ # base_recurrent * spec_draft_n_max, so a changed depth can move the+ # placement and must reload -- and without a recorded value the+ # comparison in _runtime_matches_intent would see 0 forever and reload+ # on every Apply instead of once.+ if spec_draft_n_max is not None:+ self._spec_draft_n_max = int(spec_draft_n_max)+ return flags+# effective_mode == "auto": the promotion path. No vision gate on any drafter# kind. MTP's mmproj compatibility is llama.cpp #22673; DFlash is a different# --spec-type and #22105 says nothing, so it was measured: Muse-Glimmer-30B@@ -17889,6 +18305,7 @@ class LlamaCppBackend:self._kv_value_length_swa = Noneself._ssm_inner_size = Noneself._ssm_state_size = None+ self._ssm_group_count = Noneself._ssm_conv_kernel = Noneself._kda_head_dim = Noneself._shared_kv_layers = Nonediff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 32d08f88f53..60a28b7ab53 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -1056,6 +1056,11 @@ class InferenceStatusResponse(_InferenceRuntimeFields):"whose llama.cpp MTP path runs slower than no speculation, so Auto ""used ngram-mod or spec-off instead -- updating won't help; choose ""MTP in Settings (or set UNSLOTH_MLA_MTP_ENABLED=1) to force it. "+ "'mtp_partial_offload' -> an Auto-mode policy downgrade: the model "+ "has an embedded Hybrid Mamba MTP head and the placement offloads "+ "only part of it, where the recurrent rollback copies cost more "+ "layers than the drafting wins back -- updating won't help; choose "+ "MTP in Settings to force it. ""None when the requested strategy engaged or was not requested."),)diff --git a/studio/backend/tests/test_kv_cache_estimation.py b/studio/backend/tests/test_kv_cache_estimation.pyindex 84a979ee416..4a2409d742b 100644--- a/studio/backend/tests/test_kv_cache_estimation.py+++ b/studio/backend/tests/test_kv_cache_estimation.py@@ -31,8 +31,13 @@ _loggers_stub = _types.ModuleType("loggers")_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)sys.modules.setdefault("loggers", _loggers_stub)-# structlog+# structlog. Carries get_logger because this stub is process-wide: whichever test+# module is imported first wins the setdefault, and utils/prebuilt/freshness_flow+# calls structlog.get_logger at import time. A bare module here fails that import+# for every later module on a runner without the real package, which is how this+# file's stub was breaking test_llama_cpp_mtp_detection in the same pytest run._structlog_stub = _types.ModuleType("structlog")+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")sys.modules.setdefault("structlog", _structlog_stub)# httpx -- only stub when the real library is missing. Unconditional stubbing@@ -199,6 +204,8 @@ class TestGGUFParserNewFields:("_key_length_mla", "attention.key_length_mla", 256),("_ssm_inner_size", "ssm.inner_size", 6144),("_ssm_state_size", "ssm.state_size", 128),+ ("_ssm_group_count", "ssm.group_count", 16),+ ("_ssm_conv_kernel", "ssm.conv_kernel", 4),],)def test_field_parsed(self, field, gguf_key, value):@@ -219,6 +226,8 @@ class TestGGUFParserNewFields:"_kv_value_length_swa","_ssm_inner_size","_ssm_state_size",+ "_ssm_group_count",+ "_ssm_conv_kernel",]:assert getattr(b, attr) is None@@ -410,6 +419,8 @@ class TestArchSwaPatternDefaults:"attention.value_length_swa": 64,"ssm.inner_size": 4096,"ssm.state_size": 128,+ "ssm.group_count": 16,+ "ssm.conv_kernel": 4,}b = _backend_from_gguf("testarch", fields)assert b._context_length == 131072@@ -428,6 +439,8 @@ class TestArchSwaPatternDefaults:assert b._kv_value_length_swa == 64assert b._ssm_inner_size == 4096assert b._ssm_state_size == 128+ assert b._ssm_group_count == 16+ assert b._ssm_conv_kernel == 4_SWA_FIELDS = {@@ -955,6 +968,22 @@ class TestHybridMambaEstimation:expected = 64 * 4096 * 4 * (256 + 256) * 2assert result == expected+ def test_qwen_recurrent_state_and_mtp_rollback_copies(self):+ b = self._hybrid_backend(+ _n_layers = 65,+ _nextn_predict_layers = 1,+ _ssm_group_count = 16,+ _ssm_conv_kernel = 4,+ )+ per_slot = 48 * ((4 - 1) * (6144 + 2 * 16 * 128) + 128 * 6144) * 4+ assert b._mamba_recurrent_state_bytes() == per_slot+ assert per_slot / (1024 * 1024) == pytest.approx(149.625)+ assert b._mamba_recurrent_state_bytes(n_parallel = 4) == 4 * per_slot+ assert b._mamba_recurrent_state_bytes(n_parallel = 4, n_rs_seq = 2) == 12 * per_slot++ kv_only = 16 * _runtime_kv_cells(4096, slots = 4) * 4 * (256 + 256) * 2+ assert b._estimate_kv_cache_bytes(4096, "f16", n_parallel = 4) == (kv_only + 4 * per_slot)+# E. Path 3: Sliding Window Estimationdiff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.pyindex 4db0e62f73f..70327a681e2 100644--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py@@ -1116,6 +1116,10 @@ def test_probe_detects_post_rename_ngram_mod_flavor(tmp_path):assert caps["ngram_mod_flavor"] == "new"assert caps["supports_ngram_mod"] is Trueassert caps["spec_draft_n_max_flag"] == "--spec-draft-n-max"+ # The build's own depth, off the same line: a pass-through --spec-type makes+ # the child run on this rather than on anything Studio emits, and the Hybrid+ # Mamba rollback reserve scales by it.+ assert caps["spec_draft_n_max_default"] == 16@_NEEDS_BASH@@ -1316,6 +1320,25 @@ def test_mtp_draft_n_max_ignored_when_binary_lacks_mtp():assert _draft_n_max_matches(backend, 8, speculative_type = "mtp")+ ("decided_at", "requested", "expected_match"),+ [(2, 1, False), (2, 2, True), (None, 1, False), (1, 1, True)],+)+def test_partial_offload_stand_down_follows_the_draft_depth(decided_at, requested, expected_match):+ # Auto's Hybrid Mamba stand-down engages nothing, so _speculative_type is+ # "none" and the draft-mode arms cannot see it -- but the depth is what priced+ # the rollback copies that made the placement partial, so a change must rerun+ # the fit. The recorded value is what keeps that at one reload: an unrecorded+ # depth compares against 0 forever and reloads on every Apply.+ backend = _mtp_backend(+ _requested_spec_mode = "auto",+ _speculative_type = "none",+ _spec_draft_n_max = decided_at,+ _spec_fallback_reason = "mtp_partial_offload",+ )+ assert _draft_n_max_matches(backend, requested) is expected_match++def test_already_in_target_state_draft_n_max_ignored_when_not_mtp():# ngram-mod backend; spec_draft_n_max is MTP-only and must not force# a reload against a non-MTP active spec.diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.pyindex 2248651ba81..a993819d48e 100644--- a/studio/backend/tests/test_llama_cpp_placement.py+++ b/studio/backend/tests/test_llama_cpp_placement.py@@ -214,7 +214,7 @@ def test_dspark_composed_argv_respects_placement_fit_decision(tmp_path, use_fit))sidecar = tmp_path / "dspark-model-Q8_0.gguf"sidecar.write_bytes(b"draft")- backend._select_gpus = lambda *args, **kwargs: ((None, True) if use_fit else ([0], False))+ backend._select_gpus = lambda *args, **kwargs: (None, True) if use_fit else ([0], False)backend.probe_server_capabilities = lambda _binary = None: {"supports_dspark": True,"spec_draft_n_max_flag": "--spec-draft-n-max",@@ -361,6 +361,658 @@ def test_diffusion_does_not_reinterpret_vulkan_ordinals(tmp_path):# ── Auto drops a drafter the VRAM cannot hold ─────────────────────────+def _hybrid_mtp_backend(+ tmp_path: Path,+ *,+ partial_offload: bool,+ memory = None,+):+ backend, gguf = _backend(+ tmp_path,+ vulkan = False,+ memory = [(0, 12 * 1024, 12 * 1024)] if memory is None else memory,+ )++ def read_metadata(_path):+ backend._nextn_predict_layers = 1+ backend._n_layers = 65+ backend._n_kv_heads = 4+ backend._n_heads = 24+ backend._embedding_length = 5120+ backend._kv_key_length = 256+ backend._kv_value_length = 256+ backend._full_attention_interval = 4+ backend._ssm_inner_size = 6144+ backend._ssm_state_size = 128+ backend._ssm_group_count = 16+ backend._ssm_conv_kernel = 4++ backend._read_gguf_metadata = read_metadata+ placement = (None, True) if partial_offload else ([0], False)+ backend._select_gpus = lambda *args, **kwargs: placement+ backend._select_gpus_split_aware = lambda *args, **kwargs: placement+ backend.probe_server_capabilities = lambda _binary = None: {+ "mtp_token": "draft-mtp",+ "supports_ngram_mod": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ }+ return backend, gguf+++def test_auto_disables_embedded_hybrid_mtp_under_partial_offload(tmp_path):+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--fit") + 1] == "on"+ assert "draft-mtp" not in cmd+ assert "ngram-mod" not in cmd+ assert cmd[cmd.index("--spec-type") + 1] == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"+++def test_forced_embedded_hybrid_mtp_survives_partial_offload(tmp_path):+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "mtp",+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--fit") + 1] == "on"+ assert cmd[cmd.index("--spec-type") + 1] == "draft-mtp"+ assert backend.spec_fallback_reason is None+++def test_auto_keeps_embedded_hybrid_mtp_when_fully_offloaded(tmp_path):+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--fit") + 1] == "off"+ assert cmd[cmd.index("--spec-type") + 1] == "draft-mtp"+ assert backend.spec_fallback_reason is None+++def test_auto_disables_embedded_hybrid_mtp_with_manual_partial_layers(tmp_path):+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ gpu_memory_mode = "manual",+ gpu_layers = 42,+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--gpu-layers") + 1] == "42"+ assert cmd[cmd.index("--fit") + 1] == "off"+ assert cmd[cmd.index("--spec-type") + 1] == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"++[email protected]("gpu_layers", [0, 66])+def test_auto_keeps_embedded_hybrid_mtp_without_manual_partial_layers(tmp_path, gpu_layers):+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ gpu_memory_mode = "manual",+ gpu_layers = gpu_layers,+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--gpu-layers") + 1] == str(gpu_layers)+ assert cmd[cmd.index("--spec-type") + 1] == "draft-mtp"+ assert backend.spec_fallback_reason is None+++def test_auto_keeps_embedded_hybrid_mtp_without_a_gpu(tmp_path):+ # No GPU is probed, so nothing selects a placement and `--fit on` stays --+ # the same command a CPU-only box and a Metal Mac emit. There is nothing to+ # partially offload to there, and the rollback copies cost no VRAM, so the+ # CPU MTP policy stands.+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True, memory = [])++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--fit") + 1] == "on"+ assert "draft-mtp" in cmd[cmd.index("--spec-type") + 1]+ assert backend.spec_fallback_reason is None+++def test_auto_keeps_embedded_hybrid_mtp_when_the_device_selection_is_cpu(tmp_path):+ # A GPU is probed, but the extras take the model off it. llama.cpp then runs+ # on the CPU whatever the fitter decides, so nothing is partially offloaded+ # and the rollback copies cost no VRAM.+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ extra_args = ["--device", "none"],+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--fit") + 1] == "on"+ assert "draft-mtp" in cmd[cmd.index("--spec-type") + 1]+ assert backend.spec_fallback_reason is None+++def test_a_hand_pinned_device_is_gpu_evidence_when_the_probe_found_none(tmp_path):+ # A failed probe is not evidence of no GPU: the extras can still point the+ # child at one and ask for a partial count, which is the placement this+ # fallback exists for. Same flag _device_selection_is_cpu reads for the CPU+ # answer, so the two sides agree.+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True, memory = [])++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ extra_args = ["--device", "Vulkan0", "--gpu-layers", "42"],+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--device") + 1] == "Vulkan0"+ assert cmd[cmd.index("--spec-type") + 1] == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"+++def test_partial_offload_stand_down_records_the_draft_depth_it_decided_at(tmp_path):+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ spec_draft_n_max = 3,+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--spec-type") + 1] == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"+ # Nothing drafts, so the flag is not emitted -- but the depth priced the+ # rollback copies that made this placement partial, so it is recorded for the+ # reload comparison (test_llama_cpp_mtp_detection.py owns that half).+ assert "--spec-draft-n-max" not in cmd+ assert backend.spec_draft_n_max == 3+++def test_manual_auto_layers_is_not_evidence_of_partial_offload(tmp_path):+ # Manual mode empties the probed GPU set to hand sizing to llama.cpp, so its+ # --fit on is the value this path starts at, not a finding. Reading it as+ # partial offload disabled MTP on a card with room for every layer.+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ gpu_memory_mode = "manual",+ gpu_layers = -1,+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--fit") + 1] == "on"+ assert "draft-mtp" in cmd[cmd.index("--spec-type") + 1]+ assert backend.spec_fallback_reason is None+++def test_manual_auto_layers_still_reads_a_pass_through_layer_count(tmp_path):+ # The evidence Manual mode does carry: a concrete count in the extras. That+ # still stands the drafter down, so declining to guess costs nothing where the+ # user actually said where the layers go.+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ gpu_memory_mode = "manual",+ gpu_layers = -1,+ extra_args = ["--gpu-layers", "42"],+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--spec-type") + 1] == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"+++def test_auto_disables_embedded_hybrid_mtp_for_final_partial_layer_override(tmp_path):+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ extra_args = ["--gpu-layers", "42"],+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[-2:] == ["--gpu-layers", "42"]+ assert cmd[cmd.index("--spec-type") + 1] == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"+++def test_auto_reports_the_binary_not_the_placement_when_the_build_lacks_mtp(tmp_path):+ # Nothing to stand down: this build cannot run MTP at all, so the placement+ # story would send the user to force a mode it does not have, and hide the+ # update affordance the binary fallback carries.+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)+ backend.probe_server_capabilities = lambda _binary = None: {+ "mtp_token": None,+ "mtp_probe_inconclusive": False,+ "supports_ngram_mod": False,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ }++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert "--spec-type" not in cmd+ assert "--spec-default" in cmd+ assert backend.spec_fallback_reason == "binary_no_mtp"+++def test_auto_classifies_placement_on_the_device_flags_the_child_gets(tmp_path):+ # An explicit gpu_ids pick owns placement, so the launch drops the stale+ # --device none from the extras further down. Classifying before that strip+ # would read CPU-only for a load that partially offloads.+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ gpu_ids = [0],+ extra_args = ["--device", "none"],+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ # The strip already ran: the child never sees the CPU device the classifier+ # would otherwise have believed.+ assert "--device" not in cmd+ assert cmd[cmd.index("--spec-type") + 1] == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"+++def _hybrid_reserve_backend(tmp_path: Path, *, caps = None):+ """A Hybrid Mamba target on one 24 GB card with the MTP-overhead math live.++ The drafter's own KV is stubbed away so the only moving term is the target's+ recurrent rollback state, which is what the reserve has to keep charging.+ """+ gb = 1024**3+ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 24_576, 24_576)])+ sidecar = tmp_path / "dflash-model-Q8_0.gguf"+ sidecar.write_bytes(b"draft")+ backend._get_gguf_size_bytes = lambda path: (0 if str(path) == str(sidecar) else 8 * gb)+ backend._can_estimate_kv = lambda: True+ backend._compute_buffer_ctx_bytes = lambda *args, **kwargs: 0+ backend._estimate_compute_buffer_bytes = lambda **kwargs: 1+ backend._mtp_draft_kv_bytes = lambda *args, **kwargs: 0+ backend._select_gpus = lambda *args, **kwargs: ([0], False)+ backend._select_gpus_split_aware = lambda *args, **kwargs: ([0], False)++ def read_metadata(_path):+ backend._nextn_predict_layers = 1+ backend._n_layers = 65+ backend._n_kv_heads = 4+ backend._n_heads = 24+ backend._embedding_length = 5120+ backend._kv_key_length = 256+ backend._kv_value_length = 256+ backend._full_attention_interval = 4+ backend._ssm_inner_size = 6144+ backend._ssm_state_size = 128+ backend._ssm_group_count = 16+ backend._ssm_conv_kernel = 4++ backend._read_gguf_metadata = read_metadata+ backend.probe_server_capabilities = lambda _binary = None: caps or {+ "mtp_token": "draft-mtp",+ "supports_dflash": True,+ "supports_ngram_mod": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ # Or the launch clamps the four slots to one and the per-slot state,+ # which is what these tests measure, shrinks with them.+ "supports_kv_unified": True,+ }+ return backend, gguf, sidecar+++def _recorded_mtp_reserve(backend, gguf, **load_kwargs):+ """The bytes the fit was asked to hold back for speculation."""+ charged, _fns = _recorded_mtp_reserve_and_callbacks(backend, gguf, **load_kwargs)+ return charged+++def _recorded_mtp_reserve_and_callbacks(backend, gguf, **load_kwargs):+ """The reserve the fit saw, plus the callback objects it was handed."""+ charged = []+ callbacks = []+ _fit = backend._fit_context_to_vram++ def recording_fit(requested, *args, **kwargs):+ fn = kwargs.get("mtp_overhead_fn")+ callbacks.append(fn)+ charged.append(0 if fn is None else int(fn(requested) or 0))+ return _fit(requested, *args, **kwargs)++ backend._fit_context_to_vram = recording_fit+ _launch(backend, gguf, **load_kwargs)+ assert charged, "the fit never ran, so this proves nothing"+ return charged, callbacks+++def test_a_cpu_pinned_drafter_still_pays_the_hybrid_target_rollback(tmp_path):+ # -ngld 0 moves the drafter's weights and KV to host memory, but the rollback+ # snapshots live in the TARGET context, so they stay on the GPU. Releasing the+ # whole reserve here undercounts them and the fit can pick a placement that+ # spills.+ backend, gguf, sidecar = _hybrid_reserve_backend(tmp_path)++ charged = _recorded_mtp_reserve(+ backend,+ gguf,+ dflash_draft_path = str(sidecar),+ speculative_type = "dflash",+ n_ctx = 8192,+ n_parallel = 4,+ extra_args = ["--spec-draft-ngl", "0"],+ )++ # After the launch: the GGUF dims land when the load reads the metadata.+ expected = backend._mamba_recurrent_state_bytes(n_parallel = 4) * 2+ assert expected > 0+ assert set(charged) == {expected}+++def test_the_cpu_drafter_reserve_still_reprices_per_slot_candidate(tmp_path):+ # _slots_that_fit_on_gpu re-prices the reserve for each candidate slot count+ # through the callback's _np / _n_ubatch keywords. A replacement that takes+ # neither raises TypeError there, and the broad GPU-selection handler swallows+ # it into --fit on, throwing the whole placement plan away.+ backend, gguf, sidecar = _hybrid_reserve_backend(tmp_path)++ _charged, callbacks = _recorded_mtp_reserve_and_callbacks(+ backend,+ gguf,+ dflash_draft_path = str(sidecar),+ speculative_type = "dflash",+ n_ctx = 8192,+ n_parallel = 4,+ extra_args = ["--spec-draft-ngl", "0"],+ )++ fn = callbacks[0]+ assert fn is not None+ for slots in (1, 2, 4):+ assert fn(8192, _np = slots, _n_ubatch = 512) == (+ backend._mamba_recurrent_state_bytes(n_parallel = slots) * 2+ )+ # Per-slot state, not per-token: context does not move it.+ assert fn(2048, _np = 4, _n_ubatch = 512) == fn(131072, _np = 4, _n_ubatch = 512)+++ ("spec_type", "pays_rollback"),+ [("draft-dflash", True), ("draft-eagle3", True), ("draft-simple", False)],+)+def test_a_pass_through_drafter_pays_the_rollback_its_type_calls_for(+ tmp_path, spec_type, pays_rollback+):+ # need_n_rs_seq lists every draft-model type but draft-simple, so the extras+ # path has to read the type rather than assume either answer.+ backend, gguf, sidecar = _hybrid_reserve_backend(tmp_path)++ charged = _recorded_mtp_reserve(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 8192,+ n_parallel = 4,+ extra_args = [+ "--spec-type",+ spec_type,+ "--model-draft",+ str(sidecar),+ "--spec-draft-n-max",+ "2",+ ],+ )++ rollback = backend._mamba_recurrent_state_bytes(n_parallel = 4) * 2+ assert rollback > 0+ assert set(charged) == {rollback if pays_rollback else 0}++[email protected]("requested_depth", [None, 2])+def test_a_pass_through_spec_block_budgets_the_depth_the_build_defaults_to(+ tmp_path, requested_depth+):+ # Studio emits no --spec-draft-n-max when the extras own the spec block, so+ # the child runs at the build's own default. Budgeting Studio's 2 instead+ # under-reserves the rollback copies, which scale directly with it -- and a+ # request field carries no further than the platform default does, since+ # neither is emitted.+ backend, gguf, _sidecar = _hybrid_reserve_backend(+ tmp_path,+ caps = {+ "mtp_token": "draft-mtp",+ "supports_ngram_mod": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ "spec_draft_n_max_default": 16,+ "supports_kv_unified": True,+ },+ )+ charged = _recorded_mtp_reserve(+ backend,+ gguf,+ speculative_type = "auto",+ spec_draft_n_max = requested_depth,+ n_ctx = 8192,+ n_parallel = 4,+ extra_args = ["--spec-type", "draft-mtp"],+ )++ base = backend._mamba_recurrent_state_bytes(n_parallel = 4)+ assert base > 0+ assert set(charged) == {16 * base}+++def test_a_legacy_build_inherits_its_own_draft_depth_variable(tmp_path, monkeypatch):+ # A legacy build spells the pair --draft-max / LLAMA_ARG_DRAFT_MAX. Reading only+ # the post-rename name budgets the build default while the child drafts at the+ # inherited one.+ backend, gguf, _sidecar = _hybrid_reserve_backend(+ tmp_path,+ caps = {+ "mtp_token": "draft-mtp",+ "supports_ngram_mod": True,+ "spec_draft_n_max_flag": "--draft-max",+ "spec_draft_n_max_default": 8,+ "supports_kv_unified": True,+ },+ )+ monkeypatch.setenv("LLAMA_ARG_DRAFT_MAX", "32")++ charged = _recorded_mtp_reserve(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 8192,+ n_parallel = 4,+ extra_args = ["--spec-type", "draft-mtp"],+ )++ base = backend._mamba_recurrent_state_bytes(n_parallel = 4)+ assert base > 0+ assert set(charged) == {32 * base}+++def test_a_post_rename_build_ignores_the_legacy_depth_variable(tmp_path, monkeypatch):+ # LLAMA_ARG_DRAFT_MAX is the twin of the removed --draft-max, so a build that+ # advertises the modern flag never reads it. Pricing a stale value there would+ # budget a depth the child does not draft at.+ backend, gguf, _sidecar = _hybrid_reserve_backend(+ tmp_path,+ caps = {+ "mtp_token": "draft-mtp",+ "supports_ngram_mod": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ "spec_draft_n_max_default": 16,+ "supports_kv_unified": True,+ },+ )+ monkeypatch.delenv("LLAMA_ARG_SPEC_DRAFT_N_MAX", raising = False)+ monkeypatch.setenv("LLAMA_ARG_DRAFT_MAX", "32")++ charged = _recorded_mtp_reserve(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 8192,+ n_parallel = 4,+ extra_args = ["--spec-type", "draft-mtp"],+ )++ base = backend._mamba_recurrent_state_bytes(n_parallel = 4)+ assert base > 0+ assert set(charged) == {16 * base}+++def test_an_unreadable_help_budgets_the_deepest_shipped_draft_depth(tmp_path):+ # The probe timed out, or the help line carries no default. The child is still+ # drafting at whatever the build defaults to, so Studio's own explicit-mode 2+ # would under-reserve the rollback copies by up to eight times.+ backend, gguf, _sidecar = _hybrid_reserve_backend(+ tmp_path,+ caps = {+ "mtp_token": "draft-mtp",+ "supports_ngram_mod": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ "supports_kv_unified": True,+ },+ )++ charged = _recorded_mtp_reserve(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 8192,+ n_parallel = 4,+ extra_args = ["--spec-type", "draft-mtp"],+ )++ base = backend._mamba_recurrent_state_bytes(n_parallel = 4)+ assert base > 0+ assert set(charged) == {LlamaCppBackend._UNKNOWN_SPEC_DRAFT_N_MAX * base}+++def test_an_explicit_pin_the_probe_cannot_see_is_not_a_partial_verdict(tmp_path):+ # The probe answered nothing, but the pick still pins the child to those+ # devices, so the launch does offload to them: the probe-only view read this+ # as a CPU-only box, and the GPU-evidence guard is right to accept the pin.+ #+ # That is where the pin's authority stops. Every planner branch is gated on a+ # non-empty `gpus`, so with an empty probe none of them ran and the `--fit on`+ # below is the default use_fit starts at, not a finding that the model does+ # not fit -- the same reasoning _partially_offloads_layers already applies to+ # Manual mode. Standing MTP down here would cost the drafting win on a card+ # that may well hold every layer, so Auto keeps MTP until something actually+ # says the placement is partial.+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True, memory = [])++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ gpu_ids = [0],+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--fit") + 1] == "on"+ assert cmd[cmd.index("--spec-type") + 1] == "draft-mtp"+ assert backend.spec_fallback_reason != "mtp_partial_offload"+++def test_an_unseen_pin_with_a_concrete_layer_count_still_stands_down(tmp_path):+ # The other half: a fixed 42 of 65 blocks is partial placement on its own+ # evidence, so the empty probe costs the stand-down nothing here.+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True, memory = [])++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ gpu_ids = [0],+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = ["--gpu-layers", "42"],+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--spec-type") + 1] == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"++def _tight_vram_backend(tmp_path: Path, *, drafter_gb: float):"""One 24 GB card, a 16 GB target and a drafter of the caller's size.@@ -748,7 +1400,7 @@ def test_the_drop_actually_releases_the_reserve_the_fit_charges(tmp_path):backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 24_576, 24_576)])sidecar = tmp_path / "dspark-model-Q8_0.gguf"sidecar.write_bytes(b"draft")- backend._get_gguf_size_bytes = lambda path: (6 * gb if str(path) == str(sidecar) else 16 * gb)+ backend._get_gguf_size_bytes = lambda path: 6 * gb if str(path) == str(sidecar) else 16 * gbbackend._read_gguf_metadata = lambda _path: setattr(backend, "_context_length", 8192)backend._can_estimate_kv = lambda: True# Context-linear, so an unreleased drafter reserve is paid for in context.@@ -852,7 +1504,7 @@ def test_a_subset_that_can_shrink_to_hold_both_is_where_the_decision_lands(tmp_p)sidecar = tmp_path / "dspark-model-Q8_0.gguf"sidecar.write_bytes(b"draft")- backend._get_gguf_size_bytes = lambda path: (8 * gb if str(path) == str(sidecar) else 16 * gb)+ backend._get_gguf_size_bytes = lambda path: 8 * gb if str(path) == str(sidecar) else 16 * gbbackend._read_gguf_metadata = lambda _path: setattr(backend, "_context_length", 8192)backend._can_estimate_kv = lambda: True# Context-linear throughout, so GPU0 alone can shrink its way to holding both.diff --git a/studio/backend/tests/test_mtp_partial_offload_evidence.py b/studio/backend/tests/test_mtp_partial_offload_evidence.pynew file mode 100644index 00000000000..9b18a095b25--- /dev/null+++ b/studio/backend/tests/test_mtp_partial_offload_evidence.py@@ -0,0 +1,577 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What counts as evidence that a placement is partial, and what does not.++Auto stands the embedded Hybrid Mamba MTP head down by emitting+``--spec-type none`` when the placement is partial, because the recurrent+rollback copies then cost more layers than the drafting wins back. Getting the+EVIDENCE test wrong is expensive in both directions: too strict and Studio is+back to the 3.11 token/s of the reported regression, too loose and it gives up a+real speedup on a card that had room for every layer.++``--fit on`` alone is not evidence. ``use_fit`` starts True at its declaration,+every placement-planner branch is gated on a non-empty ``gpus``, and the except+path restores True having priced nothing -- so an unfitted ``--fit on`` means+"nobody looked" at least as often as it means "it does not fit". Only a planner+run that completed over a real device list and still could not fit the model is+a verdict; a concrete ``--gpu-layers`` count is independent evidence and needs+no planner at all.++Platform is simulated by patching sys.platform (llama_cpp.py reads it at call+time) and the accelerator by stubbing the probe, which is what actually differs+between hosts: _get_gpu_memory returns nvidia-smi output on Linux/Windows/WSL+with NVIDIA, amd-smi output on ROCm, ggml Vulkan ordinals on a Vulkan build, and+[] on a Metal Mac and on any CPU-only box (llama_cpp.py:6598-6680).+"""++import sys+import tempfile+from pathlib import Path+from unittest.mock import patch++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++import pytest # noqa: E402++# Reuse the module's dependency stubs, fixtures and launch harness.+from test_llama_cpp_placement import _hybrid_mtp_backend, _launch # noqa: E402++from core.inference.llama_cpp import LlamaCppBackend # noqa: E402+++def test_auto_keeps_mtp_when_the_gpu_selector_raises():+ """GPUs enumerated, then _select_gpus throws.++ The handler logs "GPU selection failed, using --fit on" and restores+ `gpu_indices, use_fit = None, True`. _detected_gpus is already populated, so+ the GPU-evidence guard passes and a fit-only test would read that fallback+ True as a partial verdict -- but no placement was ever computed.++ This route is why a `bool(_detected_gpus)` guard would not be enough: the+ verdict has to be recorded where the planner returns, not inferred later.+ """+ with tempfile.TemporaryDirectory() as td:+ tmp_path = Path(td)+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False)++ def _boom(*args, **kwargs):+ raise RuntimeError("probe wedged")++ backend._select_gpus = _boom+ backend._select_gpus_split_aware = _boom++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ spec = cmd[cmd.index("--spec-type") + 1] if "--spec-type" in cmd else None+ assert spec != "none", (+ "Auto stood MTP down off the exception fallback's --fit on, "+ f"fallback reason {backend.spec_fallback_reason!r}"+ )+++def test_auto_keeps_mtp_when_the_planner_proved_full_offload():+ """The planner returned a fully offloaded placement.++ _select_gpus gives ([0], False) -- every layer fits -- and the user appends a+ last-wins `--fit on` in the extras. fit_is_effectively_on then reads True and+ the arm calls the placement partial, discarding a verdict that positively+ proved the opposite.+ """+ with tempfile.TemporaryDirectory() as td:+ tmp_path = Path(td)+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = ["--fit", "on"],+ )++ cmd = result["cmd"]+ spec = cmd[cmd.index("--spec-type") + 1] if "--spec-type" in cmd else None+ assert spec != "none", (+ "Auto stood MTP down despite the planner proving full offload, "+ f"fallback reason {backend.spec_fallback_reason!r}"+ )+++def test_a_concrete_partial_layer_count_still_stands_mtp_down():+ """The control: independent evidence must keep working.++ 42 of 65 blocks is partial whatever the planner did, so tightening the fit arm+ must not touch this one. Passes on the PR head and must keep passing.+ """+ with tempfile.TemporaryDirectory() as td:+ tmp_path = Path(td)+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = ["--gpu-layers", "42"],+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--spec-type") + 1] == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"+++# ─────────────── the platform x accelerator product ───────────────++# (id, sys.platform value, extra marker so WSL is distinguishable from Linux)+PLATFORMS = [+ ("linux", "linux"),+ ("wsl", "linux"),+ ("windows", "win32"),+ ("mac", "darwin"),+]++# (id, probe result, vulkan build?, device pin the user might supply)+ACCELERATORS = [+ ("nvidia", [(0, 12 * 1024, 24 * 1024)], False, None),+ ("amd", [(0, 12 * 1024, 24 * 1024)], False, None),+ ("vulkan", [(0, 12 * 1024, 24 * 1024)], True, "Vulkan0"),+ ("cpu_only", [], False, None),+]+++def _spec_of(cmd):+ return cmd[cmd.index("--spec-type") + 1] if "--spec-type" in cmd else None+++def _mtp_is_engaged(cmd):+ return _spec_of(cmd) in ("draft-mtp", "mtp")++[email protected]("plat_id,plat", PLATFORMS, ids = [p[0] for p in PLATFORMS])+ "acc_id,memory,vulkan,device",+ ACCELERATORS,+ ids = [a[0] for a in ACCELERATORS],+)+def test_partial_layer_count_stands_mtp_down_everywhere(+ tmp_path, plat_id, plat, acc_id, memory, vulkan, device+):+ """A concrete partial `--gpu-layers` is placement evidence on every host.++ 42 of 65 blocks is partial whatever the planner, the probe or the OS did, so+ this cell must stand MTP down uniformly -- except CPU-only, where there is no+ GPU to partially offload TO and the CPU MTP policy still applies.+ """+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False, memory = memory)+ backend._is_vulkan_backend = lambda _binary = None: vulkan+ extra = ["--gpu-layers", "42"]+ if device:+ extra = ["--device", device, *extra]++ with patch.object(sys, "platform", plat):+ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = extra,+ )++ cmd = result["cmd"]+ if acc_id == "cpu_only" and not device:+ # No GPU anywhere: keep the CPU MTP policy (llama_cpp.py:15530 guard).+ assert not _mtp_is_engaged(cmd) or _spec_of(cmd) != "none"+ else:+ assert _spec_of(cmd) == "none", f"{plat_id}/{acc_id} did not stand MTP down"+ assert backend.spec_fallback_reason == "mtp_partial_offload"++[email protected]("plat_id,plat", PLATFORMS, ids = [p[0] for p in PLATFORMS])+ "acc_id,memory,vulkan,device",+ ACCELERATORS,+ ids = [a[0] for a in ACCELERATORS],+)+def test_full_offload_keeps_mtp_everywhere(tmp_path, plat_id, plat, acc_id, memory, vulkan, device):+ """The planner proved every layer fits: MTP is the whole point, keep it.++ This is the regression direction that matters most -- the PR must not cost+ MTP to the users it already works for.+ """+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False, memory = memory)+ backend._is_vulkan_backend = lambda _binary = None: vulkan+ extra = ["--device", device] if device else None++ with patch.object(sys, "platform", plat):+ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = extra,+ )++ cmd = result["cmd"]+ assert _spec_of(cmd) != "none", (+ f"{plat_id}/{acc_id} stood MTP down on a proven FULL offload "+ f"(reason {backend.spec_fallback_reason!r})"+ )++[email protected]("plat_id,plat", PLATFORMS, ids = [p[0] for p in PLATFORMS])+ "acc_id,memory,vulkan,device",+ ACCELERATORS,+ ids = [a[0] for a in ACCELERATORS],+)+def test_cpu_only_layer_count_keeps_mtp_everywhere(+ tmp_path, plat_id, plat, acc_id, memory, vulkan, device+):+ """`--gpu-layers 0` is CPU-only, not partial: the rollback copies cost no VRAM."""+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False, memory = memory)+ backend._is_vulkan_backend = lambda _binary = None: vulkan+ extra = ["--gpu-layers", "0"]+ if device:+ extra = ["--device", device, *extra]++ with patch.object(sys, "platform", plat):+ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = extra,+ )++ assert _spec_of(result["cmd"]) != "none", f"{plat_id}/{acc_id} stood down on -ngl 0"++[email protected]("plat_id,plat", PLATFORMS, ids = [p[0] for p in PLATFORMS])+ "acc_id,memory,vulkan,device",+ ACCELERATORS,+ ids = [a[0] for a in ACCELERATORS],+)+def test_over_full_layer_count_keeps_mtp_everywhere(+ tmp_path, plat_id, plat, acc_id, memory, vulkan, device+):+ """`--gpu-layers 999` is full offload plus the output layer, never partial."""+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = False, memory = memory)+ backend._is_vulkan_backend = lambda _binary = None: vulkan+ extra = ["--gpu-layers", "999"]+ if device:+ extra = ["--device", device, *extra]++ with patch.object(sys, "platform", plat):+ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = extra,+ )++ assert _spec_of(result["cmd"]) != "none", f"{plat_id}/{acc_id} stood down on -ngl 999"++[email protected]("plat_id,plat", PLATFORMS, ids = [p[0] for p in PLATFORMS])+def test_explicit_mtp_survives_partial_offload_everywhere(tmp_path, plat_id, plat):+ """A user who picks MTP by hand overrides the policy on every platform."""+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ with patch.object(sys, "platform", plat):+ result = _launch(+ backend,+ gguf,+ speculative_type = "mtp",+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = ["--gpu-layers", "42"],+ )++ assert _spec_of(result["cmd"]) != "none", f"{plat_id} overrode an explicit MTP choice"++[email protected]("plat_id,plat", PLATFORMS, ids = [p[0] for p in PLATFORMS])+def test_a_metal_mac_style_empty_probe_keeps_mtp(tmp_path, plat_id, plat):+ """No probe result and no concrete layer count is not evidence of anything.++ A Metal Mac reaches llama_cpp.py:6598 with no nvidia-smi, no amd-smi and no+ torch.cuda, so the probe is [] and `--fit on` is the untouched default from+ llama_cpp.py:14127 rather than a planner verdict. Same shape as a failed+ Vulkan probe on Linux or Windows.+ """+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True, memory = [])++ with patch.object(sys, "platform", plat):+ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ )++ assert (+ _spec_of(result["cmd"]) != "none"+ ), f"{plat_id} stood MTP down with no GPU evidence and no planner verdict"++[email protected]("plat_id,plat", PLATFORMS, ids = [p[0] for p in PLATFORMS])+def test_an_empty_probe_with_a_hand_pinned_device_keeps_mtp(tmp_path, plat_id, plat):+ """The b126194 hole: a device pin proves a GPU EXISTS, not that fit is partial.++ On a Metal Mac (`--device Metal0`) or after a failed Vulkan probe+ (`--device Vulkan0`) the planner never ran -- every branch of it is gated on a+ non-empty `gpus` -- so `--fit on` is still the default. Standing MTP down here+ costs a real speedup on a card that may have room for every layer.+ """+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True, memory = [])+ device = "Metal0" if plat == "darwin" else "Vulkan0"++ with patch.object(sys, "platform", plat):+ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = ["--device", device],+ )++ assert _spec_of(result["cmd"]) != "none", (+ f"{plat_id} stood MTP down off a device pin with no planner verdict "+ f"(reason {backend.spec_fallback_reason!r})"+ )+++# ───────────────────── binary + GGUF vintage ─────────────────────+++def test_a_build_without_mtp_reports_the_binary_not_the_placement(tmp_path):+ """An old llama.cpp with no MTP spelling must not claim a placement policy.++ Its `--spec-type` enum may not even carry "none", so the emit path below has+ to name binary_no_mtp and keep the update affordance.+ """+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)+ backend.probe_server_capabilities = lambda _binary = None: {+ "supports_ngram_mod": False,+ "spec_draft_n_max_flag": None,+ }++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ extra_args = ["--gpu-layers", "42"],+ )++ assert backend.spec_fallback_reason != "mtp_partial_offload"+++def test_an_old_gguf_without_ssm_group_count_is_priced_as_before(tmp_path):+ """A GGUF predating the ssm.group_count key must not get a garbage estimate.++ _mamba_recurrent_state_bytes returns 0 when any dimension is missing, so the+ load degrades to the pre-PR number instead of a wrong one.+ """+ b = LlamaCppBackend()+ for k, v in {+ "_n_layers": 65,+ "_nextn_predict_layers": 1,+ "_n_kv_heads": 4,+ "_n_heads": 24,+ "_embedding_length": 5120,+ "_kv_key_length": 256,+ "_kv_value_length": 256,+ "_full_attention_interval": 4,+ "_ssm_inner_size": 6144,+ "_ssm_state_size": 128,+ "_ssm_group_count": None,+ "_ssm_conv_kernel": None,+ }.items():+ setattr(b, k, v)++ assert b._mamba_recurrent_state_bytes() == 0+ assert b._mamba_recurrent_state_bytes(n_parallel = 4, n_rs_seq = 2) == 0+ # And the KV estimate is still the plain attention number.+ assert b._estimate_kv_cache_bytes(4096, "f16") == 16 * 4096 * 4 * (256 + 256) * 2+++def test_a_gguf_without_nextn_is_untouched_by_the_layer_change(tmp_path):+ """No embedded head: block_count - 0 == block_count, byte for byte."""+ b = LlamaCppBackend()+ for k, v in {+ "_n_layers": 28,+ "_n_kv_heads": 8,+ "_n_heads": 16,+ "_embedding_length": 1024,+ "_kv_key_length": 128,+ "_kv_value_length": 128,+ }.items():+ setattr(b, k, v)++ assert b._estimate_kv_cache_bytes(4096, "f16") == 28 * 4096 * 8 * (128 + 128) * 2++[email protected]("n_parallel", [1, 2, 4, 8])[email protected]("n_rs_seq", [0, 1, 2, 3, 16])+def test_recurrent_state_scales_linearly_in_slots_and_depth(n_parallel, n_rs_seq):+ """llama-memory-recurrent.cpp:99 allocates n_seq_max * (1 + n_rs_seq) rows."""+ b = LlamaCppBackend()+ for k, v in {+ "_n_layers": 65,+ "_nextn_predict_layers": 1,+ "_full_attention_interval": 4,+ "_ssm_inner_size": 6144,+ "_ssm_state_size": 128,+ "_ssm_group_count": 16,+ "_ssm_conv_kernel": 4,+ }.items():+ setattr(b, k, v)++ base = b._mamba_recurrent_state_bytes(n_parallel = 1, n_rs_seq = 0)+ assert b._mamba_recurrent_state_bytes(n_parallel, n_rs_seq) == base * n_parallel * (+ 1 + n_rs_seq+ )+++ "field",+ [+ "_n_layers",+ "_ssm_inner_size",+ "_ssm_state_size",+ "_ssm_group_count",+ "_ssm_conv_kernel",+ "_full_attention_interval",+ ],+)+def test_any_missing_recurrent_dimension_fails_closed(field):+ """A partially-populated header must return 0, never a partial product."""+ b = LlamaCppBackend()+ for k, v in {+ "_n_layers": 65,+ "_nextn_predict_layers": 1,+ "_full_attention_interval": 4,+ "_ssm_inner_size": 6144,+ "_ssm_state_size": 128,+ "_ssm_group_count": 16,+ "_ssm_conv_kernel": 4,+ }.items():+ setattr(b, k, v)+ setattr(b, field, None)++ assert b._mamba_recurrent_state_bytes(n_parallel = 4, n_rs_seq = 2) == 0+++def test_zero_full_attention_interval_does_not_divide_by_zero():+ b = LlamaCppBackend()+ for k, v in {+ "_n_layers": 65,+ "_nextn_predict_layers": 1,+ "_full_attention_interval": 0,+ "_ssm_inner_size": 6144,+ "_ssm_state_size": 128,+ "_ssm_group_count": 16,+ "_ssm_conv_kernel": 4,+ }.items():+ setattr(b, k, v)++ # fai == 0 means every layer is attention, so nothing is recurrent.+ assert b._mamba_recurrent_state_bytes(n_parallel = 4) == 0+++def test_the_reported_regression_is_still_fixed(tmp_path):+ """The whole point of the PR, guarded against every fix above.++ Qwen3.8-27B UD-IQ2_M, about 12 GiB free, Auto, four slots: nvidia-smi answers,+ the planner runs over a real device list and cannot fit the model, so --fit on+ IS a verdict here and the stand-down must fire. If a tightening of the fit arm+ ever breaks this, Studio is back to 3.11 token/s.++ See https://huggingface.co/unsloth/Qwen3.8-27B-GGUF/discussions/18.+ """+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = 4,+ )++ cmd = result["cmd"]+ assert cmd[cmd.index("--fit") + 1] == "on"+ assert _spec_of(cmd) == "none"+ assert "draft-mtp" not in cmd+ assert backend.spec_fallback_reason == "mtp_partial_offload"+++def test_the_stand_down_survives_a_64k_context(tmp_path):+ """Same verdict at the other context the PR measured."""+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 65536,+ n_parallel = 4,+ )++ assert _spec_of(result["cmd"]) == "none"+ assert backend.spec_fallback_reason == "mtp_partial_offload"++[email protected]("n_parallel", [1, 2, 4, 8])+def test_the_verdict_does_not_depend_on_slot_count(tmp_path, n_parallel):+ """The rollback reserve is per-slot, but the policy is not."""+ backend, gguf = _hybrid_mtp_backend(tmp_path, partial_offload = True)++ result = _launch(+ backend,+ gguf,+ speculative_type = "auto",+ n_ctx = 4096,+ n_parallel = n_parallel,+ )++ assert _spec_of(result["cmd"]) == "none"+++def test_nextn_larger_than_block_count_does_not_go_negative():+ b = LlamaCppBackend()+ for k, v in {+ "_n_layers": 4,+ "_nextn_predict_layers": 99,+ "_full_attention_interval": 4,+ "_ssm_inner_size": 6144,+ "_ssm_state_size": 128,+ "_ssm_group_count": 16,+ "_ssm_conv_kernel": 4,+ }.items():+ setattr(b, k, v)++ assert b._mamba_recurrent_state_bytes(n_parallel = 4) >= 0+ assert b._estimate_kv_cache_bytes(4096, "f16") >= 0diff --git a/studio/backend/tests/test_mtp_vram_budget.py b/studio/backend/tests/test_mtp_vram_budget.pyindex 483a2bac2f5..e479aeab942 100644--- a/studio/backend/tests/test_mtp_vram_budget.py+++ b/studio/backend/tests/test_mtp_vram_budget.py@@ -355,6 +355,74 @@ class TestOverheadTotal:pred = b._estimate_mtp_overhead_bytes(ctx) / MIBassert pred == pytest.approx(measured_draft_kv_mib, abs = 2)+ @pytest.mark.parametrize(+ "ctx,target_kv_mib,draft_kv_mib",+ [+ (4096, 256, 16),+ (16384, 1024, 64),+ (65536, 4096, 256),+ (131072, 8192, 512),+ ],+ )+ def test_hybrid_mtp_matches_target_and_draft_context_across_lengths(+ self, ctx, target_kv_mib, draft_kv_mib+ ):+ b = _make_backend(n_layers = 65)+ b._ssm_state_size = 128+ b._ssm_group_count = 16+ b._ssm_conv_kernel = 4+ base = b._mamba_recurrent_state_bytes(n_parallel = 4)+ target = b._estimate_kv_cache_bytes(ctx, "f16", n_parallel = 4)+ draft_kv = b._mtp_draft_kv_bytes(ctx, n_parallel = 4)++ assert base / MIB == pytest.approx(598.5)+ assert target == base + target_kv_mib * MIB+ assert draft_kv == draft_kv_mib * MIB+ assert (+ b._estimate_mtp_overhead_bytes(+ ctx,+ spec_draft_n_max = 2,+ n_parallel = 4,+ )+ == draft_kv + 2 * base+ )++ def test_a_separate_drafter_pays_the_same_target_rollback_state(self, monkeypatch):+ # The rollback copies live in the TARGET context, and llama.cpp sizes them+ # from --spec-draft-n-max for every draft-model type (need_n_rs_seq), so a+ # sidecar drafter costs the Hybrid Mamba target exactly what an embedded+ # head does. draft-simple is the one engaged mode that gets none, which is+ # what the caller reports through target_rollback.+ b = _make_backend(n_layers = 65)+ b._ssm_state_size = 128+ b._ssm_group_count = 16+ b._ssm_conv_kernel = 4+ stub = _StubDrafter(kv_per_token = 2000)+ monkeypatch.setattr(b, "_draft_backend_for", lambda path: stub)+ base = b._mamba_recurrent_state_bytes(n_parallel = 4)+ draft_kv = stub._estimate_kv_cache_bytes(4096, n_parallel = 4)+ assert base > 0++ assert (+ b._estimate_mtp_overhead_bytes(+ 4096,+ drafter_path = "/m/d.gguf",+ spec_draft_n_max = 2,+ n_parallel = 4,+ )+ == draft_kv + 2 * base+ )+ assert (+ b._estimate_mtp_overhead_bytes(+ 4096,+ drafter_path = "/m/d.gguf",+ spec_draft_n_max = 2,+ n_parallel = 4,+ target_rollback = False,+ )+ == draft_kv+ )+# ---------------------------------------------------------------------------# _fit_context_to_vram: MTP reserve lowers the chosen context@@ -1044,10 +1112,17 @@ class TestExtraArgsMtpDetection:# A separate CPU-offloaded drafter (no embedded head) uses no GPU, so the# tensor reserve must be suppressed like the layer path -- else tensor mode# subtracts a phantom flat MTP reserve and under-advertises context (#6312).+ # The flat fraction is the part that must stay suppressed outright; the+ # byte reserve now has one exception, a Hybrid Mamba target's own rollback+ # state, which the CPU pin does not move off the GPU.load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())- assert "_mtp_will_engageandnot_draft_cpu_no_embedded" in load- assert "ifnot_mtp_reserves_gpu:" in load+ assert "if(_flat_mtp_engagesandnot_draft_cpu_no_embedded)" in load+ assert "_mtp_reserves_gpu=_mtp_will_engageandnot_draft_cpu_no_embedded" in loadassert "mtp_engaged=_mtp_reserves_gpu" in load+ # The tensor floor asks the narrower question, so the target state it keeps+ # is held there without also re-charging the CPU-resident draft graph.+ assert "_mtp_gpu_bytes_remain=_mtp_reserves_gpuormtp_overhead_fnisnotNone" in load+ assert "ifnot_mtp_gpu_bytes_remain:" in loaddef test_load_model_adopts_env_tensor_split_mode(self):# load_model delegates the tensor decision to _effective_tensor_parallel,diff --git a/studio/backend/tests/test_nextn_target_kv_policy.py b/studio/backend/tests/test_nextn_target_kv_policy.pynew file mode 100644index 00000000000..1aa4e76f521--- /dev/null+++ b/studio/backend/tests/test_nextn_target_kv_policy.py@@ -0,0 +1,318 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Which architectures may drop the embedded MTP blocks from target KV.++GGUF ``block_count`` includes the trailing NextN/MTP blocks, and+``llama_hparams::n_layer()`` subtracts them (llama-hparams.cpp:297) -- but the+target KV cache walks ``n_layer_all`` (llama-kv-cache.cpp:100) and drops blocks+only through an optional per-architecture filter (:169). So "carries a+nextn_predict_layers key" and "its MTP blocks are outside the target context"+are different questions, and only the second one may reduce the estimate.++Filters, ggml-org/llama.cpp @ adb55e5:+ llama-model.cpp:2289 hybrids -- qwen3next / qwen35 / qwen35moe / minimax-01,+ and nemotron_h via is_recr+ llama-model.cpp:2129 glm-dsa / deepseek32+ llama-model.cpp:2356 step35 / hy_v3 / mimo2+Everything else (deepseek2, glm4, glm4moe, bailingmoe2, cohere2moe, exaone4)+gets ``filter == nullptr``, so its trailing MTP block DOES get target KV and+subtracting it would under-reserve.++Recurrent state is the exception that always subtracts: llama_memory_recurrent+sizes on ``n_layer()`` directly (llama-memory-recurrent.cpp:29).+"""++import sys+import types as _types+from pathlib import Path++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)+_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++# Same dependency stubs the neighbouring estimation tests install, but the+# structlog stand-in carries get_logger: a bare module here is what the rest of+# the suite finds under setdefault, and utils/prebuilt/freshness_flow.py calls+# structlog.get_logger at import time.+_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)+if "structlog" not in sys.modules:+ _structlog_stub = _types.ModuleType("structlog")+ _structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")+ sys.modules["structlog"] = _structlog_stub++import pytest # noqa: E402++from core.inference.llama_cpp import LlamaCppBackend # noqa: E402+from test_kv_cache_estimation import _backend_from_gguf # noqa: E402+++def _gqa_backend(**overrides):+ """A plain-GQA header: no SSM, no MLA, no SWA, so Path 4 prices it."""+ defaults = {+ "_n_layers": 47,+ "_n_kv_heads": 8,+ "_n_heads": 96,+ "_embedding_length": 4096,+ "_kv_key_length": 128,+ "_kv_value_length": 128,+ }+ defaults.update(overrides)+ b = LlamaCppBackend()+ for k, v in defaults.items():+ setattr(b, k, v)+ return b+++def test_glm4_moe_nextn_block_stays_in_target_kv():+ """GLM-4.5-Air shape: block_count 47 = 46 trunk + 1 nextn.++ conversion/glm.py:116 writes block_count INCLUDING the nextn block and+ :154 writes nextn_predict_layers, so a shipped GLM-4.5/4.6 MoE GGUF carries+ both. src/models/glm4-moe.cpp:23 reduces n_layer(), but the target context+ for LLM_ARCH_GLM4_MOE is a plain llama_kv_cache with filter == nullptr, so+ llama-kv-cache.cpp:100 still walks all 47 blocks and allocates KV for the+ nextn block. The estimate must therefore cover 47 layers, not 46.+ """+ b = _gqa_backend(_nextn_predict_layers = 1)+ cells = 4096 # already 256-aligned, so cells == n_ctx at one unified slot+ per_layer = cells * 8 * (128 + 128) * 2++ assert b._estimate_kv_cache_bytes(4096, "f16") == 47 * per_layer+++def test_glm4_moe_target_kv_does_not_move_when_the_head_is_declared():+ """Declaring the MTP head must not shrink the target reserve by a layer."""+ with_nextn = _gqa_backend(_nextn_predict_layers = 1)+ without = _gqa_backend()++ missing = without._estimate_kv_cache_bytes(4096, "f16") - with_nextn._estimate_kv_cache_bytes(+ 4096, "f16"+ )+ # One layer of 47 is ~2.1% of the reserve, and it is llama.cpp's to allocate.+ assert missing == 0, f"target KV dropped by {missing} bytes ({missing / 1024**2:.1f} MiB)"+++def test_gemma4_assistant_shaped_header_does_not_collapse_to_one_layer():+ """src/models/gemma4-assistant.cpp:15 asserts n_layer_nextn == n_layer_all.++ block_count - nextn is 0 there, so an unconditional subtraction behind a+ max(1, ...) floor would price a 12-layer model as one layer. The arch gate+ keeps it out of the subtraction entirely. Reachable through the+ separate-drafter call at _mtp_draft_kv_bytes, which sizes a drafter GGUF's+ own KV with this function, and by loading the assistant model directly.+ """+ b = _gqa_backend(_n_layers = 12, _nextn_predict_layers = 12)+ cells = 4096+ per_layer = cells * 8 * (128 + 128) * 2++ result = b._estimate_kv_cache_bytes(4096, "f16")+ assert result != 1 * per_layer, "estimate collapsed to the max(1, ...) floor"+ assert result == 12 * per_layer+++def test_qwen35_hybrid_nextn_subtraction_is_correct():+ """The control: the PR's own target case, which upstream DOES filter.++ llama-model.cpp:2289 filters both the attention and recurrent halves to+ il < n_layer() for QWEN35/QWEN35MOE/QWEN3NEXT, and+ llama-memory-recurrent.cpp:29 sizes on n_layer() too, so subtracting is right+ here. This is what the cases above must not be allowed to break: the arch+ gate has to keep the hybrid saving while dropping the rest.+ """+ b = LlamaCppBackend()+ for k, v in {+ "_n_layers": 65,+ "_nextn_predict_layers": 1,+ "_n_kv_heads": 4,+ "_n_heads": 24,+ "_embedding_length": 5120,+ "_kv_key_length": 256,+ "_kv_value_length": 256,+ "_full_attention_interval": 4,+ "_ssm_inner_size": 6144,+ "_ssm_state_size": 128,+ "_ssm_group_count": 16,+ "_ssm_conv_kernel": 4,+ }.items():+ setattr(b, k, v)++ # 64 trunk blocks -> ceil(64/4) = 16 attention layers, 48 recurrent.+ per_slot = 48 * ((4 - 1) * (6144 + 2 * 16 * 128) + 128 * 6144) * 4+ kv_only = 16 * 4096 * 4 * (256 + 256) * 2+ assert b._estimate_kv_cache_bytes(4096, "f16") == kv_only + per_slot+++# ─────────── per-architecture truth table (real GGUF headers) ───────────++# arch -> does llama.cpp's TARGET context leave the nextn block out?+ARCH_TRUTH_TABLE = [+ # Hybrid attention + recurrent, llama-model.cpp:2289+ ("qwen35", True),+ ("qwen35moe", True),+ ("qwen3next", True),+ ("minimax-01", True),+ ("nemotron_h", True),+ ("nemotron_h_moe", True),+ # MLA / DSA trunk with a dense MTP head, llama-model.cpp:2129+ ("glm-dsa", True),+ ("deepseek32", True),+ # Plain attention trunk with an explicit nextn filter, llama-model.cpp:2356+ ("step35", True),+ ("hy_v3", True),+ ("mimo2", True),+ # filter == nullptr: the trailing MTP block still gets target KV+ ("deepseek2", False),+ ("glm4moe", False),+ ("glm4", False),+ ("bailingmoe2", False),+ ("cohere2moe", False),+ ("exaone4", False),+ ("granite-switch", False), # nextn=1 leaks for a ROUTER layer that needs KV+ # An arch this Studio has never heard of must fail closed.+ ("some_future_arch", False),+]++_GQA_FIELDS = {+ "block_count": 47,+ "attention.head_count_kv": 8,+ "attention.head_count": 96,+ "embedding_length": 4096,+ "attention.key_length": 128,+ "attention.value_length": 128,+ "context_length": 131072,+}++[email protected]("arch,excludes", ARCH_TRUTH_TABLE, ids = [a for a, _ in ARCH_TRUTH_TABLE])+def test_target_kv_nextn_policy_matches_llama_cpp_per_arch(arch, excludes):+ """One layer of 47 is the whole question; get it right per architecture."""+ b = _backend_from_gguf(arch, {**_GQA_FIELDS, "nextn_predict_layers": 1})++ assert b._nextn_predict_layers == 1, "the header did not parse"+ assert b._target_kv_excludes_nextn() is excludes++ per_layer = 4096 * 8 * (128 + 128) * 2+ expected = (46 if excludes else 47) * per_layer+ assert b._estimate_kv_cache_bytes(4096, "f16") == expected++[email protected]("arch,_excludes", ARCH_TRUTH_TABLE, ids = [a for a, _ in ARCH_TRUTH_TABLE])+def test_no_nextn_key_is_never_reduced(arch, _excludes):+ """Backwards compat: a GGUF with no MTP head is priced exactly as before."""+ b = _backend_from_gguf(arch, dict(_GQA_FIELDS))++ assert not b._nextn_predict_layers+ assert b._target_kv_excludes_nextn() is False+ assert b._estimate_kv_cache_bytes(4096, "f16") == 47 * 4096 * 8 * (128 + 128) * 2+++def test_a_hybrid_header_is_evidence_even_for_an_unknown_arch():+ """Forwards compat: a future hybrid Mamba arch must still get the subtraction.++ Every hybrid llama.cpp takes a nextn key from is filtered at+ llama-model.cpp:2289 and its recurrent half is sized on n_layer() regardless+ (llama-memory-recurrent.cpp:29), so the ssm dims answer without the name.+ """+ b = _backend_from_gguf(+ "qwen39_hypothetical",+ {+ "block_count": 65,+ "nextn_predict_layers": 1,+ "attention.head_count_kv": 4,+ "attention.head_count": 24,+ "embedding_length": 5120,+ "attention.key_length": 256,+ "attention.value_length": 256,+ "full_attention_interval": 4,+ "ssm.inner_size": 6144,+ "ssm.state_size": 128,+ "ssm.group_count": 16,+ "ssm.conv_kernel": 4,+ "context_length": 131072,+ },+ )++ assert b._target_kv_excludes_nextn() is True+ # 64 trunk blocks -> 16 attention layers + 48 recurrent.+ per_slot = 48 * ((4 - 1) * (6144 + 2 * 16 * 128) + 128 * 6144) * 4+ assert b._estimate_kv_cache_bytes(4096, "f16") == 16 * 4096 * 4 * (256 + 256) * 2 + per_slot+++def test_the_glm4_moe_regression_is_gone():+ """The concrete case: a shipped GLM-4.5-Air GGUF keeps its 47th layer.++ conversion/glm.py:116 writes block_count INCLUDING the nextn block and :154+ writes the key, so this is what a real file looks like.+ """+ with_head = _backend_from_gguf("glm4moe", {**_GQA_FIELDS, "nextn_predict_layers": 1})+ without = _backend_from_gguf("glm4moe", dict(_GQA_FIELDS))++ assert with_head._estimate_kv_cache_bytes(4096, "f16") == without._estimate_kv_cache_bytes(+ 4096, "f16"+ )+++def test_a_nextn_equal_to_block_count_does_not_collapse():+ """gemma4-assistant asserts n_layer_nextn == n_layer_all (gemma4-assistant.cpp:15).++ block_count - nextn is 0 there, and a max(1, ...) floor would price a 12-layer+ model as one layer. The arch gate keeps it out of the subtraction entirely.+ """+ b = _backend_from_gguf(+ "gemma4-assistant",+ {**_GQA_FIELDS, "block_count": 12, "nextn_predict_layers": 12},+ )++ assert b._target_kv_excludes_nextn() is False+ assert b._estimate_kv_cache_bytes(4096, "f16") == 12 * 4096 * 8 * (128 + 128) * 2+++# ───────────────────── old / unusual llama.cpp builds ─────────────────────+++def test_recurrent_state_is_independent_of_the_arch_gate():+ """llama_memory_recurrent sizes on n_layer() for EVERY arch.++ llama-memory-recurrent.cpp:29 takes hparams.n_layer(), which subtracts nextn+ unconditionally, so _mamba_recurrent_state_bytes must keep subtracting even+ where the attention half does not. Guards against a fix that over-corrects.+ """+ b = _backend_from_gguf(+ "qwen35",+ {+ "block_count": 65,+ "nextn_predict_layers": 1,+ "attention.head_count_kv": 4,+ "attention.head_count": 24,+ "embedding_length": 5120,+ "attention.key_length": 256,+ "attention.value_length": 256,+ "full_attention_interval": 4,+ "ssm.inner_size": 6144,+ "ssm.state_size": 128,+ "ssm.group_count": 16,+ "ssm.conv_kernel": 4,+ "context_length": 131072,+ },+ )++ # 48 recurrent blocks out of 64 trunk, not 49 out of 65.+ expected = 48 * ((4 - 1) * (6144 + 2 * 16 * 128) + 128 * 6144) * 4+ assert b._mamba_recurrent_state_bytes() == expected+++def test_the_status_field_stays_an_optional_string():+ """An already-installed client parses the new reason without a schema bump."""+ from models.inference import InferenceStatusResponse++ field = InferenceStatusResponse.model_fields["spec_fallback_reason"]+ assert field.default is None+ # Free-form string, so "mtp_partial_offload" needs no enum change anywhere.+ parsed = InferenceStatusResponse.model_validate({"spec_fallback_reason": "mtp_partial_offload"})+ assert parsed.spec_fallback_reason == "mtp_partial_offload"diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsxindex a406085ddd1..256832f8c9b 100644--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx@@ -426,6 +426,20 @@ function specFallbackMessage({switch (reason) {case "mla_mtp_disabled":return "MTP is disabled by default for this model architecture because it currently runs slower than standard decoding. Choose MTP in the model picker to force it.";+ case "mtp_partial_offload":+ // Not the default copy: this build does support MTP, so telling the user to+ // update llama.cpp would name the wrong cause and the wrong remedy. Says+ // what the placement IS rather than that the model could not fit: a Manual+ // layer count is a partial placement the user picked, on a card that may+ // have room for all of it, and there the useful remedy is more layers.+ //+ // Describes the placement MTP WOULD need, not the one that ends up running.+ // The partial verdict is priced with MTP's rollback reserve still in it, so+ // on the fit path llama.cpp can put every layer on the GPU once MTP is off+ // -- claiming "only part of this model is on the GPU" would then describe a+ // placement the load does not have and recommend one it already has. This+ // wording stays true both there and at a fixed partial layer count.+ return "With MTP on, part of this model would have to run on the CPU, where MTP's extra state costs more than the drafting wins back, so Auto turned it off for this load. Give the GPU room for every layer to get it back, or choose MTP in Settings to force it.";case "drafter_no_vram":// Not "without speculative decoding": the backend puts zero-VRAM ngram-mod// in the drafter's place where the build has it, so only the drafter is off.diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 2e8816d0767..f0444a50790 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -370,7 +370,11 @@ export interface InferenceStatusResponse {* shrink it (choose the drafter in Settings to force it);* "mla_mtp_disabled" -> an Auto-mode policy downgrade for MLA models* (GLM-5.2 et al.) whose llama.cpp MTP path is slower than no speculation- * (updating won't help; choose MTP in Settings to force it). Null otherwise.+ * (updating won't help; choose MTP in Settings to force it);+ * "mtp_partial_offload" -> an Auto-mode policy downgrade for an embedded+ * Hybrid Mamba MTP head on a partially offloaded placement, whose recurrent+ * rollback copies cost more layers than the drafting wins back (updating+ * won't help; choose MTP in Settings to force it). Null otherwise.*//*** Which drafter the resolution was about: "mtp", "dspark" or "dflash". Autodiff --git a/studio/frontend/tests/spec-fallback-partial-offload-copy.test.ts b/studio/frontend/tests/spec-fallback-partial-offload-copy.test.tsnew file mode 100644index 00000000000..d40ab1c4800--- /dev/null+++ b/studio/frontend/tests/spec-fallback-partial-offload-copy.test.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++// specFallbackMessage is a module-local helper inside a .tsx, which this runner+// cannot import (it strips types but does not transform JSX), so the file is read+// as source -- the same guard the other chat-settings-sheet tests use.+const settings = readFileSync(+ new URL("../src/features/chat/chat-settings-sheet.tsx", import.meta.url),+ "utf8",+);++test("the Hybrid Mamba partial-offload stand-down has its own notice", () => {+ const branch = settings.match(+ /case "mtp_partial_offload":[\s\S]*?return "([^"]+)";/,+ );+ assert.ok(branch, "specFallbackMessage has no mtp_partial_offload case");++ // Without a case it falls through to the default, which blames the installed+ // llama.cpp build and offers an update. Auto took this path on a build that+ // does support MTP, so both halves would be wrong; the remedy is to force it.+ const copy = branch[1];+ assert.doesNotMatch(copy, /llama\.cpp|update/i);+ assert.match(copy, /Settings/);++ // And it must not diagnose a failed fit. Manual mode reaches this with a+ // partial layer count the user picked, on a card that may hold the whole+ // model, where the useful remedy is more layers rather than forcing MTP.+ assert.doesNotMatch(copy, /not fit|cannot fit|doesn't fit|too (big|large)/i);++ // Nor may it assert the placement the model ENDS UP with. The partial verdict+ // is priced with MTP's rollback reserve included, so on the --fit path+ // llama.cpp can place every layer on the GPU once this branch turns MTP off;+ // an unconditional "only part of this model is on the GPU" would then be false+ // and would recommend the placement the load already has. Describe what MTP+ // would require instead.+ assert.doesNotMatch(+ copy,+ /(only|just) part of this model is on the gpu|part of this model is running on/i,+ );+ assert.match(copy, /with mtp|mtp('s)? (extra state|on)|would/i);+});