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: add opt-in DSpark speculative decoding (#7968)
oobabooga2e593b3f854d
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 2430f74af19..a620003cd91 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -139,6 +139,7 @@ class GgufLoadIntent:gguf_path: Optional[str] = Nonemmproj_path: Optional[str] = Nonemtp_draft_path: Optional[str] = None+ dspark_draft_path: Optional[str] = Nonehf_repo: Optional[str] = Nonehf_variant: Optional[str] = Nonehf_token: Optional[str] = None@@ -1158,12 +1159,23 @@ def _is_companion_gguf_path(path: str) -> bool:def _is_mtp_only_drafter_path(path: str) -> bool:- """MTP only, the one kind Studio launches today (``--spec-type draft-mtp``).- DSpark needs ``draft-dspark`` plus ``--fit off``, so drafter discovery must- narrow to MTP rather than reuse the broad companion predicate."""+ """MTP only, not the other companion GGUFs. Each drafter kind needs its own+ ``--spec-type``, so discovery narrows to one kind rather than reusing the+ broad companion predicate, which exists to EXCLUDE companions from menus."""return _drafter_path_kind(path) == "mtp"+def _is_dspark_drafter_path(path: str) -> bool:+ """True for a DSpark sidecar, excluding the separate DFlash method.++ Broader than model_config.detect_dspark_file, which additionally requires a+ published drafter NAME: a repo's ``dspark/`` directory holds only sidecars,+ while a user's local folder may hold anything. Only ever used against repo+ listings and cache snapshots for that reason.+ """+ return _drafter_path_kind(path) == "dspark"++_BIG_ENDIAN_GGUF_FILENAME_RE = re.compile(r"(^|[-_])be(?:[._-]|$)", re.IGNORECASE)_GGUF_KNOWN_QUANT_RE = re.compile(r"(UD-)?"@@ -2192,6 +2204,13 @@ def _extra_args_requests_mtp(return bool(_accumulated_spec_types(extra_args, env) & {"mtp", "draft-mtp"})+def _extra_args_requests_dspark(+ extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None+) -> bool:+ """True if DSpark lands in llama.cpp's accumulated spec-type vector."""+ return "draft-dspark" in _accumulated_spec_types(extra_args, env)++@functools.lru_cache(maxsize = 1)def _metal_device_is_paravirtual() -> bool:"""True when Metal is a virtualised Apple GPU, whose offload can corrupt output.@@ -2471,7 +2490,9 @@ def _extra_args_requests_separate_draft(_extra_args_requests_mtp; ngram-* load no model). Accumulating for the same reason as_extra_args_requests_mtp: a later --spec-default or --spec-type cannot clear aninherited draft-simple, so reading only the last under-reserves the model it loads."""- return bool(_accumulated_spec_types(extra_args, env) & {"draft-simple", "draft-eagle3"})+ return bool(+ _accumulated_spec_types(extra_args, env) & {"draft-simple", "draft-eagle3", "draft-dspark"}+ )def _extra_args_spec_draft_n_max(extra_args: Optional[Iterable[str]]) -> Optional[int]:@@ -2730,13 +2751,14 @@ def _build_ngram_mod_flags(# Canonical Speculative Decoding modes exposed by the Unsloth chat UI.-# Dropdown renders five (auto, mtp, ngram, mtp+ngram, off); the load API+# Dropdown renders six (auto, mtp, dspark, ngram, mtp+ngram, off); the load API# also accepts legacy values the original Switch and external callers emit# (default, draft-mtp, ngram-mod, ngram-simple).-_CANONICAL_SPEC_MODES = {"auto", "mtp", "ngram", "mtp+ngram", "off", "ngram-simple"}+_CANONICAL_SPEC_MODES = {"auto", "mtp", "dspark", "ngram", "mtp+ngram", "off", "ngram-simple"}_LEGACY_SPEC_MODE_MAP = {"default": "auto","draft-mtp": "mtp",+ "draft-dspark": "dspark","ngram-mod": "ngram",}@@ -2744,7 +2766,7 @@ _LEGACY_SPEC_MODE_MAP = {def _canonicalize_spec_mode(value):"""Map any accepted ``speculative_type`` input onto a canonical mode.- Returns ``auto``, ``mtp``, ``ngram``, ``mtp+ngram``, ``off``,+ Returns ``auto``, ``mtp``, ``dspark``, ``ngram``, ``mtp+ngram``, ``off``,``ngram-simple``, or ``None`` (callers treat ``None`` as ``auto``).Unknown strings collapse to ``auto`` so a stale UI value or typo fallsback to the safe platform-aware path.@@ -2933,6 +2955,8 @@ class LlamaCppBackend:# llama.cpp" hint in the UI. "binary_no_mtp" / "binary_outdated" -># a newer prebuilt would help; "runtime_error" -> it may not.self._spec_fallback_reason: Optional[str] = None+ self._spec_drafter_kind: Optional[str] = None+ self._dspark_sidecar_absent: bool = Falseself._hf_variant: Optional[str] = Noneself._is_vision: bool = False# Block-diffusion model (e.g. DiffusionGemma): served by the diffusion@@ -3691,10 +3715,15 @@ class LlamaCppBackend:return Falseelif speculative_type != (backend_spec or "auto"):return False+ # Reload so the next Apply retries the drafter fetch. Worth it when the+ # repo publishes a drafter and the fetch failed; not when it publishes+ # none, which for DSpark is the permanent state of every repo but one and+ # would relaunch an identical server forever.if (intent.gguf_path is Noneand self._spec_fallback_reason == "drafter_not_found"- and speculative_type in ("auto", "mtp", "mtp+ngram")+ and speculative_type in ("auto", "mtp", "mtp+ngram", "dspark")+ and not (self._spec_drafter_kind == "dspark" and self._dspark_sidecar_absent)and not spec_owned_by_extra_args):return False@@ -3704,7 +3733,10 @@ class LlamaCppBackend:# user's prior value in its intent. Only a changed value should retry MTP.compared_draft_n_max = self._last_load_intent.spec_draft_n_maxif (- (self._speculative_type == "draft-mtp" or self._spec_fallback_reason == "runtime_error")+ (+ self._speculative_type in ("draft-mtp", "draft-dspark")+ or self._spec_fallback_reason == "runtime_error"+ )and intent.spec_draft_n_max is not Noneand intent.spec_draft_n_max != (compared_draft_n_max or 0)):@@ -3718,11 +3750,19 @@ class LlamaCppBackend:"auto","mtp","mtp+ngram",+ "dspark",):try:- requested_draft = (- Path(intent.mtp_draft_path).resolve() if intent.mtp_draft_path else None+ # Auto counts as dspark once it resolved that way: the launch stored+ # the DSpark sidecar, so comparing the MTP field (None for these+ # repos) against it would reload a healthy server on every Apply.+ _compare_dspark = speculative_type == "dspark" or (+ speculative_type == "auto" and self._speculative_type == "draft-dspark")+ intent_draft = (+ intent.dspark_draft_path if _compare_dspark else intent.mtp_draft_path+ )+ requested_draft = Path(intent_draft).resolve() if intent_draft else None# A drafter the last load dropped on purpose counts as launched here:# the file is still there, so comparing it against the stored None# would reload the same drafter-free server forever.@@ -3790,6 +3830,17 @@ class LlamaCppBackend:def speculative_type(self) -> Optional[str]:return self._speculative_type+ @property+ def spec_drafter_kind(self) -> Optional[str]:+ """Which drafter the resolution was about, ``mtp`` or ``dspark``.++ Distinct from ``requested_spec_mode``, which stays ``auto`` when Auto+ resolves the kind itself, and from ``speculative_type``, which reads+ ``default`` once a fallback fires. The UI needs the kind to name the+ right recovery in a fallback notice.+ """+ return self._spec_drafter_kind+@propertydef requested_spec_mode(self) -> Optional[str]:"""Canonical UI-facing mode the user requested (see field doc)."""@@ -3950,13 +4001,25 @@ class LlamaCppBackend:# ── llama-server capability probe ─────────────────────────────+ # Prebuilts based on llama.cpp b10259..b10268 advertise draft-dspark but land between+ # the reshape regression (ggml-org/llama.cpp#26531) and its fix (#26577), so a DSpark+ # launch aborts on load. Matched on the base build number, not one exact tag: every+ # release in that window is affected. Source builds carry no install marker, so only+ # managed prebuilts are gated.+ _BROKEN_DSPARK_BUILDS = range(10259, 10269)++ @classmethod+ def _dspark_release_is_broken(cls, release_tag: Optional[str]) -> bool:+ match = re.match(r"b(\d+)", str(release_tag or ""))+ return bool(match) and int(match.group(1)) in cls._BROKEN_DSPARK_BUILDS+# Cached on (path, mtime); `unsloth studio update` bumps mtime._capability_cache: dict[tuple[str, int], dict[str, object]] = {}@classmethoddef probe_server_capabilities(cls, binary: Optional[str] = None) -> dict[str, object]:"""Parse `llama-server --help` for feature flags. Returns- {found, mtp_token, supports_mtp, ngram_mod_flavor,+ {found, mtp_token, supports_mtp, supports_dspark, ngram_mod_flavor,supports_ngram_mod, spec_draft_n_max_flag, cache flag support}.``ngram_mod_flavor``: ``"new"`` when the post-rename@@ -3977,6 +4040,7 @@ class LlamaCppBackend:"found": False,"mtp_token": None,"supports_mtp": False,+ "supports_dspark": False,"mtp_probe_inconclusive": True,"ngram_mod_flavor": None,"supports_ngram_mod": False,@@ -4002,6 +4066,7 @@ class LlamaCppBackend:return cachedmtp_token: Optional[str] = None+ supports_dspark = Falsengram_mod_flavor: Optional[str] = Nonespec_draft_n_max_flag: Optional[str] = Nonesupports_kv_unified = False@@ -4084,6 +4149,12 @@ class LlamaCppBackend:line for line in help_text.splitlines() if "--spec-type" in line)mtp_token = cls._mtp_token_from_spec_help(spec_help)+ supports_dspark = bool(+ re.search(+ r"(?<![a-z0-9_-])draft-dspark(?![a-z0-9_-])",+ spec_help.lower(),+ )+ )# Only a resolved --spec-type block confirms missing MTP; empty/crash# leaves saw_spec_type False so supports_mtp fails open.saw_spec_type = bool(spec_help.strip()) and "--spec-type" in spec_help@@ -4149,10 +4220,26 @@ class LlamaCppBackend:supports_mtp = Falsemtp_probe_inconclusive = True+ if supports_dspark:+ try:+ from utils.llama_cpp_freshness import read_install_marker++ marker = read_install_marker(bin_path) or {}+ release_tag = marker.get("release_tag") or marker.get("tag")+ if cls._dspark_release_is_broken(release_tag):+ supports_dspark = False+ logger.info(+ "Disabling DSpark for known-broken llama.cpp prebuilt %s",+ release_tag,+ )+ except Exception as exc:+ logger.debug("Could not inspect llama.cpp prebuilt identity: %s", exc)+info = {"found": True,"mtp_token": mtp_token,"supports_mtp": supports_mtp,+ "supports_dspark": bool(supports_dspark and saw_spec_type and probe_ok),"mtp_probe_inconclusive": mtp_probe_inconclusive,"ngram_mod_flavor": ngram_mod_flavor,"supports_ngram_mod": ngram_mod_flavor is not None,@@ -7125,6 +7212,7 @@ class LlamaCppBackend:label: str,cancel_event: Optional[threading.Event] = None,near_path: Optional[str] = None,+ outcome: Optional[dict] = None,) -> Optional[str]:"""Resolve and fetch a companion GGUF (mmproj / MTP drafter) by name.@@ -7195,6 +7283,11 @@ class LlamaCppBackend:except Exception as e:logger.debug(f"Offline cache lookup for {label} failed: {e}")+ # "The repo publishes none" and "the fetch failed" both return None, but+ # only the second is worth retrying on the next Apply. Left unset on the+ # early returns above, where the answer is genuinely unknown.+ if outcome is not None and not cancel_event.is_set():+ outcome["listed"] = target is not Noneif target is None or cancel_event.is_set():return None@@ -7343,6 +7436,102 @@ class LlamaCppBackend:near_path = near_path,)+ def _cached_repo_dspark_drafter(+ self,+ hf_repo: str,+ *,+ cache_dir: Optional[str] = None,+ ) -> Optional[str]:+ """The preferred already-cached DSpark sidecar for a repo, Q8_0 first+ (dspark_preference_key), so an offline reuse picks the same file the+ online download would have fetched."""+ try:+ from utils.models.model_config import (+ _iter_hf_cache_snapshots,+ dspark_preference_key,+ )++ snapshots = (+ _iter_hf_cache_snapshots(hf_repo)+ if cache_dir is None+ else _iter_hf_cache_snapshots(hf_repo, cache_dir)+ )+ candidates: list[Path] = []+ for snap in snapshots:+ candidates.extend(+ snap / name+ for name in _gguf_snapshot_files(snap)+ if _is_dspark_drafter_path(name)+ )+ for candidate in sorted(candidates, key = lambda p: dspark_preference_key(p.name)):+ if candidate.is_file():+ return str(candidate)+ except Exception as exc:+ logger.debug("Cached DSpark drafter lookup failed for %s: %s", hf_repo, exc)+ return None++ def _download_dspark(+ self,+ *,+ hf_repo: str,+ hf_token: Optional[str] = None,+ near_path: Optional[str] = None,+ binary: Optional[str] = None,+ ) -> Optional[str]:+ """Download the published DSpark sidecar, preferring its Q8_0 copy.++ The ~11 GB fetch is gated on ``supports_dspark``: a binary that cannot run+ ``draft-dspark`` (every prebuilt in the known-broken window included) falls+ back, so the download would never be opened. A raised probe still fetches,+ since launch re-probes and may yet engage.+ """++ def _pick_dspark(candidates: list[str]) -> Optional[str]:+ from utils.models.model_config import dspark_preference_key+ files = sorted(+ (name for name in candidates if _is_dspark_drafter_path(name)),+ key = dspark_preference_key,+ )+ return files[0] if files else None++ cached = _companion_snapshot_sibling(near_path, _pick_dspark) if near_path else None+ if not cached and _hf_env_offline():+ cached = self._cached_repo_dspark_drafter(+ hf_repo,+ cache_dir = _hub_cache_dir_for_snapshot_path(near_path),+ )+ try:+ if not self.probe_server_capabilities(binary).get("supports_dspark"):+ logger.warning(+ "Skipping the DSpark sidecar download: llama-server has no usable "+ "--spec-type draft-dspark, so this load falls back to no speculative "+ "decoding. Run `unsloth studio update`, then reload."+ )+ # A sidecar already on disk is still reported: the route rediscovers it+ # on every Apply, so answering None would make the reuse check compare+ # it against a launched None and reload the same server each time.+ # _build_speculative_flags re-checks the capability and still falls back.+ return cached+ except Exception as exc:+ logger.debug("DSpark capability probe failed before the sidecar fetch: %s", exc)++ if cached:+ logger.info("Reusing cached DSpark drafter: %s", cached)+ return cached+ outcome: dict = {}+ found = self._download_companion_gguf(+ hf_repo = hf_repo,+ hf_token = hf_token,+ pick = _pick_dspark,+ label = "DSpark drafter",+ near_path = near_path,+ outcome = outcome,+ )+ # Distinguishes a repo that ships no sidecar (the permanent state for+ # every repo but one) from a fetch that failed and could yet succeed.+ self._dspark_sidecar_absent = outcome.get("listed") is False+ return found+def _resolve_launch_mmproj_path(self, *, model_path: str, mmproj_path: Optional[str]) -> Optional[str]:@@ -7379,7 +7568,12 @@ class LlamaCppBackend:logger.debug(f"Could not size mmproj {launch_mmproj_path}: {e}")return 0- def _resolve_launch_mtp_path(self, *, mtp_draft_path: Optional[str]) -> Optional[str]:+ def _resolve_launch_mtp_path(+ self,+ *,+ mtp_draft_path: Optional[str],+ drafter_label: str = "MTP",+ ) -> 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@@ -7388,7 +7582,7 @@ class LlamaCppBackend:if not mtp_draft_path:return Noneif not Path(mtp_draft_path).is_file():- logger.warning(f"MTP drafter file not found: {mtp_draft_path}")+ logger.warning(f"{drafter_label} drafter file not found: {mtp_draft_path}")return Nonereturn str(mtp_draft_path)@@ -8204,6 +8398,7 @@ class LlamaCppBackend:gguf_path = intent.gguf_pathmmproj_path = intent.mmproj_pathmtp_draft_path = intent.mtp_draft_path+ dspark_draft_path = intent.dspark_draft_pathhf_repo = intent.hf_repohf_variant = intent.hf_varianthf_token = intent.hf_token@@ -8462,6 +8657,9 @@ 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.+ # The canonical mode drives which drafter is downloaded, sized and+ # launched, so resolve it once before either branch can use it.+ _spec_canon = _canonicalize_spec_mode(speculative_type) or "auto"# 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.@@ -8499,7 +8697,6 @@ class LlamaCppBackend:# drafter speeds up even sub-3B (Gemma E2B), and the resolver# below decides the final emission. Skipped only when the# user disabled MTP or drives --spec-type manually.- _spec_canon = _canonicalize_spec_mode(speculative_type) or "auto"if (not mtp_draft_pathand _spec_canon in ("auto", "mtp", "mtp+ngram")@@ -8510,6 +8707,20 @@ class LlamaCppBackend:hf_token = hf_token,near_path = model_path,)+ # "auto" is included: DSpark is the default whenever the repo+ # ships a sidecar. Repos without one no-op, exactly like the+ # MTP fetch above, so this costs one listing and no download.+ if (+ not dspark_draft_path+ and _spec_canon in ("auto", "dspark")+ and not _extra_args_set_spec_type(extra_args)+ ):+ dspark_draft_path = self._download_dspark(+ hf_repo = hf_repo,+ hf_token = hf_token,+ near_path = model_path,+ binary = binary,+ )elif gguf_path:if not Path(gguf_path).is_file():raise FileNotFoundError(f"GGUF file not found: {gguf_path}")@@ -8520,6 +8731,32 @@ class LlamaCppBackend:# Set identifier early so _read_gguf_metadata can use it (DeepSeek).self._model_identifier = model_identifier+ # Auto resolves to DSpark whenever a sidecar is available and this+ # binary can run it: 1.84x decode on 4x B200 and 1.91x on one, against+ # the ngram-mod fallback this architecture would otherwise get. Gated+ # on the capability because _download_dspark also reports a cached+ # sidecar an incapable binary cannot launch, and promoting there would+ # turn Auto's fallback into no speculative decoding at all.+ if (+ _spec_canon == "auto"+ and dspark_draft_path+ and not _extra_args_set_spec_type(extra_args)+ ):+ try:+ if self.probe_server_capabilities(binary).get("supports_dspark"):+ _spec_canon = "dspark"+ logger.info("Auto: DSpark sidecar available, using draft-dspark.")+ except Exception as exc:+ logger.debug("DSpark capability probe failed during Auto: %s", exc)++ # MTP and DSpark are mutually exclusive, and the drafter sizing and+ # lifecycle path below is architecture agnostic, so it carries the+ # one drafter the mode selected. From here mtp_draft_path means+ # "the drafter this load will launch", whichever kind that is;+ # _spec_canon is the only thing that says which.+ if _spec_canon == "dspark":+ mtp_draft_path = dspark_draft_path+# Read GGUF metadata (context_length, chat_template); header-only.self._read_gguf_metadata(model_path)@@ -8934,8 +9171,10 @@ class LlamaCppBackend:# Mirrors _build_speculative_flags: forced mtp/mtp+ngram always# engage; auto only on an MTP model >= 3B; ngram/off never. A# separate drafter (Gemma) counts as an MTP model.- _mtp_canonical = _canonicalize_spec_mode(speculative_type)- _mtp_effective = _mtp_canonical or "auto"+ # _spec_canon, not the raw request: Auto has already resolved to+ # dspark above when a sidecar is available, and the reserve below+ # differs by kind (no duplicated target-KV copy, depth 3).+ _mtp_effective = _spec_canon_mtp_size_for_fit = _extract_model_size_b(model_identifier)# Sub-3B drops MTP only for an embedded head; a separate# drafter (Gemma) engages and needs its VRAM reserved.@@ -8974,8 +9213,11 @@ class LlamaCppBackend:_mtp_probe_raised = Falseif not _user_mtp_via_extras:try:+ _fit_caps = self.probe_server_capabilities(binary) or {}_mtp_binary_ok = bool(- (self.probe_server_capabilities(binary) or {}).get("mtp_token")+ _fit_caps.get("supports_dspark")+ if _mtp_effective == "dspark"+ else _fit_caps.get("mtp_token"))except Exception:_mtp_binary_ok = False@@ -8984,7 +9226,7 @@ class LlamaCppBackend:not _extra_args_set_spec_type(extra_args)and _mtp_model_for_fitand (- _mtp_effective in ("mtp", "mtp+ngram")+ _mtp_effective in ("mtp", "mtp+ngram", "dspark")or (_mtp_effective == "auto" and not _mtp_sub_3b_for_fit))and (@@ -9000,11 +9242,16 @@ class LlamaCppBackend:)# The duplicated full target-KV copy (ctx_tgt) is an MTP-only# cost: the MTP head runs a second context over the target- # model's own KV geometry. The separate-drafter spec modes- # (draft-simple/draft-eagle3, reached via _user_draft_via_extras)- # load a small distinct drafter with its own KV and keep no such- # copy, so only charge it when the engaged mode is truly MTP.- _engaged_is_mtp = bool(_user_mtp_via_extras or _auto_studio_mtp)+ # model's own KV geometry. Every separate-drafter mode loads a+ # distinct drafter with its own KV and keeps no such copy, so+ # only charge it when the engaged mode is truly MTP. Those modes+ # arrive by two routes, hence the two conditions: draft-simple+ # and draft-eagle3 via _user_draft_via_extras (already excluded,+ # they never set _user_mtp_via_extras), and DSpark via Studio's+ # own resolution, which does set _auto_studio_mtp.+ _engaged_is_mtp = bool(+ _user_mtp_via_extras or (_auto_studio_mtp and _mtp_effective != "dspark")+ )# Effective draft depth: extras win (last-wins at launch), else# the field, else the platform default (2 GPU / 3 CPU).@@ -9014,7 +9261,9 @@ class LlamaCppBackend:# _detected_gpus (not gpus) so manual -- which empty# gpus to bypass the planner -- keep the GPU draft depth the# launch flags also use, instead of the CPU default.- _mtp_eff_n_max = 2 if _detected_gpus else 3+ _mtp_eff_n_max = (+ 3 if _mtp_effective == "dspark" else (2 if _detected_gpus else 3)+ )# Separate-drafter weights live on GPU (an embedded head is# already in model_size). Size the drafter the launch loads, by# precedence: extras --model-draft (last-wins), else Unsloth's@@ -10050,6 +10299,7 @@ class LlamaCppBackend:_draft_device = ",".join(f"Vulkan{i}" for i in _vulkan_pin_ids)launch_mtp_draft_path = self._resolve_launch_mtp_path(mtp_draft_path = mtp_draft_path,+ drafter_label = "DSpark" if _spec_canon == "dspark" else "MTP",)_pv_suppressed_draft_path: Optional[str] = None_pv_suppressed_spec_extra_args: Optional[List[str]] = None@@ -10138,7 +10388,9 @@ class LlamaCppBackend:model_path = model_path,gpus = bool(_detected_gpus),binary = binary,- mtp_draft_path = launch_mtp_draft_path,+ mtp_draft_path = (None if _spec_canon == "dspark" else launch_mtp_draft_path),+ dspark_draft_path = (launch_mtp_draft_path if _spec_canon == "dspark" else None),+ dspark_fit_sized = not use_fit,draft_device = _draft_device,)# _build_speculative_flags judged the stripped list, so a user@@ -10405,8 +10657,9 @@ class LlamaCppBackend:_emit_extra_args = list(extra_args)if gpu_ids is not None:# gpu_ids owns placement, so remove competing device flags.- _emit_extra_args = self._strip_device_extra_args(extra_args)- if _emit_extra_args != list(extra_args):+ _before_device_strip = list(_emit_extra_args)+ _emit_extra_args = self._strip_device_extra_args(_emit_extra_args)+ if _emit_extra_args != _before_device_strip:logger.info("Dropped user device placement flags from extra args: ""explicit gpu_ids owns placement."@@ -10674,6 +10927,8 @@ class LlamaCppBackend:# math placed the model fully on GPU. A startup crash here# means that estimate was optimistic, so fall back to --fit# on and let llama.cpp offload rather than fail the load.+ # DSpark takes this path too: fitting only skips its+ # unmeasurable sidecar reserve, the drafter still loads.logger.warning("llama-server crashed during startup (exit code %s) ""with forced --fit off; the fit estimate was optimistic, "@@ -10794,6 +11049,9 @@ class LlamaCppBackend:_spec_requested_mtp = any("mtp" in str(t).lower() for t in spec_flags) or _extra_args_requests_mtp(extra_args, env = _launch_spec_env)+ _spec_requested_dspark = any(+ "draft-dspark" in str(t).lower() for t in spec_flags+ ) or _extra_args_requests_dspark(extra_args, env = _launch_spec_env)# Is the launched server actually running MTP+tensor? Gates the# probe/watchdog/recovery; cleared if the MTP-drop fallback wins._mtp_active_for_launched_server = bool(@@ -10851,7 +11109,11 @@ class LlamaCppBackend:# _requested_spec_mode so a duplicate /load doesn't thrash. The# cancel check stops an /unload-killed attempt respawning. A# decode-probe failure above also routes here.- if not healthy and _spec_requested_mtp and not self._cancel_event.is_set():+ if (+ not healthy+ and (_spec_requested_mtp or _spec_requested_dspark)+ and not self._cancel_event.is_set()+ ):# Blame the binary only when the output shows MTP itself# failing (unknown arch / draft or context build); an# unrelated crash (e.g. OOM) gets a neutral message.@@ -10870,14 +11132,14 @@ class LlamaCppBackend:_retry_reason = ("the prebuilt may predate it; retrying without ""speculative decoding -- run `unsloth studio "- "update` for MTP"+ "update` for this drafter")self._spec_fallback_reason = ("binary_outdated" if _arch_unsupported else "runtime_error")else:_retry_reason = (- "retrying without speculative decoding in case MTP is the cause"+ "retrying without speculative decoding in case the drafter is the cause")self._spec_fallback_reason = "runtime_error"_drafter = (@@ -10886,7 +11148,7 @@ class LlamaCppBackend:else "embedded head")logger.warning(- "llama-server failed to start with MTP (%s); %s.",+ "llama-server failed to start with speculative drafter (%s); %s.",_drafter,_retry_reason,)@@ -10898,7 +11160,9 @@ class LlamaCppBackend:# failed and lose a main model that loads fine without it. The# tail loses its spec group and the env goes with it, the same way# the crash replay does it.- if _extra_args_requests_mtp(extra_args, env = _launch_spec_env):+ if _extra_args_requests_mtp(+ extra_args, env = _launch_spec_env+ ) or _extra_args_requests_dspark(extra_args, env = _launch_spec_env):_fb_tail = strip_shadowing_flags(_fb_tail,strip_context = False,@@ -11182,6 +11446,8 @@ class LlamaCppBackend:gpus: bool,binary: Optional[str],mtp_draft_path: Optional[str] = None,+ dspark_draft_path: Optional[str] = None,+ dspark_fit_sized: bool = True,draft_device: Optional[str] = None,) -> List[str]:"""Return the llama-server flag list for the requested spec mode.@@ -11286,6 +11552,21 @@ class LlamaCppBackend:return flagscaps = self.probe_server_capabilities(binary)+ # Which drafter every branch below is about. Set once here, before any+ # fallback can erase the evidence: the UI names the recovery from this,+ # and under Auto neither the requested mode nor the resolved+ # _speculative_type ("default" after a fallback) still carries the kind.+ self._spec_drafter_kind = (+ "dspark"+ if canonical_mode == "dspark"+ or (+ (canonical_mode or "auto") == "auto"+ and dspark_draft_path+ and caps.get("supports_dspark")+ )+ else "mtp"+ )+def _resolved_draft_n_max() -> int:# User override wins; else platform default (the B200 / x86# clean-sweep sweet spot from PR #5582 is n=2 GPU, n=3 CPU;@@ -11296,6 +11577,66 @@ class LlamaCppBackend:return nreturn 2 if gpus else 3+ def _emit_dspark() -> None:+ """Append --model-draft <sidecar> --spec-type draft-dspark + n-max.++ Callers have already established the sidecar and the capability; Auto+ reaches this too, since DSpark is the default when both hold.+ """+ if not dspark_fit_sized:+ # Not a blocker: the sidecar ships no token_embd/output and borrows+ # the target's, so llama.cpp's fit step cannot build a standalone+ # draft context to measure it (llama-context.cpp:153-160) and skips+ # the reserve (server-context.cpp:1190-1193). The load still works;+ # only the ~11 GB is missing from the fit budget.+ logger.info(+ "DSpark under --fit on: llama.cpp cannot size the sidecar during "+ "fitting, so its ~%.1f GB is not reserved. Pin GPU Layers in "+ "Manual mode if the load runs out of VRAM.",+ (self._get_gguf_size_bytes(dspark_draft_path) or 0) / 1e9,+ )+ draft_n_max = int(spec_draft_n_max) if spec_draft_n_max is not None else 3+ if spec_draft_n_max is not None:+ self._spec_draft_n_max = draft_n_max+ n_max_flag = caps.get("spec_draft_n_max_flag") or "--spec-draft-n-max"+ flags.extend(+ [+ "--model-draft",+ dspark_draft_path,+ "--spec-type",+ "draft-dspark",+ str(n_max_flag),+ str(draft_n_max),+ ]+ )+ self._speculative_type = "draft-dspark"+ logger.info("Spec decoding: draft-dspark using %s", dspark_draft_path)++ if effective_mode == "dspark":+ # Capability first: the fetch is gated on the same answer, so a missing+ # sidecar here is usually the binary's fault. Blaming the file instead+ # would tell the user to place one, and reload on every Apply.+ if not caps.get("supports_dspark"):+ logger.warning(+ "DSpark requested but llama-server lacks --spec-type "+ "draft-dspark; loading without speculative decoding."+ )+ flags.append("--spec-default")+ self._speculative_type = "default"+ self._spec_fallback_reason = "binary_no_mtp"+ return flags+ if not dspark_draft_path:+ logger.warning(+ "DSpark requested but no matching dspark-*.gguf sidecar was found; "+ "loading without speculative decoding."+ )+ flags.append("--spec-default")+ self._speculative_type = "default"+ self._spec_fallback_reason = "drafter_not_found"+ return flags+ _emit_dspark()+ return flags+def _emit_mtp(*, chain_ngram: bool) -> bool:"""Append --spec-type mtp[/draft-mtp][,ngram-mod] + n-max."""mtp_token = caps.get("mtp_token") if caps else None@@ -11414,7 +11755,13 @@ class LlamaCppBackend:# effective_mode == "auto": the promotion path. llama.cpp #22673:# MTP is compatible with mmproj, so there's no vision gate.- if _auto_mla_embedded_mtp:+ if dspark_draft_path and caps.get("supports_dspark"):+ # DSpark first: load_model only hands a sidecar down once it has one+ # this binary can launch, and it beats every other Auto outcome for+ # this architecture (1.84x on 4x B200, 1.91x on one). Without it these+ # models fall through to --spec-default, i.e. no drafter at all.+ _emit_dspark()+ elif _auto_mla_embedded_mtp:# MLA embedded-MTP (GLM-5.2 et al.): the MTP path regresses vs spec-off# on llama.cpp today, so Auto drops it and falls back to ngram-mod (or# spec-off if unsupported), mirroring the sub-3B branch. Forced mtp /@@ -11638,6 +11985,8 @@ class LlamaCppBackend:self._mtp_draft_path = Noneself._mtp_draft_suppressed_path = Noneself._spec_fallback_reason = None+ self._spec_drafter_kind = None+ self._dspark_sidecar_absent = Falseself._last_load_intent = Noneself._mtp_runtime_fallback_active = Falseself._hf_variant = Nonediff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex 3402e5c3ae8..5fc313cbfa1 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -209,7 +209,8 @@ _DEVICE_FLAGS: frozenset[str] = frozenset({"--device", "-dev", "--main-gpu", "-m# opt-in, not default. Layer flags are shared with llama_cpp's override# detection; the MoE flags are strip-only (manual's --n-cpu-moe slider owns them)._GPU_LAYER_FLAGS: frozenset[str] = frozenset({"-ngl", "--gpu-layers", "--n-gpu-layers"})-_LAYER_OFFLOAD_FLAGS: frozenset[str] = _GPU_LAYER_FLAGS | frozenset({"-fit", "--fit"})+_FIT_FLAGS: frozenset[str] = frozenset({"-fit", "--fit"})+_LAYER_OFFLOAD_FLAGS: frozenset[str] = _GPU_LAYER_FLAGS | _FIT_FLAGS_MOE_OFFLOAD_FLAGS: frozenset[str] = frozenset({"-ncmoe", "--n-cpu-moe", "-cmoe", "--cpu-moe"})_OFFLOAD_SHADOWING_FLAGS: frozenset[str] = _LAYER_OFFLOAD_FLAGS | _MOE_OFFLOAD_FLAGSdiff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex 3f8cd5f3081..fea34acc1a2 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -19,7 +19,7 @@ from hub.utils import inventory_scan as hf_cache_scanfrom hub.utils.gguf import (extract_quant_label,extract_quant_token,- is_mtp_only_drafter_path as _is_mtp_only_drafter_path,+ is_reclaimable_drafter_path as _is_reclaimable_drafter_path,)from hub.utils.hf_cache_state import (INCOMPLETE_SUFFIX,@@ -217,12 +217,11 @@ 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,- # Companions: mmproj and the MTP drafter -- downloaded with- # every variant, so the last variant's delete reclaims them.- # MTP only: DSpark is opt-in and in no variant plan, so Studio- # never fetched it and must not reclaim it.+ # Companions: mmproj and the drafters Studio downloads (MTP with+ # every variant, DSpark on opt-in). No main GGUF is left, so they+ # cannot be launched; reclaim them with the last variant.lambda name: _is_gguf_filename(name)- and (_is_mmproj_filename(name) or _is_mtp_only_drafter_path(name)),+ and (_is_mmproj_filename(name) or _is_reclaimable_drafter_path(name)),)for snap, _blob, name in companion_matches:try:diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex 6f8201fec43..6efcf465784 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -120,16 +120,20 @@ def is_mtp_drafter_path(path: str) -> bool:)-def is_mtp_only_drafter_path(path: str) -> bool:- """MTP drafters only, for the delete path rather than selection. Studio fetches- the root ``mtp-*.gguf`` with every variant, so a variant delete may reclaim it.- DSpark and DFlash are opt-in and in no variant plan, so sweeping them up would- destroy a file Studio never downloaded."""+def is_reclaimable_drafter_path(path: str) -> bool:+ """Drafters a repo's last-variant delete may reclaim: MTP, fetched with every+ variant, and DSpark, fetched on opt-in. Both are useless once no main GGUF is+ left, and companion filtering hides them from the variant menu, so leaving one+ behind is an invisible allocation (DSpark is ~11 GB). DFlash is excluded: the+ name doubles as a family a user picks for real weights."""p = path.replace("\\", "/").lower()if not p.endswith(".gguf"):return Falseparts = [segment for segment in p.split("/") if segment]- return parts[-1].startswith("mtp-") or "mtp" in parts[:-1]+ name, parents = parts[-1], parts[:-1]+ return any(name.startswith(f"{kind}-") for kind in _DRAFTER_DIR_KINDS) or any(+ kind in parents for kind in _DRAFTER_DIR_KINDS+ )def is_gguf_filename(filename: str) -> bool:diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 04b210b3c9c..d5d1ec65755 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -94,11 +94,14 @@ class LoadRequest(BaseModel):None,description = ("Speculative decoding mode for GGUF models. Canonical values: "- "'auto' (platform-aware: MTP on MTP GGUFs, ngram-mod fallback "- "for sub-3B), 'mtp' (force draft-mtp only on both GPU and CPU), "+ "'auto' (platform-aware: DSpark when the model ships a sidecar, "+ "else MTP on MTP GGUFs, ngram-mod fallback for sub-3B), "+ "'mtp' (force draft-mtp only on both GPU and CPU), "+ "'dspark' (force a draft-dspark sidecar), ""'ngram' (force ngram-mod only), 'mtp+ngram' (force ""ngram-mod+draft-mtp chain on both platforms), 'off' (disabled). ""Legacy values 'default' (-> auto), 'draft-mtp' (-> mtp), "+ "'draft-dspark' (-> dspark), ""'ngram-mod' (-> ngram), and 'ngram-simple' (kept as-is) are ""still accepted. Ignored for non-GGUF models."),@@ -108,11 +111,11 @@ class LoadRequest(BaseModel):ge = 1,le = 16,description = (- "Max draft tokens per step for MTP speculative decoding "+ "Max draft tokens per step for MTP or DSpark speculative decoding ""(--spec-draft-n-max). Defaults to 2 on GPU and 3 on CPU/Mac ""when unset (upstream-bench sweet spot for dense Qwen3.6 MTP ""quants). Only applied when speculative_type resolves to "- "'mtp' or 'mtp+ngram'."+ "'mtp', 'mtp+ngram', or 'dspark'."),)n_parallel: Optional[int] = Field(@@ -299,6 +302,21 @@ class ValidateModelRequest(BaseModel):"server-wide --parallel default."),)+ speculative_type: Optional[str] = Field(+ None,+ description = (+ "Speculative mode intended for the follow-up load. The estimate is "+ "mode-dependent -- the drafter it charges differs by kind, and a "+ "DSpark sidecar is ~11 GB -- so omitting it makes this preflight "+ "disagree with /load in both directions."+ ),+ )+ spec_draft_n_max: Optional[int] = Field(+ None,+ ge = 1,+ le = 16,+ description = "Draft depth intended for the follow-up load; sizes the draft KV.",+ )include_context_length: bool = Field(False,description = "Also read the native context length from the local GGUF header. "@@ -526,7 +544,7 @@ class _InferenceRuntimeFields(BaseModel):None,description = ("Canonical UI-facing requested speculative decoding mode "- "('auto' / 'mtp' / 'ngram' / 'mtp+ngram' / 'off' / "+ "('auto' / 'mtp' / 'dspark' / 'ngram' / 'mtp+ngram' / 'off' / ""'ngram-simple'), round-tripped from the original LoadRequest ""via _canonicalize_spec_mode. None when no model is loaded."),@@ -534,7 +552,7 @@ class _InferenceRuntimeFields(BaseModel):spec_draft_n_max: Optional[int] = Field(None,description = (- "Active --spec-draft-n-max for MTP speculative decoding, or "+ "Active --spec-draft-n-max for MTP or DSpark speculative decoding, or ""None when the platform default is in effect."),)@@ -686,20 +704,29 @@ class InferenceStatusResponse(_InferenceRuntimeFields):"False -> recommend `unsloth studio update`."),)+ spec_drafter_kind: Optional[str] = Field(+ None,+ description = (+ "Which drafter the resolution was about, 'mtp' or 'dspark'. Needed "+ "because Auto resolves the kind itself, so speculative_type still "+ "reads 'auto', and a fallback leaves the engaged type at 'default': "+ "neither still says which file the UI should tell the user to fix."+ ),+ )spec_fallback_reason: Optional[str] = Field(None,description = (- "Why MTP was disabled on the loaded model despite being requested "- "(auto on an MTP model, or forced mtp / mtp+ngram). "+ "Why a speculative drafter was disabled despite being requested. ""'binary_no_mtp' / 'binary_outdated' -> a newer prebuilt would ""re-enable it (show the update affordance); 'runtime_error' -> the ""current build could not run it; 'drafter_not_found' -> the model's "- "separate MTP drafter could not be resolved; 'mla_mtp_disabled' -> "+ "separate MTP or DSpark drafter could not be resolved; "+ "'mla_mtp_disabled' -> ""an Auto-mode policy downgrade: the model is MLA (GLM-5.2 et al.) ""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. "- "None when MTP engaged or was not requested."+ "None when the requested strategy engaged or was not requested."),)llama_cpp_prebuilt_stale: bool = Field(diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex a86e59b963c..266c6d954f8 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -17,7 +17,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Request, statusfrom fastapi.encoders import jsonable_encoderfrom fastapi.responses import StreamingResponse, JSONResponse, Responsefrom starlette.requests import ClientDisconnect-from typing import Any, Callable, List, NamedTuple, Optional, Union+from typing import Any, Callable, Collection, List, NamedTuple, Optional, Unionimport jsonimport httpxfrom loggers import get_logger@@ -1038,6 +1038,7 @@ try:from utils.models.model_config import (_local_gguf_companion_search_root,colocated_split_shards,+ detect_dspark_file,detect_mtp_file,load_model_defaults,)@@ -1088,6 +1089,7 @@ except ImportError:from utils.models.model_config import (_local_gguf_companion_search_root,colocated_split_shards,+ detect_dspark_file,detect_mtp_file,load_model_defaults,)@@ -3457,7 +3459,7 @@ def _validate_native_gguf_companion(gguf_path: str | None,label: str,*,- allow_mtp_subdir: bool = False,+ allowed_subdirs: Collection[str] = (),mtp_search_root: str | Path | None = None,) -> None:"""Reject a companion GGUF (mmproj / MTP drafter) that a native-lease load@@ -3487,12 +3489,12 @@ def _validate_native_gguf_companion(if not native_gguf_companion_parent_allowed(companion,gguf,- allow_mtp_subdir = allow_mtp_subdir,+ allowed_subdirs = allowed_subdirs,mtp_search_root = mtp_search_root,):location = (- "beside the selected GGUF or in its MTP directory"- if allow_mtp_subdir+ "beside the selected GGUF or in its companion directory"+ if allowed_subdirselse "next to the selected GGUF")raise HTTPException(@@ -3521,27 +3523,41 @@ def _loaded_is_local_model(return bool(model_id and is_local_path(model_id))+# Per-drafter-kind display label and the companion subdirectory a native load+# may reach into. Keyed by the kinds llama_cpp._drafter_path_kind reports.+_DRAFTER_NATIVE_RULES = {+ "mtp": ("MTP drafter", "mtp"),+ "dspark": ("DSpark drafter", "dspark"),+}++def _validate_native_mtp_drafter(companion_path: str | None,gguf_path: str | None,*,+ kind: str = "mtp",mtp_search_root: str | Path | None = None,) -> None:- """Validate an MTP drafter for a native load, every shard of it.+ """Validate a drafter for a native load, every shard of it.llama-server opens the sibling shards of a split drafter implicitly, sochecking only the launch path would let a later shard be a symlink out ofthe permitted directory without ever facing the native rules.++ ``kind`` selects the label and which companion subdirectory is in bounds;+ the kinds must not share one, or an MTP load would accept a sidecar out of+ ``dspark/`` and launch it as --model-draft."""if not companion_path or not gguf_path:return+ label, subdir = _DRAFTER_NATIVE_RULES[kind]shards, _ = colocated_split_shards(Path(companion_path))for shard in shards or [Path(companion_path)]:_validate_native_gguf_companion(str(shard),gguf_path,- "MTP drafter",- allow_mtp_subdir = True,+ label,+ allowed_subdirs = (subdir,),mtp_search_root = mtp_search_root,)@@ -3550,16 +3566,23 @@ def _native_gguf_companion_usable(companion_path: str | None,gguf_path: str | None,*,+ kind: str = "mtp",mtp_search_root: str | Path | None = None,log_rejection: bool = False,) -> bool:- """Whether a native load would accept this MTP drafter, as a predicate for+ """Whether a native load would accept this drafter, as a predicate forreload dedup. Same rules, so the two cannot disagree."""try:- _validate_native_mtp_drafter(companion_path, gguf_path, mtp_search_root = mtp_search_root)+ _validate_native_mtp_drafter(+ companion_path, gguf_path, kind = kind, mtp_search_root = mtp_search_root+ )except HTTPException as exc:if log_rejection:- logger.warning("Dropping MTP drafter for native load: %s", exc.detail)+ logger.warning(+ "Dropping %s for native load: %s",+ _DRAFTER_NATIVE_RULES[kind][0],+ exc.detail,+ )return Falsereturn True@@ -3702,14 +3725,22 @@ def _gguf_request_intent(return replace(source, **settings)-def _mtp_draft_for_path(+def _drafter_for_path(gguf_path: Optional[str],native_grant_backed: bool,*,+ kind: str = "mtp",log_native_fallback: bool = False,) -> Optional[str]:+ """The drafter of ``kind`` that pairs with a local GGUF, or None.++ A native-grant-backed load filters candidates through the native rules in+ preference order, so a root drafter it must reject still falls through to+ the in-bounds subdirectory copy instead of reading as no drafter at all.+ """if not gguf_path:return None+ detect = detect_dspark_file if kind == "dspark" else detect_mtp_fileroot = _local_gguf_companion_search_root(gguf_path, gguf_path)rejected = Falseaccept = None@@ -3720,22 +3751,48 @@ def _mtp_draft_for_path(usable = _native_gguf_companion_usable(candidate,gguf_path,+ kind = kind,mtp_search_root = root,log_rejection = log_native_fallback,)rejected |= not usablereturn usable- detected = detect_mtp_file(- gguf_path,- search_root = root,- accept = accept,- )+ detected = detect(gguf_path, search_root = root, accept = accept)if log_native_fallback and rejected and detected:- logger.info("Using MTP subdirectory drafter for native load: %s", detected)+ logger.info(+ "Using %s subdirectory drafter for native load: %s",+ _DRAFTER_NATIVE_RULES[kind][0],+ detected,+ )return detected+def _mtp_draft_for_path(+ gguf_path: Optional[str],+ native_grant_backed: bool,+ *,+ log_native_fallback: bool = False,+) -> Optional[str]:+ return _drafter_for_path(+ gguf_path, native_grant_backed, log_native_fallback = log_native_fallback+ )+++def _dspark_draft_for_path(+ gguf_path: Optional[str],+ native_grant_backed: bool,+ *,+ log_native_fallback: bool = False,+) -> Optional[str]:+ return _drafter_for_path(+ gguf_path,+ native_grant_backed,+ kind = "dspark",+ log_native_fallback = log_native_fallback,+ )++def _active_gguf_intent(request: LoadRequest,llama_backend: LlamaCppBackend,@@ -3779,6 +3836,7 @@ def _active_gguf_intent(llama_backend.layer_preserves_tensor_intent and not _is_explicit_tensor_drop(request)),mtp_draft_path = _mtp_draft_for_path(llama_backend.gguf_path, native_grant_backed),+ dspark_draft_path = _dspark_draft_for_path(llama_backend.gguf_path, native_grant_backed),compare_mtp_draft = True,extra_args_inherited = request.llama_extra_args is None,)@@ -4887,15 +4945,22 @@ def _effective_load_in_4bit(config: ModelConfig, requested: bool) -> bool:def _remote_gguf_companion_bytes(- repo: str, *, hf_token: Optional[str], include_mmproj: bool+ repo: str,+ *,+ hf_token: Optional[str],+ include_mmproj: bool,+ include_mtp: bool = True,+ include_dspark: bool = False,) -> int:- """Bytes of MTP/mmproj companion GGUFs llama-server auto-downloads. 0 on error,- so it can only add headroom, never refuse a load by itself."""+ """Bytes of companion GGUFs the requested launch downloads. 0 on error."""try:+ from core.inference.llama_cpp import _is_dspark_drafter_pathfrom huggingface_hub import model_info+ from utils.models.model_config import dspark_preference_keyinfo = model_info(repo, token = hf_token, files_metadata = True)total = 0+ dspark_candidates: list[tuple[str, int]] = []for sibling in info.siblings or []:name = sibling.rfilename or ""base = Path(name).name.lower()@@ -4904,8 +4969,14 @@ def _remote_gguf_companion_bytes(# Root-level mtp- only: -hf auto-fetches the repo-root drafter, not# the MTP/ subdir copies (which now share the mtp- prefix too).is_root_mtp = "/" not in name and base.startswith("mtp-")- if is_root_mtp or (include_mmproj and "mmproj" in base):+ if (include_mtp and is_root_mtp) or (include_mmproj and "mmproj" in base):total += getattr(sibling, "size", 0) or 0+ if include_dspark and _is_dspark_drafter_path(name):+ dspark_candidates.append((name, getattr(sibling, "size", 0) or 0))+ if dspark_candidates:+ # Same preference order the download uses, so the budget sizes the+ # file the launch will actually fetch.+ total += min(dspark_candidates, key = lambda c: dspark_preference_key(c[0]))[1]return totalexcept Exception as e:logger.warning(f"Could not size GGUF companions for {repo}: {e}")@@ -4985,6 +5056,7 @@ def _estimate_gguf_required_gb(hf_token: Optional[str] = None,max_seq_length: int = 0,llama_extra_args: Optional[list[str]] = None,+ speculative_type: Optional[str] = None,n_parallel: int = 1,cache_type_kv: Optional[str] = None,tensor_parallel: bool = False,@@ -4993,14 +5065,60 @@ def _estimate_gguf_required_gb(cache for local files (unreadable pre-download for remote). None when nothingresolves so the caller default-denies."""try:+ from core.inference.llama_cpp import (+ _canonicalize_spec_mode,+ _extra_args_requests_dspark,+ )++ _spec_mode = _canonicalize_spec_mode(speculative_type) or "auto"+ _forced_dspark = bool(+ _spec_mode == "dspark" or _extra_args_requests_dspark(llama_extra_args, env = {})+ )+ # Auto loads the sidecar whenever the model has one, so size it there too+ # or the guard admits a load 11 GB larger than it estimated.+ _auto_dspark = _spec_mode == "auto"+ _dspark_capable = True+ if _forced_dspark or _auto_dspark:+ # Gate on the same answer the loader uses: _download_dspark skips the+ # sidecar on a binary without usable draft-dspark, so charging its+ # ~11 GB here would refuse a load that never opens it. Probed for Auto+ # too, not just an explicit request: a remote config has no+ # gguf_dspark_file until the listing, so keying the probe on that would+ # leave the remote Auto charge ungated. An unreadable probe keeps the+ # sidecar counted, since this guard protects a running training job and+ # default-denies.+ try:+ _dspark_capable = bool(+ LlamaCppBackend.probe_server_capabilities().get("supports_dspark")+ )+ except Exception:+ pass+ dspark_requested = bool(+ _dspark_capable+ and (_forced_dspark or (_auto_dspark and getattr(config, "gguf_dspark_file", None)))+ )+ # Forced DSpark on a binary that cannot run it falls back to --spec-default,+ # which loads no drafter at all, so charging the MTP one would refuse a load+ # that fits. Auto is different: it falls through to the MTP branch, and keeps+ # its charge.+ _charge_no_drafter = _forced_dspark and not _dspark_capabletotal_bytes = 0main = getattr(config, "gguf_file", None)if main and Path(main).is_file():total_bytes += LlamaCppBackend._get_gguf_size_bytes(str(main))- for attr in ("gguf_mmproj_file", "gguf_mtp_file"):+ # Only the drafter the launch will load: the modes are exclusive, and a+ # 10 GB DSpark sidecar merely sitting on disk must not inflate the guard+ # for a load that never opens it.+ _sized_attrs = ["gguf_mmproj_file"]+ if not _charge_no_drafter:+ _sized_attrs.append("gguf_dspark_file" if dspark_requested else "gguf_mtp_file")+ for attr in _sized_attrs:f = getattr(config, attr, None)if f and Path(f).is_file():- total_bytes += Path(f).stat().st_size+ # Split-aware, like the main weight above: discovery hands back shard 1,+ # so stat() alone would size a split drafter at one shard and let the+ # guard admit a load that evicts the training run it protects.+ total_bytes += LlamaCppBackend._get_gguf_size_bytes(str(f))if total_bytes > 0:return total_bytes / (1024**3) + _estimate_gguf_kv_gb(main,@@ -5023,7 +5141,15 @@ def _estimate_gguf_required_gb(if main_bytes is None:return Nonecompanions = _remote_gguf_companion_bytes(- repo, hf_token = hf_token, include_mmproj = bool(has_vision)+ repo,+ hf_token = hf_token,+ include_mmproj = bool(has_vision),+ # Remote, so which sidecar the repo ships is unknown until the+ # listing. Under Auto size both: a repo has one kind or the other,+ # the absent one contributes 0, and over-estimating is the safe+ # direction for a guard that protects a running training job.+ include_mtp = (not _charge_no_drafter and (_auto_dspark or not dspark_requested)),+ include_dspark = (_dspark_capable and (_auto_dspark or dspark_requested)),)return (main_bytes + companions) / (1024**3)return None@@ -5311,11 +5437,18 @@ def _resolve_gguf_load_intent(True,log_native_fallback = True,)+ if config.gguf_dspark_file:+ config.gguf_dspark_file = _dspark_draft_for_path(+ config.gguf_file,+ True,+ log_native_fallback = True,+ )source = GgufLoadIntent(model_identifier = config.identifier,gguf_path = config.gguf_file,mmproj_path = config.gguf_mmproj_file,mtp_draft_path = config.gguf_mtp_file,+ dspark_draft_path = config.gguf_dspark_file,hf_variant = config.gguf_variant,)@@ -5484,6 +5617,7 @@ def _guard_chat_load_against_training(hf_token = request.hf_token,max_seq_length = request.max_seq_length,llama_extra_args = llama_extra_args,+ speculative_type = getattr(request, "speculative_type", None),n_parallel = n_parallel,cache_type_kv = request.cache_type_kv,tensor_parallel = (@@ -6266,6 +6400,7 @@ async def _load_model_impl(gguf_intent = replace(gguf_intent,mtp_draft_path = _mtp_draft_for_path(llama_backend.gguf_path, False),+ dspark_draft_path = _dspark_draft_for_path(llama_backend.gguf_path, False),compare_mtp_draft = True,)_effective_tensor = _effective_tensor_parallel(@@ -7861,6 +7996,7 @@ async def get_status(current_subject: str = Depends(get_current_subject)):requested_context_length = llama_backend.requested_n_ctx,llama_cpp_supports_mtp = _supports_mtp,spec_fallback_reason = llama_backend.spec_fallback_reason,+ spec_drafter_kind = llama_backend.spec_drafter_kind,llama_cpp_prebuilt_stale = _stale,llama_cpp_installed_tag = _installed_tag,llama_cpp_latest_tag = _latest_tag,diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.pyindex a1f047f0296..11a04aea22b 100644--- a/studio/backend/tests/test_chat_load_during_training.py+++ b/studio/backend/tests/test_chat_load_during_training.py@@ -1175,6 +1175,157 @@ class TestEstimateGgufRequiredGb(unittest.TestCase):gb = self.route._estimate_gguf_required_gb(cfg)self.assertAlmostEqual(gb, 3000 / (1024**3), places = 9) # both shards+ @staticmethod+ def _dspark_capable(supported = True):+ """The sizing gate asks the binary whether it can run draft-dspark, so the+ probe must be stubbed or these assertions track the host's llama.cpp."""+ from core.inference.llama_cpp import LlamaCppBackend+ return patch.object(+ LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(lambda cls, binary = None: {"supports_dspark": supported}),+ )++ def test_local_dspark_sidecar_is_only_counted_when_requested(self):+ import tempfile++ with tempfile.TemporaryDirectory() as d:+ p = Path(d)+ target = p / "model.gguf"+ sidecar = p / "dspark-model-Q8_0.gguf"+ target.write_bytes(b"x" * 2000)+ sidecar.write_bytes(b"y" * 3000)+ cfg = SimpleNamespace(+ gguf_file = str(target),+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = str(sidecar),+ gguf_hf_repo = None,+ gguf_variant = None,+ )+ with (+ patch.object(self.route, "_estimate_gguf_kv_gb", return_value = 0.0),+ self._dspark_capable(),+ ):+ off_gb = self.route._estimate_gguf_required_gb(+ cfg,+ speculative_type = "off",+ )+ dspark_gb = self.route._estimate_gguf_required_gb(+ cfg,+ speculative_type = "dspark",+ )+ extras_gb = self.route._estimate_gguf_required_gb(+ cfg,+ speculative_type = "off",+ llama_extra_args = ["--spec-type", "draft-dspark"],+ )+ self.assertAlmostEqual(off_gb, 2000 / (1024**3), places = 9)+ self.assertAlmostEqual(dspark_gb, 5000 / (1024**3), places = 9)+ self.assertAlmostEqual(extras_gb, 5000 / (1024**3), places = 9)++ def test_forced_dspark_on_an_incapable_binary_charges_no_drafter_at_all(self):+ """The loader's DSpark branch falls back to --spec-default, which loads no+ drafter, so charging the MTP one would refuse a load that fits. Auto is+ different: it falls through to the MTP branch and keeps that charge."""+ import tempfile++ with tempfile.TemporaryDirectory() as d:+ p = Path(d)+ target = p / "model.gguf"+ mtp = p / "mtp-model.gguf"+ target.write_bytes(b"x" * 2000)+ mtp.write_bytes(b"y" * 3000)+ cfg = SimpleNamespace(+ gguf_file = str(target),+ gguf_mmproj_file = None,+ gguf_mtp_file = str(mtp),+ gguf_dspark_file = None,+ gguf_hf_repo = None,+ gguf_variant = None,+ )+ with (+ patch.object(self.route, "_estimate_gguf_kv_gb", return_value = 0.0),+ self._dspark_capable(False),+ ):+ forced = self.route._estimate_gguf_required_gb(cfg, speculative_type = "dspark")+ auto = self.route._estimate_gguf_required_gb(cfg, speculative_type = "auto")+ self.assertAlmostEqual(forced, 2000 / (1024**3), places = 9)+ self.assertAlmostEqual(auto, 5000 / (1024**3), places = 9)++ def test_validate_request_carries_the_mode_the_load_will_use(self):+ """The estimate is mode-dependent, so /validate must be told the mode or+ its verdict disagrees with the /load that follows it: a user with+ speculative decoding off and a sidecar on disk would be refused at the+ preflight for a load that would have been admitted."""+ from models.inference import ValidateModelRequest++ req = ValidateModelRequest(+ model_path = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ speculative_type = "off",+ spec_draft_n_max = 3,+ )+ self.assertEqual(req.speculative_type, "off")+ self.assertEqual(req.spec_draft_n_max, 3)+ # Omitted stays None rather than defaulting to a mode, so the estimate+ # keeps its previous behaviour for callers that do not send it.+ self.assertIsNone(ValidateModelRequest(model_path = "org/repo").speculative_type)++ def test_dspark_sidecar_is_not_charged_to_a_binary_that_cannot_run_it(self):+ """The loader skips the ~11 GB fetch when llama.cpp has no usable+ draft-dspark, so charging it here would refuse a load that never opens it+ and would evict nothing."""+ import tempfile++ with tempfile.TemporaryDirectory() as d:+ p = Path(d)+ target = p / "model.gguf"+ sidecar = p / "dspark-model-Q8_0.gguf"+ target.write_bytes(b"x" * 2000)+ sidecar.write_bytes(b"y" * 3000)+ cfg = SimpleNamespace(+ gguf_file = str(target),+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = str(sidecar),+ gguf_hf_repo = None,+ gguf_variant = None,+ )+ with patch.object(self.route, "_estimate_gguf_kv_gb", return_value = 0.0):+ with self._dspark_capable(False):+ incapable = self.route._estimate_gguf_required_gb(+ cfg, speculative_type = "dspark"+ )+ with self._dspark_capable(True):+ capable = self.route._estimate_gguf_required_gb(cfg, speculative_type = "dspark")+ self.assertAlmostEqual(incapable, 2000 / (1024**3), places = 9)+ self.assertAlmostEqual(capable, 5000 / (1024**3), places = 9)++ def test_split_dspark_sidecar_counts_every_shard(self):+ """Discovery hands back shard 1, so sizing it with stat() alone would let the+ guard admit a load that evicts the training run it exists to protect."""+ import tempfile++ with tempfile.TemporaryDirectory() as d:+ p = Path(d)+ target = p / "model.gguf"+ target.write_bytes(b"x" * 2000)+ shard1 = p / "dspark-model-Q8_0-00001-of-00002.gguf"+ shard1.write_bytes(b"y" * 3000)+ (p / "dspark-model-Q8_0-00002-of-00002.gguf").write_bytes(b"z" * 4000)+ cfg = SimpleNamespace(+ gguf_file = str(target),+ gguf_mmproj_file = None,+ gguf_mtp_file = None,+ gguf_dspark_file = str(shard1),+ gguf_hf_repo = None,+ gguf_variant = None,+ )+ with patch.object(self.route, "_estimate_gguf_kv_gb", return_value = 0.0):+ with self._dspark_capable():+ gb = self.route._estimate_gguf_required_gb(cfg, speculative_type = "dspark")+ self.assertAlmostEqual(gb, 9000 / (1024**3), places = 9) # 2000 + 3000 + 4000+def test_remote_threads_token_and_adds_companions(self):import utils.models.model_config as mc@@ -1197,11 +1348,49 @@ class TestEstimateGgufRequiredGb(unittest.TestCase):patch.object(self.route, "_remote_gguf_companion_bytes", return_value = 2 * 1024**3) as comp,+ self._dspark_capable(),):- gb = self.route._estimate_gguf_required_gb(cfg, hf_token = "tok")+ gb = self.route._estimate_gguf_required_gb(+ cfg,+ hf_token = "tok",+ speculative_type = "dspark",+ )self.assertEqual(captured["token"], "tok") # token threaded for gated reposself.assertAlmostEqual(gb, 12.0, places = 6) # 10 GB variant + 2 GB companionsself.assertTrue(comp.call_args.kwargs["include_mmproj"])+ self.assertFalse(comp.call_args.kwargs["include_mtp"])+ self.assertTrue(comp.call_args.kwargs["include_dspark"])++ def test_remote_companions_choose_preferred_dspark_sidecar(self):+ siblings = [+ SimpleNamespace(rfilename = "mtp-model.gguf", size = 100),+ SimpleNamespace(rfilename = "dspark/dspark-model-BF16.gguf", size = 300),+ SimpleNamespace(rfilename = "dspark/dspark-model-Q8_0.gguf", size = 200),+ SimpleNamespace(rfilename = "dflash-model-Q8_0.gguf", size = 400),+ ]+ with patch(+ "huggingface_hub.model_info",+ return_value = SimpleNamespace(siblings = siblings),+ ):+ total = self.route._remote_gguf_companion_bytes(+ "org/repo",+ hf_token = "tok",+ include_mmproj = False,+ include_dspark = True,+ )+ self.assertEqual(total, 300) # root MTP plus the preferred Q8_0 DSpark file+ with patch(+ "huggingface_hub.model_info",+ return_value = SimpleNamespace(siblings = siblings),+ ):+ dspark_only = self.route._remote_gguf_companion_bytes(+ "org/repo",+ hf_token = "tok",+ include_mmproj = False,+ include_mtp = False,+ include_dspark = True,+ )+ self.assertEqual(dspark_only, 200)def test_remote_unknown_variant_returns_none(self):import utils.models.model_config as mcdiff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.pyindex 2e5ba946578..9b23441c391 100644--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py@@ -325,6 +325,119 @@ def test_already_in_target_state_auto_request_matches_auto_backend_for_non_mtp_m)+def test_forced_dspark_without_a_sidecar_stops_reloading():+ """drafter_not_found covers both "the fetch failed" and "this repo publishes+ none". The second is the permanent state of every repo but one, so retrying+ it relaunched an identical server on every Apply."""+ backend = _mtp_backend(+ _model_identifier = "unsloth/Qwen3-7B-GGUF",+ _speculative_type = "default",+ _requested_spec_mode = "dspark",+ _spec_fallback_reason = "drafter_not_found",+ _spec_drafter_kind = "dspark",+ _dspark_sidecar_absent = True,+ )+ assert (+ _matches(+ backend,+ gguf_path = None,+ model_identifier = "unsloth/Qwen3-7B-GGUF",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = "dspark",+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ )+ is True+ )+++def test_forced_dspark_retries_when_the_fetch_failed_rather_than_the_repo():+ """The other half: the repo does publish a sidecar and the download failed, so+ the next Apply should reload and re-run _download_dspark."""+ backend = _mtp_backend(+ _model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ _speculative_type = "default",+ _requested_spec_mode = "dspark",+ _spec_fallback_reason = "drafter_not_found",+ _spec_drafter_kind = "dspark",+ _dspark_sidecar_absent = False,+ )+ assert (+ _matches(+ backend,+ gguf_path = None,+ model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = "dspark",+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ )+ is False+ )+++def test_mtp_without_a_drafter_still_reloads_to_retry_the_fetch():+ """Negative control for the above: the MTP retry must survive."""+ backend = _mtp_backend(+ _model_identifier = "unsloth/gemma-4-12b-it-GGUF",+ _speculative_type = "default",+ _requested_spec_mode = "mtp",+ _spec_fallback_reason = "drafter_not_found",+ _spec_drafter_kind = "mtp",+ )+ assert (+ _matches(+ backend,+ gguf_path = None,+ model_identifier = "unsloth/gemma-4-12b-it-GGUF",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = "mtp",+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ )+ is False+ )+++def test_auto_resolved_dspark_reuses_its_server_instead_of_reloading(tmp_path):+ """Auto keeps arriving as "auto" while the launch stored the DSpark sidecar in+ the drafter field. Comparing the MTP field (None for these repos) against it+ would tear down and relaunch an identical server on every Apply."""+ sidecar = tmp_path / "dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"+ sidecar.write_bytes(b"draft")+ backend = _mtp_backend(+ _model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ _speculative_type = "draft-dspark",+ _mtp_draft_path = str(sidecar),+ )+ assert (+ _matches(+ backend,+ gguf_path = None,+ model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ cache_type_kv = None,+ speculative_type = None,+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ dspark_draft_path = str(sidecar),+ compare_mtp_draft = True,+ )+ is True+ )++def test_already_in_target_state_explicit_off_still_mismatches_mtp_backend():backend = _mtp_backend()assert (@@ -682,6 +795,43 @@ def test_probe_server_capabilities_detects_draft_mtp(tmp_path):assert caps["supports_mtp"] is True+@_NEEDS_BASH+def test_probe_server_capabilities_detects_dspark(tmp_path):+ fake = _make_fake_llama_server(+ tmp_path / "llama-server",+ "--spec-type none,draft-mtp,draft-dspark,ngram-mod",+ )+ _clear_caps_cache()+ caps = LlamaCppBackend.probe_server_capabilities(str(fake))+ assert caps["supports_dspark"] is True+++@_NEEDS_BASH+def test_probe_server_capabilities_gates_known_broken_dspark_prebuilt(tmp_path, monkeypatch):+ fake = _make_fake_llama_server(+ tmp_path / "llama-server",+ "--spec-type none,draft-mtp,draft-dspark,ngram-mod",+ )+ monkeypatch.setattr(+ "utils.llama_cpp_freshness.read_install_marker",+ lambda _binary: {"release_tag": "b10265-mix-89aa77b"},+ )+ _clear_caps_cache()+ caps = LlamaCppBackend.probe_server_capabilities(str(fake))+ assert caps["supports_dspark"] is False+ assert caps["supports_mtp"] is True+++def test_dspark_release_gate_covers_the_whole_broken_window():+ """Every prebuilt between the llama.cpp#26531 reshape regression and its #26577 fix+ aborts on a DSpark load, not only the b10265 one that was first seen."""+ broken = LlamaCppBackend._dspark_release_is_broken+ assert broken("b10259-mix-abc1234") and broken("b10268-mix-abc1234")+ assert not broken("b10258-mix-abc1234")+ assert not broken("b10269-mix-abc1234")+ assert not broken(None) and not broken("")++@_NEEDS_BASHdef test_probe_server_capabilities_uses_binary_library_env(tmp_path, monkeypatch):fake = _make_fake_llama_server(@@ -1282,6 +1432,7 @@ def test_backfill_usage_from_timings_passthrough_when_timings_empty():# New canonical values pass through unchanged.("auto", "auto"),("mtp", "mtp"),+ ("dspark", "dspark"),("ngram", "ngram"),("mtp+ngram", "mtp+ngram"),("off", "off"),@@ -1289,6 +1440,7 @@ def test_backfill_usage_from_timings_passthrough_when_timings_empty():# Legacy wire values map onto the new vocabulary.("default", "auto"),("draft-mtp", "mtp"),+ ("draft-dspark", "dspark"),("ngram-mod", "ngram"),# Comma-chained legacy values (e.g. from persisted state) collapse# to the right canonical mode.@@ -1330,6 +1482,7 @@ def _resolver_backend("found": True,"mtp_token": mtp_token,"supports_mtp": bool(mtp_token),+ "supports_dspark": True,"mtp_probe_inconclusive": mtp_probe_inconclusive,"ngram_mod_flavor": "new" if ngram_supported else None,"supports_ngram_mod": bool(ngram_supported),@@ -1457,7 +1610,205 @@ def test_build_speculative_flags_user_extra_args_owns_spec_type(monkeypatch):assert backend.speculative_type is None[email protected]("mode", ["auto", "mtp", "ngram", "mtp+ngram", "off"])+def test_build_speculative_flags_dspark_requires_sidecar_and_leaves_fit_to_placement(+ monkeypatch, tmp_path+):+ backend = _resolver_backend(monkeypatch)+ sidecar = tmp_path / "dspark-model-Q8_0.gguf"+ sidecar.write_bytes(b"draft")+ flags = backend._build_speculative_flags(+ speculative_type = "dspark",+ spec_draft_n_max = None,+ extra_args = None,+ model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ model_path = None,+ gpus = True,+ binary = "/fake/llama-server",+ dspark_draft_path = str(sidecar),+ )+ parsed = _flags_dict(flags)+ assert "--fit" not in parsed+ assert parsed["--model-draft"] == str(sidecar)+ assert parsed["--spec-type"] == "draft-dspark"+ assert parsed["--spec-draft-n-max"] == "3"+++def test_build_speculative_flags_dspark_missing_sidecar_falls_back(monkeypatch):+ backend = _resolver_backend(monkeypatch)+ flags = backend._build_speculative_flags(+ speculative_type = "dspark",+ spec_draft_n_max = None,+ extra_args = None,+ model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ model_path = None,+ gpus = True,+ binary = "/fake/llama-server",+ )+ assert flags == ["--spec-default"]+ assert backend.spec_fallback_reason == "drafter_not_found"+++def test_build_speculative_flags_dspark_blames_the_binary_not_the_missing_sidecar(monkeypatch):+ """The sidecar fetch is gated on the same supports_dspark answer, so on a+ binary that cannot run DSpark the sidecar is legitimately absent. Reporting+ drafter_not_found would tell the user to place a file that is not the problem,+ and would reload the server on every Apply via the drafter_not_found dedup."""+ backend = _resolver_backend(monkeypatch)+ caps = LlamaCppBackend.probe_server_capabilities()+ caps["supports_dspark"] = False+ flags = backend._build_speculative_flags(+ speculative_type = "dspark",+ spec_draft_n_max = None,+ extra_args = None,+ model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ model_path = None,+ gpus = True,+ binary = "/fake/llama-server",+ dspark_draft_path = None,+ )+ assert flags == ["--spec-default"]+ assert backend.spec_fallback_reason == "binary_no_mtp"+++# ── Auto defaults to DSpark, and only where a sidecar actually exists ──+#+# The three shapes are the real published repos, checked against the Hub:+# unsloth/DeepSeek-V4-Flash-0731-GGUF -> dspark-*.gguf at the root and in dspark/+# unsloth/gemma-4-12b-it-GGUF -> MTP/mtp-gemma-4-12b-it-*.gguf, no dspark+# unsloth/Qwen3.5-4B-MTP-GGUF -> head baked into the main GGUF, neither file+++def test_auto_defaults_to_dspark_when_a_sidecar_is_available(monkeypatch, tmp_path):+ """DSpark beats every other Auto outcome for this architecture, and without it+ these models fall through to --spec-default, i.e. no drafter at all."""+ backend = _resolver_backend(monkeypatch)+ sidecar = tmp_path / "dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"+ sidecar.write_bytes(b"draft")+ flags = backend._build_speculative_flags(+ speculative_type = "auto",+ spec_draft_n_max = None,+ extra_args = None,+ model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ model_path = None,+ gpus = True,+ binary = "/fake/llama-server",+ dspark_draft_path = str(sidecar),+ )+ parsed = _flags_dict(flags)+ assert parsed["--spec-type"] == "draft-dspark"+ assert parsed["--model-draft"] == str(sidecar)+ assert parsed["--spec-draft-n-max"] == "3"+ assert backend.spec_fallback_reason is None+ # The request stays "auto": rewriting it would make the reuse check compare+ # "dspark" against a caller that keeps sending "auto" and reload every Apply.+ assert backend.requested_spec_mode == "auto"+++def test_auto_keeps_mtp_for_a_separate_drafter_model(monkeypatch, tmp_path):+ """gemma-4-12b-it ships MTP/mtp-*.gguf and no dspark sidecar, so the DSpark+ branch must not intercept it."""+ backend = _resolver_backend(monkeypatch)+ drafter = tmp_path / "mtp-gemma-4-12b-it-Q8_0.gguf"+ drafter.write_bytes(b"draft")+ flags = backend._build_speculative_flags(+ speculative_type = "auto",+ spec_draft_n_max = None,+ extra_args = None,+ model_identifier = "unsloth/gemma-4-12b-it-GGUF",+ model_path = None,+ gpus = True,+ binary = "/fake/llama-server",+ mtp_draft_path = str(drafter),+ dspark_draft_path = None,+ )+ parsed = _flags_dict(flags)+ assert parsed["--spec-type"] == "draft-mtp"+ assert parsed["--model-draft"] == str(drafter)+ assert backend.spec_fallback_reason is None+++def test_auto_keeps_embedded_mtp(monkeypatch):+ """Qwen3.5-4B-MTP bakes the head into the main GGUF: no separate file of+ either kind, so Auto must still emit MTP."""+ backend = _resolver_backend(monkeypatch)+ backend._nextn_predict_layers = 1+ flags = backend._build_speculative_flags(+ speculative_type = "auto",+ spec_draft_n_max = None,+ extra_args = None,+ model_identifier = "unsloth/Qwen3.5-4B-MTP-GGUF",+ model_path = None,+ gpus = True,+ binary = "/fake/llama-server",+ dspark_draft_path = None,+ )+ parsed = _flags_dict(flags)+ assert parsed["--spec-type"] == "draft-mtp"+ assert backend.spec_fallback_reason is None+++def test_auto_does_not_promote_dspark_on_a_binary_that_cannot_run_it(monkeypatch, tmp_path):+ """_download_dspark still reports a cached sidecar an incapable binary cannot+ launch. Promoting there would turn Auto's fallback into no speculation at all,+ so the promotion is capability-gated and this model keeps its ngram-mod path."""+ backend = _resolver_backend(monkeypatch)+ monkeypatch.setattr(+ LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(+ lambda cls, binary = None: {+ "found": True,+ "mtp_token": "draft-mtp",+ "supports_mtp": True,+ "supports_dspark": False,+ "mtp_probe_inconclusive": False,+ "ngram_mod_flavor": "new",+ "supports_ngram_mod": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ }+ ),+ )+ sidecar = tmp_path / "dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"+ sidecar.write_bytes(b"draft")+ flags = backend._build_speculative_flags(+ speculative_type = "auto",+ spec_draft_n_max = None,+ extra_args = None,+ model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ model_path = None,+ gpus = True,+ binary = "/fake/llama-server",+ dspark_draft_path = str(sidecar),+ )+ assert "draft-dspark" not in _flags_dict(flags).get("--spec-type", "")+ assert backend.speculative_type != "draft-dspark"+++def test_build_speculative_flags_dspark_engages_under_auto_fit(monkeypatch, tmp_path):+ """--fit on is not a blocker. The sidecar borrows the target's token_embd and+ output, so llama.cpp's fit step cannot build a standalone draft context to+ measure it and skips the reserve; the load itself still gets the drafter."""+ backend = _resolver_backend(monkeypatch)+ sidecar = tmp_path / "dspark-model-Q8_0.gguf"+ sidecar.write_bytes(b"draft")+ flags = backend._build_speculative_flags(+ speculative_type = "dspark",+ spec_draft_n_max = None,+ extra_args = None,+ model_identifier = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ model_path = None,+ gpus = True,+ binary = "/fake/llama-server",+ dspark_draft_path = str(sidecar),+ dspark_fit_sized = False,+ )+ assert flags[flags.index("--spec-type") + 1] == "draft-dspark"+ assert flags[flags.index("--model-draft") + 1] == str(sidecar)+ assert backend.speculative_type == "draft-dspark"+ assert backend.spec_fallback_reason is None++[email protected]("mode", ["auto", "mtp", "dspark", "ngram", "mtp+ngram", "off"])def test_build_speculative_flags_round_trips_requested_mode(monkeypatch, mode):# The status round-trip is the contract that lets the UI dropdown# restore its picked value after reload / refresh.diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.pyindex ddfbf360c85..bedfabda2cc 100644--- a/studio/backend/tests/test_llama_cpp_placement.py+++ b/studio/backend/tests/test_llama_cpp_placement.py@@ -205,6 +205,87 @@ def test_vulkan_fit_and_mtp_drafter_follow_placement_owner(assert ("-dev=Vulkan0" in cmd) is user_device_survives[email protected]("use_fit", [False, True])+def test_dspark_composed_argv_respects_placement_fit_decision(tmp_path, use_fit):+ backend, gguf = _backend(+ tmp_path,+ vulkan = False,+ memory = [(0, 24_000, 24_000)],+ )+ 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.probe_server_capabilities = lambda _binary = None: {+ "supports_dspark": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ }++ result = _launch(+ backend,+ gguf,+ dspark_draft_path = str(sidecar),+ speculative_type = "dspark",+ )++ cmd = result["cmd"]+ assert cmd.count("--fit") == 1+ assert cmd[cmd.index("--fit") + 1] == ("on" if use_fit else "off")+ # DSpark engages under either placement: --fit on only means llama.cpp skips+ # the sidecar's memory reserve, it does not refuse to load it.+ assert cmd[cmd.index("--model-draft") + 1] == str(sidecar)+ assert cmd[cmd.index("--spec-type") + 1] == "draft-dspark"+ assert backend.spec_fallback_reason is None+++def test_dspark_keeps_a_user_fit_flag(tmp_path):+ """A caller's --fit is theirs to set: the sidecar loads under either value,+ so Studio has no reason to rewrite it."""+ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 24_000, 24_000)])+ sidecar = tmp_path / "dspark-model-Q8_0.gguf"+ sidecar.write_bytes(b"draft")+ backend._select_gpus = lambda *args, **kwargs: ([0], False)+ backend.probe_server_capabilities = lambda _binary = None: {+ "supports_dspark": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ }++ result = _launch(+ backend,+ gguf,+ dspark_draft_path = str(sidecar),+ speculative_type = "dspark",+ extra_args = ["--fit", "on", "--top-k", "5"],+ gpu_ids = [0],+ )++ cmd = result["cmd"]+ assert cmd[len(cmd) - 1 - cmd[::-1].index("--fit") + 1] == "on"+ assert cmd[cmd.index("--top-k") + 1] == "5"+ assert cmd[cmd.index("--spec-type") + 1] == "draft-dspark"+++def test_pass_through_dspark_loads_under_an_auto_fit_placement(tmp_path):+ """Manual + Auto layers emits --fit on and a user-owned --spec-type returns+ from _build_speculative_flags early. Nothing rewrites the placement: llama.cpp+ only skips the sidecar's memory reserve under fitting, it still loads it."""+ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 24_000, 24_000)])+ sidecar = tmp_path / "dspark-model-Q8_0.gguf"+ sidecar.write_bytes(b"draft")++ result = _launch(+ backend,+ gguf,+ gpu_memory_mode = "manual",+ gpu_layers = -1,+ extra_args = ["--spec-type", "draft-dspark", "--model-draft", str(sidecar)],+ )++ cmd = result["cmd"]+ assert cmd.count("--fit") == 1+ assert cmd[cmd.index("--fit") + 1] == "on"+ assert cmd[cmd.index("--spec-type") + 1] == "draft-dspark"++def test_cuda_selection_uses_visibility_and_removes_environment_placement(tmp_path, monkeypatch):monkeypatch.setenv("LLAMA_ARG_DEVICE", "CUDA0")monkeypatch.setenv("LLAMA_ARG_MAIN_GPU", "0")diff --git a/studio/backend/tests/test_metal_paravirtual_guard.py b/studio/backend/tests/test_metal_paravirtual_guard.pyindex a7be06b8b32..a59358d70f6 100644--- a/studio/backend/tests/test_metal_paravirtual_guard.py+++ b/studio/backend/tests/test_metal_paravirtual_guard.py@@ -1314,15 +1314,19 @@ def test_the_mtp_fallback_gets_the_requested_slots_back():def test_the_startup_retry_drops_the_mtp_the_extras_and_the_env_carry():- """A trailing --spec-default cannot override MTP that extras or the env supplied:- llama.cpp applies the env first and appends types rather than replacing them, so the- retry would relaunch the mode that just failed and lose a main model that loads fine- without it. It strips the spec group, and takes the child env with it."""+ """A trailing --spec-default cannot override MTP or DSpark that extras or the env+ supplied: llama.cpp applies the env first and appends types rather than replacing+ them, so the retry would relaunch the mode that just failed and lose a main model+ that loads fine without it. It strips the spec group, and takes the child env with+ it."""src = _load_model_source()retry = src[src.index("_fb_tail = cmd[_spec_start") : src.index("fallback_cmd = cmd[:_spec_start]")]- assert "_extra_args_requests_mtp(extra_args, env = _launch_spec_env)" in retry+ # Whitespace-insensitive: the guard wraps across lines once both drafters are named.+ compact = "".join(retry.split())+ assert "_extra_args_requests_mtp(extra_args,env=_launch_spec_env)" in compact+ assert "_extra_args_requests_dspark(extra_args,env=_launch_spec_env)" in compactassert "strip_spec = True" in retryassert "env.pop(_fb_spec_var, None)" in retry# ...and that strip really removes the group rather than shadowing it.diff --git a/studio/backend/tests/test_mtp_drafter_companion.py b/studio/backend/tests/test_mtp_drafter_companion.pyindex a22a7c0053d..5d02c60cdac 100644--- a/studio/backend/tests/test_mtp_drafter_companion.py+++ b/studio/backend/tests/test_mtp_drafter_companion.py@@ -36,6 +36,7 @@ from utils.models.model_config import (_is_mtp_drafter,_local_gguf_companion_search_root,detect_gguf_model,+ detect_dspark_file,detect_mtp_file,extract_model_size_b,list_local_gguf_variants,@@ -190,6 +191,109 @@ def test_detect_mtp_file_none_without_sibling(tmp_path):assert detect_mtp_file(str(tmp_path / "model-Q4_K_M.gguf")) is None+def test_detect_dspark_file_prefers_matching_q8_sidecar(tmp_path):+ weight = tmp_path / "DeepSeek-V4-Flash-0731-UD-Q4_K_M.gguf"+ weight.write_bytes(b"target")+ folder = tmp_path / "dspark"+ folder.mkdir()+ q8 = folder / "dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"+ q8.write_bytes(b"q8")+ (folder / "dspark-Other-Model-Q8_0.gguf").write_bytes(b"foreign")++ assert detect_dspark_file(str(weight)) == str(q8.resolve())+++def test_detect_dspark_file_accepts_the_suffix_naming_scheme(tmp_path):+ """``<model>-dspark.gguf`` pairs too, the same second scheme MTP accepts."""+ weight = tmp_path / "model-Q4_K_M.gguf"+ weight.write_bytes(b"target")+ folder = tmp_path / "dspark"+ folder.mkdir()+ sidecar = folder / "model-Q8_0-dspark.gguf"+ sidecar.write_bytes(b"draft")++ assert detect_dspark_file(str(weight)) == str(sidecar.resolve())+++def test_detect_dspark_file_rejects_a_weight_copy_in_the_dspark_folder(tmp_path):+ """A published drafter NAME is required even inside ``dspark/``: a weight+ copy parked there would otherwise launch as --model-draft."""+ weight = tmp_path / "model-Q4_K_M.gguf"+ weight.write_bytes(b"target")+ folder = tmp_path / "dspark"+ folder.mkdir()+ (folder / "model-Q8_0.gguf").write_bytes(b"a full weight, not a sidecar")++ assert detect_dspark_file(str(weight)) is None+++def test_detect_dspark_file_does_not_cross_attach_a_sibling_family(tmp_path):+ """A folder holding a model and its "-Lite" sibling must not pair across+ them: the family has to prefix the weight at a non-alphanumeric boundary."""+ base = tmp_path / "DeepSeek-V4-Flash-Q4_K_M.gguf"+ base.write_bytes(b"target")+ lite_sidecar = tmp_path / "dspark-DeepSeek-V4-Flash-Lite-Q8_0.gguf"+ lite_sidecar.write_bytes(b"foreign")++ assert detect_dspark_file(str(base)) is None++ own = tmp_path / "dspark-DeepSeek-V4-Flash-Q8_0.gguf"+ own.write_bytes(b"mine")+ assert detect_dspark_file(str(base)) == str(own.resolve())+++def test_detect_dspark_file_skips_an_incomplete_split_set(tmp_path):+ """A partial split would fail llama-server's draft startup and disable+ speculation, so a complete lower-precision copy wins instead."""+ weight = tmp_path / "model-Q4_K_M.gguf"+ weight.write_bytes(b"target")+ (tmp_path / "dspark-model-Q8_0-00001-of-00002.gguf").write_bytes(b"x")+ complete = tmp_path / "dspark-model-BF16.gguf"+ complete.write_bytes(b"x")++ assert detect_dspark_file(str(weight)) == str(complete.resolve())+++def test_detect_dspark_file_sums_shards_so_a_split_cannot_outrank_a_smaller_copy(tmp_path):+ """Candidates are collapsed to shard 1, so size must be summed across the+ set or a large split copy outranks a smaller single file at equal precision."""+ weight = tmp_path / "model-Q4_K_M.gguf"+ weight.write_bytes(b"target")+ folder = tmp_path / "dspark"+ folder.mkdir()+ for shard in (1, 2):+ (folder / f"dspark-model-Q8_0-0000{shard}-of-00002.gguf").write_bytes(b"x" * 4000)+ single = tmp_path / "dspark-model-Q8_0.gguf"+ single.write_bytes(b"x" * 5000)++ assert detect_dspark_file(str(weight)) == str(single.resolve())+++def test_detect_dspark_file_keeps_a_split_sidecar_on_its_snapshot_path(tmp_path):+ """llama-server opens the sibling shards implicitly, and the blob target of+ a cache symlink has no sibling shard names, so a split must NOT resolve."""+ blobs = tmp_path / "blobs"+ snapshot = tmp_path / "snapshots" / "abc"+ blobs.mkdir()+ snapshot.mkdir(parents = True)+ weight = snapshot / "model-Q4_K_M.gguf"+ weight.write_bytes(b"target")++ first = snapshot / "dspark-model-Q8_0-00001-of-00002.gguf"+ second = snapshot / "dspark-model-Q8_0-00002-of-00002.gguf"+ (blobs / "sha_1").write_bytes(b"d" * 4096)+ (blobs / "sha_2").write_bytes(b"d")+ try:+ first.symlink_to(blobs / "sha_1")+ second.symlink_to(blobs / "sha_2")+ except OSError:+ pytest.skip("symlinks unavailable")++ found = detect_dspark_file(str(weight), str(snapshot))+ assert found == str(first)+ assert (Path(found).parent / second.name).exists()++def test_detect_gguf_model_rejects_drafter_file(tmp_path):drafter = tmp_path / "mtp-model.gguf"drafter.write_bytes(b"x")@@ -356,7 +460,7 @@ def test_native_companion_parent_accepts_root_and_mtp_subdir(tmp_path):nested_drafter.write_bytes(b"x")assert native_gguf_companion_parent_allowed(root_drafter, weight)- assert native_gguf_companion_parent_allowed(nested_drafter, weight, allow_mtp_subdir = True)+ assert native_gguf_companion_parent_allowed(nested_drafter, weight, allowed_subdirs = ("mtp",))def test_native_companion_parent_rejects_other_nested_directory(tmp_path):@@ -385,7 +489,7 @@ def test_native_companion_parent_rejects_mtp_symlink_escape(tmp_path):pytest.skip(f"symlinks unavailable: {exc}")assert not native_gguf_companion_parent_allowed(- model_dir / "MTP" / drafter.name, weight, allow_mtp_subdir = True+ model_dir / "MTP" / drafter.name, weight, allowed_subdirs = ("mtp",))@@ -712,6 +816,123 @@ def test_download_mtp_online_skips_cache_reuse(tmp_path, monkeypatch):assert reached.get("hit") is True+# ── DSpark sidecar fetch is gated on the binary that would launch it ──+++def _dspark_download_probe(+ monkeypatch,+ *,+ supports_dspark,+ cached = None,+):+ """Run _download_dspark against a stubbed capability probe and an optionally+ cached sidecar; report whether the ~11 GB fetch (and even the repo listing)+ was reached."""+ import core.inference.llama_cpp as llama_cpp_module+ from core.inference.llama_cpp import LlamaCppBackend++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.setattr(+ LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(lambda cls, binary = None: {"supports_dspark": supports_dspark}),+ )+ monkeypatch.setattr(+ llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: cached+ )+ reached = {}++ def _fake_companion(+ *,+ hf_repo,+ hf_token,+ pick,+ label,+ cancel_event = None,+ near_path = None,+ outcome = None,+ ):+ reached["hit"] = True+ if outcome is not None:+ outcome["listed"] = True+ return "/cache/dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"++ b = LlamaCppBackend()+ b._download_companion_gguf = _fake_companion+ got = b._download_dspark(+ hf_repo = "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ near_path = "/cache/snap/DeepSeek-V4-Flash-0731-Q4_K_M.gguf",+ binary = "/fake/llama-server",+ )+ return got, reached.get("hit", False)+++def test_download_dspark_skips_the_fetch_when_the_binary_cannot_run_it(monkeypatch):+ """The sidecar is ~11 GB and _build_speculative_flags drops DSpark outright on+ a binary without --spec-type draft-dspark (every prebuilt in the known-broken+ window included), so the capability must be checked BEFORE the download."""+ got, reached = _dspark_download_probe(monkeypatch, supports_dspark = False)+ assert got is None+ assert reached is False+++def test_download_dspark_fetches_when_the_binary_supports_it(monkeypatch):+ got, reached = _dspark_download_probe(monkeypatch, supports_dspark = True)+ assert got == "/cache/dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"+ assert reached is True+++def test_download_dspark_records_whether_the_repo_publishes_a_sidecar(monkeypatch):+ """The reuse check retries a failed fetch but must never retry a repo that+ ships none, so the two "returned None" cases have to stay distinguishable."""+ import core.inference.llama_cpp as llama_cpp_module+ from core.inference.llama_cpp import LlamaCppBackend++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.setattr(+ LlamaCppBackend,+ "probe_server_capabilities",+ classmethod(lambda cls, binary = None: {"supports_dspark": True}),+ )+ monkeypatch.setattr(+ llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: None+ )++ def _companion(listed):+ def _fake(+ *,+ hf_repo,+ hf_token,+ pick,+ label,+ cancel_event = None,+ near_path = None,+ outcome = None,+ ):+ if outcome is not None:+ outcome["listed"] = listed+ return None++ return _fake++ for listed, expect_absent in ((False, True), (True, False)):+ b = LlamaCppBackend()+ b._download_companion_gguf = _companion(listed)+ assert b._download_dspark(hf_repo = "org/repo", binary = "/fake/llama-server") is None+ assert b._dspark_sidecar_absent is expect_absent+++def test_download_dspark_still_reports_a_cached_sidecar_it_cannot_run(monkeypatch):+ """Skipping the fetch must not hide a sidecar already on disk: the route+ rediscovers it on every Apply, so answering None would leave the reuse check+ comparing it against the launched None and reloading the same drafter-free+ server each time. _build_speculative_flags re-checks and still falls back."""+ cached = "/cache/snap/dspark/dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"+ got, reached = _dspark_download_probe(monkeypatch, supports_dspark = False, cached = cached)+ assert got == cached+ assert reached is False++def test_detect_mtp_file_returns_first_shard_of_split_subdir_drafter(tmp_path):"""llama-server takes shard 1 as the model path, so a split MTP/ copy mustnot resolve to whichever shard happens to be smallest."""@@ -961,8 +1182,8 @@ def test_gemma_mtp_is_still_auto_downloaded():def test_a_cached_dspark_drafter_is_never_launched_as_an_mtp_drafter(tmp_path, monkeypatch):"""_cached_repo_mtp_drafter uses the predicate inversely, to pick a drafter to- launch with --spec-type draft-mtp. DSpark needs draft-dspark plus --fit off,- so broadening that predicate must not widen what is launched."""+ launch with --spec-type draft-mtp. DSpark needs draft-dspark, so broadening+ that predicate must not widen what is launched."""import core.inference.llama_cpp as llama_cpp_moduledef _snapshot(files):@@ -991,6 +1212,29 @@ def test_a_cached_dspark_drafter_is_never_launched_as_an_mtp_drafter(tmp_path, massert found is not None and found.endswith("mtp-model.gguf")+def test_cached_dspark_lookup_prefers_q8_and_excludes_dflash(tmp_path, monkeypatch):+ import core.inference.llama_cpp as llama_cpp_module++ snap = tmp_path / "snapshot"+ for rel in (+ "dspark/dspark-model-BF16.gguf",+ "dspark/dspark-model-Q8_0.gguf",+ "dflash-model-Q8_0.gguf",+ ):+ path = snap / rel+ path.parent.mkdir(parents = True, exist_ok = True)+ path.write_bytes(b"x")+ monkeypatch.setattr(+ "utils.models.model_config._iter_hf_cache_snapshots",+ lambda *a, **k: [snap],+ )+ backend = llama_cpp_module.LlamaCppBackend.__new__(llama_cpp_module.LlamaCppBackend)++ assert backend._cached_repo_dspark_drafter("some/repo").endswith(+ "dspark/dspark-model-Q8_0.gguf"+ )++# ── Deletion: only auto-fetched companions are reclaimed ─────────────@@ -1024,16 +1268,18 @@ def _cache_repo(tmp_path: Path, repo_id: str, names: list[str]):), snap-def test_deleting_a_variant_keeps_an_opt_in_dspark_drafter(tmp_path):- """DSpark is in no variant plan, so Studio never downloaded it with the quant- and must not reclaim it: that would destroy an ~11 GB file the user fetched- deliberately."""+def test_deleting_one_of_several_variants_keeps_the_dspark_drafter(tmp_path):+ """A sibling quant still uses it, so only the last variant may reclaim it."""from hub.services.models.deletion import _delete_gguf_variant_from_reposrepo, snap = _cache_repo(tmp_path,"unsloth/DeepSeek-V4-Flash-0731-GGUF",- ["model-Q4_K_M.gguf", "dspark/dspark-DeepSeek-V4-Flash-0731-BF16.gguf"],+ [+ "model-Q4_K_M.gguf",+ "model-Q8_0.gguf",+ "dspark/dspark-DeepSeek-V4-Flash-0731-BF16.gguf",+ ],)_delete_gguf_variant_from_repos("unsloth/DeepSeek-V4-Flash-0731-GGUF", "Q4_K_M", [repo], None, root = tmp_path@@ -1043,6 +1289,39 @@ def test_deleting_a_variant_keeps_an_opt_in_dspark_drafter(tmp_path):assert (snap / "dspark" / "dspark-DeepSeek-V4-Flash-0731-BF16.gguf").is_symlink()+def test_deleting_the_last_variant_reclaims_an_opt_in_dspark_drafter(tmp_path):+ """Studio downloads the sidecar itself once the user opts in, and companion+ filtering keeps it out of the variant menu, so leaving it behind is an+ invisible ~11 GB allocation. Nothing can launch it with no main GGUF left."""+ from hub.services.models.deletion import _delete_gguf_variant_from_repos++ repo, snap = _cache_repo(+ tmp_path,+ "unsloth/DeepSeek-V4-Flash-0731-GGUF",+ ["model-Q4_K_M.gguf", "dspark/dspark-DeepSeek-V4-Flash-0731-BF16.gguf"],+ )+ _delete_gguf_variant_from_repos(+ "unsloth/DeepSeek-V4-Flash-0731-GGUF", "Q4_K_M", [repo], None, root = tmp_path+ )++ assert not (snap / "model-Q4_K_M.gguf").is_symlink()+ assert not (snap / "dspark" / "dspark-DeepSeek-V4-Flash-0731-BF16.gguf").is_symlink()+++def test_deleting_the_last_variant_keeps_a_dflash_weight(tmp_path):+ """Negative control: dflash is a family name a user picks for real weights,+ and Studio never fetches it as a companion, so it is not reclaimable."""+ from hub.services.models.deletion import _delete_gguf_variant_from_repos++ repo, snap = _cache_repo(+ tmp_path, "org/Model-GGUF", ["model-Q4_K_M.gguf", "dflash-model-Q8_0.gguf"]+ )+ _delete_gguf_variant_from_repos("org/Model-GGUF", "Q4_K_M", [repo], None, root = tmp_path)++ assert not (snap / "model-Q4_K_M.gguf").is_symlink()+ assert (snap / "dflash-model-Q8_0.gguf").is_symlink()++def test_deleting_the_last_variant_still_reclaims_mtp_and_mmproj(tmp_path):"""Positive control: those ARE fetched with every variant, so they still go."""from hub.services.models.deletion import _delete_gguf_variant_from_reposdiff --git a/studio/backend/tests/test_native_gguf_companion.py b/studio/backend/tests/test_native_gguf_companion.pyindex 9d5a07333a4..c639dfbbd42 100644--- a/studio/backend/tests/test_native_gguf_companion.py+++ b/studio/backend/tests/test_native_gguf_companion.py@@ -22,7 +22,11 @@ from routes.inference import _validate_native_mtp_drafterfrom routes.inference import _loaded_is_local_modelfrom routes.inference import _mtp_draft_for_pathfrom routes.inference import _native_gguf_companion_usable-from utils.models.model_config import _local_gguf_companion_search_root, detect_mtp_file+from utils.models.model_config import (+ _local_gguf_companion_search_root,+ detect_dspark_file,+ detect_mtp_file,+)from core.inference.llama_cpp import LlamaCppBackendfrom models.inference import LoadRequest@@ -43,6 +47,7 @@ def _request_matches_loaded_settings(gguf_file = model_path,gguf_mmproj_file = None,gguf_mtp_file = draft,+ gguf_dspark_file = detect_dspark_file(model_path, search_root = root),is_vision = False,)intent = _resolve_gguf_load_intent(@@ -80,7 +85,7 @@ def test_native_companion_allows_model_directory(tmp_path):def test_native_mtp_companion_allows_mtp_directory(tmp_path, folder):weight, companion = _write_pair(tmp_path, folder)_validate_native_gguf_companion(- str(companion), str(weight), "MTP drafter", allow_mtp_subdir = True+ str(companion), str(weight), "MTP drafter", allowed_subdirs = ("mtp",))@@ -96,7 +101,24 @@ def test_native_mtp_companion_allows_repo_root_mtp_directory(tmp_path):str(companion),str(weight),"MTP drafter",- allow_mtp_subdir = True,+ allowed_subdirs = ("mtp",),+ mtp_search_root = str(tmp_path),+ )+++def test_native_dspark_companion_allows_repo_dspark_directory(tmp_path):+ quant_dir = tmp_path / "Q4_0"+ weight, _ = _write_pair(quant_dir)+ companion_dir = tmp_path / "dspark"+ companion_dir.mkdir()+ companion = companion_dir / "dspark-model-Q8_0.gguf"+ companion.write_bytes(b"draft")++ _validate_native_gguf_companion(+ str(companion),+ str(weight),+ "DSpark drafter",+ allowed_subdirs = ("dspark",),mtp_search_root = str(tmp_path),)@@ -114,7 +136,7 @@ def test_native_mtp_companion_rejects_unrelated_search_root(tmp_path):str(companion),str(weight),"MTP drafter",- allow_mtp_subdir = True,+ allowed_subdirs = ("mtp",),mtp_search_root = str(tmp_path),)@@ -168,7 +190,7 @@ def test_native_companion_rejects_arbitrary_nesting(tmp_path, folder):weight, companion = _write_pair(tmp_path, folder)with pytest.raises(HTTPException, match = "must live beside") as error:_validate_native_gguf_companion(- str(companion), str(weight), "MTP drafter", allow_mtp_subdir = True+ str(companion), str(weight), "MTP drafter", allowed_subdirs = ("mtp",))assert error.value.status_code == 400@@ -202,7 +224,7 @@ def test_native_companion_rejects_directory_symlink_escape(tmp_path):str(model_dir / "MTP" / companion.name),str(weight),"MTP drafter",- allow_mtp_subdir = True,+ allowed_subdirs = ("mtp",),)diff --git a/studio/backend/tests/test_offline_gguf_cache_fallback.py b/studio/backend/tests/test_offline_gguf_cache_fallback.pyindex 900ae753621..8583f64bdf1 100644--- a/studio/backend/tests/test_offline_gguf_cache_fallback.py+++ b/studio/backend/tests/test_offline_gguf_cache_fallback.py@@ -2095,6 +2095,21 @@ class TestListLocalGgufVariantsSubdir:assert config is not Noneassert config.gguf_file == str(target.resolve())+ def test_model_config_direct_split_gguf_keeps_file_when_variant_is_echoed(self, tmp_path):+ """A settings reload sends status.gguf_variant with the direct file path."""+ from utils.models.model_config import ModelConfig++ first = tmp_path / "Model-UD-Q3_K_M-00001-of-00002.gguf"+ second = tmp_path / "Model-UD-Q3_K_M-00002-of-00002.gguf"+ first.write_bytes(b"a")+ second.write_bytes(b"b")++ config = ModelConfig.from_identifier(str(first), gguf_variant = "UD-Q3_K_M")++ assert config is not None+ assert config.is_gguf is True+ assert config.gguf_file == str(first.resolve())+def test_local_variant_listing_keeps_subdir_be_model_name_token(self, tmp_path):from utils.models.model_config import list_local_gguf_variantsdiff --git a/studio/backend/tests/test_tensor_parallel.py b/studio/backend/tests/test_tensor_parallel.pyindex cff33a6b1d0..08fa47884ea 100644--- a/studio/backend/tests/test_tensor_parallel.py+++ b/studio/backend/tests/test_tensor_parallel.py@@ -299,11 +299,11 @@ def test_mtp_decode_probe_wired_under_tensor_parallel():guard = src[max(0, probe - 400) : probe]assert "self._tensor_parallel" in guard and "_spec_requested_mtp" in guard# A hard fault retries FA-off (keeps MTP) before flipping healthy so the- # shared MTP-drop fallback fires.+ # shared drafter-drop fallback fires.after = src[probe : probe + 900]assert "_with_flash_attn_off" in after and "healthy = False" in after- fallback = src.find("if not healthy and _spec_requested_mtp")- assert 0 <= probe < fallback, "the probe must precede the MTP-drop fallback"+ fallback = src.find("and (_spec_requested_mtp or _spec_requested_dspark)")+ assert 0 <= probe < fallback, "the probe must precede the drafter-drop fallback"def test_probe_mtp_decode_returns_false_on_crash(monkeypatch):diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex f136cca7dc3..6ac8d9a726c 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -1649,6 +1649,101 @@ def detect_mmproj_file(path: str, search_root: Optional[str] = None) -> Optionalreturn str(best[1])+def _drafter_pairing_stem(name: str, *, kind: str) -> str:+ """The model family a drafter filename names, stripped of its own markers.++ Both published schemes are handled: ``<kind>-<model>`` and the older+ ``<model>-<KIND>``. The shard suffix sits outside the quant token, so it+ goes first or the anchored quant strip below cannot match. Full quant+ vocabulary, not a subset: K/IQ/UD/MXFP drafters pair too, and the optional+ bpw modifier goes with it, as _extract_quant_label does.+ """+ stem = Path(name).stem.lower()+ if stem.startswith(f"{kind}-"):+ stem = stem[len(kind) + 1 :]+ stem = re.sub(r"-[0-9]{5}-of-[0-9]{5}$", "", stem)+ if stem.endswith(f"-{kind}"):+ stem = stem[: -(len(kind) + 1)]+ return re.sub(+ rf"-(?:{_GGUF_KNOWN_QUANT_RE.pattern})(?:-[0-9]+(?:\.[0-9]+)?bpw)?$",+ "",+ stem,+ flags = re.IGNORECASE,+ )+++def _drafter_matches_weight(candidate_name: str, weight_name: Optional[str], *, kind: str) -> bool:+ """Whether a drafter pairs with the weight, by name.++ A multi-model folder must not attach a foreign drafter, so the family the+ drafter names has to PREFIX the weight filename at a non-alphanumeric+ boundary. Prefix alone is not enough: ``DeepSeek-V4-Flash-Lite`` and+ ``DeepSeek-V4-Flash`` would otherwise pair in both directions and launch+ the wrong sidecar as --model-draft.+ """+ if weight_name is None:+ return True+ stem = _drafter_pairing_stem(candidate_name, kind = kind)+ weight = weight_name.lower()+ return (+ bool(stem)+ and weight.startswith(stem)+ and (len(weight) == len(stem) or not weight[len(stem)].isalnum())+ )+++def _drafter_launch_path(candidate: Path) -> str:+ """The path llama-server should receive for *candidate*.++ llama-server takes shard 1 as the model path, and a split copy must stay on+ its snapshot path: the blob target has no sibling shard names. Single-file+ drafters still resolve, as callers expect.+ """+ loadable = _local_gguf_load_path(candidate)+ if _GGUF_SPLIT_FILE_RE.match(loadable.name):+ return str(loadable)+ return str(loadable.resolve())+++def _drafter_split_is_complete(candidate: Path) -> bool:+ """False for a partial split set, which would fail llama-server's draft+ startup and disable speculation entirely; skip it so a complete copy wins."""+ try:+ _, complete = colocated_split_shards(candidate)+ except OSError:+ return False+ return complete+++def _drafter_total_size(candidate: Path) -> int:+ """Bytes across every shard. Candidates are collapsed to shard 1, so a split+ copy must be summed or it would outrank a smaller single file."""+ try:+ shards, _ = colocated_split_shards(candidate)+ return sum(shard.stat().st_size for shard in shards)+ except OSError:+ return sys.maxsize+++def dspark_precision_rank(name: str) -> int:+ """Sidecar precision preference: Q8_0 first, the precision the DSpark model+ card recommends. Shared with the hub download and VRAM-sizing paths so the+ file Studio budgets for is the file it fetches and launches."""+ base = Path(name).name.lower()+ if "-q8_0" in base:+ return 0+ if "-q4_0" in base:+ return 1+ if "-bf16" in base or "-f16" in base:+ return 2+ return 3+++def dspark_preference_key(name: str) -> tuple[int, str]:+ """Sort key picking the preferred sidecar by name alone (no filesystem)."""+ return dspark_precision_rank(name), Path(name).name.lower()++def detect_mtp_file(path: str,search_root: Optional[str] = None,@@ -1678,58 +1773,18 @@ def detect_mtp_file(rejection as no drafter at all."""- def _pairing_stem(name: str) -> str:- stem = Path(name).stem.lower()- if stem.startswith("mtp-"):- stem = stem[len("mtp-") :]- # Shard suffix sits outside the quant token, so strip it before the anchored strip below.- stem = re.sub(r"-[0-9]{5}-of-[0-9]{5}$", "", stem)- if stem.endswith("-mtp"):- stem = stem[: -len("-mtp")]- # Full quant vocabulary (K/IQ/UD/MXFP drafters pair too), plus the optional bpw modifier.- return re.sub(- rf"-(?:{_GGUF_KNOWN_QUANT_RE.pattern})(?:-[0-9]+(?:\.[0-9]+)?bpw)?$",- "",- stem,- flags = re.IGNORECASE,- )-- def _drafter_launch_path(candidate: Path) -> str:- # llama-server takes shard 1 as the model path, and a split copy must stay on its snapshot- # path (the blob target has no sibling shard names). Single-file drafters still resolve.- loadable = _local_gguf_load_path(candidate)- if _GGUF_SPLIT_FILE_RE.match(loadable.name):- return str(loadable)- return str(loadable.resolve())-def _matches_weight(candidate: Path) -> bool:- if weight_name is None:- return True- stem = _pairing_stem(candidate.name)- return (- bool(stem)- and weight_name.startswith(stem)- and (len(weight_name) == len(stem) or not weight_name[len(stem)].isalnum())- )+ return _drafter_matches_weight(candidate.name, weight_name, kind = "mtp")def _launchable(candidate: Path) -> bool:- # An incomplete split set fails llama-server's draft startup; skip it so a complete copy wins.- try:- _, complete = colocated_split_shards(candidate)- except OSError:- return False- return complete+ return _drafter_split_is_complete(candidate)def _smallest_first(candidate: Path) -> tuple[int, int, str]:# Cheapest compatible copy wins. Size first: a fixed precision list ranked unknown quants# behind BF16, so a small K-quant lost to a far larger BF16. Precision breaks size ties,# name keeps it stable. Split copies collapse to shard 1, so sum across their shards.+ # MTP prefers Q4_0 where DSpark prefers Q8_0, so the order is its own.name = candidate.name.lower()- try:- shards, _ = colocated_split_shards(candidate)- size = sum(shard.stat().st_size for shard in shards)- except OSError:- size = sys.maxsizeif "-q4_0" in name:precision = 0elif "-q8_0" in name:@@ -1738,7 +1793,7 @@ def detect_mtp_file(precision = 2else:precision = 3- return size, precision, name+ return _drafter_total_size(candidate), precision, namep = Path(path)weight_name = p.name.lower() if p.suffix.lower() == ".gguf" else None@@ -1821,6 +1876,105 @@ def detect_mtp_file(return None+def detect_dspark_file(+ path: str,+ search_root: Optional[str] = None,+ accept: Optional[Callable[[str], bool]] = None,+) -> Optional[str]:+ """Find a DSpark sidecar for a local GGUF model.++ Unsloth publishes these as ``dspark-*.gguf`` in the repository root or+ under ``dspark/``. Prefer Q8_0, the precision recommended by the model+ card, while requiring the sidecar family name to match the target model+ (see _drafter_matches_weight: a folder holding a model and its "-Lite"+ sibling must not cross-attach their sidecars).++ Requires a published drafter name (``dspark-<model>`` / ``<model>-dspark``)+ even inside ``dspark/``, mirroring detect_mtp_file: llama_cpp's+ _drafter_path_kind accepts anything in that directory because it exists to+ EXCLUDE companions from variant menus, and reusing it here would launch a+ weight copy someone parked there as --model-draft.++ ``accept`` filters candidates in preference order, so a caller with extra+ rules (a native lease) keeps scanning instead of treating the first+ rejection as no sidecar at all.+ """++ def _rank(candidate: Path) -> tuple[int, int, str]:+ # Precision first (the model card's recommendation), then total size so+ # a split copy cannot outrank a smaller single file, then name for a+ # stable order.+ return (+ dspark_precision_rank(candidate.name),+ _drafter_total_size(candidate),+ candidate.name.lower(),+ )++ p = Path(path)+ weight_name = p.name 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))++ candidates: list[Path] = []+ seen: set[Path] = set()+ # dict.fromkeys: search_root is the weight's own parent for a flat layout,+ # and scanning it twice doubles the directory reads for nothing.+ for root in dict.fromkeys(dirs):+ try:+ root_entries = list(root.iterdir())+ except OSError:+ continue+ # One listing per directory, partitioned into the dspark/ subdir and+ # the sidecars beside the weight.+ scan: list[tuple[Path, list[Path]]] = [(root, root_entries)]+ for entry in root_entries:+ if entry.name.casefold() != "dspark":+ continue+ try:+ if entry.is_dir():+ scan.append((entry, list(entry.iterdir())))+ except OSError:+ continue+ for _directory, entries in scan:+ for candidate in entries:+ lower = candidate.name.lower()+ if not lower.endswith(".gguf"):+ continue+ # Drop the shard suffix first: a split copy under the old+ # scheme is <model>-Q8_0-dspark-00001-of-00002.gguf, whose+ # stem does not end in -dspark.+ stem = re.sub(r"-[0-9]{5}-of-[0-9]{5}$", "", Path(lower).stem)+ if not (lower.startswith("dspark-") or stem.endswith("-dspark")):+ continue+ if not _drafter_matches_weight(candidate.name, weight_name, kind = "dspark"):+ continue+ try:+ # Collapse a split copy to shard 1 before ranking.+ launch = _local_gguf_load_path(candidate)+ if not _drafter_split_is_complete(launch):+ continue+ resolved = launch.resolve()+ except OSError:+ continue+ if resolved in seen:+ continue+ seen.add(resolved)+ candidates.append(launch)++ for candidate in sorted(candidates, key = _rank):+ try:+ launch = _drafter_launch_path(candidate)+ except OSError:+ continue+ if accept is not None and not accept(launch):+ continue+ logger.info("Detected DSpark drafter: %s", launch)+ return launch+ return None++def _registered_custom_model_root(path: str) -> Optional[Path]:try:from storage.studio_db import list_scan_folders@@ -3023,6 +3177,7 @@ class ModelConfig: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_dspark_file: Optional[str] = None # Full path to a DSpark sidecar (local mode)gguf_hf_repo: Optional[str] = (None # HF repo ID for -hf mode (e.g. "unsloth/gemma-3-4b-it-GGUF"))@@ -3125,7 +3280,13 @@ class ModelConfig:# Auto-detect GGUF models (check before LoRA/vision detection)if is_local:- if gguf_variant:+ # A direct GGUF path is already an unambiguous selection. Status+ # echoes its detected quant back as ``gguf_variant`` on settings+ # reloads, but variant lookup is directory-only: a loose GGUF has+ # no config metadata for _resolve_gguf_dir and would otherwise fall+ # through to the Transformers loader. Only use the variant to pick+ # a file when the request actually names a directory.+ if gguf_variant and Path(path).is_dir():gguf_file = _find_local_gguf_by_variant(path, gguf_variant)else:gguf_file = detect_gguf_model(path)@@ -3168,6 +3329,7 @@ class ModelConfig:mtp_file = detect_mtp_file(gguf_file, search_root = companion_root)if mtp_file:logger.info(f"Detected MTP drafter: {mtp_file}")+ dspark_file = detect_dspark_file(gguf_file, search_root = companion_root)return cls(identifier = identifier,@@ -3181,6 +3343,7 @@ class ModelConfig:gguf_file = gguf_file,gguf_mmproj_file = mmproj_file,gguf_mtp_file = mtp_file,+ gguf_dspark_file = dspark_file,)else:# Does the HF repo contain GGUF files?diff --git a/studio/backend/utils/native_path_leases.py b/studio/backend/utils/native_path_leases.pyindex d17a96eb007..9edec69bb28 100644--- a/studio/backend/utils/native_path_leases.py+++ b/studio/backend/utils/native_path_leases.py@@ -24,7 +24,7 @@ import timefrom contextlib import contextmanagerfrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Callable, Iterable, Iterator, Mapping+from typing import Any, Callable, Collection, Iterable, Iterator, MappingLEASE_SECRET_ENV = "UNSLOTH_STUDIO_NATIVE_PATH_LEASE_SECRET"_MAX_NATIVE_PATH_REDACTIONS = 100@@ -51,15 +51,22 @@ def native_gguf_companion_parent_allowed(companion_path: str | Path,gguf_path: str | Path,*,- allow_mtp_subdir: bool = False,+ allowed_subdirs: Collection[str] = (),mtp_search_root: str | Path | None = None,) -> bool:- """Check whether a GGUF companion is in an allowed directory."""+ """Check whether a GGUF companion is in an allowed directory.++ ``allowed_subdirs`` names the companion directories (``mtp``, ``dspark``)+ this caller may reach into, beside the weight's own. A collection rather+ than one flag per kind: each caller admits exactly the kind it is+ resolving, so an MTP load never accepts a sidecar out of ``dspark/``.+ """companion_parent = Path(companion_path).resolve(strict = True).parentgguf_parent = Path(gguf_path).resolve(strict = True).parentif companion_parent == gguf_parent:return True- if not allow_mtp_subdir or companion_parent.name.casefold() != "mtp":+ permitted = {name.casefold() for name in allowed_subdirs}+ if companion_parent.name.casefold() not in permitted:return Falseallowed_roots = {gguf_parent}if mtp_search_root is not None:diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.pyindex 11f0b381a2c..fbd54629d1f 100644--- a/studio/backend/utils/openai_auto_switch_settings.py+++ b/studio/backend/utils/openai_auto_switch_settings.py@@ -265,17 +265,19 @@ VALID_SPECULATIVE_TYPES = frozenset({"auto","mtp",+ "dspark","ngram","mtp+ngram","off","default","draft-mtp",+ "draft-dspark","ngram-mod","ngram-simple",})-# Only these consume spec_draft_n_max (mirrors MTP_SPECULATIVE_TYPES in the UI).-MTP_SPECULATIVE_TYPES = frozenset({"mtp", "mtp+ngram", "draft-mtp"})+# Only these consume spec_draft_n_max (mirrors DRAFT_N_MAX_SPEC_TYPES in the UI).+DRAFT_N_MAX_SPEC_TYPES = frozenset({"mtp", "mtp+ngram", "draft-mtp", "dspark", "draft-dspark"})VALID_GPU_MEMORY_MODES = frozenset({"auto", "manual"})# Mirrors PARALLEL_MIN/MAX in llama_server_args.py. Mirrored not imported: that module owns@@ -341,8 +343,9 @@ def normalize_model_override(payload: dict[str, Any]) -> dict[str, Any]:speculative_type = _clean_str(payload.get("speculative_type"), VALID_SPECULATIVE_TYPES)if speculative_type:entry["speculative_type"] = speculative_type- # MTP-only; storing it otherwise shows an edit the loader ignores.- if speculative_type in MTP_SPECULATIVE_TYPES:+ # Only the modes that launch a drafter with a configurable depth (MTP+ # and DSpark); storing it otherwise shows an edit the loader ignores.+ if speculative_type in DRAFT_N_MAX_SPEC_TYPES:spec_draft_n_max = _bounded_int(payload.get("spec_draft_n_max"), minimum = 1, maximum = 16)if spec_draft_n_max:entry["spec_draft_n_max"] = spec_draft_n_maxdiff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex d2204160689..14f3dc2bbf0 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -262,6 +262,11 @@ export async function validateModel(gpu_layers: payload.gpu_layers,// Slots scale the KV estimate; keep validate sized like the load.n_parallel: payload.n_parallel,+ // The estimate charges a drafter whose size differs by kind (a DSpark+ // sidecar is ~11 GB), so omitting the mode makes this preflight disagree+ // with /load in both directions.+ speculative_type: payload.speculative_type ?? null,+ spec_draft_n_max: payload.spec_draft_n_max ?? null,}),});return parseJsonOrThrow<ValidateModelResponse>(response);diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsxindex 8397b71089e..e6c45f4ae3c 100644--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx@@ -398,6 +398,46 @@ interface ChatSettingsPanelProps {externalProviderType?: string | null;}+/**+ * Copy for the amber "running without speculative decoding" notice. Mirrors+ * InferenceStatusResponse.spec_fallback_reason.+ *+ * Out of the JSX so the three independent dimensions (reason, drafter kind,+ * local vs remote) read as a table rather than a five-level nested ternary,+ * and so each string is directly testable.+ */+function specFallbackMessage({+ reason,+ drafter,+ isLocalGguf,+ updateAvailable,+}: {+ reason: string;+ drafter: "MTP" | "DSpark";+ isLocalGguf: boolean;+ updateAvailable: boolean;+}): string {+ 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 "runtime_error":+ return `${drafter} could not start for this model on the installed llama.cpp build, so it is running without speculative decoding.`;+ case "drafter_not_found":+ if (drafter === "DSpark") {+ return isLocalGguf+ ? "No matching DSpark sidecar was found. Place its dspark-*.gguf beside the model or in its dspark folder, then reload the model."+ : "The DSpark sidecar could not be downloaded, so this model is running without speculative decoding. Check network or Hugging Face access, then reload it.";+ }+ return isLocalGguf+ ? "This local model supports MTP, but no matching drafter file was found. Place its mtp-*.gguf beside the model or in its MTP folder, then reload the model."+ : "This model supports MTP, but its drafter file could not be downloaded, so MTP is off and it falls back to n-gram speculative decoding where the llama.cpp build supports it. Check your network connection or Hugging Face access, then reload the model to retry the drafter.";+ default:+ return `${drafter} is not available in the installed llama.cpp build, so this model is running without it.${+ updateAvailable ? " Update llama.cpp to enable it." : ""+ }`;+ }+}+export function ChatSettingsPanel({open,onOpenChange,@@ -466,6 +506,12 @@ export function ChatSettingsPanel({const nParallel = useChatRuntimeStore((s) => s.nParallel);const speculativeType = useChatRuntimeStore((s) => s.speculativeType);const specFallbackReason = useChatRuntimeStore((s) => s.specFallbackReason);+ const specDrafterKind = useChatRuntimeStore((s) => s.specDrafterKind);+ // The loaded model's own kind, not the pending control: the notice explains a+ // fallback that already happened, so a staged edit (or a preset applied without+ // a reload) must not re-label it and point at the wrong file.+ const speculativeDrafterLabel =+ (specDrafterKind ?? speculativeType) === "dspark" ? "DSpark" : "MTP";const mtpUpdatable =specFallbackReason === "binary_no_mtp" ||specFallbackReason === "binary_outdated";@@ -481,7 +527,7 @@ export function ChatSettingsPanel({const result = await applyLlamaUpdate();if (result.ok) {const reloadHint = result.reloadRequired- ? " Reload your model to enable MTP."+ ? ` Reload your model to enable ${speculativeDrafterLabel}.`: "";toast.success(`llama.cpp updated to ${result.tag ?? "the latest build"}.${reloadHint}`,@@ -491,7 +537,7 @@ export function ChatSettingsPanel({`llama.cpp update failed: ${result.error ?? "unknown error"}`,);}- }, [applyLlamaUpdate]);+ }, [applyLlamaUpdate, speculativeDrafterLabel]);const loadedEffectiveContext = customContextLength ?? ggufContextLength;const showSpecFallback =!isExternalModel &&@@ -499,7 +545,8 @@ export function ChatSettingsPanel({specFallbackReason != null &&(speculativeType === "auto" ||speculativeType === "mtp" ||- speculativeType === "mtp+ngram");+ speculativeType === "mtp+ngram" ||+ speculativeType === "dspark");const showContextVramWarning =!isExternalModel &&isGguf &&@@ -898,19 +945,12 @@ export function ChatSettingsPanel({{showSpecFallback && (<div className="rounded-lg bg-amber-500/[0.08] px-3 py-2 text-ui-12 leading-[1.4] text-nav-fg/80"><p>- {specFallbackReason === "mla_mtp_disabled"- ? "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."- : specFallbackReason === "runtime_error"- ? "MTP could not start for this model on the installed llama.cpp build, so it is running without speculative decoding."- : specFallbackReason === "drafter_not_found"- ? isLocalGguf- ? "This local model supports MTP, but no matching drafter file was found. Place its mtp-*.gguf beside the model or in its MTP folder, then reload the model."- : "This model supports MTP, but its drafter file could not be downloaded, so MTP is off and it falls back to n-gram speculative decoding where the llama.cpp build supports it. Check your network connection or Hugging Face access, then reload the model to retry the drafter."- : `MTP is not available in the installed llama.cpp build, so this model is running without it.${- llamaUpdateStatus?.update_available- ? " Update llama.cpp to enable it."- : ""- }`}+ {specFallbackMessage({+ reason: specFallbackReason,+ drafter: speculativeDrafterLabel,+ isLocalGguf,+ updateAvailable: Boolean(llamaUpdateStatus?.update_available),+ })}</p>{mtpUpdatable && llamaUpdateStatus?.update_available && (<Buttondiff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.tsindex 6c1e07b0fd1..734e792508b 100644--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts@@ -16,6 +16,7 @@ import {type ReasoningStyle,loadOptionalBool,loadedGpuMemoryFields,+ normalizeSpeculativeType,resolveToolsEnabledOnLoad,useChatRuntimeStore,} from "../stores/chat-runtime-store";@@ -33,33 +34,10 @@ function sameArray<T>(a: T[] | null, b: T[] | null): boolean {return JSON.stringify(a) === JSON.stringify(b);}-// Canonicalises backend / persisted speculative mode values onto the UI modes.-export function normalizeSpeculativeType(- v: string | null | undefined,-): string | null {- if (v == null) return null;- const s = String(v).trim().toLowerCase();- if (!s) return null;- if (s === "auto" || s === "default") return "auto";- if (s === "off") return "off";- if (s === "mtp" || s === "draft-mtp") return "mtp";- if (s === "ngram" || s === "ngram-mod" || s === "ngram-simple") {- return "ngram";- }- if (s === "mtp+ngram") return "mtp+ngram";- const parts = s- .split(",")- .map((p) => p.trim())- .filter(Boolean);- const hasMtp = parts.some((p) => p === "mtp" || p === "draft-mtp");- const hasNgram = parts.some(- (p) => p === "ngram" || p === "ngram-mod" || p === "ngram-simple",- );- if (hasMtp && hasNgram) return "mtp+ngram";- if (hasMtp) return "mtp";- if (hasNgram) return "ngram";- return "auto";-}+// Canonicalises backend / persisted speculative mode values onto the UI+// modes. Re-exported from the store, which owns the vocabulary: a second+// copy meant every new mode had to be added twice or the two would disagree.+export { normalizeSpeculativeType } from "../stores/chat-runtime-store";export function clampLocalReasoningEffort(value: ReasoningEffort,@@ -343,6 +321,7 @@ export function applyActiveModelStatusToStore(loadedIsDiffusion: status.is_diffusion ?? false,activeModelIsLocal: status.is_local_model ?? false,specFallbackReason: status.spec_fallback_reason ?? null,+ specDrafterKind: status.spec_drafter_kind ?? null,// The spec / KV seeds share the GPU-fields reseed mechanism below: a// non-GGUF status leaves their loaded baselines null, so the "unseeded"// guard re-fires every refresh -- hold them too while a staged pick'sdiff --git a/studio/frontend/src/features/chat/presets/preset-load-config.ts b/studio/frontend/src/features/chat/presets/preset-load-config.tsindex a0e6ad13f38..9c366d4c165 100644--- a/studio/frontend/src/features/chat/presets/preset-load-config.ts+++ b/studio/frontend/src/features/chat/presets/preset-load-config.ts@@ -11,13 +11,15 @@ import {DEFAULT_PER_MODEL_CONFIG,DEFAULT_MAX_SEQ_LENGTH,KV_CACHE_DTYPES,- MTP_SPECULATIVE_TYPES,N_PARALLEL_MAX,N_PARALLEL_MIN,- SPECULATIVE_TYPES,normalizeMaxSeqLength,type PerModelConfig,} from "@/features/model-picker/model-config/per-model-config";+import {+ DRAFT_N_MAX_SPEC_TYPES,+ SPECULATIVE_TYPES,+} from "@/lib/speculative-modes";import {GPU_LAYERS_AUTO,useChatRuntimeStore,@@ -77,7 +79,7 @@ export function normalizePresetLoadConfig(const speculativeType = rawSpecType ?? null;const specDraftNMax =speculativeType != null &&- MTP_SPECULATIVE_TYPES.has(speculativeType) &&+ DRAFT_N_MAX_SPEC_TYPES.has(speculativeType) &&typeof partial.specDraftNMax === "number" &&Number.isFinite(partial.specDraftNMax)? Math.max(1, Math.min(16, Math.round(partial.specDraftNMax)))diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex c74fe948c87..567f588463e 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -23,6 +23,7 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";+import { DRAFT_N_MAX_SPEC_TYPES } from "@/lib/speculative-modes";import {StudioDictationAdapter,isStudioDictationAvailable,@@ -474,7 +475,7 @@ function resolveCompareSpecDraftNMax(speculativeType: string | null,value: number | null,): number | null {- return speculativeType === "mtp" || speculativeType === "mtp+ngram"+ return speculativeType != null && DRAFT_N_MAX_SPEC_TYPES.has(speculativeType)? value: null;}diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 7d5da0226bf..1c4c1d2e87d 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -9,6 +9,7 @@ import {type GpuIndexKind,} from "@/hooks/use-gpu-info";import { toast } from "@/lib/toast";+import { DRAFT_N_MAX_SPEC_TYPES } from "@/lib/speculative-modes";import { create } from "zustand";import {GPU_LAYERS_AUTO,@@ -91,9 +92,10 @@ export const CHAT_RAG_CAPTION_KEY = "unsloth_chat_rag_caption_figures";export const CHAT_SPECULATIVE_TYPE_KEY = "unsloth_chat_speculative_type";export const CHAT_GPU_MEMORY_MODE_KEY = "unsloth_chat_gpu_memory_mode";-// Persist only the model-agnostic intents (auto/ngram/off). MTP modes-// (mtp/mtp+ngram) and spec_draft_n_max stay session-only: a persisted MTP-// choice would silently no-op on models without an MTP head. Unknown -> auto.+// Persist only the model-agnostic intents (auto/ngram/off). The model-specific+// drafter modes (mtp/mtp+ngram/dspark) and spec_draft_n_max stay session-only:+// a persisted choice would silently no-op on a model with no MTP head or no+// DSpark sidecar. Unknown -> auto.const PERSISTED_SPEC_MODES = new Set(["auto", "ngram", "off"]);export type RagSource = { type: "thread" } | { type: "kb"; kbId: string };@@ -501,6 +503,7 @@ export function normalizeSpeculativeType(if (s === "auto" || s === "default") return "auto";if (s === "off") return "off";if (s === "mtp" || s === "draft-mtp") return "mtp";+ if (s === "dspark" || s === "draft-dspark") return "dspark";if (s === "ngram" || s === "ngram-mod" || s === "ngram-simple") {return "ngram";}@@ -1036,10 +1039,17 @@ type ChatRuntimeStore = {speculativeType: string | null;loadedSpeculativeType: string | null;/**- * Why MTP was disabled on the loaded model despite being requested, or null.+ * Why speculative decoding was disabled despite being requested, or null.* Mirrors InferenceStatusResponse.spec_fallback_reason.*/specFallbackReason: string | null;+ /**+ * Which drafter the loaded model's speculative resolution was about, "mtp" or+ * "dspark". Paired with specFallbackReason: the reason alone cannot name the+ * file to fix, since Auto resolves the kind server-side and the requested mode+ * still reads "auto".+ */+ specDrafterKind: string | null;/** User --spec-draft-n-max override (null = platform default). */specDraftNMax: number | null;loadedSpecDraftNMax: number | null;@@ -1591,6 +1601,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({speculativeType: readPersistedSpeculativeType(),loadedSpeculativeType: null,specFallbackReason: null,+ specDrafterKind: null,specDraftNMax: null,loadedSpecDraftNMax: null,nParallel: null,@@ -1959,6 +1970,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({contextUsageByThreadId: {},activeModelIsLocal: false,specFallbackReason: null,+ specDrafterKind: null,}: {}),// Switching to an external provider disables Deep Research, which only@@ -2041,6 +2053,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({speculativeType: readPersistedSpeculativeType(),loadedSpeculativeType: null,specFallbackReason: null,+ specDrafterKind: null,specDraftNMax: null,loadedSpecDraftNMax: null,nParallel: null,@@ -2614,7 +2627,8 @@ export function resolveSpeculativeSettingsForLoad({speculativeType,specDraftNMax:!usePersistedPreference &&- (speculativeType === "mtp" || speculativeType === "mtp+ngram")+ speculativeType != null &&+ DRAFT_N_MAX_SPEC_TYPES.has(speculativeType)? state.specDraftNMax: null,};diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex cbb20844974..ed7e75747bb 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -55,14 +55,15 @@ export interface LoadModelRequest {/*** Speculative decoding mode for GGUF models. Canonical values: "auto"* (platform-aware: MTP on MTP GGUFs, ngram-mod fallback for sub-3B), "mtp"- * (force draft-mtp), "ngram" (force ngram-mod), "mtp+ngram" (ngram-mod ++ * (force draft-mtp), "dspark" (force draft-dspark with a sidecar),+ * "ngram" (force ngram-mod), "mtp+ngram" (ngram-mod +* draft-mtp chain), "off". Legacy "default"/"draft-mtp"/"ngram-mod"/* "ngram-simple" are still accepted by the backend.*/speculative_type?: string | null;/*** Override --spec-draft-n-max for MTP speculative decoding. Applied only- * when speculative_type resolves to "mtp" or "mtp+ngram".+ * when speculative_type resolves to "mtp", "mtp+ngram", or "dspark".*/spec_draft_n_max?: number | null;/**@@ -298,13 +299,20 @@ export interface InferenceStatusResponse {/** Model's MoE expert-layer count (the n_cpu_moe ceiling); 0 if not MoE. */n_moe_layers?: number;/**- * Why MTP was disabled on the loaded model despite being requested.+ * Why a speculative drafter was disabled despite being requested.* "binary_no_mtp" / "binary_outdated" -> updating llama.cpp would re-enable* it; "runtime_error" -> the current build could not run it;+ * "drafter_not_found" -> its MTP or DSpark sidecar was unavailable;* "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.*/+ /**+ * Which drafter the resolution was about, "mtp" or "dspark". Auto resolves the+ * kind itself, so speculative_type still reads "auto", and a fallback leaves+ * the engaged type at "default": neither names the file to fix.+ */+ spec_drafter_kind?: string | null;spec_fallback_reason?: string | null;}diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsxindex dae27170831..0bf8705d631 100644--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx@@ -52,11 +52,11 @@ import {CONTEXT_LENGTH_MIN,DEFAULT_MAX_SEQ_LENGTH,DEFAULT_PER_MODEL_CONFIG,+ DRAFT_N_MAX_SPEC_TYPES,KV_CACHE_DTYPES,MAX_SEQ_LENGTH_MAX,MAX_SEQ_LENGTH_MIN,MAX_SEQ_LENGTH_STEP,- MTP_SPECULATIVE_TYPES,N_PARALLEL_MAX,N_PARALLEL_MIN,type PerModelConfig,@@ -96,6 +96,7 @@ const SPECULATIVE_TYPE_LABELS: Record<> = {auto: "Auto",mtp: "MTP",+ dspark: "DSpark",ngram: "Ngram","mtp+ngram": "MTP+Ngram",off: "Off",@@ -497,7 +498,7 @@ function GpuMemorySettings({function GgufAdvancedSettings({config,update,- isMtp,+ showDraftTokens,speculativeFallback,onEditTemplate,layerCount,@@ -509,7 +510,7 @@ function GgufAdvancedSettings({}: {config: PerModelConfig;update: (patch: Partial<PerModelConfig>) => void;- isMtp: boolean;+ showDraftTokens: boolean;speculativeFallback: string;onEditTemplate: () => void;layerCount: number | null;@@ -561,8 +562,12 @@ function GgufAdvancedSettings({<div className="flex min-w-0 items-center gap-1.5"><span className={LABEL_CLASS_WRAP}>Speculative Decoding</span><InfoHint>- Faster generation with no accuracy hit. Auto picks MTP / ngram based- on the model and platform. Pick a strategy to force it.+ Faster generation. Auto picks the best strategy for the model and+ platform: DSpark when the model ships a drafter sidecar, otherwise+ MTP / ngram. Pick a strategy to force it, or Off to disable.+ DSpark downloads a sidecar of about 11 GB and trades VRAM for speed;+ on quantized targets its greedy output can differ from a non+ speculative run. MTP and ngram do not change output.</InfoHint></div><Select@@ -570,8 +575,9 @@ function GgufAdvancedSettings({onValueChange={(v) =>update({speculativeType: v,- specDraftNMax:- v === "mtp" || v === "mtp+ngram" ? config.specDraftNMax : null,+ specDraftNMax: DRAFT_N_MAX_SPEC_TYPES.has(v)+ ? config.specDraftNMax+ : null,})}>@@ -593,13 +599,13 @@ function GgufAdvancedSettings({</Select></div>- {isMtp && (+ {showDraftTokens && (<div className={ROW_CLASS}><div className="flex min-w-0 items-center gap-1.5"><span className={LABEL_CLASS}>Draft Tokens</span><InfoHint>- Max MTP draft tokens per step. Leave blank for the platform- default (2 on GPU, 3 on CPU/Mac).+ Max draft tokens per step. Leave blank for the default (MTP: 2 on+ GPU, 3 on CPU/Mac; DSpark: 3).</InfoHint></div><input@@ -881,9 +887,11 @@ export function ModelConfigPage({...patch,}));- const isMtp =+ // True for every mode that takes a draft depth, DSpark included, so this+ // gates the Draft Tokens row rather than naming a drafter.+ const showDraftTokens =config.speculativeType != null &&- MTP_SPECULATIVE_TYPES.has(config.speculativeType);+ DRAFT_N_MAX_SPEC_TYPES.has(config.speculativeType);const nativeContextLength =target.meta.contextLength ?? stagedDims?.contextLength ?? null;const activeLoadedContext =@@ -1190,7 +1198,7 @@ export function ModelConfigPage({<GgufAdvancedSettingsconfig={config}update={update}- isMtp={isMtp}+ showDraftTokens={showDraftTokens}speculativeFallback={speculativeFallback}onEditTemplate={() => setTemplateOpen(true)}layerCount={stagedDims?.layerCount ?? null}diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.tsindex c965c92f2bf..207a619ce65 100644--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts@@ -10,6 +10,7 @@ import {publicModelId,} from "./model-identity";import type { GpuIndexKind } from "@/hooks/use-gpu-info";+import { DRAFT_N_MAX_SPEC_TYPES } from "@/lib/speculative-modes";export interface PerModelConfig {customContextLength: number | null;@@ -65,17 +66,10 @@ export const KV_CACHE_DTYPES = [] as const;const VALID_KV_CACHE_DTYPES = new Set<string>(KV_CACHE_DTYPES);-export const SPECULATIVE_TYPES = [- "auto",- "mtp",- "ngram",- "mtp+ngram",- "off",-] as const;-export const MTP_SPECULATIVE_TYPES: ReadonlySet<string> = new Set([- "mtp",- "mtp+ngram",-]);+export {+ DRAFT_N_MAX_SPEC_TYPES,+ SPECULATIVE_TYPES,+} from "@/lib/speculative-modes";const STORAGE_KEY = "unsloth_model_configs";const LEGACY_STORAGE_KEY = "unsloth_load_settings";@@ -174,6 +168,9 @@ function canonicalizeSpeculativeType(value: string): string | null {if (s === "mtp" || s === "draft-mtp") {return "mtp";}+ if (s === "dspark" || s === "draft-dspark") {+ return "dspark";+ }if (s === "ngram" || s === "ngram-mod" || s === "ngram-simple") {return "ngram";}@@ -548,7 +545,7 @@ function normalizeV1(partial: RawConfig): PerModelConfig {rawSpecType ?? DEFAULT_PER_MODEL_CONFIG.speculativeType;const specDraftNMax =speculativeType != null &&- MTP_SPECULATIVE_TYPES.has(speculativeType) &&+ DRAFT_N_MAX_SPEC_TYPES.has(speculativeType) &&typeof partial.specDraftNMax === "number" &&Number.isFinite(partial.specDraftNMax)? Math.max(1, Math.min(16, Math.round(partial.specDraftNMax)))diff --git a/studio/frontend/src/lib/speculative-modes.ts b/studio/frontend/src/lib/speculative-modes.tsnew file mode 100644index 00000000000..75d780ba8cb--- /dev/null+++ b/studio/frontend/src/lib/speculative-modes.ts@@ -0,0 +1,33 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * The speculative-decoding vocabulary shared by the model picker and chat.+ *+ * Lives in lib/, not in either feature: both read it, and a low-level module+ * like the chat runtime store cannot import the model-picker barrel (the+ * feature-boundary lint rule bans deep imports, and the barrel pulls the+ * picker's components back into an eval-time cycle with chat).+ *+ * Mirrors the backend's _CANONICAL_SPEC_MODES (core/inference/llama_cpp.py).+ */+export const SPECULATIVE_TYPES = [+ "auto",+ "mtp",+ "dspark",+ "ngram",+ "mtp+ngram",+ "off",+] as const;++/**+ * The modes that consume spec_draft_n_max, i.e. the ones that launch a drafter+ * with a configurable depth. Named for the setting rather than for MTP: DSpark+ * is in here too. Mirrors DRAFT_N_MAX_SPEC_TYPES in+ * studio/backend/utils/openai_auto_switch_settings.py.+ */+export const DRAFT_N_MAX_SPEC_TYPES: ReadonlySet<string> = new Set([+ "mtp",+ "mtp+ngram",+ "dspark",+]);diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 19021fb2d68..49dffc7ac15 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -600,7 +600,9 @@ def test_local_mtp_warning_covers_path_and_native_gguf_sources():)[0]assert "activeModelIsLocal: false" in resetassert "specFallbackReason: null" in reset- assert "isLocalGguf" in src.split('specFallbackReason === "drafter_not_found"', 1)[1]+ # The reason chain is a switch, so slice on the case label rather than the+ # ternary comparison it replaced.+ assert "isLocalGguf" in src.split('case "drafter_not_found":', 1)[1]def test_local_mtp_warning_uses_backend_source_metadata():diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.pyindex 861108cb760..a49f2b8edfe 100644--- a/unsloth_cli/_inference.py+++ b/unsloth_cli/_inference.py@@ -10,10 +10,16 @@ import reimport sysfrom contextlib import contextmanager, redirect_stderr, redirect_stdoutfrom pathlib import Path-from typing import List, Optional+from typing import List, Literal, Optionalimport typer+# Canonical speculative-decoding modes, mirroring the backend's+# _CANONICAL_SPEC_MODES. Named once so the CLI's option annotations, the HTTP+# payload builders and the in-process loader cannot drift apart when a mode is+# added; typer reads it at runtime to validate --speculative-type.+SpeculativeType = Literal["auto", "mtp", "dspark", "ngram", "mtp+ngram", "off", "ngram-simple"]+_THINK_OPEN = "<think>"_THINK_BLOCK = re.compile(rf"{re.escape(_THINK_OPEN)}.*?</think>", re.DOTALL)_STREAMED_ERROR_PREFIX = "Error: "@@ -444,6 +450,8 @@ def _load_gguf_backend(hf_token,max_seq_length,tensor_parallel: bool = False,+ speculative_type: Optional[SpeculativeType] = None,+ spec_draft_n_max: Optional[int] = None,llama_extra_args: Optional[List[str]] = None,):ensure_studio_backend_path()@@ -465,7 +473,12 @@ def _load_gguf_backend(gguf_path = model_config.gguf_file,mmproj_path = model_config.gguf_mmproj_file,mtp_draft_path = model_config.gguf_mtp_file,+ dspark_draft_path = model_config.gguf_dspark_file,)+ if speculative_type is not None:+ intent_fields["speculative_type"] = speculative_type+ if spec_draft_n_max is not None:+ intent_fields["spec_draft_n_max"] = spec_draft_n_maxasync def _attempt_gguf_load(requested_tensor_parallel: bool, attempt_extra_args: Optional[List[str]]@@ -499,6 +512,8 @@ def load_chat_backend(max_seq_length: int,load_in_4bit: bool,tensor_parallel: bool = False,+ speculative_type: Optional[SpeculativeType] = None,+ spec_draft_n_max: Optional[int] = None,llama_extra_args: Optional[List[str]] = None,model_config = None,fresh_backend: bool = False,@@ -534,6 +549,8 @@ def load_chat_backend(hf_token = hf_token,max_seq_length = max_seq_length,tensor_parallel = tensor_parallel,+ speculative_type = speculative_type,+ spec_draft_n_max = spec_draft_n_max,llama_extra_args = llama_extra_args,)@@ -741,6 +758,8 @@ class HttpChatBackend:max_seq_length,load_in_4bit,tensor_parallel: bool = False,+ speculative_type: Optional[SpeculativeType] = None,+ spec_draft_n_max: Optional[int] = None,llama_extra_args: Optional[List[str]] = None,) -> None:typer.echo(f"Loading {model} on the Unsloth server", err = True)@@ -753,6 +772,10 @@ class HttpChatBackend:}if llama_extra_args:payload["llama_extra_args"] = llama_extra_args+ if speculative_type is not None:+ payload["speculative_type"] = speculative_type+ if spec_draft_n_max is not None:+ payload["spec_draft_n_max"] = spec_draft_n_maxtry:# Read the body, don't close at the headers: a slow load commits its 200# early and pads until done, so closing here would generate mid-load and@@ -846,6 +869,8 @@ def connect_studio_server(max_seq_length,load_in_4bit,tensor_parallel: bool = False,+ speculative_type: Optional[SpeculativeType] = None,+ spec_draft_n_max: Optional[int] = None,llama_extra_args: Optional[List[str]] = None,):"""Backend on a running Unsloth server, or None (caller loads locally)."""@@ -890,6 +915,8 @@ def connect_studio_server(max_seq_length = max_seq_length,load_in_4bit = load_in_4bit,tensor_parallel = tensor_parallel,+ speculative_type = speculative_type,+ spec_draft_n_max = spec_draft_n_max,llama_extra_args = llama_extra_args,)return backenddiff --git a/unsloth_cli/commands/chat.py b/unsloth_cli/commands/chat.pyindex fdc55777007..423ce23e173 100644--- a/unsloth_cli/commands/chat.py+++ b/unsloth_cli/commands/chat.py@@ -8,6 +8,7 @@ import typerfrom rich.console import Consolefrom unsloth_cli._inference import (+ SpeculativeType,collect_stream,configure_quiet_logging,connect_studio_server,@@ -181,6 +182,18 @@ def chat("parallel mode instead of pipeline mode."),),+ speculative_type: Optional[SpeculativeType] = typer.Option(+ None,+ "--speculative-type",+ help = "Speculative decoding mode for GGUF models, including DSpark sidecar discovery.",+ ),+ spec_draft_n_max: Optional[int] = typer.Option(+ None,+ "--spec-draft-n-max",+ min = 1,+ max = 16,+ help = "Maximum draft tokens per step for MTP or DSpark (1..16).",+ ),llama_extra_args: Optional[List[str]] = typer.Option(None,"--llama-extra-arg",@@ -261,6 +274,10 @@ def chat(tensor_parallel = tensor_parallel,llama_extra_args = llama_extra_args,)+ if speculative_type is not None:+ load_opts["speculative_type"] = speculative_type+ if spec_draft_n_max is not None:+ load_opts["spec_draft_n_max"] = spec_draft_n_max# Prefer a running Unsloth server: instant starts, model shared with the UI.chat_backend = (diff --git a/unsloth_cli/commands/inference.py b/unsloth_cli/commands/inference.pyindex 7df05cef94e..1d44a795b11 100644--- a/unsloth_cli/commands/inference.py+++ b/unsloth_cli/commands/inference.py@@ -6,6 +6,7 @@ from typing import List, Optionalimport typerfrom unsloth_cli._inference import (+ SpeculativeType,collect_stream,configure_quiet_logging,connect_studio_server,@@ -44,6 +45,18 @@ def inference("parallel mode instead of pipeline mode."),),+ speculative_type: Optional[SpeculativeType] = typer.Option(+ None,+ "--speculative-type",+ help = "Speculative decoding mode for GGUF models, including DSpark sidecar discovery.",+ ),+ spec_draft_n_max: Optional[int] = typer.Option(+ None,+ "--spec-draft-n-max",+ min = 1,+ max = 16,+ help = "Maximum draft tokens per step for MTP or DSpark (1..16).",+ ),llama_extra_args: Optional[List[str]] = typer.Option(None,"--llama-extra-arg",@@ -95,6 +108,10 @@ def inference(tensor_parallel = tensor_parallel,llama_extra_args = llama_extra_args,)+ if speculative_type is not None:+ load_opts["speculative_type"] = speculative_type+ if spec_draft_n_max is not None:+ load_opts["spec_draft_n_max"] = spec_draft_n_maxchat_backend = (None if (no_server or is_mlx_distributed) else connect_studio_server(model, **load_opts))diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 0796d79af10..8fc3700d3d3 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -24,6 +24,7 @@ from typing import List, Literal, Optional, Sequenceimport typerfrom unsloth_cli import _studio_deps+from unsloth_cli._inference import SpeculativeTypefrom unsloth_cli.commands import _password_promptstudio_app = typer.Typer(help = "Unsloth Studio commands.")@@ -1242,6 +1243,8 @@ def _load_model_via_http(load_in_4bit: bool,gpu_memory_mode: Literal["auto", "manual"] = "auto",tensor_parallel: bool = False,+ speculative_type: Optional[SpeculativeType] = None,+ spec_draft_n_max: Optional[int] = None,llama_extra_args: Optional[List[str]] = None,timeout: int = 600,) -> dict:@@ -1264,6 +1267,10 @@ def _load_model_via_http(payload["gpu_layers"] = -1if tensor_parallel:payload["tensor_parallel"] = True+ if speculative_type is not None:+ payload["speculative_type"] = speculative_type+ if spec_draft_n_max is not None:+ payload["spec_draft_n_max"] = spec_draft_n_maxif llama_extra_args:payload["llama_extra_args"] = list(llama_extra_args)@@ -1835,6 +1842,23 @@ def run("delegates placement and sizing to llama.cpp --fit."),),+ speculative_type: Optional[SpeculativeType] = typer.Option(+ None,+ "--speculative-type",+ rich_help_panel = _RUN_PANEL_MODEL,+ help = (+ "Speculative decoding mode for GGUF models. DSpark automatically uses a "+ "matching dspark-*.gguf sidecar when available. Default: unset (Studio auto)."+ ),+ ),+ spec_draft_n_max: Optional[int] = typer.Option(+ None,+ "--spec-draft-n-max",+ min = 1,+ max = 16,+ rich_help_panel = _RUN_PANEL_MODEL,+ help = "Maximum draft tokens per step for MTP or DSpark (1..16).",+ ),load_in_4bit: bool = typer.Option(True, "--load-in-4bit/--no-load-in-4bit", rich_help_panel = _RUN_PANEL_MODEL),@@ -2246,6 +2270,10 @@ def run(args.extend(["--gpu-memory-mode", gpu_memory_mode])if gguf_variant:args.extend(["--gguf-variant", gguf_variant])+ if speculative_type is not None:+ args.extend(["--speculative-type", speculative_type])+ if spec_draft_n_max is not None:+ args.extend(["--spec-draft-n-max", str(spec_draft_n_max)])# Forward the explicit polarity; a future default flip on one# layer must not silently invert behaviour for the other.args.append("--load-in-4bit" if load_in_4bit else "--no-load-in-4bit")@@ -2367,6 +2395,8 @@ def run(load_in_4bit = load_in_4bit,gpu_memory_mode = gpu_memory_mode,tensor_parallel = tensor_parallel,+ speculative_type = speculative_type,+ spec_draft_n_max = spec_draft_n_max,llama_extra_args = extra_llama_args,)except RuntimeError as exc:diff --git a/unsloth_cli/tests/test_inference_chat.py b/unsloth_cli/tests/test_inference_chat.pyindex dbb3c7b125c..d32bf46d016 100644--- a/unsloth_cli/tests/test_inference_chat.py+++ b/unsloth_cli/tests/test_inference_chat.py@@ -146,6 +146,11 @@ def test_inference_exposes_gguf_runtime_options():extra = _option(inference, "llama_extra_args")assert "--llama-extra-arg" in (getattr(extra, "param_decls", None) or [])+ spec_type = _option(inference, "speculative_type")+ assert "--speculative-type" in (getattr(spec_type, "param_decls", None) or [])+ draft_n = _option(inference, "spec_draft_n_max")+ assert "--spec-draft-n-max" in (getattr(draft_n, "param_decls", None) or [])+def test_mlx_distributed_info_reads_launch_env(monkeypatch, tmp_path):_clear_mlx_distributed_env(monkeypatch)@@ -206,6 +211,11 @@ def test_chat_command_is_registered_with_options():extra = _option(chatmod.chat, "llama_extra_args")assert "--llama-extra-arg" in (getattr(extra, "param_decls", None) or [])+ spec_type = _option(chatmod.chat, "speculative_type")+ assert "--speculative-type" in (getattr(spec_type, "param_decls", None) or [])+ draft_n = _option(chatmod.chat, "spec_draft_n_max")+ assert "--spec-draft-n-max" in (getattr(draft_n, "param_decls", None) or [])+class _FakeBackend:def __init__(self):@@ -477,6 +487,8 @@ def test_http_backend_load_forwards_gguf_runtime_options(monkeypatch):max_seq_length = 8192,load_in_4bit = False,tensor_parallel = True,+ speculative_type = "dspark",+ spec_draft_n_max = 3,llama_extra_args = ["--top-k", "20"],)@@ -490,6 +502,8 @@ def test_http_backend_load_forwards_gguf_runtime_options(monkeypatch):"max_seq_length": 8192,"load_in_4bit": False,"tensor_parallel": True,+ "speculative_type": "dspark",+ "spec_draft_n_max": 3,"llama_extra_args": ["--top-k", "20"],},None,@@ -676,11 +690,13 @@ def test_deferred_error_helper_defaults_a_missing_status():"gguf_file": "/models/model.gguf","gguf_mmproj_file": "/models/mmproj.gguf","gguf_mtp_file": "/models/mtp.gguf",+ "gguf_dspark_file": "/models/dspark-model.gguf",},{"gguf_path": "/models/model.gguf","mmproj_path": "/models/mmproj.gguf","mtp_draft_path": "/models/mtp.gguf",+ "dspark_draft_path": "/models/dspark-model.gguf",},),],@@ -736,6 +752,8 @@ def test_load_gguf_backend_forwards_source_and_runtime_options(hf_token = "hf_x",max_seq_length = 8192,tensor_parallel = True,+ speculative_type = "dspark",+ spec_draft_n_max = 3,llama_extra_args = ["--top-k", "20"],)@@ -746,6 +764,8 @@ def test_load_gguf_backend_forwards_source_and_runtime_options("model_identifier": "org/model-GGUF","is_vision": False,"n_ctx": 8192,+ "speculative_type": "dspark",+ "spec_draft_n_max": 3,"tensor_parallel": True,"extra_args": ["--top-k", "20"],**expected_source,@@ -916,6 +936,10 @@ def test_chat_forwards_gguf_runtime_options_to_loader(monkeypatch):["fake-model","--tensor-parallel",+ "--speculative-type",+ "dspark",+ "--spec-draft-n-max",+ "3","--llama-extra-arg=--top-k","--llama-extra-arg","20",@@ -932,6 +956,8 @@ def test_chat_forwards_gguf_runtime_options_to_loader(monkeypatch):"max_seq_length": 4096,"load_in_4bit": True,"tensor_parallel": True,+ "speculative_type": "dspark",+ "spec_draft_n_max": 3,"llama_extra_args": ["--top-k", "20"],},)@@ -964,6 +990,10 @@ def test_inference_forwards_gguf_runtime_options_to_loader(monkeypatch):"fake-model","hello","--tensor-parallel",+ "--speculative-type",+ "dspark",+ "--spec-draft-n-max",+ "3","--llama-extra-arg=--top-k","--llama-extra-arg","20",@@ -979,6 +1009,8 @@ def test_inference_forwards_gguf_runtime_options_to_loader(monkeypatch):"max_seq_length": 2048,"load_in_4bit": True,"tensor_parallel": True,+ "speculative_type": "dspark",+ "spec_draft_n_max": 3,"llama_extra_args": ["--top-k", "20"],},)diff --git a/unsloth_cli/tests/test_studio_run_parallel_flag.py b/unsloth_cli/tests/test_studio_run_parallel_flag.pyindex 5c76fe3bd00..dabcef2ed9a 100644--- a/unsloth_cli/tests/test_studio_run_parallel_flag.py+++ b/unsloth_cli/tests/test_studio_run_parallel_flag.py@@ -78,6 +78,21 @@ def test_gpu_memory_mode_option_is_registered_with_auto_default():assert getattr(opt, "rich_help_panel", None) == "Model"+def test_speculative_options_are_registered():+ studio_mod = _load_run_command()+ import inspect++ sig = inspect.signature(studio_mod.run)+ spec_type = sig.parameters["speculative_type"].default+ draft_n = sig.parameters["spec_draft_n_max"].default+ assert set(getattr(spec_type, "param_decls", None) or []) == {"--speculative-type"}+ assert getattr(spec_type, "default", "missing") is None+ assert set(getattr(draft_n, "param_decls", None) or []) == {"--spec-draft-n-max"}+ assert getattr(draft_n, "default", "missing") is None+ assert getattr(draft_n, "min", None) == 1+ assert getattr(draft_n, "max", None) == 16++def test_parallel_default_is_four():"""Default must stay at 4 so plain `unsloth studio run` is unchanged."""studio_mod = _load_run_command()@@ -410,6 +425,39 @@ def test_reexec_omits_default_gpu_memory_mode(monkeypatch):assert "--gpu-memory-mode" not in captured[0]["argv"]+def test_reexec_forwards_speculative_options(monkeypatch):+ result, captured = _invoke_run(+ monkeypatch,+ _BASE + ["--speculative-type", "dspark", "--spec-draft-n-max", "3"],+ )+ assert len(captured) == 1, result.output+ argv = captured[0]["argv"]+ assert _value_after(argv, "--speculative-type") == "dspark", argv+ assert _value_after(argv, "--spec-draft-n-max") == "3", argv+++def test_reexec_omits_unset_speculative_options(monkeypatch):+ result, captured = _invoke_run(monkeypatch, _BASE)+ assert len(captured) == 1, result.output+ argv = captured[0]["argv"]+ assert "--speculative-type" not in argv+ assert "--spec-draft-n-max" not in argv+++ "args",+ [+ ["--speculative-type", "invalid"],+ ["--spec-draft-n-max", "0"],+ ["--spec-draft-n-max", "17"],+ ],+)+def test_run_rejects_invalid_speculative_options(monkeypatch, args):+ result, captured = _invoke_run(monkeypatch, _BASE + args)+ assert result.exit_code != 0+ assert captured == []++def test_run_rejects_invalid_gpu_memory_mode(monkeypatch):result, captured = _invoke_run(monkeypatch,@@ -461,6 +509,31 @@ def test_load_model_http_payload_for_gpu_memory_mode(monkeypatch, mode, expectedassert captured["request"].get_header("Authorization") == "Bearer sk-test"+def test_load_model_http_payload_for_dspark(monkeypatch):+ studio_mod = _load_run_command()+ captured = {}++ def urlopen(request, timeout):+ captured["request"] = request+ return BytesIO(b'{"model": "owner/model-GGUF"}')++ monkeypatch.setattr(studio_mod.urllib.request, "urlopen", urlopen)+ studio_mod._load_model_via_http(+ port = 8888,+ api_key = "sk-test",+ model = "owner/model-GGUF",+ gguf_variant = None,+ max_seq_length = 8192,+ load_in_4bit = True,+ speculative_type = "dspark",+ spec_draft_n_max = 3,+ )++ payload = json.loads(captured["request"].data)+ assert payload["speculative_type"] == "dspark"+ assert payload["spec_draft_n_max"] == 3++def test_load_model_http_fails_on_a_deferred_error(monkeypatch):"""A slow load commits its 200 and pads the body (routes/inference.py_tunnel_safe_json), so a late failure arrives in-band; it must still surface as the