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: split DiffusionGemma across GPUs when one GPU cannot hold it (#13291)
Daniel Han1a2258b5e29a
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 32916deafc7..801c51de6e9 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -5019,6 +5019,33 @@ def _shim_supports_ngl(shim_cmd: List[str]) -> bool:return False+def _visual_server_splits_gpus(visual_bin: Optional[str]) -> bool:+ """Whether the diffusion visual server survives a model split over several GPUs.++ Builds before the fix abort on the first request once split: with the prompt-KV store+ off (it is single-device) every [prompt|canvas] row asked for logits past the server's+ canvas-sized output cap. Fixed builds answer ``--capabilities`` with ``multi_gpu_split``;+ read that literal from the binary rather than spawning it, since an old build takes+ 10-30 s to fail on the unknown argument.+ """+ if not visual_bin:+ return False+ try:+ st = os.stat(visual_bin)+ except OSError:+ return False+ return _binary_has_marker(visual_bin, st.st_mtime_ns, st.st_size, b"multi_gpu_split")++[email protected]_cache(maxsize = 16)+def _binary_has_marker(path: str, _mtime_ns: int, _size: int, marker: bytes) -> bool:+ try:+ with open(path, "rb") as f:+ return marker in f.read()+ except OSError:+ return False++def _swa_full_from_args_or_env(extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None) -> bool:@@ -9150,14 +9177,15 @@ class LlamaCppBackend:A regular GGUF load may narrow the requested placement pool to thesmallest fitting subset. Accept both the original request and theeffective status-echoed subset so either can round-trip without a- needless reload. Diffusion drives one device and keeps its existing- lowest-device normalization.+ needless reload. Diffusion records the lowest device of a pick that fits it,+ else the whole pick it split over, so either form matches."""if self._is_diffusion:- requested = [sorted(int(x) for x in gpu_ids)[0]] if gpu_ids else None+ full = sorted(int(x) for x in gpu_ids) if gpu_ids else None# Raw pick accepted too: a forced-CPU runner records no effective pin, so# without it re-sending the same selection would reload every time.- return requested in ((self._gpu_ids or None), (self._requested_gpu_ids or None))+ held = ((self._gpu_ids or None), (self._requested_gpu_ids or None))+ return (full[:1] if full else None) in held or full in heldrequested = [int(x) for x in gpu_ids] if gpu_ids else Noneraw = self._requested_gpu_ids or None@@ -9181,7 +9209,11 @@ class LlamaCppBackend:later reload do not restore GPUs the user just removed."""if self._is_diffusion:- self._requested_gpu_ids = [sorted(int(x) for x in gpu_ids)[0]] if gpu_ids else None+ full = sorted(int(x) for x in gpu_ids) if gpu_ids else None+ # Keep the whole pick when the fit moved off its lowest GPU (a split, or one+ # higher card), or a later pick of that lowest GPU would match and not reload.+ moved = bool(self._gpu_ids) and bool(full) and self._gpu_ids != full[:1]+ self._requested_gpu_ids = full if moved else (full[:1] if full else None)else:self._requested_gpu_ids = [int(x) for x in gpu_ids] if gpu_ids else Noneif self._last_load_intent is not None:@@ -19511,6 +19543,59 @@ class LlamaCppBackend:return firstreturn "0"+ @classmethod+ def _diffusion_fit_gpus(+ cls,+ model_size_bytes: int,+ gpu_ids: Optional[List[int]],+ gpu: str,+ visual_bin: Optional[str],+ ) -> Optional[List[int]]:+ """Physical GPUs to layer-split a diffusion GGUF over, or None to keep ``gpu`` alone.++ The visual server loads with llama.cpp's default layer split over every device in+ its mask, so widening the mask is the whole change. Only a GGUF that does not fit+ ``gpu`` moves: alone it overflows the card (a hang on Windows, where it spills into+ shared memory, #6347). The pool is the explicit pick, else every visible GPU; when+ no subset holds it, None leaves the single-device GPU / CPU layer fit in charge.+ Each device is charged the runner's own context on top of its weights, the same fit+ test as _diffusion_auto_ngl, so the two never disagree on whether ``gpu`` suffices.+ Shared with the training guard, so both budget the devices the runner will use. A+ runner that cannot split keeps today's single device."""+ if not gpu.isdigit() or not model_size_bytes or not _visual_server_splits_gpus(visual_bin):+ return None+ # Unpinned: only ids the child resolves the same way under PCI order (no inherited+ # mask to reinterpret, ids from nvidia-smi / NVML), as for llama-server auto fits.+ if not gpu_ids and ("DG_GPU" in os.environ or "CUDA_VISIBLE_DEVICES" in os.environ):+ return None+ try:+ binary = cls._find_llama_server_binary()+ # Vulkan ordinals are not the CUDA ids the runner's mask takes.+ if binary and cls._is_vulkan_backend(binary):+ return None+ memory = cls._get_gpu_memory(binary)+ except Exception as e:+ logger.debug(f"DiffusionGemma GPU fit skipped: {e}")+ return None+ if not gpu_ids and cls._GPU_IDS_ARE_PCI_INDICES is not True:+ return None+ pool = set(int(i) for i in gpu_ids) if gpu_ids else None+ gpus = [(idx, free) for idx, free, _ in memory if pool is None or idx in pool]+ total_by_idx = {idx: total for idx, _, total in memory}+ first = [(idx, free) for idx, free in gpus if idx == int(gpu)]+ if len(gpus) < 2 or not first:+ return None+ overhead = int(_DIFFUSION_RUNNER_OVERHEAD_MIB * 1024 * 1024)+ need = model_size_bytes + overhead+ if cls._select_gpus(need, first, total_by_idx = total_by_idx)[0]:+ return None+ picked, _ = cls._select_gpus(+ need, gpus, total_by_idx = total_by_idx, per_device_overhead_bytes = overhead+ )+ if not picked or sorted(picked) == [int(gpu)]:+ return None+ return sorted(picked)+def _diffusion_fit_ngl(self, model_path: str, gpu: str, maxtok: int, *, pinned: bool) -> Optional[int]:@@ -19617,20 +19702,37 @@ class LlamaCppBackend:# 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.+ # Honor the GPU picker first: start from the lowest selected GPU. With no pick,+ # fall back to the CPU-only mask, else DG_GPU / 0. A manual split already says+ # where the layers go; otherwise a GGUF too big for that one device is+ # layer-split over the pool (#6347).gpu = self._diffusion_gpu_arg(gpu_ids, cpu_only = cpu_only, force_cpu = holds_no_gpu)- # Auto: a GGUF too large for that device gets the split that fits it (#6456).+ # Auto: a GGUF too large for that device is layer-split over the GPU pool when the+ # runner supports it (#6347), else gets the GPU / CPU split that fits it (#6456).fit_ngl = None+ fit_gpus = Noneif manual_ngl is None:fit_ngl = self._diffusion_fit_ngl(model_path, gpu, maxtok, pinned = bool(gpu_ids))+ try:+ fit_gpus = self._diffusion_fit_gpus(+ self._get_gguf_size_bytes(model_path),+ gpu_ids,+ gpu,+ visual_bin,+ )+ except OSError as e:+ logger.debug(f"DiffusionGemma GPU fit skipped: {e}")# The probe runs under the load lock and can be slow: honour a Stop that came in.if cancelled is not None and cancelled():logger.info("Load cancelled before diffusion server start")self._health_wait_cancelled = Truereturn False+ if fit_gpus:+ fit_ngl = None+ gpu = ",".join(str(i) for i in fit_gpus)+ logger.info(+ f"DiffusionGemma does not fit one GPU; splitting layers over GPUs {gpu}"+ )if fit_ngl is not None and not _shim_supports_ngl(shim_cmd):logger.warning("DiffusionGemma does not fit GPU %s and the installed unsloth_zoo shim "@@ -19696,7 +19798,7 @@ class LlamaCppBackend:env.setdefault("UNSLOTH_ALLOW_CPU", "1")env["DG_VISUAL_BIN"] = visual_binenv["DG_GPU"] = gpu- if gpu_ids:+ if gpu_ids or fit_gpus:# The visual server remasks via CUDA_VISIBLE_DEVICES=<gpu>; pin PCI# order (as the llama-server path does) so the picked physical id maps# to the GPU the picker showed, not CUDA's default fastest-first order.@@ -19843,18 +19945,19 @@ class LlamaCppBackend:# leftover arch-gate flag would answer holds_no_vram True and let the arbiter# run a competing workload into its memory (#7624).self._arch_gate_forced_cpu = False- # The single-device runner records only the lowest selected GPU (chosen- # above), not the whole pick, and clears any explicit pin from a prior- # chat load; a multi-GPU list would misreport placement and mis-dedup.+ # Record the devices the runner got: the lowest selected GPU, or the split above.+ # Unused members of a pick that fits one device are dropped, or /status misreports+ # placement and the dedup reloads. Clears any explicit pin from a prior chat load.# A zero-layer split on virtualised Metal masks the child's devices outright, so# it pins nothing: record no effective pin, or /status names a device the runner# never used and clearing that pick reloads the same CPU runner._pv_diffusion_cpu = manual_ngl == 0 and _metal_device_is_paravirtual()- self._gpu_ids = [sorted(gpu_ids)[0]] if gpu_ids and not _pv_diffusion_cpu else None+ _pinned = (fit_gpus or [sorted(gpu_ids)[0]]) if gpu_ids else None+ self._gpu_ids = _pinned if not _pv_diffusion_cpu else None# The frontend prefers requested_gpu_ids when hydrating the picker.- # Diffusion uses only one device, so echo the collapsed effective pin,- # not unused members of the original request.- self._requested_gpu_ids = [sorted(gpu_ids)[0]] if gpu_ids else None+ self._requested_gpu_ids = (+ sorted(int(i) for i in gpu_ids) if gpu_ids and fit_gpus else _pinned+ )if hf_variant:self._hf_variant = hf_variantelif gguf_path:diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex a831910a46b..b6657fc3025 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -16635,6 +16635,26 @@ def _guard_chat_load_against_training(required_override_gb, diffusion_ngl, _gguf_layer_count(config))+ # Without a manual split the runner layer-splits a GGUF its one device cannot hold+ # (#6347): budget the devices that same decision picks, from the same weight bytes the+ # launcher reads. A GGUF not on disk yet keeps the stricter single-device budget.+ guard_gpu_ids = requested_gpu_ids+ _gguf_file = getattr(config, "gguf_file", None) if is_gguf else None+ if diffusion_gpu and diffusion_ngl is None and _gguf_file and os.path.isfile(_gguf_file):+ try:+ _assets = get_llama_cpp_backend()._find_diffusion_assets()+ fit_gpus = LlamaCppBackend._diffusion_fit_gpus(+ LlamaCppBackend._get_gguf_size_bytes(_gguf_file),+ requested_gpu_ids,+ diffusion_gpu,+ _assets[1] if _assets else None,+ )+ except Exception as e:+ logger.debug("Diffusion GPU fit skipped in the training guard: %s", e)+ fit_gpus = None+ if fit_gpus:+ diffusion_gpu, guard_gpu_ids = None, fit_gpus+vulkan_free_vram_gb = Noneif is_gguf:if is_vulkan_backend and (gpu_ids_are_vulkan_ordinals or diffusion_kind is False):@@ -16672,7 +16692,7 @@ def _guard_chat_load_against_training(hf_token = request.hf_token,load_in_4bit = load_in_4bit,max_seq_length = request.max_seq_length,- requested_gpu_ids = requested_gpu_ids,+ requested_gpu_ids = guard_gpu_ids,is_gguf = is_gguf,gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,vulkan_free_vram_gb = vulkan_free_vram_gb,diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.pyindex d5cdd850cc2..b84da076ca7 100644--- a/studio/backend/tests/test_chat_load_during_training.py+++ b/studio/backend/tests/test_chat_load_during_training.py@@ -8,6 +8,7 @@ perform (HF auto reuses the loader's selector, HF explicit applies a per-GPUfloor, GGUF sizes from on-disk weights, LoRA 4-bit->16-bit flips resolved first)and leaves non-training/external loads untouched."""+import tempfileimport asyncioimport importlib.utilimport sys@@ -629,11 +630,32 @@ class TestChatLoadGuardRoute(unittest.TestCase):classify.assert_called_once_with(config)self.assertEqual(captured, [])- def test_manual_diffusion_keeps_single_device_training_guard(self):- captured = []- config = SimpleNamespace(is_gguf = True)+ def _guard_diffusion_pick(+ self,+ captured,+ fit = None,+ gguf_file = None,+ **kwargs,+ ):+ config = SimpleNamespace(is_gguf = True, gguf_file = gguf_file)+ backend = SimpleNamespace(+ diffusion_split_supported = lambda: True,+ _find_diffusion_assets = lambda: (["python"], "/bin/vs", None),+ )+ fits = []with (+ patch.object(+ self.route.LlamaCppBackend,+ "_diffusion_fit_gpus",+ side_effect = lambda *a: fits.append(a) or fit,+ ),+ patch.object(+ self.route.LlamaCppBackend,+ "_get_gguf_size_bytes",+ side_effect = lambda _p: 9 * 1024**3,+ ),patch.object(self.route, "_classify_diffusion_gguf", return_value = True),+ 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,@@ -648,11 +670,43 @@ class TestChatLoadGuardRoute(unittest.TestCase):decision = (True, {"mode": "single_device"}),gpu_memory_mode = "manual",requested_gpu_ids = [3, 1],+ **kwargs,)+ return fits++ def test_manual_diffusion_split_keeps_single_device_training_guard(self):+ # An explicit layer count runs on the lowest picked GPU only.+ captured = []+ self._guard_diffusion_pick(captured, gpu_layers = 20)self.assertEqual(len(captured), 1)self.assertEqual(captured[0]["single_device_gpu"], "1")self.assertEqual(captured[0]["requested_gpu_ids"], [3, 1])+ def test_auto_layers_diffusion_split_is_budgeted_on_its_gpus(self):+ # Without a layer count the runner splits what GPU 1 cannot hold (#6347): the+ # guard budgets the GPUs that same decision picks, from the launcher's weight bytes+ # (the GGUF file), not the context-inclusive estimate.+ captured = []+ with tempfile.NamedTemporaryFile(suffix = ".gguf") as f:+ fits = self._guard_diffusion_pick(captured, fit = [1, 3], gguf_file = f.name)+ self.assertEqual(fits, [(9 * 1024**3, [3, 1], "1", "/bin/vs")])+ self.assertIsNone(captured[0]["single_device_gpu"])+ self.assertEqual(captured[0]["requested_gpu_ids"], [1, 3])++ def test_auto_layers_diffusion_pick_that_fits_one_gpu_keeps_its_budget(self):+ captured = []+ with tempfile.NamedTemporaryFile(suffix = ".gguf") as f:+ self._guard_diffusion_pick(captured, fit = None, gguf_file = f.name)+ self.assertEqual(captured[0]["single_device_gpu"], "1")+ self.assertEqual(captured[0]["requested_gpu_ids"], [3, 1])++ def test_diffusion_gguf_not_on_disk_keeps_the_single_device_budget(self):+ # Nothing to read the launcher's weight size from: stay on the stricter budget.+ captured = []+ fits = self._guard_diffusion_pick(captured, fit = [1, 3])+ self.assertEqual(fits, [])+ self.assertEqual(captured[0]["single_device_gpu"], "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)diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.pyindex 33a5be9ce7f..6177a7908c9 100644--- a/studio/backend/tests/test_gpu_memory_mode.py+++ b/studio/backend/tests/test_gpu_memory_mode.py@@ -950,9 +950,10 @@ def test_start_diffusion_server_resets_tensor_parallel():# diffusion re-Apply reloads against stale tensor-parallel state.src = inspect.getsource(llama_cpp_module.LlamaCppBackend._start_diffusion_server)assert "self._tensor_parallel = False" in src- # Still the collapsed single-device pick, but taken from the request rather than the- # effective pin, which a forced-CPU launch on virtualised Metal clears.- assert "self._requested_gpu_ids = [sorted(gpu_ids)[0]] if gpu_ids else None" in src+ # Taken from the request rather than the effective pin, which a forced-CPU launch on+ # virtualised Metal clears.+ assert "_pinned = (fit_gpus or [sorted(gpu_ids)[0]]) if gpu_ids else None" in src+ assert "self._gpu_ids = _pinned if not _pv_diffusion_cpu else None" in src# ── Manual tensor split: child enumeration pinned to the picker's order ──────@@ -1268,6 +1269,275 @@ def test_diffusion_gpu_arg_honors_override_and_cpu_mask(monkeypatch):assert LlamaCppBackend._diffusion_gpu_arg(None, cpu_only = True) == ""+# ── Diffusion layer split when one GPU cannot hold the GGUF (#6347) ──────────++_GIB = 1024**3+++def _diffusion_fit_host(+ monkeypatch,+ gguf_gib,+ gpus,+ *,+ vulkan = False,+):+ """``gpus``: (index, free MiB, total MiB) as the placement probe reports them."""+ monkeypatch.delenv("DG_GPU", raising = False)+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "/bin/ls")+ )+ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _b = None: vulkan))+ monkeypatch.setattr(LlamaCppBackend, "_sysmem_fallback_risk", staticmethod(lambda: False))+ monkeypatch.setattr(+ LlamaCppBackend, "_get_gpu_memory", staticmethod(lambda _b = None, **_k: list(gpus))+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_get_gguf_size_bytes", staticmethod(lambda _p: int(gguf_gib * _GIB))+ )+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.setattr(LlamaCppBackend, "_GPU_IDS_ARE_PCI_INDICES", True)+ monkeypatch.setattr(llama_cpp_module, "_visual_server_splits_gpus", lambda _bin: True)+++_TWO_3090 = [(0, 23_500, 24_576), (1, 23_500, 24_576)]+++ ("gguf_gib", "gpu_ids", "gpu", "expected"),+ [+ (16.8, None, "0", None), # Q4_K_M fits one 24 GB card: unchanged single device+ (16.8, [0, 1], "0", None), # explicit pair, still fits the lowest: unchanged+ (26.9, None, "0", [0, 1]), # Q8_0: auto spreads over the visible pair+ (26.9, [0, 1], "0", [0, 1]), # Q8_0: explicit pair is honoured+ (26.9, [0], "0", None), # a single explicit GPU is never widened+ (50.5, None, "0", None), # BF16 fits no subset: left to the GPU / CPU layer fit+ ],+)+def test_diffusion_fit_gpus_splits_only_what_one_gpu_cannot_hold(+ monkeypatch, gguf_gib, gpu_ids, gpu, expected+):+ _diffusion_fit_host(monkeypatch, gguf_gib, _TWO_3090)+ assert (+ LlamaCppBackend._diffusion_fit_gpus(int(gguf_gib * _GIB), gpu_ids, gpu, "/bin/vs")+ == expected+ )+++def test_diffusion_fit_gpus_keeps_explicit_pool_and_operator_overrides(monkeypatch):+ _diffusion_fit_host(monkeypatch, 26.9, _TWO_3090 + [(2, 23_500, 24_576)])+ _size = int(26.9 * _GIB)+ # The pick bounds the pool: GPU 2 is never added to a [1, 2] pick's split.+ assert LlamaCppBackend._diffusion_fit_gpus(_size, [1, 2], "1", "/bin/vs") == [1, 2]+ # A device token that is not a physical index (UUID / MIG / CPU mask) is left alone.+ assert LlamaCppBackend._diffusion_fit_gpus(_size, None, "GPU-abc", "/bin/vs") is None+ assert LlamaCppBackend._diffusion_fit_gpus(_size, None, "", "/bin/vs") is None+ monkeypatch.setenv("DG_GPU", "0")+ assert LlamaCppBackend._diffusion_fit_gpus(_size, None, "0", "/bin/vs") is None+++def test_diffusion_auto_fit_only_on_pci_ids_without_an_inherited_mask(monkeypatch):+ # Under PCI_BUS_ID the child would re-read torch ordinals or masked ids as other cards.+ _diffusion_fit_host(monkeypatch, 26.9, _TWO_3090)+ _size = int(26.9 * _GIB)+ assert LlamaCppBackend._diffusion_fit_gpus(_size, None, "0", "/bin/vs") == [0, 1]+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1")+ assert LlamaCppBackend._diffusion_fit_gpus(_size, None, "0", "/bin/vs") is None+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES")+ monkeypatch.setattr(LlamaCppBackend, "_GPU_IDS_ARE_PCI_INDICES", False)+ assert LlamaCppBackend._diffusion_fit_gpus(_size, None, "0", "/bin/vs") is None+ # An explicit pick comes from the PCI-ordered picker and is pinned as before.+ assert LlamaCppBackend._diffusion_fit_gpus(_size, [0, 1], "0", "/bin/vs") == [0, 1]+++def test_diffusion_moved_fit_keeps_the_pool_on_a_dedup_match():+ # The fit moved a [0, 1] pick onto GPU 1 alone: re-sending [0, 1] must keep that pick+ # recorded, or a later pick of GPU 0 matches and the runner stays on GPU 1.+ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ backend._is_diffusion = True+ backend._last_load_intent = None+ backend._gpu_ids, backend._requested_gpu_ids = [1], [0, 1]+ assert backend.matches_gpu_ids([0, 1])+ backend._record_matching_gpu_request([0, 1])+ assert backend.requested_gpu_ids == [0, 1]+ assert not backend.matches_gpu_ids([0])+ # The usual single-device fit still collapses to its lowest GPU.+ backend._gpu_ids, backend._requested_gpu_ids = [0], [0]+ backend._record_matching_gpu_request([1, 0])+ assert backend.requested_gpu_ids == [0]+++def test_diffusion_fit_gpus_agrees_with_the_layer_fit_on_one_card(monkeypatch):+ # Both decide "does gpu 0 hold it" the same way, also in the runner-overhead margin, so+ # a GGUF never gets CPU layers while a second card is free, nor a split it did not need.+ _diffusion_fit_host(monkeypatch, 1, _TWO_3090)+ _, free, total = _TWO_3090[0]+ for tenth in range(180, 260):+ size = int(tenth / 10 * _GIB)+ too_big = llama_cpp_module._diffusion_auto_ngl(size, 30, 8, 4096, free, total) is not None+ fit = LlamaCppBackend._diffusion_fit_gpus(size, [0, 1], "0", "/bin/vs")+ assert fit == ([0, 1] if too_big else None), tenth / 10+++def test_diffusion_fit_gpus_moves_to_one_card_that_fits(monkeypatch):+ # GPU 0 is busy, GPU 1 holds the whole model: one card beats a layer split.+ _diffusion_fit_host(monkeypatch, 16.8, [(0, 4_000, 24_576), (1, 23_500, 24_576)])+ assert LlamaCppBackend._diffusion_fit_gpus(int(16.8 * _GIB), [0, 1], "0", "/bin/vs") == [1]+++def test_diffusion_fit_gpus_needs_a_runner_that_can_split(monkeypatch):+ # Older visual servers abort on the first request once split, so they keep one GPU.+ _diffusion_fit_host(monkeypatch, 26.9, _TWO_3090)+ monkeypatch.setattr(llama_cpp_module, "_visual_server_splits_gpus", lambda _bin: False)+ assert LlamaCppBackend._diffusion_fit_gpus(int(26.9 * _GIB), [0, 1], "0", "/bin/vs") is None+++def test_visual_server_split_marker_is_read_from_the_binary(tmp_path):+ old, new = tmp_path / "old-vs", tmp_path / "new-vs"+ old.write_bytes(b"\x7fELF usage: %s <model.gguf>")+ new.write_bytes(b"\x7fELF --capabilities\x00multi_gpu_split\n\x00")+ assert not llama_cpp_module._visual_server_splits_gpus(str(old))+ assert llama_cpp_module._visual_server_splits_gpus(str(new))+ assert not llama_cpp_module._visual_server_splits_gpus(str(tmp_path / "missing"))+ assert not llama_cpp_module._visual_server_splits_gpus(None)+++def test_diffusion_fit_gpus_never_reads_vulkan_ordinals(monkeypatch):+ _diffusion_fit_host(monkeypatch, 26.9, _TWO_3090, vulkan = True)+ assert LlamaCppBackend._diffusion_fit_gpus(int(26.9 * _GIB), None, "0", "/bin/vs") is None+++class _StopAtHealth(Exception):+ pass+++def _launch_diffusion(monkeypatch, tmp_path, *, gguf_gib, gpus, gpu_ids, **kwargs):+ """Drive the real _start_diffusion_server to the health wait; return (argv, env, backend)."""+ _diffusion_fit_host(monkeypatch, gguf_gib, gpus)+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.delenv("CUDA_DEVICE_ORDER", raising = False)+ backend = LlamaCppBackend()+ seen = {}++ class _FakePopen:+ pid = 999_999_999+ stdout = iter(())++ def __init__(self, cmd, **kw):+ seen["cmd"], seen["env"] = list(cmd), dict(kw["env"])++ def poll(self):+ return None++ monkeypatch.setattr(+ backend, "_find_diffusion_assets", lambda: (["python", "-m", "shim"], "/bin/vs", None)+ )+ monkeypatch.setattr(backend, "_kill_process", lambda: None)+ monkeypatch.setattr(backend, "_find_free_port", lambda: 18_123)+ monkeypatch.setattr(+ LlamaCppBackend, "_effective_gpu_count", staticmethod(lambda *_a: len(gpus))+ )+ monkeypatch.setattr(llama_cpp_module, "_swa_cache_path", lambda: tmp_path / "swa.json")+ monkeypatch.setattr(llama_cpp_module.subprocess, "Popen", _FakePopen)+ monkeypatch.setattr(+ backend,+ "_wait_for_health",+ lambda **_kw: (_ for _ in ()).throw(_StopAtHealth()),+ )+ with pytest.raises(_StopAtHealth):+ backend._start_diffusion_server(+ model_path = "/m.gguf",+ gguf_path = "/m.gguf",+ hf_repo = None,+ hf_variant = None,+ model_identifier = "unsloth/diffusiongemma-26B-A4B-it-GGUF",+ n_ctx = 0,+ extra_args = None,+ gpu_ids = gpu_ids,+ **kwargs,+ )+ return seen["cmd"], seen["env"], backend+++def _gpu_token(cmd):+ return cmd[cmd.index("--gpu") + 1]+++def test_diffusion_launch_splits_a_gguf_one_gpu_cannot_hold(monkeypatch, tmp_path):+ cmd, env, backend = _launch_diffusion(+ monkeypatch, tmp_path, gguf_gib = 26.9, gpus = _TWO_3090, gpu_ids = [1, 0]+ )+ assert _gpu_token(cmd) == "0,1"+ assert env["DG_GPU"] == "0,1"+ assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"+ assert backend.gpu_ids == [0, 1]+ assert backend.requested_gpu_ids == [0, 1]+ backend._is_diffusion = True+ assert backend.matches_gpu_ids([1, 0])+ assert not backend.matches_gpu_ids([0])+ backend._record_matching_gpu_request([1, 0])+ assert backend.requested_gpu_ids == [0, 1]+++def test_diffusion_launch_auto_split_records_no_pin(monkeypatch, tmp_path):+ cmd, env, backend = _launch_diffusion(+ monkeypatch, tmp_path, gguf_gib = 26.9, gpus = _TWO_3090, gpu_ids = None+ )+ assert _gpu_token(cmd) == "0,1"+ assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"+ assert backend.gpu_ids is None and backend.requested_gpu_ids is None++[email protected]("gpu_ids", [None, [0, 1]])+def test_diffusion_launch_that_fits_one_gpu_is_unchanged(monkeypatch, tmp_path, gpu_ids):+ cmd, env, backend = _launch_diffusion(+ monkeypatch, tmp_path, gguf_gib = 16.8, gpus = _TWO_3090, gpu_ids = gpu_ids+ )+ assert _gpu_token(cmd) == "0"+ assert ("CUDA_DEVICE_ORDER" in env) == bool(gpu_ids)+ expected = [0] if gpu_ids else None+ assert backend.gpu_ids == expected and backend.requested_gpu_ids == expected+ backend._is_diffusion = True+ assert backend.matches_gpu_ids(gpu_ids)+ assert backend.matches_gpu_ids([0]) == bool(gpu_ids)+++def test_diffusion_launch_manual_split_never_spreads(monkeypatch, tmp_path):+ monkeypatch.setattr(llama_cpp_module, "_shim_supports_ngl", lambda _cmd: True)+ cmd, _env, backend = _launch_diffusion(+ monkeypatch,+ tmp_path,+ gguf_gib = 26.9,+ gpus = _TWO_3090,+ gpu_ids = [0, 1],+ gpu_memory_mode = "manual",+ gpu_layers = 20,+ )+ assert _gpu_token(cmd) == "0"+ assert cmd[cmd.index("--ngl") + 1] == "20"+ assert backend.gpu_ids == [0]+++ ("gguf_gib", "fit_ngl", "token", "ngl"),+ [+ (26.9, 18, "0,1", None), # the pair holds Q8_0: split, no CPU layers+ (50.5, 12, "0", "12"), # BF16 fits no subset: one card plus CPU layers (#6456)+ ],+)+def test_diffusion_launch_prefers_a_gpu_split_over_cpu_layers(+ monkeypatch, tmp_path, gguf_gib, fit_ngl, token, ngl+):+ monkeypatch.setattr(llama_cpp_module, "_shim_supports_ngl", lambda _cmd: True)+ monkeypatch.setattr(LlamaCppBackend, "_diffusion_fit_ngl", lambda self, *_a, **_k: fit_ngl)+ cmd, _env, _backend = _launch_diffusion(+ monkeypatch, tmp_path, gguf_gib = gguf_gib, gpus = _TWO_3090, gpu_ids = [0, 1]+ )+ assert _gpu_token(cmd) == token+ assert (cmd[cmd.index("--ngl") + 1] if "--ngl" in cmd else None) == ngl+ # Only a CPU split pins the context; an all-GPU split keeps the runner's auto-size.+ assert cmd[cmd.index("--maxtok") + 1] == ("4096" if ngl else "0")++# ── Deliberate zero-offload (manual gpu_layers=0): training-skip flag ─────────diff --git a/studio/backend/tests/test_metal_paravirtual_guard.py b/studio/backend/tests/test_metal_paravirtual_guard.pyindex 74eccb7b2b6..81815173a2c 100644--- a/studio/backend/tests/test_metal_paravirtual_guard.py+++ b/studio/backend/tests/test_metal_paravirtual_guard.py@@ -1405,7 +1405,7 @@ def test_a_forced_cpu_diffusion_runner_records_no_effective_gpu_pin():made clearing it reload the same CPU runner; the pick still has to round-trip."""src = inspect.getsource(llama_cpp.LlamaCppBackend._start_diffusion_server)assert "_pv_diffusion_cpu = manual_ngl == 0 and _metal_device_is_paravirtual()" in src- assert "if gpu_ids and not _pv_diffusion_cpu else None" in src+ assert "self._gpu_ids = _pinned if not _pv_diffusion_cpu else None" in srcbackend = llama_cpp.LlamaCppBackend.__new__(llama_cpp.LlamaCppBackend)backend._is_diffusion = Truediff --git a/studio/frontend/src/features/chat/lib/resident-config-match.ts b/studio/frontend/src/features/chat/lib/resident-config-match.tsindex d5bb60b4214..122b490aee5 100644--- a/studio/frontend/src/features/chat/lib/resident-config-match.ts+++ b/studio/frontend/src/features/chat/lib/resident-config-match.ts@@ -473,19 +473,22 @@ const SETTING_CHECKS: SettingCheck[] = [c.selectedGpuIds ?? null,c.selectedGpuIndexKind,);- // The diffusion runner drives one device, so matches_gpu_ids reduces the request to its lowest id- // and the status reports only that.- const pick =+ // The diffusion runner reports the lowest id of a pick that fits it, else the whole sorted pick+ // it split over; matches_gpu_ids accepts either.+ const picks: (number[] | null)[] =s.is_diffusion === true && reconciled?.length- ? [Math.min(...reconciled)]- : reconciled;- if (sameGpuPlacement(pick, s.requested_gpu_ids)) {+ ? [[Math.min(...reconciled)], [...reconciled].sort((a, b) => a - b)]+ : [reconciled];+ if (picks.some((pick) => sameGpuPlacement(pick, s.requested_gpu_ids))) {return true;}// Either pool, as matches_gpu_ids accepts either: fitting may narrow the request to the smallest// subset that holds the model. Guarded on a non-empty echo, since an absent one is no// placement rather than Automatic.- return Boolean(s.gpu_ids?.length) && sameGpuPlacement(pick, s.gpu_ids);+ return (+ Boolean(s.gpu_ids?.length) &&+ picks.some((pick) => sameGpuPlacement(pick, s.gpu_ids))+ );},},{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 54bba704586..7bd9ed20498 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@@ -1175,9 +1175,9 @@ function GpuMemorySettings({</span></div>)}- {/* Not for diffusion: that runner drives one device and matches_gpu_ids- reduces the request to its lowest id, so the arrows would move a row- without moving the model, under help text promising the opposite. */}+ {/* Not for diffusion: that runner uses the lowest id, or splits in id+ order, so the arrows would move a row without moving the model, under+ help text promising the opposite. */}{isGpuChecked(d.index) && !singleGpuInUse && !isDiffusion && (<div className="flex shrink-0 items-center gap-0.5"><buttondiff --git a/studio/frontend/tests/resident-config-match.test.ts b/studio/frontend/tests/resident-config-match.test.tsindex c2da6f5ad72..1a6c65f05ec 100644--- a/studio/frontend/tests/resident-config-match.test.ts+++ b/studio/frontend/tests/resident-config-match.test.ts@@ -1094,6 +1094,17 @@ test("a diffusion resident is not judged on the chat-only invocation fields", ()assert.equal(matches({ ...diffusion, cache_type_kv: "q8_0" }, BLANK), false);});+test("a diffusion pick matches its lowest GPU or the GPUs it split over (#6347)", () => {+ // Fits one card: the runner reports only the lowest picked GPU.+ const single = { ...DEFAULTS, is_diffusion: true, requested_gpu_ids: [0], gpu_ids: [0] };+ assert.equal(matches(single, { ...BLANK, selectedGpuIds: [1, 0] }), true);+ // Too big for one card: it reports the whole sorted pick it split over.+ const split = { ...DEFAULTS, is_diffusion: true, requested_gpu_ids: [0, 1], gpu_ids: [0, 1] };+ assert.equal(matches(split, { ...BLANK, selectedGpuIds: [1, 0] }), true);+ // Narrowing that pick to one card is a reload.+ assert.equal(matches(split, { ...BLANK, selectedGpuIds: [0] }), false);+});+test("a dropped diffusion split is rechecked once the shim can apply it", () => {// diffusion_requested_ngl retains the request even when an older shim ignored it, so// once the installed shim gains --ngl support the same request must go through and