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 selection for image and video loads (#8645)
Maheswar Kumare7ea3cb979b1
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex db5486347e2..3924950793d 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -59,8 +59,13 @@ from .diffusion_families import (from .diffusion_compat import assert_flux2_pick_compatible, flux2_pick_mismatchfrom .diffusion_device import (DiffusionDeviceTarget,+ apply_diffusion_device_ordinal,+ diffusion_device_scope,diffusion_device_target_from_torch_device,+ pin_cuda_ordinal,+ placed_cuda_ordinal,resolve_diffusion_device_target,+ resolve_selected_cuda_ordinal,)from .diffusion_ideogram4 import ideogram4_repo_is_fp8, load_ideogram4_pipelinefrom .diffusion_hidream import HIDREAM_FAMILY_NAME, hidream_te4_kwargs@@ -778,6 +783,14 @@ class _LoadState:resolved: Optional[dict] = None# The single-file checkpoint basename this load committed (None for a pipeline). Part of the build identity.gguf_filename: Optional[str] = None+ # The torch ordinal this pipeline's weights were placed on, or None for an automatic pick.+ # Committed WITH the pipeline, so a load in flight never moves the resident model's card.+ gpu_ordinal: Optional[int] = None+ # The card the weights are ACTUALLY on, including the automatic case, where it is whichever+ # device the load thread was pointing at. Only for re-pinning a pooled generate worker that a+ # previous pinned load left on another card; the target and the reported build read+ # gpu_ordinal, so the automatic path still resolves a bare device.+ placed_ordinal: Optional[int] = None# The exact variant hint the memory plan was built from (family + checkpoint name + repo ids).# Stored rather than rebuilt so generate()'s activation re-check budgets with the SAME# distilled / edit multipliers the load did, and the two can never drift apart.@@ -1099,11 +1112,15 @@ class DiffusionBackend:def is_loaded(self) -> bool:return self._state is not None- def _pick_device_and_dtype(self) -> tuple[str, Any]:+ def _pick_device_and_dtype(self, ordinal: Optional[int] = None) -> tuple[str, Any]:"""(device, dtype) for the current host. Thin wrapper over the devicepolicy module, kept as a method so tests can still monkeypatch it."""- target = resolve_diffusion_device_target()- return target.device, target.dtype+ if ordinal is None:+ target = resolve_diffusion_device_target()+ return target.device, target.dtype+ target = resolve_diffusion_device_target(ordinal = ordinal)+ # The INDEXED string, so _resolve_device_target can rebuild a selection an override would erase.+ return target.torch_device, target.dtype# Memory requests whose offload policy is decided by the REQUEST rather than by the measured# footprint. `fast` and `auto` are measurements and so cannot be judged network-free.@@ -1116,6 +1133,7 @@ class DiffusionBackend:text_encoder_quant: Optional[str] = None,memory_mode: Optional[str] = None,cpu_offload: bool = False,+ gpu_ordinal: Optional[int] = None,) -> None:"""Raise ``RuntimeError`` (the route's 409) when an EXPLICIT precision cannot run here.@@ -1134,8 +1152,34 @@ class DiffusionBackend:te_mode = normalize_te_quant(text_encoder_quant)if pinned is None and te_mode is None:return- # One probe for both checks (it reads the live device).- target = self._resolve_device_target(fam)+ # One probe for both checks, asked of the card THIS load will use: on a mixed box the+ # default device can be a different generation, which would refuse a scheme the selected+ # card supports, or pass one it does not and fail only after eviction. Scoped, because the+ # route calls this on a pooled thread and the probes below use argument-less CUDA calls.+ with diffusion_device_scope(gpu_ordinal):+ target = self._target_for_ordinal(fam, gpu_ordinal)+ return self._assert_precision_for_target(+ fam,+ target,+ model_kind = model_kind,+ pinned = pinned,+ te_mode = te_mode,+ memory_mode = memory_mode,+ cpu_offload = cpu_offload,+ )++ def _assert_precision_for_target(+ self,+ fam: Optional[DiffusionFamily],+ target: DiffusionDeviceTarget,+ *,+ model_kind: str,+ pinned: Optional[str],+ te_mode: Optional[str],+ memory_mode: Optional[str],+ cpu_offload: bool,+ ) -> None:+ """The body of ``assert_precision_available``, run with the selected card current."""if pinned is not None and pinned != TQ_AUTO:reason = Noneif model_kind != "gguf":@@ -1227,7 +1271,12 @@ class DiffusionBackend:))- def _resolve_device_target(self, fam: Optional[DiffusionFamily]) -> DiffusionDeviceTarget:+ def _resolve_device_target(+ self,+ fam: Optional[DiffusionFamily],+ *,+ ordinal: Optional[int] = None,+ ) -> DiffusionDeviceTarget:"""The device target with the family fp16 guard applied.Routes through _pick_device_and_dtype() (so a monkeypatched override still@@ -1235,15 +1284,48 @@ class DiffusionBackend:families (Z-Image), rebuilding the target so dtype + capability flags stayconsistent with the effective dtype."""- device, dtype = self._pick_device_and_dtype()+ # Called with no argument on the automatic path so a monkeypatched seam keeps working.+ device, dtype = (+ self._pick_device_and_dtype()+ if ordinal is None+ else self._pick_device_and_dtype(ordinal)+ )effective = _resolve_diffusion_compute_dtype(fam, dtype)if effective is not dtype:logger.warning("diffusion.dtype_promoted: family=%s float16 -> float32 (fp16-incompatible)",getattr(fam, "name", None),)+ # Builds only. Pinning is the CALLER's decision: a worker thread is dedicated and takes+ # the permanent pin, while a route preflight runs on a pooled executor thread where an+ # unrestored set_device would leak this request's card into the next one.return diffusion_device_target_from_torch_device(device, effective)+ def _target_for_ordinal(+ self, fam: Optional[DiffusionFamily], ordinal: Optional[int]+ ) -> DiffusionDeviceTarget:+ """``_resolve_device_target`` with the ordinal only when there is one, so a monkeypatched+ seam taking just ``fam`` keeps working on the automatic path."""+ if ordinal is None:+ return self._resolve_device_target(fam)+ return self._resolve_device_target(fam, ordinal = ordinal)++ def _state_device_target(self, state: _LoadState) -> DiffusionDeviceTarget:+ """The resident pipeline's target, pinned onto the calling thread.++ Every worker touching the loaded pipeline goes through this rather than resolving bare:+ the weights are on ``state.gpu_ordinal`` while ``state.device`` is un-indexed, so an+ unpinned thread would resolve to its own default card.+ """+ target = self._target_for_ordinal(state.family, state.gpu_ordinal)+ apply_diffusion_device_ordinal(target)+ # And put an AUTOMATIC load back on its own card. generate() runs on a pooled+ # asyncio.to_thread worker, so a previous pinned model leaves that thread set to its GPU+ # for good; with no ordinal to pin, the bare "cuda" Generators below would then target that+ # card while these weights sit on the default one.+ pin_cuda_ordinal(state.placed_ordinal)+ return target+def _resolve_gguf_path(self, repo_id: str, gguf_filename: str, hf_token: Optional[str]) -> str:local_root = Path(repo_id).expanduser()if local_root.exists():@@ -1314,74 +1396,98 @@ class DiffusionBackend:return Falseif mm is None and kwargs.get("cpu_offload"):return False- target = self._resolve_device_target(fam)- # Same decline as load_pipeline: an uncached hosted pre-quant keeps the GGUF, so the- # plan must not stage the base transformer/ shards either.- if (- auto- # Active weights only: disagreeing with the load stages shards it never reads.- and not _has_active_lora(kwargs.get("loras"))- and _uncached_prequant_repo(+ # The card this load will land on, and SCOPED: the selectors below use argument-less+ # capability, smoke and memory probes, so building an indexed target is not enough to+ # move them off the default card.+ with diffusion_device_scope(kwargs.get("gpu_ordinal")):+ return self._dense_quant_prefetch_decision(fam,- target,- mode,- base_repo = kwargs.get("base_repo"),- prequant_path = kwargs.get("transformer_prequant_path"),- )- is not None- ):- return False- # The same rule, applied to the base repo's own dense shards. The fast path loads- # transformer/ INSTEAD of the GGUF, so on a pick the user made BY QUANT an uncached- # base means fetching a second, much larger denoiser and never opening the first:- # Qwen-Image-Edit's Q6_K is 16.9 GB and the base transformer is another 40.9 GB.- # Cached shards cost nothing, so anyone who already has the dense base keeps the fast- # path, and an EXPLICIT transformer_quant still opts in as before.- #- # This returns the same False a PREQUANT candidate returns below, so a cached- # pre-quant reaches the load with no transformer/ staged and NOT because a download- # was refused. That is why the load side re-asks the resolver rather than reading an- # empty stage as a decline: same verdict here, two different reasons there.- if (- auto- and not _has_active_lora(kwargs.get("loras"))- and not _dense_transformer_cached(- kwargs.get("base_repo"),+ kwargs,+ auto = auto,+ mode = mode,companion_files = companion_files,transformer_files = transformer_files,)- ):- return False- # Only widen when the loader would take the dense path; same candidate load_pipeline re-plans against.- candidate = resolve_dense_quant_candidate(- fam = fam,- target = target,- requested = mode,+ except Exception: # noqa: BLE001 -- an unanswerable probe keeps the GGUF+ return False++ def _dense_quant_prefetch_decision(+ self,+ fam: DiffusionFamily,+ kwargs: dict,+ *,+ auto: bool,+ mode: str,+ companion_files: Optional[Sequence[str]] = None,+ transformer_files: Optional[Sequence[str]] = None,+ ) -> bool:+ """``_dense_quant_prefetch_needed``'s body, run with the selected card current."""+ target = self._target_for_ordinal(fam, kwargs.get("gpu_ordinal"))+ # Same decline as load_pipeline: an uncached hosted pre-quant keeps the GGUF, so the+ # plan must not stage the base transformer/ shards either.+ if (+ auto+ # Active weights only: disagreeing with the load stages shards it never reads.+ and not _has_active_lora(kwargs.get("loras"))+ and _uncached_prequant_repo(+ fam,+ target,+ mode,base_repo = kwargs.get("base_repo"),prequant_path = kwargs.get("transformer_prequant_path"),- # An all-zero list bakes nothing; sizing it dense stages shards the load never reads.- force_dense = _has_active_lora(kwargs.get("loras")),- logger = None,)- # A prequant loads a small checkpoint, so widening defeats the savings and can disk-full.- if candidate is None or candidate.prequant:- return False- # Capacity gate: mirror plan_fits_total_capacity against TOTAL capacity, else load_pipeline declines the dense path anyway.- from .diffusion_memory import (- _reserve_mib,- snapshot_device_memory,+ is not None+ ):+ return False+ # The same rule, applied to the base repo's own dense shards. The fast path loads+ # transformer/ INSTEAD of the GGUF, so on a pick the user made BY QUANT an uncached+ # base means fetching a second, much larger denoiser and never opening the first:+ # Qwen-Image-Edit's Q6_K is 16.9 GB and the base transformer is another 40.9 GB.+ # Cached shards cost nothing, so anyone who already has the dense base keeps the fast+ # path, and an EXPLICIT transformer_quant still opts in as before.+ #+ # This returns the same False a PREQUANT candidate returns below, so a cached+ # pre-quant reaches the load with no transformer/ staged and NOT because a download+ # was refused. That is why the load side re-asks the resolver rather than reading an+ # empty stage as a decline: same verdict here, two different reasons there.+ if (+ auto+ and not _has_active_lora(kwargs.get("loras"))+ and not _dense_transformer_cached(+ kwargs.get("base_repo"),+ companion_files = companion_files,+ transformer_files = transformer_files,)-- memory = snapshot_device_memory(target)- total = memory.total_mib- steady = getattr(candidate, "steady_total_mib", None)- if total is not None and steady is not None:- budget = int((int(total) - _reserve_mib(memory.memory_kind, int(total))) * 0.85)- if int(steady) > budget:- return False- return True- except Exception: # noqa: BLE001 — widening the prefetch is best-effort only+ ):return False+ # Only widen when the loader would take the dense path; same candidate load_pipeline re-plans against.+ candidate = resolve_dense_quant_candidate(+ fam = fam,+ target = target,+ requested = mode,+ base_repo = kwargs.get("base_repo"),+ prequant_path = kwargs.get("transformer_prequant_path"),+ # An all-zero list bakes nothing; sizing it dense stages shards the load never reads.+ force_dense = _has_active_lora(kwargs.get("loras")),+ logger = None,+ )+ # A prequant loads a small checkpoint, so widening defeats the savings and can disk-full.+ if candidate is None or candidate.prequant:+ return False+ # Capacity gate: mirror plan_fits_total_capacity against TOTAL capacity, else load_pipeline declines the dense path anyway.+ from .diffusion_memory import (+ _reserve_mib,+ snapshot_device_memory,+ )++ memory = snapshot_device_memory(target)+ total = memory.total_mib+ steady = getattr(candidate, "steady_total_mib", None)+ if total is not None and steady is not None:+ budget = int((int(total) - _reserve_mib(memory.memory_kind, int(total))) * 0.85)+ if int(steady) > budget:+ return False+ return True@staticmethoddef _auto_prequant_retry_scheme(@@ -1662,10 +1768,26 @@ class DiffusionBackend:transformer_cache_threshold: Optional[float] = None,model_kind: Optional[str] = None,loras: Optional[list[tuple[str, float]]] = None,+ gpu_ids: Optional[list[int]] = None,+ # The ordinal the ROUTE already ranked, so the preflight and the load agree on one card.+ gpu_ordinal: Optional[int] = None,) -> dict[str, Any]:"""Validate, then run the (slow) load on a daemon thread. Returns at once."""# A blank token must mean "anonymous", not an empty credential the Hub 401s.hf_token = (hf_token.strip() if isinstance(hf_token, str) else hf_token) or None+ # Resolved ONCE, here, and carried to the worker: outside it so a bad pick is the route's+ # 400 rather than a load that dies mid-download, and only once so free VRAM cannot re-rank+ # the choice after the weights land. Gated on the resolved backend, since XPU / MPS / CPU+ # ignore physical ids and would otherwise 400 a selection the contract says to drop.+ # Re-ranked only when the caller did not already do it: free VRAM moves between the+ # route's preflight and here (network preflight, engine activation, arbiter eviction), so+ # resolving twice can approve a scheme against one card and place the weights on another.+ if gpu_ordinal is None:+ gpu_ordinal = (+ resolve_selected_cuda_ordinal(gpu_ids)+ if gpu_ids and resolve_diffusion_device_target().device == "cuda"+ else None+ )# base_repo is gated at the route pre-eviction; this only cheap-fails the resolved repo/family.fam = self.validate_load_request(repo_id,@@ -1682,6 +1804,7 @@ class DiffusionBackend:model_kind = resolve_model_kind(gguf_filename, model_kind),transformer_quant = transformer_quant,text_encoder_quant = text_encoder_quant,+ gpu_ordinal = gpu_ordinal,)with self._lock:@@ -1718,6 +1841,7 @@ class DiffusionBackend:transformer_cache_threshold = transformer_cache_threshold,model_kind = model_kind,loras = loras,+ gpu_ordinal = gpu_ordinal,_load_token = token,_cancel_event = cancel_event,),@@ -1745,7 +1869,10 @@ class DiffusionBackend:kwargs["base_repo"] = base# The pre-cast encoder replaces these weights, so skip their dense shards. Same resolver as the injection.te_prequant_files = self._te_prequant_plan_files(- fam, kwargs.get("text_encoder_quant"), kwargs.get("hf_token")+ fam,+ kwargs.get("text_encoder_quant"),+ kwargs.get("hf_token"),+ kwargs.get("gpu_ordinal"),)expected, base_files = self._estimate_download_bytes(kwargs["repo_id"],@@ -1894,7 +2021,10 @@ class DiffusionBackend:@staticmethoddef _te_prequant_plan_files(- fam: Any, text_encoder_quant: Optional[str], hf_token: Optional[str]+ fam: Any,+ text_encoder_quant: Optional[str],+ hf_token: Optional[str],+ gpu_ordinal: Optional[int] = None,) -> dict[str, tuple[str, list[tuple[str, int]]]]:"""``{component: (repo_id, [(rfilename, size)])}`` for the text encoders this pick willtake PRE-CAST from a hosted checkpoint instead of the base repo's dense weights.@@ -1909,7 +2039,12 @@ class DiffusionBackend:sources = te_prequant_sources(fam,te_quant_mode = text_encoder_quant,- target = resolve_diffusion_device_target(),+ # The selected card, for the same reason the dense-quant probe uses it.+ target = (+ resolve_diffusion_device_target()+ if gpu_ordinal is None+ else resolve_diffusion_device_target(ordinal = gpu_ordinal)+ ),)if not sources:return {}@@ -1957,62 +2092,70 @@ class DiffusionBackend:return Noneif mm is None and kwargs.get("cpu_offload"):return None- target = self._resolve_device_target(fam)- # An auto quant DECLINES an uncached hosted checkpoint and runs the GGUF as-is, so- # those bytes never land. Only a cached one, or an explicit request, counts.- if (- auto- and _uncached_prequant_repo(- fam,- target,- mode,- base_repo = kwargs.get("base_repo"),- prequant_path = kwargs.get("transformer_prequant_path"),+ # The card this load will land on, and SCOPED for the same reason as the dense-quant+ # probe: the selectors below read the current device, so an indexed target alone+ # leaves them on the default card.+ with diffusion_device_scope(kwargs.get("gpu_ordinal")):+ target = self._target_for_ordinal(fam, kwargs.get("gpu_ordinal"))+ # An auto quant DECLINES an uncached hosted checkpoint and runs the GGUF as-is, so+ # those bytes never land. Only a cached one, or an explicit request, counts.+ if (+ auto+ and _uncached_prequant_repo(+ fam,+ target,+ mode,+ base_repo = kwargs.get("base_repo"),+ prequant_path = kwargs.get("transformer_prequant_path"),+ )+ is not None+ ):+ return None+ scheme = select_transformer_quant_scheme(+ target, mode, family = getattr(fam, "name", None))- is not None- ):- return None- scheme = select_transformer_quant_scheme(- target, mode, family = getattr(fam, "name", None)- )- if scheme is None:- return None- source = usable_prequant_source(- fam,- scheme,- path_override = kwargs.get("transformer_prequant_path"),- base_repo = kwargs.get("base_repo"),- )-- if source is None and auto:- retry = self._auto_prequant_retry_scheme(- target,+ if scheme is None:+ return None+ source = usable_prequant_source(fam,- mode,scheme,- base_repo = kwargs.get("base_repo"),path_override = kwargs.get("transformer_prequant_path"),- loras = kwargs.get("loras"),+ base_repo = kwargs.get("base_repo"),)- if retry is not None:- source = usable_prequant_source(++ if source is None and auto:+ retry = self._auto_prequant_retry_scheme(+ target,fam,- retry,- path_override = kwargs.get("transformer_prequant_path"),+ mode,+ scheme,base_repo = kwargs.get("base_repo"),+ path_override = kwargs.get("transformer_prequant_path"),+ loras = kwargs.get("loras"),)- # A local override is the operator's own file: already on disk, never downloaded.- if source is None or source.kind != "repo":- return None- from huggingface_hub import HfApi+ if retry is not None:+ source = usable_prequant_source(+ fam,+ retry,+ path_override = kwargs.get("transformer_prequant_path"),+ base_repo = kwargs.get("base_repo"),+ )+ # A local override is the operator's own file: already on disk, never downloaded.+ if source is None or source.kind != "repo":+ return None+ from huggingface_hub import HfApi- info = HfApi(token = hf_token or None).model_info(source.location, files_metadata = True)- sizes = {s.rfilename: int(getattr(s, "size", 0) or 0) for s in (info.siblings or [])}- # Primary name first, then the legacy one, in the order the loader tries them.- for name in (source.filename, source.fallback_filename):- if name and name in sizes:- return (source.location, name, int(sizes[name]))- return None+ info = HfApi(token = hf_token or None).model_info(+ source.location, files_metadata = True+ )+ sizes = {+ s.rfilename: int(getattr(s, "size", 0) or 0) for s in (info.siblings or [])+ }+ # Primary name first, then the legacy one, in the order the loader tries them.+ for name in (source.filename, source.fallback_filename):+ if name and name in sizes:+ return (source.location, name, int(sizes[name]))+ return Noneexcept Exception as exc: # noqa: BLE001 -- an unsizable prequant must not fail the planlogger.warning("diffusion.dit_prequant_plan_failed: %s", exc)return None@@ -2210,7 +2353,9 @@ class DiffusionBackend:# request for the GGUF's tensor table), and None whenever nothing is known to be wrong.incompatible = flux2_pick_mismatch(fam, repo_id, gguf_filename, base, hf_token)# Only a checkpoint that really resolves on the Hub earns the right to drop dense shards.- te_files = self._te_prequant_plan_files(fam, text_encoder_quant, hf_token)+ te_files = self._te_prequant_plan_files(+ fam, text_encoder_quant, hf_token, load_kwargs.get("gpu_ordinal")+ )sizes: dict[str, int] = {}file_sizes: dict[str, dict[str, int]] = {}revisions: dict[str, str] = {}@@ -2872,6 +3017,8 @@ class DiffusionBackend:model_kind: Optional[str] = None,# LoRA adapters to BAKE into a torchao int8/fp8 build. Ignored elsewhere (bf16/bnb take them at generate time).loras: Optional[list[tuple[str, float]]] = None,+ # The torch ordinal begin_load resolved for this load, carried rather than re-derived.+ gpu_ordinal: Optional[int] = None,_load_token: Optional[int] = None,_base_local_dir: Optional[str] = None,# True when the prefetch staged the base repo's ``transformer/`` shards, the only condition under which the dense-quant@@ -2909,7 +3056,10 @@ class DiffusionBackend:# the only id handed to something that downloads. One decision per load (the background# path took it before staging), so nothing stages one repo and assembles from the other.fetch_base = _fetch_base or prefer_ungated_mirror(base, hf_token)- target = self._resolve_device_target(fam)+ target = self._target_for_ordinal(fam, gpu_ordinal)+ # A dedicated worker thread, so the pin is permanent and everything downstream -- the+ # placement, the offload budget, the un-indexed state.device -- lands on the same card.+ apply_diffusion_device_ordinal(target)device, dtype = target.device, target.dtypeimport diffusers@@ -3974,7 +4124,14 @@ class DiffusionBackend:# Apply the planned placement; apply_memory_plan returns what ACTUALLY engaged so status stays honest.effective_policy, effective_tiling = apply_memory_plan(- pipe, plan, device = device, logger = logger+ pipe,+ plan,+ device = device,+ # Indexed when a card was selected: the CPU-offload APIs read the index off+ # this string and default to cuda:0 without one, which would page modules+ # onto a different card than the one generation runs on.+ placement_device = target.torch_device,+ logger = logger,)# Per-control provenance for status. cpu_offload=False is the unset default, so only True is explicit.@@ -4070,6 +4227,8 @@ class DiffusionBackend:repo_id = repo_id,base_repo = base,device = device,+ gpu_ordinal = target.ordinal,+ placed_ordinal = placed_cuda_ordinal(target),dtype = str(dtype).replace("torch.", ""),kind = kind,cpu_offload = effective_policy != OFFLOAD_NONE,@@ -5016,7 +5175,7 @@ class DiffusionBackend:from .diffusion_eager_patches import install_compile_safe_patchesfrom .diffusion_arch_patches import install_arch_patches- target = self._resolve_device_target(state.family)+ target = self._state_device_target(state)install_compile_safe_patches()install_arch_patches()object.__setattr__(state, "eager_patched", True)@@ -5135,6 +5294,11 @@ class DiffusionBackend:# Publish an active (step 0) state before the slow pre-denoise setup so a reload mount probe does not read idle.self._gen = _GenState(total_steps = steps)try:+ # FIRST, before any device object exists. This worker is not the thread that loaded+ # the pipeline, so until it is pinned the un-indexed state.device below -- and the+ # ControlNet placement further down -- resolve to its own default card while the+ # weights sit on the selected one.+ self._state_device_target(state)# The local `state` ref keeps the pipe alive even if unload() nulls _state. Resolve the per-image (prompt, seed) jobs# up front: N prompts, one prompt x N seeds, or one prompt deriving base..base+batch_size-1 (as the native engine does).jobs, seed = resolve_batch_jobs(@@ -5398,7 +5562,7 @@ class DiffusionBackend:# variant credits the same reclaimable bytes back arithmetically instead,# so a warm allocator does not read as a full card and nothing is flushed.device_memory = reclaimable_snapshot_device_memory(- self._resolve_device_target(state.family)+ self._state_device_target(state)),width = guard_width,height = guard_height,diff --git a/studio/backend/core/inference/diffusion_compile_cache.py b/studio/backend/core/inference/diffusion_compile_cache.pyindex be0e2a73daa..9b88e9f2762 100644--- a/studio/backend/core/inference/diffusion_compile_cache.py+++ b/studio/backend/core/inference/diffusion_compile_cache.py@@ -118,8 +118,12 @@ def environment_fingerprint() -> dict[str, Any]:fp["torch"] = str(torch.__version__)fp["torch_cuda"] = str(torch.version.cuda)if torch.cuda.is_available():- fp["gpu_name"] = torch.cuda.get_device_name(0)- cap = torch.cuda.get_device_capability(0)+ # The CURRENT device, not 0: a load pinned to another card compiles for that+ # architecture, and keying the bundle by GPU 0 lets two cards share or overwrite+ # each other's supposedly architecture-specific artifacts.+ index = torch.cuda.current_device()+ fp["gpu_name"] = torch.cuda.get_device_name(index)+ cap = torch.cuda.get_device_capability(index)fp["gpu_capability"] = f"sm_{cap[0]}{cap[1]}"except Exception: # noqa: BLE001 — best-effortpassdiff --git a/studio/backend/core/inference/diffusion_device.py b/studio/backend/core/inference/diffusion_device.pyindex f50ded7428d..6590c985a1f 100644--- a/studio/backend/core/inference/diffusion_device.py+++ b/studio/backend/core/inference/diffusion_device.py@@ -12,6 +12,7 @@ the capability flags optimisation paths key off.from __future__ import annotationsimport os+from contextlib import contextmanagerfrom dataclasses import dataclassfrom typing import Any, Optional@@ -28,11 +29,18 @@ class DiffusionDeviceTarget:supports_default_torch_compile: boolsupports_pinned_transfer: boolsupports_float64: bool = True+ # Selected CUDA/ROCm physical index, kept OUT of ``device``: the memory, speed and attention policies compare that string against "cuda", so a "cuda:1" there disables them silently.+ ordinal: Optional[int] = None@propertydef is_cuda_torch_device(self) -> bool:return self.device == "cuda"+ @property+ def torch_device(self) -> str:+ """The device string to PLACE weights on, indexed when one card was selected."""+ return f"{self.device}:{self.ordinal}" if self.ordinal is not None else self.device+def as_public_dict(self) -> dict[str, Any]:return {"device": self.device,@@ -43,6 +51,7 @@ class DiffusionDeviceTarget:"supports_default_torch_compile": self.supports_default_torch_compile,"supports_pinned_transfer": self.supports_pinned_transfer,"supports_float64": self.supports_float64,+ "ordinal": self.ordinal,}@@ -143,13 +152,154 @@ def _studio_device_is(studio_device: Any, device_type: Any, name: str) -> bool:return member is not None and studio_device == member-def resolve_diffusion_device_target() -> DiffusionDeviceTarget:+def resolve_selected_cuda_ordinal(+ gpu_ids: Optional[list[int]], *, allow_ranking: bool = True+) -> Optional[int]:+ """The torch ordinal one diffusion load should run on, or None for automatic.++ ``gpu_ids`` carries PHYSICAL ids, as chat, training and the UI use. Torch indexes only the+ parent-visible subset, so under a ``CUDA_VISIBLE_DEVICES`` mask the two differ in value and+ order (``4,5`` -> torch 0,1; ``1,0`` reverses them), hence going through the hardware layer+ that owns the mask.++ Neither engine shards a checkpoint, so several cards still resolve to one: most free VRAM+ wins, as ``auto_select_gpu_ids`` already does for training, ties to the lowest ordinal. Taking+ the FIRST id instead would land on ordinal 0 whenever everything is selected, i.e. the small+ card on the mixed boxes this exists for. Resolved ONCE per load and carried, never re-derived:+ free VRAM moves the moment the checkpoint lands.++ Raises ValueError for a selection this host cannot honour, so the load is refused with a+ reason rather than quietly running somewhere the user did not choose.++ ``allow_ranking = False`` drops only the free-VRAM probe, for a caller that must not open a+ CUDA context (the plan routes while a trainer holds the cards). Validation and translation+ still run -- they read the mask and nvidia-smi -- so the single card the UI sends resolves and+ only a multi-card pick comes back None.+ """+ wanted = sorted({int(gpu_id) for gpu_id in gpu_ids or ()})+ if not wanted:+ return None+ try:+ from utils.hardware.hardware import (+ get_parent_visible_gpu_ids,+ resolve_requested_gpu_ids,+ )+ except Exception as exc: # noqa: BLE001 -- without the hardware layer the mask is unknowable+ raise ValueError(f"GPU selection is unavailable on this host: {exc}") from exc+ allowed = resolve_requested_gpu_ids(wanted)+ visible = get_parent_visible_gpu_ids()+ # Torch enumerates the parent-visible list in order, so its ordinal for a physical id is that+ # id's position in the mask. Unmasked, the layer reports range(physical count) and this is+ # the identity mapping.+ ordinals = [visible.index(gpu_id) for gpu_id in allowed if gpu_id in visible]+ if not ordinals:+ raise ValueError(+ f"Requested GPU {wanted} but none of them are visible to this process "+ f"(visible: {visible}). Clear the GPU selection to use the default device."+ )+ if len(ordinals) == 1:+ return ordinals[0]+ if not allow_ranking:+ return None++ def _free_vram(ordinal: int) -> int:+ try:+ import torch+ return int(torch.cuda.mem_get_info(ordinal)[0])+ except Exception: # noqa: BLE001 -- an unreadable card sorts last rather than failing the load+ return -1++ return max(ordinals, key = lambda ordinal: (_free_vram(ordinal), -ordinal))+++@contextmanager+def diffusion_device_scope(ordinal: Optional[int]):+ """Make ``ordinal`` the current CUDA device for the block, then restore the previous one.++ For probes on a POOLED thread. ``torch.cuda.set_device`` is thread-local but not scoped, so a+ permanent pin on an asyncio.to_thread executor thread outlives the request and leaves the next+ one -- perhaps an automatic load -- resolving bare "cuda" against the previous request's card.+ Worker threads are dedicated and keep the permanent pin.+ """+ if ordinal is None:+ yield+ return+ # Entering the context is what may fail on an unusable index; the BODY's exceptions have to+ # travel untouched, or a yield-after-throw replaces the caller's real refusal with+ # "generator didn't stop after throw()".+ try:+ import torch+ scope = torch.cuda.device(ordinal)+ scope.__enter__()+ except Exception: # noqa: BLE001 -- an unreadable index still runs the probe, unpinned+ yield+ return+ try:+ yield+ finally:+ try:+ scope.__exit__(None, None, None)+ except Exception: # noqa: BLE001 -- restoring is best effort; never mask the body+ pass+++def apply_diffusion_device_ordinal(target: DiffusionDeviceTarget) -> None:+ """Point this thread's CUDA context at ``target.ordinal``.++ Thread-local, so every worker that loads or runs a pipeline has to call it; the load thread+ setting it does nothing for the generate thread. The right lever rather than an indexed device+ string because the offload policy reads ``torch.cuda.mem_get_info()`` with no argument, i.e.+ the CURRENT device, so this steers the weights and their budget to the same card. A no-op for+ an automatic pick.+ """+ if not target.is_cuda_torch_device:+ return+ pin_cuda_ordinal(target.ordinal)+++def pin_cuda_ordinal(ordinal: Optional[int]) -> None:+ """``torch.cuda.set_device``, thread-local, never fatal. A no-op for None."""+ if ordinal is None:+ return+ try:+ import torch+ torch.cuda.set_device(ordinal)+ except Exception: # noqa: BLE001 -- placement still works off torch_device; never fail a load here+ pass+++def placed_cuda_ordinal(target: DiffusionDeviceTarget) -> Optional[int]:+ """The card the weights are actually on: the selection when there was one, else the card the+ loading thread was pointing at.++ Recorded WITH the pipeline because ``/images/generate`` runs on a pooled ``asyncio.to_thread``+ worker: a pinned load leaves that worker on its card permanently, and a later automatic load+ has no ordinal to re-pin with, so its bare "cuda" Generators and allocations would land on the+ previous model's GPU while the weights sat on the default one. Kept apart from ``ordinal`` so+ the automatic path still reports a bare device and an un-indexed target, as it always did.+ """+ if not target.is_cuda_torch_device:+ return None+ if target.ordinal is not None:+ return target.ordinal+ try:+ import torch+ return int(torch.cuda.current_device())+ except Exception: # noqa: BLE001 -- an unreadable device simply leaves the worker alone+ return None+++def resolve_diffusion_device_target(*, ordinal: Optional[int] = None) -> DiffusionDeviceTarget:"""Resolve the torch device + dtype + capability flags for diffusion.Prefers Studio's hardware layer, else probes torch (CUDA -> XPU -> MPS -> CPU). On AppleSilicon Studio may report MLX/CPU, but diffusers uses MPS, so those fall through to the MPSprobe. Torch is optional: without it the native sd.cpp engine still runs, so a missing torchreports a torch-free CPU target instead of crashing ``/images/load`` before engine selection.++ ``ordinal`` is an ALREADY-RESOLVED torch index from ``resolve_selected_cuda_ordinal``, carried+ for one load rather than re-derived. Honoured only on CUDA / ROCm, where an index is what the+ runners speak; XPU has no applicator and MPS / CPU nothing to choose between."""try:import torch@@ -178,14 +328,14 @@ def resolve_diffusion_device_target() -> DiffusionDeviceTarget:if DeviceType is not None and studio_device is not None:if _studio_device_is(studio_device, DeviceType, "CUDA"):if torch.cuda.is_available():- return _cuda_or_rocm_target(torch, is_rocm = is_rocm)+ return _cuda_or_rocm_target(torch, is_rocm = is_rocm, ordinal = ordinal)return _cpu_target(torch)if _studio_device_is(studio_device, DeviceType, "XPU"):return _xpu_target(torch)# MLX / CPU / else: diffusers uses MPS, so fall through to the torch probe (MPS over CPU).if torch.cuda.is_available():- return _cuda_or_rocm_target(torch, is_rocm = is_rocm)+ return _cuda_or_rocm_target(torch, is_rocm = is_rocm, ordinal = ordinal)xpu = getattr(torch, "xpu", None)if xpu is not None and callable(getattr(xpu, "is_available", None)):@@ -203,7 +353,7 @@ def diffusion_device_target_from_torch_device() -> DiffusionDeviceTarget:"""Reconstruct a target from a (device, dtype) pair, so a caller overriding the tuple (the``_pick_device_and_dtype`` shim / monkeypatch path) can still recover the capability flags."""- device = str(torch_device).split(":", 1)[0]+ device, _, index = str(torch_device).partition(":")if device == "cuda":try:import torch@@ -218,6 +368,8 @@ def diffusion_device_target_from_torch_device(supports_model_cpu_offload = True,supports_default_torch_compile = not is_rocm,supports_pinned_transfer = True,+ # An overriding caller's "cuda:1" is a device choice to keep, not one to drop back to ordinal 0.+ ordinal = int(index) if index.isdigit() else None,)if device == "xpu":return DiffusionDeviceTarget(@@ -243,18 +395,30 @@ def diffusion_device_target_from_torch_device(return _cpu_target(torch = None, dtype = dtype)-def _cuda_or_rocm_target(torch: Any, *, is_rocm: bool) -> DiffusionDeviceTarget:+def _cuda_or_rocm_target(+ torch: Any,+ *,+ is_rocm: bool,+ ordinal: Optional[int] = None,+) -> DiffusionDeviceTarget:if is_rocm:# ROCm lacks NVIDIA's pre-Ampere bf16-emulation quirk, so is_bf16_supported() is trustworthy.+ # It takes no device argument, so the selected card is asked by scoping the current device.try:- bf16_ok = bool(torch.cuda.is_bf16_supported())+ with diffusion_device_scope(ordinal):+ bf16_ok = bool(torch.cuda.is_bf16_supported())except Exception:bf16_ok = Falsedtype = torch.bfloat16 if bf16_ok else torch.float16else:# NVIDIA: bf16 needs Ampere+ (major >= 8), by capability NOT is_bf16_supported() (pre-Ampere cards emulate bf16 slowly but report it supported).+ # Asked of the SELECTED card, since the argument-less form reports the current device, a different generation on a mixed box; still argument-less without a selection.try:- major = torch.cuda.get_device_capability()[0]+ major = (+ torch.cuda.get_device_capability()+ if ordinal is None+ else torch.cuda.get_device_capability(ordinal)+ )[0]except Exception:major = 0dtype = torch.bfloat16 if major >= 8 else torch.float16@@ -266,6 +430,7 @@ def _cuda_or_rocm_target(torch: Any, *, is_rocm: bool) -> DiffusionDeviceTarget:supports_model_cpu_offload = True,supports_default_torch_compile = not is_rocm,supports_pinned_transfer = True,+ ordinal = ordinal,)diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex a2492246afc..58e0ba83e97 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -783,6 +783,7 @@ def apply_memory_plan(plan: MemoryPlan,*,device: str,+ placement_device: Optional[str] = None,logger: Any = None,) -> tuple[str, bool]:"""Apply ``plan`` to a built diffusers pipeline: enable the VAE savers then place / offload@@ -790,7 +791,15 @@ def apply_memory_plan(Returns the ``(offload_policy, vae_tiling)`` ACTUALLY engaged, which can differ from the plan:tiling is a no-op where there's no tiling control, and group / sequential offload fall back to- whole-module offload if unsupported (e.g. sequential is broken for GGUF through diffusers 0.39)."""+ whole-module offload if unsupported (e.g. sequential is broken for GGUF through diffusers 0.39).++ ``placement_device`` is the INDEXED string when a card was selected ("cuda:1"), and is what+ every diffusers handoff below receives. A bare "cuda" is not equivalent to the CPU-offload+ APIs: ``enable_model_cpu_offload`` reads the index off the device and, finding none, falls+ back to ``_offload_gpu_id = 0`` and onloads to cuda:0 (pipeline_utils.py, diffusers 0.39), so+ the modules would page onto the very card the selection existed to avoid while generation ran+ on another. ``device`` stays bare for anything reading it as a policy string."""+ placement = placement_device or devicetiling_engaged = Falseif plan.vae_tiling:tiling_engaged = _enable_vae_saver(pipe, "enable_vae_tiling", "enable_tiling", logger)@@ -800,28 +809,28 @@ def apply_memory_plan(def _fallback_to_model_offload() -> None:# The GROUP plan set vae_tiling=False (the VAE stays resident). Dropping to whole-module offload is the low-VRAM case where the decode spike can OOM, so turn tiling on now.nonlocal tiling_engaged- pipe.enable_model_cpu_offload(device = device)+ pipe.enable_model_cpu_offload(device = placement)if not tiling_engaged:tiling_engaged = _enable_vae_saver(pipe, "enable_vae_tiling", "enable_tiling", logger)policy = plan.offload_policyif policy == OFFLOAD_MODEL:- pipe.enable_model_cpu_offload(device = device)+ pipe.enable_model_cpu_offload(device = placement)elif policy == OFFLOAD_GROUP:# getattr, not attribute access: manually built / duck-typed plans predate this field.if not _apply_group_offload(pipe,- device,+ placement,logger,stream_text_encoders = bool(getattr(plan, "stream_text_encoders", False)),):_fallback_to_model_offload()policy = OFFLOAD_MODELelif policy == OFFLOAD_STREAMING:- _apply_streaming_offload(pipe, device, logger)+ _apply_streaming_offload(pipe, placement, logger)elif policy == OFFLOAD_SEQUENTIAL:try:- pipe.enable_sequential_cpu_offload(device = device)+ pipe.enable_sequential_cpu_offload(device = placement)except Exception as exc: # noqa: BLE001 — keep the model loadableif logger is not None:logger.warning(@@ -832,7 +841,7 @@ def apply_memory_plan(_fallback_to_model_offload()policy = OFFLOAD_MODELelse:- pipe.to(device)+ pipe.to(placement)return policy, tiling_engageddiff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex 3c1aafe8c84..1093f0d0f25 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -353,6 +353,18 @@ def _strip_paths(text: str) -> str:# Cache of (scheme, device) -> bool so the quantise+matmul smoke test runs once._SMOKE_CACHE: dict[tuple[str, str], bool] = {}++def _smoke_cache_device_key(device: str) -> str:+ """``device`` qualified with the current CUDA index, so each card is validated on its own."""+ if device != "cuda":+ return device+ try:+ import torch+ return f"cuda:{torch.cuda.current_device()}"+ except Exception: # noqa: BLE001 -- an unreadable index falls back to the un-indexed key+ return device++# Data-center GPU tokens (un-nerfed FP32 accumulate). Matched as whole tokens of get_device_name() so "A4000" is not mistaken for "A40"; anything else is consumer-class._DATACENTER_GPU_TOKENS = frozenset({@@ -797,7 +809,10 @@ def _smoke_probe(``new_zeros`` out to 226 or 512, so the tail rows reaching the DiT are exactly zero.Measured on B200, 4096-wide Linear: 412 of 512 rows non-finite without the floor, 0 of 512with it. Failing here costs one ladder step down to int8 instead."""- key = (scheme, device)+ # Keyed by the CARD, not just "cuda": the probe runs on whichever device is current, so on a+ # heterogeneous host a pass on one selected GPU would otherwise stand in for an untested one,+ # and a failure on an older card would reject the scheme on a capable one.+ key = (scheme, _smoke_cache_device_key(device))if key in _SMOKE_CACHE:return _SMOKE_CACHE[key]ok = _run_smoke_probe(scheme, device)diff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.pyindex 57ebf02641b..37330ba32be 100644--- a/studio/backend/core/inference/sd_cpp_args.py+++ b/studio/backend/core/inference/sd_cpp_args.py@@ -13,6 +13,7 @@ one knob drives both engines. Ref: sd.cpp ``examples/cli`` and ``docs/z_image.mdfrom __future__ import annotations+from collections.abc import Sequencefrom dataclasses import dataclass, fieldfrom typing import Optional@@ -173,6 +174,56 @@ def metal_text_encoder_flags() -> list[str]:# Everything on the CPU backend. sd.cpp prefers GPU -> integrated GPU -> CPU and only `--backend` changes which backend EXECUTES the graph (`--offload-to-cpu` moves parameters, not compute), so this is the one flag that removes ggml-metal entirely.CPU_BACKEND_FLAGS: tuple[str, ...] = ("--backend", "cpu")++def device_backend_flags(+ device_name: Optional[str], offload: Optional[list[str]] = None+) -> list[str]:+ """Pin the diffusion, text-encoder and VAE graphs to one ggml device (e.g. ``CUDA1``).++ Without this sd.cpp uses its own default device, ordinal 0 whatever the user chose, so on a+ mixed box the checkpoint lands on the first card rather than the one that can hold it. Empty+ for an automatic pick, which keeps sd.cpp's choice.++ ``--clip-on-cpu`` / ``--vae-on-cpu`` are the deprecated spellings of ``te=cpu`` / ``vae=cpu``,+ so pinning a device over them would win last and undo the low_vram policy. Only the modules+ that policy left on the GPU are pinned.+ """+ if not device_name:+ return []+ flags = offload or []+ te = "cpu" if "--clip-on-cpu" in flags else device_name+ vae = "cpu" if "--vae-on-cpu" in flags else device_name+ return ["--backend", f"diffusion={device_name},te={te},vae={vae}"]+++def without_device_backend_flags(flags: Sequence[str]) -> list[str]:+ """``flags`` with every ``--backend <spec>`` pair removed.++ Two callers, both wrong if they read the pin.++ The status and the saved recipe derive "was anything offloaded?" from these flags being+ empty, so a pin on a `fast` load (whose policy is deliberately no flags) would report an+ offload that never happened, purely because a card was selected.++ And sd.cpp CONCATENATES repeated ``--backend`` values rather than replacing+ (``examples/common/common.cpp``, ``concat = ','``), with an explicit per-module entry beating+ the bare default (``ggml_extend_backend.cpp``). Appending ``--backend cpu`` to a spec that+ says ``diffusion=CUDA0`` therefore leaves the denoiser on CUDA, making the CPU-backend restart+ -- the recovery from a ggml op the device cannot run -- a silent no-op.+ """+ out: list[str] = []+ skip = False+ for flag in flags:+ if skip:+ skip = False+ continue+ if flag == "--backend":+ skip = True+ continue+ out.append(flag)+ return out++# The ggml signature for "this graph cannot run on this backend at all": ggml-metal calls GGML_ABORT when ggml_metal_device_supports_op() returns false, since a single-backend graph has nowhere else to put the node. The SIGABRT takes sd-server down mid-generation._GGML_UNSUPPORTED_OP_MARKERS = ("unsupported op", "ggml_abort")diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex ee7fd13c7fc..6990a65ba04 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -35,7 +35,10 @@ from pathlib import Pathfrom typing import Any, Optionalfrom core.inference.diffusion_compat import flux2_inner_dim_for_pick-from core.inference.diffusion_device import resolve_diffusion_device_target+from core.inference.diffusion_device import (+ resolve_diffusion_device_target,+ resolve_selected_cuda_ordinal,+)from core.inference.diffusion_families import (DIFFUSION_CANCELLED_MSG,DIFFUSION_NOT_LOADED_MSG,@@ -62,8 +65,10 @@ from core.inference.sd_cpp_args import (SdCppGenParams,SdCppModelFiles,build_img_gen_request,+ device_backend_flags,is_ggml_unsupported_op_abort,offload_flags,+ without_device_backend_flags,)from core.inference.sd_cpp_engine import (NATIVE_GENERATION_TIMEOUT_S,@@ -354,6 +359,42 @@ def sd_cpp_accelerator_device_verdict(binary: str) -> Optional[bool]:return any(name.upper() != "CPU" for name in names)+# ggml device-name prefixes indexed by CUDA physical ordinal (ggml names its HIP backend either way); Vulkan is excluded, its ordinals are another namespace.+_PHYSICAL_INDEX_DEVICE_PREFIXES: tuple[str, ...] = ("CUDA", "ROCM")+++def sd_cpp_device_name_for_ordinal(binary: Optional[str], ordinal: Optional[int]) -> Optional[str]:+ """The ``--list-devices`` name for CUDA/ROCm physical index ``ordinal``, or None.++ None whenever the answer is not certain -- no selection, an unreadable probe, a build whose+ devices are in another namespace, an index it does not list -- since the fallback is sd.cpp's+ own device choice, i.e. today's behaviour.+ """+ if not binary or ordinal is None:+ return None+ text = _sd_cpp_probe_output(binary, "--list-devices")+ if text is not None:+ for line in text.splitlines():+ name = line.split("\t", 1)[0].strip()+ head = name.rstrip("0123456789")+ if head.upper() not in _PHYSICAL_INDEX_DEVICE_PREFIXES:+ continue+ if name[len(head) :] == str(ordinal):+ return name+ # Said out loud rather than dropped in silence: the load still runs, on whichever device this+ # build picks for itself, which is what happens today for every native load. Refusing instead+ # would take the GPU selection from "not honoured here" to "cannot load at all" on any build+ # older than the one that added --list-devices, including a user's own SD_CLI_PATH copy, since+ # sd.cpp treats an unknown argument as fatal.+ logger.warning(+ "sd_cpp.device_pin_unresolved: this build does not report a CUDA/ROCm device %s "+ "(--list-devices %s), so the graph runs on its own default device",+ ordinal,+ "was unreadable" if text is None else "does not list it",+ )+ return None++def _h3_replacement_hint(binary: str) -> str:"""The trailing "or delete it" clause of the H3 refusal, or "" when there is nothing to delete.@@ -823,6 +864,16 @@ class _SdState:sd_accelerator: Optional[str] = None+def _offload_with_device_pin_impl(+ offload: tuple[str, ...] | list[str], binary: Optional[str], ordinal: Optional[int]+) -> list[str]:+ """``offload`` plus the ``--backend`` pin for whichever build is about to run it."""+ flags = list(offload)+ if ordinal is None:+ return flags+ return [*flags, *device_backend_flags(sd_cpp_device_name_for_ordinal(binary, ordinal), flags)]++def _memory_policy(memory_mode: Optional[str], cpu_offload: bool) -> str:"""Map the diffusers memory knobs onto an sd-cli offload policy. Only meaningfuloff-CPU (forced sd_cpp / MPS); on CPU everything is resident in RAM anyway."""@@ -1096,10 +1147,24 @@ class SdCppDiffusionBackend:model_kind: Optional[str] = None,# Parity with the diffusers load-time LoRA bake; native applies LoRA per generation, so a load-time selection is ignored.loras: Optional[list[tuple[str, float]]] = None,+ gpu_ids: Optional[list[int]] = None,+ # The ordinal the ROUTE already ranked, so the preflight and the load agree on one card.+ gpu_ordinal: Optional[int] = None,) -> dict[str, Any]:"""Validate, then fetch assets on a daemon thread. Returns at once."""# Empty/whitespace token = "no token"; "" verbatim breaks the anonymous fallback.hf_token = hf_token.strip() if hf_token and hf_token.strip() else None+ # Same fallback the diffusers and video backends take: the route ranks the selection and+ # passes the winner, but a direct caller (an MCP client, a test, a plugin) hands over+ # gpu_ids alone, and without this the native engine is the one engine that would drop the+ # pick silently. Re-ranked only when nobody has, so a route-resolved winner is never+ # second-guessed against free VRAM that has moved since.+ if gpu_ordinal is None:+ gpu_ordinal = (+ resolve_selected_cuda_ordinal(gpu_ids)+ if gpu_ids and resolve_diffusion_device_target().device == "cuda"+ else None+ )if not gguf_filename:raise ValueError("gguf_filename is required: the native engine loads single-file GGUF checkpoints only."@@ -1178,6 +1243,7 @@ class SdCppDiffusionBackend:cpu_offload = cpu_offload,memory_mode = memory_mode,speed_mode = speed_mode,+ gpu_ordinal = gpu_ordinal,_load_token = token,_cancel_event = cancel_event,),@@ -1196,6 +1262,7 @@ class SdCppDiffusionBackend:cpu_offload: bool = False,memory_mode: Optional[str] = None,speed_mode: Optional[str] = None,+ gpu_ordinal: Optional[int] = None,_load_token: int,_cancel_event: Optional[threading.Event] = None,) -> None:@@ -1302,6 +1369,11 @@ class SdCppDiffusionBackend:offload: tuple[str, ...] = ()if device != "cpu":offload = tuple(offload_flags(_memory_policy(memory_mode, cpu_offload)))+ # The device pin is NOT folded in here: the binary can still change below, through the+ # deferred accelerator install, the post-download re-resolve, or a server start that+ # falls back to one-shot, and the ggml device names come from whichever build ends up+ # running. It is added at each point the flags are handed to a binary instead.+ gpu_ordinal = gpu_ordinal if device == "cuda" else Nonenative_speed = _native_speed_for(speed_mode)# Tear down the old model then commit the new one under _generate_lock: abort and WAIT for a generation started during@@ -1437,7 +1509,9 @@ class SdCppDiffusionBackend:server.start(files,vae_format = fam.sd_cpp_vae_format,- offload = list(offload),+ offload = _offload_with_device_pin_impl(+ offload, server_binary, gpu_ordinal+ ),native_speed = native_speed,# Pin to physical cores (sd.cpp's default oversubscribes; see _default_threads).threads = _default_threads(),@@ -1506,7 +1580,15 @@ class SdCppDiffusionBackend:files = files,vae_format = fam.sd_cpp_vae_format,native_speed = native_speed,- offload_flags = offload,+ # Pinned against the binary this load COMMITTED to, which a deferred install or+ # a one-shot fallback may have changed since the policy was built.+ offload_flags = tuple(+ _offload_with_device_pin_impl(+ offload,+ server_binary if mode == "server" else getattr(engine, "binary", None),+ gpu_ordinal,+ )+ ),# One-shot sd-cli reads this per generation; pin to physical cores.threads = _default_threads(),sampling_method = fam.sd_cpp_sampling_method,@@ -2075,7 +2157,11 @@ class SdCppDiffusionBackend:"transformer_quant": None,"text_encoder_quant": None,"memory_mode": None,- "offload_policy": "active" if state.offload_flags else "none",+ # The POLICY flags only: a --backend pin says which card ran the graph, not+ # that anything was offloaded, and a `fast` load carries no policy flags at all.+ "offload_policy": (+ "active" if without_device_backend_flags(state.offload_flags) else "none"+ ),}except SdCppCancelled as exc:raise RuntimeError(DIFFUSION_CANCELLED_MSG) from exc@@ -2246,7 +2332,11 @@ class SdCppDiffusionBackend:server.start(state.files,vae_format = state.vae_format,- offload = list(state.offload_flags),+ # WITHOUT the device pin. sd.cpp joins repeated --backend values into one spec+ # instead of replacing, and an explicit diffusion=CUDA0 outranks the bare `cpu`+ # default, so leaving the pin on would restart the server onto the very backend+ # that just aborted.+ offload = without_device_backend_flags(state.offload_flags),native_speed = state.native_speed,threads = state.threads,extra_args = list(CPU_BACKEND_FLAGS),@@ -2499,9 +2589,12 @@ class SdCppDiffusionBackend:"gguf_variant": extract_quant_token(state.gguf_filename)if state.gguf_filenameelse None,- # Reflect the offload flags actually passed to sd-cli (empty on CPU -> "none").- "cpu_offload": bool(state.offload_flags),- "offload_policy": "active" if state.offload_flags else "none",+ # Reflect the offload flags actually passed to sd-cli (empty on CPU -> "none"), minus+ # the --backend device pin, which is a card choice rather than an offload decision.+ "cpu_offload": bool(without_device_backend_flags(state.offload_flags)),+ "offload_policy": (+ "active" if without_device_backend_flags(state.offload_flags) else "none"+ ),"vae_tiling": False,"memory_mode": None,"speed_mode": state.native_speed,diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 3b65e6c3249..60fd1cca84b 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -59,9 +59,15 @@ from .diffusion_cache import (normalize_transformer_cache,)from .diffusion_device import (+ DiffusionDeviceTarget,+ apply_diffusion_device_ordinal,+ diffusion_device_scope,force_float32_rope,install_decoder_sync,+ pin_cuda_ordinal,+ placed_cuda_ordinal,resolve_diffusion_device_target,+ resolve_selected_cuda_ordinal,)from .diffusion_memory import (apply_memory_plan,@@ -196,6 +202,7 @@ def assert_video_precision_available(transformer_quant: Optional[str] = None,text_encoder_quant: Optional[str] = None,memory_mode: Optional[str] = None,+ gpu_ordinal: Optional[int] = None,) -> None:"""Raise ``RuntimeError`` (the route's 409) when an EXPLICIT precision cannot run here.@@ -213,8 +220,38 @@ def assert_video_precision_available(te_mode = normalize_te_quant(text_encoder_quant)if pinned is None and te_mode is None:return- # One probe for both checks (it reads the live device).- target = resolve_diffusion_device_target()+ # One probe for both checks, asked of the card THIS load will use: the default one can be a+ # different generation, refusing a scheme the selected card supports or passing one it cannot.+ # SCOPED around the probes below, which use argument-less CUDA calls and bare "cuda"+ # allocations, and which the route reaches on a pooled thread that must not keep the pin.+ with diffusion_device_scope(gpu_ordinal):+ target = (+ resolve_diffusion_device_target()+ if gpu_ordinal is None+ else resolve_diffusion_device_target(ordinal = gpu_ordinal)+ )+ _assert_video_precision_for_target(+ fam,+ target,+ model_kind = model_kind,+ transformer_quant = transformer_quant,+ text_encoder_quant = text_encoder_quant,+ memory_mode = memory_mode,+ )+++def _assert_video_precision_for_target(+ fam: Any,+ target: Any,+ *,+ model_kind: str,+ transformer_quant: Optional[str] = None,+ text_encoder_quant: Optional[str] = None,+ memory_mode: Optional[str] = None,+) -> None:+ """The body of ``assert_video_precision_available``, run with the selected card current."""+ pinned = normalize_transformer_quant(transformer_quant)+ te_mode = normalize_te_quant(text_encoder_quant)# A modular-workflow family (MiniMax-H3) never reaches the memory plan the offload refusals# below reason about: load_pipeline hands it to _load_h3_modular_pipeline, which always uses# the ComponentsManager auto CPU offload and PINS a pre-quantized denoiser resident, so@@ -467,6 +504,13 @@ class _VideoLoadState:dtype: strkind: strengine: str = "diffusers"+ # The torch ordinal this pipeline's weights were placed on, or None for an automatic pick.+ # Committed WITH the pipeline, so a load in flight never moves the resident model's card.+ gpu_ordinal: Optional[int] = None+ # The card the weights are ACTUALLY on, automatic loads included. Only for re-pinning a worker+ # that a previous pinned load may have left on another card; everything reported reads+ # gpu_ordinal, so an automatic load still resolves a bare device. Mirrors the image backend.+ placed_ordinal: Optional[int] = Nonegguf_filename: Optional[str] = None# Resident MiniMax-H3 denoiser partition, if any.h3_task: Optional[str] = None@@ -981,6 +1025,30 @@ class VideoBackend:# True from begin_generate() until its worker records a terminal state, so a second call is refused while it runs.self._generate_job_active = False+ def _device_target(self, ordinal: Optional[int] = None) -> DiffusionDeviceTarget:+ """The device target for ``ordinal``, pinned onto the calling thread.++ ``torch.cuda.set_device`` is thread-local, so this runs per worker rather than once at+ load: the daemon thread that builds the pipeline is not the one that denoises. Called with+ no argument on the automatic path, so a monkeypatched resolver keeps working.+ """+ if ordinal is None:+ return resolve_diffusion_device_target()+ target = resolve_diffusion_device_target(ordinal = ordinal)+ apply_diffusion_device_ordinal(target)+ return target++ def _state_device_target(self, state: _VideoLoadState) -> DiffusionDeviceTarget:+ """The resident pipeline's target, pinned onto the calling thread. Every worker that+ touches the loaded pipeline goes through this: the weights are on ``state.gpu_ordinal``+ and ``state.device`` is un-indexed, so an unpinned thread resolves to its own card."""+ target = self._device_target(state.gpu_ordinal)+ # And an automatic load back onto its own card, in case this thread is a shared one a+ # previous pinned load left elsewhere. The image path reaches this through a pooled+ # executor; here it costs one no-op call to keep the two engines identical.+ pin_cuda_ordinal(state.placed_ordinal)+ return target+# ── validation ───────────────────────────────────────────────────────────def validate_load_request(@@ -1217,9 +1285,25 @@ class VideoBackend:text_encoder_quant: Optional[str] = None,model_kind: Optional[str] = None,h3_task: Optional[str] = None,+ gpu_ids: Optional[list[int]] = None,+ # The ordinal the ROUTE already ranked, so the preflight and the load agree on one card.+ gpu_ordinal: Optional[int] = None,) -> dict[str, Any]:"""Validate, then run the (slow) load on a daemon thread. Returns at once."""hf_token = (hf_token.strip() if isinstance(hf_token, str) else hf_token) or None+ # Resolved ONCE, here, and carried to the worker: outside it so a bad pick is the route's+ # 400 rather than a load that dies tens of GB later, and only once so free VRAM cannot+ # re-rank the choice after the weights land. Gated on the resolved backend, since XPU /+ # MPS / CPU ignore physical ids and would otherwise 400 a selection the contract drops.+ # Re-ranked only when the caller did not already do it: free VRAM moves between the+ # route's preflight and here, so resolving twice can approve a scheme against one card+ # and place the weights on another.+ if gpu_ordinal is None:+ gpu_ordinal = (+ resolve_selected_cuda_ordinal(gpu_ids)+ if gpu_ids and resolve_diffusion_device_target().device == "cuda"+ else None+ )fam = self.validate_load_request(repo_id,gguf_filename = gguf_filename,@@ -1240,6 +1324,7 @@ class VideoBackend:model_kind = resolve_video_model_kind(gguf_filename, model_kind),transformer_quant = transformer_quant,text_encoder_quant = text_encoder_quant,+ gpu_ordinal = gpu_ordinal,)# Resolved out here so the companion claim is published in the SAME locked section as# _loading. begin_load returns as soon as the thread is scheduled, and a delete arriving in@@ -1282,6 +1367,7 @@ class VideoBackend:text_encoder_quant = text_encoder_quant,model_kind = model_kind,h3_task = h3_task,+ gpu_ordinal = gpu_ordinal,_load_token = token,_cancel_event = cancel_event,),@@ -1318,7 +1404,9 @@ class VideoBackend:)kwargs["base_repo"] = base# An fp8 encoder request loads a hosted pre-cast checkpoint, so neither the estimate nor the pull includes those dense shards.- te_sources = self._te_prequant_sources(fam, kwargs.get("text_encoder_quant"))+ te_sources = self._te_prequant_sources(+ fam, kwargs.get("text_encoder_quant"), kwargs.get("gpu_ordinal")+ )# The same deal for the denoiser: a hosted pre-quantized checkpoint replaces the dense# DiT shards, so the estimate and the scoped pull below both drop them. VERIFIED, like# the conditioner below and like the plan: this flag both REMOVES 66 GB from the pull@@ -1335,6 +1423,9 @@ class VideoBackend:text_encoder_quant = kwargs.get("text_encoder_quant"),speed_mode = kwargs.get("speed_mode"),h3_task = kwargs.get("h3_task"),+ # This decides the file set AND the memory policy, so it has to read the card the+ # pipeline will land on: the default one can be larger or smaller than the pick.+ gpu_ordinal = kwargs.get("gpu_ordinal"),)skip_transformer_weights = self._denoiser_prequant_verified(fam,@@ -1486,16 +1577,18 @@ class VideoBackend:gguf_filename: Optional[str] = None,hf_token: Optional[str] = None,memory_mode: Optional[str] = None,+ gpu_ordinal: Optional[int] = None,**_: Any,) -> None:"""Download and commit the four-file stable-diffusion.cpp H3 runtime."""from huggingface_hub import HfApi- from .sd_cpp_args import SdCppModelFiles, offload_flags+ from .sd_cpp_args import SdCppModelFiles, device_backend_flags, offload_flagsfrom .diffusion_engine_router import _install_accelerator_forfrom .sd_cpp_backend import (_install_allowed,ensure_h3_sd_cpp_binary,+ sd_cpp_device_name_for_ordinal,sd_cpp_lists_accelerator_device,)from .sd_cpp_engine import SdCppEngine@@ -1534,7 +1627,7 @@ class VideoBackend:# an install nobody is waiting for. The download loop used to be the first check.if cancel_event.is_set():raise RuntimeError(VIDEO_CANCELLED_MSG)- target = resolve_diffusion_device_target()+ target = self._device_target(gpu_ordinal)allow_install = _install_allowed()binary = ensure_h3_sd_cpp_binary(allow_install = allow_install,@@ -1713,6 +1806,15 @@ class VideoBackend:"again.")binary_identity = _sd_cli_identity(binary)+ # Dropped with the accelerator: the CPU fallback runs on no card, so a recorded ordinal+ # would outlive the decision and be committed against a runtime that never used it.+ native_ordinal = None if native_device == "cpu" else gpu_ordinal+ # Under the claim like every other probe here; None on the CPU fallback, which has no card to choose between.+ native_device_name = (+ None+ if native_device == "cpu"+ else sd_cpp_device_name_for_ordinal(binary, native_ordinal)+ )requested_mode = normalize_memory_mode(memory_mode) or "auto"policy = {"auto": "none" if native_device == "cpu" else "group",@@ -1742,6 +1844,8 @@ class VideoBackend:native_offload = tuple(offload_flags(policy, vae_tiling = False, diffusion_fa = True, vae_on_cpu = False))+ # After the policy, so the pin can see which modules it left on the CPU; without it sd.cpp uses ordinal 0 whatever was selected.+ native_offload += tuple(device_backend_flags(native_device_name, list(native_offload)))from .video_minimax_h3 import MiniMaxH3NativeRuntimeruntime = MiniMaxH3NativeRuntime(@@ -1777,6 +1881,10 @@ class VideoBackend:repo_id = repo_id,base_repo = fam.base_repo,device = native_device,+ gpu_ordinal = native_ordinal,+ # The native runtime is sd.cpp, not torch, so there is no thread-local+ # device to put back: the pin it honours is the --backend one.+ placed_ordinal = native_ordinal,dtype = Path(filename).stem.split("-")[-1],kind = "gguf",engine = "sd_cpp",@@ -1831,14 +1939,24 @@ class VideoBackend:_LTX23_BASE_PREFIXES = ("scheduler/", "text_encoder/", "tokenizer/")@staticmethod- def _te_prequant_sources(fam: Any, text_encoder_quant: Optional[str]) -> dict[str, Any]:+ def _te_prequant_sources(+ fam: Any,+ text_encoder_quant: Optional[str],+ gpu_ordinal: Optional[int] = None,+ ) -> dict[str, Any]:"""``{component: source}`` for the text encoders this load will take PRE-CAST from ahosted checkpoint instead of the base repo's dense weights (``{}`` when none)."""from .diffusion_te_prequant import te_prequant_sourcesreturn te_prequant_sources(fam,te_quant_mode = text_encoder_quant,- target = resolve_diffusion_device_target(),+ # The selected card: an fp8 encoder the default card cannot take is still hosted+ # pre-cast for the one this load lands on, and vice versa.+ target = (+ resolve_diffusion_device_target()+ if gpu_ordinal is None+ else resolve_diffusion_device_target(ordinal = gpu_ordinal)+ ),)@staticmethod@@ -1990,6 +2108,7 @@ class VideoBackend:text_encoder_quant: Optional[str],speed_mode: Optional[str],h3_task: Optional[str],+ gpu_ordinal: Optional[int] = None,) -> Optional[str]:"""The auto denoiser fallback, resolved BEFORE anything is downloaded, or None.@@ -2009,21 +2128,31 @@ class VideoBackend:return Noneimport torch- target = resolve_diffusion_device_target()- dtype = target.dtype- if getattr(fam, "fp16_incompatible", False) and dtype is torch.float16:- dtype = torch.float32- return _h3_auto_denoiser_scheme(- fam,- target = target,- dtype = dtype,- device = target.device,- te_scheme = self._h3_te_quant_scheme(fam, text_encoder_quant, base, target),- task = h3_task or getattr(fam, "modular_workflow", None),- base_repo = base,- speed_mode = speed_mode,- free_reader = _h3_device_capacity_bytes,- )+ # SCOPED, not pinned: the plan route reaches this on a pooled asyncio.to_thread+ # thread, which must not be handed back to the pool set to this request's card.+ # The WHOLE sizing call, not just the target: _h3_device_capacity_bytes and the+ # encoder-scheme probe read the current device, so a scope that closes early measures+ # the pooled thread's default card and stages the wrong denoiser.+ with diffusion_device_scope(gpu_ordinal):+ target = (+ resolve_diffusion_device_target()+ if gpu_ordinal is None+ else resolve_diffusion_device_target(ordinal = gpu_ordinal)+ )+ dtype = target.dtype+ if getattr(fam, "fp16_incompatible", False) and dtype is torch.float16:+ dtype = torch.float32+ return _h3_auto_denoiser_scheme(+ fam,+ target = target,+ dtype = dtype,+ device = target.device,+ te_scheme = self._h3_te_quant_scheme(fam, text_encoder_quant, base, target),+ task = h3_task or getattr(fam, "modular_workflow", None),+ base_repo = base,+ speed_mode = speed_mode,+ free_reader = _h3_device_capacity_bytes,+ )except Exception: # noqa: BLE001 -- an unanswerable probe keeps the dense shardsreturn None@@ -2459,6 +2588,8 @@ class VideoBackend:text_encoder_quant = text_encoder_quant,speed_mode = load_kwargs.get("speed_mode"),h3_task = h3_task,+ # Sizes the file set from device capacity, so it has to read the selected card.+ gpu_ordinal = load_kwargs.get("gpu_ordinal"),)or transformer_quant)@@ -2561,7 +2692,9 @@ class VideoBackend:revision = getattr(extras_info, "sha", None),)# Pre-cast encoders first: only a checkpoint that really resolves earns the right to drop the dense shards.- te_sources = self._te_prequant_sources(fam, text_encoder_quant)+ te_sources = self._te_prequant_sources(+ fam, text_encoder_quant, load_kwargs.get("gpu_ordinal")+ )te_files = self._te_prequant_hub_files(te_sources, api)for component, files in te_files.items():total += add(te_sources[component].location, files)@@ -3008,6 +3141,8 @@ class VideoBackend:text_encoder_quant: Optional[str] = None,model_kind: Optional[str] = None,h3_task: Optional[str] = None,+ # The torch ordinal begin_load resolved for this load, carried rather than re-derived.+ gpu_ordinal: Optional[int] = None,_load_token: Optional[int] = None,_base_local_dir: Optional[str] = None,_te_prequant_skipped: tuple[str, ...] = (),@@ -3073,7 +3208,7 @@ class VideoBackend:# Released here, not at the end of the load: the old pipe is gone (or this load bailed), and a raising teardown must not leave the fence up for the life of the process.self._teardown_waiters -= 1- target = resolve_diffusion_device_target()+ target = self._device_target(gpu_ordinal)device = target.device# Video DiTs are bf16-native; fp16 overflows, so a resolved fp16 promotes to float32. CPU stays float32.dtype = target.dtype@@ -3594,7 +3729,15 @@ class VideoBackend:del pipeclear_gpu_cache()raise RuntimeError("Video load was cancelled or superseded.")- offload_policy, vae_tiling = apply_memory_plan(pipe, plan, device = device, logger = logger)+ offload_policy, vae_tiling = apply_memory_plan(+ pipe,+ plan,+ device = device,+ # Same reason as the image path: a bare "cuda" sends the CPU-offload hooks to+ # ordinal 0 whatever was selected.+ placement_device = target.torch_device,+ logger = logger,+ )# A dual-DiT MoE needs no extra per-expert pass: apply_memory_plan covers every DiT; a second pass would duplicate-hook.if not vae_tiling:# Whole-clip decode is the video memory peak; tiling is near-free, so always on.@@ -3680,6 +3823,8 @@ class VideoBackend:repo_id = repo_id,base_repo = base,device = device,+ gpu_ordinal = target.ordinal,+ placed_ordinal = placed_cuda_ordinal(target),dtype = str(dtype).replace("torch.", ""),kind = kind,gguf_filename = gguf_filename,@@ -3807,7 +3952,7 @@ class VideoBackend:# directly, and by the time it runs the resident pipeline has already been torn down.if kind != "pipeline":raise ValueError("MiniMax-H3 Diffusers loading requires the pipeline artifact.")- umem_target = target if target is not None else resolve_diffusion_device_target()+ umem_target = target if target is not None else self._device_target()# What the CALLER asked for, kept for the resolved record, before the tri-state below# rewrites it. An unset request must not read back as a pin.transformer_quant_requested = transformer_quant@@ -4412,6 +4557,8 @@ class VideoBackend:repo_id = repo_id,base_repo = base,device = device,+ gpu_ordinal = umem_target.ordinal,+ placed_ordinal = placed_cuda_ordinal(umem_target),dtype = str(dtype).replace("torch.", ""),kind = kind,engine = "diffusers",@@ -4762,6 +4909,11 @@ class VideoBackend:# resolution, and there is nothing truthful to report.request_shape: Optional[dict[str, Any]] = Nonetry:+ # FIRST, before any device object exists. begin_generate runs this on a fresh+ # daemon thread, so until it is pinned the un-indexed state.device below -- the H3+ # memory probe and every torch.Generator -- resolves to its own default card while+ # the pipeline sits on the selected one.+ self._state_device_target(state)fam = state.familyfirst_pil, last_pil, width, height, conditioning = self._resolve_keyframes(fam, state.h3_task, first_frame, last_frame, width, heightdiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 65353dccfcb..d70ecb5236b 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2648,6 +2648,13 @@ class DiffusionLoadRequest(BaseModel):"quality). null auto-picks 0.08 (0.12 when the transformer is quantised, which ""shifts the residual distribution).",)+ gpu_ids: Optional[List[int]] = Field(+ None,+ description = "CUDA / ROCm physical indices this load may use, or null for automatic. "+ "Neither engine shards a diffusion checkpoint, so a selection of several cards resolves "+ "to the one with the most free VRAM. Refused with a 400 when an index does not exist "+ "here; ignored on XPU / MPS / CPU, which have no applicator for a physical index.",+ )@field_validator("attention_backend", mode = "before")@classmethod@@ -3428,6 +3435,14 @@ class VideoLoadRequest(BaseModel):"separate ~62 GB partitions, so a load serves one of them. Ignored for a GGUF pick, ""whose filename already names the partition; rejected if it contradicts that filename.",)+ gpu_ids: Optional[List[int]] = Field(+ None,+ description = "CUDA / ROCm physical indices this load may use, or null for automatic. "+ "Neither engine shards a video checkpoint, so a selection of several cards resolves to "+ "the one with the most free VRAM. Refused with a 400 when an index does not exist here; "+ "ignored on XPU / MPS / CPU, which have no applicator for a physical index. Mirrors the "+ "image backend's field.",+ )@field_validator("attention_backend", mode = "before")@classmethoddiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 16c0c5debb8..d1a22bb2a75 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -22430,6 +22430,36 @@ def _guard_diffusion_load_against_training() -> None:)+async def _selected_gpu_ordinal(gpu_ids, *, allow_ranking: bool = True) -> Optional[int]:+ """The torch ordinal for a request's ``gpu_ids``, or None when there is nothing to honour.++ Physical ids have no applicator off CUDA / ROCm, which the contract says to ignore rather than+ refuse, so the resolver only runs once the target reports a CUDA device. Raises ValueError for+ a bad pick, which every caller maps to a 400.++ ``allow_ranking = False`` drops only the free-VRAM comparison, for the plan routes while a+ trainer holds the cards: the ids are still validated and translated (mask plus nvidia-smi, no+ CUDA context), so a bad pick is refused at the plan rather than tens of gigabytes later.+ """+ from core.inference.diffusion_device import (+ resolve_diffusion_device_target,+ resolve_selected_cuda_ordinal,+ )++ if not gpu_ids:+ return None+ device = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)+ if device != "cuda":+ return None+ # The keyword only when it is not the default, so the ordinary path calls the resolver with+ # the same one-argument shape it always had (a monkeypatched seam still fits it).+ if allow_ranking:+ return await asyncio.to_thread(resolve_selected_cuda_ordinal, gpu_ids)+ return await asyncio.to_thread(+ lambda: resolve_selected_cuda_ordinal(gpu_ids, allow_ranking = False)+ )++@studio_router.post("/images/download-plan", response_model = DiffusionDownloadPlanResponse)async def diffusion_download_plan(request: DiffusionLoadRequest, current_subject: str = Depends(get_current_subject)@@ -22481,7 +22511,16 @@ async def diffusion_download_plan(# guard exists to prevent, and the plan runs BEFORE that guard has had a say. Staging# files during training is legitimate and needs no GPU, so the plan is answered without# the precision check; /images/load still refuses the same pick afterwards.- if fam is not None and not await asyncio.to_thread(_training_is_active):+ # Ranking reads free VRAM per candidate, which opens a CUDA context on each: exactly what+ # the training guard below exists to prevent, so the RANKING waits until training is known+ # idle. The ids are validated and translated either way -- that costs no CUDA context, and+ # skipping it entirely let the plan accept a GPU the load would refuse, and size its file+ # set for the wrong card. ONE resolution for the whole request, reused by preflight + plan.+ gpu_ordinal = None+ training = fam is not None and await asyncio.to_thread(_training_is_active)+ if fam is not None:+ gpu_ordinal = await _selected_gpu_ordinal(request.gpu_ids, allow_ranking = not training)+ if fam is not None and not training:if planner is backend:await asyncio.to_thread(backend.assert_precision_available,@@ -22493,6 +22532,8 @@ async def diffusion_download_plan(# anything is measured, and an offloaded transformer skips the dense quant.memory_mode = getattr(request, "memory_mode", None),cpu_offload = bool(getattr(request, "cpu_offload", False)),+ # Judged on the card this pick would load on, as the loader does.+ gpu_ordinal = gpu_ordinal,)else:_assert_native_precision_unset(@@ -22502,6 +22543,7 @@ async def diffusion_download_plan(plan = await asyncio.to_thread(planner.download_plan,request.model_path,+ gpu_ordinal = gpu_ordinal,gguf_filename = request.gguf_filename,base_repo = request.base_repo,family_override = request.family_override,@@ -22572,7 +22614,10 @@ async def load_diffusion_model(resolve_local_single_file,resolve_model_kind,)- from core.inference.diffusion_device import resolve_diffusion_device_target+ from core.inference.diffusion_device import (+ resolve_diffusion_device_target,+ resolve_selected_cuda_ordinal,+ )from core.inference.diffusion_engine_router import (active_engine_name,annotate_status,@@ -22610,6 +22655,10 @@ async def load_diffusion_model(# Pure resolve, so it can run before selection, which the refusal below has to precede.device = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)needs_gpu = device != "cpu"+ # Refuse a bad pick before anything is evicted or staged; begin_load re-checks, but only+ # after the arbiter has taken the GPU. Only on CUDA / ROCm: physical ids have no applicator+ # on XPU / MPS / CPU, which the request contract says to ignore rather than 400.+ gpu_ordinal = await _selected_gpu_ordinal(request.gpu_ids)def _preflight(target):# Gated/unreadable-companion refusal, asked of ONE engine (they check different repos).@@ -22647,6 +22696,7 @@ async def load_diffusion_model(text_encoder_quant = request.text_encoder_quant,memory_mode = getattr(request, "memory_mode", None),cpu_offload = bool(getattr(request, "cpu_offload", False)),+ gpu_ordinal = gpu_ordinal,)elif fam is not None and pending_name == ENGINE_SD_CPP:# The native engine accepts both knobs for interface parity and ignores them. It was@@ -22696,6 +22746,7 @@ async def load_diffusion_model(text_encoder_quant = request.text_encoder_quant,memory_mode = getattr(request, "memory_mode", None),cpu_offload = bool(getattr(request, "cpu_offload", False)),+ gpu_ordinal = gpu_ordinal,)def _start_engine_load():@@ -22718,6 +22769,10 @@ async def load_diffusion_model(transformer_cache_threshold = request.transformer_cache_threshold,model_kind = kind,loras = [(s.id, s.weight) for s in request.loras] if request.loras else None,+ gpu_ids = request.gpu_ids,+ # The winner this route already ranked and preflighted, so the load cannot pick a+ # different card from free VRAM that has moved since.+ gpu_ordinal = gpu_ordinal,)def _begin_load():diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex 9e55083392b..1c3615cd89d 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -47,6 +47,12 @@ logger = get_logger(__name__)router = APIRouter()+def _selected_gpu_ordinal(gpu_ids, *, allow_ranking: bool = True):+ """The images route's resolver, shared so both media routes apply one rule."""+ from routes.inference import _selected_gpu_ordinal as _resolve+ return _resolve(gpu_ids, allow_ranking = allow_ranking)++def _training_is_active() -> bool:"""The non-raising half of the load guard, for callers that must not take the GPU."""from routes.inference import _training_is_active as _images_training_is_active@@ -132,7 +138,16 @@ async def video_download_plan(# Skipped while a trainer holds the GPU: an uncached scheme takes this into a# quantise-and-matmul smoke probe that initialises CUDA in the Studio process, and the# plan runs before the load's training guard can refuse. Staging needs no GPU.- if fam is not None and not await asyncio.to_thread(_training_is_active):+ # Ranking opens a CUDA context per candidate, which the training guard exists to prevent,+ # so the RANKING waits until training is known idle. Validating and translating the ids+ # does not, so that happens either way: a plan that skipped it accepted a GPU the load+ # would refuse and sized its file set for the wrong card. ONE resolution, reused by+ # preflight and plan.+ gpu_ordinal = None+ training = fam is not None and await asyncio.to_thread(_training_is_active)+ if fam is not None:+ gpu_ordinal = await _selected_gpu_ordinal(request.gpu_ids, allow_ranking = not training)+ if fam is not None and not training:await asyncio.to_thread(assert_video_precision_available,fam,@@ -140,10 +155,13 @@ async def video_download_plan(transformer_quant = request.transformer_quant,text_encoder_quant = request.text_encoder_quant,memory_mode = request.memory_mode,+ # Judged on the card this pick would load on, as the loader does.+ gpu_ordinal = gpu_ordinal,)plan = await asyncio.to_thread(backend.download_plan,request.model_path,+ gpu_ordinal = gpu_ordinal,gguf_filename = request.gguf_filename,base_repo = request.base_repo,family_override = request.family_override,@@ -174,7 +192,10 @@ async def load_video_model(request: VideoLoadRequest, current_subject: str = Depends(get_current_subject)):from core.inference.diffusion import resolve_local_single_file- from core.inference.diffusion_device import resolve_diffusion_device_target+ from core.inference.diffusion_device import (+ resolve_diffusion_device_target,+ resolve_selected_cuda_ordinal,+ )from core.inference.gpu_arbiter import VIDEO, acquire_for, releasefrom core.inference.video import (assert_video_precision_available,@@ -215,6 +236,10 @@ async def load_video_model(# arbiter lock BEFORE the register callback -- so a refusal raised there arrives having# already taken the GPU away from the model it was meant to preserve. `auto` is never# refused, so a caller that left the precision to the backend cannot reach this.+ # Ahead of the precision gate, which has to judge the card this pick would load on.+ # Refused here too, before anything is evicted or staged; begin_load re-checks, but only+ # after the arbiter has taken the GPU.+ gpu_ordinal = await _selected_gpu_ordinal(request.gpu_ids)await asyncio.to_thread(assert_video_precision_available,fam,@@ -224,6 +249,7 @@ async def load_video_model(# The memory request settles the offload policy for balanced/low_vram before# anything is measured, and an offloaded DiT or encoder skips the torchao build.memory_mode = request.memory_mode,+ gpu_ordinal = gpu_ordinal,)# Take the GPU from chat only for a non-CPU load. Release stale VIDEO ownership on a CPU load (owner-guarded no-op).device = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)@@ -245,6 +271,10 @@ async def load_video_model(text_encoder_quant = request.text_encoder_quant,model_kind = kind,h3_task = request.h3_task,+ gpu_ids = request.gpu_ids,+ # The winner this route already ranked and preflighted, so the load cannot pick a+ # different card from free VRAM that has moved since.+ gpu_ordinal = gpu_ordinal,)if device != "cpu":diff --git a/studio/backend/tests/test_diffusion_device.py b/studio/backend/tests/test_diffusion_device.pyindex 1c5c503559b..0848ba6bb06 100644--- a/studio/backend/tests/test_diffusion_device.py+++ b/studio/backend/tests/test_diffusion_device.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport sysimport types+from typing import Optionalimport pytest@@ -73,14 +74,25 @@ def _make_torch(mps_probe: str = "pass", # "pass" | "raise" | "nonfinite"xpu_available = None, # None -> no xpu attr; True/False -> presentxpu_bf16: bool = False,+ device_count: int = 1,+ # Free VRAM per physical index, for the multi-card pick. Absent -> 0.+ free_vram_by_index: Optional[dict] = None,+ # Records every torch.cuda.set_device() this fake receives, so a test can assert the pin.+ set_device_calls: Optional[list] = None,) -> types.ModuleType:torch = types.ModuleType("torch")torch.bfloat16 = BF16torch.float16 = FP16torch.float32 = FP32torch.version = types.SimpleNamespace(hip = hip)+ free_vram_by_index = free_vram_by_index or {}- def _get_cap():+ def _set_device(index):+ if set_device_calls is not None:+ set_device_calls.append(index)++ # Same optional-device signature as torch's own, so a probe of a SELECTED card is answered rather than raising.+ def _get_cap(device = None):if capability_raises:raise RuntimeError("no capability")return capability@@ -89,6 +101,9 @@ def _make_torch(is_available = lambda: cuda_available,get_device_capability = _get_cap,is_bf16_supported = lambda: bf16_supported,+ device_count = lambda: device_count,+ mem_get_info = lambda index = None: (free_vram_by_index.get(index, 0), 0),+ set_device = _set_device,)mps_ns = types.SimpleNamespace(is_available = lambda: mps_available)@@ -629,3 +644,319 @@ def test_decoder_sync_survives_a_synchronize_that_raises(monkeypatch):decoder = _FakeDecoder()assert dd.install_decoder_sync(_pipe_with(decoder), _target("mps")) is Trueassert decoder.decode(2) == ["out0", "out1"]+++# ── GPU selection ─────────────────────────────────────────────────────+++def _mask(+ monkeypatch,+ visible,+ *,+ physical_count = None,+):+ """Stub the hardware layer's parent-visible view, the mask `gpu_ids` is expressed against."""+ import utils.hardware.hardware as hw++ monkeypatch.setattr(+ hw,+ "_get_parent_visible_gpu_spec",+ lambda: {"raw": None, "numeric_ids": list(visible), "supports_explicit_gpu_ids": True},+ )+ monkeypatch.setattr(+ hw, "get_physical_gpu_count", lambda: physical_count or (max(visible) + 1 if visible else 0)+ )+++def test_no_selection_leaves_the_target_on_the_default_device(monkeypatch):+ # The automatic pick must stay byte-for-byte what it was: no index, nothing pinned.+ calls: list = []+ torch = _make_torch(cuda_available = True, capability = (8, 0), set_device_calls = calls)+ _install(monkeypatch, torch, studio_device = "cuda")+ t = dd.resolve_diffusion_device_target()+ assert t.ordinal is None+ assert t.torch_device == "cuda"+ dd.apply_diffusion_device_ordinal(t)+ assert calls == []+++def test_a_single_card_pick_is_honoured_exactly(monkeypatch):+ calls: list = []+ torch = _make_torch(+ cuda_available = True, capability = (8, 0), device_count = 2, set_device_calls = calls+ )+ _install(monkeypatch, torch, studio_device = "cuda")+ _mask(monkeypatch, [0, 1])+ t = dd.resolve_diffusion_device_target(ordinal = dd.resolve_selected_cuda_ordinal([1]))+ assert t.ordinal == 1+ # The device string stays BARE: is_cuda / memory / speed / attention all compare it by value.+ assert t.device == "cuda"+ assert t.is_cuda_torch_device is True+ assert t.torch_device == "cuda:1"+ dd.apply_diffusion_device_ordinal(t)+ assert calls == [1]+++def test_physical_ids_are_translated_through_the_visibility_mask(monkeypatch):+ # CUDA_VISIBLE_DEVICES=4,5: physical 4 and 5 are the valid picks and torch sees 0 and 1.+ # Validating against torch.cuda.device_count() would reject both.+ torch = _make_torch(cuda_available = True, capability = (8, 0), device_count = 2)+ _install(monkeypatch, torch, studio_device = "cuda")+ _mask(monkeypatch, [4, 5], physical_count = 8)+ assert dd.resolve_selected_cuda_ordinal([4]) == 0+ assert dd.resolve_selected_cuda_ordinal([5]) == 1+ with pytest.raises(ValueError):+ dd.resolve_selected_cuda_ordinal([0])++ # A REORDERED mask: physical 1 is torch ordinal 0, so the order matters, not just membership.+ _mask(monkeypatch, [1, 0], physical_count = 2)+ assert dd.resolve_selected_cuda_ordinal([1]) == 0+ assert dd.resolve_selected_cuda_ordinal([0]) == 1+++def test_several_cards_resolve_to_the_one_with_the_most_free_vram(monkeypatch):+ # The mixed box this exists for: ordinal 0 is the SMALL card, so taking the first id lands on the GPU that cannot hold the checkpoint.+ torch = _make_torch(+ cuda_available = True,+ capability = (8, 0),+ device_count = 2,+ free_vram_by_index = {0: 6 * 1024**3, 1: 15 * 1024**3},+ )+ _install(monkeypatch, torch, studio_device = "cuda")+ _mask(monkeypatch, [0, 1])+ assert dd.resolve_selected_cuda_ordinal([0, 1]) == 1++ # Equal cards take the lowest ordinal, so the same selection always resolves the same way.+ torch.cuda.mem_get_info = lambda index = None: (8 * 1024**3, 0)+ assert dd.resolve_selected_cuda_ordinal([0, 1]) == 0+++def test_free_vram_is_read_on_the_torch_ordinal_not_the_physical_id(monkeypatch):+ # Under a mask the two differ, and querying the physical id would rank the wrong cards.+ seen: list = []+ torch = _make_torch(cuda_available = True, capability = (8, 0), device_count = 2)+ torch.cuda.mem_get_info = lambda index = None: (seen.append(index), 1 << 30)[1:]+ _install(monkeypatch, torch, studio_device = "cuda")+ _mask(monkeypatch, [4, 5], physical_count = 8)+ dd.resolve_selected_cuda_ordinal([4, 5])+ assert seen == [0, 1]+++def test_an_unreadable_card_sorts_last_rather_than_failing_the_load(monkeypatch):+ torch = _make_torch(+ cuda_available = True,+ capability = (8, 0),+ device_count = 3,+ free_vram_by_index = {2: 4 * 1024**3},+ )+ _install(monkeypatch, torch, studio_device = "cuda")+ _mask(monkeypatch, [0, 1, 2])+ assert dd.resolve_selected_cuda_ordinal([0, 2]) == 2+ # Nothing readable at all: a stable answer, not an exception.+ assert dd.resolve_selected_cuda_ordinal([0, 1]) == 0+++def test_an_index_this_host_does_not_have_is_refused(monkeypatch):+ torch = _make_torch(cuda_available = True, capability = (8, 0), device_count = 2)+ _install(monkeypatch, torch, studio_device = "cuda")+ _mask(monkeypatch, [0, 1])+ with pytest.raises(ValueError):+ dd.resolve_selected_cuda_ordinal([5])+ with pytest.raises(ValueError):+ dd.resolve_selected_cuda_ordinal([-1])+ # Empty and None are "automatic", never a refusal.+ assert dd.resolve_selected_cuda_ordinal([]) is None+ assert dd.resolve_selected_cuda_ordinal(None) is None+++def test_the_capability_probe_asks_about_the_selected_card(monkeypatch):+ # Ordinal 0 is pre-Ampere and ordinal 1 is not, so an index-less probe picks the wrong dtype.+ torch = _make_torch(cuda_available = True, device_count = 2)+ seen: list = []+ _NOTHING = object()++ def _cap(device = _NOTHING):+ seen.append(device)+ return (7, 5) if device in (_NOTHING, 0) else (8, 9)++ torch.cuda.get_device_capability = _cap+ _install(monkeypatch, torch, studio_device = "cuda")+ assert dd.resolve_diffusion_device_target(ordinal = 1).dtype == BF16+ assert seen == [1]++ # No selection probes with NO argument: a stub or older build that takes none would+ # otherwise raise into the fp16 fallback.+ seen.clear()+ assert dd.resolve_diffusion_device_target().dtype == FP16+ assert seen == [_NOTHING]+++def test_an_indexed_override_string_keeps_its_card(monkeypatch):+ # _pick_device_and_dtype hands back the indexed string; rebuilding must not drop to ordinal 0.+ torch = _make_torch(cuda_available = True, capability = (8, 0))+ _install(monkeypatch, torch, studio_device = "cuda")+ t = dd.diffusion_device_target_from_torch_device("cuda:1", BF16)+ assert (t.device, t.ordinal, t.torch_device) == ("cuda", 1, "cuda:1")+ assert dd.diffusion_device_target_from_torch_device("cuda", BF16).ordinal is None+++def test_a_selection_is_ignored_where_physical_indices_mean_nothing(monkeypatch):+ # MPS has one device and no applicator for an index; the pick must not become a refusal.+ torch = _make_torch(mps_available = True)+ _install(monkeypatch, torch, studio_device = "mlx")+ assert dd.resolve_diffusion_device_target(ordinal = 1).ordinal is None+++def test_the_device_scope_restores_the_previous_card(monkeypatch):+ # Route preflights run on a pooled executor, so a pin left set there is inherited by the+ # NEXT request on that thread, including an automatic one.+ calls: list = []+ torch = _make_torch(cuda_available = True, device_count = 2, set_device_calls = calls)++ class _Scope:+ def __init__(self, index):+ calls.append(("enter", index))++ def __enter__(self):+ return self++ def __exit__(self, *_exc):+ calls.append(("exit", None))+ return False++ torch.cuda.device = _Scope+ monkeypatch.setitem(sys.modules, "torch", torch)+ with dd.diffusion_device_scope(1):+ pass+ assert calls == [("enter", 1), ("exit", None)]++ # No selection is a plain no-op, so the automatic path never touches the current device.+ calls.clear()+ with dd.diffusion_device_scope(None):+ pass+ assert calls == []+++def test_the_rocm_bf16_probe_asks_about_the_selected_card(monkeypatch):+ # is_bf16_supported() takes no device argument, so asking about the selected card means+ # making it current; otherwise a bf16-capable pick behind an older default goes to fp32.+ torch = _make_torch(cuda_available = True, hip = "6.0", device_count = 2)+ scoped: list = []++ class _Scope:+ def __init__(self, index):+ scoped.append(index)++ def __enter__(self):+ return self++ def __exit__(self, *_exc):+ return False++ torch.cuda.device = _Scope+ torch.cuda.is_bf16_supported = lambda: bool(scoped and scoped[-1] == 1)+ _install(monkeypatch, torch, studio_device = "cuda", is_rocm = True)+ assert dd.resolve_diffusion_device_target(ordinal = 1).dtype == BF16+ assert scoped == [1]+++def test_the_device_scope_lets_the_body_exception_through(monkeypatch):+ # Catching around the yield made contextlib raise "generator didn't stop after throw()",+ # replacing a precision refusal with an error the route maps to the wrong status.+ torch = _make_torch(cuda_available = True, device_count = 2)++ class _Scope:+ def __init__(self, index):+ pass++ def __enter__(self):+ return self++ def __exit__(self, *_exc):+ return False++ torch.cuda.device = _Scope+ monkeypatch.setitem(sys.modules, "torch", torch)+ with pytest.raises(RuntimeError, match = "the real refusal"):+ with dd.diffusion_device_scope(1):+ raise RuntimeError("the real refusal")+++def test_the_device_scope_still_runs_the_body_on_an_unusable_index(monkeypatch):+ # Entering may fail on a stale index; the probe then runs unpinned rather than not at all.+ torch = _make_torch(cuda_available = True, device_count = 2)++ def _boom(_index):+ raise RuntimeError("invalid device ordinal")++ torch.cuda.device = _boom+ monkeypatch.setitem(sys.modules, "torch", torch)+ ran = []+ with dd.diffusion_device_scope(9):+ ran.append(True)+ assert ran == [True]+++def test_the_placed_ordinal_records_the_card_an_automatic_load_used(monkeypatch):+ # /images/generate runs on a pooled worker, so a pinned load leaves that thread on its card+ # for good and a later automatic load has no ordinal to re-pin with. The card it landed on is+ # recorded separately and puts the worker back.+ current = [3]+ torch = _make_torch(cuda_available = True, device_count = 4)+ torch.cuda.current_device = lambda: current[0]+ torch.cuda.set_device = lambda index: current.__setitem__(0, index)+ monkeypatch.setitem(sys.modules, "torch", torch)+ _install(monkeypatch, torch, studio_device = "cuda")++ automatic = dd.resolve_diffusion_device_target()+ assert automatic.ordinal is None # the target itself stays un-indexed+ assert dd.placed_cuda_ordinal(automatic) == 3 # but the card is known++ selected = dd.resolve_diffusion_device_target(ordinal = 1)+ assert dd.placed_cuda_ordinal(selected) == 1 # a selection needs no observation++ # Nothing to record off CUDA: there is no thread-local device to put back.+ cpu_torch = _make_torch(cuda_available = False)+ monkeypatch.setitem(sys.modules, "torch", cpu_torch)+ _install(monkeypatch, cpu_torch, studio_device = "cpu")+ assert dd.placed_cuda_ordinal(dd.resolve_diffusion_device_target()) is None+++def test_pinning_an_automatic_load_puts_a_shared_worker_back(monkeypatch):+ current = [0]+ torch = _make_torch(cuda_available = True, device_count = 4)+ torch.cuda.current_device = lambda: current[0]+ torch.cuda.set_device = lambda index: current.__setitem__(0, index)+ monkeypatch.setitem(sys.modules, "torch", torch)+ _install(monkeypatch, torch, studio_device = "cuda")++ # A pinned load runs here first and leaves the thread on its card.+ dd.apply_diffusion_device_ordinal(dd.resolve_diffusion_device_target(ordinal = 2))+ assert current == [2]+ # The next model loaded automatically; its weights are on 0, so the worker goes back to 0.+ dd.pin_cuda_ordinal(0)+ assert current == [0]+ # And a None never moves anything.+ dd.pin_cuda_ordinal(None)+ assert current == [0]+++def test_a_multi_card_pick_declines_to_rank_when_ranking_is_barred(monkeypatch):+ # The plan routes must not open a CUDA context while a trainer holds the cards; validating+ # and translating the ids costs none, so a bad pick is still refused at the plan.+ torch = _make_torch(cuda_available = True, device_count = 4, free_vram_by_index = {0: 1, 1: 2})+ probed: list = []+ torch.cuda.mem_get_info = lambda index = None: (probed.append(index), (1, 2))[1]+ monkeypatch.setitem(sys.modules, "torch", torch)+ _install(monkeypatch, torch, studio_device = "cuda")+ import utils.hardware.hardware as hw++ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: [0, 1, 2, 3])+ monkeypatch.setattr(hw, "get_physical_gpu_count", lambda: 4)++ assert dd.resolve_selected_cuda_ordinal([2], allow_ranking = False) == 2+ assert probed == [] # no free-VRAM probe, so no CUDA context+ assert dd.resolve_selected_cuda_ordinal([0, 1], allow_ranking = False) is None+ assert probed == []+ with pytest.raises(ValueError):+ dd.resolve_selected_cuda_ordinal([9], allow_ranking = False)diff --git a/studio/backend/tests/test_diffusion_memory.py b/studio/backend/tests/test_diffusion_memory.pyindex a5fb6d5bd2f..a15070db232 100644--- a/studio/backend/tests/test_diffusion_memory.py+++ b/studio/backend/tests/test_diffusion_memory.py@@ -1812,3 +1812,41 @@ def test_the_batch_remedy_appears_only_when_a_batch_was_budgeted():assert batched is not Noneassert "at a batch of 4" in batchedassert "or a smaller batch size" in batched+++def test_cpu_offload_hooks_take_the_indexed_card_not_a_bare_cuda():+ # diffusers reads the index off this device and, finding none, falls back to _offload_gpu_id 0+ # and onloads to cuda:0 (pipeline_utils.py, 0.39). A load pinned elsewhere generates there, so+ # the modules would page onto the wrong GPU: a cross-device failure, or the small card filling.+ for build, policy, call in (+ (_plan, OFFLOAD_MODEL, "model_offload"),+ (_manual_plan, OFFLOAD_SEQUENTIAL, "sequential_offload"),+ ):+ pipe = _RecordingPipe()+ apply_memory_plan(+ pipe, build(policy, tiling = False), device = "cuda", placement_device = "cuda:1"+ )+ assert call in pipe.calls+ assert pipe.offload_device == "cuda:1"+++def test_the_resident_placement_follows_the_selected_card_too():+ pipe = _RecordingPipe()+ apply_memory_plan(+ pipe, _plan(OFFLOAD_NONE, tiling = False), device = "cuda", placement_device = "cuda:1"+ )+ assert pipe.calls == ["to:cuda:1"]+++def test_an_automatic_load_still_hands_over_a_bare_device():+ # No selection: every call receives exactly the string it did before, resolved against the+ # current device as always.+ for policy, expected in (+ (OFFLOAD_NONE, ["to:cuda"]),+ (OFFLOAD_MODEL, ["model_offload"]),+ ):+ pipe = _RecordingPipe()+ apply_memory_plan(pipe, _plan(policy, tiling = False), device = "cuda")+ assert expected[0] in pipe.calls+ if policy is OFFLOAD_MODEL:+ assert pipe.offload_device == "cuda"diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.pyindex 95a19bda228..dbf6e3e158b 100644--- a/studio/backend/tests/test_diffusion_routes.py+++ b/studio/backend/tests/test_diffusion_routes.py@@ -1214,6 +1214,86 @@ def test_gpu_native_load_takes_arbiter(client, monkeypatch):assert acquired == [gpu_arbiter.DIFFUSION]+def test_load_forwards_the_gpu_selection(client, monkeypatch):+ # The bug this fixes: the UI's card pick reached chat and training but never the image load,+ # so both engines pinned every module to ordinal 0 whatever was selected.+ backend = diffusion_module.get_diffusion_backend()+ _force_engine(monkeypatch, backend, engine_name = "diffusers", device = "cuda")+ import core.inference.diffusion_device as devmod++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", lambda ids: max(ids))+ resp = client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "x/z-image",+ "gguf_filename": "q.gguf",+ "gpu_ids": [1],+ },+ )+ assert resp.status_code == 200+ assert backend.last_load_kwargs["gpu_ids"] == [1]+++def test_load_refuses_a_gpu_index_this_host_does_not_have(client, monkeypatch):+ # Refused BEFORE the arbiter evicts chat, so a bad pick costs a resident model nothing.+ backend = diffusion_module.get_diffusion_backend()+ acquired = _force_engine(monkeypatch, backend, engine_name = "diffusers", device = "cuda")+ import core.inference.diffusion_device as devmod++ def _refuse(_ids):+ raise ValueError("Requested GPU [7] but this host has 2 CUDA device(s).")++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", _refuse)+ resp = client.post(+ "/api/inference/images/load",+ json = {"model_path": "x/z-image", "gguf_filename": "q.gguf", "gpu_ids": [7]},+ )+ assert resp.status_code == 400+ assert "2 CUDA device" in resp.json()["detail"]+ assert acquired == []+++def test_load_ignores_a_gpu_selection_off_cuda(client, monkeypatch):+ # The request contract says physical ids are dropped on XPU / MPS / CPU, so validating them+ # there turned a documented no-op into a 400.+ backend = diffusion_module.get_diffusion_backend()+ _force_engine(monkeypatch, backend, engine_name = "diffusers", device = "mps")+ import core.inference.diffusion_device as devmod++ def _never(_ids):+ raise AssertionError("the CUDA resolver must not run off a CUDA target")++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", _never)+ resp = client.post(+ "/api/inference/images/load",+ json = {"model_path": "x/z-image", "gguf_filename": "q.gguf", "gpu_ids": [1]},+ )+ assert resp.status_code == 200+++def test_native_load_accepts_the_resolved_ordinal(client, monkeypatch):+ # The route passes gpu_ordinal to whichever engine it activated, so the native backend has to+ # take it: an unexpected-keyword TypeError here 500s every native GGUF load.+ import inspect++ from core.inference.sd_cpp_backend import SdCppDiffusionBackend++ assert "gpu_ordinal" in inspect.signature(SdCppDiffusionBackend.begin_load).parameters++ from core.inference.sd_cpp_engine import ENGINE_SD_CPP++ backend = diffusion_module.get_diffusion_backend()+ _force_engine(monkeypatch, backend, engine_name = ENGINE_SD_CPP, device = "cuda")+ import core.inference.diffusion_device as devmod++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", lambda ids: max(ids))+ resp = client.post(+ "/api/inference/images/load",+ json = {"model_path": "x/z-image", "gguf_filename": "q.gguf", "gpu_ids": [1]},+ )+ assert resp.status_code == 200++def test_images_info_lists_every_family(client):# The pure info endpoint is hardware-independent: one entry per auto-policy family with the quant estimates the UI shows.from core.inference.diffusion_auto_policy import _FAMILY_BF16_GB@@ -2143,3 +2223,169 @@ def test_layerwise_fp8_does_not_need_torchao(monkeypatch):backend.assert_precision_available(types.SimpleNamespace(name = "qwen-image"), model_kind = "gguf", text_encoder_quant = "fp8")+++def test_download_plan_sizes_its_file_set_for_the_selected_card(client, monkeypatch):+ # The plan sizes the dense/prequant file set against a card's capability and free VRAM, so a+ # plan built for the default GPU stages the wrong files. One ranking per request, reused.+ import types as _types++ from core.inference import diffusion_device as devmod+ from core.inference import diffusion_engine_router as router+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS++ monkeypatch.setattr(router, "predict_engine", lambda fam, **_: ENGINE_DIFFUSERS)+ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: _types.SimpleNamespace(device = "cuda")+ )+ ranked: list = []++ def _resolve(ids):+ ranked.append(list(ids))+ return 1++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", _resolve)+ backend = diffusion_module.get_diffusion_backend()+ seen: dict = {}++ def _plan(model_path, **kwargs):+ seen.update(kwargs)+ return {"entries": [], "total_bytes": 0}++ monkeypatch.setattr(backend, "download_plan", _plan, raising = False)+ resp = client.post(+ "/api/inference/images/download-plan",+ json = {+ "model_path": "unsloth/FLUX.1-dev-GGUF",+ "gguf_filename": "flux1-dev-Q4_K_M.gguf",+ "model_kind": "gguf",+ "gpu_ids": [0, 1],+ },+ )+ assert resp.status_code == 200+ assert seen["gpu_ordinal"] == 1+ assert backend.last_precision_kwargs["gpu_ordinal"] == 1+ # ONE ranking: the preflight's smoke probe allocates on the card it tests, so a second could+ # answer with a different card than the plan was sized for.+ assert ranked == [[0, 1]]+++def test_download_plan_refuses_a_gpu_index_this_host_does_not_have(client, monkeypatch):+ # A bad pick is a 400, not a 500: this call sits inside the plan route's own try/except.+ import types as _types++ from core.inference import diffusion_device as devmod+ from core.inference import diffusion_engine_router as router+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS++ monkeypatch.setattr(router, "predict_engine", lambda fam, **_: ENGINE_DIFFUSERS)+ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: _types.SimpleNamespace(device = "cuda")+ )++ def _refuse(_ids):+ raise ValueError("Requested GPU [7] but none of them are visible to this process")++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", _refuse)+ resp = client.post(+ "/api/inference/images/download-plan",+ json = {+ "model_path": "unsloth/FLUX.1-dev-GGUF",+ "gguf_filename": "flux1-dev-Q4_K_M.gguf",+ "model_kind": "gguf",+ "gpu_ids": [7],+ },+ )+ assert resp.status_code == 400+ assert "visible to this process" in resp.json()["detail"]+++def test_download_plan_ignores_a_gpu_selection_off_cuda(client, monkeypatch):+ # Same contract the load route applies: physical ids have no applicator on XPU / MPS / CPU, so+ # they are dropped rather than refused.+ import types as _types++ from core.inference import diffusion_device as devmod+ from core.inference import diffusion_engine_router as router+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS++ monkeypatch.setattr(router, "predict_engine", lambda fam, **_: ENGINE_DIFFUSERS)+ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: _types.SimpleNamespace(device = "mps")+ )++ def _never(_ids):+ raise AssertionError("the CUDA resolver must not run off a CUDA target")++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", _never)+ backend = diffusion_module.get_diffusion_backend()+ seen: dict = {}+ monkeypatch.setattr(+ backend,+ "download_plan",+ lambda model_path, **kwargs: (seen.update(kwargs), {"entries": [], "total_bytes": 0})[1],+ raising = False,+ )+ resp = client.post(+ "/api/inference/images/download-plan",+ json = {+ "model_path": "unsloth/FLUX.1-dev-GGUF",+ "gguf_filename": "flux1-dev-Q4_K_M.gguf",+ "model_kind": "gguf",+ "gpu_ids": [1],+ },+ )+ assert resp.status_code == 200+ assert seen["gpu_ordinal"] is None+++def test_download_plan_still_refuses_a_bad_gpu_while_training_holds_the_cards(client, monkeypatch):+ # The training guard is about not opening a CUDA context, which only the ranking does.+ # Skipping the whole resolution let the plan answer 200 for a GPU the load then refuses, and+ # size its files for the default card, after tens of gigabytes had been staged.+ import types as _types++ from core.inference import diffusion_device as devmod+ from core.inference import diffusion_engine_router as router+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS+ from routes import inference as routes_inference++ monkeypatch.setattr(router, "predict_engine", lambda fam, **_: ENGINE_DIFFUSERS)+ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: _types.SimpleNamespace(device = "cuda")+ )+ monkeypatch.setattr(routes_inference, "_training_is_active", lambda: True)+ seen: dict = {}++ def _resolve(ids, *, allow_ranking = True):+ seen["ids"], seen["allow_ranking"] = list(ids), allow_ranking+ if ids == [7]:+ raise ValueError("Requested GPU [7] but none of them are visible to this process")+ return ids[0]++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", _resolve)+ backend = diffusion_module.get_diffusion_backend()+ planned: dict = {}+ monkeypatch.setattr(+ backend,+ "download_plan",+ lambda model_path, **kwargs: (planned.update(kwargs), {"entries": [], "total_bytes": 0})[1],+ raising = False,+ )+ body = {+ "model_path": "unsloth/FLUX.1-dev-GGUF",+ "gguf_filename": "flux1-dev-Q4_K_M.gguf",+ "model_kind": "gguf",+ }+ # A card that exists: honoured, and the plan is sized for it, without a ranking probe.+ resp = client.post("/api/inference/images/download-plan", json = {**body, "gpu_ids": [1]})+ assert resp.status_code == 200+ assert seen == {"ids": [1], "allow_ranking": False}+ assert planned["gpu_ordinal"] == 1+ # The precision preflight is still skipped while training runs; only the selection is judged.+ assert getattr(backend, "last_precision_kwargs", None) is None++ # And one that does not: refused here rather than after the download.+ resp = client.post("/api/inference/images/download-plan", json = {**body, "gpu_ids": [7]})+ assert resp.status_code == 400+ assert "visible to this process" in resp.json()["detail"]diff --git a/studio/backend/tests/test_sd_cpp_args.py b/studio/backend/tests/test_sd_cpp_args.pyindex 4bfece5afad..e4b5b97c951 100644--- a/studio/backend/tests/test_sd_cpp_args.py+++ b/studio/backend/tests/test_sd_cpp_args.py@@ -28,6 +28,7 @@ from core.inference.sd_cpp_args import (build_sd_cpp_server_command,build_sd_cpp_upscale_command,build_sd_cpp_video_command,+ device_backend_flags,is_ggml_unsupported_op_abort,metal_text_encoder_flags,native_speed_flags,@@ -741,3 +742,35 @@ def test_minimax_h3_video_command_carries_the_video_flow_shift():assert "--flow-shift" not in _h3_video_cmd()assert _pair(_h3_video_cmd(flow_shift = 8.5), "--flow-shift") == "8.5"assert _pair(_h3_video_cmd(flow_shift = 12.0), "--flow-shift") == "12"+++def test_device_backend_flags_pin_all_three_graphs():+ # sd.cpp defaults to ordinal 0 unless told otherwise, so a selection only takes effect through --backend.+ assert device_backend_flags("CUDA1") == ["--backend", "diffusion=CUDA1,te=CUDA1,vae=CUDA1"]+ # No selection keeps sd.cpp's own choice rather than pinning ordinal 0 explicitly.+ assert device_backend_flags(None) == []+ assert device_backend_flags("") == []+++def test_device_backend_flags_leave_the_offloaded_modules_on_the_cpu():+ # --clip-on-cpu / --vae-on-cpu ARE te=cpu / vae=cpu and the parser is last-wins, so pinning them would undo low_vram.+ low_vram = offload_flags(OFFLOAD_MODEL)+ assert "--clip-on-cpu" in low_vram and "--vae-on-cpu" in low_vram+ assert device_backend_flags("CUDA1", low_vram) == [+ "--backend",+ "diffusion=CUDA1,te=cpu,vae=cpu",+ ]+ # The group policy offloads parameters but runs both on the device, so both are pinned.+ assert device_backend_flags("CUDA1", offload_flags(OFFLOAD_GROUP)) == [+ "--backend",+ "diffusion=CUDA1,te=CUDA1,vae=CUDA1",+ ]+++def test_device_backend_flags_are_appended_not_folded_into_the_policy():+ # The pin is built per binary at the point the flags are handed over, so the policy list it+ # reads must stay unchanged: a deferred install can replace the build after this is computed.+ policy = offload_flags(OFFLOAD_GROUP)+ before = list(policy)+ device_backend_flags("CUDA1", policy)+ assert policy == beforediff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex 6d6dc928d7f..e734c9974d7 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -1194,6 +1194,58 @@ def test_lists_accelerator_device_reads_the_ggml_device_list(monkeypatch):assert bk.sd_cpp_lists_accelerator_device(None) is False+def test_device_name_for_ordinal_reads_the_ggml_device_list(monkeypatch):+ monkeypatch.setattr(+ bk,+ "_sd_cpp_probe_output",+ lambda *_a: "CUDA0\tRTX 4070 Ti\nCUDA1\tRTX 5060 Ti\nCPU\tAMD Ryzen 9\n",+ )+ assert bk.sd_cpp_device_name_for_ordinal("/existing/sd-cli", 1) == "CUDA1"+ assert bk.sd_cpp_device_name_for_ordinal("/existing/sd-cli", 0) == "CUDA0"+ # An index this build does not enumerate keeps sd.cpp's own device choice.+ assert bk.sd_cpp_device_name_for_ordinal("/existing/sd-cli", 3) is None+ assert bk.sd_cpp_device_name_for_ordinal("/existing/sd-cli", None) is None+ assert bk.sd_cpp_device_name_for_ordinal(None, 1) is None++ # ggml names its HIP backend ROCm on newer builds, and it takes the same physical index.+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: "ROCm1\tRadeon RX 7900\n")+ assert bk.sd_cpp_device_name_for_ordinal("/existing/sd-cli", 1) == "ROCm1"++ # Vulkan ordinals are another namespace, so they never match: pinning one would name a card the user did not choose.+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: "Vulkan1\tRTX 5060 Ti\n")+ assert bk.sd_cpp_device_name_for_ordinal("/existing/sd-cli", 1) is None++ # An unreadable probe is "cannot tell", so nothing is pinned.+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: None)+ assert bk.sd_cpp_device_name_for_ordinal("/existing/sd-cli", 1) is None+++def test_offload_device_pin_is_probed_against_the_binary_it_is_given(monkeypatch):+ # Rebuilt per binary: a deferred accelerator install replaces the build after the offload+ # policy is computed, and the ggml names come from whichever one runs.+ seen: list = []++ def _probe(binary, *_args):+ seen.append(binary)+ return "CUDA0\tA\nCUDA1\tB\n" if binary == "/new/sd-cli" else "CPU\tRyzen\n"++ monkeypatch.setattr(bk, "_sd_cpp_probe_output", _probe)+ base = ["--offload-to-cpu"]+ # The pre-upgrade CPU-only build enumerates no CUDA device, so nothing is pinned.+ assert bk._offload_with_device_pin_impl(base, "/old/sd-cli", 1) == base+ # The build that actually runs does, and the same call now pins it.+ assert bk._offload_with_device_pin_impl(base, "/new/sd-cli", 1) == [+ "--offload-to-cpu",+ "--backend",+ "diffusion=CUDA1,te=CUDA1,vae=CUDA1",+ ]+ assert seen == ["/old/sd-cli", "/new/sd-cli"]+ # No selection never spawns the probe at all.+ seen.clear()+ assert bk._offload_with_device_pin_impl(base, "/new/sd-cli", None) == base+ assert seen == []++def test_unload_clears_state_and_signals_cancel():cancel = threading.Event()b = _loaded_backend()@@ -2202,3 +2254,143 @@ def test_a_completed_native_generation_stops_advertising_itself_as_cancellable(massert out["images"]seen.append(b2.cancel_generate())assert seen == [False]+++def _pinned_state(+ b,+ *,+ policy_flags = (),+ device = "cuda",+):+ """A resident native load whose argv carries the --backend device pin on top of `policy_flags`,+ exactly as _run_load builds it once a card has been selected."""+ from core.inference.sd_cpp_args import device_backend_flags++ s = b._state+ return bk._SdState(+ repo_id = s.repo_id,+ base_repo = s.base_repo,+ family = s.family,+ device = device,+ files = s.files,+ vae_format = s.vae_format,+ sampling_method = s.sampling_method,+ flow_shift = s.flow_shift,+ mode = s.mode,+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",+ offload_flags = (+ *policy_flags,+ *device_backend_flags("CUDA1", list(policy_flags)),+ ),+ )+++def test_a_card_pick_is_not_reported_as_an_offload():+ # `fast` asks for no offload, so its flag list is empty and status() and the saved recipe+ # read "nothing was offloaded" off that. The pin lands in the same tuple, which made picking+ # a GPU look like turning CPU offload on.+ b = _loaded_backend()+ b._state = _pinned_state(b, policy_flags = ())+ assert b._state.offload_flags, "the fixture must actually carry the pin"+ status = b.status()+ assert status["cpu_offload"] is False+ assert status["offload_policy"] == "none"+ out = b.generate(prompt = "a fox", width = 64, height = 64, steps = 4, seed = 1)+ assert out["offload_policy"] == "none"+++def test_a_real_offload_still_reports_itself_when_a_card_is_pinned():+ # The other half of the same rule: stripping the pin must not swallow a policy that IS active.+ b = _loaded_backend()+ b._state = _pinned_state(b, policy_flags = ("--offload-to-cpu", "--diffusion-fa"))+ assert b.status()["cpu_offload"] is True+ assert b.status()["offload_policy"] == "active"+++def test_the_cpu_backend_restart_drops_the_device_pin(monkeypatch):+ # sd.cpp CONCATENATES repeated --backend values (declared with concat = ',') and a per-module+ # entry outranks the bare `cpu` default, so restarting with the pin still in argv leaves the+ # denoiser on the card that just aborted: the recovery is a no-op, the same GGML_ABORT.+ started: dict = {}++ class _FakeServer:+ def __init__(self, binary):+ self.binary = binary++ def start(self, files, **kwargs):+ started.update(kwargs)++ def stop(self):+ pass++ b = _loaded_backend()+ b._state = _pinned_state(b, policy_flags = ("--offload-to-cpu", "--clip-on-cpu"))+ object.__setattr__(b._state, "server", _FakeServer("/bin/sd-server"))+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/bin/sd-server")+ monkeypatch.setattr(bk, "SdCppServer", _FakeServer)++ server = b._restart_server_on_cpu_backend(+ b._state,+ "ggml_metal_op_encode_impl: unsupported op 'MUL_MAT' -> ggml_abort",+ threading.Event(),+ )+ assert server is not None+ argv = [*started["offload"], *started["extra_args"]]+ # One --backend value survives, and it is the CPU one.+ backends = [argv[i + 1] for i, flag in enumerate(argv) if flag == "--backend"]+ assert backends == ["cpu"]+ # The policy the load committed to is untouched.+ assert "--offload-to-cpu" in argv and "--clip-on-cpu" in argv+++def test_the_native_engine_resolves_a_bare_gpu_selection_itself(monkeypatch):+ # The routes hand over the ranked winner, but a direct caller (MCP client, plugin) passes+ # gpu_ids alone. diffusers and video re-rank in that case; native used to drop the pick.+ import core.inference.sd_cpp_backend as backend_module++ seen: dict = {}+ monkeypatch.setattr(+ backend_module,+ "resolve_diffusion_device_target",+ lambda **kw: types.SimpleNamespace(device = "cuda"),+ )+ monkeypatch.setattr(+ backend_module,+ "resolve_selected_cuda_ordinal",+ lambda ids: (seen.update(ids = list(ids)), 1)[1],+ )+ b = SdCppDiffusionBackend(engine = _FakeEngine())+ monkeypatch.setattr(b, "_start_load_thread", lambda *a, **k: None, raising = False)+ captured: dict = {}++ def _fake_thread(+ target = None,+ kwargs = None,+ **_,+ ):+ captured.update(kwargs or {})+ return types.SimpleNamespace(start = lambda: None, join = lambda *a, **k: None)++ monkeypatch.setattr(backend_module.threading, "Thread", _fake_thread)+ b.begin_load(+ "unsloth/Z-Image-Turbo-GGUF",+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",+ gpu_ids = [3],+ )+ assert seen["ids"] == [3]+ assert captured["gpu_ordinal"] == 1+++def test_an_unresolvable_device_pin_says_so_and_still_loads(tmp_path, capsys):+ # Refusing here would turn an unhonoured selection into an unloadable model on any build+ # predating --list-devices, including a user's own SD_CLI_PATH copy (sd.cpp treats an unknown+ # argument as fatal). It runs on the build's own device, as every native load does today, and+ # says so rather than dropping the pick in silence.+ binary = tmp_path / "sd-cli-old"+ binary.write_text("#!/usr/bin/env bash\nexit 1\n")+ binary.chmod(0o755)+ assert bk.sd_cpp_device_name_for_ordinal(str(binary), 1) is None+ assert "device_pin_unresolved" in capsys.readouterr().out+ # No selection is not an unresolved one, so it says nothing.+ assert bk.sd_cpp_device_name_for_ordinal(str(binary), None) is None+ assert "device_pin_unresolved" not in capsys.readouterr().outdiff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.pyindex d3324fc7c26..941178fb2a8 100644--- a/studio/backend/tests/test_video_routes.py+++ b/studio/backend/tests/test_video_routes.py@@ -309,6 +309,57 @@ def test_load_happy_path_and_arbiter_acquired(client, monkeypatch):assert acquired == [gpu_arbiter.VIDEO] # the GPU was handed to VIDEO+def test_load_forwards_the_gpu_selection(client, monkeypatch):+ # /video/load carried no gpu_ids at all, so sd.cpp and diffusers both pinned ordinal 0.+ import types++ import core.inference.diffusion_device as devmod+ import core.inference.video as video_module++ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )+ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", lambda ids: max(ids))+ monkeypatch.setattr(gpu_arbiter, "acquire_for", lambda role, register = None: register())+ resp = client.post(+ "/api/inference/video/load",+ json = {+ "model_path": "unsloth/LTX-2.3-GGUF",+ "gguf_filename": "ltx-2.3-distilled-Q4_K_M.gguf",+ "gpu_ids": [1],+ },+ )+ assert resp.status_code == 200+ assert video_module.get_video_backend().last_load_kwargs["gpu_ids"] == [1]+++def test_load_refuses_a_gpu_index_this_host_does_not_have(client, monkeypatch):+ # Refused BEFORE the arbiter evicts chat, so a bad pick costs a resident model nothing.+ import types++ import core.inference.diffusion_device as devmod++ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )++ def _refuse(_ids):+ raise ValueError("Requested GPU [7] but this host has 2 CUDA device(s).")++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", _refuse)+ resp = client.post(+ "/api/inference/video/load",+ json = {+ "model_path": "unsloth/LTX-2.3-GGUF",+ "gguf_filename": "ltx-2.3-distilled-Q4_K_M.gguf",+ "gpu_ids": [7],+ },+ )+ assert resp.status_code == 400+ assert "2 CUDA device" in resp.json()["detail"]+ assert gpu_arbiter._owner is None++def test_load_value_error_returns_400(client):# A non-ltx repo is not a supported family: the cheap validation rejects it -> 400.resp = client.post(@@ -1552,3 +1603,117 @@ def test_the_video_gate_leaves_a_measured_memory_mode_alone(monkeypatch):transformer_quant = "fp8",memory_mode = "fast",)+++def test_video_download_plan_sizes_its_file_set_for_the_selected_card(client, monkeypatch):+ # The H3 planner sets its denoiser partition and memory policy from device capacity, so a+ # plan sized against the default card stages the wrong weights.+ import types++ import core.inference.diffusion_device as devmod++ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "1")+ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )+ ranked: list = []+ monkeypatch.setattr(+ devmod,+ "resolve_selected_cuda_ordinal",+ lambda ids: (ranked.append(list(ids)), 1)[1],+ )+ backend = video_module.get_video_backend()+ seen: dict = {}+ monkeypatch.setattr(+ backend,+ "download_plan",+ lambda model_path, **kwargs: (seen.update(kwargs), {"entries": [], "total_bytes": 0})[1],+ raising = False,+ )+ resp = client.post(+ "/api/inference/video/download-plan",+ json = {+ "model_path": "unsloth/LTX-2.3-GGUF",+ "gguf_filename": "distilled/ltx-2.3-22b-distilled-Q4_K_M.gguf",+ "model_kind": "gguf",+ "gpu_ids": [0, 1],+ },+ )+ assert resp.status_code == 200+ assert seen["gpu_ordinal"] == 1+ # One ranking for the request, shared by the precision preflight and the plan.+ assert ranked == [[0, 1]]+++def test_video_download_plan_refuses_a_gpu_index_this_host_does_not_have(client, monkeypatch):+ import types++ import core.inference.diffusion_device as devmod++ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )++ def _refuse(_ids):+ raise ValueError("Requested GPU [7] but none of them are visible to this process")++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", _refuse)+ backend = video_module.get_video_backend()+ monkeypatch.setattr(+ backend,+ "download_plan",+ lambda *a, **k: pytest.fail("a refused GPU pick must not reach the planner"),+ raising = False,+ )+ resp = client.post(+ "/api/inference/video/download-plan",+ json = {+ "model_path": "unsloth/LTX-2.3-GGUF",+ "gguf_filename": "distilled/ltx-2.3-22b-distilled-Q4_K_M.gguf",+ "model_kind": "gguf",+ "gpu_ids": [7],+ },+ )+ assert resp.status_code == 400+ assert "visible to this process" in resp.json()["detail"]+++def test_video_download_plan_still_refuses_a_bad_gpu_while_training_holds_the_cards(+ client, monkeypatch+):+ # Same rule as the image twin: the training guard bars the ranking, not the validation,+ # which reads the mask and nvidia-smi and opens no CUDA context.+ import types++ import core.inference.diffusion_device as devmod+ from routes import video as routes_video++ monkeypatch.setattr(+ devmod, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )+ monkeypatch.setattr(routes_video, "_training_is_active", lambda: True)+ seen: dict = {}++ def _resolve(ids, *, allow_ranking = True):+ seen["ids"], seen["allow_ranking"] = list(ids), allow_ranking+ raise ValueError("Requested GPU [7] but none of them are visible to this process")++ monkeypatch.setattr(devmod, "resolve_selected_cuda_ordinal", _resolve)+ backend = video_module.get_video_backend()+ monkeypatch.setattr(+ backend,+ "download_plan",+ lambda *a, **k: pytest.fail("a refused GPU pick must not reach the planner"),+ raising = False,+ )+ resp = client.post(+ "/api/inference/video/download-plan",+ json = {+ "model_path": "unsloth/LTX-2.3-GGUF",+ "gguf_filename": "distilled/ltx-2.3-22b-distilled-Q4_K_M.gguf",+ "model_kind": "gguf",+ "gpu_ids": [7],+ },+ )+ assert resp.status_code == 400+ assert seen == {"ids": [7], "allow_ranking": False}diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 8d2c91e893a..029a996dc6f 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -101,6 +101,8 @@ export interface DiffusionLoadRequest {| "xformers"| "aiter";memory_mode?: "auto" | "fast" | "balanced" | "low_vram";+ // CUDA / ROCm physical indices this load may use; omit for automatic. Neither engine shards a checkpoint, so several cards resolve to the one with the most free VRAM.+ gpu_ids?: number[];transformer_cache?: "off" | "fbcache";// LoRA adapters to BAKE into a torchao int8/fp8 build: they can only attach to the dense transformer BEFORE quantisation +// compile, so a quantized load that omits them rejects every generation. Ignored by bf16 / bnb-4bit, which apply at generate time.diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 4419486877a..6bd05d1f4d4 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -50,6 +50,8 @@ import {TooltipTrigger,} from "@/components/ui/tooltip";import { InfoHint } from "@/components/ui/info-hint";+import { useDiffusionGpuChoices } from "@/hooks/use-gpu-info";+import { usePersistedChoice } from "@/hooks/use-persisted-choice";import { useScrollFades } from "@/hooks/use-scroll-fades";import { ModelSelector } from "@/features/model-picker/components/model-selector";import { IMAGE_GEN_TASKS } from "@/features/model-picker/components/model-selector/pickers";@@ -1156,6 +1158,7 @@ type LoadAdvanced = Pick<| "memory_mode"| "transformer_cache"| "loras"+ | "gpu_ids">;export function ImagesPage({ active = true }: { active?: boolean }) {@@ -1268,6 +1271,16 @@ export function ImagesPage({ active = true }: { active?: boolean }) {"auto",);const [memoryMode, setMemoryMode] = useState<"auto" | "fast" | "balanced" | "low_vram">("auto");+ // "auto", or the physical index to pin this load to. Only offered on a multi-card CUDA / ROCm host.+ // Persisted, unlike the selects around it: those are reseeded from the loaded build, and the+ // status carries the device a pipeline is on but not which card, so a refresh would reset this+ // one to Auto while the model stayed put and the next Reapply would move it to the default GPU.+ // A stored id is only a hint; the send path below still drops one whose card is no longer there.+ const [selectedGpu, setSelectedGpu] = usePersistedChoice(+ "unsloth_image_gpu_choice",+ "auto",+ );+ const gpuChoices = useDiffusionGpuChoices();const [transformerCache, setTransformerCache] = useState<"auto" | "off" | "fbcache">("auto");const [cpuOffload, setCpuOffload] = useState(false);// The last load descriptor, so "Reapply" can reload the same model with new advanced options without the user re-picking it.@@ -2375,6 +2388,12 @@ export function ImagesPage({ active = true }: { active?: boolean }) {memory_mode: memoryMode === "auto" ? undefined : memoryMode,transformer_cache: transformerCache === "auto" ? undefined : transformerCache,loras: baked.length > 0 ? baked : undefined,+ // Dropped when the chosen card is gone (a driver reset, an eGPU unplugged), so a stale pick loads automatically instead of 400ing.+ gpu_ids:+ selectedGpu !== "auto" &&+ gpuChoices.some((d) => String(d.index) === selectedGpu)+ ? [Number(selectedGpu)]+ : undefined,};},[@@ -2385,6 +2404,8 @@ export function ImagesPage({ active = true }: { active?: boolean }) {attentionBackend,memoryMode,transformerCache,+ selectedGpu,+ gpuChoices,],);@@ -2457,6 +2478,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {memory_mode: advanced.memory_mode,transformer_cache: advanced.transformer_cache,loras: bakeLoras.length > 0 ? bakeLoras : undefined,+ gpu_ids: advanced.gpu_ids,});await startRequest;} catch (err) {@@ -2598,6 +2620,9 @@ export function ImagesPage({ active = true }: { active?: boolean }) {// The backend prefetch decision reads the adapter selection too: a baked LoRA always runs the dense build path. Omitting it// planned a quantized file set and staged too little. Same list handleLoad bakes.loras: advanced.loras,+ // The plan route preflights precision and sizes the file set against the card the load+ // will use, so a selection the load carries has to reach the plan as well.+ gpu_ids: advanced.gpu_ids,}),[],);@@ -3502,6 +3527,24 @@ export function ImagesPage({ active = true }: { active?: boolean }) {["low_vram", "Low VRAM"],]}/>+ {gpuChoices.length > 0 && (+ <AdvancedSelect+ label="GPU"+ hint="Which card this model loads on. Auto uses whichever device torch is pointing at, which on a mixed box is not necessarily the largest. An image model is never split across cards, so this is one choice, not a pool."+ value={selectedGpu}+ onValueChange={setSelectedGpu}+ options={[+ ["auto", "Auto"],+ ...gpuChoices.map(+ (d) =>+ [+ String(d.index),+ `GPU ${d.index}${d.memoryTotalGb ? ` · ${Math.round(d.memoryTotalGb)} GB` : ""}`,+ ] as [string, string],+ ),+ ]}+ />+ )}<AdvancedSelectlabel="Step cache"hint="First-Block-Cache reuses the transformer tail across steps for many-step models (~1.4x). Auto turns it on at 20+ steps and off for few-step distilled models, re-checked per image."diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.tsindex 60f780d5f91..ec22846c333 100644--- a/studio/frontend/src/features/video/api.ts+++ b/studio/frontend/src/features/video/api.ts@@ -137,6 +137,8 @@ export interface VideoLoadRequest {transformer_quant?: "none" | "fp8" | "int8" | "nvfp4" | "mxfp8";// Pipeline denoiser partition. GGUF filenames already identify theirs.h3_task?: "fl2va" | "ref2va";+ // CUDA / ROCm physical indices this load may use; omit for automatic. Neither engine shards a checkpoint, so several cards resolve to the one with the most free VRAM.+ gpu_ids?: number[];// Text-encoder precision (omit to keep the dense bf16 encoder). Refused with a 409 when the host cannot run it.text_encoder_quant?: "fp8" | "fp8_dynamic" | "int8" | "nvfp4";}diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex 0188129960d..7f020ac066a 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -30,6 +30,7 @@ import {sortGalleryItems,subscribeGalleryChanged,} from "@/lib/gallery-flags";+import { useDiffusionGpuChoices } from "@/hooks/use-gpu-info";import { useHardwareInfo } from "@/hooks/use-hardware-info";import { usePersistedToggle } from "@/hooks/use-persisted-toggle";import {@@ -78,6 +79,7 @@ import {} from "@/components/ui/tooltip";import { InfoHint } from "@/components/ui/info-hint";import { NegativePromptField } from "@/components/negative-prompt-field";+import { usePersistedChoice } from "@/hooks/use-persisted-choice";import { useScrollFades } from "@/hooks/use-scroll-fades";import { ModelSelector } from "@/features/model-picker/components/model-selector";import { VIDEO_GEN_TASKS } from "@/features/model-picker/components/model-selector/pickers";@@ -761,6 +763,7 @@ type VideoLoadAdvanced = Pick<| "attention_backend"| "transformer_cache"| "transformer_quant"+ | "gpu_ids">;// Centered panel used for both halves of the capability gate below: the wait, and the answer.@@ -887,6 +890,16 @@ function VideoGenerator({ active = true }: { active?: boolean }) {);// Advanced (load-time) options; "auto"/"off" map to the backend defaults. "Reapply" reloads with new values.const [memoryMode, setMemoryMode] = useState<"auto" | "fast" | "balanced" | "low_vram">("auto");+ // "auto", or the physical index to pin this load to. Only offered on a multi-card CUDA / ROCm host.+ // Persisted, unlike the selects around it: those are reseeded from the loaded build, and the+ // status carries the device a pipeline is on but not which card, so a refresh would reset this+ // one to Auto while the model stayed put and the next Reapply would move it to the default GPU.+ // A stored id is only a hint; the send path below still drops one whose card is no longer there.+ const [selectedGpu, setSelectedGpu] = usePersistedChoice(+ "unsloth_video_gpu_choice",+ "auto",+ );+ const gpuChoices = useDiffusionGpuChoices();const [speedMode, setSpeedMode] = useState<"auto" | "off" | "eager" | "default" | "max">("auto");const [attentionBackend, setAttentionBackend] = useState<"auto" | "native" | "cudnn" | "flash3" | "sage"@@ -2124,6 +2137,8 @@ function VideoGenerator({ active = true }: { active?: boolean }) {attentionBackend,transformerCache,transformerQuant,+ selectedGpu,+ gpuChoices,});loadControlsRef.current = {memoryMode,@@ -2131,6 +2146,8 @@ function VideoGenerator({ active = true }: { active?: boolean }) {attentionBackend,transformerCache,transformerQuant,+ selectedGpu,+ gpuChoices,};const currentLoadAdvanced = useCallback((kind: "gguf" | "single_file" | "pipeline"): VideoLoadAdvanced => {@@ -2146,6 +2163,12 @@ function VideoGenerator({ active = true }: { active?: boolean }) {kind === "pipeline" && controls.transformerQuant !== "auto"? controls.transformerQuant: undefined,+ // Dropped when the chosen card is gone (a driver reset, an eGPU unplugged), so a stale pick loads automatically instead of 400ing.+ gpu_ids:+ controls.selectedGpu !== "auto" &&+ controls.gpuChoices.some((d) => String(d.index) === controls.selectedGpu)+ ? [Number(controls.selectedGpu)]+ : undefined,};},[],@@ -2161,6 +2184,8 @@ function VideoGenerator({ active = true }: { active?: boolean }) {hf_token: hfApiToken(getHfToken()),transformer_quant: advanced.transformer_quant,memory_mode: advanced.memory_mode,+ // The plan sizes its file set against the card the load will use, so it needs the pick.+ gpu_ids: advanced.gpu_ids,});const requiredBytes = plan.required_bytes ?? 0;if (requiredBytes <= 0) return null;@@ -2227,6 +2252,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {// Not an Advanced control: the partition is chosen per pick, so it stays on opts rather// than joining the pinned set.h3_task: opts.h3Task,+ gpu_ids: advanced.gpu_ids,});await startRequest;} catch (err) {@@ -2386,6 +2412,8 @@ function VideoGenerator({ active = true }: { active?: boolean }) {// And the partition, for the same reason: the two H3 denoisers are separate downloads,// so a plan asked without it stages the default fl2va weights for a References pick.h3_task: opts.h3Task,+ // The plan sizes its file set against the card the load will use, so it needs the pick.+ gpu_ids: advanced.gpu_ids,});// Superseded. Report started so this pick's `.then` leaves the newer label alone.if (pick !== pickSeq.current || !owns()) return true;@@ -3076,6 +3104,24 @@ function VideoGenerator({ active = true }: { active?: boolean }) {["sage", "SageAttention (INT8)"],]}/>+ {gpuChoices.length > 0 && (+ <AdvancedSelect+ label="GPU"+ hint="Which card this model loads on. Auto uses whichever device torch is pointing at, which on a mixed box is not necessarily the largest. A video model is never split across cards, so this is one choice, not a pool."+ value={selectedGpu}+ onValueChange={setSelectedGpu}+ options={[+ ["auto", "Auto"],+ ...gpuChoices.map(+ (d) =>+ [+ String(d.index),+ `GPU ${d.index}${d.memoryTotalGb ? ` · ${Math.round(d.memoryTotalGb)} GB` : ""}`,+ ] as [string, string],+ ),+ ]}+ />+ )}<AdvancedSelectlabel="Step cache"hint="First-Block-Cache reuses the transformer tail across steps for many-step models. Auto turns it on at 20+ steps and off for few-step distilled models, re-checked per clip."diff --git a/studio/frontend/src/hooks/use-gpu-info.ts b/studio/frontend/src/hooks/use-gpu-info.tsindex a6324f6597f..1a3ef8dfb1d 100644--- a/studio/frontend/src/hooks/use-gpu-info.ts+++ b/studio/frontend/src/hooks/use-gpu-info.ts@@ -1,13 +1,14 @@// 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 { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import {type GpuIndexKind,type PinnableGpuContext,type ReconciledGpuSelection,type SystemGpuDevice,pickLoadDevice,+ pinnableGpuContext,reconcileGpuSelection,resolveGpuSelectionContext,} from "./gpu-selection";@@ -92,14 +93,20 @@ function toGpuInfo(};}-function toGpuDevices(data: SystemInfoResponse | null): SystemGpuDevice[] {+function toGpuDevices(+ data: SystemInfoResponse | null,+ // Diffusion runs on torch, not llama-server, so it reads the torch inventory even where the+ // inference backend is Vulkan: those are separate runtimes and a Vulkan chat build says nothing+ // about the CUDA / ROCm devices an image or video load can be pinned to.+ forDiffusion = false,+): SystemGpuDevice[] {// GGUF loads run through llama-server, so on a Vulkan build the pickable set// is the inference inventory, not the torch view: it can see cards torch// cannot, and its indices are the ggml ordinals `--device Vulkan<i>` pins.// The XPU ban does not apply there, it is about torch-xpu ordinals that no// applicator speaks; a Vulkan pick does not use them.const inference = data?.inference_gpu;- if (inference?.backend === "vulkan") {+ if (!forDiffusion && inference?.backend === "vulkan") {// The installed inference backend is confirmed Vulkan, so even an empty// device list (probe still cold, or transiently failed) must NOT fall// through to the torch/CUDA inventory below: those physical IDs are@@ -201,10 +208,10 @@ export function useInferenceGpuInfo(): GpuInfo {}/** All backend-visible GPUs (index, name, total VRAM); shares the same fetch. */-export function useGpuDevices(): SystemGpuDevice[] {+export function useGpuDevices(forDiffusion = false): SystemGpuDevice[] {const cachedSystem = getCachedSystemInfo();const [devices, setDevices] = useState<SystemGpuDevice[]>(- cachedSystem ? toGpuDevices(cachedSystem) : [],+ cachedSystem ? toGpuDevices(cachedSystem, forDiffusion) : [],);useEffect(() => {// No early return on cachedSystem: a consumer mounting as the cache fills@@ -213,7 +220,7 @@ export function useGpuDevices(): SystemGpuDevice[] {let lastSerialized: string | null = null;const sync = (data: SystemInfoResponse | null) => {if (cancelled) return;- const next = toGpuDevices(data);+ const next = toGpuDevices(data, forDiffusion);// Every refresh builds a fresh array, so compare by value or a 3s Vulkan// retry loop would re-render this hook forever.const serialized = JSON.stringify(next);@@ -229,10 +236,28 @@ export function useGpuDevices(): SystemGpuDevice[] {cancelled = true;unsubscribe();};- }, []);+ }, [forDiffusion]);return devices;}+/**+ * Cards an image or video load may be pinned to, or empty when there is nothing to choose+ * between. Neither engine shards a diffusion checkpoint, so this drives a single-choice control+ * rather than the chat picker's candidate pool.+ */+export function useDiffusionGpuChoices(): SystemGpuDevice[] {+ const devices = useGpuDevices(true);+ // Memoized on the device list, which only changes when the inventory does. pinnableGpuContext+ // builds a fresh filtered array per call, so an unmemoized return changed identity on every+ // render of the page holding it: it feeds the load-advanced snapshot, that feeds the download+ // footprint resolver, and the GGUF picker re-runs its effect whenever the resolver changes --+ // clearing the sizes it had and re-POSTing a download plan per variant on every status poll.+ return useMemo(() => {+ const context = pinnableGpuContext(devices, true);+ return (context.ids?.length ?? 0) > 1 ? (context.devices ?? []) : [];+ }, [devices]);+}+/** Whether device discovery is settled enough to rewrite remembered UI state. */export function gpuDeviceCacheReady(): boolean {const cachedSystem = getCachedSystemInfo();diff --git a/studio/frontend/src/hooks/use-persisted-choice.ts b/studio/frontend/src/hooks/use-persisted-choice.tsnew file mode 100644index 00000000000..5ddfa4004f4--- /dev/null+++ b/studio/frontend/src/hooks/use-persisted-choice.ts@@ -0,0 +1,44 @@+// 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 { useCallback, useState } from "react";++/** A string choice that survives reloads, falling back to `fallback`.+ *+ * The string sibling of `usePersistedToggle`, for a control that cannot be reseeded from the+ * loaded build: the backend reports the device a pipeline is on but not the physical card, so a+ * refresh would reset the GPU pick to Auto while the model stayed put and the next Reapply moved+ * it. The stored value is only a hint, so the caller must check it against the live inventory: a+ * card that has gone (driver reset, eGPU unplugged) falls back to automatic rather than being+ * sent to a backend that would 400 it.+ *+ * Storage failures keep the control working for the session.+ */+export function usePersistedChoice(+ key: string,+ fallback: string,+): [string, (next: string) => void] {+ const [value, setValueState] = useState(() => {+ try {+ return localStorage.getItem(key) ?? fallback;+ } catch {+ return fallback;+ }+ });+ const setValue = useCallback(+ (next: string) => {+ setValueState(next);+ try {+ if (next === fallback) {+ localStorage.removeItem(key);+ } else {+ localStorage.setItem(key, next);+ }+ } catch {+ // storage unavailable+ }+ },+ [key, fallback],+ );+ return [value, setValue];+}diff --git a/studio/frontend/tests/diffusion-gpu-choices.test.ts b/studio/frontend/tests/diffusion-gpu-choices.test.tsnew file mode 100644index 00000000000..2c2dbe8757b--- /dev/null+++ b/studio/frontend/tests/diffusion-gpu-choices.test.ts@@ -0,0 +1,107 @@+// 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 rule behind the Images / Video Advanced GPU control: which cards a load may be pinned to.+// A different question from the chat picker's, since a Vulkan llama-server says nothing about the+// CUDA devices a torch diffusion load can use, and since neither engine shards a checkpoint, so+// this is a single choice that appears only when there is something to choose between.++import assert from "node:assert/strict";+import test from "node:test";++import {+ type SystemGpuDevice,+ pinnableGpuContext,+} from "../src/hooks/gpu-selection.ts";++function device(+ index: number,+ overrides: Partial<SystemGpuDevice> = {},+): SystemGpuDevice {+ return {+ index,+ indexKind: "physical",+ name: `GPU ${index}`,+ memoryTotalGb: 24,+ memoryFreeGb: 20,+ pinnable: true,+ diffusionPinnable: true,+ ...overrides,+ };+}++// What the control renders from: ids only when more than one card is pinnable.+function choices(devices: SystemGpuDevice[] | null): SystemGpuDevice[] {+ const context = pinnableGpuContext(devices, true);+ return (context.ids?.length ?? 0) > 1 ? (context.devices ?? []) : [];+}++test("one card is nothing to choose between, so no control is offered", () => {+ assert.deepEqual(choices([device(0)]), []);+ assert.deepEqual(choices([]), []);+ assert.deepEqual(choices(null), []);+});++test("two pinnable cards are offered, in inventory order", () => {+ const offered = choices([device(0), device(1)]);+ assert.deepEqual(+ offered.map((d) => d.index),+ [0, 1],+ );+});++test("a masked host offers the physical ids it actually sees, not 0..n", () => {+ // Under CUDA_VISIBLE_DEVICES=4,5 the backend reports physical 4 and 5 and the routes do the+ // translation, so the control sends the physical ids through.+ const offered = choices([device(4), device(5)]);+ assert.deepEqual(+ offered.map((d) => d.index),+ [4, 5],+ );+});++test("cards the diffusion runner cannot address are not offered", () => {+ // diffusionPinnable is false off CUDA / ROCm (XPU ordinals have no applicator) and for any+ // Vulkan ordinal, which belongs to another index space entirely.+ assert.deepEqual(+ choices([+ device(0, { diffusionPinnable: false }),+ device(1, { diffusionPinnable: false }),+ ]),+ [],+ );+ // One pinnable card beside an unpinnable one is still a single choice.+ assert.deepEqual(choices([device(0), device(1, { diffusionPinnable: false })]), []);+});++test("the chat picker and the diffusion control answer independently", () => {+ // A Vulkan chat build with CUDA torch devices: chat pins ggml ordinals, diffusion physical ids.+ const devices = [+ device(0, { indexKind: "vulkan", pinnable: true, diffusionPinnable: false }),+ device(1, { indexKind: "vulkan", pinnable: true, diffusionPinnable: false }),+ ];+ assert.deepEqual(pinnableGpuContext(devices, false).ids, [0, 1]);+ assert.deepEqual(choices(devices), []);+});++test("mixed index namespaces are never offered as one pool", () => {+ const devices = [+ device(0, { indexKind: "physical" }),+ device(1, { indexKind: "vulkan" }),+ ];+ assert.deepEqual(pinnableGpuContext(devices, true).ids, []);+ assert.deepEqual(choices(devices), []);+});++test("a pick whose card has gone falls back to automatic rather than a refusal", () => {+ // A remembered index no longer in the inventory (driver reset, eGPU unplugged) is dropped, so+ // the load runs automatically instead of 400ing.+ const offered = choices([device(0), device(1)]);+ const send = (selected: string) =>+ selected !== "auto" && offered.some((d) => String(d.index) === selected)+ ? [Number(selected)]+ : undefined;+ assert.deepEqual(send("1"), [1]);+ assert.equal(send("auto"), undefined);+ assert.equal(send("7"), undefined);+});diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 98b1de2810a..12c0309bb7e 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -2145,7 +2145,14 @@ def test_vulkan_inference_devices_are_the_pickable_set():# The Vulkan inventory is authoritative even while its probe is temporarily# empty. Falling through would expose physical CUDA/ROCm IDs in an ordinal# picker and make DiffusionGemma offer a selection the route rejects.- assert 'const inference = data?.inference_gpu; if (inference?.backend === "vulkan") {' in src+ # Scoped to the GGUF picker: an image or video load runs on torch, not llama-server, so it+ # reads the torch inventory even here. A Vulkan chat build says nothing about the CUDA / ROCm+ # devices a diffusion load can be pinned to.+ vulkan_gate = (+ "const inference = data?.inference_gpu; "+ 'if (!forDiffusion && inference?.backend === "vulkan") {'+ )+ assert vulkan_gate in src# A confirmed-Vulkan backend with no enumerated devices yet must return no# devices, not fall through to the torch/CUDA inventory below.assert "if (!(inference.devices ?? []).length) return [];" in src@@ -3546,3 +3553,36 @@ def test_the_backend_keys_the_footprint_on_family_and_text_encoders():assert answer.count("dependency_key = _variant_dependency_key(") >= 4schema = _read_backend("hub/schemas/inventory.py")assert "dependency_key: Optional[str] = Field(" in schema+++def test_the_diffusion_gpu_choices_are_memoized():+ """An unstable array here reaches the GGUF picker as a new footprint resolver on every render.++ ImagesPage feeds the choices into its load-advanced snapshot, that snapshot into+ resolveDownloadFootprint, and the picker's effect depends on the resolver: a fresh identity per+ render clears the companion sizes it had resolved and re-POSTs /images/download-plan for every+ variant, on every status poll, discarding the in-flight answers.+ """+ src = " ".join(_read("hooks/use-gpu-info.ts").split())+ choices = src[src.index("export function useDiffusionGpuChoices") :]+ choices = choices[: choices.index("/** Whether device discovery")]+ assert "return useMemo(() => {" in choices+ # Keyed on the device list, which useGpuDevices only replaces when the inventory changes.+ assert "}, [devices]);" in choices+++def test_the_media_gpu_pick_survives_a_reload():+ """Every other Advanced select is reseeded from the loaded build; this one cannot be, because+ the status reports the device a pipeline is on and not which physical card. Without persistence+ a refresh silently reset the pick to Auto while the model stayed put, and the next Reapply+ moved it to the default GPU -- on a mixed box, potentially onto the card that cannot hold it."""+ for page, key in (+ ("features/images/images-page.tsx", "unsloth_image_gpu_choice"),+ ("features/video/video-page.tsx", "unsloth_video_gpu_choice"),+ ):+ src = " ".join(_read(page).split())+ assert f'usePersistedChoice( "{key}", "auto", )' in src, page+ # A stored id is only a hint: a card that has gone falls back to automatic.+ assert "gpuChoices.some((d) => String(d.index) === selectedGpu)" in src or (+ "controls.gpuChoices.some((d) => String(d.index) === controls.selectedGpu)" in src+ ), page