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 multi-GPU placement fixes and a placement decision in status (#14657)
Daniel Han94a1e3d35139
diff --git a/studio/backend/core/inference/diffusion_layer_split_plan.py b/studio/backend/core/inference/diffusion_layer_split_plan.pyindex 0c66d3ebbaa..886540404fc 100644--- a/studio/backend/core/inference/diffusion_layer_split_plan.py+++ b/studio/backend/core/inference/diffusion_layer_split_plan.py@@ -380,14 +380,22 @@ def plan_layer_split(return dataclasses.replace(split, reason = reason), reasonavailable = (sum(card_limits[o] - reserve[o] for o in cards)- - max(denoise, decode)+ - max(denoise, decode, encode if te_mib else 0)- (k - 1) * working)- shortfall = need_total - available+ # the text encoders can always stream from host memory, so they do not count against the cards+ shortfall = need_total - te_mib - availablebest_shortfall = shortfall if best_shortfall is None else min(best_shortfall, shortfall)+ shortfall_text = (+ f"short by about {best_shortfall} MiB"+ if best_shortfall is not None and best_shortfall > 0+ else "no cut of the blocks fits every card"+ )return None, (- f"layer split does not fit the selected cards ({need_total} MiB of weights, "- f"short by about {max(0, best_shortfall or 0)} MiB after the per-card reserves)"+ f"layer split does not fit the selected cards ({need_total - te_mib} MiB of denoiser and VAE weights with "+ f"the text encoders streamed, {shortfall_text} after the per-card reserves and "+ f"{max(denoise, decode, encode if te_mib else 0)} MiB "+ f"of activations on cuda:{primary})")diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex e8ee9cc48a7..033043575fe 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -1207,6 +1207,10 @@ def calibrated_image_activation()+DISCRETE_RESERVE_CAP_MIB = 4096+_ROCM_APU_POOL = "rocm_apu_pool"++def _reserve_mib(memory_kind: str, base: int) -> int:if memory_kind == METAL_WORKING_SET:# Only other apps' growth during the load: the working set already sits below RAM. At least as strict as@@ -1216,7 +1220,15 @@ def _reserve_mib(memory_kind: str, base: int) -> int:return max(2048, int(base * 0.20)) # OS + CPU share this poolif memory_kind == "system_memory":return max(1024, int(base * 0.10))- return max(2048, int(base * 0.10))+ if memory_kind == _ROCM_APU_POOL:+ # The amdgpu GTT pool of an APU whose host RAM already covers the OS: still shared with the CPU side, so it+ # keeps the uncapped 10%.+ return max(2048, int(base * 0.10))+ # A discrete card's reserve covers fragmentation and other tenants' growth, not the load's own activations (the+ # runtime headroom prices those). 10% of the TOTAL grew with the card: 17.8 GiB on a 178 GiB card, which refused+ # a resident or companion-split plan on a partly used big card with plenty free. Capped near ComfyUI's fixed+ # reserve (~1.2 GiB plus its activation estimate); cards up to 40 GiB keep 10% (the 2 GiB floor below 20 GiB).+ return max(2048, min(int(base * 0.10), DISCRETE_RESERVE_CAP_MIB))def _rocm_linux_apu_os_room_outside_pool(memory: DeviceMemory) -> bool:@@ -1243,7 +1255,7 @@ def _rocm_linux_apu_os_room_outside_pool(memory: DeviceMemory) -> bool:def _budget_reserve_kind(memory: DeviceMemory) -> str:if getattr(memory, "metal_working_set_mib", None) is not None:return METAL_WORKING_SET- return "discrete_vram" if _rocm_linux_apu_os_room_outside_pool(memory) else memory.memory_kind+ return _ROCM_APU_POOL if _rocm_linux_apu_os_room_outside_pool(memory) else memory.memory_kinddef _safe_device_budget_mib(memory: DeviceMemory) -> Optional[int]:diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.pyindex 284ebc2f1fc..27919a2b36f 100644--- a/studio/backend/core/inference/diffusion_multigpu.py+++ b/studio/backend/core/inference/diffusion_multigpu.py@@ -414,7 +414,42 @@ def plan_companion_split(return None-def choose_component_assignment([email protected](frozen = True)+class AssignmentTrial:+ """One companion assignment the planner tried: what moves, and each card's need against its resident limit."""++ moved: tuple[str, ...]+ moved_mib: int+ primary_need_mib: int+ primary_limit_mib: int+ secondary_need_mib: int+ secondary_limit_mib: int++ @property+ def fits(self) -> bool:+ return (+ self.primary_need_mib <= self.primary_limit_mib+ and self.secondary_need_mib <= self.secondary_limit_mib+ )++ def why_not(self, primary: int, secondary: int) -> str:+ moved = "+".join(self.moved)+ if self.primary_need_mib > self.primary_limit_mib:+ return (+ f"{moved} on cuda:{secondary}: cuda:{primary} still needs {_gib(self.primary_need_mib)} of "+ f"{_gib(self.primary_limit_mib)}"+ )+ return (+ f"{moved} on cuda:{secondary}: needs {_gib(self.secondary_need_mib)} there, "+ f"{_gib(self.secondary_limit_mib)} allowed"+ )+++def _gib(mib: Optional[int]) -> str:+ return "unknown" if mib is None else f"{int(mib) / 1024:.1f} GiB"+++def component_assignment_trials(sizes: dict[str, tuple[int, str]],*,headroom_mib: int,@@ -422,16 +457,15 @@ def choose_component_assignment(primary_limit_mib: int,secondary_limit_mib: int,move_denoisers: bool = True,-) -> Optional[tuple[str, ...]]:- """Names to place on the secondary so each card holds its share resident, or None. ``sizes`` maps component name- -> (MiB, role) with role 'dit' / 'text_encoder' / 'other'. A card running a denoiser or the VAE (any 'other'- component) is priced with the runtime headroom; a card holding only text encoders with an encoder forward's room.- Tried in order: every companion; the text encoders alone; the second denoiser; the second denoiser plus the- companions. The first denoiser always stays on the primary; ``move_denoisers=False`` (the secondary cannot run the- denoiser's attention backend) keeps every denoiser there."""+ encoders_only_limit_mib: Optional[int] = None,+) -> list[AssignmentTrial]:+ """Every assignment :func:`choose_component_assignment` tries, in its order, priced (the first that fits wins).+ ``encoders_only_limit_mib``: what a secondary holding nothing but text encoders may take (its free memory minus+ ComfyUI's per-card floor); such a card runs one encoder forward per prompt, so it is priced with the weights and+ an encoder forward's room instead of the base overhead and the 85% resident margin of a card that denoises."""dits = [n for n, (_m, r) in sizes.items() if r == "dit"]if not dits:- return None+ return []first = "transformer" if "transformer" in dits else dits[0]seconds = [n for n in dits if n != first]companions = [@@ -455,10 +489,59 @@ def choose_component_assignment(busy = any(sizes[n][1] != "text_encoder" for n in names)return weights + (headroom_mib if busy else TEXT_ENCODER_HEADROOM_MIB) + overhead_mib+ def secondary(moved: tuple[str, ...]) -> tuple[int, int]:+ standard = (need(list(moved)), int(secondary_limit_mib))+ if encoders_only_limit_mib is None or any(sizes[n][1] != "text_encoder" for n in moved):+ return standard+ encoders = (+ sum(sizes[n][0] for n in moved) + TEXT_ENCODER_HEADROOM_MIB,+ int(encoders_only_limit_mib),+ )+ return encoders if encoders[1] - encoders[0] > standard[1] - standard[0] else standard++ trials = []for moved in candidates:- on_primary = [n for n in sizes if n not in moved]- if need(on_primary) <= primary_limit_mib and need(list(moved)) <= secondary_limit_mib:- return moved+ sec_need, sec_limit = secondary(moved)+ trials.append(+ AssignmentTrial(+ moved = moved,+ moved_mib = sum(sizes[n][0] for n in moved),+ primary_need_mib = need([n for n in sizes if n not in moved]),+ primary_limit_mib = int(primary_limit_mib),+ secondary_need_mib = sec_need,+ secondary_limit_mib = sec_limit,+ )+ )+ return trials+++def choose_component_assignment(+ sizes: dict[str, tuple[int, str]],+ *,+ headroom_mib: int,+ overhead_mib: int,+ primary_limit_mib: int,+ secondary_limit_mib: int,+ move_denoisers: bool = True,+ encoders_only_limit_mib: Optional[int] = None,+) -> Optional[tuple[str, ...]]:+ """Names to place on the secondary so each card holds its share resident, or None. ``sizes`` maps component name+ -> (MiB, role) with role 'dit' / 'text_encoder' / 'other'. A card running a denoiser or the VAE (any 'other'+ component) is priced with the runtime headroom; a card holding only text encoders with an encoder forward's room.+ Tried in order: every companion; the text encoders alone; the second denoiser; the second denoiser plus the+ companions. The first denoiser always stays on the primary; ``move_denoisers=False`` (the secondary cannot run the+ denoiser's attention backend) keeps every denoiser there."""+ for trial in component_assignment_trials(+ sizes,+ headroom_mib = headroom_mib,+ overhead_mib = overhead_mib,+ primary_limit_mib = primary_limit_mib,+ secondary_limit_mib = secondary_limit_mib,+ move_denoisers = move_denoisers,+ encoders_only_limit_mib = encoders_only_limit_mib,+ ):+ if trial.fits:+ return trial.movedreturn None@@ -488,6 +571,88 @@ def _secondary_runs_denoiser(return False[email protected](frozen = True)+class PlacementCandidate:+ """One placement the automatic planner considered: ``kind`` is one of ``one_card`` (everything resident on the+ primary), ``companion_split``, ``layer_split``, ``offload`` (one card, streamed) or ``cfg_parallel``."""++ kind: str+ reason: str++[email protected](frozen = True)+class PlacementDecision:+ """What the multi-GPU refinement chose for a load under a multi-card selection, and why every other candidate+ was rejected. Recorded per pipeline; ``status()["multi_gpu"]["decision"]`` shows it (``"placement"`` there stays+ the companion split's component-to-device map). ``fallback_resident``: the one-card plan a split would fall back+ to keeps everything resident (a forced split of a model that fits one card)."""++ chosen: str+ summary: str+ primary: int+ automatic: bool+ rejected: tuple[PlacementCandidate, ...] = ()+ fallback_resident: bool = False++ def describe(self) -> dict[str, Any]:+ return {+ "chosen": self.chosen,+ "summary": self.summary,+ "primary": f"cuda:{self.primary}",+ "automatic": self.automatic,+ "rejected": [{"kind": c.kind, "reason": c.reason} for c in self.rejected],+ }+++_DECISIONS: "weakref.WeakKeyDictionary[Any, PlacementDecision]" = weakref.WeakKeyDictionary()+++def placement_decision(pipe: Any) -> Optional[PlacementDecision]:+ try:+ return _DECISIONS.get(pipe) if pipe is not None else None+ except TypeError:+ return None+++def _record_decision(+ pipe: Any,+ selection: MultiGpuSelection,+ chosen: str,+ summary: str,+ rejected: Sequence[PlacementCandidate] = (),+ *,+ fallback_resident: bool = False,+) -> None:+ with contextlib.suppress(TypeError):+ _DECISIONS[pipe] = PlacementDecision(+ chosen = chosen,+ summary = f"placement: {summary}",+ primary = int(selection.primary),+ automatic = bool(selection.automatic),+ rejected = tuple(rejected),+ fallback_resident = bool(fallback_resident),+ )+++def forget_placement_decision(pipe: Any) -> None:+ with contextlib.suppress(TypeError):+ _DECISIONS.pop(pipe, None)+++def _denoiser_mib(sizes: dict[str, tuple[int, str]]) -> int:+ return sum(m for m, role in sizes.values() if role == "dit")+++def _one_card_rejection(plan: Any, primary: int) -> PlacementCandidate:+ required = plan.estimates.get("resident_required_mib")+ budget = plan.estimates.get("safe_device_budget_mib")+ return PlacementCandidate(+ "one_card",+ f"everything resident on cuda:{primary} needs {_gib(required)}, {_gib(budget)} free after the reserve; "+ f"one card would use '{plan.offload_policy}'",+ )++def refine_plan_for_multigpu(pipe: Any,plan: Any,@@ -497,52 +662,96 @@ def refine_plan_for_multigpu(No-op without a selection, for explicit offload modes, a plan already resident (unless forced) or split, unified memoryor an unknown budget. When no component assignment fits, a layer split (diffusion_layer_split_plan) is tried before- keeping the offload plan. Returns the plan (a ``dataclasses.replace`` copy when it changed)."""+ keeping the offload plan. Returns the plan (a ``dataclasses.replace`` copy when it changed). Under a selection the+ decision and every rejected candidate are recorded for :func:`placement_status`."""selection = current_selection()if selection is None or plan is None:return plan- if (- getattr(plan, "secondary_ordinal", None) is not None- or getattr(plan, "layer_split", None) is not None- ):+ primary = int(selection.primary)++ def keep(chosen: str, summary: str, *rejected: PlacementCandidate) -> Any:+ fallback = getattr(plan, "fallback_plan", None)+ _record_decision(+ pipe,+ selection,+ chosen,+ summary,+ rejected,+ fallback_resident = getattr(fallback, "offload_policy", None) == "none",+ )return plan++ def one_card_plan(why: str) -> Any:+ if plan.offload_policy == "none":+ return keep("one_card", f"one card: everything resident on cuda:{primary} ({why})")+ return keep(+ "offload", f"one card with '{plan.offload_policy}' offload on cuda:{primary} ({why})"+ )++ if getattr(plan, "secondary_ordinal", None) is not None:+ return keep(+ "companion_split",+ f"companion split: {', '.join(plan.secondary_components or ('companions',))} on "+ f"cuda:{plan.secondary_ordinal}, the denoiser resident on cuda:{primary} (planned before the load)",+ )+ if getattr(plan, "layer_split", None) is not None:+ return keep("layer_split", f"layer split across {_cards(plan.layer_split.cards)}")from .diffusion_layer_split_plan import layer_split_mode, refine_plan_for_layer_splitlayer_force = layer_split_mode() == "force"if plan.offload_policy == "none" and multigpu_mode() != "force" and not layer_force:- return plan+ required = plan.estimates.get("resident_required_mib")+ budget = plan.estimates.get("safe_device_budget_mib")+ not_needed = f"not needed: the model fits cuda:{primary}"+ return keep(+ "one_card",+ f"one card: everything resident on cuda:{primary} (needs {_gib(required)}, {_gib(budget)} free after "+ "the reserve)",+ PlacementCandidate("companion_split", not_needed),+ PlacementCandidate("layer_split", not_needed),+ )if getattr(plan, "requested_mode", None) not in ("auto", "fast"):- return plan+ return one_card_plan(+ f"memory mode '{getattr(plan, 'requested_mode', None)}' was chosen explicitly"+ )if plan.estimates.get("explicit_cpu_offload"):- return plan+ return one_card_plan("CPU offload was requested explicitly")memory = plan.device_memoryif memory.is_unified or getattr(memory, "device", None) != "cuda":if memory.is_unified:from .diffusion_layer_split_plan import note_unified_primarynote_unified_primary(pipe, selection, logger)- return plan+ return one_card_plan("unified memory" if memory.is_unified else "not a CUDA card")budget = plan.estimates.get("safe_device_budget_mib")if budget is None:- return plan+ return one_card_plan(f"free memory of cuda:{primary} is unknown")from .diffusion_memory import _loaded_component_mibsizes = _loaded_component_mib(pipe)if not sizes:- return plan+ return one_card_plan("component sizes are unreadable")secondary = best_secondary(selection)if secondary is None:- return plan+ return one_card_plan("no second card")mode = getattr(plan, "requested_mode", None)sec_limit = secondary_resident_limit_mib(secondary, mode)if sec_limit is None:- return plan+ return one_card_plan(f"free memory of cuda:{secondary} is unknown")from .diffusion_memory import _fast_device_budget_mibprimary_limit = (_fast_device_budget_mib(memory) if mode == "fast" else int(int(budget) * _RESIDENT_FRACTION))if primary_limit is None:- return plan+ return one_card_plan(f"free memory of cuda:{primary} is unknown")+ from .diffusion_memory import plan_keeps_transformer_resident++ if mode != "fast" and plan.offload_policy != "none" and plan_keeps_transformer_resident(plan):+ # The one-card plan already holds the denoiser resident against the full budget and streams only the+ # encoders: moving companions off leaves the primary holding no more than that, so the 85% margin would+ # refuse a split that is lighter than the plan it replaces (the text encoder then streamed from host memory+ # beside an idle second card).+ primary_limit = max(int(primary_limit), int(budget))headroom = int(plan.estimates.get("measured_runtime_headroom_mib")or plan.estimates.get("calibrated_headroom_mib")@@ -550,9 +759,12 @@ def refine_plan_for_multigpu(or 0)overhead = int(plan.estimates.get("base_overhead_mib") or 0)+ rejected: list[PlacementCandidate] = []+ if plan.offload_policy != "none":+ rejected.append(_one_card_rejection(plan, primary))def layer_split_or_plan() -> Any:- return refine_plan_for_layer_split(+ refined = refine_plan_for_layer_split(pipe,plan,selection = selection,@@ -563,18 +775,76 @@ def refine_plan_for_multigpu(overhead_mib = overhead,logger = logger,)+ split = getattr(refined, "layer_split", None)+ if split is not None:+ _record_decision(+ pipe,+ selection,+ "layer_split",+ f"layer split: denoiser blocks across {_cards(split.cards)} (denoiser "+ f"{_gib(_denoiser_mib(sizes))} does not fit one card with its working memory)",+ rejected,+ fallback_resident = plan.offload_policy == "none",+ )+ return refined+ from .diffusion_layer_split_plan import (+ LAYER_SPLIT_ENV,+ engine_available,+ layer_split_status,+ plan_offloads_denoiser,+ )++ if layer_split_mode() == "off":+ declined = f"{LAYER_SPLIT_ENV}=0"+ elif not engine_available():+ declined = "the layer split engine is unavailable"+ elif not plan_offloads_denoiser(plan) and not layer_force:+ declined = f"not needed: the denoiser stays resident on cuda:{primary}"+ else:+ declined = (layer_split_status(pipe) or {}).get("declined") or "no split fits"+ rejected.append(PlacementCandidate("layer_split", str(declined)))+ if plan.offload_policy == "none":+ # a forced split of a model one card already holds: the plan returned is that resident one-card plan+ _record_decision(+ pipe,+ selection,+ "one_card",+ f"one card: everything resident on cuda:{primary} (no forced split fits)",+ rejected,+ )+ else:+ _record_decision(+ pipe,+ selection,+ "offload",+ f"one card with '{plan.offload_policy}' offload on cuda:{primary} (no split fits)",+ rejected,+ )+ return refinedif layer_force:return layer_split_or_plan()- moved = choose_component_assignment(+ move_denoisers = _secondary_runs_denoiser(pipe, selection, secondary, sizes, logger)+ trials = component_assignment_trials(sizes,headroom_mib = headroom,overhead_mib = overhead,primary_limit_mib = int(primary_limit),secondary_limit_mib = int(sec_limit),- move_denoisers = _secondary_runs_denoiser(pipe, selection, secondary, sizes, logger),+ move_denoisers = move_denoisers,+ encoders_only_limit_mib = encoder_card_limit_mib(secondary),)+ winner = next((t for t in trials if t.fits), None)+ moved = winner.moved if winner is not None else None+ for trial in trials:+ if trial is winner:+ break+ rejected.append(PlacementCandidate("companion_split", trial.why_not(primary, secondary)))if moved is None:+ if not trials:+ rejected.append(+ PlacementCandidate("companion_split", "no denoiser among the loaded components")+ )return layer_split_or_plan()reason = (f"multi-GPU (loaded sizes): {', '.join(moved)} on cuda:{secondary}, the rest resident on "@@ -582,6 +852,17 @@ def refine_plan_for_multigpu()if logger is not None:logger.info("diffusion.multigpu: %s", reason)+ on_primary = winner.primary_need_mib+ _record_decision(+ pipe,+ selection,+ "companion_split",+ f"companion split: {', '.join(moved)} on cuda:{secondary} (denoiser {_gib(_denoiser_mib(sizes))} fits "+ f"cuda:{primary}, {_gib(on_primary)} of {_gib(int(primary_limit))} with its working memory; "+ f"{', '.join(moved)} {_gib(winner.moved_mib)} does not fit beside it)",+ rejected,+ fallback_resident = plan.offload_policy == "none",+ )return dataclasses.replace(plan,offload_policy = "none",@@ -600,6 +881,19 @@ def refine_plan_for_multigpu()+def _cards(ordinals: Sequence[int]) -> str:+ return ", ".join(f"cuda:{int(o)}" for o in ordinals)+++def encoder_card_limit_mib(ordinal: int) -> Optional[int]:+ """What a secondary that only runs text encoders may hold: free memory minus ComfyUI's per-card floor (the layer+ split prices its block-only cards the same way). None when the card cannot be read."""+ from .diffusion_layer_split_plan import secondary_reserve_mib++ free, _total = _free_total_mib(int(ordinal))+ return None if free is None else max(0, int(free) - secondary_reserve_mib())++def secondary_device_memory(ordinal: int) -> Any:from .diffusion_memory import DeviceMemory@@ -1009,7 +1303,8 @@ def placement_status(pipe: Any) -> Optional[dict[str, Any]]:from .diffusion_layer_split_plan import layer_split_statuslayer = layer_split_status(pipe)- if info is None and cfg is None and declined is None and layer is None:+ decision = placement_decision(pipe)+ if info is None and cfg is None and declined is None and layer is None and decision is None:return Noneout: dict[str, Any] = dict(info or {})from .diffusion_layer_split import layer_split_stats@@ -1032,6 +1327,42 @@ def placement_status(pipe: Any) -> Optional[dict[str, Any]]:out["cfg_parallel"] = cfg.describe()elif declined is not None:out["cfg_parallel"] = {"armed": False, "declined": declined}+ if decision is not None:+ out["decision"] = _live_decision(+ pipe, decision, info, layer, declined if cfg is None else None+ )+ return out+++def _live_decision(+ pipe: Any,+ decision: PlacementDecision,+ info: Optional[dict],+ layer: Optional[dict],+ cfg_declined: Optional[str],+) -> dict[str, Any]:+ """The recorded decision, corrected by what engaged: a split whose placement failed reports its one-card fallback,+ and a declined CFG-parallel replica joins the rejected candidates."""+ out = decision.describe()+ failed = None+ if decision.chosen == "companion_split" and info is None:+ failed = "the companion split did not engage at placement"+ elif decision.chosen == "layer_split" and not (layer or {}).get("cards"):+ failed = f"the layer split did not engage ({(layer or {}).get('declined') or 'placement failed'})"+ if failed is not None:+ out["rejected"] = [{"kind": decision.chosen, "reason": failed}, *out["rejected"]]+ if decision.fallback_resident:+ out["chosen"] = "one_card"+ out["summary"] = (+ f"placement: one card: everything resident on cuda:{decision.primary} ({failed})"+ )+ else:+ out["chosen"] = "offload"+ out["summary"] = (+ f"placement: one card with offload on cuda:{decision.primary} ({failed})"+ )+ if cfg_declined is not None:+ out["rejected"] = [*out["rejected"], {"kind": "cfg_parallel", "reason": cfg_declined}]return outdiff --git a/studio/backend/tests/test_diffusion_auto_placement.py b/studio/backend/tests/test_diffusion_auto_placement.pynew file mode 100644index 00000000000..99313af90bf--- /dev/null+++ b/studio/backend/tests/test_diffusion_auto_placement.py@@ -0,0 +1,566 @@+# 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 placement end to end on fake card topologies, CPU only.++One fake host feeds every reader the real decision uses: the nvidia-smi rows (``resolve_auto_cuda_ordinal`` ranks the+primary from them, ``smi_free_total_mib`` sizes the other cards without a CUDA context), the primary's own+``trusted_mem_get_info``, torch's device count / names / capabilities and an optional CUDA_VISIBLE_DEVICES mask. The+one-card plan comes from ``plan_diffusion_memory`` with the primary's real budget rule, and the multi-GPU refinement,+the layer split packer and the CFG-parallel gate run unpatched. Only the loaded component sizes, the block layout and+the layer split engine are fakes (no weights)."""++from __future__ import annotations++import dataclasses+from typing import Optional++import pytest+import torch++from core.inference import diffusion_device as dd+from core.inference import diffusion_layer_split_plan as lsp+from core.inference import diffusion_memory as dm+from core.inference import diffusion_multigpu as mg++GIB = 1024+++class Card:+ index: int # physical (nvidia-smi) index+ total_mib: int+ used_mib: int = 0+ cap: tuple = (7, 5)+ name: str = "Tesla T4"++ @property+ def free_mib(self) -> int:+ return self.total_mib - self.used_mib+++T4 = 15360 # MiB nvidia-smi reports for a T4+++class Host:+ def __init__(+ self,+ cards: list[Card],+ mask: Optional[list[int]] = None,+ ):+ self.cards = {c.index: c for c in cards}+ self.visible = list(mask) if mask is not None else sorted(self.cards)+ self.mem_get_info_calls: list[int] = []++ def card(self, ordinal: int) -> Card:+ return self.cards[self.visible[int(ordinal)]]++ def install(self, monkeypatch) -> None:+ from utils import hardware as hw_pkg+ from utils.hardware import hardware as hw+ from utils.hardware import nvidia++ rows = {+ "devices": [+ {+ "index": c.index,+ "vram_total_gb": c.total_mib / 1024,+ "vram_used_gb": c.used_mib / 1024,+ }+ for c in self.cards.values()+ ]+ }+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: list(self.visible))+ monkeypatch.setattr(hw, "_cuda_order_matches_smi", lambda: True)+ monkeypatch.setattr(hw, "_integrated_cuda_rows", lambda visible: ({}, ""))+ monkeypatch.setattr(hw, "_get_parent_visible_gpu_spec", lambda: {})+ monkeypatch.setattr(hw, "_smi_visible_utilization", lambda spec: rows)+ monkeypatch.setattr(hw, "_nvidia_mig_gpu_indices_or_none", lambda: set())+ monkeypatch.setattr(+ nvidia,+ "get_compute_capabilities",+ lambda: {c.index: c.cap for c in self.cards.values()},+ )++ def mem_get_info(ordinal, *, module = None):+ self.mem_get_info_calls.append(int(ordinal))+ c = self.card(int(ordinal))+ return c.free_mib << 20, c.total_mib << 20++ monkeypatch.setattr(hw_pkg, "trusted_mem_get_info", mem_get_info)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: len(self.visible))+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda o = 0: self.card(int(o)).name)+ monkeypatch.setattr(mg, "_capability", lambda o: tuple(self.card(int(o)).cap))+ monkeypatch.setattr(mg, "_rocm_torch", lambda: False)+ monkeypatch.setattr(lsp, "_is_rocm", lambda: False)+ monkeypatch.setattr(+ dd,+ "resolve_diffusion_device_target",+ lambda **kw: dd.DiffusionDeviceTarget(+ "cuda", torch.float16, "cuda", "nvidia", True, True, True+ ),+ )+ monkeypatch.setattr(dd, "_PINNED_AWAY_FROM_ZERO", False)+++class _Target:+ supports_model_cpu_offload: bool = True+ ordinal: Optional[int] = 0+ device: str = "cuda"+ backend: str = "cuda"+ is_cuda_torch_device: bool = True+++class _Pipe:+ components: dict = {}+ transformer = None++ def to(self, *a, **k):+ return self+++class _Engine:+ def __init__(self):+ self.placed = []++ def place(+ self,+ pipe,+ *,+ primary,+ split,+ logger = None,+ ):+ self.placed.append(split)+ return {}++ def undo(self, pipe):+ pass++[email protected](autouse = True)+def _env(monkeypatch):+ for var in (mg.MULTIGPU_ENV, mg.CFG_PARALLEL_ENV, lsp.LAYER_SPLIT_ENV, "CUDA_VISIBLE_DEVICES"):+ monkeypatch.delenv(var, raising = False)+ monkeypatch.setattr(mg, "models_kept_loaded", lambda: False)+ eng = _Engine()+ monkeypatch.setattr(lsp, "engine_available", lambda: True)+ monkeypatch.setattr(lsp, "place_layer_split", eng.place)+ monkeypatch.setattr(lsp, "undo_layer_split", eng.undo)+ monkeypatch.setattr("core.inference.diffusion_bg_compile.load_time_enabled", lambda: False)+ yield eng+++def _sizes(+ dit: int,+ te: int,+ vae: int = 160,+ dit2: int = 0,+) -> dict:+ out = {"transformer": (dit, "dit")}+ if dit2:+ out["transformer_2"] = (dit2, "dit")+ out["text_encoder"] = (te, "text_encoder")+ out["vae"] = (vae, "other")+ return out+++class Decision:+ primary: Optional[int]+ selection: Optional[mg.MultiGpuSelection]+ one_card: dm.MemoryPlan+ plan: dm.MemoryPlan+ status: Optional[dict]+ cfg_parallel: Optional[str]+++def decide(+ monkeypatch,+ host: Host,+ sizes: dict,+ *,+ headroom: int = 2500,+ blocks: Optional[dict] = None,+ gpu_ids: Optional[list[int]] = None,+ preload_split: bool = True,+ place: bool = True,+) -> Decision:+ """What an Automatic load (``gpu_ids`` None) or an explicit selection decides on ``host`` for ``sizes``."""+ host.install(monkeypatch)+ monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: sizes)+ if blocks is None:+ dits = {n: m for n, (m, r) in sizes.items() if r == "dit"}+ blocks = {n: lsp.DenoiserLayout(max(1, m // 40), (m // 40,) * 39) for n, m in dits.items()}+ monkeypatch.setattr(lsp, "_denoiser_layouts", lambda pipe: blocks)+ if gpu_ids is None:+ primary = dd.auto_cuda_ordinal_for_load()+ selection = mg.automatic_selection(primary)+ else:+ primary = min(gpu_ids)+ selection = mg.make_selection(primary, gpu_ids)+ ordinal = 0 if primary is None else primary+ card = host.card(ordinal)+ memory = dm.DeviceMemory(+ backend = "cuda",+ device = "cuda",+ memory_kind = "discrete_vram",+ free_mib = card.free_mib,+ total_mib = card.total_mib,+ )+ dits = sum(m for m, r in sizes.values() if r == "dit")+ companions = sum(m for m, r in sizes.values() if r != "dit")+ tes = sum(m for m, r in sizes.values() if r == "text_encoder")+ pipe = _Pipe()+ with mg.selection_scope(selection if preload_split else None):+ one_card = dm.plan_diffusion_memory(+ target = _Target(ordinal = primary),+ device_memory = memory,+ model_dense_mib = dits + companions,+ companion_dense_mib = companions,+ text_encoder_dense_mib = tes,+ runtime_headroom_mib = headroom,+ requested_mode = "auto",+ )+ with mg.selection_scope(selection):+ plan = mg.refine_plan_for_multigpu(pipe, one_card)+ if not place:+ pass # placement failed: nothing engaged, the one-card fallback runs+ elif plan.layer_split is not None:+ lsp.apply_layer_split_plan(pipe, plan, placement = f"cuda:{ordinal}")+ elif plan.secondary_ordinal is not None:+ # what place_split records: the component-to-device map under "placement"+ mg._PLACEMENTS[pipe] = {+ "primary": f"cuda:{ordinal}",+ "secondary": f"cuda:{plan.secondary_ordinal}",+ "placement": {+ name: f"cuda:{plan.secondary_ordinal}"+ if role == "text_encoder"+ else f"cuda:{ordinal}"+ for name, (_mib, role) in sizes.items()+ },+ }+ cfg = mg.install_cfg_parallel(pipe, offload_policy = plan.offload_policy)+ return Decision(primary, selection, one_card, plan, mg.placement_status(pipe), cfg)+++def _placement(d: Decision) -> dict:+ assert d.status is not None and "decision" in d.status, d.status+ return d.status["decision"]+++# A: fits one card -> one card, no CFG-parallel, no CUDA context on the other card.+def test_a_fits_one_card_uses_one_card_and_no_cfg_parallel(monkeypatch):+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 3900, te = 1600))+ assert d.plan is d.one_card and d.plan.offload_policy == dm.OFFLOAD_NONE+ assert d.plan.secondary_ordinal is None and d.plan.layer_split is None+ assert d.cfg_parallel is not None and "automatic" in d.cfg_parallel+ p = _placement(d)+ assert p["chosen"] == "one_card"+ 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")+ assert "automatic" in kinds["cfg_parallel"]+ assert set(host.mem_get_info_calls) <= {0}+++def test_a_explicit_selection_of_a_model_that_fits_still_offers_cfg_parallel(monkeypatch):+ # The user picked both cards: the one-card plan stays, CFG-parallel is the user's lever (declined here only+ # because the fake pipeline has no denoiser module).+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 3900, te = 1600), gpu_ids = [0, 1])+ assert d.plan is d.one_card and not d.selection.automatic+ assert d.cfg_parallel is not None and "automatic" not in d.cfg_parallel+++# B: denoiser fits card 0, text encoder does not fit beside it -> text encoder on card 1.+def test_b_companion_split_puts_the_text_encoder_on_the_second_card(monkeypatch):+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 7400, te = 7600))+ assert d.one_card.offload_policy != dm.OFFLOAD_NONE+ assert d.plan.offload_policy == dm.OFFLOAD_NONE and d.plan.secondary_ordinal == 1+ assert "text_encoder" in d.plan.secondary_components+ assert d.plan.layer_split is None+ assert d.cfg_parallel is not None and "automatic" in d.cfg_parallel+ p = _placement(d)+ assert p["chosen"] == "companion_split"+ assert "text_encoder" in p["summary"] and "on cuda:1" in p["summary"]+ assert "fits cuda:0" in p["summary"] and "does not fit beside it" in p["summary"]+ assert p["rejected"][0]["kind"] == "one_card"+++# C: the denoiser fits no single card but fits two -> layer split.+def test_c_denoiser_too_big_for_one_card_is_layer_split(monkeypatch, _env):+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 14000, te = 7600))+ assert d.plan.layer_split is not None and d.plan.layer_split.cards == (0, 1)+ assert d.plan.secondary_ordinal is None+ assert _env.placed+ assert "layer split" in d.cfg_parallel+ p = _placement(d)+ assert p["chosen"] == "layer_split" and "cuda:0, cuda:1" in p["summary"]+ rejected = [r["kind"] for r in p["rejected"]]+ assert rejected[0] == "one_card" and "companion_split" in rejected+++# D: nothing fits -> one-card offload, with the layer split's reason.+def test_d_nothing_fits_offloads_on_one_card(monkeypatch, _env):+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 32000, te = 7600))+ assert d.plan is d.one_card and d.plan.offload_policy != dm.OFFLOAD_NONE+ assert not _env.placed+ p = _placement(d)+ assert p["chosen"] == "offload"+ layer = [r for r in p["rejected"] if r["kind"] == "layer_split"]+ assert layer and "fit" in layer[0]["reason"]+++# E: the primary is busy (a foreign process) -> the free card.+def test_e_busy_first_card_moves_the_load_to_the_free_card(monkeypatch):+ host = Host([Card(0, T4, 13000), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 3900, te = 1600))+ assert d.primary == 1 and d.selection.primary == 1+ assert d.plan.offload_policy == dm.OFFLOAD_NONE+ assert _placement(d)["summary"].startswith("placement: one card: everything resident on cuda:1")+ assert set(host.mem_get_info_calls) <= {1}+++# F: mixed sizes.+def test_f_mixed_sizes_put_the_denoiser_on_the_big_card(monkeypatch):+ for order in ((24576, 12288), (12288, 24576)):+ host = Host([Card(0, order[0], 400, name = "RTX"), Card(1, order[1], 400, name = "RTX")])+ d = decide(monkeypatch, host, _sizes(dit = 15000, te = 5000))+ big = 0 if order[0] > order[1] else 1+ assert d.selection.primary == big+ assert d.plan.secondary_ordinal == 1 - big+ assert "text_encoder" in d.plan.secondary_components+++def test_f_mixed_sizes_layer_split_cuts_in_proportion(monkeypatch, _env):+ host = Host([Card(0, 24576, 400, name = "RTX"), Card(1, 12288, 400, name = "RTX")])+ d = decide(monkeypatch, host, _sizes(dit = 19500, te = 1500))+ split = d.plan.layer_split+ assert split is not None and split.cards == (0, 1)+ blocks = {o: sum(r.stop - r.start for r in split.ranges if r.card == o) for o in split.cards}+ assert blocks[0] > blocks[1]+++def test_f_older_second_card_takes_no_component(monkeypatch):+ host = Host([Card(0, 24576, 400, cap = (8, 9)), Card(1, 24576, 400, cap = (7, 5))])+ d = decide(monkeypatch, host, _sizes(dit = 15000, te = 9000))+ assert d.selection is None+ assert d.plan.secondary_ordinal is None and d.plan.offload_policy != dm.OFFLOAD_NONE+++# G: three cards.+def test_g_three_cards_companion_goes_to_the_freest_secondary(monkeypatch):+ host = Host([Card(0, T4, 300), Card(1, T4, 6000), Card(2, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 7400, te = 7600))+ assert d.plan.secondary_ordinal == 2+++def test_g_three_cards_layer_split_uses_two_when_two_suffice(monkeypatch, _env):+ host = Host([Card(0, T4, 300), Card(1, T4, 300), Card(2, T4, 300)])+ two = decide(monkeypatch, host, _sizes(dit = 14000, te = 7600))+ assert two.plan.layer_split is not None and len(two.plan.layer_split.cards) == 2+ three = decide(monkeypatch, host, _sizes(dit = 22000, te = 7600))+ assert three.plan.layer_split is not None and three.plan.layer_split.cards == (0, 1, 2)+++# H: a CUDA_VISIBLE_DEVICES mask: torch ordinals are positions in the mask, smi rows are physical.+def test_h_mask_maps_torch_ordinals_to_physical_rows(monkeypatch):+ cards = [Card(0, T4, 300), Card(1, T4, 300), Card(2, T4, 300), Card(3, T4, 13000)]+ host = Host(cards, mask = [3, 1])+ d = decide(monkeypatch, host, _sizes(dit = 3900, te = 1600))+ # physical 3 (ordinal 0) is busy: ordinal 1 = physical 1 wins, and only the two masked cards are candidates+ assert d.primary == 1 and d.selection.secondaries == (0,)+ assert dd.smi_free_total_mib(0) == (T4 - 13000, T4)+ split = decide(monkeypatch, Host(cards, mask = [1, 2]), _sizes(dit = 7400, te = 7600))+ assert split.selection.primary == 0 and split.plan.secondary_ordinal == 1+++def test_one_visible_card_or_the_kill_switch_is_today_one_card_path(monkeypatch):+ host = Host([Card(0, T4, 300), Card(1, T4, 300)], mask = [1])+ d = decide(monkeypatch, host, _sizes(dit = 7400, te = 7600))+ assert d.selection is None and d.status is None+ assert d.plan is d.one_card+ monkeypatch.setenv(mg.MULTIGPU_ENV, "0")+ off = decide(monkeypatch, Host([Card(0, T4, 300), Card(1, T4, 300)]), _sizes(dit = 7400, te = 7600))+ assert off.selection is None and off.status is None and off.plan is off.one_card+ assert off.plan == d.plan+++# Video families share the refinement: a two-expert denoiser and a large video DiT.+def test_video_two_experts_that_do_not_fit_one_card_share_two(monkeypatch):+ # Wan 2.2 A14B on 2x A100 80 GB: the experts stay together on the primary, every companion moves.+ a100 = dict(total_mib = 81920, used_mib = 1000, cap = (8, 0), name = "A100")+ host = Host([Card(0, **a100), Card(1, **a100)])+ d = decide(monkeypatch, host, _sizes(dit = 28600, dit2 = 28600, te = 11400), headroom = 6000)+ assert d.plan.offload_policy == dm.OFFLOAD_NONE and d.plan.secondary_ordinal == 1+ assert _placement(d)["chosen"] == "companion_split"+++def test_video_second_expert_moves_when_the_companions_are_not_enough(monkeypatch):+ l40 = dict(total_mib = 46068, used_mib = 500, cap = (8, 9), name = "L40S")+ host = Host([Card(0, **l40), Card(1, **l40)])+ d = decide(monkeypatch, host, _sizes(dit = 19000, dit2 = 19000, te = 3000), headroom = 4000)+ assert d.plan.secondary_ordinal == 1+ assert "transformer_2" in (d.plan.secondary_components or ())+ assert _placement(d)["chosen"] == "companion_split"+++def test_video_wan5b_on_two_t4s(monkeypatch):+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 9500, te = 10800, vae = 1400), headroom = 3500)+ p = _placement(d)+ assert p["chosen"] in ("companion_split", "layer_split")+ assert d.plan.offload_policy == dm.OFFLOAD_NONE+++# A U-Net family (SDXL): the loaded-size reader tags ``unet`` 'other', so the post-load refinement finds no denoiser+# to keep on the primary and leaves the one-card plan. Kept that way on purpose: with the U-Net counted as the+# denoiser, the pre-compile layer split preview of an SDXL load predicts a split that the whole-compiled U-Net then+# refuses, and the compile is set up for a resident denoiser under model offload (Kaggle 2x T4 run).+def test_unet_family_keeps_todays_refinement(monkeypatch):+ card = dict(total_mib = 12288, used_mib = 300, cap = (8, 6), name = "RTX 3060")+ host = Host([Card(0, **card), Card(1, **card)])+ sdxl = {+ "unet": (4900, "other"),+ "text_encoder": (235, "text_encoder"),+ "text_encoder_2": (1324, "text_encoder"),+ "vae": (160, "other"),+ }+ d = decide(monkeypatch, host, sdxl, headroom = 1200, preload_split = False)+ assert d.plan is d.one_card+ assert d.plan.secondary_ordinal is None and d.plan.layer_split is None+++def test_video_umt5_text_encoder_moves_to_a_second_t4(monkeypatch):+ # Wan 2.1 1.3B: the 10.6 GiB umt5-xxl encoder fits a free 15 GB T4 once that card is priced for an encoder+ # forward (weights + 1 GiB + ComfyUI's 1.2 GiB floor) instead of a denoising card's overhead and margin.+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 2700, te = 10834, vae = 485), headroom = 3500)+ assert d.one_card.offload_policy != dm.OFFLOAD_NONE+ assert d.plan.secondary_ordinal == 1 and d.plan.offload_policy == dm.OFFLOAD_NONE+ assert set(d.plan.secondary_components) == {"text_encoder"}+ assert _placement(d)["chosen"] == "companion_split"+++def test_encoder_card_pricing_never_admits_an_encoder_that_does_not_fit_the_free_memory(+ monkeypatch,+):+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 2700, te = 14000, vae = 485), headroom = 3500)+ assert d.plan.secondary_ordinal is None+++# The discrete reserve: a partly used big card.+ "total, expected",+ [(15360, 2048), (24576, 2457), (40960, 4096), (81920, 4096), (182272, 4096)],+)+def test_discrete_reserve_is_capped(total, expected):+ assert dm._reserve_mib("discrete_vram", total) == expected+++def test_partly_used_big_cards_get_the_companion_split(monkeypatch):+ # 2x B200 (178 GiB) with 22 / 17 GiB free: the uncapped 10% reserve (17.8 GiB) left 4 GiB on the primary and+ # nothing on the secondary, so this streamed the denoiser on one card.+ b200 = 182272+ host = Host(+ [+ Card(0, b200, b200 - 22 * GIB, cap = (10, 0), name = "B200"),+ Card(1, b200, b200 - 17 * GIB, cap = (10, 0), name = "B200"),+ ]+ )+ d = decide(monkeypatch, host, _sizes(dit = 7400, te = 7600), headroom = 3000)+ assert d.plan.secondary_ordinal == 1 and d.plan.offload_policy == dm.OFFLOAD_NONE+++def test_the_apu_pool_keeps_the_uncapped_reserve(monkeypatch):+ memory = dm.DeviceMemory("cuda", "cuda:0", "unified_memory", 31 * GIB, 96 * GIB)+ monkeypatch.setattr(dm, "_rocm_linux_apu_os_room_outside_pool", lambda m: True)+ assert dm._safe_device_budget_mib(memory) == 31 * GIB - int(96 * GIB * 0.10)+++# Review follow-ups: the decision must not overwrite the component map, and forced splits of a model one card holds+# must report their resident fallback as one card.+def test_decision_keeps_the_companion_component_map(monkeypatch):+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 7400, te = 7600))+ assert d.plan.secondary_ordinal == 1+ assert d.status["placement"]["text_encoder"] == "cuda:1"+ assert d.status["placement"]["transformer"] == "cuda:0"+ assert d.status["decision"]["chosen"] == "companion_split"+++def test_video_card_floors_still_read_the_component_map(monkeypatch):+ from core.inference import video as vid++ class _Module(torch.nn.Module):+ def __init__(self, n):+ super().__init__()+ self.w = torch.nn.Parameter(torch.zeros(n))++ pipe = _Pipe()+ pipe.components = {"transformer": _Module(4), "text_encoder": _Module(8), "vae": _Module(2)}+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ host.install(monkeypatch)+ sel = mg.make_selection(0, [0, 1], automatic = True)+ mg._PLACEMENTS[pipe] = {+ "primary": "cuda:0",+ "secondary": "cuda:1",+ "placement": {"transformer": "cuda:0", "text_encoder": "cuda:1", "vae": "cuda:0"},+ }+ mg._record_decision(pipe, sel, "companion_split", "companion split: text_encoder on cuda:1")+ floors = vid._video_split_card_floors(pipe)+ assert floors is not None+ assert {int(card[0]) for card in floors} == {0, 1}+++def test_forced_layer_split_of_a_resident_model_that_does_not_cut_reports_one_card(monkeypatch):+ monkeypatch.setenv(lsp.LAYER_SPLIT_ENV, "force")+ monkeypatch.setattr(lsp, "engine_available", lambda: False)+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 3900, te = 1600))+ assert d.plan is d.one_card and d.plan.offload_policy == dm.OFFLOAD_NONE+ p = _placement(d)+ assert p["chosen"] == "one_card" and "everything resident" in p["summary"]+++def test_failed_forced_companion_split_of_a_resident_model_reports_one_card(monkeypatch):+ monkeypatch.setenv(mg.MULTIGPU_ENV, "force")+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 3900, te = 1600), preload_split = False, place = False)+ assert d.one_card.offload_policy == dm.OFFLOAD_NONE+ assert d.plan.secondary_ordinal == 1+ p = _placement(d)+ assert p["chosen"] == "one_card", p+ assert p["rejected"][0]["kind"] == "companion_split"+++def test_failed_companion_split_of_an_offloading_model_reports_offload(monkeypatch):+ host = Host([Card(0, T4, 300), Card(1, T4, 300)])+ d = decide(monkeypatch, host, _sizes(dit = 7400, te = 7600), place = False)+ assert d.plan.secondary_ordinal == 1+ assert _placement(d)["chosen"] == "offload"+++def test_layer_split_decline_reports_the_encode_activation_it_charged():+ layout = {"transformer": lsp.DenoiserLayout(500, (900,) * 20)}+ split, reason = lsp.plan_layer_split(+ denoisers = layout,+ companions = {"text_encoder": (7000, "text_encoder"), "vae": (160, "other")},+ primary = 0,+ card_limits = {0: 9000, 1: 9000},+ headroom_mib = 2000,+ overhead_mib = 2048,+ phase_headroom_mib = (5555, 1000, 1200),+ )+ assert split is None+ assert "5555 MiB of activations" in reasondiff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex eea9452203c..a04ec8ec196 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -5515,7 +5515,8 @@ def test_dense_quant_replan_no_retry_when_capacity_truly_short(replan_calls.append(True)return types.SimpleNamespace(offload_policy = "model",- estimates = {"resident_required_mib": 150_000, "safe_device_budget_mib": 40_000},+ # above the capacity margin, 0.85 * (183,359 - 4,096 capped reserve) = 152,373+ estimates = {"resident_required_mib": 160_000, "safe_device_budget_mib": 40_000},device_memory = types.SimpleNamespace(total_mib = 183_359, memory_kind = "discrete_vram", free_mib = 60_000),@@ -5562,7 +5563,7 @@ def _decline_dense_quant(backend, monkeypatch, tmp_path):return dataclasses.replace(real, offload_policy = "model")return types.SimpleNamespace(offload_policy = "model",- estimates = {"resident_required_mib": 150_000, "safe_device_budget_mib": 40_000},+ estimates = {"resident_required_mib": 160_000, "safe_device_budget_mib": 40_000},device_memory = types.SimpleNamespace(total_mib = 183_359, memory_kind = "discrete_vram", free_mib = 60_000),diff --git a/studio/backend/tests/test_diffusion_memory.py b/studio/backend/tests/test_diffusion_memory.pyindex 2cba10c9e34..52aa320b46f 100644--- a/studio/backend/tests/test_diffusion_memory.py+++ b/studio/backend/tests/test_diffusion_memory.py@@ -1221,8 +1221,8 @@ def test_plan_fits_total_capacity():)assert plan_fits_total_capacity(plan(90_228, 183_359)) is True- # 0.85 * (183,359 - 18,335) = 140,270- assert plan_fits_total_capacity(plan(150_000, 183_359)) is False+ # 0.85 * (183,359 - 4,096 capped reserve) = 152,373+ assert plan_fits_total_capacity(plan(160_000, 183_359)) is Falseassert plan_fits_total_capacity(plan(None, 183_359)) is Falseassert plan_fits_total_capacity(plan(90_228, None)) is Falseassert plan_fits_total_capacity(types.SimpleNamespace()) is Falsediff --git a/studio/backend/tests/test_diffusion_memory_rocm_apu_reserve.py b/studio/backend/tests/test_diffusion_memory_rocm_apu_reserve.pyindex ad8d0bed204..d5b47855559 100644--- a/studio/backend/tests/test_diffusion_memory_rocm_apu_reserve.py+++ b/studio/backend/tests/test_diffusion_memory_rocm_apu_reserve.py@@ -113,9 +113,10 @@ def test_nvidia_unified_memory_unchanged(host):assert _plan().estimates["safe_device_budget_mib"] == POOL_FREE - int(POOL_TOTAL * 0.20)-def test_discrete_vram_unchanged(host):- assert _plan(kind = "discrete_vram").estimates["safe_device_budget_mib"] == POOL_FREE - int(- POOL_TOTAL * 0.10+def test_discrete_vram_keeps_the_discrete_reserve(host):+ # a real discrete card: 10% of the total, capped (diffusion_memory.DISCRETE_RESERVE_CAP_MIB)+ assert _plan(kind = "discrete_vram").estimates["safe_device_budget_mib"] == POOL_FREE - min(+ int(POOL_TOTAL * 0.10), dm.DISCRETE_RESERVE_CAP_MIB)diff --git a/studio/backend/tests/test_video_ltx23_memory_plan.py b/studio/backend/tests/test_video_ltx23_memory_plan.pyindex 884de46777f..6b322952a05 100644--- a/studio/backend/tests/test_video_ltx23_memory_plan.py+++ b/studio/backend/tests/test_video_ltx23_memory_plan.py@@ -239,7 +239,8 @@ def test_resident_proof_uses_the_budget_fast_was_placed_with():"""Auto precision keeps bf16 only on a proven fit; a fast plan placed resident under its own budget is one."""from core.inference.diffusion import _plan_proves_resident- fast = _plan(TENANT_FREE_MIB, LTX23_DIT_MIB)+ # Free memory between the auto and the fast budget (the discrete reserve is capped at 4 GiB, fast keeps 2 GiB).+ fast = _plan(79_500, LTX23_DIT_MIB)assert fast.offload_policy == OFFLOAD_NONEassert fast.estimates["resident_required_mib"] > fast.estimates["safe_device_budget_mib"]assert _plan_proves_resident(fast)