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 diffusion: Automatic partner card, FLUX batch split, LoRA scale mirror, CFG batching fallback (#16682)
Daniel Han4a863277ee2f
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 4dc177cbc18..a5b8e0a09bd 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -135,6 +135,8 @@ from .diffusion_multigpu import (install_cfg_parallel,multigpu_mode,invalidate_cfg_replica,+ mirror_cfg_replica_adapter_scales,+ set_cfg_parallel_fallback,placement_status as multigpu_placement_status,refine_plan_for_multigpu,uninstall_cfg_parallel,@@ -11069,6 +11071,19 @@ class DiffusionBackend:transformer_quant = transformer_quant_engaged,logger = logger,)+ # CFG-parallel wins when armed (cfg_batch declines a wrapped forward); if its replica fails at+ # render time, CFG batching takes over from the next render instead of unbatched branches.+ set_cfg_parallel_fallback(+ pipe,+ # called with the pipeline: capturing it here would keep a rolled-back load alive+ functools.partial(+ install_cfg_batch,+ offload_policy = effective_policy,+ speed_mode = speed_mode,+ transformer_quant = transformer_quant_engaged,+ logger = logger,+ ),+ )# Z-Image guided steps at the guidance-off batch: turning CFG on compiles and records nothing new.# compiled_only: an eager denoiser keeps the batched guided call (no graph to protect).install_zimage_cfg_split(@@ -13388,7 +13403,9 @@ class DiffusionBackend:pipe._unsloth_loras = desired# A captured graph bakes the scales in.cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))- invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)+ # Same adapters, new scales: the replica takes the scales; a rebuild only when they do not line up.+ if not mirror_cfg_replica_adapter_scales(pipe, logger):+ invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)return# PEFT targets to_q / to_k / to_v: a fused U-Net that dropped them gets them back first (bit-exact).restore_unfused_projections(getattr(pipe, "unet", None))diff --git a/studio/backend/core/inference/diffusion_device.py b/studio/backend/core/inference/diffusion_device.pyindex 127b041a0eb..f95deda96c5 100644--- a/studio/backend/core/inference/diffusion_device.py+++ b/studio/backend/core/inference/diffusion_device.py@@ -524,6 +524,28 @@ def smi_free_total_mib(ordinal: int) -> tuple[Optional[int], Optional[int]]:return None, None+def smi_util_pct(ordinal: int) -> Optional[float]:+ """nvidia-smi utilization.gpu (percent) of torch ordinal ``ordinal``, without a CUDA context; None wherever+ :func:`smi_free_total_mib` would not trust the rows. Never raises."""+ try:+ from utils.hardware import hardware as hw++ if hw.IS_ROCM or hw._cuda_instance_ids_active() or not hw._cuda_order_matches_smi():+ return None+ visible = hw.get_parent_visible_gpu_ids()+ if not 0 <= int(ordinal) < len(visible):+ return None+ index = visible[int(ordinal)]+ result = hw._smi_visible_utilization(hw._get_parent_visible_gpu_spec())+ for device in (result or {}).get("devices", []):+ if device.get("index") == index:+ util = device.get("gpu_utilization_pct")+ return None if util is None else float(util)+ except Exception: # noqa: BLE001 -- unknown utilisation: the memory test alone decides+ pass+ return None++def auto_cuda_ranking_possible_cached() -> Optional[bool]:"""``auto_cuda_ranking_possible`` when it can be answered from state already in memory, else None.diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.pyindex 2226e640c00..5b397dafeee 100644--- a/studio/backend/core/inference/diffusion_multigpu.py+++ b/studio/backend/core/inference/diffusion_multigpu.py@@ -68,13 +68,71 @@ def automatic_cfg_parallel_off() -> bool:)+# ... and computes at most this much (nvidia-smi utilization.gpu, percent): a card running another job is not lent.+AUTO_CFG_PARALLEL_IDLE_UTIL_PCT = 5.0++def _idle_card(probe: Any) -> bool:free, total = getattr(probe, "free_mib", None), getattr(probe, "total_mib", None)if free is None or total is None:return False+ util = getattr(probe, "util_pct", None)+ if util is not None and float(util) > AUTO_CFG_PARALLEL_IDLE_UTIL_PCT:+ return Falsereturn int(total) - int(free) <= AUTO_CFG_PARALLEL_IDLE_USED_MIB+def automatic_partner(+ primary: Any,+ cards: Sequence[Any],+ need_mib: int,+ *,+ p2p: Optional[dict[int, bool]] = None,+) -> tuple[Optional[int], str]:+ """The card Automatic lends a load's replica to, from ``cards`` (DeviceProbe-like: ordinal, name, total_mib,+ free_mib, util_pct), or None and the reason. Pure: no device is touched.++ One partner per load, on any number of cards: CFG-parallel and the batch split each need exactly one second+ copy, and a third copy would have no second call to run (a step has at most two guidance branches, and a batch is+ cut in two). The cards left over stay free for another load (keep multiple models loaded) or another app.++ A card is a candidate only when it is (in this order of rejection):+ - not the primary;+ - the same card model as the primary (same kernels, so the branches agree and neither card waits on a slower+ one; a mixed pair such as a 4090 with a 3060 is never paired automatically, ``force`` overrides);+ - idle: at most ``AUTO_CFG_PARALLEL_IDLE_USED_MIB`` in use and at most ``AUTO_CFG_PARALLEL_IDLE_UTIL_PCT``+ utilisation (another process's work is never slowed and its memory never taken);+ - able to hold the replica plus its reserve.+ Among candidates: the most usable free memory, then a peer-to-peer link to the primary, then the lowest ordinal.+ A static rule, not a trial: on identical idle cards the measured gains are 1.46x to 1.79x (well beyond A/A)."""+ p2p = p2p or {}+ pidx = getattr(primary, "ordinal", None)+ pname = getattr(primary, "name", None)+ rejected: dict[str, list[int]] = {}+ fits: list[tuple[int, int, int]] = []+ for card in cards:+ o = int(card.ordinal)+ if o == pidx:+ continue+ if not pname or card.name != pname:+ rejected.setdefault("a different card model", []).append(o)+ continue+ if not _idle_card(card):+ rejected.setdefault("busy", []).append(o)+ continue+ free = int(card.free_mib)+ usable = free - _replica_reserve_mib(free, card.total_mib)+ if usable < int(need_mib):+ rejected.setdefault(f"short of the {int(need_mib)} MiB replica", []).append(o)+ continue+ fits.append((usable, 1 if p2p.get(o) else 0, -o))+ if fits:+ return -max(fits)[2], "idle card of the same model"+ if not rejected:+ return None, "no other card"+ return None, "; ".join(f"cuda:{','.join(map(str, v))} {k}" for k, v in rejected.items())++def cfg_parallel_mode() -> str:"""``off`` / ``auto`` (default) / ``force`` (also across different card models)."""if multigpu_mode() == "off":@@ -265,6 +323,7 @@ class DeviceProbe:name: strtotal_mib: Optional[int]free_mib: Optional[int]+ util_pct: Optional[float] = None_PROBE_LOCK = threading.Lock()@@ -303,10 +362,29 @@ def probe_devices(ordinals: Sequence[int]) -> dict[int, DeviceProbe]:out: dict[int, DeviceProbe] = {}for o in ords:free, total = _free_total_mib(o)- out[o] = DeviceProbe(ordinal = o, name = _NAMES.get(o, ""), total_mib = total, free_mib = free)+ out[o] = DeviceProbe(+ ordinal = o, name = _NAMES.get(o, ""), total_mib = total, free_mib = free, util_pct = _util_pct(o)+ )return out+def _util_pct(ordinal: int) -> Optional[float]:+ """nvidia-smi utilisation of a card an automatic load may borrow; None elsewhere (unknown counts as idle)."""+ selection = _SELECTION.get()+ if selection is None or not selection.automatic or int(ordinal) == selection.primary:+ return None+ return _smi_util_pct(ordinal)+++def _smi_util_pct(ordinal: int) -> Optional[float]:+ """nvidia-smi utilisation of ``ordinal`` (no CUDA context), read outside any load scope; None when unknown."""+ try:+ from .diffusion_device import smi_util_pct+ return smi_util_pct(int(ordinal))+ except Exception: # noqa: BLE001+ return None++def best_secondary(selection: MultiGpuSelection,probes: Optional[dict[int, DeviceProbe]] = None,@@ -2474,7 +2552,11 @@ class CfgParallelRouter:"kv_cache_declined": 0,"kv_prefill_primary_calls": 0,"replica_failures": 0,+ "batch_splits": 0,+ "batch_split_skip": None,}+ # the last render ran one call per step (no guidance branches): a batch can split from its first step+ self.last_render_single = False# source prefix-KV cache id -> (source cache, the tensors it held when copied, the replica's copy)self.kv_mirrors: dict[int, tuple[Any, list, Any]] = {}self.kv_declined: dict[int, tuple[Any, list]] = {}@@ -2494,6 +2576,8 @@ class CfgParallelRouter:self.warm_primary: set = set()self.warm_replica: set = set()self._pair_job: Optional[dict] = None+ # why the denoiser's layers scale activations per call (a split batch would change them), read once+ self._split_scaled: Optional[tuple] = Nonedef describe(self) -> dict[str, Any]:return {@@ -2508,8 +2592,14 @@ class CfgParallelRouter:def disable(self, reason: str) -> None:if self.disabled_reason is None:self.disabled_reason = reason- if reason.startswith("replica "):+ if (+ reason.startswith("replica ")+ or "no longer idle" in reason+ or "carries hooks" in reason+ ):self.stats["replica_failures"] += 1+ # the load's CFG batching lever takes over after this render (end_cfg_render), not unbatched branches+ self.fallback_pending = getattr(self, "fallback", None) is not Noneif self.logger is not None:self.logger.warning("diffusion.multigpu: CFG-parallel disabled (%s); one card from here", reason@@ -2544,6 +2634,7 @@ class CfgParallelRouter:self.prev_latent = Noneself.template = Noneself.b0_leaves = {}+ self.last_render_single = self.singles >= 1 and not self.cfg_seenself.branch = 0# the next render shows its own guidance shape: no speculative branch before its first odd callself.cfg_seen = False@@ -2613,6 +2704,15 @@ class CfgParallelRouter:self._prefetch(args, kwargs)sig = _call_signature(args, kwargs)self._launch_prediction(latent, sig)+ if (+ self.branch == 0+ and not self.cfg_seen+ and (self.singles >= 1 or self.last_render_single)+ and self.disabled_reason is None+ ):+ out = self._batch_split(latent, args, kwargs)+ if out is not None:+ return outprefill = self.branch % 2 == 1 and _is_prefill(kwargs)if (self.branch % 2 == 1@@ -2665,17 +2765,79 @@ class CfgParallelRouter:self.stats["primary_calls"] += 1return self._primary_noting(sig, args, kwargs)+ def _batch_split(self, latent: Any, args: tuple, kwargs: dict) -> Any:+ """A step without guidance branches (a distilled model, or both branches batched into one call) whose batch is+ even: the first half runs on the source, the second on the replica at the same time. Only for denoiser classes+ whose every batched input is known (``_DIT_BATCH_SPLIT_KWARGS``); anything else, an odd batch, or the kill+ switch keeps the call whole. None = not split (the caller runs it whole)."""+ torch = _torch()+ module = self.module_ref()+ allowed = _DIT_BATCH_SPLIT_KWARGS.get(type(module).__name__) if module is not None else None+ if allowed is None or _batch_split_disabled() or torch.compiler.is_compiling():+ return None+ if getattr(module, "_compiled_call_impl", None) is not None:+ return self._skip_split("denoiser is compiled whole")+ n = latent.shape[0] if isinstance(latent, torch.Tensor) and latent.dim() >= 1 else 0+ if n < 2 or n % 2:+ return None+ if args:+ return self._skip_split("positional inputs")+ extra = sorted(+ k for k, v in kwargs.items() if k not in allowed and v is not None and v is not False+ )+ if extra:+ return self._skip_split(f"unknown inputs {extra}")+ if kwargs.get("joint_attention_kwargs"):+ return self._skip_split("attention kwargs")+ if self._split_scaled is None:+ from .diffusion_cfg_batch import per_call_scaled+ self._split_scaled = (per_call_scaled(module),)+ if self._split_scaled[0] is not None:+ # each half would take its own activation amax (dynamic NVFP4): not the one-card computation+ return self._skip_split(f"per-call activation scaling ({self._split_scaled[0]})")+ try:+ (a0, k0), (a1, k1) = [+ (_split_batch(args, n, h), _split_batch(kwargs, n, h)) for h in (0, 1)+ ]+ except TypeError as exc:+ return self._skip_split(f"unsplittable input ({exc})")+ # inside the denoiser's own call: its root hooks already wrap the whole batch, so run_pair need not refuse them+ res = self.run_pair(lambda: self._primary_noting(None, a0, k0), a1, k1, inside_call = True)+ if res is None:+ self._skip_split(f"pair not run ({self.disabled_reason or 'replica unavailable'})")+ # run_pair forgets the step: keep this one's latent so the next call is read as a new step+ self.prev_latent = latent+ self.branch = 0+ if res is None:+ return None+ first, second = res+ if second is None:+ second = self._primary(*a1, **k1)+ self.stats["primary_calls"] += 1+ self.stats["batch_splits"] += 1+ return _join_batch(first, second)++ def _skip_split(self, reason: str) -> None:+ self.stats["batch_split_skip"] = reason+ return None+def run_pair(- self, primary_call: Callable[[], Any], args: tuple, kwargs: dict+ self,+ primary_call: Callable[[], Any],+ args: tuple,+ kwargs: dict,+ *,+ inside_call: bool = False,) -> Optional[tuple]:"""Second half on the replica, ``primary_call`` on the source. ``(first, second)``; None = run both on source;- ``second`` None = replica failed."""+ ``second`` None = replica failed. ``inside_call``: called from within the denoiser's own ``__call__`` (batch+ split), whose root hooks already ran around the whole call."""if self.disabled_reason is not None or _background_compile_call():return Nonemodule = self.module_ref()if module is None or _holds_opaque_tensors((args, kwargs)):return None- if any(getattr(module, attr, None) for attr in _ROOT_HOOK_DICTS):+ if not inside_call and any(getattr(module, attr, None) for attr in _ROOT_HOOK_DICTS):return Noneself._drop_pending()self.template = None@@ -2908,13 +3070,22 @@ class CfgParallelRouter:t.numel() * t.element_size() for t in (*module.parameters(), *module.buffers())) // (1 << 20)free, total = self._secondary_free_total_mib()- if getattr(self, "automatic_idle_only", False) and not _idle_card(- DeviceProbe(ordinal = self.secondary.index, name = "", total_mib = total, free_mib = free)- ):- # Automatic borrowed this card because it was idle at load; something else took it since- raise RuntimeError(- f"{self.secondary} is no longer idle ({free} of {total} MiB free)"- )+ if getattr(self, "automatic_idle_only", False):+ # Built lazily during generation, after the load's selection scope ended: read the card directly.+ util = _smi_util_pct(self.secondary.index)+ if not _idle_card(+ DeviceProbe(+ ordinal = self.secondary.index,+ name = "",+ total_mib = total,+ free_mib = free,+ util_pct = util,+ )+ ):+ # Automatic borrowed this card because it was idle at load; something else took it since+ raise RuntimeError(+ f"{self.secondary} is no longer idle ({free} of {total} MiB free, {util}% busy)"+ )reserve = _replica_reserve_mib(free, total)if free is not None and need_mib + reserve > free:raise RuntimeError(@@ -3178,6 +3349,42 @@ class UnetCfgParallelRouter(CfgParallelRouter):return _join_batch(first, second)+# DiT classes whose batch may be cut along dim 0 (every per-sample input is a dim-0 tensor; ids, when unbatched, keep+# a leading size that is the token count, never the batch). Z-Image passes per-sample lists and has its own split.+_DIT_BATCH_SPLIT_KWARGS = {+ "FluxTransformer2DModel": frozenset(+ {+ "hidden_states",+ "encoder_hidden_states",+ "pooled_projections",+ "timestep",+ "img_ids",+ "txt_ids",+ "guidance",+ "joint_attention_kwargs",+ "return_dict",+ }+ ),+ "Flux2Transformer2DModel": frozenset(+ {+ "hidden_states",+ "encoder_hidden_states",+ "timestep",+ "img_ids",+ "txt_ids",+ "guidance",+ "joint_attention_kwargs",+ "return_dict",+ }+ ),+}+BATCH_SPLIT_ENV = "UNSLOTH_DIFFUSION_BATCH_SPLIT"+++def _batch_split_disabled() -> bool:+ return (os.environ.get(BATCH_SPLIT_ENV) or "").strip().lower() in ("0", "off", "false", "no")++_CFG_ROUTERS: "weakref.WeakKeyDictionary[Any, CfgParallelRouter]" = weakref.WeakKeyDictionary()_CFG_DECLINES: "weakref.WeakKeyDictionary[Any, str]" = weakref.WeakKeyDictionary()@@ -3281,9 +3488,10 @@ def install_cfg_parallel(offload_policy: str,logger: Any = None,) -> Optional[str]:- """Arm CFG-parallel on ``pipe.transformer`` when a secondary card can hold a replica. The replica is built on the- first step that shows two branches, so a guidance-distilled model never pays for it. Returns the decline reason or- None when armed."""+ """Arm CFG-parallel on ``pipe.transformer`` (or a U-Net) when a secondary card can hold a replica. The replica is+ built on the first step that shows two branches, or, for a FLUX.1 / FLUX.2 denoiser, the first step of a render+ without branches whose batch is even (batch split): a distilled model rendering one image never pays for it.+ Automatic placement lends one card per load (:func:`automatic_partner`). Returns the decline reason or None."""selection = current_selection()reason = cfg_parallel_decline(pipe, offload_policy = offload_policy, selection = selection)if reason is None:@@ -3299,22 +3507,41 @@ def install_cfg_parallel(]candidates = same if cfg_parallel_mode() != "force" else list(selection.secondaries)automatic = selection.automatic and cfg_parallel_mode() != "force"- if automatic:- # nothing else may live on a card Automatic borrows for a replica- candidates = [o for o in candidates if _idle_card(probes.get(o))]+ auto_reason = Nonetry:placed = ((_PLACEMENTS.get(pipe) or {}).get("placement") or {}).values()except TypeError:placed = ()occupied = {str(d) for d in placed} - {str(primary)}+ if automatic:+ # nothing else may live on a card Automatic borrows for a replica (busy: memory in use or computing)+ need = sum(+ t.numel() * t.element_size() for t in (*denoiser.parameters(), *denoiser.buffers())+ ) // (1 << 20)+ pick, auto_reason = automatic_partner(+ probes.get(primary.index) or DeviceProbe(primary.index, "", None, None),+ # a card holding the split's components cannot take the replica: never the one Automatic lends+ [+ probes[o]+ for o in selection.secondaries+ if probes.get(o) is not None+ and probes[o].free_mib is not None+ and f"cuda:{o}" not in occupied+ ],+ need,+ )+ candidates = [o for o in candidates if _idle_card(probes.get(o))]+ if pick is not None:+ candidates = [pick]if occupied:candidates = [o for o in candidates if f"cuda:{o}" not in occupied]if not candidates and occupied:reason = f"the only replica card ({', '.join(sorted(occupied))}) holds the split's components"elif not candidates and automatic and same:reason = (- f"automatic GPU placement: no idle card for a replica (more than "- f"{AUTO_CFG_PARALLEL_IDLE_USED_MIB} MiB in use; select several cards or set {CFG_PARALLEL_ENV}=force)"+ f"automatic GPU placement: no idle card for a replica ({auto_reason}; idle = at most "+ f"{AUTO_CFG_PARALLEL_IDLE_USED_MIB} MiB in use and {AUTO_CFG_PARALLEL_IDLE_UTIL_PCT:g}% busy; "+ f"select several cards or set {CFG_PARALLEL_ENV}=force)")elif not candidates:reason = "secondary card is a different model (bit-identity needs the same kernels)"@@ -3360,7 +3587,8 @@ def install_cfg_parallel(denoiser._unsloth_cfg_router = routerif logger is not None:logger.info(- "diffusion.multigpu: CFG-parallel armed (replica on cuda:%s when guidance runs two branches%s)",+ "diffusion.multigpu: CFG-parallel armed (replica on cuda:%s when guidance runs two branches or"+ " an even batch splits%s)",best,"; U-Net batch split" if router_cls is UnetCfgParallelRouter else "",)@@ -3397,6 +3625,62 @@ def invalidate_cfg_replica(return True+_ADAPTER_SCALE_ATTRS = ("scaling", "_active_adapter", "_disable_adapters")+++def mirror_cfg_replica_adapter_scales(pipe: Any, logger: Any = None) -> bool:+ """After a LoRA weight-only change (``set_adapters`` on the same adapter set), copy each adapter layer's scales+ and active-adapter state onto the CFG-parallel replica instead of dropping it. True when mirrored (the replica now+ computes what the source does); False when there was nothing to mirror or the layers do not line up, in which case+ the caller drops the replica as before."""+ try:+ router = _CFG_ROUTERS.get(pipe) if pipe is not None else None+ except TypeError:+ return False+ if router is None or router.replica is None:+ return False+ module = router.module_ref()+ if module is None:+ return False+ src = [+ (n, m) for n, m in module.named_modules() if isinstance(getattr(m, "scaling", None), dict)+ ]+ dst = dict(+ (n, m)+ for n, m in router.replica.named_modules()+ if isinstance(getattr(m, "scaling", None), dict)+ )+ if not src or len(src) != len(dst):+ return False+ for name, layer in src:+ copy_layer = dst.get(name)+ if copy_layer is None or set(copy_layer.scaling) != set(layer.scaling):+ return False # a different adapter set: only a rebuild is right+ for name, layer in src:+ copy_layer = dst[name]+ for attr in _ADAPTER_SCALE_ATTRS:+ if attr in layer.__dict__:+ value = layer.__dict__[attr]+ copy_layer.__dict__[attr] = (+ dict(value) if isinstance(value, dict) else copy.copy(value)+ )+ try:+ # the fingerprint covers adapter scales: record the new ones as the replica's, else the next step rebuilds it+ router.fingerprint = weights_fingerprint(module)+ except Exception: # noqa: BLE001 - unverifiable: drop the replica as before+ return False+ # Python-valued scales are guards of a compiled region: both sides may recompile, so they warm one at a time again+ router.warm_primary.clear()+ router.warm_replica.clear()+ router.stats["adapter_scale_mirrors"] = router.stats.get("adapter_scale_mirrors", 0) + 1+ if logger is not None:+ logger.info(+ "diffusion.multigpu: CFG-parallel replica kept; LoRA scales mirrored onto it (%d layers)",+ len(src),+ )+ return True++def _router_slot(module: Any, router: Any) -> Any:"""``module`` when ``router`` is its forward, the outer layer (static step skip) whose inner it is, else None."""slot = module.__dict__.get("forward")@@ -3445,6 +3729,38 @@ def end_cfg_render(pipe: Any) -> None:returnif router is not None:router.end_render()+ if getattr(router, "fallback_pending", False):+ # The replica failed at render time: hand the denoiser to the fallback (CFG batching, #16261) between+ # renders, never inside one. The render that failed finished on the source.+ fallback, router.fallback, router.fallback_pending = router.fallback, None, False+ reason = router.disabled_reason+ uninstall_cfg_parallel(pipe)+ try:+ result = fallback(pipe)+ except Exception as exc: # noqa: BLE001 - an optional lever: one card stands+ result = f"{type(exc).__name__}: {exc}"+ if router.logger is not None:+ router.logger.info(+ "diffusion.multigpu: CFG-parallel off after a render-time replica failure (%s); CFG batching %s",+ reason,+ "armed" if result is None else f"not armed ({result})",+ )+++def set_cfg_parallel_fallback(pipe: Any, fallback: Callable[[Any], Optional[str]]) -> bool:+ """Register the lever that replaces CFG-parallel when its replica fails at render time (CFG batching): called once+ with the pipeline, after ``uninstall_cfg_parallel``, between renders; returns its decline reason or None when armed.+ It must not hold the pipeline itself (the router is the value of a weak-keyed map on it, so that would keep a+ rolled-back load alive). True when a router was armed to carry it."""+ try:+ router = _CFG_ROUTERS.get(pipe) if pipe is not None else None+ except TypeError:+ return False+ if router is None:+ return False+ router.fallback = fallback+ router.fallback_pending = False+ return Truedef release_cfg_prefix_kv(pipe: Any) -> None:diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 2495f4b3999..2c86fa8d580 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -125,6 +125,7 @@ from .diffusion_multigpu import (is_split as multigpu_is_split,placement_status as multigpu_placement_status,refine_plan_for_multigpu,+ set_cfg_parallel_fallback,uninstall_cfg_parallel,with_load_selection,)@@ -10595,6 +10596,18 @@ class VideoBackend:transformer_quant = transformer_quant_engaged,logger = logger,)+ # a render-time replica failure hands the denoiser to CFG batching from the next render+ set_cfg_parallel_fallback(+ pipe,+ # called with the pipeline: capturing it here would keep a rolled-back load alive+ functools.partial(+ install_cfg_batch,+ offload_policy = offload_policy,+ speed_mode = speed_mode,+ transformer_quant = transformer_quant_engaged,+ logger = logger,+ ),+ )# Opt-in (UNSLOTH_DIFFUSION_BG_COMPILE=1): off by default so the same seed twice repeats.from . import diffusion_bg_compile as bg_compilediff --git a/studio/backend/tests/test_diffusion_auto_multigpu_policy.py b/studio/backend/tests/test_diffusion_auto_multigpu_policy.pynew file mode 100644index 00000000000..fd032927ca7--- /dev/null+++ b/studio/backend/tests/test_diffusion_auto_multigpu_policy.py@@ -0,0 +1,520 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Automatic multi-GPU policy: which card a load borrows (pure decision table over 2-8 cards) and the batch split of+distilled DiTs (FLUX.1 / FLUX.2) across the pair."""++import pytest++torch = pytest.importorskip("torch")++from core.inference import diffusion_multigpu as mg # noqa: E402++T4 = "Tesla T4"+TOTAL = 15360+++def card(+ o,+ name = T4,+ used = 400,+ util = 0.0,+ total = TOTAL,+):+ return mg.DeviceProbe(+ ordinal = o, name = name, total_mib = total, free_mib = total - used, util_pct = util+ )+++NEED = 6000+++ "cards, expect, why",+ [+ # two identical idle cards: the other one+ ([card(0), card(1)], 1, "idle card"),+ # four cards: the idle one with the most free memory; the rest stay free for other loads+ ([card(0), card(1, used = 900), card(2, used = 500), card(3, used = 700)], 2, "idle card"),+ # busy by memory (another process holds 2 GiB) or by compute (util above 5%): skipped+ ([card(0), card(1, used = 2048), card(2, util = 40.0), card(3)], 3, "idle card"),+ # a different model (4090 + 3060 style) is never paired automatically+ ([card(0, name = "RTX 4090"), card(1, name = "RTX 3060")], None, "a different card model"),+ # same model but every other card busy+ ([card(0), card(1, used = 3000), card(2, util = 90.0)], None, "busy"),+ # same model, idle, but the replica does not fit+ ([card(0, total = 6144), card(1, total = 6144, used = 400)], None, "short of the"),+ # only the primary+ ([card(0)], None, "no other card"),+ # unknown utilisation counts as idle (memory still decides)+ ([card(0), card(1, util = None)], 1, "idle card"),+ ],+)+def test_automatic_partner_decision_table(cards, expect, why):+ pick, reason = mg.automatic_partner(cards[0], cards, NEED)+ assert pick == expect+ assert why in reason+++def test_automatic_partner_prefers_a_peer_link_on_a_tie_then_the_lowest_ordinal():+ cards = [card(0), card(1), card(2), card(3)]+ assert mg.automatic_partner(cards[0], cards, NEED)[0] == 1+ assert mg.automatic_partner(cards[0], cards, NEED, p2p = {3: True})[0] == 3+++def test_automatic_partner_eight_cards_lends_exactly_one():+ cards = [card(o, used = 400 + 10 * o) for o in range(8)]+ pick, _ = mg.automatic_partner(cards[3], cards, NEED)+ assert (+ pick == 0+ ) # most free among the other seven; one replica per load whatever the card count+++def test_idle_card_requires_low_memory_and_low_utilisation():+ assert mg._idle_card(card(1))+ assert not mg._idle_card(card(1, used = 2000))+ assert not mg._idle_card(card(1, util = mg.AUTO_CFG_PARALLEL_IDLE_UTIL_PCT + 1))+ assert mg._idle_card(card(1, util = mg.AUTO_CFG_PARALLEL_IDLE_UTIL_PCT))+++class FluxTransformer2DModel(torch.nn.Module):+ """Named like diffusers' FLUX.1 class: the batch split keys on the class name."""++ def __init__(self):+ super().__init__()+ self.x = torch.nn.Linear(8, 8)+ self.t = torch.nn.Linear(6, 8)+ self.calls = []++ def forward(+ self,+ hidden_states,+ encoder_hidden_states = None,+ pooled_projections = None,+ timestep = None,+ img_ids = None,+ txt_ids = None,+ guidance = None,+ joint_attention_kwargs = None,+ return_dict = True,+ **extra,+ ):+ self.calls.append(int(hidden_states.shape[0]))+ h = self.x(hidden_states) * timestep[:, None, None] * guidance[:, None, None]+ h = (+ h+ + self.t(encoder_hidden_states).mean(1, keepdim = True)+ + pooled_projections[:, None, :8]+ )+ h = h + img_ids.float().mean() + txt_ids.float().mean()+ for value in extra.values():+ if isinstance(value, torch.Tensor):+ h = h + value.sum()+ return (h,) if not return_dict else type("Out", (), {"sample": h})()+++class OtherTransformer(FluxTransformer2DModel):+ pass+++def _router(model):+ built = []++ def factory():+ r = mg.build_replica(model, torch.device("cpu"))+ built.append(r)+ return r++ router = mg.CfgParallelRouter(model, primary = "cpu", secondary = "cpu", replica_factory = factory)+ model.forward = router+ return router, built+++def _flux_loop(model, batch, steps, **extra):+ g = torch.Generator().manual_seed(5)+ latents = torch.randn(batch, 16, 8, generator = g)+ emb = torch.randn(batch, 7, 6, generator = g)+ pooled = torch.randn(batch, 12, generator = g)+ img_ids = torch.randn(16, 3, generator = g) # unbatched: leading size is the token count+ txt_ids = torch.zeros(7, 3)+ for i in range(steps):+ t = torch.full((batch,), 1.0 - i / steps)+ out = model(+ hidden_states = latents,+ encoder_hidden_states = emb,+ pooled_projections = pooled,+ timestep = t,+ img_ids = img_ids,+ txt_ids = txt_ids,+ guidance = torch.full((batch,), 3.5),+ return_dict = False,+ **extra,+ )[0]+ latents = latents - 0.1 * out+ return latents+++def _reference(cls, batch, steps):+ torch.manual_seed(0)+ model = cls()+ return model, _flux_loop(model, batch, steps)+++def test_distilled_flux_batch_splits_from_the_second_step_and_matches_one_card():+ ref_model, ref = _reference(FluxTransformer2DModel, 4, 5)+ torch.manual_seed(0)+ model = FluxTransformer2DModel()+ router, built = _router(model)+ out = _flux_loop(model, 4, 5)+ torch.testing.assert_close(out, ref, rtol = 1e-5, atol = 1e-6)+ # step 1 learns there is one call per step (no guidance branch); steps 2-5 split 4 -> 2 + 2+ assert router.stats["batch_splits"] == 4+ assert len(built) == 1+ assert model.calls[0] == 4+ assert sorted(set(model.calls[1:])) == [2]+ assert (+ built[0].calls.count(2) == 4+ ) # (the copy carries the source's call log from before it was built)+++def test_next_render_splits_from_its_first_step():+ torch.manual_seed(0)+ model = FluxTransformer2DModel()+ router, _ = _router(model)+ _flux_loop(model, 2, 3)+ router.end_render()+ before = router.stats["batch_splits"]+ _flux_loop(model, 2, 3)+ assert router.stats["batch_splits"] - before == 3+++def test_odd_batch_unknown_class_unknown_input_and_kill_switch_stay_whole(monkeypatch):+ for cls, batch, extra in (+ (FluxTransformer2DModel, 3, {}),+ (OtherTransformer, 4, {}),+ (FluxTransformer2DModel, 4, {"controlnet_block_samples": torch.ones(1)}),+ ):+ torch.manual_seed(0)+ model = cls()+ router, built = _router(model)+ _flux_loop(model, batch, 3, **extra)+ assert router.stats["batch_splits"] == 0, (cls.__name__, batch, list(extra))+ assert not built+ monkeypatch.setenv(mg.BATCH_SPLIT_ENV, "0")+ torch.manual_seed(0)+ model = FluxTransformer2DModel()+ router, built = _router(model)+ _flux_loop(model, 4, 3)+ assert router.stats["batch_splits"] == 0 and not built+++def test_guided_render_keeps_cfg_routing_and_does_not_batch_split():+ """True CFG (two calls per step, same latent): the odd branch goes to the replica as before."""+ torch.manual_seed(0)+ model = FluxTransformer2DModel()+ router, _ = _router(model)+ g = torch.Generator().manual_seed(5)+ latents = torch.randn(2, 16, 8, generator = g)+ kw = dict(+ encoder_hidden_states = torch.randn(2, 7, 6, generator = g),+ pooled_projections = torch.randn(2, 12, generator = g),+ img_ids = torch.zeros(16, 3),+ txt_ids = torch.zeros(7, 3),+ guidance = torch.full((2,), 3.5),+ return_dict = False,+ )+ for i in range(4):+ t = torch.full((2,), 1.0 - i / 4)+ c = model(hidden_states = latents, timestep = t, **kw)[0]+ u = model(hidden_states = latents, timestep = t, **kw)[0]+ latents = latents - 0.1 * (u + 4.0 * (c - u))+ assert router.stats["batch_splits"] == 0+ assert router.stats["replica_calls"] >= 3+++def test_replica_failure_during_a_batch_split_recomputes_on_the_source():+ ref_model, ref = _reference(FluxTransformer2DModel, 2, 4)+ torch.manual_seed(0)+ model = FluxTransformer2DModel()++ class Boom(torch.nn.Module):+ def forward(self, *a, **k):+ raise RuntimeError("replica gone")++ router = mg.CfgParallelRouter(model, primary = "cpu", secondary = "cpu", replica_factory = Boom)+ model.forward = router+ out = _flux_loop(model, 2, 4)+ torch.testing.assert_close(out, ref, rtol = 1e-5, atol = 1e-6)+ assert router.disabled_reason is not None+++def test_batch_split_skips_are_recorded_and_stay_exact():+ """A foreign root hook cannot be mirrored onto a replica, and an unknown input cannot be split: both renders stay+ on the source, match one card, and say why."""+ ref_model, ref = _reference(FluxTransformer2DModel, 2, 3)+ torch.manual_seed(0)+ model = FluxTransformer2DModel()+ model.register_forward_pre_hook(lambda mod, args: None)+ router, built = _router(model)+ out = _flux_loop(model, 2, 3)+ torch.testing.assert_close(out, ref, rtol = 1e-5, atol = 1e-6)+ assert router.stats["batch_splits"] == 0 and "carries hooks" in router.stats["batch_split_skip"]+ torch.manual_seed(0)+ model = FluxTransformer2DModel()+ router, _ = _router(model)+ _flux_loop(model, 2, 3, controlnet_block_samples = torch.ones(1))+ assert "unknown inputs" in router.stats["batch_split_skip"]+++# --- LoRA weight-only change: mirror the scales onto the replica instead of dropping it ---------------------------+++class _Pipe:+ pass+++def _lora_model(seed = 0):+ peft = pytest.importorskip("peft")+ torch.manual_seed(seed)+ model = FluxTransformer2DModel()+ cfg = peft.LoraConfig(r = 4, lora_alpha = 4, target_modules = ["x", "t"], init_lora_weights = False)+ peft.inject_adapter_in_model(cfg, model, adapter_name = "style")+ return model+++def _set_scale(model, scale):+ from peft.tuners.lora import LoraLayer+ for mod in model.modules():+ if isinstance(mod, LoraLayer):+ mod.set_scale("style", scale)+++def _one_call(model):+ g = torch.Generator().manual_seed(9)+ x = torch.randn(2, 16, 8, generator = g)+ return model(+ hidden_states = x,+ encoder_hidden_states = torch.randn(2, 7, 6, generator = g),+ pooled_projections = torch.randn(2, 12, generator = g),+ timestep = torch.ones(2),+ img_ids = torch.zeros(16, 3),+ txt_ids = torch.zeros(7, 3),+ guidance = torch.ones(2),+ return_dict = False,+ )[0]+++def test_weight_only_lora_change_mirrors_scales_onto_the_replica_bitwise():+ model = _lora_model()+ router, built = _router(model)+ pipe = _Pipe()+ mg._CFG_ROUTERS[pipe] = router+ try:+ router._build_replica()+ replica = router.replica+ assert replica is not None+ _set_scale(model, 0.5)+ assert mg.mirror_cfg_replica_adapter_scales(pipe)+ assert router.replica is replica and router.stats["replica_rebuilds"] == 0+ with torch.no_grad():+ src = router.orig_forward(+ hidden_states = torch.ones(2, 16, 8),+ encoder_hidden_states = torch.ones(2, 7, 6),+ pooled_projections = torch.ones(2, 12),+ timestep = torch.ones(2),+ img_ids = torch.zeros(16, 3),+ txt_ids = torch.zeros(7, 3),+ guidance = torch.ones(2),+ return_dict = False,+ )[0]+ rep = replica(+ hidden_states = torch.ones(2, 16, 8),+ encoder_hidden_states = torch.ones(2, 7, 6),+ pooled_projections = torch.ones(2, 12),+ timestep = torch.ones(2),+ img_ids = torch.zeros(16, 3),+ txt_ids = torch.zeros(7, 3),+ guidance = torch.ones(2),+ return_dict = False,+ )[0]+ assert torch.equal(src, rep)+ fresh = _lora_model()+ _set_scale(fresh, 0.5)+ with torch.no_grad():+ assert torch.equal(_one_call(fresh), _one_call(router.replica))+ # a guided render after the change keeps the same replica (no rebuild) and matches a one-card fresh load+ with torch.no_grad():+ out = _cfg_steps(model)+ fresh_out = _cfg_steps(fresh)+ assert router.replica is replica and router.stats["replica_rebuilds"] == 0+ assert router.stats["replica_calls"] >= 2+ assert torch.equal(out, fresh_out)+ finally:+ mg._CFG_ROUTERS.pop(pipe, None)+++def test_a_changed_adapter_set_is_not_mirrored():+ peft = pytest.importorskip("peft")+ model = _lora_model()+ router, _ = _router(model)+ pipe = _Pipe()+ mg._CFG_ROUTERS[pipe] = router+ try:+ router._build_replica()+ cfg = peft.LoraConfig(r = 4, lora_alpha = 4, target_modules = ["x"], init_lora_weights = False)+ peft.inject_adapter_in_model(cfg, model, adapter_name = "second")+ assert not mg.mirror_cfg_replica_adapter_scales(pipe)+ assert not mg.mirror_cfg_replica_adapter_scales(_Pipe()) # no router: nothing to mirror+ finally:+ mg._CFG_ROUTERS.pop(pipe, None)+++# --- replica failure at render time: CFG batching takes over from the next render --------------------------------+++def _cfg_steps(model, steps = 3):+ g = torch.Generator().manual_seed(4)+ latents = torch.randn(1, 16, 8, generator = g)+ kw = dict(+ encoder_hidden_states = torch.randn(1, 7, 6, generator = g),+ pooled_projections = torch.randn(1, 12, generator = g),+ img_ids = torch.zeros(16, 3),+ txt_ids = torch.zeros(7, 3),+ guidance = torch.ones(1),+ return_dict = False,+ )+ for i in range(steps):+ t = torch.full((1,), 1.0 - i / steps)+ c = model(hidden_states = latents, timestep = t, **kw)[0]+ u = model(hidden_states = latents, timestep = t, **kw)[0]+ latents = latents - 0.1 * (u + 4.0 * (c - u))+ return latents+++def test_render_time_replica_failure_hands_over_to_cfg_batching_between_renders():+ torch.manual_seed(0)+ ref = _cfg_steps(FluxTransformer2DModel())+ torch.manual_seed(0)+ model = FluxTransformer2DModel()++ def boom():+ raise RuntimeError("out of memory on cuda:1")++ router = mg.CfgParallelRouter(model, primary = "cpu", secondary = "cpu", replica_factory = boom)+ model.forward = router+ pipe = _Pipe()+ mg._CFG_ROUTERS[pipe] = router+ calls = []+ assert mg.set_cfg_parallel_fallback(pipe, lambda p: calls.append("cfg_batch") or None)+ out = _cfg_steps(model)+ torch.testing.assert_close(+ out, ref, rtol = 1e-5, atol = 1e-6+ ) # the failing render finishes on the source+ assert router.disabled_reason.startswith("replica unavailable")+ assert calls == [] # never swapped inside a render+ mg.end_cfg_render(pipe)+ assert calls == ["cfg_batch"]+ assert (+ pipe not in mg._CFG_ROUTERS and "forward" not in model.__dict__+ ) # router gone, cfg_batch can wrap it+ mg.end_cfg_render(pipe)+ assert calls == ["cfg_batch"] # once+++def test_no_fallback_without_a_failure_and_none_registered():+ torch.manual_seed(0)+ model = FluxTransformer2DModel()+ router, _ = _router(model)+ pipe = _Pipe()+ mg._CFG_ROUTERS[pipe] = router+ calls = []+ mg.set_cfg_parallel_fallback(pipe, lambda p: calls.append(1))+ _cfg_steps(model)+ mg.end_cfg_render(pipe)+ assert calls == [] and mg._CFG_ROUTERS.get(pipe) is router+ mg._CFG_ROUTERS.pop(pipe, None)+ assert not mg.set_cfg_parallel_fallback(_Pipe(), lambda p: None)+++def test_weight_only_lora_path_mirrors_before_it_would_drop_the_replica():+ import inspect++ from core.inference import diffusion++ src = inspect.getsource(diffusion)+ branch = src.split("if _lora_weights_only_change(")[1].split("# Read before loading")[0]+ assert "mirror_cfg_replica_adapter_scales(pipe, logger)" in branch+ assert branch.index("mirror_cfg_replica_adapter_scales") < branch.index(+ "invalidate_cfg_replica"+ )+++def test_dynamic_nvfp4_layers_keep_the_batch_whole():+ """A layer that takes its activation scale from each call's amax (ComfyUI's dynamic NVFP4) would quantise each half+ against its own maximum: the split is refused and the render matches one card."""++ class ComfyNVFP4DynamicLinear(torch.nn.Linear):+ pass++ ref_model, ref = _reference(FluxTransformer2DModel, 2, 3)+ torch.manual_seed(0)+ model = FluxTransformer2DModel()+ model.q = ComfyNVFP4DynamicLinear(2, 2)+ router, built = _router(model)+ out = _flux_loop(model, 2, 3)+ torch.testing.assert_close(out, ref, rtol = 1e-5, atol = 1e-6)+ assert router.stats["batch_splits"] == 0+ assert "per-call activation scaling" in router.stats["batch_split_skip"]+++def test_mirroring_lora_scales_resets_the_warm_state():+ """Python-valued scales guard a compiled region, so after a mirror both sides may recompile: the next calls warm+ one at a time again instead of overlapping."""+ model = _lora_model()+ router, _ = _router(model)+ pipe = _Pipe()+ mg._CFG_ROUTERS[pipe] = router+ try:+ router._build_replica()+ router.warm_primary.add(("sig",))+ router.warm_replica.add(("sig",))+ _set_scale(model, 0.5)+ assert mg.mirror_cfg_replica_adapter_scales(pipe)+ assert not router.warm_primary and not router.warm_replica+ finally:+ mg._CFG_ROUTERS.pop(pipe, None)+++def test_the_registered_fallback_does_not_keep_the_pipeline_alive():+ """The router is the value of a weak-keyed map on the pipeline: a fallback that captured the pipeline would keep a+ load rolled back before publication (and its weights) alive. It is handed the pipeline when it runs instead."""+ import functools++ model = FluxTransformer2DModel()+ router, _ = _router(model)+ pipe = _Pipe()+ mg._CFG_ROUTERS[pipe] = router+ seen = []+ assert mg.set_cfg_parallel_fallback(+ pipe, functools.partial(lambda p, tag: seen.append((p, tag)), tag = "batch")+ )+ router.fallback_pending = True+ mg.end_cfg_render(pipe)+ assert seen == [(pipe, "batch")]+ # the image and video loads register a partial that leaves the pipeline to the call+ import ast+ from pathlib import Path++ backend = Path(__file__).resolve().parents[1] / "core" / "inference"+ for name in ("diffusion.py", "video.py"):+ tree = ast.parse((backend / name).read_text(encoding = "utf-8"))+ calls = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and getattr(node.func, "id", None) == "set_cfg_parallel_fallback"+ ]+ assert len(calls) == 1, name+ held = calls[0].args[1]+ assert isinstance(held, ast.Call) and ast.unparse(held.func) == "functools.partial", name+ assert [ast.unparse(a) for a in held.args] == ["install_cfg_batch"], namediff --git a/studio/backend/tests/test_diffusion_auto_placement.py b/studio/backend/tests/test_diffusion_auto_placement.pyindex 2da99bf3c50..c00cbf4f795 100644--- a/studio/backend/tests/test_diffusion_auto_placement.py+++ b/studio/backend/tests/test_diffusion_auto_placement.py@@ -269,6 +269,8 @@ def test_a_fits_one_card_uses_one_card_and_no_cfg_parallel(monkeypatch):assert p["summary"].startswith("placement: one card: everything resident on cuda:0")kinds = {r["kind"]: r["reason"] for r in p["rejected"]}assert kinds["companion_split"].startswith("not needed")+ # Automatic now borrows an idle card of the same model for CFG-parallel (every guided model that fits ran+ # 1.46-1.79x faster on 2x T4); the fake pipeline declines only because it has no denoiser moduleassert "no DiT denoiser" in kinds["cfg_parallel"]assert set(host.mem_get_info_calls) <= {0}@@ -290,6 +292,8 @@ def test_b_companion_split_puts_the_text_encoder_on_the_second_card(monkeypatch)assert d.plan.offload_policy == dm.OFFLOAD_NONE and d.plan.secondary_ordinal == 1assert "text_encoder" in d.plan.secondary_componentsassert d.plan.layer_split is None+ # Automatic now borrows an idle card of the same model for CFG-parallel (every guided model that fits ran+ # 1.46-1.79x faster on 2x T4); the fake pipeline declines only because it has no denoiser moduleassert d.cfg_parallel is not None and "no DiT denoiser" in d.cfg_parallelp = _placement(d)assert p["chosen"] == "companion_split"diff --git a/studio/backend/tests/test_diffusion_multigpu.py b/studio/backend/tests/test_diffusion_multigpu.pyindex 7c8a5a6282d..2c048205f91 100644--- a/studio/backend/tests/test_diffusion_multigpu.py+++ b/studio/backend/tests/test_diffusion_multigpu.py@@ -2806,3 +2806,35 @@ def test_warm_signature_keys_on_storage_offset_and_autocast():with torch.autocast("cpu", enabled = False, cache_enabled = False):assert mg._call_signature((base[:4],), {}) != aassert mg._call_signature((base[:4],), {}) == a+++def test_automatic_partner_skips_a_card_holding_the_splits_components(monkeypatch):+ """Three cards, Automatic: the idlest card holds a small text encoder of the split, so it cannot take the replica;+ the next idle card does (the occupied card is excluded before the partner is chosen, not after)."""++ class Pipe:+ transformer = _Dit()++ probes = {+ 0: mg.DeviceProbe(ordinal = 0, name = "B200", total_mib = 180000, free_mib = 170000, util_pct = 0.0),+ 1: mg.DeviceProbe(ordinal = 1, name = "B200", total_mib = 180000, free_mib = 179900, util_pct = 0.0),+ 2: mg.DeviceProbe(ordinal = 2, name = "B200", total_mib = 180000, free_mib = 179800, util_pct = 0.0),+ }+ monkeypatch.setattr(mg, "cfg_parallel_decline", lambda pipe, **kw: None)+ monkeypatch.setattr(mg, "_module_device", lambda m: torch.device("cuda", 0))+ monkeypatch.setattr(+ mg, "probe_devices", lambda ordinals, **kw: {o: probes[o] for o in ordinals}+ )+ pipe = Pipe()+ mg._PLACEMENTS[pipe] = {+ "placement": {"transformer": "cuda:0", "vae": "cuda:0", "text_encoder": "cuda:1"}+ }+ try:+ with mg.selection_scope(+ mg.MultiGpuSelection(primary = 0, secondaries = (1, 2), automatic = True)+ ):+ assert mg.install_cfg_parallel(pipe, offload_policy = "none") is None+ assert str(mg._CFG_ROUTERS[pipe].secondary) == "cuda:2"+ finally:+ mg.uninstall_cfg_parallel(pipe)+ mg._PLACEMENTS.pop(pipe, None)diff --git a/studio/backend/tests/test_diffusion_native_quant.py b/studio/backend/tests/test_diffusion_native_quant.pyindex c06aa0609fe..678fef585e9 100644--- a/studio/backend/tests/test_diffusion_native_quant.py+++ b/studio/backend/tests/test_diffusion_native_quant.py@@ -406,6 +406,17 @@ def test_int8_act_kill_switch_reads_only_zero(monkeypatch):def _block_torchao(monkeypatch):+ # peft caches is_torchao_available() per process: a True from an earlier test on this worker would send its torchao+ # LoRA dispatcher into the blocked import. Answer as peft does with torchao absent (monkeypatch restores it).+ try:+ import importlib+ importlib.import_module("peft.tuners.lora.torchao")+ except Exception: # noqa: BLE001 - no peft: nothing caches the answer+ pass+ for name in ("peft.import_utils", "peft.tuners.lora.torchao"):+ module = sys.modules.get(name)+ if module is not None and hasattr(module, "is_torchao_available"):+ monkeypatch.setattr(module, "is_torchao_available", lambda: False)# A None sys.modules entry makes any torchao import raise, proving the branch never reaches it.monkeypatch.setitem(sys.modules, "torchao", None)monkeypatch.setitem(sys.modules, "torchao.quantization", None)@@ -1257,3 +1268,18 @@ def test_fp8_codes_layer_matches_the_dequant_formula_eager_and_compiled(fmt):assert explained.graph_break_count == 0compiled = torch.compile(layer, fullgraph = True)assert torch.equal(compiled(x), layer(x))+++def test_blocked_torchao_holds_after_peft_cached_it_available(monkeypatch):+ """An earlier test on the same worker can leave peft's cached ``is_torchao_available()`` True; the blocked tests+ must still keep peft's torchao dispatcher off the import (it raised ``torchao.quantization halted`` in CI)."""+ peft = pytest.importorskip("peft")+ import peft.tuners.lora.torchao as peft_torchao++ monkeypatch.setattr(peft_torchao, "is_torchao_available", lambda: True)+ _block_torchao(monkeypatch)+ monkeypatch.setitem(+ sys.modules, "torchao.utils", None+ ) # newer peft's dispatcher imports this one instead+ model = _toy()+ peft.inject_adapter_in_model(peft.LoraConfig(r = 4, target_modules = ["to_q"]), model)diff --git a/studio/backend/tests/test_diffusion_unet_cfg_parallel.py b/studio/backend/tests/test_diffusion_unet_cfg_parallel.pyindex f762c39c416..a3e6427509e 100644--- a/studio/backend/tests/test_diffusion_unet_cfg_parallel.py+++ b/studio/backend/tests/test_diffusion_unet_cfg_parallel.py@@ -312,6 +312,21 @@ def test_automatic_replica_is_not_built_on_a_card_that_got_busy(monkeypatch):assert unet.calls[-1] == 2 # whole on the source from then on+def test_automatic_replica_is_not_built_on_a_card_another_job_keeps_busy(monkeypatch):+ # memory still free (under 1 GiB used), but another process computes on it: the build-time recheck refuses too+ unet = UNet2DConditionModel()+ router, replicas = _router(unet)+ router.automatic_idle_only = True+ monkeypatch.setattr(router, "_secondary_free_total_mib", lambda: (15000, 15360))+ # read at render time, outside the load's selection scope (where _util_pct answers None)+ monkeypatch.setattr(mg, "_smi_util_pct", lambda _o: 80.0)+ assert mg._SELECTION.get() is None+ lat = torch.randn(1, 4, 8, 8)+ _sdxl_loop(unet, lat, steps = 2)+ assert replicas == [] and "no longer idle" in (router.disabled_reason or "")+ assert "80.0% busy" in router.disabled_reason++def test_group_offloaded_denoiser_runs_cfg_parallel_from_its_onload_card(monkeypatch):from core.inference import diffusion_memory as dm