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: support separate-file MTP GGUF drafters (Gemma 4) (#6125)
oobabooga2b319e8d3a21
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 317c9c7f213..ead962aac79 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -23,7 +23,7 @@ import sysimport threadingimport timefrom pathlib import Path-from typing import Generator, Iterable, List, Optional+from typing import Callable, Generator, Iterable, List, Optionalimport httpx@@ -481,6 +481,45 @@ def _is_mtp_model_name(model_identifier: Optional[str], gguf_path: Optional[str]return False+def _is_companion_gguf_path(path: str) -> bool:+ """True for a non-main GGUF: vision mmproj or a separate MTP drafter+ (repo-root ``mtp-*.gguf`` or the ``MTP/`` subdir copies, Gemma 4).++ Mirrors hub.utils.gguf so variant resolution never picks a companion as+ the main model -- e.g. a Gemma ``Q8_0`` request must not resolve to the+ ``MTP/...-Q8_0-MTP.gguf`` drafter, which sorts ahead of the real weight.+ """+ p = path.lower()+ if not p.endswith(".gguf"):+ return False+ if "mmproj" in p:+ return True+ name = p.rsplit("/", 1)[-1]+ return name.startswith("mtp-") or "/mtp/" in f"/{p}"+++# Below this many B params, draft-mtp regresses vs spec-off (bench in+# _build_speculative_flags); auto mode drops MTP under it.+_MTP_MIN_SIZE_B = 3.0++# Context-fit VRAM budget: tighter than _GPU_PIN_VRAM_FRACTION (0.95) on+# purpose -- over-promising context OOMs at runtime (#5106).+_CTX_FIT_VRAM_FRACTION = 0.90++# Extra VRAM fraction reserved when MTP will engage: the draft model's+# weights, KV cache, and compute buffers live outside the main model's+# estimate. Applied to BOTH the ctx-fit budget and the GPU pin thresholds --+# tightening only the fit lets a load whose weights land between the two+# fractions pin without any room for the drafter.+_MTP_VRAM_RESERVE_FRAC = 0.05+++def _auto_mode_drops_mtp(req_mode: Optional[str], size_b: Optional[float]) -> bool:+ """Auto mode drops MTP below _MTP_MIN_SIZE_B (draft-mtp regresses there);+ forced mtp / mtp+ngram engage regardless of size."""+ return req_mode == "auto" and size_b is not None and size_b < _MTP_MIN_SIZE_B++def _extra_args_set_spec_type(extra_args: Optional[Iterable[str]]) -> bool:"""User passed --spec-type / --spec-default? llama-server takes one--spec-type (comma-separated to chain), so suppress auto-emit."""@@ -625,6 +664,9 @@ class LlamaCppBackend:self._model_identifier: Optional[str] = Noneself._gguf_path: Optional[str] = Noneself._hf_repo: Optional[str] = None+ # Separate MTP drafter launched with the current model; reload-dedup+ # key so a drafter that appears next to the weights forces a reload.+ self._mtp_draft_path: Optional[str] = Noneself._hf_variant: Optional[str] = Noneself._is_vision: bool = Falseself._healthy = False@@ -732,6 +774,14 @@ class LlamaCppBackend:def hf_variant(self) -> Optional[str]:return self._hf_variant+ @property+ def gguf_path(self) -> Optional[str]:+ return self._gguf_path++ @property+ def mtp_draft_path(self) -> Optional[str]:+ return self._mtp_draft_path+@propertydef extra_args(self) -> Optional[List[str]]:"""Extra llama-server flags from the last load (a copy). None =@@ -1484,13 +1534,16 @@ class LlamaCppBackend:@staticmethoddef _select_gpus(- model_size_bytes: int, gpus: list[tuple[int, int]]+ model_size_bytes: int,+ gpus: list[tuple[int, int]],+ usable_fraction: Optional[float] = None,) -> tuple[Optional[list[int]], bool]:"""Pick GPU(s) for a model from estimated VRAM and free memory.``model_size_bytes`` should include weights and estimated KV cache.- ``_GPU_PIN_VRAM_FRACTION`` provides headroom for compute buffers,- CUDA context, and other runtime overhead.+ ``usable_fraction`` (default ``_GPU_PIN_VRAM_FRACTION``) provides+ headroom for compute buffers, CUDA context, and other runtime+ overhead; callers lower it when MTP reserves VRAM for a draft model.Returns (gpu_indices, use_fit):- ([1], False) fits on 1 GPU at the headroom threshold@@ -1501,7 +1554,8 @@ class LlamaCppBackend:return None, Truemodel_size_mib = model_size_bytes / (1024 * 1024)- usable_fraction = LlamaCppBackend._GPU_PIN_VRAM_FRACTION+ if usable_fraction is None:+ usable_fraction = LlamaCppBackend._GPU_PIN_VRAM_FRACTION# Sort GPUs by free memory descendingranked = sorted(gpus, key = lambda g: g[1], reverse = True)@@ -1749,8 +1803,8 @@ class LlamaCppBackend:ctx_checkpoints = ctx_checkpoints,)- # MTP needs a tighter budget; drop from 0.90 to 0.85.- budget_frac = 0.85 if mtp_engaged else 0.90+ # MTP engaged: carve the drafter's reserve out of the fit budget.+ budget_frac = _CTX_FIT_VRAM_FRACTION - (_MTP_VRAM_RESERVE_FRAC if mtp_engaged else 0.0)budget_bytes = available_mib * 1024 * 1024 * budget_fracmodel_footprint = model_size_bytes@@ -1808,7 +1862,9 @@ class LlamaCppBackend:from huggingface_hub import get_paths_info, list_repo_filesfiles = list_repo_files(hf_repo, token = hf_token)- gguf_files = [f for f in files if f.endswith(".gguf") and "mmproj" not in f.lower()]+ gguf_files = [+ f for f in files if f.endswith(".gguf") and not _is_companion_gguf_path(f)+ ]if not gguf_files:return None@@ -2169,7 +2225,11 @@ class LlamaCppBackend:r"(?<![a-zA-Z0-9])" + re.escape(variant_lower) + r"(?![a-zA-Z0-9])")gguf_files = sorted(- f for f in files if f.endswith(".gguf") and boundary.search(f.lower())+ f+ for f in files+ if f.endswith(".gguf")+ and boundary.search(f.lower())+ and not _is_companion_gguf_path(f))if gguf_files:gguf_filename = gguf_files[0]@@ -2199,7 +2259,7 @@ class LlamaCppBackend:matches = sorted(p.relative_to(snap).as_posix()for p in snap.rglob("*.gguf")- if "mmproj" not in p.name.lower()+ if not _is_companion_gguf_path(p.relative_to(snap).as_posix())and boundary.search(p.relative_to(snap).as_posix().lower()))if not matches:@@ -2303,7 +2363,7 @@ class LlamaCppBackend:for f in all_gguf_filesif f.startswith(_prefix)and f != gguf_filename- and "mmproj" not in f.lower()+ and not _is_companion_gguf_path(f))else:gguf_extra_shards = []@@ -2357,69 +2417,121 @@ class LlamaCppBackend:logger.info(f"GGUF downloaded in {dl_elapsed:.1f}s: {local_path}")return local_path- def _download_mmproj(+ def _download_companion_gguf(self,*,hf_repo: str,- hf_token: Optional[str] = None,+ hf_token: Optional[str],+ pick: Callable[[list[str]], Optional[str]],+ label: str,) -> Optional[str]:- """Download the mmproj (vision projection) file from a GGUF repo.+ """Resolve and fetch a companion GGUF (mmproj / MTP drafter) by name.- Prefers mmproj-F16.gguf, else any mmproj*.gguf. Returns the local- path, or None if none exists.+ Tries the live repo file list, then the local HF cache snapshots+ (offline, same fallback as _download_gguf), then hf_hub_download.+ Runs WITHOUT self._lock (like _download_gguf); honors _cancel_event so+ an /unload between the main download and here skips the fetch."""-- def _pick_mmproj(candidates: list[str]) -> Optional[str]:- mmproj_files = sorted(- f- for f in candidates- if f.lower().endswith(".gguf") and "mmproj" in Path(f).name.lower()- )- if not mmproj_files:- return None- for f in mmproj_files:- if f.lower().endswith("-f16.gguf"):- return f- return mmproj_files[0]+ if self._cancel_event.is_set():+ return Nonetarget: Optional[str] = Nonetry:from huggingface_hub import list_repo_files- target = _pick_mmproj(list_repo_files(hf_repo, token = hf_token))+ target = pick(list_repo_files(hf_repo, token = hf_token))except Exception as e:- logger.debug(f"Could not list repo files for mmproj: {e}")+ logger.debug(f"Could not list repo files for {label}: {e}")- # Offline: resolve mmproj from the local HF cache snapshot, same as- # _download_gguf's offline fallback above.if target is None:try:from utils.models.model_config import _iter_hf_cache_snapshotsfor snap in _iter_hf_cache_snapshots(hf_repo):rel_files = [p.relative_to(snap).as_posix() for p in snap.rglob("*.gguf")]- target = _pick_mmproj(rel_files)+ target = pick(rel_files)if target is not None:- logger.info("Resolved mmproj %s from local HF cache", target)+ logger.info("Resolved %s %s from local HF cache", label, target)breakexcept Exception as e:- logger.debug(f"Offline cache lookup for mmproj failed: {e}")+ logger.debug(f"Offline cache lookup for {label} failed: {e}")- if target is None:+ if target is None or self._cancel_event.is_set():return Nonetry:from huggingface_hub import hf_hub_download-- logger.info(f"Downloading mmproj: {hf_repo}/{target}")- local_path = hf_hub_download(+ logger.info(f"Downloading {label}: {hf_repo}/{target}")+ return hf_hub_download(repo_id = hf_repo,filename = target,token = hf_token,)- return local_pathexcept Exception as e:- logger.warning(f"Could not download mmproj: {e}")+ logger.warning(f"Could not download {label}: {e}")return None+ def _download_mmproj(+ self,+ *,+ hf_repo: str,+ hf_token: Optional[str] = None,+ ) -> Optional[str]:+ """Download the mmproj (vision projection) file from a GGUF repo.++ Prefers mmproj-F16.gguf, else any mmproj*.gguf. Returns the local+ path, or None if none exists.+ """++ def _pick_mmproj(candidates: list[str]) -> Optional[str]:+ mmproj_files = sorted(+ f+ for f in candidates+ if f.lower().endswith(".gguf") and "mmproj" in Path(f).name.lower()+ )+ if not mmproj_files:+ return None+ for f in mmproj_files:+ if f.lower().endswith("-f16.gguf"):+ return f+ return mmproj_files[0]++ return self._download_companion_gguf(+ hf_repo = hf_repo,+ hf_token = hf_token,+ pick = _pick_mmproj,+ label = "mmproj",+ )++ def _download_mtp(+ self,+ *,+ hf_repo: str,+ hf_token: Optional[str] = None,+ ) -> Optional[str]:+ """Download the separate MTP drafter (speculative head) from a GGUF repo.++ Targets the repo-root ``mtp-*.gguf`` companion -- the Q8_0 drafter+ unsloth mirrors there for llama.cpp ``-hf`` auto-discovery (smallest,+ recommended for speculation). Repos that bake the MTP head into the+ main GGUF (e.g. Qwen) ship no such sibling and this returns None. The+ higher-precision copies under ``MTP/`` are for explicit selection and+ are intentionally skipped. Returns the local path, or None.+ """++ def _pick_mtp(candidates: list[str]) -> Optional[str]:+ mtp_files = sorted(+ f+ for f in candidates+ if f.lower().endswith(".gguf") and Path(f).name.lower().startswith("mtp-")+ )+ return mtp_files[0] if mtp_files else None++ return self._download_companion_gguf(+ hf_repo = hf_repo,+ hf_token = hf_token,+ pick = _pick_mtp,+ label = "MTP drafter",+ )+def _resolve_launch_mmproj_path(self, *, model_path: str, mmproj_path: Optional[str]) -> Optional[str]:@@ -2446,6 +2558,19 @@ class LlamaCppBackend:return str(mmproj)+ def _resolve_launch_mtp_path(self, *, mtp_draft_path: Optional[str]) -> Optional[str]:+ """Return mtp_draft_path iff it exists on disk, else None.++ No family check needed: the drafter is only ever auto-resolved from+ the same repo as the main GGUF (see _download_mtp).+ """+ if not mtp_draft_path:+ return None+ if not Path(mtp_draft_path).is_file():+ logger.warning(f"MTP drafter file not found: {mtp_draft_path}")+ return None+ return str(mtp_draft_path)+# ── Lifecycle ─────────────────────────────────────────────────# GGUF ``general.architecture`` values for diffusion / image models.@@ -2550,6 +2675,8 @@ class LlamaCppBackend:gguf_path: Optional[str] = None,# Vision projection (mmproj) for local vision modelsmmproj_path: Optional[str] = None,+ # Separate MTP drafter for local Gemma loads (HF loads auto-resolve it)+ mtp_draft_path: Optional[str] = None,# HF mode: let llama-server download via -hf "repo:quant"hf_repo: Optional[str] = None,hf_variant: Optional[str] = None,@@ -2582,6 +2709,7 @@ class LlamaCppBackend:# live server already satisfies this request.if self._already_in_target_state(gguf_path = gguf_path,+ mtp_draft_path = mtp_draft_path,model_identifier = model_identifier,hf_variant = hf_variant,n_ctx = n_ctx,@@ -2653,6 +2781,8 @@ class LlamaCppBackend:)# ── Phase 2: download (NO lock held, so cancel can proceed) ──+ # mtp_draft_path arrives set for local Gemma loads (detected+ # sibling); for -hf loads it's None here and resolved just below.# Scope HF_HUB_OFFLINE to the download block only when DNS is# dead; cleanup runs even on exception so a transient hiccup# can't quarantine future loads.@@ -2669,6 +2799,28 @@ class LlamaCppBackend:hf_repo = hf_repo,hf_token = hf_token,)+ # Auto-download the separate MTP drafter (e.g. Gemma) when+ # the requested spec mode can use it. Repos with the head+ # baked into the main GGUF (Qwen) have no mtp- sibling and+ # this no-ops. Skipped when the user disabled MTP, drives+ # --spec-type manually via extra_args, or in auto mode on a+ # sub-3B model (e.g. Gemma E2B) where the resolver drops+ # MTP anyway -- no point fetching a drafter it never uses.+ # Forced mtp / mtp+ngram still download (user override).+ _spec_canon = _canonicalize_spec_mode(speculative_type) or "auto"+ _auto_drops_mtp = _auto_mode_drops_mtp(+ _spec_canon, _extract_model_size_b(model_identifier)+ )+ if (+ not mtp_draft_path+ and _spec_canon in ("auto", "mtp", "mtp+ngram")+ and not _auto_drops_mtp+ and not _extra_args_set_spec_type(extra_args)+ ):+ mtp_draft_path = self._download_mtp(+ hf_repo = hf_repo,+ hf_token = hf_token,+ )elif gguf_path:if not Path(gguf_path).is_file():raise FileNotFoundError(f"GGUF file not found: {gguf_path}")@@ -2736,12 +2888,15 @@ class LlamaCppBackend:# Will MTP engage on this load? If so, auto-fit reserves# extra VRAM for the draft model. Mirrors# _build_speculative_flags' resolver: forced mtp / mtp+ngram- # always engage; auto only on an MTP GGUF >= 3B; ngram /- # ngram-simple / off never engage MTP.+ # always engage; auto only on an MTP model >= 3B; ngram /+ # ngram-simple / off never engage MTP. A separate drafter+ # (Gemma) counts as an MTP model just like a baked-in head._mtp_canonical = _canonicalize_spec_mode(speculative_type)_mtp_effective = _mtp_canonical or "auto"_mtp_size_for_fit = _extract_model_size_b(model_identifier)- _mtp_sub_3b_for_fit = _mtp_size_for_fit is not None and _mtp_size_for_fit < 3.0+ _mtp_sub_3b_for_fit = (+ _mtp_size_for_fit is not None and _mtp_size_for_fit < _MTP_MIN_SIZE_B+ )_mtp_will_engage = bool(not _extra_args_set_spec_type(extra_args)and (@@ -2751,6 +2906,7 @@ class LlamaCppBackend:and (bool(self._nextn_predict_layers)or _is_mtp_model_name(model_identifier, model_path)+ or bool(mtp_draft_path))and not _mtp_sub_3b_for_fit)@@ -2766,6 +2922,11 @@ class LlamaCppBackend:# context, since multi-GPU is slower.gpu_indices, use_fit = None, Trueexplicit_ctx = requested_ctx > 0+ # MTP draft model lives outside the main estimates; carve+ # its reserve out of every fit budget and pin threshold so+ # a load can't pin into the drafter's headroom.+ _mtp_reserve = _MTP_VRAM_RESERVE_FRAC if _mtp_will_engage else 0.0+ _pin_fraction = self._GPU_PIN_VRAM_FRACTION - _mtp_reserveif gpus and self._can_estimate_kv() and effective_ctx > 0:# Largest hardware-aware cap from the native context@@ -2790,7 +2951,7 @@ class LlamaCppBackend:capped, cache_type_kv, n_parallel = n_parallel)total_mib = (model_size + kv) / (1024 * 1024)- if total_mib <= pool_mib * 0.90:+ if total_mib <= pool_mib * (_CTX_FIT_VRAM_FRACTION - _mtp_reserve):best_cap = max(best_cap, capped)if best_cap > 0:max_available_ctx = best_cap@@ -2807,13 +2968,15 @@ class LlamaCppBackend:requested_total = model_size + self._estimate_kv_cache_bytes(effective_ctx, cache_type_kv, n_parallel = n_parallel)- gpu_indices, use_fit = self._select_gpus(requested_total, gpus)+ gpu_indices, use_fit = self._select_gpus(+ requested_total, gpus, usable_fraction = _pin_fraction+ )# No silent shrink: effective_ctx stays == requested_ctx.else:# Auto context: prefer fewer GPUs, cap to fit. Same# headroom threshold as _select_gpus (#5106).ranked = sorted(gpus, key = lambda g: g[1], reverse = True)- pin_fraction = self._GPU_PIN_VRAM_FRACTION+ pin_fraction = _pin_fractionfor n_gpus in range(1, len(ranked) + 1):subset = ranked[:n_gpus]pool_mib = sum(free for _, free in subset)@@ -2861,7 +3024,9 @@ class LlamaCppBackend:"Falling back to file-size-only GPU selection",model_size_gb = round(model_size / (1024**3), 2),)- gpu_indices, use_fit = self._select_gpus(model_size, gpus)+ gpu_indices, use_fit = self._select_gpus(+ model_size, gpus, usable_fraction = _pin_fraction+ )if use_fit and not explicit_ctx:# Weights don't fit on any subset; default UI to 4096# so the slider isn't on an unusable native ctx.@@ -2978,6 +3143,9 @@ class LlamaCppBackend:# Speculative decoding. See _build_speculative_flags for the# mode resolution, benchmarks, and llama.cpp references.+ launch_mtp_draft_path = self._resolve_launch_mtp_path(+ mtp_draft_path = mtp_draft_path,+ )spec_flags = self._build_speculative_flags(speculative_type = speculative_type,spec_draft_n_max = spec_draft_n_max,@@ -2986,7 +3154,11 @@ class LlamaCppBackend:model_path = model_path,gpus = bool(gpus),binary = binary,+ mtp_draft_path = launch_mtp_draft_path,)+ # Remember where the spec block sits so a drafter-load failure+ # can be retried with these flags swapped out (see below).+ _spec_start = len(cmd)cmd.extend(spec_flags)# Apply custom chat template override if provided.@@ -3184,84 +3356,87 @@ class LlamaCppBackend:# retry once with --fit off before declaring the load failed.# Never retry when fit was requested (use_fit) or the caller# passed an explicit fit flag via extra args.- _fit_retry_allowed = self._fit_off_retry_eligible(cmd, use_fit)- for _spawn_attempt in (0, 1):- # Defensive kill: drop an orphan Popen a concurrent load may- # have stored before we overwrite the reference (#5161).- # Also reaps the crashed first attempt on the retry pass.- self._kill_process()-- self._stdout_lines = []- # Tee llama-server output to a dedicated log file so a- # post-mortem has the full trail even when the parent only- # kept the last 50 lines. Path is under the studio home.- self._llama_log_fh = None- try:- log_dir = _swa_cache_path().parent / "logs" / "llama-server"- log_dir.mkdir(parents = True, exist_ok = True)- # Include the attempt index: the --fit off retry can- # respawn within the same epoch second, and reusing the- # name would truncate the crash log the retry warning- # just pointed the user at.- self._llama_log_path = log_dir / (- f"llama-{int(time.time())}-port-{self._port}"- f"-try{_spawn_attempt}.log"- )- self._llama_log_fh = open(- self._llama_log_path,- "w",- encoding = "utf-8",- buffering = 1,+ def _spawn_and_wait(run_cmd, *, label = ""):+ """Start llama-server with run_cmd and wait for health.++ Retries once with --fit off when the first attempt+ crashes during startup and run_cmd is eligible (see+ _fit_off_retry_eligible).+ """+ _fit_retry_allowed = self._fit_off_retry_eligible(run_cmd, use_fit)+ for _spawn_attempt in (0, 1):+ # Defensive kill: drop an orphan Popen a concurrent load may+ # have stored before we overwrite the reference (#5161).+ # Also reaps the crashed first attempt on the retry pass.+ self._kill_process()++ self._stdout_lines = []+ # Tee llama-server output to a dedicated log file so a+ # post-mortem has the full trail even when the parent only+ # kept the last 50 lines. Path is under the studio home.+ # ``label`` (MTP fallback) and the attempt index (--fit+ # off retry) keep a respawn within the same epoch second+ # from truncating the crash log a retry warning just+ # pointed the user at.+ self._llama_log_fh = None+ try:+ log_dir = _swa_cache_path().parent / "logs" / "llama-server"+ log_dir.mkdir(parents = True, exist_ok = True)+ self._llama_log_path = log_dir / (+ f"llama-{int(time.time())}{label}-port-{self._port}"+ f"-try{_spawn_attempt}.log"+ )+ self._llama_log_fh = open(+ self._llama_log_path,+ "w",+ encoding = "utf-8",+ buffering = 1,+ )+ logger.info(f"llama-server stdout/stderr -> {self._llama_log_path}")+ except OSError as e:+ # Best-effort; never block the load on logging.+ logger.debug(f"Could not open llama-server log file: {e}")+ self._llama_log_path = None+ self._process = subprocess.Popen(+ run_cmd,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ env = env,+ **_windows_hidden_subprocess_kwargs(),)- logger.info(f"llama-server stdout/stderr -> {self._llama_log_path}")- except OSError as e:- # Best-effort; never block the load on logging.- logger.debug(f"Could not open llama-server log file: {e}")- self._llama_log_path = None- self._process = subprocess.Popen(- cmd,- stdout = subprocess.PIPE,- stderr = subprocess.STDOUT,- text = True,- env = env,- **_windows_hidden_subprocess_kwargs(),- )- # Background thread to drain stdout (prevents pipe deadlock)- self._stdout_thread = threading.Thread(- target = self._drain_stdout, daemon = True, name = "llama-stdout"- )- self._stdout_thread.start()- if self._wait_for_health(timeout = 600.0):- break- _startup_crashed = (- self._process.poll() is not None and self._process.returncode != 0- )- if _spawn_attempt == 0 and _fit_retry_allowed and _startup_crashed:- logger.warning(- "llama-server crashed during startup (exit code %s) "- "with the default memory-fit step enabled; Studio "- "already verified the model fits, retrying once "- "with --fit off. Crash log: %s",- self._process.returncode,- self._llama_log_path,+ # Background thread to drain stdout (prevents pipe deadlock)+ self._stdout_thread = threading.Thread(+ target = self._drain_stdout, daemon = True, name = "llama-stdout")- cmd = [*cmd, "--fit", "off"]- continue- self._kill_process()- raise RuntimeError(- self._classify_llama_start_failure(- "\n".join(self._stdout_lines[-50:]),- gguf_path,- model_identifier,+ self._stdout_thread.start()+ if self._wait_for_health(timeout = 600.0):+ return True+ _startup_crashed = (+ self._process.poll() is not None and self._process.returncode != 0)- )+ if _spawn_attempt == 0 and _fit_retry_allowed and _startup_crashed:+ logger.warning(+ "llama-server crashed during startup (exit code %s) "+ "with the default memory-fit step enabled; Studio "+ "already verified the model fits, retrying once "+ "with --fit off. Crash log: %s",+ self._process.returncode,+ self._llama_log_path,+ )+ run_cmd = [*run_cmd, "--fit", "off"]+ continue+ return False# Store the resolved on-disk path, not the caller's kwarg: in# HF mode gguf_path is None and ``model_path`` is what- # llama-server mmap's, which downstream consumers need.+ # llama-server mmap's, which downstream consumers need. Must be+ # set BEFORE the spawn: load_progress() reads _gguf_path for+ # the mmap progress total while the health wait runs.self._gguf_path = model_pathself._hf_repo = hf_repo+ self._mtp_draft_path = launch_mtp_draft_path# For local GGUF files, extract variant from filename if absentif hf_variant:self._hf_variant = hf_variant@@ -3285,7 +3460,76 @@ class LlamaCppBackend:max_available_ctx if max_available_ctx > 0 else self._effective_context_length)- # Health was confirmed inside the spawn/retry loop above.+ healthy = _spawn_and_wait(cmd)+ # A separate MTP drafter (e.g. Gemma's gemma4-assistant head)+ # can fail to load on a llama-server that advertises the+ # --spec-type draft-mtp flag but predates the drafter's+ # architecture -- and that aborts the whole server. Retry once+ # with the whole spec block replaced by --spec-default so the+ # main model still loads (without speculation). Replacing the+ # slice -- rather than re-resolving with mtp_draft_path=None --+ # is what guarantees MTP is off even for a forced mtp / mtp+ngram+ # request (which would otherwise re-emit --spec-type draft-mtp).+ # _requested_spec_mode (the user's choice) is left intact so a+ # duplicate /load doesn't thrash a reload.+ # Gate on the flag actually being in the command, not on the+ # drafter merely existing on disk: local loads pass the path+ # even in off/ngram modes (and auto drops MTP sub-3B), where a+ # retry would blame the drafter for an unrelated failure and+ # override the user's spec choice. The cancel check keeps an+ # /unload that killed the first attempt from respawning.+ if (+ not healthy+ and "--model-draft" in spec_flags+ and not self._cancel_event.is_set()+ ):+ # Only blame the binary's age when the output shows the+ # drafter actually failing (unknown arch / draft load);+ # an unrelated crash (e.g. OOM) gets a neutral message.+ # Substrings are upstream llama.cpp messages+ # (llama_model_load / srv load_model [spec]); if they+ # drift, only the wording degrades -- the retry fires+ # either way.+ _attempt_output = "\n".join(self._stdout_lines)+ if (+ "unknown model architecture" in _attempt_output+ or "failed to measure draft model memory" in _attempt_output+ ):+ _retry_reason = (+ "the prebuilt may predate its architecture; retrying "+ "without speculative decoding -- run "+ "`unsloth studio update` for MTP"+ )+ else:+ _retry_reason = (+ "retrying without speculative decoding in case the "+ "drafter is the cause"+ )+ logger.warning(+ "llama-server failed to start with MTP drafter %s; %s.",+ Path(launch_mtp_draft_path).name,+ _retry_reason,+ )+ self._kill_process()+ fallback_cmd = (+ cmd[:_spec_start]+ + ["--spec-default"]+ + cmd[_spec_start + len(spec_flags) :]+ )+ healthy = _spawn_and_wait(fallback_cmd, label = "-retry")+ if healthy:+ self._speculative_type = "default"++ if not healthy:+ self._kill_process()+ raise RuntimeError(+ self._classify_llama_start_failure(+ "\n".join(self._stdout_lines[-50:]),+ gguf_path,+ self._model_identifier,+ )+ )+self._healthy = True# Commit caller intent only after _healthy=True so a failed start@@ -3373,6 +3617,7 @@ class LlamaCppBackend:model_path: Optional[str],gpus: bool,binary: Optional[str],+ mtp_draft_path: Optional[str] = None,) -> List[str]:"""Return the llama-server flag list for the requested spec mode.@@ -3417,12 +3662,16 @@ class LlamaCppBackend:# Canonical UI-facing requested mode (legacy values mapped via# _canonicalize_spec_mode).canonical_mode = _canonicalize_spec_mode(speculative_type)- is_mtp_model = bool(self._nextn_predict_layers) or (- _is_mtp_model_name(model_identifier, model_path)+ # MTP signals: head baked into the main GGUF (Qwen, via metadata or+ # name), or a separate drafter resolved from the repo (Gemma).+ is_mtp_model = (+ bool(self._nextn_predict_layers)+ or _is_mtp_model_name(model_identifier, model_path)+ or bool(mtp_draft_path))user_owns_spec_type = _extra_args_set_spec_type(extra_args)_mtp_size_b = _extract_model_size_b(model_identifier)- _mtp_too_small = _mtp_size_b is not None and _mtp_size_b < 3.0+ _mtp_too_small = _mtp_size_b is not None and _mtp_size_b < _MTP_MIN_SIZE_Bif user_owns_spec_type:# User --spec-type wins outright; suppress auto-emit to avoid a@@ -3457,6 +3706,12 @@ class LlamaCppBackend:return Falsedraft_n_max = _resolved_draft_n_max()n_max_flag = caps.get("spec_draft_n_max_flag") or "--spec-draft-n-max"+ # Separate-file drafter (Gemma): point llama-server at it. Baked-in+ # heads (Qwen) pass no path -- llama-server reads them from the+ # main GGUF.+ if mtp_draft_path:+ flags.extend(["--model-draft", mtp_draft_path])+ logger.info(f"Using separate MTP drafter: {mtp_draft_path}")if chain_ngram:ngram_knobs = _build_ngram_mod_flags(caps)if ngram_knobs:@@ -3589,6 +3844,7 @@ class LlamaCppBackend:is_vision: bool,gguf_path: Optional[str] = None,spec_draft_n_max: Optional[int] = None,+ mtp_draft_path: Optional[str] = None,) -> bool:"""True iff the live server already satisfies these load kwargs.@@ -3647,6 +3903,22 @@ class LlamaCppBackend:if (self._chat_template_override or None) != (chat_template_override or None):return False+ # A drafter appearing/disappearing next to a local GGUF changes the+ # launch command (--model-draft) when the mode can use it; without+ # this, adding mtp-*.gguf after a load is deduped away and MTP can't+ # engage short of an unload. HF loads resolve the drafter inside+ # load_model (gguf_path is None here), so only local paths compare;+ # the route-level probe covers HF cache repos. No sub-3B gate: both+ # sides come from the same config detection, so a sub-3B mismatch+ # only happens when a drafter genuinely appeared (one benign reload,+ # then the stored path converges).+ if (+ gguf_path is not None+ and req_mode in ("auto", "mtp", "mtp+ngram")+ and (mtp_draft_path or None) != (self._mtp_draft_path or None)+ ):+ return False+# extra_args=None means "no opinion" (inherit handled at the route# layer); only an explicit list forces equality.if extra_args is not None:@@ -3688,6 +3960,7 @@ class LlamaCppBackend:self._model_identifier = Noneself._gguf_path = Noneself._hf_repo = None+ self._mtp_draft_path = Noneself._hf_variant = Noneself._is_vision = Falseself._is_audio = Falsediff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex 66c7f10d425..1862c9c5de2 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -132,7 +132,13 @@ _SPEC_FLAGS: frozenset[str] = frozenset("--spec-ngram-size","--draft-min","--draft-max",- # MTP path (llama.cpp #22673).+ # MTP path (llama.cpp #22673). --model-draft and aliases are+ # Studio-managed since the separate-drafter support (Gemma 4): an+ # inherited copy must not last-wins-override the auto-detected+ # drafter. Explicit extras for the current load are never stripped.+ "--model-draft",+ "-md",+ "--spec-draft-model","--spec-draft-n-max","--spec-draft-n-min","--spec-draft-p-min",diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.pyindex 688d324a606..f381bffe9cd 100644--- a/studio/backend/hub/services/models/common.py+++ b/studio/backend/hub/services/models/common.py@@ -21,6 +21,7 @@ from hub.utils.gguf import (extract_quant_label,is_gguf_filename as _is_gguf_filename,is_mmproj_filename as _is_mmproj_filename,+ is_mtp_drafter_path as _is_mtp_drafter_path,)from hub.utils.paths import is_valid_repo_id as _is_valid_repo_id@@ -71,7 +72,7 @@ def _is_model_directory(d: Path) -> bool:if suffix == ".safetensors":return Trueif suffix == ".gguf":- return "mmproj" not in f.name.lower()+ return "mmproj" not in f.name.lower() and not _is_mtp_drafter_path(f.name)if suffix == ".bin":name = f.name.lower()return (@@ -276,7 +277,9 @@ def _classify_non_gguf_model_format(def _is_main_gguf_filename(name: str) -> bool:- return _is_gguf_filename(name) and not _is_mmproj_filename(name)+ return (+ _is_gguf_filename(name) and not _is_mmproj_filename(name) and not _is_mtp_drafter_path(name)+ )def _iter_gguf_paths(root: Path):diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex d4aed0d59f3..ecc9f8426d0 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -32,6 +32,7 @@ from hub.services.models.common import (_is_gguf_filename,_is_main_gguf_filename,_is_mmproj_filename,+ _is_mtp_drafter_path,)logger = get_logger(__name__)@@ -139,7 +140,10 @@ def _delete_gguf_variant_from_repos(if matched and not sibling_active and not _has_remaining_main_gguf(target_repo):companion_matches = _repo_file_matches(target_repo,- lambda name: _is_gguf_filename(name) and _is_mmproj_filename(name),+ # Companions: mmproj and the MTP drafter -- downloaded with+ # every variant, so the last variant's delete reclaims them.+ lambda name: _is_gguf_filename(name)+ and (_is_mmproj_filename(name) or _is_mtp_drafter_path(name)),)for snap, _blob, name in companion_matches:try:diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.pyindex efe6bdf6c4a..0b4671c6d23 100644--- a/studio/backend/hub/services/models/gguf_variants.py+++ b/studio/backend/hub/services/models/gguf_variants.py@@ -38,6 +38,7 @@ from hub.utils.paths import ()from hub.services.models.common import (_is_mmproj_filename,+ _is_mtp_drafter_path,_iter_gguf_paths,)from hub.utils.gguf_plan import (@@ -479,7 +480,7 @@ async def get_gguf_variants_response(continuekey = rel.lower()by_filename[key] = max(by_filename.get(key, 0), size)- if _is_mmproj_filename(f.name):+ if _is_mmproj_filename(f.name) or _is_mtp_drafter_path(rel):continueq = extract_quant_label(rel).lower()by_quant[q] = by_quant.get(q, 0) + size@@ -593,7 +594,11 @@ async def get_gguf_variants_response(requirement = requirements_by_quant.get(variant.quant.lower())if requirement is None:continue- if requirement.mmproj_hashes & incomplete_hashes and _filenames_cached(+ # companion_hashes adds the MTP drafter (mmproj_hashes covers+ # every mmproj precision in the repo, not just the planned one).+ if (+ (requirement.mmproj_hashes | requirement.companion_hashes) & incomplete_hashes+ ) and _filenames_cached(requirement.main_filenames,requirement.main_size_bytes,):diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex 4bd1961c338..c9b3ce97e30 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -83,6 +83,28 @@ def is_mmproj_filename(filename: str) -> bool:return "mmproj" in filename.lower()+def is_mtp_drafter_path(path: str) -> bool:+ """True for a separate-file MTP drafter (speculative head), a companion to+ the main model rather than a selectable quant.++ Covers the repo-root ``mtp-*.gguf`` (the Q8_0 copy unsloth ships for+ llama.cpp ``-hf`` auto-discovery) and the ``MTP/`` subdir copies (Gemma 4).+ Repos that bake the head into the main GGUF (Qwen) have no such file, so+ this is False for them. Must be excluded from main-model selection+ everywhere mmproj is.++ CANONICAL COPY. Layering keeps two mirrors that must change in lockstep:+ utils/models/model_config.py ``_is_mtp_drafter`` (utils cannot import+ hub) and core/inference/llama_cpp.py ``_is_companion_gguf_path`` (core+ avoids hub imports; bundles the mmproj check).+ """+ p = path.lower()+ if not p.endswith(".gguf"):+ return False+ name = p.rsplit("/", 1)[-1]+ return name.startswith("mtp-") or "/mtp/" in f"/{p}"++def is_gguf_filename(filename: str) -> bool:return filename.lower().endswith(".gguf")@@ -119,7 +141,9 @@ def iter_gguf_files(directory: Path, recursive: bool = False):def pick_best_gguf(filenames: list[str]) -> Optional[str]:gguf_files = [- name for name in filenames if is_gguf_filename(name) and not is_mmproj_filename(name)+ name+ for name in filenames+ if is_gguf_filename(name) and not is_mmproj_filename(name) and not is_mtp_drafter_path(name)]if not gguf_files:return None@@ -270,6 +294,12 @@ def list_partial_gguf_variants_from_state(for expected in manifest.expected_files:if not is_gguf_filename(expected.path):continue+ if is_mtp_drafter_path(expected.path):+ # Downloaded with every variant (like mmproj) but not a+ # selectable quant; count it so the shown download size+ # matches what is fetched.+ companion_bytes += max(0, int(expected.size or 0))+ continueif is_mmproj_filename(expected.path):has_vision = Truecompanion_bytes += max(0, int(expected.size or 0))@@ -336,6 +366,8 @@ def list_gguf_variants(filename = getattr(sibling, "rfilename", None)if not isinstance(filename, str) or not is_gguf_filename(filename):continue+ if is_mtp_drafter_path(filename):+ continueif is_mmproj_filename(filename):has_vision = Truecontinue@@ -389,6 +421,8 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], booexcept OSError:size = 0rel = file.relative_to(root).as_posix()+ if is_mtp_drafter_path(rel):+ continuequant = extract_quant_label(rel)quant_totals[quant] = quant_totals.get(quant, 0) + sizequant_first_file.setdefault(quant, rel)diff --git a/studio/backend/hub/utils/gguf_plan.py b/studio/backend/hub/utils/gguf_plan.pyindex 03ec847f4c6..60782fa1092 100644--- a/studio/backend/hub/utils/gguf_plan.py+++ b/studio/backend/hub/utils/gguf_plan.py@@ -7,7 +7,12 @@ from dataclasses import dataclassfrom typing import Optional, Sequencefrom hub.utils.download_manifest import ExpectedFile-from hub.utils.gguf import extract_quant_label, is_gguf_filename, is_mmproj_filename+from hub.utils.gguf import (+ extract_quant_label,+ is_gguf_filename,+ is_mmproj_filename,+ is_mtp_drafter_path,+)@dataclass(frozen = True)@@ -53,24 +58,30 @@ def expected_file_from_sibling(sibling) -> Optional[ExpectedFile]:def is_companion_gguf_path(path: str) -> bool:- return is_gguf_filename(path) and is_mmproj_filename(path)+ """Companion (non-main) GGUF downloaded alongside a variant: the vision+ mmproj or the separate MTP drafter (Gemma 4)."""+ return is_gguf_filename(path) and (is_mmproj_filename(path) or is_mtp_drafter_path(path))def is_main_gguf_variant_path(path: str, variant: str) -> bool:return (is_gguf_filename(path)and not is_mmproj_filename(path)+ and not is_mtp_drafter_path(path)and extract_quant_label(path).lower() == variant.lower())+def _gguf_rfilename(sibling) -> Optional[str]:+ """The sibling's rfilename when it is a GGUF, else None."""+ name = getattr(sibling, "rfilename", None)+ if isinstance(name, str) and is_gguf_filename(name):+ return name+ return None++def mmproj_siblings(siblings: Sequence) -> list:- return [- s- for s in siblings- if isinstance(getattr(s, "rfilename", None), str)- and is_companion_gguf_path(getattr(s, "rfilename"))- ]+ return [s for s in siblings if (name := _gguf_rfilename(s)) and is_mmproj_filename(name)]def preferred_mmproj_sibling(siblings: Sequence) -> Optional[object]:@@ -83,6 +94,25 @@ def preferred_mmproj_sibling(siblings: Sequence) -> Optional[object]:)+def preferred_mtp_sibling(siblings: Sequence) -> Optional[object]:+ """The separate MTP drafter to fetch with every variant: the repo-root+ ``mtp-*.gguf`` copy unsloth ships for llama.cpp ``-hf`` auto-discovery+ (Gemma 4). Same pick as the loader's drafter resolution (``mtp-`` basename+ prefix, first in sort order) so download and load resolve the same file;+ the higher-precision ``MTP/`` subdir copies are for explicit selection and+ are not auto-fetched. None for repos with the head baked into the main+ GGUF (Qwen)."""+ candidates = sorted(+ (+ s+ for s in siblings+ if (name := _gguf_rfilename(s)) and name.lower().rsplit("/", 1)[-1].startswith("mtp-")+ ),+ key = lambda s: getattr(s, "rfilename"),+ )+ return candidates[0] if candidates else None++def build_gguf_variant_plans(siblings: Sequence) -> dict[str, GgufVariantPlan]:main: dict[str, list] = {}all_mmproj = mmproj_siblings(siblings)@@ -94,12 +124,20 @@ def build_gguf_variant_plans(siblings: Sequence) -> dict[str, GgufVariantPlan]:all_mmproj_hashes = frozenset(h for h in (sibling_sha256(s) for s in all_mmproj) if h)companion = preferred_mmproj_sibling(siblings)companion_expected = expected_file_from_sibling(companion) if companion is not None else None+ mtp_sibling = preferred_mtp_sibling(siblings)+ mtp_expected = expected_file_from_sibling(mtp_sibling) if mtp_sibling is not None else None+ companions_expected = tuple(+ file for file in (companion_expected, mtp_expected) if file is not None+ )for sibling in siblings:- name = getattr(sibling, "rfilename", None)- if not isinstance(name, str) or not is_gguf_filename(name):+ name = _gguf_rfilename(sibling)+ if name is None:continue- if is_mmproj_filename(name):+ # Companions are folded into every plan below; keep them out of the+ # quant grouping so a drafter never lands in a variant's main files+ # (the root mtp-*.gguf carries a quant label, e.g. Q8_0).+ if is_mmproj_filename(name) or is_mtp_drafter_path(name):continuequant = extract_quant_label(name).lower()main.setdefault(quant, []).append(sibling)@@ -111,11 +149,7 @@ def build_gguf_variant_plans(siblings: Sequence) -> dict[str, GgufVariantPlan]:for sibling in target_main_siblingsif (file := expected_file_from_sibling(sibling)) is not None)- expected_files = (- (*main_expected, companion_expected)- if companion_expected is not None- else main_expected- )+ expected_files = (*main_expected, *companions_expected)plans[quant] = plan_from_expected_files(quant,expected_files,@@ -135,6 +169,9 @@ def plan_from_expected_files(expected = tuple(expected_files)main_files = tuple(file for file in expected if is_main_gguf_variant_path(file.path, variant))companion_files = tuple(file for file in expected if is_companion_gguf_path(file.path))+ # Manifest-resume fallback for the mmproj fields below: companion_files+ # also holds the MTP drafter, so keep an mmproj-only view.+ mmproj_files = tuple(file for file in companion_files if is_mmproj_filename(file.path))main_hashes = frozenset(file.sha256 for file in main_files if file.sha256)companion_hashes = frozenset(file.sha256 for file in companion_files if file.sha256)required_hashes = frozenset(file.sha256 for file in expected if file.sha256)@@ -149,9 +186,13 @@ def plan_from_expected_files(mmproj_filenames = (all_mmproj_filenamesif all_mmproj_filenames is not None- else frozenset(file.path for file in companion_files)+ else frozenset(file.path for file in mmproj_files)+ ),+ mmproj_hashes = (+ all_mmproj_hashes+ if all_mmproj_hashes is not None+ else frozenset(file.sha256 for file in mmproj_files if file.sha256)),- mmproj_hashes = (all_mmproj_hashes if all_mmproj_hashes is not None else companion_hashes),expected_files = expected,main_size_bytes = main_size,download_size_bytes = download_size,diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.pyindex a7281ad8b38..fe3aadfd38d 100644--- a/studio/backend/hub/utils/inventory_scan.py+++ b/studio/backend/hub/utils/inventory_scan.py@@ -25,7 +25,12 @@ from loggers import get_loggerlogger = get_logger(__name__)-from hub.utils.gguf import extract_quant_label, is_gguf_filename, is_mmproj_filename+from hub.utils.gguf import (+ extract_quant_label,+ is_gguf_filename,+ is_mmproj_filename,+ is_mtp_drafter_path,+)from hub.utils.state_dir import RepoTypefrom hub.utils.hf_cache_state import (@@ -336,7 +341,7 @@ def _completed_gguf_variants(snapshot_dir: Optional[Path]) -> set[str]:except OSError:continuerel = path.relative_to(snapshot_dir).as_posix()- if not is_gguf_filename(rel) or is_mmproj_filename(rel):+ if not is_gguf_filename(rel) or is_mmproj_filename(rel) or is_mtp_drafter_path(rel):continuequant = extract_quant_label(rel)split = _GGUF_SPLIT_RE.search(path.name)diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 9c12f8faac4..96f24887bd8 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -72,7 +72,7 @@ class LoadRequest(BaseModel):"ngram-mod+draft-mtp chain on both platforms), 'off' (disabled). ""Legacy values 'default' (-> auto), 'draft-mtp' (-> mtp), ""'ngram-mod' (-> ngram), and 'ngram-simple' (kept as-is) are "- "still accepted. Ignored for non-GGUF and vision models."+ "still accepted. Ignored for non-GGUF models."),)spec_draft_n_max: Optional[int] = Field(diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 9f0bb43c9a8..418206e9385 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -417,7 +417,9 @@ try:LlamaCppBackend,_DEFAULT_MAX_TOKENS_FLOOR,_DEFAULT_T_MAX_PREDICT_MS,+ _auto_mode_drops_mtp,_canonicalize_spec_mode,+ _extra_args_set_spec_type,_hf_offline_if_dns_dead,detect_reasoning_flags,)@@ -427,7 +429,11 @@ try:)from utils.models import ModelConfigfrom utils.inference import load_inference_config- from utils.models.model_config import load_model_defaults+ from utils.models.model_config import (+ detect_mtp_file,+ extract_model_size_b,+ load_model_defaults,+ )from utils.native_path_leases import (NativePathLeaseError,display_label_for_native_path,@@ -444,7 +450,9 @@ except ImportError:LlamaCppBackend,_DEFAULT_MAX_TOKENS_FLOOR,_DEFAULT_T_MAX_PREDICT_MS,+ _auto_mode_drops_mtp,_canonicalize_spec_mode,+ _extra_args_set_spec_type,_hf_offline_if_dns_dead,detect_reasoning_flags,)@@ -454,7 +462,11 @@ except ImportError:)from utils.models import ModelConfigfrom utils.inference import load_inference_config- from utils.models.model_config import load_model_defaults+ from utils.models.model_config import (+ detect_mtp_file,+ extract_model_size_b,+ load_model_defaults,+ )from utils.native_path_leases import (NativePathLeaseError,display_label_for_native_path,@@ -927,35 +939,42 @@ def _strip_tool_xml_for_display(text: str, *, auto_heal_tool_calls: bool) -> strlogger = get_logger(__name__)-def _validate_native_mmproj_companion(mmproj_path: str | None, gguf_path: str | None) -> None:- if not mmproj_path or not gguf_path:+def _validate_native_gguf_companion(+ companion_path: str | None, gguf_path: str | None, label: str+) -> None:+ """Reject a companion GGUF (mmproj / MTP drafter) that a native-lease load+ would otherwise hand to llama-server: must be a regular file (no symlink+ escaping the leased directory) living next to the selected GGUF."""+ if not companion_path or not gguf_path:returnimport stat as _stat_module- mm = Path(mmproj_path)+ companion = Path(companion_path)gguf = Path(gguf_path)try:- mm_lstat = os.lstat(mm)+ companion_lstat = os.lstat(companion)except OSError as exc:raise HTTPException(status_code = 400,- detail = "Native vision companion is no longer accessible.",+ detail = f"Native {label} is no longer accessible.",) from exc- if _stat_module.S_ISLNK(mm_lstat.st_mode) or not _stat_module.S_ISREG(mm_lstat.st_mode):+ if _stat_module.S_ISLNK(companion_lstat.st_mode) or not _stat_module.S_ISREG(+ companion_lstat.st_mode+ ):raise HTTPException(status_code = 400,- detail = "Native vision companion must be a regular file.",+ detail = f"Native {label} must be a regular file.",)try:- if mm.resolve(strict = True).parent != gguf.resolve(strict = True).parent:+ if companion.resolve(strict = True).parent != gguf.resolve(strict = True).parent:raise HTTPException(status_code = 400,- detail = "Native vision companion must live next to the selected GGUF.",+ detail = f"Native {label} must live next to the selected GGUF.",)except OSError as exc:raise HTTPException(status_code = 400,- detail = "Native vision companion is no longer accessible.",+ detail = f"Native {label} is no longer accessible.",) from exc@@ -980,13 +999,11 @@ def _request_matches_loaded_settings(request: LoadRequest, llama_backend: LlamaCllama_backend.cache_type_kv):return False- # Vision loads silently drop speculative decoding (llama_cpp.py gates spec- # on ``not is_vision``), so treat the request as ``off`` against the- # backend's ``None`` to avoid a redundant reload.- if llama_backend.is_vision:- req_mode = "off"- else:- req_mode = _canonicalize_spec_mode(request.speculative_type) or "auto"+ # Spec decoding works on vision models too (MTP is mmproj-compatible,+ # llama.cpp #22673; the old ``not is_vision`` gate is gone), so compare+ # the real requested mode -- coercing vision to ``off`` here used to+ # swallow every spec-mode change on a vision model as already_loaded.+ req_mode = _canonicalize_spec_mode(request.speculative_type) or "auto"backend_mode = llama_backend.requested_spec_mode or "auto"if req_mode != backend_mode:return False@@ -1008,6 +1025,35 @@ def _request_matches_loaded_settings(request: LoadRequest, llama_backend: LlamaCelse:if list(request.llama_extra_args) != backend_extra:return False+ # A drafter that appeared next to the loaded weights since the last load+ # changes the launch command (--model-draft) when the mode can use it;+ # without this, a duplicate /load is deduped and MTP can't engage short+ # of an unload. Runs last: it stats the filesystem (two dir scans against+ # the resolved weight path -- covers local dirs and HF cache snapshots+ # alike), so every pure-memory comparison above short-circuits first.+ # Skipped when auto drops MTP anyway (sub-3B) or the user owns+ # --spec-type, where a drafter changes nothing. Resolve both sides: the+ # stored launch path may be a snapshot symlink while detect_mtp_file+ # returns the resolved blob.+ if req_mode in ("auto", "mtp", "mtp+ngram") and llama_backend.gguf_path:+ effective_extras = (+ request.llama_extra_args+ if request.llama_extra_args is not None+ else llama_backend.extra_args+ )+ size_b = extract_model_size_b(llama_backend.model_identifier or "")+ if not _auto_mode_drops_mtp(req_mode, size_b) and not _extra_args_set_spec_type(+ effective_extras+ ):+ detected = detect_mtp_file(llama_backend.gguf_path)+ stored = llama_backend.mtp_draft_path+ try:+ detected_resolved = Path(detected).resolve() if detected else None+ stored_resolved = Path(stored).resolve() if stored else None+ except OSError:+ return False+ if detected_resolved != stored_resolved:+ return Falsereturn True@@ -1313,12 +1359,26 @@ async def load_model()else:# Local mode: llama-server loads via -m <path>- if native_grant_backed and config.gguf_mmproj_file:- _validate_native_mmproj_companion(config.gguf_mmproj_file, config.gguf_file)+ if native_grant_backed:+ if config.gguf_mmproj_file:+ _validate_native_gguf_companion(+ config.gguf_mmproj_file, config.gguf_file, "vision companion"+ )+ if config.gguf_mtp_file:+ # The drafter is optional (unlike mmproj for a vision+ # model): drop it rather than fail the load.+ try:+ _validate_native_gguf_companion(+ config.gguf_mtp_file, config.gguf_file, "MTP drafter"+ )+ except HTTPException as exc:+ logger.warning("Dropping MTP drafter for native load: %s", exc.detail)+ config.gguf_mtp_file = Nonesuccess = await asyncio.to_thread(llama_backend.load_model,gguf_path = config.gguf_file,mmproj_path = config.gguf_mmproj_file,+ mtp_draft_path = config.gguf_mtp_file,# Pass the resolved variant so _extra_args_source keys off# the same string the inheritance check at the top of /load# uses (#5401 followup).diff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.pyindex 52e3848157a..09775707ee6 100644--- a/studio/backend/tests/test_llama_server_args.py+++ b/studio/backend/tests/test_llama_server_args.py@@ -507,3 +507,28 @@ def test_strip_shadowing_flags_defaults_strip_everything():["-c", "4096", "--cache-type-k", "q8_0", "--spec-default", "--jinja"])assert out == []+++def test_strip_shadowing_flags_drops_model_draft_with_spec():+ # --model-draft (and aliases) are Studio-managed since the separate+ # MTP drafter support: an inherited copy must not last-wins-override+ # the auto-detected drafter.+ out = strip_shadowing_flags(+ ["--model-draft", "/old/mtp.gguf", "-md", "/old2.gguf", "--top-k", "20"],+ strip_context = False,+ strip_cache = False,+ strip_spec = True,+ strip_template = False,+ )+ assert out == ["--top-k", "20"]+++def test_strip_shadowing_flags_keeps_model_draft_without_spec():+ out = strip_shadowing_flags(+ ["--model-draft", "/custom/mtp.gguf"],+ strip_context = True,+ strip_cache = False,+ strip_spec = False,+ strip_template = False,+ )+ assert out == ["--model-draft", "/custom/mtp.gguf"]diff --git a/studio/backend/tests/test_mtp_drafter_companion.py b/studio/backend/tests/test_mtp_drafter_companion.pynew file mode 100644index 00000000000..d5e8d13652a--- /dev/null+++ b/studio/backend/tests/test_mtp_drafter_companion.py@@ -0,0 +1,276 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Separate-file MTP drafter (Gemma 4) contracts.++Pins: the drafter-path predicate and its two layering mirrors, Gemma+effective-size extraction, companion classification in variant plans+(including resume from pre-fix manifests where the drafter leaked into a+quant's main files), and local drafter detection / self-pairing rejection.+"""++from __future__ import annotations++import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from hub.utils.download_manifest import ExpectedFile+from hub.utils.gguf import is_mtp_drafter_path+from hub.utils.gguf_plan import build_gguf_variant_plans, plan_from_expected_files+from utils.models.model_config import (+ _is_mtp_drafter,+ detect_gguf_model,+ detect_mtp_file,+ extract_model_size_b,+)+++# ── Predicate + layering mirrors ─────────────────────────────────────++DRAFTER_CASES = [+ ("mtp-gemma-4-12b-it.gguf", True),+ ("MTP/gemma-4-12b-it-Q8_0-MTP.gguf", True),+ ("foo/MTP/bar.gguf", True),+ ("gemma-4-12b-it-Q8_0.gguf", False),+ # Baked-in Qwen MTP repos: the head is inside the main GGUF, the file+ # IS the model -- must never be classified as a companion.+ ("Qwen3.6-27B-MTP-Q4_K_M.gguf", False),+ ("prompt-mtp-test.gguf", False),+ ("smtp/model.gguf", False),+ ("mtp-readme.txt", False),+]++[email protected]("path,expected", DRAFTER_CASES)+def test_drafter_predicate_and_mirrors_agree(path, expected):+ from core.inference.llama_cpp import _is_companion_gguf_path++ assert is_mtp_drafter_path(path) is expected+ assert _is_mtp_drafter(path) is expected+ # The core mirror bundles mmproj; none of these inputs are mmproj, so+ # it must agree with the canonical predicate.+ assert _is_companion_gguf_path(path) is expected+++# ── Gemma effective-size extraction ──────────────────────────────────+++ "model_id,size_b",+ [+ ("unsloth/gemma-4-E2B-it-GGUF", 2.0),+ ("unsloth/gemma-4-E4B-it", 4.0),+ ("unsloth/gemma-3n-E4B-it", 4.0),+ # MoE active params beat effective and total notation.+ ("unsloth/Qwen3.5-35B-A3B", 3.0),+ ("unsloth/gemma-4-12b-it-GGUF", 12.0),+ ("unsloth/Qwen3.5-9B-MTP-GGUF", 9.0),+ ("no-size-here", None),+ ],+)+def test_extract_model_size_b(model_id, size_b):+ assert extract_model_size_b(model_id) == size_b+++# ── Variant plan companion classification ────────────────────────────+++def _sib(name: str, size: int, sha: str):+ return SimpleNamespace(rfilename = name, size = size, lfs = {"sha256": sha})+++GEMMA_SIBLINGS = [+ _sib("gemma-4-12b-it-Q4_K_M.gguf", 4_000, "main-q4"),+ _sib("gemma-4-12b-it-Q8_0.gguf", 8_000, "main-q8"),+ _sib("mtp-gemma-4-12b-it.gguf", 100, "drafter"),+ _sib("MTP/gemma-4-12b-it-Q8_0-MTP.gguf", 100, "mtp-sub-q8"),+ _sib("MTP/gemma-4-12b-it-BF16-MTP.gguf", 200, "mtp-sub-bf16"),+ _sib("mmproj-F16.gguf", 500, "mmproj"),+]+++def test_variant_plans_carry_drafter_as_companion():+ plans = build_gguf_variant_plans(GEMMA_SIBLINGS)++ # No phantom quants from the drafter's Q8_0 label or the MTP/ copies.+ assert set(plans) == {"q4_k_m", "q8_0"}+ for plan in plans.values():+ assert "mtp-gemma-4-12b-it.gguf" in plan.target_filenames+ assert not any("MTP/" in name for name in plan.target_filenames)+ assert "drafter" in plan.companion_hashes+ assert "drafter" not in plan.main_hashes+ assert plan.mmproj_filenames == frozenset({"mmproj-F16.gguf"})++ q4 = plans["q4_k_m"]+ assert q4.main_filenames == frozenset({"gemma-4-12b-it-Q4_K_M.gguf"})+ assert q4.main_size_bytes == 4_000+ # Download size = main + mmproj + drafter.+ assert q4.download_size_bytes == 4_600+++def test_baked_in_repo_plans_unchanged():+ plans = build_gguf_variant_plans([_sib("Qwen3.6-27B-MTP-Q4_K_M.gguf", 4_000, "q4")])+ assert plans["q4_k_m"].target_filenames == ("Qwen3.6-27B-MTP-Q4_K_M.gguf",)+++def test_old_manifest_resume_reclassifies_drafter():+ # Pre-fix manifests could leak the drafter into a quant's expected+ # files; resume must classify it as a companion, not a main shard.+ old = [+ ExpectedFile(path = "gemma-4-12b-it-Q8_0.gguf", size = 8_000, sha256 = "main-q8"),+ ExpectedFile(path = "mtp-gemma-4-12b-it.gguf", size = 100, sha256 = "drafter"),+ ]+ plan = plan_from_expected_files("Q8_0", old)+ assert plan.main_hashes == frozenset({"main-q8"})+ assert plan.companion_hashes == frozenset({"drafter"})+ assert plan.mmproj_filenames == frozenset()+++# ── Local detection / self-pairing ───────────────────────────────────+++def test_detect_mtp_file_finds_root_sibling(tmp_path):+ (tmp_path / "model-Q4_K_M.gguf").write_bytes(b"x")+ (tmp_path / "mtp-model.gguf").write_bytes(b"x")+ (tmp_path / "MTP").mkdir()+ (tmp_path / "MTP" / "model-Q8_0-MTP.gguf").write_bytes(b"x")++ found = detect_mtp_file(str(tmp_path / "model-Q4_K_M.gguf"))+ assert found is not None+ assert found.endswith("mtp-model.gguf")+++def test_detect_mtp_file_none_without_sibling(tmp_path):+ (tmp_path / "model-Q4_K_M.gguf").write_bytes(b"x")+ assert detect_mtp_file(str(tmp_path / "model-Q4_K_M.gguf")) is None+++def test_detect_gguf_model_rejects_drafter_file(tmp_path):+ drafter = tmp_path / "mtp-model.gguf"+ drafter.write_bytes(b"x")+ assert detect_gguf_model(str(drafter)) is None+++def test_detect_gguf_model_dir_skips_companions(tmp_path):+ main = tmp_path / "model-Q4_K_M.gguf"+ main.write_bytes(b"xxxx")+ # Companions are larger so a size-sorted pick would wrongly win.+ (tmp_path / "mtp-model.gguf").write_bytes(b"x" * 64)+ (tmp_path / "mmproj-F16.gguf").write_bytes(b"x" * 128)++ assert detect_gguf_model(str(tmp_path)) == str(main.resolve())+++def test_detect_mtp_file_pairs_by_weight_name(tmp_path):+ # Multi-model folder: each weight must get its own drafter, never the+ # first-sorted foreign one.+ (tmp_path / "gemma-4-12b-it-Q4_K_M.gguf").write_bytes(b"x")+ (tmp_path / "gemma-4-31B-it-Q4_K_M.gguf").write_bytes(b"x")+ (tmp_path / "mtp-gemma-4-12b-it.gguf").write_bytes(b"x")+ (tmp_path / "mtp-gemma-4-31B-it.gguf").write_bytes(b"x")++ found = detect_mtp_file(str(tmp_path / "gemma-4-31B-it-Q4_K_M.gguf"))+ assert found is not None and found.endswith("mtp-gemma-4-31B-it.gguf")+++def test_detect_mtp_file_skips_foreign_drafter(tmp_path):+ (tmp_path / "qwen3-8b-Q4_K_M.gguf").write_bytes(b"x")+ (tmp_path / "mtp-gemma-4-12b-it.gguf").write_bytes(b"x")+ assert detect_mtp_file(str(tmp_path / "qwen3-8b-Q4_K_M.gguf")) is None+++def test_detect_mtp_file_qat_prefix_layout(tmp_path):+ # unsloth's qat repo: drafter stem omits the -qat suffix but prefixes+ # the weight name (mtp-gemma-4-12B-it.gguf / gemma-4-12B-it-qat-Q4_0.gguf).+ (tmp_path / "gemma-4-12B-it-qat-Q4_0.gguf").write_bytes(b"x")+ (tmp_path / "mtp-gemma-4-12B-it.gguf").write_bytes(b"x")+ found = detect_mtp_file(str(tmp_path / "gemma-4-12B-it-qat-Q4_0.gguf"))+ assert found is not None and found.endswith("mtp-gemma-4-12B-it.gguf")+++def test_detect_mtp_file_search_root(tmp_path):+ # Weight in a quant subdir, drafter at the granted directory root.+ sub = tmp_path / "Q4_K_M"+ sub.mkdir()+ (sub / "gemma-4-12b-it-Q4_K_M.gguf").write_bytes(b"x")+ (tmp_path / "mtp-gemma-4-12b-it.gguf").write_bytes(b"x")+ found = detect_mtp_file(str(sub / "gemma-4-12b-it-Q4_K_M.gguf"), search_root = str(tmp_path))+ assert found is not None and found.endswith("mtp-gemma-4-12b-it.gguf")+++# ── Reload dedup includes the drafter ────────────────────────────────+++def _loaded_backend(weight, drafter_path):+ from core.inference.llama_cpp import LlamaCppBackend++ b = LlamaCppBackend()+ # Shape matches atexit cleanup expectations (terminate/wait/kill).+ b._process = SimpleNamespace(+ poll = lambda: None,+ terminate = lambda: None,+ wait = lambda timeout = None: 0,+ kill = lambda: None,+ )+ b._healthy = True+ b._model_identifier = "local-gemma"+ b._gguf_path = str(weight)+ b._hf_variant = None+ b._requested_n_ctx = 4096+ b._cache_type_kv = None+ b._requested_spec_mode = "auto"+ b._speculative_type = "draft-mtp" if drafter_path else "default"+ b._spec_draft_n_max = None+ b._chat_template_override = None+ b._extra_args = None+ b._mtp_draft_path = drafter_path+ return b+++def _target_state_kwargs(weight, mtp_draft_path):+ return dict(+ model_identifier = "local-gemma",+ hf_variant = None,+ n_ctx = 4096,+ cache_type_kv = None,+ speculative_type = "auto",+ spec_draft_n_max = None,+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ gguf_path = str(weight),+ mtp_draft_path = mtp_draft_path,+ )+++def test_already_in_target_state_bounces_on_new_drafter(tmp_path):+ weight = tmp_path / "gemma-4-12b-it-Q4_K_M.gguf"+ weight.write_bytes(b"x")+ drafter = tmp_path / "mtp-gemma-4-12b-it.gguf"+ drafter.write_bytes(b"x")++ # Loaded without a drafter; one now exists on disk -> must reload.+ b = _loaded_backend(weight, None)+ assert not b._already_in_target_state(**_target_state_kwargs(weight, str(drafter)))+ # Same drafter as launched -> still deduped.+ b = _loaded_backend(weight, str(drafter))+ assert b._already_in_target_state(**_target_state_kwargs(weight, str(drafter)))+++def test_detect_gguf_model_rejects_mtp_subdir_copy(tmp_path):+ # Direct selection of an MTP/ copy: the basename alone has no mtp-+ # prefix, so rejection relies on the parent dir name.+ sub = tmp_path / "MTP"+ sub.mkdir()+ copy = sub / "gemma-4-12b-it-BF16-MTP.gguf"+ copy.write_bytes(b"x")+ assert detect_gguf_model(str(copy)) is None+ # Selecting the MTP dir itself must not surface the copies as models.+ assert detect_gguf_model(str(sub)) is Nonediff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex 9dc01f83c5e..f61c210cf60 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -58,25 +58,28 @@ import re as _re_MODEL_SIZE_RE = _re.compile(r"(?:^|[-_/])(\d+\.?\d*)\s*([bm])(?:$|[-_/])", _re.IGNORECASE)# MoE active-parameter pattern: "A3B", "A3.5B", etc._ACTIVE_SIZE_RE = _re.compile(r"(?:^|[-_/])a(\d+\.?\d*)\s*([bm])(?:$|[-_/])", _re.IGNORECASE)+# Gemma 3n/4 effective-parameter pattern: "E2B", "E4B" -- the runtime+# footprint (MatFormer + per-layer embeddings), which is the size that+# matters for size-gated policies like sub-3B speculative-decoding fallback.+_EFFECTIVE_SIZE_RE = _re.compile(r"(?:^|[-_/])e(\d+\.?\d*)\s*([bm])(?:$|[-_/])", _re.IGNORECASE)def extract_model_size_b(model_id: str) -> float | None:"""Extract model size in billions from a model identifier.Prefers MoE active-parameter notation (e.g. ``A3B`` in- ``Qwen3.5-35B-A3B``) over total params. Handles ``B`` (billions)- and ``M`` (millions) suffixes.+ ``Qwen3.5-35B-A3B``), then Gemma effective-parameter notation+ (e.g. ``E2B``), over total params. Handles ``B`` (billions) and+ ``M`` (millions) suffixes."""mid = (model_id or "").lower()- active = _ACTIVE_SIZE_RE.search(mid)- if active:- val = float(active.group(1))- return val / 1000.0 if active.group(2).lower() == "m" else val- size = _MODEL_SIZE_RE.search(mid)- if not size:- return None- val = float(size.group(1))- return val / 1000.0 if size.group(2).lower() == "m" else val+ # First match wins, in priority order: active > effective > total.+ for pattern in (_ACTIVE_SIZE_RE, _EFFECTIVE_SIZE_RE, _MODEL_SIZE_RE):+ m = pattern.search(mid)+ if m:+ val = float(m.group(1))+ return val / 1000.0 if m.group(2).lower() == "m" else val+ return None# Maps equivalent model names to their canonical YAML config file.@@ -930,6 +933,24 @@ def _is_mmproj(filename: str) -> bool:return "mmproj" in filename.lower()+def _is_mtp_drafter(path: str) -> bool:+ """True for a separate-file MTP drafter (speculative head), a companion+ to the main model rather than a selectable quant: the repo-root+ ``mtp-*.gguf`` or the ``MTP/`` subdir copies (Gemma 4).++ Mirrors hub.utils.gguf.is_mtp_drafter_path (utils cannot import hub).+ Must be excluded everywhere mmproj is, or the drafter leaks into variant+ menus (a phantom quant) and quant-matched file lookups -- e.g. a ``Q8_0``+ request must not resolve to ``MTP/...-Q8_0-MTP.gguf``, which sorts ahead+ of the real weight.+ """+ p = path.lower()+ if not p.endswith(".gguf"):+ return False+ name = p.rsplit("/", 1)[-1]+ return name.startswith("mtp-") or "/mtp/" in f"/{p}"++# Family tokens for #5347's filename fallback. Lowercase; order irrelevant._MODEL_FAMILY_TOKENS: tuple[str, ...] = ("qwen",@@ -1137,6 +1158,48 @@ def detect_mmproj_file(path: str, search_root: Optional[str] = None) -> Optionalreturn str(best[1])+def detect_mtp_file(path: str, search_root: Optional[str] = None) -> Optional[str]:+ """Find the separate MTP drafter (``mtp-*.gguf``) for a local GGUF model.++ The drafter that pairs with the main weights sits at the repo/snapshot+ root (Gemma 4); the weight itself may be at the root or in a quant subdir,+ so scan the weight's directory and ``search_root``. Matches by the+ ``mtp-`` filename prefix unsloth uses for ``-hf`` auto-discovery -- the+ same signal as the HF download path. Repos that bake the head into the+ main GGUF (Qwen) have no such sibling, so this returns None.++ Pairs by name so a multi-model folder can't attach a foreign drafter:+ unsloth names the drafter ``mtp-<model>.gguf`` where ``<model>`` prefixes+ the weight filename across all Gemma 4 repos (e.g.+ ``mtp-gemma-4-12B-it.gguf`` next to ``gemma-4-12B-it-qat-Q4_0.gguf``).+ An unmatched drafter is skipped (fail-safe: no MTP).+ """+ p = Path(path)+ weight_name = p.name.lower() if p.suffix.lower() == ".gguf" else None+ start_dir = p.parent if p.is_file() else p+ dirs = [start_dir]+ if search_root is not None:+ dirs.append(Path(search_root))+ for d in dirs:+ try:+ entries = sorted(d.iterdir())+ except OSError:+ continue+ for f in entries:+ name = f.name.lower()+ if not (name.startswith("mtp-") and name.endswith(".gguf")):+ continue+ stem = name[len("mtp-") : -len(".gguf")]+ if not stem or (weight_name is not None and not weight_name.startswith(stem)):+ continue+ try:+ if f.is_file():+ return str(f.resolve())+ except OSError:+ continue+ return None++def detect_gguf_model(path: str) -> Optional[str]:"""Check if a local path is or contains a GGUF model file.@@ -1148,7 +1211,12 @@ def detect_gguf_model(path: str) -> Optional[str]:# Case 1: direct .gguf fileif p.suffix.lower() == ".gguf":- if _is_mmproj(p.name):+ # Companions are not models: rejecting a drafter here also keeps+ # detect_mtp_file from pairing the same file with itself+ # (-m drafter --model-draft drafter). Include the immediate parent+ # dir so the MTP/ subdir copies are caught -- the basename alone+ # (...-MTP.gguf) doesn't match the predicate's mtp- prefix.+ if _is_mmproj(p.name) or _is_mtp_drafter(f"{p.parent.name}/{p.name}"):return None# Extension is authoritative: don't gate on is_file()/exists(), which# can fail in the Windows lock window after llama-server is killed.@@ -1160,10 +1228,14 @@ def detect_gguf_model(path: str) -> Optional[str]:return str(p.absolute()) # absolute() keeps symlink names readable# Directory named "*.gguf": fall through to the dir scan below.- # Case 2: directory containing .gguf files (skip mmproj)+ # Case 2: directory containing .gguf files (skip mmproj / MTP drafter)if p.is_dir():gguf_files = sorted(- (f for f in _iter_gguf_files(p) if not _is_mmproj(f.name)),+ (+ f+ for f in _iter_gguf_files(p)+ if not _is_mmproj(f.name) and not _is_mtp_drafter(f"{f.parent.name}/{f.name}")+ ),key = lambda f: f.stat().st_size,reverse = True,)@@ -1393,6 +1465,9 @@ def list_gguf_variants(if "mmproj" in fname.lower():has_vision = Truecontinue+ # MTP drafters are speculative-decoding companions, not quants.+ if _is_mtp_drafter(fname):+ continuequant = _extract_quant_label(fname)quant_totals[quant] = quant_totals.get(quant, 0) + size@@ -1468,6 +1543,8 @@ def list_local_gguf_variants(directory: str) -> tuple[list[GgufVariantInfo], boo# Use the relative path so ``BF16/foo.gguf`` and ``Q4_K_M/foo.gguf``# get distinct quant labels instead of collapsing on basename.rel = f.relative_to(p).as_posix()+ if _is_mtp_drafter(rel):+ continuequant = _extract_quant_label(rel)quant_totals[quant] = quant_totals.get(quant, 0) + sizeif quant not in quant_first_file:@@ -1504,7 +1581,9 @@ def _find_local_gguf_by_variant(directory: str, variant: str) -> Optional[str]:matches = sorted(ffor f in _iter_gguf_files(p, recursive = True)- if not _is_mmproj(f.name) and _extract_quant_label(f.relative_to(p).as_posix()) == variant+ if not _is_mmproj(f.name)+ and not _is_mtp_drafter(f.relative_to(p).as_posix())+ and _extract_quant_label(f.relative_to(p).as_posix()) == variant)if matches:return str(matches[0].resolve())@@ -1519,9 +1598,9 @@ def _detect_gguf_from_hf_cache(repo_id: str) -> Optional[str]:"""for snap in _iter_hf_cache_snapshots(repo_id):rel_files = [- f.relative_to(snap).as_posix()+ relfor f in _iter_gguf_files(snap, recursive = True)- if not _is_mmproj(f.name)+ if not _is_mtp_drafter(rel := f.relative_to(snap).as_posix()) and not _is_mmproj(f.name)]if rel_files:return _pick_best_gguf(rel_files)@@ -2068,6 +2147,7 @@ class ModelConfig:has_audio_input: bool = False # Accepts audio input (ASR/speech understanding)gguf_file: Optional[str] = None # Full path to the .gguf file (local mode)gguf_mmproj_file: Optional[str] = None # Full path to the mmproj .gguf file (vision projection)+ gguf_mtp_file: Optional[str] = None # Full path to the separate MTP drafter (local mode)gguf_hf_repo: Optional[str] = (None # HF repo ID for -hf mode (e.g. "unsloth/gemma-3-4b-it-GGUF"))@@ -2207,6 +2287,11 @@ class ModelConfig:elif base_is_vision:logger.warning(f"Base model is vision but no mmproj file found in {gguf_dir}")+ # Separate MTP drafter sibling (Gemma 4), mirroring mmproj.+ mtp_file = detect_mtp_file(gguf_file, search_root = path)+ if mtp_file:+ logger.info(f"Detected MTP drafter: {mtp_file}")+return cls(identifier = identifier,display_name = display_name,@@ -2218,6 +2303,7 @@ class ModelConfig:is_gguf = True,gguf_file = gguf_file,gguf_mmproj_file = mmproj_file,+ gguf_mtp_file = mtp_file,)else:# Does the HF repo contain GGUF files?