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: honour the GPU-layer split for DiffusionGemma loads (#7575)
Leo Borcherdingeb92c60e0b5b
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex cf7f2d9350a..909bc42bb7c 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -7,6 +7,7 @@ Manages a llama-server subprocess and proxies chat completions through itsOpenAI-compatible /v1/chat/completions endpoint."""+import astimport atexitimport contextlibimport functools@@ -1748,6 +1749,80 @@ def _extra_args_set_any_flag(extra_args: Optional[Iterable[str]], flags: Collectreturn False+def _diffusion_manual_ngl(gpu_memory_mode: str, gpu_layers: int) -> Optional[int]:+ """The --ngl the diffusion runner would launch with, or None for its default.++ Only an explicit manual count reaches the child; Auto (-1) and Unsloth mode defer.+ Shared with both dedup guards, so an inert manual preference cannot loop.+ """+ return int(gpu_layers) if (gpu_memory_mode == "manual" and int(gpu_layers) >= 0) else None+++def _scale_diffusion_required_gb(required_gb: float, ngl: int, n_layers: Optional[int]) -> float:+ """GPU share of a partially offloaded diffusion GGUF, for the training guard.++ Only the ``ngl`` resident layers compete for VRAM; sizing the whole file 409s a+ split that fits. An unknown layer count keeps the full estimate."""+ if not n_layers or n_layers <= 0 or ngl >= n_layers:+ return required_gb+ return required_gb * (ngl / n_layers)+++def _source_declares_option(source: str, option: str) -> bool:+ """True iff ``source`` really registers ``option`` on an argparse parser.++ Parsed, not grepped: a substring test matches the flag in a comment and misses it+ when quoted differently. Falls back to a substring scan when the file will not parse.+ """+ try:+ tree = ast.parse(source)+ except (SyntaxError, ValueError):+ return option in source+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ func = node.func+ if not (isinstance(func, ast.Attribute) and func.attr == "add_argument"):+ continue+ for arg in node.args:+ if isinstance(arg, ast.Constant) and arg.value == option:+ return True+ return False+++def _shim_supports_ngl(shim_cmd: List[str]) -> bool:+ """Whether the resolved diffusion shim accepts --ngl.++ The package floor still allows an unsloth_zoo without the flag and argparse exits+ on an unknown option, so emitting it blindly breaks the launch. Read the source+ rather than spawning a probe: the launch path is already slow.+ """+ # _find_diffusion_assets emits a file override ([python, <path>]) or the installed+ # package ([python, -m, <module>]). Key on the shape, not the suffix (an override may+ # be extensionless, .pyw or SHIM.PY), and probe that exact file: a sibling shim.py+ # answers for a different shim than argparse will run.+ if len(shim_cmd) >= 2 and "-m" not in shim_cmd:+ candidates = [Path(shim_cmd[-1])]+ else:+ candidates = []+ try:+ import importlib.util+ spec = importlib.util.find_spec("unsloth_zoo")+ if spec is not None and spec.submodule_search_locations:+ pkg_dir = Path(list(spec.submodule_search_locations)[0])+ candidates.append(pkg_dir / "diffusion_studio" / "shim.py")+ except Exception:+ return False+ for path in candidates:+ try:+ source = path.read_text(encoding = "utf-8", errors = "ignore")+ except OSError:+ continue+ if _source_declares_option(source, "--ngl"):+ return True+ return False++def _swa_full_from_args_or_env(extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None) -> bool:@@ -2402,6 +2477,8 @@ class LlamaCppBackend:self._stats_logger = None # vLLM-style engine-stats poller, set on load# Set by _classify_gpu_offload after _wait_for_health.self._gpu_offload_active: Optional[bool] = None+ # Diffusion only: the split the running child was asked for.+ self._diffusion_requested_ngl: Optional[int] = Noneself._context_length: Optional[int] = Noneself._effective_context_length: Optional[int] = Noneself._max_context_length: Optional[int] = None@@ -2920,6 +2997,14 @@ class LlamaCppBackend:"""Requested --gpu-layers for manual mode (-1 when not manual)."""return self._gpu_layers+ @property+ def diffusion_requested_ngl(self) -> Optional[int]:+ """The diffusion split the live runner was ASKED for, or None for the default.++ Differs from ``gpu_layers`` only when the shim could not take the split: that+ reports what is running, this keeps the ask so a repeat still dedupes."""+ return getattr(self, "_diffusion_requested_ngl", None)+@propertydef n_cpu_moe(self) -> int:"""MoE expert layers manual mode kept on CPU (--n-cpu-moe); 0 = none."""@@ -5779,8 +5864,28 @@ class LlamaCppBackend:return None+ def diffusion_split_supported(self) -> bool:+ """Whether a diffusion launch right now would honour --ngl.++ Mirrors the launch gate for the training guard: a split the launcher will drop+ must be guarded as GPU-resident. False when no shim resolves or the probe fails,+ matching the launcher's own fallback."""+ try:+ assets = self._find_diffusion_assets()+ except Exception:+ return False+ if assets is None:+ return False+ shim_cmd, _visual_bin, _extra_pythonpath = assets+ return _shim_supports_ngl(shim_cmd)+@staticmethod- def _diffusion_gpu_arg(gpu_ids: Optional[List[int]], *, cpu_only: bool = False) -> str:+ def _diffusion_gpu_arg(+ gpu_ids: Optional[List[int]],+ *,+ cpu_only: bool = False,+ force_cpu: bool = False,+ ) -> str:"""Device token passed to the diffusion visual-server child.The visual engine replaces its child's CUDA visibility mask with this@@ -5788,6 +5893,12 @@ class LlamaCppBackend:parent's mask rather than turning a parent-relative ordinal into a newphysical selection."""+ # force_cpu alone outranks the picker: zero GPU layers place nothing, and a real+ # device would let the child hold a context while _gpu_offload_active reports+ # False, making the training VRAM coordinator skip the unload. cpu_only stays+ # *below* the picker: an explicit pick wins on a host whose GPU torch cannot see.+ if force_cpu:+ return ""if gpu_ids:return str(sorted(gpu_ids)[0])if cpu_only:@@ -5812,11 +5923,15 @@ class LlamaCppBackend:n_ctx: int,extra_args: Optional[List[str]],gpu_ids: Optional[List[int]] = None,+ gpu_memory_mode: Literal["auto", "manual"] = "auto",+ gpu_layers: int = -1,) -> bool:"""Launch the OpenAI-compat diffusion shim (which drives the on-devicevisual decoder) and wait for health. Presents the same /v1 + /healthinterface as llama-server, so the rest of Unsloth is unchanged.- """++ Manual mode forwards gpu_layers as --ngl so a GGUF larger than VRAM can be+ split across GPU and RAM; auto leaves the runner's all-layers default."""assets = self._find_diffusion_assets()if assets is None:raise RuntimeError(@@ -5833,15 +5948,32 @@ class LlamaCppBackend:# Auto-size (0): the visual server probes the largest context that fits this GPU's VRAM# (capped at the training context). An explicit in-range n_ctx overrides it.maxtok = n_ctx if (n_ctx and 0 < n_ctx <= 65536) else 0+ # Manual mode: honour the picked split. Without it the runner pins every layer+ # to GPU and a GGUF larger than VRAM dies in cudaMalloc even at 0 layers+ # (#7574). An older shim has no --ngl, so drop it rather than die in argparse.+ manual_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers)+ if manual_ngl is not None and not _shim_supports_ngl(shim_cmd):+ logger.warning(+ "DiffusionGemma: ignoring the %d GPU-layer split; the installed "+ "unsloth_zoo shim has no --ngl. Upgrade unsloth_zoo to set the split.",+ manual_ngl,+ )+ manual_ngl = None# No visible CUDA GPU: a genuine CPU host, or a GPU host masked with# CUDA_VISIBLE_DEVICES="" to force CPU serving. Keep the visual-server child# CPU-masked (empty --gpu) so the shim does not re-expose GPU 0 via its default.cpu_only = self._effective_gpu_count() == 0+ # Stronger than cpu_only and deliberately not derived from it: _effective_gpu_count+ # is torch.cuda only, so it reads 0 on Metal, Vulkan, Windows-HIP or Intel XPU hosts+ # the visual server will happily use. Only an explicit zero-layer split keeps the+ # weights off every backend, and a real --gpu token there would let the child hold a+ # CUDA context while _gpu_offload_active reports False, which the coordinator trusts.+ holds_no_gpu = manual_ngl == 0# Honor the GPU picker first: the diffusion runner takes a single device,# so use the lowest selected GPU (matches the sorted set recorded below, so# the device used == the echoed gpu_ids[0]). With no pick, fall back to the# CPU-only mask, else DG_GPU / 0.- gpu = self._diffusion_gpu_arg(gpu_ids, cpu_only = cpu_only)+ gpu = self._diffusion_gpu_arg(gpu_ids, cpu_only = cpu_only, force_cpu = holds_no_gpu)cmd = list(shim_cmd) + ["--gguf",@@ -5855,6 +5987,17 @@ class LlamaCppBackend:"--maxtok",str(maxtok),]+ if manual_ngl is not None:+ cmd += ["--ngl", str(manual_ngl)]+ # Block diffusion is compute-bound, so CPU-side layers cost far more than on an+ # autoregressive model (~6 tok/s vs ~31 for non-diffusion Gemma). Make the+ # tradeoff visible instead of swapping an OOM for a slow model.+ logger.warning(+ "DiffusionGemma: %d GPU layers requested. Layers left on CPU are much "+ "slower for block diffusion than for a regular model; prefer a smaller "+ "quant over a large CPU split if throughput matters.",+ manual_ngl,+ )env = child_env_without_native_path_secret()# `python -m unsloth_zoo.diffusion_studio.shim` imports unsloth_zoo, which@@ -5926,12 +6069,18 @@ class LlamaCppBackend:self._flash_attn_enabled = Trueself._effective_cache_types = ("f16", "f16")self._kv_cache_context_total = None- self._gpu_offload_active = True- # Diffusion doesn't use the llama.cpp GPU-memory knobs; reset them to- # defaults (the picked device is still recorded below) so /load, /status- # and reload dedup don't report a previous GGUF's manual settings.- self._gpu_memory_mode = "auto"- self._gpu_layers = -1+ # False means "confirmed to hold no VRAM" and makes the training coordinator skip+ # the unload, so it is claimed only for a zero-layer split.+ self._gpu_offload_active = not holds_no_gpu+ # Diffusion uses only the layer split of the llama.cpp GPU-memory knobs: record what+ # was applied (so /load, /status and reload dedup agree with the child) and reset the+ # rest so a previous GGUF's manual settings are not reported.+ self._gpu_memory_mode = gpu_memory_mode if manual_ngl is not None else "auto"+ self._gpu_layers = manual_ngl if manual_ngl is not None else -1+ # What was ASKED for, not always what was applied (no --ngl downgrades it above).+ # /status reports reality via _gpu_layers, but the dedup guards must compare like+ # with like or the same request reloads on every /load.+ self._diffusion_requested_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers)self._n_cpu_moe = 0self._tensor_split = None# Diffusion is never tensor-parallel; clear any state left by a prior TP@@ -5964,7 +6113,7 @@ class LlamaCppBackend:healthy = self._wait_for_health(timeout = 600.0)if healthy:self._healthy = True- self._gpu_offload_active = True+ self._gpu_offload_active = not holds_no_gpuif extra_args is not None:self._extra_args = list(extra_args)self._extra_args_source = (model_identifier, hf_variant)@@ -7451,6 +7600,8 @@ class LlamaCppBackend:n_ctx = n_ctx,extra_args = extra_args,gpu_ids = gpu_ids,+ gpu_memory_mode = gpu_memory_mode,+ gpu_layers = gpu_layers,)if not binary:@@ -10130,10 +10281,25 @@ class LlamaCppBackend:):return False- # The diffusion runner is mode-agnostic (always "auto", ignores the- # layer/MoE/split knobs), so a standing manual preference in the- # request must not force a needless reload -- only the GPU pick matters.- if not self._is_diffusion:+ # The diffusion runner takes the layer split but ignores the MoE/split knobs, so+ # only the GPU pick and the effective --ngl matter here.+ if self._is_diffusion:+ # Compare the EFFECTIVE split, not the raw mode: a standing manual preference+ # would reload forever, while raw gpu_layers would miss that Auto(-1) and+ # Unsloth mode both mean "runner default".+ requested_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers)+ if requested_ngl != self.diffusion_requested_ngl:+ return False+ # An identical ask whose split was DROPPED at launch (old shim) still dedupes,+ # unless the shim has gained --ngl since (zoo upgraded mid-session), in which+ # case the reload finally applies it.+ if (+ requested_ngl is not None+ and self._gpu_layers != requested_ngl+ and self.diffusion_split_supported()+ ):+ return False+ else:requested_extra_args = extra_args if extra_args is not None else self._extra_argsif self._swa_full != _swa_full_from_args_or_env(requested_extra_args):return False@@ -10420,6 +10586,9 @@ class LlamaCppBackend:# isn't seen as a crash; a real crash never routes through here.self._stop_mtp_crash_watchdog()self._reset_effective_parallel_slots()+ # Cleared before the early return, not in the finally below, so a stale split never+ # outlives its runner even when there was no process to kill.+ self._diffusion_requested_ngl = Noneif self._process is None:returntry:diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 7bd2f1cf690..aa0ff6c9770 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -279,6 +279,16 @@ class ValidateModelRequest(BaseModel):"delegate fitting to llama.cpp, while explicit layers are user-owned."),)+ gpu_layers: int = Field(+ -1,+ ge = -1,+ description = (+ "Layer count intended for the follow-up load, so the coexistence estimate "+ "sizes like /load. Only 0 changes the verdict: a zero-layer DiffusionGemma "+ "split places no layers on any device, so it cannot compete with training "+ "for VRAM. -1 (Auto) keeps the previous behaviour for callers that omit it."+ ),+ )n_parallel: Optional[int] = Field(None,ge = PARALLEL_MIN,@@ -338,6 +348,14 @@ class ValidateModelResponse(BaseModel):is_diffusion: bool = Field(False, description = "Whether this is a block-diffusion model (DiffusionGemma)")+ diffusion_unknown: bool = Field(+ False,+ description = "Whether the diffusion check came back inconclusive: the GGUF is not "+ "downloaded yet (or its header is unreadable) and its name does not carry the "+ "DiffusionGemma family, so is_diffusion == False here means 'not known to be "+ "diffusion', NOT 'known to be an ordinary GGUF'. Callers that choose a GPU-layer "+ "split before the load must treat this as possibly-diffusion.",+ )is_lora: bool = Field(False, description = "Whether this is a LoRA adapter")is_vision: bool = Field(False, description = "Whether this is a vision-capable model")requires_trust_remote_code: bool = Field(@@ -451,6 +469,13 @@ class LoadResponse(BaseModel):is_diffusion: bool = Field(False, description = "Whether model is a block-diffusion model (DiffusionGemma)")+ diffusion_requested_ngl: Optional[int] = Field(+ None,+ description = "GPU-layer count the diffusion runner was ASKED for, when that differs "+ "from what it applied: an unsloth_zoo shim without --ngl drops the split and runs "+ "Auto, so gpu_layers reports -1 while this reports the standing request. None for "+ "non-diffusion models and whenever the ask and the applied split agree.",+ )is_audio: bool = Field(False, description = "Whether model is a TTS audio model")audio_type: Optional[str] = Field(None, description = "Audio codec type: snac, csm, bicodec, dac")has_audio_input: bool = Field(False, description = "Whether model accepts audio input (ASR)")@@ -635,6 +660,13 @@ class InferenceStatusResponse(BaseModel):is_diffusion: bool = Field(False, description = "Whether the active model is a block-diffusion model (DiffusionGemma)")+ diffusion_requested_ngl: Optional[int] = Field(+ None,+ description = "GPU-layer count the diffusion runner was ASKED for, when that differs "+ "from what it applied: an unsloth_zoo shim without --ngl drops the split and runs "+ "Auto, so gpu_layers reports -1 while this reports the standing request. None for "+ "non-diffusion models and whenever the ask and the applied split agree.",+ )gguf_variant: Optional[str] = Field(None, description = "GGUF quantization variant (e.g. Q4_K_M)")is_audio: bool = Field(False, description = "Whether the active model is a TTS audio model")audio_type: Optional[str] = Field(None, description = "Audio codec type: snac, csm, bicodec, dac")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex f43d1580440..df277e55204 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3555,10 +3555,28 @@ def _request_matches_loaded_settings(effective_extra, request.tensor_parallel, llama_backend.tensor_parallel):return False- # The diffusion runner is mode-agnostic (it always reports "auto" and ignores- # the layer/MoE/split knobs), so a standing manual preference in the request- # must not force a needless reload -- only the GPU pick matters.- if not llama_backend.is_diffusion:+ # The diffusion runner takes the layer split but ignores the MoE/split knobs, so only+ # the GPU pick and the effective --ngl matter for it.+ if llama_backend.is_diffusion:+ # Compare the EFFECTIVE split, not the raw mode: a standing manual preference would+ # reload forever, while raw gpu_layers would miss that Auto(-1) and Unsloth mode both+ # mean "runner default". And compare against what the runner was ASKED for, not what+ # it applied: without --ngl the two differ and the same request mismatches forever.+ from core.inference.llama_cpp import _diffusion_manual_ngl++ loaded_ngl = llama_backend.diffusion_requested_ngl+ requested_ngl = _diffusion_manual_ngl(request.gpu_memory_mode, request.gpu_layers)+ if requested_ngl != loaded_ngl:+ return False+ # A dropped split (old shim) still dedupes, unless the shim has gained --ngl+ # since (zoo upgraded mid-session). Mirrors _already_in_target_state.+ if (+ requested_ngl is not None+ and llama_backend.gpu_layers != requested_ngl+ and llama_backend.diffusion_split_supported()+ ):+ return False+ else:if request.gpu_memory_mode != llama_backend.gpu_memory_mode:return False# Manual: a layer-count change always reloads; MoE/split only matter with@@ -4921,6 +4939,25 @@ def _estimate_gguf_required_gb(return None+def _gguf_layer_count(config: ModelConfig) -> Optional[int]:+ """Total block count from a local GGUF header, or None (remote / unreadable)."""+ try:+ main = getattr(config, "gguf_file", None)+ if not (main and Path(main).is_file()):+ repo = getattr(config, "gguf_hf_repo", None)+ variant = getattr(config, "gguf_variant", None)+ if repo and variant:+ from hub.utils.gguf import resolve_local_gguf_path+ main = resolve_local_gguf_path(repo, variant)+ if main and Path(main).is_file():+ probe = LlamaCppBackend()+ probe._read_gguf_metadata(str(main))+ return getattr(probe, "_n_layers", None) or None+ except Exception as e:+ logger.debug("Could not read GGUF layer count for training guard: %s", e)+ return None++def _classify_diffusion_gguf(config: ModelConfig) -> Optional[bool]:"""Classify a GGUF as diffusion, normal, or unknown before loading."""identity = " ".join(@@ -5124,6 +5161,7 @@ def _guard_chat_load_against_training(cache_type_kv: Optional[str] = None,tensor_parallel: bool = False,gpu_memory_mode: Literal["auto", "manual"] = "auto",+ gpu_layers: int = -1,gpu_ids_are_vulkan_ordinals: bool = False,diffusion_kind: Optional[bool] | object = _DIFFUSION_KIND_UNSET,) -> None:@@ -5133,10 +5171,10 @@ def _guard_chat_load_against_training(effective quantization (see _effective_load_in_4bit). Manual chat-GGUFplacement is an explicit override: Auto layers delegate fitting tollama.cpp's ``--fit`` and pinned layers are owned by the user, so neither is- estimated here. Diffusion is still guarded because its mode-agnostic runner- ignores those controls and uses one GPU. An unclassified GGUF is guarded as- potentially diffusion until its local header proves otherwise. Other loads- raise HTTP 409 when they would not fit beside training.+ estimated here. Diffusion is still guarded because its runner uses one GPU, except+ for an explicit zero-layer split, which places no layers at all; an unclassified+ GGUF is guarded as potentially diffusion until its local header proves otherwise.+ Other loads raise HTTP 409 when they would not fit beside training."""from core.training import get_training_backendfrom routes.training_vram import can_load_chat_during_training@@ -5148,11 +5186,32 @@ def _guard_chat_load_against_training(logger.warning("Could not check training state for chat-load guard: %s", e)return+ from core.inference.llama_cpp import _diffusion_manual_ngl, _scale_diffusion_required_gb+is_gguf = bool(getattr(config, "is_gguf", False))if diffusion_kind is _DIFFUSION_KIND_UNSET:diffusion_kind = _classify_diffusion_gguf(config) if is_gguf else Falseif is_gguf and gpu_memory_mode == "manual" and diffusion_kind is False:return+ # A zero-layer diffusion split places no model layers on any device, so it cannot compete+ # with training for VRAM. Mirrors the loader, which folds the same condition into its+ # cpu_only (core/inference/llama_cpp.py).+ diffusion_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers) if is_gguf else None+ if diffusion_ngl is not None and diffusion_kind is not False:+ # The loader drops the split when the shim has no --ngl and launches GPU-resident.+ # Guard what will run, not what was asked, or a zero-layer request skips the VRAM+ # check while the child takes a whole GPU.+ try:+ if not get_llama_cpp_backend().diffusion_split_supported():+ diffusion_ngl = None+ except Exception as e:+ logger.warning("Could not probe diffusion shim for chat-load guard: %s", e)+ diffusion_ngl = None+ # `is True`, not `is not False`: only a CONFIRMED diffusion GGUF places nothing at ngl 0.+ # On a possibly-ordinary GGUF a device pin, tensor mode, mmproj or a GPU drafter keeps it+ # resident (see LlamaCppBackend._zero_offload_keeps_gpu_visible).+ if is_gguf and diffusion_kind is True and diffusion_ngl == 0:+ returndiffusion_gpu = Noneif is_gguf and diffusion_kind is not False and not gpu_ids_are_vulkan_ordinals:@@ -5160,6 +5219,11 @@ def _guard_chat_load_against_training(# followed by DG_GPU, the first parent-visible token, then GPU 0. Suppressed# for a Vulkan-ordinal pin so single-device CUDA budgeting can't override the# Vulkan-ordinal path (single_device_gpu wins in can_load_chat_during_training).+ # No force_cpu, deliberately: a CONFIRMED zero-layer split already returned above, so+ # ngl 0 here means an UNCLASSIFIED GGUF -- and an empty token makes+ # can_load_chat_during_training short-circuit to "cpu_only" and always allow the+ # load, on an assumption that only holds for real diffusion. Let the picker choose a+ # device so an ordinary GGUF keeping VRAM at --gpu-layers 0 stays conservatively sized.diffusion_gpu = LlamaCppBackend._diffusion_gpu_arg(requested_gpu_ids,cpu_only = LlamaCppBackend._effective_gpu_count() == 0,@@ -5207,6 +5271,18 @@ def _guard_chat_load_against_training(if is_ggufelse None)+ # A confirmed-diffusion positive split puts only ngl/n_layers of the weights on the GPU (a+ # split the loader would drop was nulled above). Unknown classification keeps the full+ # estimate: its header was unreadable, so the layer count is too.+ if (+ required_override_gb is not None+ and diffusion_kind is True+ and diffusion_ngl is not None+ and diffusion_ngl > 0+ ):+ required_override_gb = _scale_diffusion_required_gb(+ required_override_gb, diffusion_ngl, _gguf_layer_count(config)+ )vulkan_free_vram_gb = Noneif is_gguf:@@ -5877,6 +5953,7 @@ async def _load_model_impl(llama_backend, native_grant_backed, llama_backend.model_identifier),is_diffusion = llama_backend.is_diffusion,+ diffusion_requested_ngl = llama_backend.diffusion_requested_ngl,is_audio = _gguf_is_audio,audio_type = _gguf_audio,has_audio_input = getattr(llama_backend, "_has_audio_input", False),@@ -6070,6 +6147,7 @@ async def _load_model_impl(cache_type_kv = request.cache_type_kv,tensor_parallel = bool(request.tensor_parallel),gpu_memory_mode = request.gpu_memory_mode,+ gpu_layers = request.gpu_layers,gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,diffusion_kind = diffusion_kind,)@@ -6348,6 +6426,7 @@ async def _load_model_impl(is_gguf = True,is_local_model = config.is_local,is_diffusion = llama_backend.is_diffusion,+ diffusion_requested_ngl = llama_backend.diffusion_requested_ngl,is_audio = _gguf_is_audio,audio_type = _gguf_audio,has_audio_input = llama_backend._has_audio_input,@@ -6873,6 +6952,7 @@ async def validate_model(cache_type_kv = request.cache_type_kv,tensor_parallel = request.tensor_parallel,gpu_memory_mode = request.gpu_memory_mode,+ gpu_layers = request.gpu_layers,gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,diffusion_kind = diffusion_kind,)@@ -6956,6 +7036,8 @@ async def validate_model(else getattr(config, "display_name", config.identifier),is_gguf = is_gguf,is_diffusion = is_gguf and diffusion_kind is True,+ # None = unreadable header + no family in the name, not "ordinary GGUF".+ diffusion_unknown = is_gguf and diffusion_kind is None,is_lora = getattr(config, "is_lora", False),is_vision = getattr(config, "is_vision", False),requires_trust_remote_code = requires_trust_remote_code,@@ -7720,6 +7802,7 @@ async def get_status(current_subject: str = Depends(get_current_subject)):llama_backend, _native_grant_backed, _model_id),is_diffusion = llama_backend.is_diffusion,+ diffusion_requested_ngl = llama_backend.diffusion_requested_ngl,gguf_variant = llama_backend.hf_variant,is_audio = getattr(llama_backend, "_is_audio", False),audio_type = _audio_type,diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.pyindex 31c8d0be371..36cb897b9fe 100644--- a/studio/backend/tests/test_chat_load_during_training.py+++ b/studio/backend/tests/test_chat_load_during_training.py@@ -486,6 +486,7 @@ class TestChatLoadGuardRoute(unittest.TestCase):llama_extra_args = None,cache_type_kv = None,tensor_parallel = False,+ gpu_layers = -1,):config = config or SimpleNamespace(is_gguf = False, is_lora = False, path = None)with _stub_guard_deps(@@ -502,6 +503,7 @@ class TestChatLoadGuardRoute(unittest.TestCase):cache_type_kv = cache_type_kv,tensor_parallel = tensor_parallel,gpu_memory_mode = gpu_memory_mode,+ gpu_layers = gpu_layers,gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,)@@ -607,6 +609,59 @@ class TestChatLoadGuardRoute(unittest.TestCase):self.assertEqual(captured[0]["single_device_gpu"], "1")self.assertEqual(captured[0]["requested_gpu_ids"], [3, 1])+ def _guard_zero_layer(self, *, diffusion_kind, captured):+ """Drive the guard with a manual zero-layer split and a shim that has --ngl."""+ config = SimpleNamespace(is_gguf = True)+ backend = SimpleNamespace(diffusion_split_supported = lambda: True)+ with (+ patch.object(self.route, "_classify_diffusion_gguf", return_value = diffusion_kind),+ patch.object(self.route, "get_llama_cpp_backend", return_value = backend),+ patch.object(self.route, "_estimate_gguf_required_gb", return_value = 12.5),+ patch.object(self.route.LlamaCppBackend, "_effective_gpu_count", return_value = 2),+ ):+ self._guard(+ config = config,+ captured = captured,+ training_active = True,+ decision = (False, {"reason": "must not run"}),+ gpu_memory_mode = "manual",+ gpu_layers = 0,+ )++ def test_zero_layer_diffusion_split_bypasses_the_training_guard(self):+ """A confirmed DiffusionGemma at ngl 0 places no layers, so it is not refused."""+ captured = []+ self._guard_zero_layer(diffusion_kind = True, captured = captured)+ self.assertEqual(captured, [])++ def test_zero_layer_unclassified_gguf_still_hits_the_training_guard(self):+ """An unreadable header is not a diffusion promise: --gpu-layers 0 on an+ ordinary GGUF can still hold VRAM, so the estimate must run."""+ captured = []+ with self.assertRaises(HTTPException) as ctx:+ self._guard_zero_layer(diffusion_kind = None, captured = captured)+ self.assertEqual(ctx.exception.status_code, 409)+ self.assertEqual(len(captured), 1)++ def test_zero_layer_unclassified_gguf_is_not_sized_as_cpu_only(self):+ """Reaching the guard is not enough: it must not be handed a CPU-only token.++ can_load_chat_during_training short-circuits an EMPTY single_device_gpu to+ "cpu_only" and always returns True, so an unclassified GGUF passed through with+ force_cpu would be allowed during training on an assumption that only holds for+ confirmed diffusion. The sibling test above stubs can_load, so it cannot see this.+ """+ captured = []+ with self.assertRaises(HTTPException):+ self._guard_zero_layer(diffusion_kind = None, captured = captured)+ self.assertEqual(len(captured), 1)+ token = captured[0].get("single_device_gpu")+ self.assertTrue(+ token is None or str(token).strip() != "",+ "an unclassified zero-layer GGUF must not be budgeted as CPU-only; "+ f"single_device_gpu was {token!r}, which training_vram reads as cpu_only",+ )+def test_unclassified_gguf_on_vulkan_build_budgets_as_ordinals(self):# Unknown GGUFs still use the Vulkan ordinal namespace selected by the build.captured = []diff --git a/studio/backend/tests/test_validate_diffusion_unknown.py b/studio/backend/tests/test_validate_diffusion_unknown.pynew file mode 100644index 00000000000..6335c276a4a--- /dev/null+++ b/studio/backend/tests/test_validate_diffusion_unknown.py@@ -0,0 +1,114 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""/api/inference/validate must report an INCONCLUSIVE diffusion check as such.++`_classify_diffusion_gguf` is a tri-state: True (diffusion), False (header read,+ordinary), None (nothing to read, and no family in the name).++The response used to collapse None into `is_diffusion = False`, so a caller could not+tell "ordinary GGUF" from "unknown". The staged-metadata preflight picks a GPU-layer+split from that answer, and /load may then apply it to a diffusion runner: an inherited+0 CPU-masks it, another count repartitions or OOMs it.+"""++import asyncio+import importlib.util+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++from models.inference import ValidateModelRequest+++_BACKEND_ROOT = Path(__file__).resolve().parent.parent+++def _load_route_module(name: str):+ spec = importlib.util.spec_from_file_location(name, _BACKEND_ROOT / "routes/inference.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++async def _noop_gpu_ids(_config, gpu_ids, **_kwargs):+ return gpu_ids, False+++class TestValidateReportsDiffusionUnknown(unittest.TestCase):+ def _validate(+ self,+ route,+ *,+ diffusion_kind,+ is_gguf = True,+ ):+ # Mirrors the real staged-metadata preflight; also skips the training guard.+ request = ValidateModelRequest(+ model_path = "someone/repacked-gguf",+ include_context_length = True,+ )+ config = SimpleNamespace(+ identifier = "someone/repacked-gguf",+ display_name = "repacked-gguf",+ is_gguf = is_gguf,+ is_lora = False,+ is_vision = False,+ gguf_file = None,+ )+ with (+ patch.object(+ route,+ "_resolve_model_identifier_for_request",+ return_value = ("someone/repacked-gguf", "someone/repacked-gguf", False),+ ),+ patch.object(route.ModelConfig, "from_identifier", return_value = config),+ patch.object(route, "_resolve_inherited_extra_args", return_value = None),+ patch.object(route, "_classify_diffusion_gguf", return_value = diffusion_kind),+ patch.object(route, "_resolve_gguf_gpu_ids_for_request", new = _noop_gpu_ids),+ patch.object(route, "_effective_load_in_4bit", return_value = True),+ ):+ return asyncio.run(route.validate_model(request, current_subject = "test-user"))++ def test_unclassifiable_gguf_is_reported_unknown_not_ordinary(self):+ """The bug: None must not look identical to a confirmed ordinary GGUF."""+ route = _load_route_module("inf_route_diffusion_unknown_1")+ resp = self._validate(route, diffusion_kind = None)+ self.assertFalse(resp.is_diffusion)+ self.assertTrue(+ resp.diffusion_unknown,+ "an unreadable/undownloaded GGUF with no family in its name is UNKNOWN; "+ "reporting it as a plain non-diffusion GGUF lets a caller inherit a "+ "GPU-layer split that /load will apply to a diffusion runner",+ )++ def test_confirmed_ordinary_gguf_is_not_unknown(self):+ route = _load_route_module("inf_route_diffusion_unknown_2")+ resp = self._validate(route, diffusion_kind = False)+ self.assertFalse(resp.is_diffusion)+ self.assertFalse(resp.diffusion_unknown)++ def test_confirmed_diffusion_gguf_is_not_unknown(self):+ route = _load_route_module("inf_route_diffusion_unknown_3")+ resp = self._validate(route, diffusion_kind = True)+ self.assertTrue(resp.is_diffusion)+ self.assertFalse(resp.diffusion_unknown)++ def test_non_gguf_is_never_unknown(self):+ """A transformers model is definitively not a diffusion GGUF."""+ route = _load_route_module("inf_route_diffusion_unknown_4")+ resp = self._validate(route, diffusion_kind = False, is_gguf = False)+ self.assertFalse(resp.is_diffusion)+ self.assertFalse(resp.diffusion_unknown)++ def test_flag_defaults_off_so_an_old_client_reads_the_same_response(self):+ """Additive field: absent/False keeps the pre-#7575 meaning of is_diffusion."""+ from models.inference import ValidateModelResponse++ resp = ValidateModelResponse(valid = True, message = "ok")+ self.assertFalse(resp.diffusion_unknown)+++if __name__ == "__main__":+ unittest.main()diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 8585bed6948..5d36597634a 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -1709,6 +1709,9 @@ async function autoLoadSmallestModel(): Promise<{? {gpu_ids: effectiveGpuIds ?? undefined,gpu_memory_mode: effectiveGpuMemoryMode,+ // Sized like the load below: a remembered manual DiffusionGemma+ // split (0 especially) must not be refused as a full-GGUF occupant.+ gpu_layers: effectiveGpuLayers,n_parallel: config.nParallel ?? null,}: {}),diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 240a23429b3..c2db5137f02 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -238,6 +238,9 @@ export async function validateModel(// --fit, while a pinned layer count is owned by the user. Tell validate// so it applies the same training-guard policy as /load.gpu_memory_mode: payload.gpu_memory_mode,+ // Only 0 changes the verdict: a zero-layer DiffusionGemma split places+ // no layers, so validate must not refuse what /load would accept.+ gpu_layers: payload.gpu_layers,// Slots scale the KV estimate; keep validate sized like the load.n_parallel: payload.n_parallel,}),@@ -263,6 +266,9 @@ export async function fetchGgufStagedMetadata(payload: {layerCount: number | null;moeLayerCount: number | null;isDiffusion: boolean;+ /** Unclassifiable, so `isDiffusion: false` above means "not known to be diffusion":+ * callers picking a GPU split must assume possibly-diffusion. */+ diffusionUnknown: boolean;}> {let nativePathLease: string | null = null;if (payload.nativePathToken) {@@ -272,11 +278,13 @@ export async function fetchGgufStagedMetadata(payload: {).nativePathLease;} catch {// Lease expired / revoked: degrade to no metadata (the load can re-mint).+ // Nothing was read, so the diffusion answer is unknown rather than false.return {contextLength: null,layerCount: null,moeLayerCount: null,isDiffusion: false,+ diffusionUnknown: true,};}}@@ -297,6 +305,8 @@ export async function fetchGgufStagedMetadata(payload: {layerCount: res.layer_count ?? null,moeLayerCount: res.moe_layer_count ?? null,isDiffusion: res.is_diffusion ?? false,+ // Absent on a pre-#7575 backend, which never reported the inconclusive case.+ diffusionUnknown: res.diffusion_unknown ?? false,};}diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsindex 4a3f331db7c..768edfd28b3 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts@@ -908,6 +908,9 @@ export function useChatModelRuntime() {...(isGguf? {gpu_memory_mode: loadGpuMemoryMode,+ // Sized like the follow-up /load: else a manual DiffusionGemma+ // split 409s during training even when it fits.+ gpu_layers: validateGpuLayers,n_parallel: validateNParallel,}: {}),diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 739254bb2b2..1fa09055485 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -57,6 +57,7 @@ export {reconcilePersistedGpuSelection,GPU_LAYERS_AUTO,} from "./stores/chat-runtime-store";+export { resolveStagedDiffusionClassification } from "./lib/gpu-placement";export {preferFullToolOutput,toolOutputKey,diff --git a/studio/frontend/src/features/chat/lib/gpu-placement.ts b/studio/frontend/src/features/chat/lib/gpu-placement.tsnew file mode 100644index 00000000000..fc5b3b45152--- /dev/null+++ b/studio/frontend/src/features/chat/lib/gpu-placement.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Placement sentinels and resolution rules shared by the load paths. Kept free+// of store / React imports so the contract is unit-testable.++// Manual-mode gpu_layers sentinel: -1 = Auto (hand layer + context sizing to+// llama.cpp's --fit). The Manual default; "all on GPU" is the slider's max.+export const GPU_LAYERS_AUTO = -1;++/** GPU placement a compare pane loads with.+ *+ * `own` is the pane's per-model config; `shared` is the live-store snapshot taken at+ * Send, so a sequential load's response echo cannot rewrite it mid-run.+ *+ * A pane's OWN split is sent rather than forced to Auto, since the diffusion runner+ * honours it (#7574). The shared snapshot is NOT inherited by a diffusion pane: its+ * layer count is bounded by another GGUF, no diffusion UI can show or clear it, and+ * a leaked 0 masks the devices entirely.+ */+export function resolveComparePlacement(+ own: { gpuMemoryMode?: "auto" | "manual"; gpuLayers?: number },+ shared: { gpuMemoryMode: "auto" | "manual"; gpuLayers: number },+ treatAsDiffusion: boolean,+): { gpuMemoryMode: "auto" | "manual"; gpuLayers: number } {+ return {+ gpuMemoryMode:+ own.gpuMemoryMode ?? (treatAsDiffusion ? "auto" : shared.gpuMemoryMode),+ gpuLayers:+ own.gpuLayers ?? (treatAsDiffusion ? GPU_LAYERS_AUTO : shared.gpuLayers),+ };+}++/** Whether a pane must get the diffusion-safe placement above.+ *+ * An UNCLASSIFIED GGUF counts: the preflight only reads a header already on disk, so+ * an undownloaded GGUF with no family in its name comes back `diffusion_unknown`, and+ * `/load` may then read a diffusion header and apply the inherited count anyway.+ * Non-GGUF panes are excluded: definitively not diffusion, and they send no placement.+ */+export function shouldPinDiffusionPlacement(+ targetIsGguf: boolean,+ isDiffusion: boolean | undefined,+ diffusionUnknown: boolean,+): boolean {+ if (!targetIsGguf) return false;+ return isDiffusion === true || diffusionUnknown;+}++/** The split an older shim DROPPED, recovered from a load/status response.+ *+ * A shim without `--ngl` cannot apply a manual split, so the runner reports Auto while+ * the backend keeps the ask in `diffusion_requested_ngl`. In-memory state carries that+ * across a reload but not a refresh, where the store starts at Auto and the response+ * alone looks like a genuine Auto run; the ask has to be restored or the next Apply+ * sends `manual/-1`, which the post-upgrade retry can never turn back into the count.+ *+ * Null when there is nothing to recover: not diffusion, a split that was actually+ * applied (mode "manual", so `gpu_layers` is authoritative), or no standing ask. Zero+ * is a real ask (CPU-only) and is preserved.+ */+export function recoverDroppedDiffusionSplit(+ isDiffusion: boolean | undefined,+ mode: "auto" | "manual",+ requestedNgl: number | null | undefined,+): number | null {+ if (isDiffusion !== true || mode === "manual") return null;+ return requestedNgl ?? null;+}++/** Tri-state diffusion classification for a staged (pre-load) GGUF selection.+ *+ * `undefined` means "not known" and must NOT be collapsed to false by a caller that+ * hands the answer on: a definite false tells the compare flow this is an ordinary+ * GGUF, skipping the re-probe above and letting an unconfigured pane inherit another+ * model's layer split (#7574).+ */+export function resolveStagedDiffusionClassification(+ knownDiffusion: boolean | undefined,+ staged:+ | { isDiffusion?: boolean; diffusionUnknown?: boolean }+ | null+ | undefined,+): boolean | undefined {+ if (knownDiffusion) return true;+ if (staged == null || staged.diffusionUnknown) return undefined;+ return staged.isDiffusion;+}diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 40f93a2d996..2ecad304e55 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -107,7 +107,10 @@ import {usePlusMenuPrefsStore,} from "./stores/plus-menu-prefs-store";import {- GPU_LAYERS_AUTO,+ resolveComparePlacement,+ shouldPinDiffusionPlacement,+} from "./lib/gpu-placement";+import {loadedGpuMemoryFields,type ReasoningEffort,reconcilePersistedGpuIds,@@ -1064,6 +1067,9 @@ export function SharedComposer({(sel.ggufVariant ?? null) != null ||sel.id.toLowerCase().endsWith(".gguf");let resolvedIsDiffusion = sel.isDiffusion;+ // Set when the preflight could not classify the GGUF, so a false+ // resolvedIsDiffusion below must not be read as "ordinary".+ let diffusionUnknown = false;if (targetIsGguf && resolvedIsDiffusion === undefined) {const preparedToken = await prepareHfTokenForUse(currentStore.hfToken,@@ -1071,13 +1077,13 @@ export function SharedComposer({if (!preparedToken.proceed) {throw new Error("Model load cancelled.");}- resolvedIsDiffusion = (- await fetchGgufStagedMetadata({- model_path: sel.id,- gguf_variant: sel.ggufVariant ?? null,- hf_token: preparedToken.token,- })- ).isDiffusion;+ const staged = await fetchGgufStagedMetadata({+ model_path: sel.id,+ gguf_variant: sel.ggufVariant ?? null,+ hf_token: preparedToken.token,+ });+ resolvedIsDiffusion = staged.isDiffusion;+ diffusionUnknown = staged.diffusionUnknown;}// Mirror single-view resolveLoadMaxSeqLength: a GGUF pane with no explicit// context loads at native (0 -> n_ctx_train), not the session maxSeqLength,@@ -1108,14 +1114,23 @@ export function SharedComposer({if (ownConfig.selectedGpuIds != null) {await ensureGpuDeviceCache();}- const effectiveGpuMemoryMode =- resolvedIsDiffusion- ? "auto"- : (ownConfig.gpuMemoryMode ?? compareLoadKnobs.gpuMemoryMode);- const effectiveGpuLayers =- resolvedIsDiffusion- ? GPU_LAYERS_AUTO- : (ownConfig.gpuLayers ?? compareLoadKnobs.gpuLayers);+ // A pane's OWN saved split is sent instead of being forced to Auto+ // (#7574); the shared Send-time snapshot is not, since its layer count+ // is bounded by another GGUF. Knobs the runner has no equivalent for+ // (MoE offload, tensor parallel) stay hard-forced. An UNCLASSIFIED GGUF+ // is pinned too: see lib/gpu-placement.ts.+ const {+ gpuMemoryMode: effectiveGpuMemoryMode,+ gpuLayers: effectiveGpuLayers,+ } = resolveComparePlacement(+ ownConfig,+ compareLoadKnobs,+ shouldPinDiffusionPlacement(+ targetIsGguf,+ resolvedIsDiffusion,+ diffusionUnknown,+ ),+ );const effectiveNCpuMoe =resolvedIsDiffusion? 0@@ -1169,6 +1184,9 @@ export function SharedComposer({? {gpu_ids: effectiveSelectedGpuIds ?? undefined,gpu_memory_mode: effectiveGpuMemoryMode,+ // Sized like the load below: a manual DiffusionGemma split+ // must not be validated as a full-GGUF occupant.+ gpu_layers: effectiveGpuLayers,// Slots scale the KV estimate; keep validate sized like the load.n_parallel: ownConfig.nParallel ?? 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 b86c31548fd..4a8ad80dabb 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -10,6 +10,10 @@ import {} from "@/hooks/use-gpu-info";import { toast } from "@/lib/toast";import { create } from "zustand";+import {+ GPU_LAYERS_AUTO,+ recoverDroppedDiffusionSplit,+} from "../lib/gpu-placement";import { isExternalModelId, parseExternalModelId } from "../external-providers";import {type ChatPresetSource,@@ -568,9 +572,8 @@ export function persistGpuMemoryModeOnLoad(if (resp.is_gguf && !resp.is_diffusion) saveGpuMemoryMode(mode);}-// Manual-mode gpu_layers sentinel: -1 = Auto (hand layer + context sizing to-// llama.cpp's --fit). The Manual default; "all on GPU" is the slider's max.-export const GPU_LAYERS_AUTO = -1;+// Re-exported from its dependency-free home so existing imports keep working.+export { GPU_LAYERS_AUTO } from "../lib/gpu-placement";// Round real-valued shares to integers summing exactly to `total`, giving the// leftover units to the largest fractional parts (largest-remainder method).@@ -677,6 +680,7 @@ export function loadedGpuMemoryFields(resp: {n_moe_layers?: number;gpu_ids?: number[] | null;requested_gpu_ids?: number[] | null;+ diffusion_requested_ngl?: number | null;}) {// GPU-memory state is meaningful only for a GGUF chat load. A non-GGUF response// still carries gpu_memory_mode (its default "auto" is serialized), so gate on@@ -721,6 +725,13 @@ export function loadedGpuMemoryFields(resp: {// once the shared system cache warms.const gpuIds =reportedGpuIds != null && gpuIndexKind !== null ? reportedGpuIds : null;+ // A shim without --ngl reports Auto while the backend still holds the ask, so recover+ // it: in-memory state survives a reload but not a refresh.+ const droppedSplit = recoverDroppedDiffusionSplit(+ resp.is_diffusion,+ mode,+ resp.diffusion_requested_ngl,+ );// Layer/MoE/split knobs apply (and are reported) only in manual mode; in auto// the server ignores them, so don't seed the loaded baseline or the editable// knobs with values it never applied. In manual, the server reports gpu_layers@@ -743,17 +754,28 @@ export function loadedGpuMemoryFields(resp: {// loaded baseline) -- else a later switch back to Manual would snapshot// and send a previous model's stale gpuLayers/nCpuMoe/split that this// load never applied. Mirrors the non-GGUF branch above.- gpuLayers: GPU_LAYERS_AUTO,+ // Diffusion excepted: an "auto" diffusion response may be an older shim+ // DROPPING a manual split. Restore the ask when the response carries it (a+ // refresh has none left in memory), else keep what is standing. Resetting the+ // slider would turn the ask into manual/-1, unapplyable even after the+ // unsloth_zoo upgrade that adds --ngl.+ ...(resp.is_diffusion+ ? droppedSplit != null+ ? { gpuLayers: droppedSplit }+ : {}+ : { gpuLayers: GPU_LAYERS_AUTO }),nCpuMoe: 0,splitRatio: null,};return {- // A diffusion GGUF runs mode-agnostic (pins all layers on one GPU, reports- // "auto"), so adopt everything a chat GGUF does EXCEPT the live standing- // preference -- the next chat load must still honor the user's manual choice.- // The loaded baseline is still "auto", but the UI hides mode controls for a- // loaded diffusion model so it can't read as dirty against the preference.- ...(resp.is_diffusion ? {} : { gpuMemoryMode: mode }),+ // A diffusion GGUF reporting "auto" ran on the runner's defaults, so an inert standing+ // manual preference must survive it. But "manual" means a split was actually applied+ // (#7574): adopt it, or a refresh hydrates back to "auto" while the runner serves one.+ ...(resp.is_diffusion && mode !== "manual"+ ? droppedSplit != null+ ? { gpuMemoryMode: "manual" as const }+ : {}+ : { gpuMemoryMode: mode }),loadedGpuMemoryMode: mode,ggufLayerCount: resp.n_layers ?? null,// MoE expert-layer count: the n_cpu_moe slider max, and 0 hides the slider.diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex c45d12eb3ed..cbb20844974 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -96,6 +96,9 @@ export interface ValidateModelResponse {display_name?: string | null;is_gguf?: boolean;is_diffusion?: boolean;+ /** The diffusion check was inconclusive, so `is_diffusion: false` above means+ * "not known to be diffusion", not "known to be ordinary". */+ diffusion_unknown?: boolean;is_lora?: boolean;is_vision?: boolean;requires_trust_remote_code?: boolean;@@ -167,6 +170,10 @@ export interface LoadModelResponse {is_gguf?: boolean;is_local_model?: boolean;is_diffusion?: boolean;+ /** GPU-layer count the diffusion runner was ASKED for, when it differs from what+ * it applied: a shim without --ngl runs Auto, so gpu_layers reports -1 while+ * this carries the standing request. */+ diffusion_requested_ngl?: number | null;is_audio?: boolean;audio_type?: string | null;has_audio_input?: boolean;@@ -231,6 +238,10 @@ export interface InferenceStatusResponse {is_gguf?: boolean;is_local_model?: boolean;is_diffusion?: boolean;+ /** GPU-layer count the diffusion runner was ASKED for, when it differs from what+ * it applied: a shim without --ngl runs Auto, so gpu_layers reports -1 while+ * this carries the standing request. */+ diffusion_requested_ngl?: number | null;gguf_variant?: string | null;is_audio?: boolean;audio_type?: 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 abcebb56b44..044a84d0718 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@@ -17,6 +17,7 @@ import {GPU_LAYERS_AUTO,fetchGgufStagedMetadata,readPersistedSpeculativeType,+ resolveStagedDiffusionClassification,useChatRuntimeStore,} from "@/features/chat";import { prepareHfTokenForUse } from "@/features/hf-auth";@@ -801,6 +802,7 @@ export function ModelConfigPage({layerCount: number | null;moeLayerCount: number | null;isDiffusion?: boolean;+ diffusionUnknown?: boolean;} | null>(null);useEffect(() => {if (contextFetchKey == null) {@@ -855,7 +857,13 @@ export function ModelConfigPage({contextFetchKey != null &&stagedDims == null &&(config.gpuMemoryMode === "manual" || config.selectedGpuIds != null);- const classifiedIsDiffusion = isDiffusion ? true : stagedDims?.isDiffusion;+ // Tri-state on purpose: an inconclusive probe stays undefined so onRun hands+ // "unknown" to the selection. Collapsing it to false would tell a compare pane+ // this is an ordinary GGUF, letting it inherit another model's split (#7574).+ const classifiedIsDiffusion = resolveStagedDiffusionClassification(+ isDiffusion,+ stagedDims,+ );const resolvedIsDiffusion = classifiedIsDiffusion === true;const gpuIndexKind =pinnableGpuContext(gpuDevices, resolvedIsDiffusion).indexKind ?? null;diff --git a/studio/frontend/tests/gpu-placement.test.ts b/studio/frontend/tests/gpu-placement.test.tsnew file mode 100644index 00000000000..ef3e6bc7077--- /dev/null+++ b/studio/frontend/tests/gpu-placement.test.ts@@ -0,0 +1,221 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import {+ GPU_LAYERS_AUTO,+ resolveComparePlacement,+ recoverDroppedDiffusionSplit,+ resolveStagedDiffusionClassification,+ shouldPinDiffusionPlacement,+} from "../src/features/chat/lib/gpu-placement.ts";++// The Send-time snapshot: Manual with 12 of another chat GGUF's layers on GPU.+const shared = { gpuMemoryMode: "manual" as const, gpuLayers: 12 };++test("a diffusion pane never inherits another model's layer split", () => {+ // An unremembered pane carries neither key, so `??` would fall through to shared.+ assert.deepEqual(resolveComparePlacement({}, shared, true), {+ gpuMemoryMode: "auto",+ gpuLayers: GPU_LAYERS_AUTO,+ });+});++test("a leaked zero cannot mask a diffusion pane's devices", () => {+ assert.deepEqual(+ resolveComparePlacement(+ {},+ { gpuMemoryMode: "manual", gpuLayers: 0 },+ true,+ ),+ { gpuMemoryMode: "auto", gpuLayers: GPU_LAYERS_AUTO },+ );+});++test("a diffusion pane's OWN split is honoured (#7574)", () => {+ assert.deepEqual(+ resolveComparePlacement(+ { gpuMemoryMode: "manual", gpuLayers: 0 },+ shared,+ true,+ ),+ { gpuMemoryMode: "manual", gpuLayers: 0 },+ );+});++test("a chat GGUF pane still inherits the Send-time snapshot", () => {+ assert.deepEqual(resolveComparePlacement({}, shared, false), {+ gpuMemoryMode: "manual",+ gpuLayers: 12,+ });+});++test("an own value wins over the snapshot for a chat GGUF too", () => {+ assert.deepEqual(+ resolveComparePlacement(+ { gpuMemoryMode: "auto", gpuLayers: 3 },+ shared,+ false,+ ),+ { gpuMemoryMode: "auto", gpuLayers: 3 },+ );+});++// ── an unclassified GGUF must not inherit the split either ──+// An undownloaded GGUF with no "DiffusionGemma" in its name comes back+// is_diffusion=false + diffusion_unknown=true; /load may then read a diffusion+// header and apply whatever split the request carried.++test("an unclassified GGUF pane gets the diffusion-safe placement", () => {+ assert.equal(shouldPinDiffusionPlacement(true, false, true), true);+ assert.deepEqual(+ resolveComparePlacement(+ {},+ shared,+ shouldPinDiffusionPlacement(true, false, true),+ ),+ { gpuMemoryMode: "auto", gpuLayers: GPU_LAYERS_AUTO },+ );+});++test("an unclassified GGUF pane cannot inherit a CPU-masking zero", () => {+ assert.deepEqual(+ resolveComparePlacement(+ {},+ { gpuMemoryMode: "manual", gpuLayers: 0 },+ shouldPinDiffusionPlacement(true, false, true),+ ),+ { gpuMemoryMode: "auto", gpuLayers: GPU_LAYERS_AUTO },+ );+});++test("a CLASSIFIED ordinary GGUF still inherits the snapshot", () => {+ // The point of the tri-state: the common path keeps its existing inheritance.+ assert.equal(shouldPinDiffusionPlacement(true, false, false), false);+ assert.deepEqual(+ resolveComparePlacement(+ {},+ shared,+ shouldPinDiffusionPlacement(true, false, false),+ ),+ { gpuMemoryMode: "manual", gpuLayers: 12 },+ );+});++test("a confirmed diffusion GGUF is pinned however it was classified", () => {+ assert.equal(shouldPinDiffusionPlacement(true, true, false), true);+ assert.equal(shouldPinDiffusionPlacement(true, true, true), true);+});++test("a non-GGUF pane keeps inheriting the snapshot", () => {+ // It sends no placement at all, so an unknown flag must not flip it to Auto.+ assert.equal(shouldPinDiffusionPlacement(false, undefined, false), false);+ assert.equal(shouldPinDiffusionPlacement(false, undefined, true), false);+});++test("an own split still wins for an unclassified GGUF", () => {+ assert.deepEqual(+ resolveComparePlacement(+ { gpuMemoryMode: "manual", gpuLayers: 6 },+ shared,+ shouldPinDiffusionPlacement(true, false, true),+ ),+ { gpuMemoryMode: "manual", gpuLayers: 6 },+ );+});++// -- the config-picker path must hand on "unknown", not a definite false --+// onRun passes the probe answer into the selection, which becomes+// sel.isDiffusion in the compare flow. A definite false there skips the pane's+// re-probe, so the unknown state has to survive this hop.++test("an inconclusive staged probe stays unknown", () => {+ assert.equal(+ resolveStagedDiffusionClassification(undefined, {+ isDiffusion: false,+ diffusionUnknown: true,+ }),+ undefined,+ );+});++test("a confirmed ordinary GGUF stays a definite false", () => {+ assert.equal(+ resolveStagedDiffusionClassification(undefined, {+ isDiffusion: false,+ diffusionUnknown: false,+ }),+ false,+ );+});++test("a confirmed diffusion GGUF stays a definite true", () => {+ assert.equal(+ resolveStagedDiffusionClassification(undefined, {+ isDiffusion: true,+ diffusionUnknown: false,+ }),+ true,+ );+});++test("an already-known diffusion target short-circuits the probe", () => {+ assert.equal(resolveStagedDiffusionClassification(true, null), true);+});++test("a pending probe is unknown, not ordinary", () => {+ assert.equal(resolveStagedDiffusionClassification(undefined, null), undefined);+ assert.equal(+ resolveStagedDiffusionClassification(undefined, undefined),+ undefined,+ );+});++test("the unknown verdict re-probes and reaches diffusion-safe placement", () => {+ // End to end: unknown -> undefined -> the compare preflight re-probes.+ const handedOn = resolveStagedDiffusionClassification(undefined, {+ isDiffusion: false,+ diffusionUnknown: true,+ });+ assert.equal(handedOn, undefined);+ assert.deepEqual(+ resolveComparePlacement({}, shared, shouldPinDiffusionPlacement(true, handedOn, true)),+ { gpuMemoryMode: "auto", gpuLayers: GPU_LAYERS_AUTO },+ );+});++// -- a dropped split must survive a browser refresh --+// A shim without --ngl runs Auto and the backend keeps the ask in+// diffusion_requested_ngl. A refresh starts the store at Auto, so the response+// has to carry it back or the next Apply sends manual/-1 and the post-upgrade+// retry has nothing to apply.++test("an auto diffusion response recovers the standing ask", () => {+ assert.equal(recoverDroppedDiffusionSplit(true, "auto", 20), 20);+});++test("a zero-layer ask is recovered, not treated as absent", () => {+ assert.equal(recoverDroppedDiffusionSplit(true, "auto", 0), 0);+});++test("an applied manual split is authoritative, so nothing is recovered", () => {+ // mode "manual" means the shim honoured the split: gpu_layers is the truth.+ assert.equal(recoverDroppedDiffusionSplit(true, "manual", 20), null);+});++test("no standing ask means nothing to recover", () => {+ assert.equal(recoverDroppedDiffusionSplit(true, "auto", null), null);+ assert.equal(recoverDroppedDiffusionSplit(true, "auto", undefined), null);+});++test("a non-diffusion response never recovers a split", () => {+ assert.equal(recoverDroppedDiffusionSplit(false, "auto", 20), null);+ assert.equal(recoverDroppedDiffusionSplit(undefined, "auto", 20), null);+});++test("an older backend without the field leaves the response unchanged", () => {+ // Absent field -> undefined -> nothing recovered.+ assert.equal(recoverDroppedDiffusionSplit(true, "auto", undefined), null);+});diff --git a/tests/studio/test_diffusion_gpu_layers_contract.py b/tests/studio/test_diffusion_gpu_layers_contract.pynew file mode 100644index 00000000000..38c37894312--- /dev/null+++ b/tests/studio/test_diffusion_gpu_layers_contract.py@@ -0,0 +1,442 @@+# 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 diffusion runner must honour the GPU-layer split (#7574).++Studio used to drop a manual GPU-layers setting on the diffusion path and pin every layer+to GPU, so a GGUF larger than VRAM OOMed in cudaMalloc with no way out.++The pure helpers run directly; the wiring is checked at source level, since importing the+backend pulls in the whole studio stack.+"""++from __future__ import annotations++import ast+import importlib.util+import sys+from pathlib import Path++import pytest+++REPO_ROOT = Path(__file__).resolve().parents[2]+SOURCE_PATH = REPO_ROOT / "studio" / "backend" / "core" / "inference" / "llama_cpp.py"+ROUTE_PATH = REPO_ROOT / "studio" / "backend" / "routes" / "inference.py"+SRC = SOURCE_PATH.read_text(encoding = "utf-8")+TREE = ast.parse(SRC)++[email protected](scope = "module")+def llama_cpp():+ """Import the backend module directly; skip if the studio deps aren't installed."""+ backend = str(REPO_ROOT / "studio" / "backend")+ if backend not in sys.path:+ sys.path.insert(0, backend)+ spec = importlib.util.spec_from_file_location("_llama_cpp_under_test", SOURCE_PATH)+ module = importlib.util.module_from_spec(spec)+ try:+ spec.loader.exec_module(module)+ except Exception as exc: # missing optional studio dep on a bare checkout+ pytest.skip(f"llama_cpp not importable here: {exc}")+ finally:+ # Do not leave studio/backend on sys.path: it shadows generic top-level names+ # (utils, state, models, hub, auth, storage) for every later test.+ if sys.path and sys.path[0] == backend:+ sys.path.pop(0)+ return module+++def _function(name: str) -> ast.FunctionDef:+ for node in ast.walk(TREE):+ if isinstance(node, ast.FunctionDef) and node.name == name:+ return node+ raise AssertionError(f"{name} missing")+++def _body(name: str) -> str:+ return ast.get_source_segment(SRC, _function(name)) or ""+++# ── the split the child actually launches with ──+++ ("mode", "layers", "expected"),+ [+ ("manual", 8, 8),+ ("manual", 0, 0), # CPU-only is a real request, not "unset"+ ("manual", -1, None), # Auto slider defers to the runner+ ("auto", 8, None), # Unsloth mode ignores a stale layer count+ ("auto", -1, None),+ ],+)+def test_effective_ngl(llama_cpp, mode, layers, expected):+ assert llama_cpp._diffusion_manual_ngl(mode, layers) == expected+++def test_zero_layers_is_not_swallowed_as_falsy(llama_cpp):+ """The exact case in the report: GPU layers set to 0 must reach the child."""+ assert llama_cpp._diffusion_manual_ngl("manual", 0) == 0+++# ── shim capability probe ──+++def test_shim_without_ngl_is_detected(llama_cpp, tmp_path):+ shim = tmp_path / "shim.py"+ shim.write_text('ap.add_argument("--maxtok", type=int)\n', encoding = "utf-8")+ assert llama_cpp._shim_supports_ngl(["python", str(shim)]) is False+++def test_shim_with_ngl_is_detected(llama_cpp, tmp_path):+ shim = tmp_path / "shim.py"+ shim.write_text('ap.add_argument("--ngl", type=int)\n', encoding = "utf-8")+ assert llama_cpp._shim_supports_ngl(["python", str(shim)]) is True+++def test_missing_shim_file_does_not_raise(llama_cpp, tmp_path):+ assert llama_cpp._shim_supports_ngl(["python", str(tmp_path / "gone.py")]) is False+++# ── wiring ──+++def test_diffusion_server_accepts_the_layer_split():+ fn = _function("_start_diffusion_server")+ names = {a.arg for a in fn.args.kwonlyargs} | {a.arg for a in fn.args.args}+ assert {"gpu_memory_mode", "gpu_layers"} <= names+++def test_diffusion_server_forwards_ngl_and_gates_it_on_shim_support():+ body = _body("_start_diffusion_server")+ assert '"--ngl"' in body+ assert "_shim_supports_ngl" in body+++def test_zero_layers_masks_the_child_devices(llama_cpp):+ """gpu_layers=0 must CUDA-mask the child, else _gpu_offload_active=False lies to the+ training VRAM coordinator and a GPU-resident runner survives into a training run.+ Behavioural, not a source-text match: what matters is the token the child gets."""+ arg = llama_cpp.LlamaCppBackend._diffusion_gpu_arg+ assert arg([3, 1], force_cpu = True) == ""+ assert arg(None, force_cpu = True) == ""+++def test_explicit_pick_still_wins_when_layers_are_not_zero(llama_cpp):+ """force_cpu is the only thing above the picker. A host whose GPU torch cannot see+ (Metal, Vulkan, Windows-HIP, Intel XPU) still has to honour an explicit pick."""+ arg = llama_cpp.LlamaCppBackend._diffusion_gpu_arg+ assert arg([3, 1], cpu_only = True) == "1"+ assert arg([3, 1]) == "1"+++def test_no_gpu_and_no_pick_masks_the_child(llama_cpp):+ assert llama_cpp.LlamaCppBackend._diffusion_gpu_arg(None, cpu_only = True) == ""+++def test_diffusion_load_passes_the_users_split_through():+ body = _body("load_model")+ start = body.index("_start_diffusion_server(")+ call = body[start : body.index(")", body.index("gpu_ids = gpu_ids", start))]+ assert "gpu_memory_mode = gpu_memory_mode" in call+ assert "gpu_layers = gpu_layers" in call+++def test_diffusion_no_longer_hardcodes_auto_over_the_users_choice():+ body = _body("_start_diffusion_server")+ assert 'self._gpu_memory_mode = "auto"' not in body+ assert "self._gpu_layers = -1" not in body+++# ── dedup guards must see a split change ──+++def _loaded_diffusion(llama_cpp, *, recorded_layers, requested_ngl):+ """A backend that looks like a healthy diffusion runner, for the dedup guards."""+ b = llama_cpp.LlamaCppBackend()+ b._process, b._healthy, b._is_diffusion = object(), True, True+ b._model_identifier = "unsloth/DiffusionGemma-GGUF"+ b._hf_variant = b._gguf_path = b._cache_type_kv = None+ b._requested_n_ctx = 4096+ b._tensor_parallel = b._layer_preserves_tensor_intent = False+ b._gpu_layers = recorded_layers+ b._gpu_memory_mode = "auto" if recorded_layers < 0 else "manual"+ b._diffusion_requested_ngl = requested_ngl+ b._gpu_ids = b._requested_gpu_ids = [0]+ b._requested_spec_mode = "auto"+ b._spec_fallback_reason = b._speculative_type = b._spec_draft_n_max = None+ b._chat_template_override = b._mtp_draft_path = b._extra_args = None+ # Dropped-split rows model "the shim stayed old"; the upgrade flip is separate.+ b.diffusion_split_supported = lambda: False+ return b+++def _in_target_state(b, *, mode, layers):+ return b._already_in_target_state(+ model_identifier = "unsloth/DiffusionGemma-GGUF",+ hf_variant = None,+ n_ctx = 4096,+ cache_type_kv = None,+ speculative_type = None,+ chat_template_override = None,+ extra_args = None,+ is_vision = False,+ gpu_memory_mode = mode,+ gpu_layers = layers,+ gpu_ids = [0],+ )+++ ("recorded", "requested_ngl", "mode", "layers", "expected"),+ [+ (-1, None, "auto", -1, True), # auto -> auto+ (-1, None, "manual", -1, True), # inert manual preference must not loop+ (-1, None, "manual", 8, False), # a real split must reload+ (8, 8, "manual", 8, True), # same split dedupes+ (8, 8, "manual", 4, False), # a split change reloads+ (8, 8, "auto", -1, False), # manual -> auto reloads+ (0, 0, "manual", 0, True), # CPU-only split dedupes with itself+ # No --ngl: -1 runs but 20 was the ask; comparing on the ask stops a reload loop.+ (-1, 20, "manual", 20, True),+ (-1, 20, "manual", 8, False),+ ],+)+def test_backend_dedup_compares_the_requested_split(+ llama_cpp, recorded, requested_ngl, mode, layers, expected+):+ b = _loaded_diffusion(llama_cpp, recorded_layers = recorded, requested_ngl = requested_ngl)+ assert _in_target_state(b, mode = mode, layers = layers) is expected+++def test_route_dedup_compares_the_requested_split():+ """The route mirrors the backend guard, so it must read the same field."""+ route_src = ROUTE_PATH.read_text(encoding = "utf-8")+ route_tree = ast.parse(route_src)+ for node in ast.walk(route_tree):+ if isinstance(node, ast.FunctionDef) and node.name == "_request_matches_loaded_settings":+ body = ast.get_source_segment(route_src, node) or ""+ assert "_diffusion_manual_ngl(request.gpu_memory_mode, request.gpu_layers)" in body+ assert "llama_backend.diffusion_requested_ngl" in body+ return+ raise AssertionError("_request_matches_loaded_settings missing")+++def test_requested_split_survives_a_shim_without_the_flag(llama_cpp):+ """gpu_layers reports what is running; diffusion_requested_ngl reports the ask."""+ b = _loaded_diffusion(llama_cpp, recorded_layers = -1, requested_ngl = 20)+ assert b.gpu_layers == -1+ assert b.diffusion_requested_ngl == 20+++# ── the capability probe must read code, not prose ──+++ ("source", "expected"),+ [+ ('ap.add_argument("--ngl", type=int)', True),+ ("ap.add_argument('--ngl', type=int)", True), # quoting must not matter+ ('# someday: support "--ngl"', False), # a comment is not support+ ('"""usage: --ngl N"""', False), # nor is a docstring+ ('ap.add_argument("--maxtok", type=int)', False),+ ],+)+def test_probe_reads_declarations_not_substrings(llama_cpp, tmp_path, source, expected):+ shim = tmp_path / "shim.py"+ shim.write_text(source + "\n", encoding = "utf-8")+ assert llama_cpp._shim_supports_ngl(["python", str(shim)]) is expected+++def test_probe_accepts_an_uppercase_extension(llama_cpp, tmp_path):+ """A Windows UNSLOTH_DG_SHIM override may be SHIM.PY; it must still be the file read."""+ shim = tmp_path / "SHIM.PY"+ shim.write_text('ap.add_argument("--ngl", type=int)\n', encoding = "utf-8")+ assert llama_cpp._shim_supports_ngl(["python", str(shim)]) is True+++def test_probe_falls_back_to_a_substring_scan_on_unparseable_source(llama_cpp, tmp_path):+ shim = tmp_path / "shim.py"+ shim.write_text('ap.add_argument("--ngl"\n', encoding = "utf-8") # syntax error+ assert llama_cpp._shim_supports_ngl(["python", str(shim)]) is True+++# ── the training guard must not refuse a load that holds no VRAM ──+++def test_training_guard_sees_the_layer_count():+ """A manual/0 diffusion load places no layers, so it cannot compete with training."""+ route_src = ROUTE_PATH.read_text(encoding = "utf-8")+ route_tree = ast.parse(route_src)+ fn = next(+ n+ for n in ast.walk(route_tree)+ if isinstance(n, ast.FunctionDef) and n.name == "_guard_chat_load_against_training"+ )+ names = {a.arg for a in fn.args.args} | {a.arg for a in fn.args.kwonlyargs}+ assert "gpu_layers" in names+ body = ast.get_source_segment(route_src, fn) or ""+ assert "diffusion_ngl == 0" in body++ calls = [+ n+ for n in ast.walk(route_tree)+ if isinstance(n, ast.Call)+ and any(+ isinstance(a, ast.Name) and a.id == "_guard_chat_load_against_training" for a in n.args+ )+ ]+ assert len(calls) == 2, "expected the /load and /validate call sites"+ for call in calls:+ assert any(kw.arg == "gpu_layers" for kw in call.keywords)+++# ── the probe must inspect the file that will be spawned, whatever its name ──++[email protected]("name", ["shim", "shim.pyw", "SHIM.PY"])+def test_probe_keys_on_argv_shape_not_suffix(llama_cpp, tmp_path, name):+ """Any UNSLOTH_DG_SHIM file launches as-is, so the probe must answer for that exact+ file; an extensionless or .pyw override used to fall through to the package."""+ shim = tmp_path / name+ shim.write_text('ap.add_argument("--ngl", type=int)\n', encoding = "utf-8")+ assert llama_cpp._shim_supports_ngl(["python", str(shim)]) is True+++def test_probe_does_not_mistake_the_module_form_for_a_file(llama_cpp, monkeypatch):+ """[python, -m, unsloth_zoo.diffusion_studio.shim] carries a module name, not a+ path; the probe must resolve the installed package, not stat the module string."""+ import importlib.util as ilu++ monkeypatch.setattr(ilu, "find_spec", lambda name: None)+ cmd = ["python", "-m", "unsloth_zoo.diffusion_studio.shim"]+ assert llama_cpp._shim_supports_ngl(cmd) is False # unresolvable -> conservative+++# ── the guard must mirror what the launcher will actually do ──+++def test_split_supported_mirrors_the_launch_gate(llama_cpp, tmp_path, monkeypatch):+ b = llama_cpp.LlamaCppBackend()+ shim = tmp_path / "shim.py"++ shim.write_text('ap.add_argument("--ngl", type=int)\n', encoding = "utf-8")+ monkeypatch.setattr(+ b, "_find_diffusion_assets", lambda: (["python", str(shim)], "/bin/dg", None)+ )+ assert b.diffusion_split_supported() is True++ shim.write_text('ap.add_argument("--maxtok", type=int)\n', encoding = "utf-8")+ assert b.diffusion_split_supported() is False++ monkeypatch.setattr(b, "_find_diffusion_assets", lambda: None)+ assert b.diffusion_split_supported() is False # no runner -> no split+++def test_training_guard_mirrors_shim_support():+ """The zero-layer bypass and the split-scaled estimate are only valid when the+ launcher will actually emit --ngl; a dropped split runs GPU-resident."""+ route_src = ROUTE_PATH.read_text(encoding = "utf-8")+ route_tree = ast.parse(route_src)+ fn = next(+ n+ for n in ast.walk(route_tree)+ if isinstance(n, ast.FunctionDef) and n.name == "_guard_chat_load_against_training"+ )+ body = ast.get_source_segment(route_src, fn) or ""+ assert "diffusion_split_supported" in body+ assert body.index("diffusion_split_supported") < body.index("diffusion_ngl == 0")+ assert "_scale_diffusion_required_gb" in body+++# ── a positive split competes with its GPU share, not the whole file ──+++ ("required", "ngl", "n_layers", "expected"),+ [+ (15.0, 10, 30, 5.0), # a third of the layers -> a third of the footprint+ (15.0, 30, 30, 15.0), # all layers -> unchanged+ (15.0, 99, 30, 15.0), # over-ask clamps to all layers+ (15.0, 10, None, 15.0), # unknown layer count stays conservative+ (15.0, 10, 0, 15.0), # degenerate header value stays conservative+ ],+)+def test_positive_split_scales_the_guard_estimate(llama_cpp, required, ngl, n_layers, expected):+ assert llama_cpp._scale_diffusion_required_gb(required, ngl, n_layers) == pytest.approx(+ expected+ )+++# ── a custom-named override answers for itself, not a sibling shim.py ──+++def test_probe_ignores_a_sibling_shim_next_to_a_custom_override(llama_cpp, tmp_path):+ """An override runs as-is; a capable sibling shim.py must not vouch for it, or the+ launch appends --ngl to a parser that exits on it."""+ override = tmp_path / "my_shim"+ override.write_text('ap.add_argument("--maxtok", type=int)\n', encoding = "utf-8")+ sibling = tmp_path / "shim.py"+ sibling.write_text('ap.add_argument("--ngl", type=int)\n', encoding = "utf-8")+ assert llama_cpp._shim_supports_ngl(["python", str(override)]) is False+++# ── a zoo upgrade mid-session must un-stick a dropped split ──+++def test_zoo_upgrade_reloads_a_dropped_split(llama_cpp):+ """manual/20 against an old shim launched with the default and deduped on the+ ask. Once the shim gains --ngl, the identical ask must reload to apply it."""+ b = _loaded_diffusion(llama_cpp, recorded_layers = -1, requested_ngl = 20)+ assert _in_target_state(b, mode = "manual", layers = 20) is True # shim still old+ b.diffusion_split_supported = lambda: True # zoo upgraded in this session+ assert _in_target_state(b, mode = "manual", layers = 20) is False # now applies+ b2 = _loaded_diffusion(llama_cpp, recorded_layers = 20, requested_ngl = 20)+ b2.diffusion_split_supported = lambda: True+ assert _in_target_state(b2, mode = "manual", layers = 20) is True # applied: rest+++# ── the dropped split must reach the client ──+++def test_response_models_expose_the_requested_split():+ """A refresh has no in-memory split left, so the wire has to carry the ask."""+ models_src = (REPO_ROOT / "studio" / "backend" / "models" / "inference.py").read_text(+ encoding = "utf-8"+ )+ tree = ast.parse(models_src)+ for name in ("LoadResponse", "InferenceStatusResponse"):+ cls = next(n for n in ast.walk(tree) if isinstance(n, ast.ClassDef) and n.name == name)+ fields = {+ t.target.id+ for t in cls.body+ if isinstance(t, ast.AnnAssign) and isinstance(t.target, ast.Name)+ }+ assert "diffusion_requested_ngl" in fields, f"{name} must report the ask"+++def test_every_diffusion_response_also_reports_the_requested_split():+ """Wiring, not prose: a new response site that forgets the ask reddens here."""+ route_src = ROUTE_PATH.read_text(encoding = "utf-8")+ tree = ast.parse(route_src)+ sites = 0+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ kwargs = {kw.arg for kw in node.keywords}+ # Only responses describing a LOADED model; /validate has no runner yet, so no+ # applied-vs-asked split.+ if "is_diffusion" not in kwargs or "is_gguf" not in kwargs:+ continue+ if not any(+ isinstance(kw.value, ast.Attribute) and kw.value.attr == "is_diffusion"+ for kw in node.keywords+ if kw.arg == "is_diffusion"+ ):+ continue+ sites += 1+ assert "diffusion_requested_ngl" in kwargs, (+ f"response at line {node.lineno} reports is_diffusion from the backend "+ "but not diffusion_requested_ngl, so a dropped split cannot survive a refresh"+ )+ assert sites == 3, f"expected the 2 load sites and the status site, found {sites}"diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 2c6adb90ad0..eba0a3de078 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -269,8 +269,16 @@ def test_gpu_picker_round_trips_requested_pool_not_fitted_subset():def test_compare_load_uses_each_models_gpu_config():src = _read("features/chat/shared-composer.tsx")- assert "ownConfig.gpuMemoryMode ?? compareLoadKnobs.gpuMemoryMode" in src- assert "ownConfig.gpuLayers ?? compareLoadKnobs.gpuLayers" in src+ # The mode/layer rule now lives in lib/gpu-placement.ts (behaviour covered by+ # studio/frontend/tests/gpu-placement.test.ts): assert the delegation here.+ assert "} = resolveComparePlacement(" in src+ assert "shouldPinDiffusionPlacement(" in src+ placement = " ".join(_read("features/chat/lib/gpu-placement.ts").split())+ assert 'own.gpuMemoryMode ?? (treatAsDiffusion ? "auto" : shared.gpuMemoryMode)' in placement+ assert "own.gpuLayers ?? (treatAsDiffusion ? GPU_LAYERS_AUTO : shared.gpuLayers)" in placement+ # An unclassified GGUF is pinned like a confirmed one: /load may still find a+ # diffusion header after the download.+ assert "return isDiffusion === true || diffusionUnknown" in placementassert "ownConfig.nCpuMoe ?? compareLoadKnobs.nCpuMoe" in srcassert "if (ownConfig.selectedGpuIds != null)" in srcassert "ownConfig.selectedGpuIndexKind," in src