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
Unsloth Studio / Desktop: image generation ignores the VRAM Budget setting when planning offload (#14816)
Leo Borcherding38c5e3abed65
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 56e194a5a4c..8dd82dd4a8d 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -176,6 +176,10 @@ from .diffusion_small_host import (from .model_ids import hf_cache_repo_idfrom .safetensors_pread import pread_availablefrom .diffusion_memory import (+ commit_load_budget_fraction,+ release_load_budget_fraction,+ vram_budget_scope,+ carry_load_budget,MEMORY_MODE_BALANCED,MEMORY_MODE_LOW_VRAM,ACTIVATION_TILE,@@ -2413,7 +2417,7 @@ def _guard_layer_cards(pipe: Any, guard_target: Any, guard_kwargs: dict) -> int:pipeline carries no split record). Raises the guard's refusal (a ValueError); returns the number of cardschecked. Fails open on anything unknown."""from .diffusion_layer_split_plan import applied_layer_split, secondary_block_cards- from .diffusion_memory import _oversized_generate_override+ from .diffusion_memory import _device_user_budget_reserve_mib, _oversized_generate_overridesplit = applied_layer_split(pipe)if split is None or guard_kwargs.get("allow_oversized") or _oversized_generate_override():@@ -2438,16 +2442,18 @@ def _guard_layer_cards(pipe: Any, guard_target: Any, guard_kwargs: dict) -> int:if working + reserve <= 0:continuewith diffusion_device_scope(int(ordinal)):- free = reclaimable_snapshot_device_memory(guard_target).free_mib+ card = reclaimable_snapshot_device_memory(guard_target)+ free = card.free_mibif free is None:continue+ free = int(free) - _device_user_budget_reserve_mib(card, card.total_mib or free)checked += 1need = int(working * scale) + reserveif need > int(free):raise ImageActivationShortfallError(f"Generating at {guard_kwargs.get('width')}x{guard_kwargs.get('height')} needs about "f"{need / 1024:.2f} GB of working memory on cuda:{int(ordinal)}, which runs part of the model split "- f"across GPUs, but only about {int(free) / 1024:.2f} GB is free there. Generate at a smaller "+ f"across GPUs, but only about {max(0, int(free)) / 1024:.2f} GB is free there. Generate at a smaller ""resolution, or free GPU memory on that GPU. To try anyway, turn on 'Allow oversized generations' ""under Advanced on the Images page.")@@ -2588,8 +2594,11 @@ def _untiled_decode_shortfall_mib(vae: Any, z: Any) -> Optional[int]:def _untiled_encode_shortfall_mib(vae: Any, x: Any) -> Optional[int]:- """MiB short for encoding ``x`` untiled, the decode's rule; None off CUDA or on unknown figures."""+ """MiB short for encoding ``x`` untiled, the decode's rule (free less the VRAM Budget reserve); None off CUDA+ or on unknown figures."""+ from .diffusion_memory import user_budget_reserve_bytesfrom .diffusion_vae_tiling import FREE_FRACTION, _fused, _geometry, encode_mib_per_latent+try:import torch@@ -2599,8 +2608,9 @@ def _untiled_encode_shortfall_mib(vae: Any, x: Any) -> Optional[int]:per_latent = encode_mib_per_latent(ratio, _fused(vae), type(vae).__name__)if per_latent is None or ratio <= 0:return None- free, _ = torch.cuda.mem_get_info(x.device)+ free, total = torch.cuda.mem_get_info(x.device)free += torch.cuda.memory_reserved(x.device) - torch.cuda.memory_allocated(x.device)+ free -= user_budget_reserve_bytes(x.device, total)elem = next(vae.encoder.parameters()).element_size()# enable_fp16_vae_decode's fp32_encode upcasts the fp16 encoder and input for the encode itselfif getattr(vae, "_unsloth_fp16_decode", False):@@ -5072,6 +5082,7 @@ class DiffusionBackend:@_account_owned_load@pauses_background_embedding+ @vram_budget_scope("image", load = True)def begin_load(self,repo_id: str,@@ -5192,7 +5203,7 @@ class DiffusionBackend:)account_thread(- target = self._run_load,+ target = carry_load_budget(self._run_load),kwargs = dict(repo_id = repo_id,display_repo_id = display_repo_id,@@ -5230,6 +5241,7 @@ class DiffusionBackend:# The multi-GPU selection (begin_load's ``_gpu_ordinals``) is visible to this load's planner and placement only.@with_load_selection@scoped_local_files_only+ @vram_budget_scope("image", load = True)def _run_load(self, **kwargs: Any) -> None:token = kwargs.get("_load_token")# This load's own event: a later load replaces self._cancel_event rather than clearing it.@@ -6546,6 +6558,7 @@ class DiffusionBackend:failures_out.append(exc)return total, base_files+ @vram_budget_scope("image", load = True)def download_plan(self,repo_id: str,@@ -7838,6 +7851,7 @@ class DiffusionBackend:@_plans_at_requested_speed@scoped_local_files_only@_with_supplied_components+ @vram_budget_scope("image", load = True)def load_pipeline(self,repo_id: str,@@ -10662,6 +10676,7 @@ class DiffusionBackend:self._raise_if_load_cancelled(_load_token)self._state = statestate_committed = True+ commit_load_budget_fraction("image")try:from . import diffusion_vae_prebuilddiffusion_vae_prebuild.maybe_kick(pipe, compile_ctx, logger)@@ -12936,6 +12951,7 @@ class DiffusionBackend:@_release_render_on_unload@holds_inference@with_hires+ @vram_budget_scope("image")def generate(self,*,@@ -14356,6 +14372,7 @@ class DiffusionBackend:return self.status()def _unload_locked(self) -> None:+ release_load_budget_fraction("image")state = self._stateif state is None:returndiff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.pyindex e4fbd8def1c..b9b78223af8 100644--- a/studio/backend/core/inference/diffusion_attention.py+++ b/studio/backend/core/inference/diffusion_attention.py@@ -1222,13 +1222,17 @@ def _rocm_flash_probe_bytes(def _rocm_flash_probe_fits(device: str, need: int) -> bool:"""Room for the probe beside the live forward: device free plus the allocator's cached-but-unused blocks, with- 25% + 256 MiB to spare. Unknown memory state counts as no room."""+ 25% + 256 MiB to spare, less the user's VRAM Budget reserve (0 at the default). Unknown memory state counts as no+ room."""try:import torch- free, _total = torch.cuda.mem_get_info(device)+ from .diffusion_memory import user_budget_reserve_bytes++ free, total = torch.cuda.mem_get_info(device)cached = torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)- return free + max(int(cached), 0) >= need * 1.25 + (256 << 20)+ reserve = user_budget_reserve_bytes(device, total)+ return free + max(int(cached), 0) - reserve >= need * 1.25 + (256 << 20)except Exception: # noqa: BLE001return Falsediff --git a/studio/backend/core/inference/diffusion_cfg_batch.py b/studio/backend/core/inference/diffusion_cfg_batch.pyindex 14a4887f494..3f143e4de2a 100644--- a/studio/backend/core/inference/diffusion_cfg_batch.py+++ b/studio/backend/core/inference/diffusion_cfg_batch.py@@ -248,12 +248,14 @@ def cfg_batch_decline(def _usable_free_mib(device: Any) -> Optional[int]:- """Driver free plus this process's reserved-but-unallocated cache on ``device``."""+ """Driver free plus this process's reserved-but-unallocated cache on ``device``, less what the user's VRAM Budget keeps free (0 at the default)."""torch = _torch()try:- free, _total = torch.cuda.mem_get_info(device)+ from .diffusion_memory import _user_budget_reserve_mib++ free, total = torch.cuda.mem_get_info(device)idle = torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)- return int(free + max(0, idle)) >> 20+ return (int(free + max(0, idle)) >> 20) - _user_budget_reserve_mib(int(total) >> 20)except Exception: # noqa: BLE001 - unreadable: the out-of-memory backstop decidesreturn Nonediff --git a/studio/backend/core/inference/diffusion_device.py b/studio/backend/core/inference/diffusion_device.pyindex 75364e5f681..d338dc7a226 100644--- a/studio/backend/core/inference/diffusion_device.py+++ b/studio/backend/core/inference/diffusion_device.py@@ -345,15 +345,31 @@ def resolve_selected_cuda_ordinal(return rank_cuda_ordinals(ordinals)[0]+def _ranking_room_mib(free_mib: int, total_mib: Optional[int]) -> int:+ """What a card offers a primary pick."""+ from .diffusion_memory import DeviceMemory, _safe_device_budget_mib, _user_budget_reserve_mib++ if _user_budget_reserve_mib(1 << 20) <= 0:+ return int(free_mib)+ memory = DeviceMemory("cuda", "cuda", "discrete_vram", int(free_mib), total_mib)+ return int(_safe_device_budget_mib(memory) or 0)++def rank_cuda_ordinals(ordinals: list[int]) -> list[int]:"""``ordinals`` by free VRAM, most first, ties to the lowest ordinal (an unreadable card sorts last)."""def _free_vram(ordinal: int) -> int:try:import torch- return int(torch.cuda.mem_get_info(ordinal)[0])++ free, total = torch.cuda.mem_get_info(ordinal)+ from .diffusion_memory import _user_budget_reserve_mib++ if _user_budget_reserve_mib(1 << 20) <= 0:+ return int(free)+ return _ranking_room_mib(int(free) >> 20, int(total) >> 20) << 20except Exception: # noqa: BLE001 -- an unreadable card sorts last rather than failing the load- return -1+ return -(1 << 62)return sorted(ordinals, key = lambda ordinal: (-_free_vram(ordinal), ordinal))@@ -446,6 +462,11 @@ def resolve_auto_cuda_ordinal() -> Optional[int]:floor = caps.get(visible[0])if floor is None:return None+ try:+ from .diffusion_memory import _user_budget_reserve_mib+ budgeted = _user_budget_reserve_mib(1 << 20) > 0+ except Exception: # noqa: BLE001 -- unreadable setting: the default ranking+ budgeted = Falsefree_by_ordinal: dict[int, float] = {}for device in devices:index, total, used = (@@ -457,7 +478,15 @@ def resolve_auto_cuda_ordinal() -> Optional[int]:continueif caps.get(index, (0, 0)) < floor:continue- free_by_ordinal[visible.index(index)] = max(float(total) - float(used), 0.0) * 1024**3+ free_bytes = max(float(total) - float(used), 0.0) * 1024**3+ if budgeted:+ try:+ free_bytes = float(+ _ranking_room_mib(int(free_bytes) >> 20, int(float(total) * 1024)) << 20+ )+ except Exception: # noqa: BLE001 -- never raises: keep the raw reading+ pass+ free_by_ordinal[visible.index(index)] = free_bytesif not free_by_ordinal:return Nonebest = max(free_by_ordinal.values())diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex 03b6bac45b4..98b9389762d 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -24,7 +24,7 @@ import osimport sysimport threadingfrom dataclasses import dataclass, field, replace-from typing import Any, Callable, Optional+from typing import Any, Callable, Iterator, Optionalfrom .rocm_bf16 import is_rocm_torch@@ -1627,13 +1627,197 @@ def _budget_reserve_kind(memory: DeviceMemory) -> str:return _ROCM_APU_POOL if _rocm_linux_apu_os_room_outside_pool(memory) else memory.memory_kind+_LOAD_BUDGET_FRACTIONS: dict[str, float] = {}+_LOAD_BUDGET_LOCK = threading.Lock()+_BUDGET_SCOPE: contextvars.ContextVar[Optional[tuple]] = contextvars.ContextVar(+ "unsloth_vram_budget_scope", default = None+)+_UPCOMING_LOAD_FRACTION: contextvars.ContextVar[Optional[float]] = contextvars.ContextVar(+ "unsloth_vram_budget_upcoming_load", default = None+)+++def _live_vram_budget_fraction() -> float:+ from utils.vram_budget_settings import get_vram_budget_fraction+ return float(get_vram_budget_fraction())+++def _vram_budget_fraction() -> float:+ """The fraction the reserve readers charge."""+ scope = _BUDGET_SCOPE.get()+ with _LOAD_BUDGET_LOCK:+ if scope is not None and scope[0] == "load" and scope[2] is not None:+ return float(scope[2])+ if scope is not None and scope[1] in _LOAD_BUDGET_FRACTIONS:+ return _LOAD_BUDGET_FRACTIONS[scope[1]]+ if scope is None:+ upcoming = _UPCOMING_LOAD_FRACTION.get()+ if upcoming is not None:+ return float(upcoming)+ pinned = tuple(_LOAD_BUDGET_FRACTIONS.values())+ return min(pinned) if pinned else _live_vram_budget_fraction()+++def vram_budget_scope(owner: str, *, load: bool = False) -> Callable:+ """Decorator: run a backend load (snapshots the live Budget) or generation under ``owner``'s budget scope."""++ def wrap(fn: Callable) -> Callable:+ @functools.wraps(fn)+ def scoped(*args: Any, **kwargs: Any) -> Any:+ outer = _BUDGET_SCOPE.get()+ if load and outer is not None and outer[0] == "load" and outer[1] == owner:+ return fn(*args, **kwargs)+ if load:+ fraction: Optional[float] = _UPCOMING_LOAD_FRACTION.get()+ if fraction is None:+ try:+ fraction = _live_vram_budget_fraction()+ except Exception: # noqa: BLE001 - settings are a convenience; a load must never fail on them+ fraction = None+ scope = ("load", owner, fraction)+ else:+ scope = ("generate", owner, None)+ token = _BUDGET_SCOPE.set(scope)+ try:+ return fn(*args, **kwargs)+ finally:+ _BUDGET_SCOPE.reset(token)++ return scoped++ return wrap+++def snapshot_upcoming_load_budget() -> Optional[float]:+ """Snapshot the live VRAM Budget for the load this request is preparing, before it ranks GPUs, so the ranking, the plan and the load itself agree."""+ fraction = _UPCOMING_LOAD_FRACTION.get()+ if fraction is not None:+ return fraction+ try:+ fraction = _live_vram_budget_fraction()+ except Exception: # noqa: BLE001+ return None+ _UPCOMING_LOAD_FRACTION.set(fraction)+ return fraction+++def upcoming_load_budget() -> Iterator[Optional[float]]:+ """``snapshot_upcoming_load_budget`` for a block only (a ranking helper that runs outside a request's own context)."""+ if _UPCOMING_LOAD_FRACTION.get() is not None:+ yield _UPCOMING_LOAD_FRACTION.get()+ return+ try:+ fraction: Optional[float] = _live_vram_budget_fraction()+ except Exception: # noqa: BLE001+ fraction = None+ token = _UPCOMING_LOAD_FRACTION.set(fraction)+ try:+ yield fraction+ finally:+ _UPCOMING_LOAD_FRACTION.reset(token)+++def carry_load_budget(fn: Callable) -> Callable:+ """Wrap a load's worker-thread target so it inherits the fraction the calling load began with."""+ scope = _BUDGET_SCOPE.get()+ fraction = (+ scope[2] if scope is not None and scope[0] == "load" else _UPCOMING_LOAD_FRACTION.get()+ )+ if fraction is None:+ return fn++ @functools.wraps(fn)+ def carried(*args: Any, **kwargs: Any) -> Any:+ token = _UPCOMING_LOAD_FRACTION.set(float(fraction))+ try:+ return fn(*args, **kwargs)+ finally:+ _UPCOMING_LOAD_FRACTION.reset(token)++ return carried+++def commit_load_budget_fraction(owner: str) -> None:+ """Publish the fraction ``owner``'s load planned with, alongside its committed state. Never raises."""+ scope = _BUDGET_SCOPE.get()+ fraction = scope[2] if scope is not None and scope[0] == "load" and scope[1] == owner else None+ if fraction is None:+ try:+ fraction = _live_vram_budget_fraction()+ except Exception: # noqa: BLE001+ return+ with _LOAD_BUDGET_LOCK:+ _LOAD_BUDGET_FRACTIONS[owner] = float(fraction)+++def release_load_budget_fraction(owner: str) -> None:+ """Drop ``owner``'s snapshot when its committed pipeline is torn down."""+ with _LOAD_BUDGET_LOCK:+ _LOAD_BUDGET_FRACTIONS.pop(owner, None)+++def _user_budget_reserve_mib(base: Optional[int]) -> int:+ """What the user's VRAM Budget setting keeps free of ``base``."""+ if not base or int(base) <= 0:+ return 0+ try:+ from utils.vram_budget_settings import VRAM_FRACTION_DEFAULT+ fraction = _vram_budget_fraction()+ except Exception: # noqa: BLE001 - settings are a convenience; a load must never fail on them+ return 0+ if not fraction < VRAM_FRACTION_DEFAULT:+ return 0+ return int(base * (1.0 - fraction))+++def user_budget_reserve_share() -> float:+ """The share of each card the user's VRAM Budget keeps free."""+ try:+ from utils.vram_budget_settings import VRAM_FRACTION_DEFAULT+ fraction = _vram_budget_fraction()+ except Exception: # noqa: BLE001 - settings are a convenience; a load must never fail on them+ return 0.0+ return 1.0 - fraction if fraction < VRAM_FRACTION_DEFAULT else 0.0+++def user_budget_reserve_bytes(device: Any, total_bytes: Optional[int]) -> int:+ """What the user's VRAM Budget keeps free on ``device`` (``total_bytes`` total), in bytes."""+ kind = str(getattr(device, "type", device) or "").split(":")[0]+ if kind in ("cpu", "mps") or not total_bytes:+ return 0+ try:+ return _user_budget_reserve_mib(int(total_bytes) >> 20) << 20+ except Exception: # noqa: BLE001+ return 0+++def _device_user_budget_reserve_mib(memory: DeviceMemory, base: Optional[int]) -> int:+ """:func:`_user_budget_reserve_mib` for ``memory``, 0 where the LLM path ignores the setting too."""+ backend = str(getattr(memory, "backend", "") or "").split(":")[0]+ if (+ backend in ("mps", "cpu")+ or getattr(memory, "memory_kind", None) == "system_memory"+ or getattr(memory, "metal_working_set_mib", None) is not None+ ):+ return 0+ return _user_budget_reserve_mib(base)+++def _planner_reserve_mib(memory: DeviceMemory, base: int) -> int:+ return max(+ _reserve_mib(_budget_reserve_kind(memory), base),+ _device_user_budget_reserve_mib(memory, base),+ )++def _safe_device_budget_mib(memory: DeviceMemory) -> Optional[int]:"""Free memory minus a headroom reserve (room for fragmentation + other tenants). None whenfree memory is unknown."""if memory.free_mib is None:return Nonebase = memory.total_mib or memory.free_mib- return max(0, int(memory.free_mib) - _reserve_mib(_budget_reserve_kind(memory), base))+ return max(0, int(memory.free_mib) - _planner_reserve_mib(memory, base))def _fast_device_budget_mib(memory: DeviceMemory) -> Optional[int]:@@ -1642,7 +1826,11 @@ def _fast_device_budget_mib(memory: DeviceMemory) -> Optional[int]:if memory.free_mib is None:return Nonebase = memory.total_mib or memory.free_mib- reserve = max(2048, _reserve_mib(_budget_reserve_kind(memory), base) // 2)+ reserve = max(+ 2048,+ _reserve_mib(_budget_reserve_kind(memory), base) // 2,+ _device_user_budget_reserve_mib(memory, base),+ )return max(0, int(memory.free_mib) - reserve)@@ -2124,7 +2312,7 @@ def total_capacity_budget_mib(memory: DeviceMemory) -> Optional[int]:total = memory.total_mibif total is None:return None- return int((int(total) - _reserve_mib(_budget_reserve_kind(memory), int(total))) * 0.85)+ return int((int(total) - _planner_reserve_mib(memory, int(total))) * 0.85)# Opt-in escape hatch for the unified-memory refusal below: the shortfall check is an estimate, so an operator who@@ -2582,7 +2770,14 @@ def plan_diffusion_memory(companion_dense_mib = companion_dense_mib,text_encoder_dense_mib = text_encoder_dense_mib,base_overhead_mib = base_overhead_mib,- free_mib = device_memory.free_mib,+ free_mib = (+ None+ if device_memory.free_mib is None+ else int(device_memory.free_mib)+ - _device_user_budget_reserve_mib(+ device_memory, device_memory.total_mib or device_memory.free_mib+ )+ ),policy = policy,stream_transformer = stream_transformer,)@@ -3548,8 +3743,13 @@ _RESIDENT_DIT_SLACK_MIN_MIB = 1024def _resident_dit_slack_mib(memory: Any) -> int:+ """The measured-residency margin, or what the user's VRAM Budget keeps free when larger (as the planner reserve)."""base = getattr(memory, "total_mib", None) or getattr(memory, "free_mib", None) or 0- return max(_RESIDENT_DIT_SLACK_MIN_MIB, int(int(base) * _RESIDENT_DIT_SLACK_FRACTION))+ return max(+ _RESIDENT_DIT_SLACK_MIN_MIB,+ int(int(base) * _RESIDENT_DIT_SLACK_FRACTION),+ _device_user_budget_reserve_mib(memory, int(base)),+ )def _resident_dit_fits(memory: Any, dit_mib: int, headroom_mib: int, other_mib: int) -> bool:@@ -6544,7 +6744,21 @@ def image_activation_verdict(# false refusal at or below the default resolution, because the `needed <= planned` arm already exempts every# request the load itself budgeted for.numbers = dict(needed_mib = int(needed), tiled_needed_mib = tiled, budget_mib = int(budget))- if int(needed) + overhead <= int(budget) or (not conditioned and needed <= planned):+ if int(needed) + overhead <= int(budget):+ return ImageActivationVerdict(ACTIVATION_RUN, **numbers)+ if not conditioned and needed <= planned:+ if (+ tiled is not None+ and int(tiled) + overhead <= int(budget)+ and _device_user_budget_reserve_mib(+ device_memory, device_memory.total_mib or device_memory.free_mib+ )+ > _reserve_mib(+ _budget_reserve_kind(device_memory),+ device_memory.total_mib or device_memory.free_mib,+ )+ ):+ return ImageActivationVerdict(ACTIVATION_TILE, **numbers)return ImageActivationVerdict(ACTIVATION_RUN, **numbers)if tiled is not None and (int(tiled) + overhead <= int(budget) or (not conditioned and tiled <= planned)diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.pyindex 0b9865ffce5..fccf44aef54 100644--- a/studio/backend/core/inference/diffusion_multigpu.py+++ b/studio/backend/core/inference/diffusion_multigpu.py@@ -305,21 +305,40 @@ def probe_devices(ordinals: Sequence[int]) -> dict[int, DeviceProbe]:def best_secondary(- selection: MultiGpuSelection, probes: Optional[dict[int, DeviceProbe]] = None+ selection: MultiGpuSelection,+ probes: Optional[dict[int, DeviceProbe]] = None,+ *,+ mode: Optional[str] = None,) -> Optional[int]:if not selection.secondaries:return None+ from .diffusion_memory import (+ DeviceMemory,+ _fast_device_budget_mib,+ _safe_device_budget_mib,+ _user_budget_reserve_mib,+ )++ budgeted = _user_budget_reserve_mib(1 << 20) > 0+ limit_of = _fast_device_budget_mib if mode == "fast" else _safe_device_budget_mib++ def usable(free: Optional[int], total: Optional[int]) -> int:+ if free is None:+ return -1+ if not budgeted:+ return int(free)+ memory = DeviceMemory("cuda", "cuda", "discrete_vram", int(free), total)+ return int(limit_of(memory) or 0)+if probes is None and selection.automatic:- free = {o: _free_total_mib(o)[0] for o in selection.secondaries}- return max(- selection.secondaries, key = lambda o: (free[o] if free[o] is not None else -1, -o)- )+ free = {o: _free_total_mib(o) for o in selection.secondaries}+ return max(selection.secondaries, key = lambda o: (usable(*free[o]), -o))if probes is None:probes = probe_devices((selection.primary, *selection.secondaries))def key(o: int) -> tuple[int, int]:p = probes.get(o)- return (p.free_mib if p is not None and p.free_mib is not None else -1, -o)+ return (usable(p.free_mib, p.total_mib) if p is not None else -1, -o)return max(selection.secondaries, key = key)@@ -730,10 +749,10 @@ def refine_plan_for_multigpu(sizes = _loaded_component_mib(pipe)if not sizes:return one_card_plan("component sizes are unreadable")- secondary = best_secondary(selection)+ mode = getattr(plan, "requested_mode", None)+ secondary = best_secondary(selection, mode = mode)if secondary is None: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 one_card_plan(f"free memory of cuda:{secondary} is unknown")@@ -890,9 +909,18 @@ 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 layersplit prices its block-only cards the same way). None when the card cannot be read."""from .diffusion_layer_split_plan import secondary_reserve_mib+ from .diffusion_memory import _user_budget_reserve_mib- free, _total = _free_total_mib(int(ordinal))- return None if free is None else max(0, int(free) - secondary_reserve_mib())+ free, total = _free_total_mib(int(ordinal))+ if free is None:+ return None+ return max(0, int(free) - max(secondary_reserve_mib(), _user_budget_reserve_mib(total or free)))+++def _replica_reserve_mib(free: Optional[int], total: Optional[int]) -> int:+ """Room a CFG replica leaves free on its card: 1 GiB, or what the user's VRAM Budget keeps free when larger."""+ from .diffusion_memory import _user_budget_reserve_mib+ return max(1024, _user_budget_reserve_mib(total or free))def secondary_device_memory(ordinal: int) -> Any:@@ -2851,8 +2879,9 @@ class CfgParallelRouter:need_mib = sum(t.numel() * t.element_size() for t in (*module.parameters(), *module.buffers())) // (1 << 20)- free = self._secondary_free_mib()- if free is not None and need_mib + 1024 > free:+ free, total = self._secondary_free_total_mib()+ reserve = _replica_reserve_mib(free, total)+ if free is not None and need_mib + reserve > free:raise RuntimeError(f"replica needs {need_mib} MiB, {free} MiB free on {self.secondary}")@@ -2951,10 +2980,9 @@ class CfgParallelRouter:and all(a is b for a, b in zip(declined[1], held))):raise _KVMirrorDeclined("prefix cache does not fit on the replica card")- # Admission's 1 GiB margin: decline before copying rather than OOM mid-copy and lose the replica.need = sum(t.numel() * t.element_size() for t in held)- free = self._secondary_free_mib()- if free is not None and need + (1024 << 20) > free * (1 << 20):+ free, total = self._secondary_free_total_mib()+ if free is not None and need + (_replica_reserve_mib(free, total) << 20) > free * (1 << 20):self.kv_declined[id(cache)] = (cache, held)self.stats["kv_cache_declined"] += 1if self.logger is not None:@@ -2975,9 +3003,9 @@ class CfgParallelRouter:self.stats["kv_cache_copies"] += 1return mirror- def _secondary_free_mib(self) -> Optional[int]:- """Free MiB on the replica card, counting its allocator's cached-but-unused blocks (as the admission does)."""- free, _total = _free_total_mib(self.secondary.index)+ def _secondary_free_total_mib(self) -> tuple[Optional[int], Optional[int]]:+ """(free, total) MiB on the replica card; free counts the allocator's cached-but-unused blocks."""+ free, total = _free_total_mib(self.secondary.index)if free is not None:with contextlib.suppress(Exception):torch = _torch()@@ -2985,7 +3013,7 @@ class CfgParallelRouter:torch.cuda.memory_reserved(self.secondary)- torch.cuda.memory_allocated(self.secondary)) // (1 << 20)- return free+ return free, totaldef _run_replica(self, args: tuple, kwargs: dict) -> Any:# Unpredicted: nothing verified the copies made before the primary branch ran, and an input edited in place@@ -3111,9 +3139,19 @@ def install_cfg_parallel(need_mib = sum(t.numel() * t.element_size() for t in (*denoiser.parameters(), *denoiser.buffers())) // (1 << 20)- best = max(candidates, key = lambda o: probes[o].free_mib or -1)++ def usable(o: int) -> int:+ free_o = probes[o].free_mib+ if free_o is None:+ return -1+ return int(free_o) - _replica_reserve_mib(free_o, probes[o].total_mib)++ best = max(candidates, key = usable)free = probes[best].free_mib- if free is not None and need_mib + 1024 > free:+ if (+ free is not None+ and need_mib + _replica_reserve_mib(free, probes[best].total_mib) > free+ ):reason = f"replica needs {need_mib} MiB, {free} MiB free on cuda:{best}"else:graph = _resident_graph(denoiser)diff --git a/studio/backend/core/inference/diffusion_multistage.py b/studio/backend/core/inference/diffusion_multistage.pyindex 7550b7bf5b9..c94c0bd6245 100644--- a/studio/backend/core/inference/diffusion_multistage.py+++ b/studio/backend/core/inference/diffusion_multistage.py@@ -45,12 +45,15 @@ def companions_fit_beside_denoiser(pipe: Any, companions: Iterable[Any]) -> boolparam = next(dits[0].parameters()) if dits else Noneif param is None or param.device.type != "cuda":return False- free, _total = torch.cuda.mem_get_info(param.device)+ free, total = torch.cuda.mem_get_info(param.device)idle = torch.cuda.memory_reserved(param.device) - torch.cuda.memory_allocated(param.device)+ from .diffusion_memory import _user_budget_reserve_mib++ reserve = _user_budget_reserve_mib(int(total) >> 20) << 20except Exception: # noqa: BLE001 -- no CUDA / no denoiser: keep the stock offloadreturn Falseneed = sum(module_bytes(m) for m in companions if m is not None) + HOLD_MARGIN_BYTES- return free + max(0, idle) >= need+ return free + max(0, idle) - reserve >= need@contextlib.contextmanagerdiff --git a/studio/backend/core/inference/diffusion_segment.py b/studio/backend/core/inference/diffusion_segment.pyindex 097809b5071..f88a6e53632 100644--- a/studio/backend/core/inference/diffusion_segment.py+++ b/studio/backend/core/inference/diffusion_segment.py@@ -821,9 +821,10 @@ def _resident_cuda_ordinal() -> Optional[int]:def _cuda_free_mib(ordinal: int) -> tuple[Optional[int], Optional[int]]:"""(free, total) MiB on CUDA card ``ordinal``: driver free plus this process's reusable allocator cache, the same- credit the render's memory check gives (diffusion_memory.cuda_reclaimable_bytes). Parking leaves SAM's emptied- weights in that cache on purpose, so driver free alone would send the next detection to the CPU on a warm card- (ComfyUI's get_free_memory likewise adds reserved minus active bytes)."""+ credit the render's memory check gives (diffusion_memory.cuda_reclaimable_bytes), less the user's VRAM Budget+ reserve (raw at the default), so the segmenter neither lands on nor stays resident in that reserve. Parking leaves+ SAM's emptied weights in that cache on purpose, so driver free alone would send the next detection to the CPU on a+ warm card (ComfyUI's get_free_memory likewise adds reserved minus active bytes)."""try:import torchfree, total = torch.cuda.mem_get_info(ordinal)@@ -835,6 +836,12 @@ def _cuda_free_mib(ordinal: int) -> tuple[Optional[int], Optional[int]]:except Exception: # noqa: BLE001 -- no allocator reading: driver free still standsreclaimable = 0free = min(int(free) + max(0, int(reclaimable)), int(total))+ try:+ from core.inference.diffusion_memory import user_budget_reserve_bytes+ reserve = int(user_budget_reserve_bytes("cuda", total) or 0)+ except Exception: # noqa: BLE001 -- no Budget reading: the raw figure stands+ reserve = 0+ free = max(0, free - reserve)return int(free // (1024 * 1024)), int(total // (1024 * 1024))diff --git a/studio/backend/core/inference/diffusion_small_host.py b/studio/backend/core/inference/diffusion_small_host.pyindex df5fd58183f..5040a820af4 100644--- a/studio/backend/core/inference/diffusion_small_host.py+++ b/studio/backend/core/inference/diffusion_small_host.py@@ -659,6 +659,36 @@ def _group_tensors(group: Any) -> list:return out+def _prefetch_budget_bytes(device: Any) -> int:+ """Bytes of encoder groups the prefetcher may hold on ``device`` ahead of compute."""+ try:+ import torch++ from .diffusion_memory import user_budget_reserve_bytes++ free, total = torch.cuda.mem_get_info(device)+ reserve = user_budget_reserve_bytes(device, total)+ free = max(0, int(free) - reserve)+ if reserve > 0 and free < _PREFETCH_MIN_BYTES:+ return 0+ return max(_PREFETCH_MIN_BYTES, min(_PREFETCH_MAX_BYTES, free // 8))+ except Exception: # noqa: BLE001+ return _PREFETCH_MIN_BYTES+++def _prefetch_budget_lowered(device: Any) -> bool:+ """True when the user's VRAM Budget keeps a reserve on ``device``."""+ try:+ import torch++ from .diffusion_memory import user_budget_reserve_bytes++ _free, total = torch.cuda.mem_get_info(device)+ return user_budget_reserve_bytes(device, total) > 0+ except Exception: # noqa: BLE001+ return False++class _EncoderPrefetcher:"""Copies a memory-mapped encoder's offload groups ahead of its forward, in the previous forward's order, on aworker thread through a pinned ring (diffusers pins each group on the calling thread). Off-order groups and worker@@ -684,6 +714,8 @@ class _EncoderPrefetcher:self.ready: dict = {} # id(group) -> (device tensors, event)self.inflight = 0self.budget = _PREFETCH_MIN_BYTES+ self.strict = False # lowered Budget: an ahead group must fit the window, else it copies synchronously+ self.skipped: dict = {} # group id -> times the worker left to a synchronous copyself.pos = 0self.stop = Falseself.worker = None@@ -691,6 +723,8 @@ class _EncoderPrefetcher:self.stage: list = []self.stage_events: list = []self.slot = 0+ # The worker and a synchronous onload copy (a group skipped under a lowered Budget) share the staging ring.+ self.copy_lock = threading.Lock()self.stats = {"prefetched": 0, "sync": 0, "passes": 0}self.by_id = {id(g): g for g in groups}@@ -713,6 +747,11 @@ class _EncoderPrefetcher:def _copy_group(self, group: Any) -> tuple:"""Device copies of ``group``'s host tensors, issued on the side stream. Returns (tensors, event, bytes)."""+ # Held across staging write, H2D enqueue and slot event so the other thread cannot reuse a slot in between.+ with self.copy_lock:+ return self._copy_group_locked(group)++ def _copy_group_locked(self, group: Any) -> tuple:import torchself._ensure_stage()@@ -764,6 +803,14 @@ class _EncoderPrefetcher:done.record(stream)return moved, done, nbytes+ def _group_bytes(self, group: Any) -> int:+ """Host bytes :meth:`_copy_group` would stage for ``group``."""+ n = 0+ for _t, src in _group_tensors(group):+ if src.device.type == "cpu" and src.is_contiguous() and not src.is_pinned():+ n += int(src.numel()) * int(src.element_size())+ return n+def _attach(self, group: Any, moved: list, done: Any) -> None:import torch@@ -782,15 +829,25 @@ class _EncoderPrefetcher:if self.device.type == "cuda":torch.cuda.set_device(self.device)for gid in order:+ group = self.by_id.get(gid)+ need = self._group_bytes(group) if self.strict and group is not None else 0with self.cond:+ if need > self.budget:+ self.skipped[gid] = self.skipped.get(gid, 0) + 1+ self.cond.notify_all()+ continue# A group the forward onloads twice waits for its first copy to be taken.while not self.stop and (- (self.inflight > 0 and self.inflight >= self.budget) or gid in self.ready+ (+ self.inflight + need > self.budget+ if self.strict+ else self.inflight > 0 and self.inflight >= self.budget+ )+ or gid in self.ready):self.cond.wait(0.05)if self.stop:return- group = self.by_id.get(gid)if group is None:continuemoved, done, n = self._copy_group(group)@@ -814,6 +871,7 @@ class _EncoderPrefetcher:self.worker = Nonewith self.cond:self.ready.clear()+ self.skipped.clear()self.inflight = 0def begin(self) -> None:@@ -833,11 +891,10 @@ class _EncoderPrefetcher:)if not self.order:return # first forward: synchronous copies, and it records the order- try:- free, _total = torch.cuda.mem_get_info(self.device)- self.budget = max(_PREFETCH_MIN_BYTES, min(_PREFETCH_MAX_BYTES, int(free) // 8))- except Exception: # noqa: BLE001- self.budget = _PREFETCH_MIN_BYTES+ self.budget = _prefetch_budget_bytes(self.device)+ if self.budget <= 0:+ return # no budgeted room: every group copies synchronously, as on the first forward+ self.strict = _prefetch_budget_lowered(self.device)self._order_after_compute()self.worker = threading.Thread(target = self._run, args = (list(self.order),), daemon = True, name = "unsloth-encoder-prefetch"@@ -867,9 +924,16 @@ class _EncoderPrefetcher:if expected == gid:self.pos += 1with self.cond:- while gid not in self.ready and self.error is None and self.worker.is_alive():+ while (+ gid not in self.ready+ and not self.skipped.get(gid)+ and self.error is None+ and self.worker.is_alive()+ ):self.cond.wait(0.05)entry = self.ready.pop(gid, None)+ if entry is None and self.skipped.get(gid):+ self.skipped[gid] -= 1if entry is not None:self.inflight -= entry[2]self.cond.notify_all()diff --git a/studio/backend/core/inference/diffusion_vae_fused.py b/studio/backend/core/inference/diffusion_vae_fused.pyindex 26a1cb6dda5..50499f5a4c4 100644--- a/studio/backend/core/inference/diffusion_vae_fused.py+++ b/studio/backend/core/inference/diffusion_vae_fused.py@@ -1486,12 +1486,15 @@ _TILE_PEAK_FACTOR = 24def _tile_batch_cap(vae: Any, z: Any) -> int:- """Tiles per decoder call: env override, else what half the free VRAM holds, at most 4."""+ """Tiles per decoder call."""raw = os.environ.get(TILE_BATCH_ENV, "").strip()if raw.isdigit() and int(raw) > 0:return int(raw)try:- free, _ = _torch().cuda.mem_get_info(z.device)+ from .diffusion_memory import user_budget_reserve_bytes++ free, total = _torch().cuda.mem_get_info(z.device)+ free = max(0, int(free) - user_budget_reserve_bytes(z.device, total))norm_out = getattr(getattr(vae, "decoder", None), "norm_out", None)c_last = int(norm_out.gamma.numel()) if norm_out is not None else 128px = int(vae.tile_sample_min_height) * int(vae.tile_sample_min_width)diff --git a/studio/backend/core/inference/diffusion_vae_prebuild.py b/studio/backend/core/inference/diffusion_vae_prebuild.pyindex 7bb2c93c104..c6381be473e 100644--- a/studio/backend/core/inference/diffusion_vae_prebuild.py+++ b/studio/backend/core/inference/diffusion_vae_prebuild.py@@ -97,8 +97,10 @@ def maybe_kick(job = plan(pipe)if job is None:return False- free, _total = torch.cuda.mem_get_info(job["device"])- if free < _MIN_FREE_BYTES:+ from .diffusion_memory import user_budget_reserve_bytes++ free, total = torch.cuda.mem_get_info(job["device"])+ if free - user_budget_reserve_bytes(job["device"], total) < _MIN_FREE_BYTES:return Falsereturn _spawn(job, logger)except Exception as exc: # noqa: BLE001 - a prebuild, never a failed loaddiff --git a/studio/backend/core/inference/diffusion_vae_tiling.py b/studio/backend/core/inference/diffusion_vae_tiling.pyindex 3c49e7be04a..5bb46a097db 100644--- a/studio/backend/core/inference/diffusion_vae_tiling.py+++ b/studio/backend/core/inference/diffusion_vae_tiling.py@@ -280,11 +280,14 @@ def _free_mib("""(free MiB after the fp32 output accumulator, decoder bytes per param / 2); None off CUDA."""import torch+ from .diffusion_memory import user_budget_reserve_bytes+if getattr(z, "device", None) is None or z.device.type != "cuda":return None- free, _ = torch.cuda.mem_get_info(z.device)+ free, total = torch.cuda.mem_get_info(z.device)if cached:free += torch.cuda.memory_reserved(z.device) - torch.cuda.memory_allocated(z.device)+ free -= user_budget_reserve_bytes(z.device, total)ratio = _geometry(vae)[0]frames = z.shape[2] if z.dim() == 5 else 1# fp32 accumulatordiff --git a/studio/backend/core/inference/media_locality.py b/studio/backend/core/inference/media_locality.pyindex f3227fc06fd..211ecc82bf4 100644--- a/studio/backend/core/inference/media_locality.py+++ b/studio/backend/core/inference/media_locality.py@@ -276,8 +276,10 @@ def plan_gpu_ordinal() -> Optional[int]:if pinned:return ordinalfrom core.inference.diffusion_device import auto_cuda_ordinal_for_load+ from core.inference.diffusion_memory import upcoming_load_budget- return auto_cuda_ordinal_for_load()+ with upcoming_load_budget():+ return auto_cuda_ordinal_for_load()def catalog_gpu_ordinal() -> Optional[int]:diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex a2ead652948..cf58f1e88a7 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -126,6 +126,10 @@ from .diffusion_multigpu import (with_load_selection,)from .diffusion_memory import (+ commit_load_budget_fraction,+ release_load_budget_fraction,+ vram_budget_scope,+ carry_load_budget,DEFAULT_BASE_OVERHEAD_MIB,DEFAULT_GROUP_BLOCKS,MEMORY_MODE_AUTO,@@ -1850,8 +1854,10 @@ def _h3_budgeted_launch_flags(out = list(flags)# Never replace a UMA pinned-weight reserve (-17.05): it would hand sd.cpp the memory those weights take.- if not explicit_vram_budget_enabled() or not max_vram_is_placeholder(max_vram_value(out)):+ if not max_vram_is_placeholder(max_vram_value(out)):return out+ if not explicit_vram_budget_enabled():+ return _h3_spare_user_reserve(runtime, out, read_free = True)probe = getattr(runtime, "vram_free_probe", None)try:free = probe() if probe is not None else None@@ -1877,10 +1883,13 @@ def _h3_budgeted_launch_flags(if not budget:if cap is not None and not known_small:out = with_max_vram_budget(out, cap)+ else:+ # "-1" is sd.cpp's RAW free reading: under a lowered VRAM Budget it must spare the reserve too, and a+ out = _h3_spare_user_reserve(runtime, out, free = free if known_small else None)logger.info("video.h3_native_vram_budget: free VRAM unreadable or too small (%s); %s",free,- f"--max-vram {max_vram_value(out)}" if cap is not None else "keeping --max-vram -1",+ f"--max-vram {max_vram_value(out)}",)return outout = with_max_vram_budget(out, budget)@@ -1893,6 +1902,104 @@ def _h3_budgeted_launch_flags(return out+class _H3UnpinnedMultiCardReserve(int):+ """The smallest card's VRAM Budget reserve on an unpinned multi-card H3 load (``_h3_card_reserve_bytes`` with ``single_card_only``)."""+++def _h3_spare_user_reserve(+ runtime: Any,+ flags: "list[str]",+ *,+ free: Any = None,+ read_free: bool = False,+) -> list[str]:+ """``flags`` with the ``--max-vram -1`` placeholder kept within a lowered VRAM Budget (unchanged at the default, off CUDA, or when the reserve is unread)."""+ from .sd_cpp_args import (+ GRAPH_CUT_VRAM_FLAGS,+ graph_cut_budget_gib,+ max_vram_is_placeholder,+ max_vram_value,+ with_max_vram_budget,+ )++ from .video_minimax_h3 import H3NativeMemoryRefusal++ if not max_vram_is_placeholder(max_vram_value(flags)):+ return list(flags)+ probe = getattr(runtime, "vram_reserve_probe", None)+ try:+ reserve = probe() if probe is not None else None+ except Exception: # noqa: BLE001 -- an unreadable reserve keeps sd.cpp's own reading+ reserve = None+ if not reserve or int(reserve) <= 0:+ return list(flags)+ multi_card = isinstance(reserve, _H3UnpinnedMultiCardReserve)+ if read_free:+ free_probe = getattr(runtime, "vram_free_probe", None)+ try:+ free = free_probe() if free_probe is not None else None+ except Exception: # noqa: BLE001 -- an unreadable card keeps the single-card spare+ free = None+ if not multi_card:+ if isinstance(free, dict):+ small = next(+ (v is not None for v in free.values() if graph_cut_budget_gib(v) is None), False+ )+ else:+ small = free is not None and graph_cut_budget_gib(free) is None+ free = free if small else None++ def _refuse(shown_bytes: Optional[int]) -> H3NativeMemoryRefusal:+ shown = (+ "an unreadable amount of"+ if shown_bytes is None+ else (f"about {max(0.0, shown_bytes / float(1 << 30)):.1f} GiB of")+ )+ return H3NativeMemoryRefusal(+ f"MiniMax-H3 has {shown} VRAM left inside the VRAM Budget on the render card, "+ "too little for the graph-cut render. Free VRAM on that card, raise the VRAM Budget, or lower the "+ "resolution or duration."+ )++ sd_spare_bytes = int(-float(GRAPH_CUT_VRAM_FLAGS[1]) * (1 << 30))+ if multi_card:+ readings = list(free.values()) if isinstance(free, dict) else [free]+ if not readings or any(value is None for value in readings):+ raise _refuse(None)+ smallest = min(int(value) for value in readings)+ # Rounded DOWN to 0.01 GiB, so the cap never exceeds the tightest card's budget-adjusted free less 1 GiB.+ cap = max(0, (smallest - sd_spare_bytes) * 100 // (1 << 30)) / 100.0+ if cap <= 0:+ raise _refuse(smallest)+ out = with_max_vram_budget(flags, cap)+ logger.info(+ "video.h3_native_vram_budget: --max-vram %s (unpinned multi-card: smallest budget-adjusted free %s "+ "less sd.cpp's 1 GiB spare)",+ max_vram_value(out),+ smallest,+ )+ return out+ # Rounded UP to 0.01 GiB, so the spare never undercuts the reserve; the refusal then checks THIS spare.+ spare_hundredths = int(-float(GRAPH_CUT_VRAM_FLAGS[1]) * 100) + -(+ -int(reserve) * 100 // (1 << 30)+ )+ spare_bytes = -(-spare_hundredths * (1 << 30) // 100)+ if isinstance(free, dict):+ known = [int(v) for v in free.values() if v is not None]+ raise _refuse(min(known) if known else None)+ if free is not None and int(free) + int(reserve) <= spare_bytes:+ raise _refuse(int(free))+ out = list(flags)+ index = out.index("--max-vram") + 1+ out[index] = f"-{spare_hundredths // 100}.{spare_hundredths % 100:02d}"+ logger.info(+ "video.h3_native_vram_budget: --max-vram %s (sd.cpp's free reading less the VRAM Budget reserve %s)",+ out[index],+ reserve,+ )+ return out++def _h3_restart_for_retry(slot: Any, reason: str) -> bool:"""Stop for a retry unless a release is pending; under the slot lock so a racing release is not lost."""restart = getattr(slot, "restart_for_retry", None)@@ -2520,16 +2627,51 @@ def _h3_planned_denoiser_bytes(return None+def _user_reserve_bytes(device: Any, total_bytes: Optional[int]) -> int:+ """What the user's VRAM Budget keeps free on ``device`` (total ``total_bytes``), in bytes."""+ from .diffusion_memory import user_budget_reserve_bytes+ return user_budget_reserve_bytes(device, total_bytes)+++def _planned_free_less_user_reserve_mib(memory: Any) -> Optional[int]:+ """The load-time placement guard's free MiB."""+ free = getattr(memory, "free_mib", None)+ if free is None:+ return None+ from .diffusion_memory import _device_user_budget_reserve_mib++ return int(free) - _device_user_budget_reserve_mib(+ memory, getattr(memory, "total_mib", None) or free+ )+++def _request_available_bytes(device_obj: Any, module: Any) -> int:+ """A request guard's available VRAM on ``device_obj``."""+ from utils.hardware import trusted_mem_get_info++ free_bytes, total_bytes = trusted_mem_get_info(device_obj, module = module)+ reserved_bytes = module.memory_reserved(device_obj) if hasattr(module, "memory_reserved") else 0+ return int(free_bytes) + int(reserved_bytes) - _user_reserve_bytes(device_obj, total_bytes)++def _h3_free_device_bytes(device: str) -> Optional[int]:"""Live free VRAM, or None when it cannot be read. None means "cannot tell", never zero."""+ free = _h3_signed_free_device_bytes(device)+ return None if free is None else max(0, free)+++def _h3_signed_free_device_bytes(device: str) -> Optional[int]:+ """:func:`_h3_free_device_bytes` before the clamp at 0."""if device != "cuda":return Nonetry:from utils.hardware import trusted_mem_get_info+ from .diffusion_memory import _user_budget_reserve_mib+# Windows ROCm over-reports free (#8403); pinning the denoiser on that reading is how a card that is already- # full still looks roomy- return int(trusted_mem_get_info()[0])+ free, total = trusted_mem_get_info()+ return int(free) - (_user_budget_reserve_mib(int(total) >> 20) << 20)except Exception: # noqa: BLE001 -- an unreadable card decides nothingreturn None@@ -2542,7 +2684,9 @@ def _h3_card_memory_bytes() -> tuple[Optional[int], Optional[int]]:"""(free, total) VRAM of the H3 render card, or (None, None). No pin = ordinal 0. nvidia-smi / amd-smi / sysfsfirst (no CUDA context); torch only when none answers and ``allow_context``, as the residency and pressure reads- always did. The pre-spawn budget passes False: it never pays for a context."""+ always did. The pre-spawn budget passes False: it never pays for a context. Free is less the user's VRAM Budget+ reserve (raw at the default), so the sd.cpp resident-vs-offload pick, its ``--max-vram`` probe and the+ server-pressure check all keep that share free."""if device != "cuda":return None, Nonefound = _h3_read_card_memory_bytes(ordinal, no_context = True)@@ -2568,7 +2712,8 @@ def _h3_read_card_memory_bytes(if total is None or used is None:return None, Nonetotal_bytes = int(float(total) * 1024**3)- return max(0, int((float(total) - float(used)) * 1024**3)), total_bytes+ free_bytes = int((float(total) - float(used)) * 1024**3)+ return max(0, free_bytes - _user_reserve_bytes("cuda", total_bytes)), total_bytesexcept Exception: # noqa: BLE001 -- an unreadable card decides nothingreturn None, Nonereturn None, None@@ -2581,14 +2726,87 @@ def _h3_card_free_bytes(single_card_only: bool = False,allow_context: bool = True,) -> Optional[int]:- """Free VRAM of the H3 render card, or None. ``single_card_only``: None on multi-card boxes, where one card's- scalar budget applied to every card would steer sd.cpp's own device pick. ``allow_context``: see- ``_h3_card_memory_bytes``."""+ """Free VRAM of the H3 render card, or None."""if single_card_only and _h3_visible_card_count(device) != 1:- return None+ readings = _h3_unpinned_multi_card_readings(device)+ if not readings or any(free is None for free, _total in readings):+ return None+ return min(free for free, _total in readings)return _h3_card_memory_bytes(device, ordinal, allow_context = allow_context)[0]+def _h3_unpinned_multi_card_readings(+ device: Optional[str],+) -> Optional[list[tuple[Optional[int], int]]]:+ """(budget-adjusted free, total) bytes of every visible card for an unpinned multi-card H3 render under a lowered VRAM Budget, or None at the default / off CUDA / unread."""+ if device != "cuda":+ return None+ from .diffusion_memory import user_budget_reserve_share++ if user_budget_reserve_share() <= 0:+ return None+ try:+ from utils.hardware import get_visible_gpu_utilization, gpu_query++ with gpu_query.fresh_reads():+ devices = get_visible_gpu_utilization(no_context = True).get("devices", [])+ out: list[tuple[Optional[int], int]] = []+ for entry in devices:+ total = entry.get("vram_total_gb")+ if total is None:+ return None+ total_bytes = int(float(total) * 1024**3)+ used = entry.get("vram_used_gb")+ free = (+ None+ if used is None+ else max(+ 0,+ int((float(total) - float(used)) * 1024**3)+ - _user_reserve_bytes("cuda", total_bytes),+ )+ )+ out.append((free, total_bytes))+ except Exception: # noqa: BLE001 -- an unreadable card decides nothing+ return None+ return out or None+++def _h3_card_reserve_bytes(+ device: Optional[str],+ ordinal: Optional[int],+ *,+ single_card_only: bool = False,+) -> Optional[int]:+ """Bytes the user's VRAM Budget keeps free on the H3 render card."""+ if device != "cuda":+ return 0+ from .diffusion_memory import user_budget_reserve_share++ if user_budget_reserve_share() <= 0:+ return 0+ try:+ from utils.hardware import get_visible_gpu_utilization, gpu_query++ with gpu_query.fresh_reads():+ devices = get_visible_gpu_utilization(no_context = True).get("devices", [])+ want = 0 if ordinal is None else int(ordinal)+ totals = [+ int(float(entry["vram_total_gb"]) * 1024**3)+ for entry in devices+ if entry.get("vram_total_gb") is not None+ and ((single_card_only and len(devices) != 1) or entry.get("visible_ordinal") == want)+ ]+ except Exception: # noqa: BLE001 -- an unreadable card decides nothing+ return None+ if not totals:+ return None+ smallest = min(_user_reserve_bytes("cuda", total) for total in totals)+ if single_card_only and len(devices) != 1:+ return _H3UnpinnedMultiCardReserve(smallest)+ return smallest++def _h3_visible_card_count(device: Optional[str]) -> Optional[int]:if device != "cuda":return None@@ -2627,12 +2845,17 @@ def _h3_device_capacity_bytes(device: str) -> Optional[int]:pipeline is not torn down until ``load_pipeline`` runs, so a free reading taken while the planis being built describes the OLD model's occupancy, not this load's. Capacity cannot -- it isan upper bound on any later free reading, so "does not fit in the whole card" still holds when- the loader asks again against live free memory."""+ the loader asks again against live free memory. Less the user's VRAM Budget reserve, which+ ``_h3_free_device_bytes`` charges at placement, so planning and placement cannot disagree."""if device != "cuda":return Nonetry:import torch- return int(torch.cuda.mem_get_info()[1])++ from .diffusion_memory import _user_budget_reserve_mib++ total = int(torch.cuda.mem_get_info()[1])+ return max(0, total - (_user_budget_reserve_mib(total >> 20) << 20))except Exception: # noqa: BLE001 -- an unreadable card decides nothingreturn None@@ -2662,8 +2885,7 @@ def _h3_residency_budget_bytes(fragmentation: bool = True,top_gb: float = 0.0,) -> int:- """Device bytes the resident set may occupy for this request: free + allocator cache + resident, minus the- request's largest phase. Negative = not even fully streamed fits. Unreadable is 0 (all streamed)."""+ """Device bytes the resident set may occupy for this request."""try:import torch@@ -2671,7 +2893,8 @@ def _h3_residency_budget_bytes(from .video_minimax_h3_residency import h3_phase_need_gbfrom .video_minimax_h3_te import H3_TE_STREAMED_GB- free = _h3_free_device_bytes(device)+ # Signed: a card already inside the budget reserve owes that deficit before cache and resident groups count.+ free = _h3_signed_free_device_bytes(device)if free is None:return 0cached = int(torch.cuda.memory_reserved()) - int(torch.cuda.memory_allocated())@@ -3150,7 +3373,7 @@ def _stage_denoiser_for_quant(device = torch.device(getattr(target, "torch_device", None) or "cuda")from utils.hardware import trusted_mem_get_info- free_bytes, _ = trusted_mem_get_info(device, module = torch.cuda)+ free_bytes, total_bytes = trusted_mem_get_info(device, module = torch.cuda)largest_linear = max((_module_dense_bytes(m)@@ -3161,6 +3384,7 @@ def _stage_denoiser_for_quant()budget = (int(free_bytes)+ - _user_reserve_bytes(device, total_bytes)- DEFAULT_BASE_OVERHEAD_MIB * 1024 * 1024- _STAGE_LINEAR_WORKSPACE * largest_linear)@@ -4397,6 +4621,7 @@ class VideoBackend:# ── background load + progress ───────────────────────────────────────────@pauses_background_embedding+ @vram_budget_scope("video", load = True)def begin_load(self,repo_id: str,@@ -4524,7 +4749,7 @@ class VideoBackend:)account_thread(- target = self._run_load,+ target = carry_load_budget(self._run_load),kwargs = dict(repo_id = repo_id,display_repo_id = display_repo_id,@@ -4556,6 +4781,7 @@ class VideoBackend:# The multi-GPU selection (begin_load's ``_gpu_ordinals``) is visible to this load's planner and placement only.@with_load_selection@scoped_local_files_only+ @vram_budget_scope("video", load = True)def _run_load(self, **kwargs: Any) -> None:token = kwargs.get("_load_token")# This load's own event: a later load replaces self._cancel_event rather than clearing it.@@ -5048,6 +5274,7 @@ class VideoBackend:self._loading.error = modelscope_missing(exc) or redact_native_paths(str(exc))self._loading.error_code = unified_memory_refusal_code(exc)+ @vram_budget_scope("video", load = True)def _run_load_h3_native(self,*,@@ -5659,6 +5886,16 @@ class VideoBackend:if native_device != "cpu"else None),+ vram_reserve_probe = (+ functools.partial(+ _h3_card_reserve_bytes,+ native_device,+ native_ordinal if native_device_name else None,+ single_card_only = not native_device_name,+ )+ if native_device != "cpu"+ else None+ ),env = native_env,cudnn = native_cudnn,server_slot = (@@ -5750,6 +5987,7 @@ class VideoBackend:}),)+ commit_load_budget_fraction("video")finally:self._teardown_waiters -= 1if native_device == "cpu":@@ -6897,6 +7135,7 @@ class VideoBackend:except Exception: # noqa: BLE001 -- progress totals are best-effort onlyreturn None+ @vram_budget_scope("video", load = True)def download_plan(self,repo_id: str,@@ -7866,6 +8105,7 @@ class VideoBackend:@scoped_allow_oversized_load@rocm_probe_load_scoped@scoped_local_files_only+ @vram_budget_scope("video", load = True)def load_pipeline(self,repo_id: str,@@ -9501,7 +9741,7 @@ class VideoBackend:plan = refinedplan = _video_refine_for_multigpu(fam, pipe, plan, logger)vram_floor_mib = _video_offload_vram_floor_mib(pipe, plan)- free_mib = getattr(getattr(plan, "device_memory", None), "free_mib", None)+ free_mib = _planned_free_less_user_reserve_mib(getattr(plan, "device_memory", None))if vram_floor_mib is not None and free_mib is not None:shortfall = video_offload_shortfall_message(family = fam.name,@@ -9845,6 +10085,7 @@ class VideoBackend:resolved = resolved,bg_compile = load_bg_compile,)+ commit_load_budget_fraction("video")self._precommit_globals = Nonepending_encoder = self._ltx25_pending_encoderif (@@ -11083,6 +11324,7 @@ class VideoBackend:h3_residency = residency,resolved = resolved,)+ commit_load_budget_fraction("video")self._precommit_globals = Nonelogger.info("video.loaded: %s (%s, modular diffusers, speed=%s%s, transformer_quant=%s, "@@ -11227,6 +11469,7 @@ class VideoBackend:except Exception: # noqa: BLE001 -- reset is best-effort, never fail a generationpass+ @vram_budget_scope("video")def begin_generate(self,*,@@ -11612,6 +11855,7 @@ class VideoBackend:)@holds_inference+ @vram_budget_scope("video")def generate(self,*,@@ -11784,15 +12028,9 @@ class VideoBackend:if device_module is not None and hasattr(device_module, "mem_get_info"):# Windows ROCm's free half is an over-report and this is a hard refusal, so cap it against the# allocator (#8403).- from utils.hardware import trusted_mem_get_info-- free_bytes, _ = trusted_mem_get_info(device_obj, module = device_module)- reserved_bytes = (- device_module.memory_reserved(device_obj)- if hasattr(device_module, "memory_reserved")- else 0+ available_vram_gb = (+ _request_available_bytes(device_obj, device_module) / 1_000_000_000)- available_vram_gb = (free_bytes + reserved_bytes) / 1_000_000_000# Size the floor from the components this load ACTUALLY holds, not from the released bfloat16# pair. Both fields are the ENGAGED schemes (a declined or failed request is recorded as None at# load), so a dense fallback keeps the dense floor.@@ -11840,7 +12078,7 @@ class VideoBackend:raise RuntimeError(f"MiniMax-H3 needs about {required_vram_gb:.1f} GB available "f"VRAM for {width}x{height} at {frames} frames; "- f"{available_vram_gb:.1f} GB is available. Lower the resolution "+ f"{max(0.0, available_vram_gb):.1f} GB is available. Lower the resolution ""or duration, or load the GGUF artifact.")@@ -11850,7 +12088,7 @@ class VideoBackend:# other from the released pair refuses exactly the configuration the quantized components exist# for.shortfall = h3_host_ram_shortfall(- available_vram_gb,+ max(0.0, available_vram_gb),text_encoder_gb = h3_te_resident_gb(state.text_encoder_quant, bf16_gb = H3_TEXT_ENCODER_BF16_GB),@@ -11867,17 +12105,12 @@ class VideoBackend:and hasattr(torch, "cuda")and hasattr(torch.cuda, "mem_get_info")):- from utils.hardware import trusted_mem_get_infodef _available_mib(ordinal: int) -> int:- device_obj = torch.device("cuda", ordinal)- free_bytes, _ = trusted_mem_get_info(device_obj, module = torch.cuda)- reserved_bytes = (- torch.cuda.memory_reserved(device_obj)- if hasattr(torch.cuda, "memory_reserved")- else 0+ available = _request_available_bytes(+ torch.device("cuda", ordinal), torch.cuda)- return int((free_bytes + reserved_bytes) // (1024 * 1024))+ return int(available // (1024 * 1024))shortfall = video_split_shortfall_message(state.vram_split_cards,@@ -11905,8 +12138,6 @@ class VideoBackend:and hasattr(torch.cuda, "mem_get_info")):# Otherwise a card that cannot hold the tier's weights is admitted and dies at the first onload.- from utils.hardware import trusted_mem_get_info-ordinal = getattr(state, "placed_ordinal", None)device_obj = (torch.device("cuda", int(ordinal))@@ -11986,16 +12217,11 @@ class VideoBackend:frames = frames,device = device_obj,)- free_bytes, _ = trusted_mem_get_info(device_obj, module = torch.cuda)- reserved_bytes = (- torch.cuda.memory_reserved(device_obj)- if hasattr(torch.cuda, "memory_reserved")- else 0- )+ available_bytes = _request_available_bytes(device_obj, torch.cuda)shortfall = video_offload_shortfall_message(family = fam.name,floor_mib = int(state.vram_floor_mib),- available_mib = int((free_bytes + reserved_bytes) // (1024 * 1024)),+ available_mib = int(available_bytes // (1024 * 1024)),placement = f"'{state.offload_policy}' offload",width = width,height = height,@@ -13354,6 +13580,7 @@ class VideoBackend:"""Free the committed state. The caller holds _generate_lock (no generationin flight) AND _lock, so the whole teardown is one atomic step: a generationcannot observe a half-torn-down backend."""+ release_load_budget_fraction("video")state, self._state = self._state, Noneif state is not None:server_slot = getattr(getattr(state, "pipe", None), "server_slot", None)diff --git a/studio/backend/core/inference/video_ltx25.py b/studio/backend/core/inference/video_ltx25.pyindex 9946f17ae88..f0d7920df2d 100644--- a/studio/backend/core/inference/video_ltx25.py+++ b/studio/backend/core/inference/video_ltx25.py@@ -1186,6 +1186,11 @@ def start_text_encoder(# The worker is another process: the plan's commit travels in its config (absent when unpinned).client.config.update({"revision": revision} if revision else pinned_revision_kwargs(repo))+ from .diffusion_memory import user_budget_reserve_share++ share = user_budget_reserve_share()+ if share > 0:+ client.config["vram_reserve_share"] = shareclient.start()return clientdiff --git a/studio/backend/core/inference/video_ltx25_te_worker.py b/studio/backend/core/inference/video_ltx25_te_worker.pyindex b41824d502f..926fe8a4b7f 100644--- a/studio/backend/core/inference/video_ltx25_te_worker.py+++ b/studio/backend/core/inference/video_ltx25_te_worker.py@@ -540,8 +540,9 @@ def _encode_device(need = _weights_mib(model) + ENCODE_MARGIN_MIBroom: Optional[int] = Nonetry:- free, _total = getattr(torch, kind).mem_get_info(torch.device(device))- room = free >> 20+ free, total = getattr(torch, kind).mem_get_info(torch.device(device))+ share = float(config.get("vram_reserve_share") or 0.0)+ room = (int(free) - int(int(total) * share)) >> 20except Exception: # noqa: BLE001 -- judged by the budget alonepassbudget = config.get("budget_mib")diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.pyindex ebb8cc9c16d..e960e265f27 100644--- a/studio/backend/core/inference/video_minimax_h3.py+++ b/studio/backend/core/inference/video_minimax_h3.py@@ -1813,6 +1813,7 @@ class MiniMaxH3NativeRuntime:fit_inputs: Any = None# Free VRAM now (bytes or ``{device: bytes}``), read per launch for the explicit ``--max-vram`` budget.vram_free_probe: Optional[Callable[[], Any]] = None+ vram_reserve_probe: Optional[Callable[[], Optional[int]]] = None# 0 / false / off: every render on a fresh one-shot sd-cli.diff --git a/studio/backend/core/inference/video_minimax_h3_vae.py b/studio/backend/core/inference/video_minimax_h3_vae.pyindex 9e1467f03b8..f226a4d1085 100644--- a/studio/backend/core/inference/video_minimax_h3_vae.py+++ b/studio/backend/core/inference/video_minimax_h3_vae.py@@ -989,7 +989,9 @@ def _tile_batch_size(z: Any) -> int:if env.isdigit() and int(env) > 0:return int(env)try:- free, _ = torch.cuda.mem_get_info(z.device)+ from .diffusion_memory import user_budget_reserve_bytes+ free, total = torch.cuda.mem_get_info(z.device)+ free = max(0, int(free) - user_budget_reserve_bytes(z.device, total))except Exception: # noqa: BLE001return 1return int(diff --git a/studio/backend/core/inference/video_stream_residency.py b/studio/backend/core/inference/video_stream_residency.pyindex b6fc6e4188e..1100c7d671d 100644--- a/studio/backend/core/inference/video_stream_residency.py+++ b/studio/backend/core/inference/video_stream_residency.py@@ -488,12 +488,16 @@ def fit_for_request(try:import torch- from .diffusion_memory import _keep_groups_resident, release_resident_groups+ from .diffusion_memory import (+ _keep_groups_resident,+ _user_budget_reserve_mib,+ release_resident_groups,+ )dev = torch.device(device)if dev.type != "cuda":return None- free, _total = torch.cuda.mem_get_info(dev)+ free, total = torch.cuda.mem_get_info(dev)unused = int(torch.cuda.memory_reserved(dev)) - int(torch.cuda.memory_allocated(dev))current = resident_mib(module)# an earlier request that never reached record_request_peak (cancelled, failed) leaves nothing measured@@ -519,6 +523,7 @@ def fit_for_request(if wider > room:room = wider_COUNTS["measured_fits"] += 1+ room = max(0, room - _user_budget_reserve_mib(int(total) >> 20))if not blocks_enabled():top = _top_group_mib(module)room = min(room, top) if top else 0diff --git a/studio/backend/core/inference/video_vae_untiled.py b/studio/backend/core/inference/video_vae_untiled.pyindex 83d8498fe8f..b35304f4a64 100644--- a/studio/backend/core/inference/video_vae_untiled.py+++ b/studio/backend/core/inference/video_vae_untiled.py@@ -73,13 +73,15 @@ def _decoder_itemsize(vae: Any) -> int:def _free_bytes(device: Any) -> Optional[int]:- """Device free memory plus torch's unused cache."""+ """Device free memory plus torch's unused cache, less the user's VRAM Budget reserve (raw at the default)."""try:import torch- free, _ = torch.cuda.mem_get_info(device)+ from .diffusion_memory import user_budget_reserve_bytes++ free, total = torch.cuda.mem_get_info(device)cached = torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)- return int(free) + max(0, int(cached))+ return max(0, int(free) + max(0, int(cached)) - user_budget_reserve_bytes(device, total))except Exception: # noqa: BLE001return Nonediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex db794cbdbe8..6d276b98edc 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -51439,7 +51439,9 @@ async def _selected_gpu_ordinal(gpu_ids, *, allow_ranking: bool = True) -> Optioresolve_diffusion_device_target,resolve_selected_cuda_ordinal,)+ from core.inference.diffusion_memory import snapshot_upcoming_load_budget+ snapshot_upcoming_load_budget()if not gpu_ids:if not allow_ranking:return Nonediff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex ceb98d4014d..b12c8de4603 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -117,6 +117,18 @@ def _no_real_mxc_drive_aliases(monkeypatch):monkeypatch.setenv("UNSLOTH_MXC_DRIVE_ALIAS", "0")[email protected](autouse = True)+def _forget_load_budget_snapshots():+ def _forget():+ for name, module in list(sys.modules.items()):+ if name.endswith("core.inference.diffusion_memory"):+ getattr(module, "_LOAD_BUDGET_FRACTIONS", {}).clear()++ _forget()+ yield+ _forget()++@pytest.fixture(autouse = True)def _forget_mxc_isolation_settings():# The setting is cached for a second across tests that each get their own Studio home.diff --git a/studio/backend/tests/test_account_inference_isolation.py b/studio/backend/tests/test_account_inference_isolation.pyindex 6b13498b057..499da9a18c6 100644--- a/studio/backend/tests/test_account_inference_isolation.py+++ b/studio/backend/tests/test_account_inference_isolation.py@@ -717,6 +717,12 @@ def test_every_model_load_worker_is_pinned_to_its_account():from core.inference import diffusion, sd_cpp_backend, video as video_backend+ def _is_run_load(value):+ # A target may be wrapped (carry_load_budget(self._run_load)); the worker is still _run_load.+ if isinstance(value, ast.Call) and value.args:+ value = value.args[0]+ return isinstance(value, ast.Attribute) and value.attr == "_run_load"+for module in (diffusion, sd_cpp_backend, video_backend):tree = ast.parse(inspect.getsource(module))starters = [@@ -724,10 +730,7 @@ def test_every_model_load_worker_is_pinned_to_its_account():for node in ast.walk(tree)if isinstance(node, ast.Call)and any(- keyword.arg == "target"- and isinstance(keyword.value, ast.Attribute)- and keyword.value.attr == "_run_load"- for keyword in node.keywords+ keyword.arg == "target" and _is_run_load(keyword.value) for keyword in node.keywords)]assert starters, module.__name__diff --git a/studio/backend/tests/test_diffusion_auto_gpu.py b/studio/backend/tests/test_diffusion_auto_gpu.pyindex 97b84605abe..7ffdbdf595e 100644--- a/studio/backend/tests/test_diffusion_auto_gpu.py+++ b/studio/backend/tests/test_diffusion_auto_gpu.py@@ -248,3 +248,65 @@ def test_route_pins_its_automatic_decision_for_the_backend(monkeypatch):return ordinal, real.get()assert asyncio.run(load()) == (None, None)+++def test_automatic_primary_pick_ranks_by_the_budgeted_room(monkeypatch):+ from utils import vram_budget_settings++ fraction = {"value": vram_budget_settings.VRAM_FRACTION_DEFAULT}+ monkeypatch.setattr(vram_budget_settings, "get_vram_budget_fraction", lambda: fraction["value"])+ _host(monkeypatch, [0, 1], [_dev(0, 24.0, 1.0), _dev(1, 192.0, 132.0)])+ assert dd.resolve_auto_cuda_ordinal() == 1+ fraction["value"] = 0.5+ assert dd.resolve_auto_cuda_ordinal() == 0+ _host(monkeypatch, [0, 1], [_dev(0, 80.0, 0.6), _dev(1, 80.0, 0.5)])+ assert dd.resolve_auto_cuda_ordinal() is None+++def test_route_ranks_the_next_load_under_its_own_budget(monkeypatch):+ from core.inference import diffusion_memory as dm+ from routes import inference as routes+ from utils import vram_budget_settings++ fraction = {"value": vram_budget_settings.VRAM_FRACTION_DEFAULT}+ monkeypatch.setattr(vram_budget_settings, "get_vram_budget_fraction", lambda: fraction["value"])+ monkeypatch.setattr(dm, "_LOAD_BUDGET_FRACTIONS", {})+ _host(monkeypatch, [0, 1], [_dev(0, 24.0, 1.0), _dev(1, 192.0, 132.0)])+ monkeypatch.setattr(+ dd, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )+ monkeypatch.setattr(dd, "auto_cuda_ranking_possible_cached", lambda: True)+ dm.vram_budget_scope("image", load = True)(lambda: dm.commit_load_budget_fraction("image"))()+ fraction["value"] = 0.5+ assert dm.vram_budget_scope("image")(dm._vram_budget_fraction)() == pytest.approx(0.97)++ seen = {}++ @dm.vram_budget_scope("image", load = True)+ def plan():+ seen["load"] = dm._vram_budget_fraction()++ def worker():+ seen["worker"] = dm._vram_budget_fraction()++ async def request():+ ordinal = await routes._selected_gpu_ordinal(None)+ fraction["value"] = (+ 0.8 # edited after the ranking: the load still plans with the ranking's value+ )+ await asyncio.to_thread(plan)+ return ordinal++ assert asyncio.run(request()) == 0+ assert seen == {"load": pytest.approx(0.5)}+ assert dm._vram_budget_fraction() == pytest.approx(0.97)+ import threading++ fraction["value"] = 0.5+ carried = dm.vram_budget_scope("image", load = True)(+ lambda: (fraction.update(value = 0.8), dm.carry_load_budget(worker))[1]+ )()+ thread = threading.Thread(target = carried)+ thread.start()+ thread.join()+ assert seen["worker"] == pytest.approx(0.5)diff --git a/studio/backend/tests/test_diffusion_layer_split_plan.py b/studio/backend/tests/test_diffusion_layer_split_plan.pyindex a47bd05928b..f19e7e8ac81 100644--- a/studio/backend/tests/test_diffusion_layer_split_plan.py+++ b/studio/backend/tests/test_diffusion_layer_split_plan.py@@ -452,7 +452,7 @@ def _cards(monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: sizes)monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: sec_limit)monkeypatch.setattr(- mg, "best_secondary", lambda selection, probes = None: selection.secondaries[0]+ mg, "best_secondary", lambda selection, probes = None, **_: selection.secondaries[0])monkeypatch.setattr(lsp,diff --git a/studio/backend/tests/test_diffusion_memory_vram_budget.py b/studio/backend/tests/test_diffusion_memory_vram_budget.pynew file mode 100644index 00000000000..9b01daa6006--- /dev/null+++ b/studio/backend/tests/test_diffusion_memory_vram_budget.py@@ -0,0 +1,722 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The image memory planner honours the user's VRAM Budget setting (#8178, #10695). Hermetic: no GPU."""++from __future__ import annotations++import types++import pytest++import core.inference.diffusion_memory as dm+from core.inference.diffusion_memory import (+ DeviceMemory,+ OFFLOAD_NONE,+ plan_diffusion_memory,+ total_capacity_budget_mib,+)+from utils import vram_budget_settings++GiB = 1024+++def fraction(monkeypatch):+ state = {"value": vram_budget_settings.VRAM_FRACTION_DEFAULT}+ monkeypatch.setattr(vram_budget_settings, "get_vram_budget_fraction", lambda: state["value"])+ return state+++def _card(+ free,+ total,+ kind = "discrete_vram",+):+ return DeviceMemory("cuda", "cuda", kind, free, total)+++def _plan(memory, model_mib):+ return plan_diffusion_memory(+ target = types.SimpleNamespace(+ device = "cuda", backend = "cuda", supports_model_cpu_offload = True+ ),+ device_memory = memory,+ model_dense_mib = model_mib,+ runtime_headroom_mib = 1 * GiB,+ companion_dense_mib = 2 * GiB,+ )+++def test_lower_budget_shrinks_the_planner_budget(fraction):+ card = _card(22 * GiB, 24 * GiB)+ default = dm._safe_device_budget_mib(card)+ fraction["value"] = 0.80+ assert dm._safe_device_budget_mib(card) == 22 * GiB - int(24 * GiB * 0.20)+ assert dm._safe_device_budget_mib(card) < default+++def test_lower_budget_moves_a_resident_load_to_offload(fraction):+ card = _card(22 * GiB, 24 * GiB)+ model = 12 * GiB # + 1 GiB headroom + 2 GiB base overhead = 15 GiB resident+ assert _plan(card, model).offload_policy == OFFLOAD_NONE+ fraction["value"] = 0.70+ plan = _plan(card, model)+ assert plan.offload_policy != OFFLOAD_NONE+ assert plan.estimates["safe_device_budget_mib"] == 22 * GiB - int(24 * GiB * 0.30)+++def test_fast_and_capacity_budgets_follow_the_setting(fraction):+ card = _card(22 * GiB, 24 * GiB)+ fast, capacity = dm._fast_device_budget_mib(card), total_capacity_budget_mib(card)+ fraction["value"] = 0.60+ reserve = int(24 * GiB * 0.40)+ assert dm._fast_device_budget_mib(card) == 22 * GiB - reserve < fast+ assert total_capacity_budget_mib(card) == int((24 * GiB - reserve) * 0.85) < capacity+++ "free, total, kind",+ [+ (22 * GiB, 24 * GiB, "discrete_vram"),+ (150 * GiB, 192 * GiB, "discrete_vram"), # 3% of 192 GiB exceeds the 4 GiB discrete cap+ (20 * GiB, 32 * GiB, "unified_memory"),+ (10 * GiB, 16 * GiB, "system_memory"),+ ],+)[email protected]("value", [None, 0.97, 0.99, 1.0])+def test_default_or_higher_budget_is_unchanged(fraction, free, total, kind, value):+ card = _card(free, total, kind)+ if value is not None:+ fraction["value"] = value+ reserve = dm._reserve_mib(kind, total)+ assert dm._safe_device_budget_mib(card) == free - reserve+ assert dm._fast_device_budget_mib(card) == free - max(2048, reserve // 2)+ assert total_capacity_budget_mib(card) == int((total - reserve) * 0.85)+++def test_unified_reserve_is_only_ever_tightened(fraction):+ mac = _card(20 * GiB, 32 * GiB, "unified_memory")+ default = dm._safe_device_budget_mib(mac)+ fraction["value"] = 0.85 # below the 20% unified reserve already kept+ assert dm._safe_device_budget_mib(mac) == default+ fraction["value"] = 0.50+ assert dm._safe_device_budget_mib(mac) == 20 * GiB - 16 * GiB+++def test_unreadable_setting_keeps_the_planner_budget(monkeypatch):+ card = _card(22 * GiB, 24 * GiB)+ default = dm._safe_device_budget_mib(card)++ def boom():+ raise RuntimeError("settings store unavailable")++ monkeypatch.setattr(vram_budget_settings, "get_vram_budget_fraction", boom)+ assert dm._safe_device_budget_mib(card) == default+++def test_encoder_only_secondary_card_honours_the_budget(fraction, monkeypatch):+ import core.inference.diffusion_multigpu as mg+ from core.inference.diffusion_layer_split_plan import secondary_reserve_mib++ monkeypatch.setattr(mg, "_free_total_mib", lambda ordinal: (22 * GiB, 24 * GiB))+ assert mg.encoder_card_limit_mib(1) == 22 * GiB - secondary_reserve_mib()+ fraction["value"] = 0.50+ assert mg.encoder_card_limit_mib(1) == 22 * GiB - 12 * GiB+++def test_cfg_replica_is_declined_when_it_would_break_the_budget(fraction, monkeypatch):+ torch = pytest.importorskip("torch")+ import core.inference.diffusion_multigpu as mg++ class Pipe:+ transformer = torch.nn.Linear(1024, 1024) # 4 MiB of weights++ probes = {+ o: mg.DeviceProbe(ordinal = o, name = "card", total_mib = 24 * GiB, free_mib = 13 * GiB)+ for o in (0, 1)+ }+ 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}+ )+ armed, declined = Pipe(), Pipe()+ try:+ with mg.selection_scope(mg.MultiGpuSelection(primary = 0, secondaries = (1,))):+ assert mg.install_cfg_parallel(armed, offload_policy = "none") is None+ fraction["value"] = (+ 0.50 # keeps 12 GiB of the 13 GiB free: the 4 MiB replica still fits+ )+ mg.uninstall_cfg_parallel(armed)+ assert mg.install_cfg_parallel(armed, offload_policy = "none") is None+ fraction["value"] = 0.45 # keeps 13.2 GiB: no room left for the replica+ reason = mg.install_cfg_parallel(declined, offload_policy = "none")+ assert reason is not None and reason.startswith("replica needs")+ finally:+ mg.uninstall_cfg_parallel(armed)+ mg.uninstall_cfg_parallel(declined)+++def test_video_h3_free_reading_keeps_the_budget_free(fraction, monkeypatch):+ import core.inference.video as vid+ from utils import hardware++ monkeypatch.setattr(+ hardware, "trusted_mem_get_info", lambda *a, **k: (22 * GiB << 20, 24 * GiB << 20)+ )+ assert vid._h3_free_device_bytes("cuda") == 22 * GiB << 20+ fraction["value"] = 0.50+ assert vid._h3_free_device_bytes("cuda") == 10 * GiB << 20+++def test_default_request_tiles_under_a_lowered_budget_but_is_never_refused(fraction):+ card = _card(22 * GiB, 24 * GiB)++ def verdict(tile_side):+ return dm.image_activation_verdict(+ device_memory = card, width = None, height = None, vae_tile_side = tile_side+ ).action++ assert verdict(512) == dm.ACTIVATION_RUN # default budget: untouched+ fraction["value"] = 0.40 # 7,783 MiB budget: under the 8,192 MiB default estimate + overhead+ assert verdict(512) == dm.ACTIVATION_TILE+ assert (+ verdict(None) == dm.ACTIVATION_RUN+ ) # nothing to tile: the load budgeted this size, so still not refused+++def test_calibrated_tier_does_not_promote_past_a_lowered_budget(fraction):+ from core.inference.diffusion_memory import OFFLOAD_MODEL, CalibratedImageActivation++ act = CalibratedImageActivation(+ text_encoder_mib = 1_498,+ denoise_mib = 794,+ decode_mib = 9_172,+ tiled_decode_mib = 590,+ max_canvas_mib = 2_960,+ )+ total = 25 * GiB+ card = DeviceMemory("cuda", "cuda", "discrete_vram", total - 1_229, total)++ def plan():+ return plan_diffusion_memory(+ target = types.SimpleNamespace(+ device = "cuda", backend = "cuda", supports_model_cpu_offload = True+ ),+ device_memory = card,+ runtime_headroom_mib = 8192,+ calibrated_activation = act,+ model_dense_mib = 17_897,+ companion_dense_mib = 10_247,+ text_encoder_dense_mib = 8_959,+ )++ fraction["value"] = 0.50+ p = plan()+ budget = p.estimates["safe_device_budget_mib"]+ assert budget == total - 1_229 - int(total * 0.50)+ transformer = 17_897 - 10_247+ if p.offload_policy == OFFLOAD_MODEL:+ assert transformer + act.max_canvas_mib + p.estimates["base_overhead_mib"] <= budget+++ "memory",+ [+ DeviceMemory("mps", "mps", "unified_memory", 20 * GiB, 32 * GiB),+ DeviceMemory(+ "mps", "mps", "unified_memory", 20 * GiB, 32 * GiB, metal_working_set_mib = 28 * GiB+ ),+ DeviceMemory("cpu", "cpu", "system_memory", 10 * GiB, 16 * GiB),+ ],+)+def test_metal_and_cpu_ignore_the_budget_like_the_llm_path(fraction, memory):+ safe, fast, capacity = (+ dm._safe_device_budget_mib(memory),+ dm._fast_device_budget_mib(memory),+ total_capacity_budget_mib(memory),+ )+ fraction["value"] = 0.30+ assert dm._safe_device_budget_mib(memory) == safe+ assert dm._fast_device_budget_mib(memory) == fast+ assert total_capacity_budget_mib(memory) == capacity+++def test_cfg_replica_picks_the_card_the_budget_leaves_room_on(fraction, monkeypatch):+ torch = pytest.importorskip("torch")+ import core.inference.diffusion_multigpu as mg++ class Pipe:+ transformer = torch.nn.Linear(51_200, 51_200, bias = False, device = "meta") # 10 GiB fp32++ probes = {+ 0: mg.DeviceProbe(ordinal = 0, name = "card", total_mib = 24 * GiB, free_mib = 23 * GiB),+ 1: mg.DeviceProbe(ordinal = 1, name = "card", total_mib = 192 * GiB, free_mib = 60 * GiB),+ 2: mg.DeviceProbe(ordinal = 2, name = "card", total_mib = 24 * GiB, free_mib = 23 * GiB),+ }+ 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}+ )+ fraction["value"] = (+ 0.50 # cuda:1 must keep 96 GiB free (none usable), cuda:2 keeps 12 GiB (11 GiB usable)+ )+ pipe = Pipe()+ try:+ with mg.selection_scope(mg.MultiGpuSelection(primary = 0, secondaries = (1, 2))):+ 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)+++def test_measured_residency_promotion_keeps_the_budget_free(fraction, monkeypatch):+ for env in (dm.MEASURED_ACTIVATION_ENV, dm.PARTIAL_RESIDENT_ENV, dm.RESIDENT_DIT_ENV):+ monkeypatch.delenv(env, raising = False)+ monkeypatch.delenv("UNSLOTH_DIFFUSION_STREAMED_RESIDENCY", raising = False)+ monkeypatch.setattr(dm, "_pipe_denoisers_hold_torchao", lambda pipe: True)+ loaded = {+ "transformer": (6922, "dit"),+ "text_encoder": (8960, "text_encoder"),+ "vae": (645, "other"),+ }+ monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: dict(loaded))+ monkeypatch.setattr(dm, "_stream_window_mib", lambda pipe: 624, raising = False)+ card = DeviceMemory("cuda", "cuda", "discrete_vram", 11_598, 12 * GiB)++ def refined():+ plan = plan_diffusion_memory(+ target = types.SimpleNamespace(supports_model_cpu_offload = True),+ device_memory = card,+ model_dense_mib = 19630,+ companion_dense_mib = 12182,+ text_encoder_dense_mib = 10847,+ runtime_headroom_mib = 8192,+ )+ if plan.offload_policy == dm.OFFLOAD_MODEL:+ plan = dm.torchao_streaming_plan(plan)+ return dm.refine_plan_from_loaded_weights(+ object(), plan, family = "qwen-image-2.1", speed_mode = "default"+ )++ default = refined()+ fraction["value"] = 0.50+ capped = refined()+ reserve = int(12 * GiB * 0.50)+ resident = capped.resident_transformer_mib or 0+ assert resident + 645 + capped.estimates["measured_runtime_headroom_mib"] + reserve <= 11_598+ assert resident < (default.resident_transformer_mib or 0)+++def test_companion_card_is_ranked_by_what_the_budget_leaves(fraction, monkeypatch):+ import core.inference.diffusion_multigpu as mg++ probes = {+ 0: mg.DeviceProbe(ordinal = 0, name = "a", total_mib = 24 * GiB, free_mib = 23 * GiB),+ 1: mg.DeviceProbe(ordinal = 1, name = "b", total_mib = 192 * GiB, free_mib = 60 * GiB),+ 2: mg.DeviceProbe(ordinal = 2, name = "a", total_mib = 24 * GiB, free_mib = 23 * GiB),+ }+ selection = mg.MultiGpuSelection(primary = 0, secondaries = (1, 2))+ assert mg.best_secondary(selection, probes) == 1 # default budget: most free wins, unchanged+ fraction["value"] = 0.50 # cuda:1 keeps 96 GiB free (nothing usable), cuda:2 has 11 GiB usable+ assert mg.best_secondary(selection, probes) == 2+ readings = {1: (60 * GiB, 192 * GiB), 2: (23 * GiB, 24 * GiB)}+ monkeypatch.setattr(mg, "_free_total_mib", lambda o: readings[o])+ automatic = mg.MultiGpuSelection(primary = 0, secondaries = (1, 2), automatic = True)+ assert mg.best_secondary(automatic) == 2+++def test_companion_card_rank_uses_the_reserve_the_limit_enforces(fraction):+ import core.inference.diffusion_multigpu as mg++ probes = {+ 0: mg.DeviceProbe(ordinal = 0, name = "a", total_mib = 24 * GiB, free_mib = 23 * GiB),+ 1: mg.DeviceProbe(ordinal = 1, name = "a", total_mib = 24 * GiB, free_mib = 20 * GiB),+ 2: mg.DeviceProbe(ordinal = 2, name = "b", total_mib = 192 * GiB, free_mib = 26 * GiB),+ }+ selection = mg.MultiGpuSelection(primary = 0, secondaries = (1, 2))+ assert mg.best_secondary(selection, probes) == 2 # default: most free+ fraction["value"] = 0.96 # just below the default: the planner reserves still bind+ limits = {+ o: dm._safe_device_budget_mib(+ DeviceMemory("cuda", "cuda", "discrete_vram", probes[o].free_mib, probes[o].total_mib)+ )+ for o in (1, 2)+ }+ assert limits[2] > limits[1]+ assert mg.best_secondary(selection, probes) == 2+++def test_video_h3_capacity_probe_charges_the_same_reserve_as_placement(fraction, monkeypatch):+ torch = pytest.importorskip("torch")+ import core.inference.video as vid+ from utils import hardware++ total = 80 * GiB << 20+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda *a, **k: (total, total))+ monkeypatch.setattr(hardware, "trusted_mem_get_info", lambda *a, **k: (total, total))+ assert vid._h3_device_capacity_bytes("cuda") == total+ fraction["value"] = 0.50+ assert vid._h3_device_capacity_bytes("cuda") == vid._h3_free_device_bytes("cuda") == total // 2+++def _share_of_card_reserve(monkeypatch):+ monkeypatch.setattr(+ dm,+ "discrete_reserve_mib",+ lambda total_mib = None: max(2048, min(int((total_mib or 0) * 0.10), 4096)),+ )+++def test_companion_card_rank_uses_the_fast_limit_in_fast_mode(fraction, monkeypatch):+ import core.inference.diffusion_multigpu as mg++ _share_of_card_reserve(monkeypatch)++ probes = {+ 0: mg.DeviceProbe(ordinal = 0, name = "a", total_mib = 24 * GiB, free_mib = 23 * GiB),+ 1: mg.DeviceProbe(ordinal = 1, name = "a", total_mib = 24 * GiB, free_mib = 20 * GiB),+ 2: mg.DeviceProbe(ordinal = 2, name = "b", total_mib = 192 * GiB, free_mib = 26010),+ }+ selection = mg.MultiGpuSelection(primary = 0, secondaries = (1, 2))+ fraction["value"] = 0.96+ fast = {+ o: dm._fast_device_budget_mib(+ DeviceMemory("cuda", "cuda", "discrete_vram", probes[o].free_mib, probes[o].total_mib)+ )+ for o in (1, 2)+ }+ assert fast[1] > fast[2]+ assert mg.best_secondary(selection, probes) == 2+ assert mg.best_secondary(selection, probes, mode = "fast") == 1+++def test_video_h3_residency_budget_keeps_the_reserve_deficit(fraction, monkeypatch):+ torch = pytest.importorskip("torch")+ import core.inference.video as vid+ import core.inference.video_minimax_h3_residency as res+ from utils import hardware++ monkeypatch.setattr(+ hardware, "trusted_mem_get_info", lambda *a, **k: (2 * GiB << 20, 24 * GiB << 20)+ )+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda *a, **k: 9 * GiB << 20)+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda *a, **k: 8 * GiB << 20)+ monkeypatch.setattr(res, "h3_phase_need_gb", lambda *a, **k: 0.0)+ residency = types.SimpleNamespace(resident_bytes = lambda: 8 * GiB << 20)++ def budget():+ return vid._h3_residency_budget_bytes(+ residency, "cuda", width = 64, height = 64, frames = 1, te_streamed = True, te_scheme = None+ )++ assert budget() == 11 * GiB << 20 # default budget: free + cache + resident+ fraction["value"] = 0.50 # keeps 12 GiB free: the card is already 10 GiB inside it+ assert budget() == -(1 * GiB << 20)+ assert (+ vid._h3_free_device_bytes("cuda") == 0+ ) # the plain free reading still never goes negative+++def test_video_request_available_reading_charges_the_reserve(fraction, monkeypatch):+ import core.inference.video as vid+ from utils import hardware++ monkeypatch.setattr(+ hardware, "trusted_mem_get_info", lambda *a, **k: (40 * GiB << 20, 80 * GiB << 20)+ )+ cuda = types.SimpleNamespace(memory_reserved = lambda device = None: 2 * GiB << 20)+ dev = types.SimpleNamespace(type = "cuda", index = 0)+ assert vid._request_available_bytes(dev, cuda) == 42 * GiB << 20+ fraction["value"] = 0.80 # keeps 16 GiB of the 80 GiB card free+ assert vid._request_available_bytes(dev, cuda) == (42 * GiB - int(80 * GiB * (1 - 0.80))) << 20+ assert vid._user_reserve_bytes(types.SimpleNamespace(type = "mps"), 80 * GiB << 20) == 0+ assert vid._user_reserve_bytes("cpu", 80 * GiB << 20) == 0+++def test_every_video_request_guard_reads_through_the_reserve():+ """No request guard (H3 tiers with or without residency, the multi-GPU split, the conventional offload floor) sums raw free + allocator cache on its own any more."""+ import ast+ import inspect++ import core.inference.video as vid++ tree = ast.parse(inspect.getsource(vid))+ raw = [+ node.lineno+ for node in ast.walk(tree)+ if isinstance(node, ast.BinOp)+ and isinstance(node.op, ast.Add)+ and {getattr(node.left, "id", None), getattr(node.right, "id", None)}+ == {"free_bytes", "reserved_bytes"}+ ]+ assert raw == []+ generate = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.FunctionDef)+ and "MiniMax-H3 needs about" in ast.get_source_segment(inspect.getsource(vid), n)+ and n.name != "_request_available_bytes"+ )+ calls = [+ n+ for n in ast.walk(generate)+ if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "_request_available_bytes"+ ]+ assert len(calls) == 3+++def test_video_load_placement_guard_charges_the_reserve(fraction):+ import core.inference.video as vid++ card = _card(22 * GiB, 24 * GiB)+ assert vid._planned_free_less_user_reserve_mib(card) == 22 * GiB+ assert vid._planned_free_less_user_reserve_mib(_card(None, 24 * GiB)) is None+ fraction["value"] = 0.75+ assert vid._planned_free_less_user_reserve_mib(card) == 22 * GiB - 6 * GiB+ mac = DeviceMemory("mps", "mps", "unified_memory", 20 * GiB, 32 * GiB)+ assert vid._planned_free_less_user_reserve_mib(mac) == 20 * GiB+++def test_h3_native_card_free_charges_the_reserve(fraction, monkeypatch):+ import contextlib++ import core.inference.video as vid+ from utils import hardware++ monkeypatch.setattr(+ hardware,+ "get_visible_gpu_utilization",+ lambda **k: {+ "devices": [{"visible_ordinal": 0, "vram_total_gb": 24.0, "vram_used_gb": 4.0}]+ },+ )+ from utils.hardware import gpu_query++ monkeypatch.setattr(gpu_query, "fresh_reads", contextlib.nullcontext)+ gib = 1024**3+ assert vid._h3_card_memory_bytes("cuda", 0) == (20 * gib, 24 * gib)+ fraction["value"] = 0.50+ assert vid._h3_card_memory_bytes("cuda", 0) == (8 * gib, 24 * gib)+ assert vid._h3_card_free_bytes("cuda", 0) == 8 * gib+++def test_quant_staging_keeps_the_reserve_free(fraction, monkeypatch):+ torch = pytest.importorskip("torch")+ import core.inference.video as V++ moved = []++ class Block(torch.nn.Linear):+ def to(self, *a, **k):+ moved.append(self)+ return self++ dit = torch.nn.Module()+ dit.blocks = torch.nn.ModuleList(+ [Block(1024, 1024, bias = False).to(torch.bfloat16) for _ in range(4)]+ )+ moved.clear()+ block = 1024 * 1024 * 2+ total = 64 * GiB << 20+ free = (+ V.DEFAULT_BASE_OVERHEAD_MIB * 1024 * 1024+ + V._STAGE_LINEAR_WORKSPACE * block+ + 4 * block+ + (1 * GiB << 20)+ )+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr("utils.hardware.trusted_mem_get_info", lambda d, module = None: (free, total))+ target = types.SimpleNamespace(device = "cuda", torch_device = "cuda")+ assert len(V._stage_denoiser_for_quant(dit, target)) == 4+ moved.clear()+ fraction["value"] = 0.99 # 0.64 GiB reserve: the 1 GiB spare covers it, all four still stage+ assert len(V._stage_denoiser_for_quant(dit, target)) == 4+ fraction["value"] = 0.90 # 6.4 GiB reserve: nothing fits beside it+ assert V._stage_denoiser_for_quant(dit, target) == []+++def test_image_layer_split_card_guard_charges_the_reserve(fraction, monkeypatch):+ torch = pytest.importorskip("torch")+ from core.inference import diffusion as D+ from core.inference import diffusion_layer_split_plan as lsp++ from . import test_diffusion_layer_split_plan as T++ for env in (T.mg.MULTIGPU_ENV, T.mg.CFG_PARALLEL_ENV, lsp.LAYER_SPLIT_ENV):+ monkeypatch.delenv(env, raising = False)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 8)+ monkeypatch.setattr(T.mg, "_capability", lambda o: None)+ monkeypatch.setattr(lsp, "_is_rocm", lambda: False)+ monkeypatch.setattr(T.mg, "_rocm_torch", lambda: False)+ eng = T._Engine()+ monkeypatch.setattr(lsp, "engine_available", lambda: True)+ monkeypatch.setattr(lsp, "place_layer_split", eng.place)+ monkeypatch.setattr(lsp, "undo_layer_split", eng.undo)+ plan, pipe = T._layer_plan(monkeypatch, eng)+ lsp.apply_layer_split_plan(pipe, plan, placement = "cuda:0")+ monkeypatch.setattr(D, "estimate_image_runtime_mib", lambda **k: 4096)+ working, reserve = lsp.applied_layer_split(pipe).working_mib(1)+ free = working + reserve + 512+ monkeypatch.setattr(+ D,+ "reclaimable_snapshot_device_memory",+ lambda target: DeviceMemory("cuda", "cuda", "discrete_vram", free, 24 * GiB),+ )+ kw = {"width": 1024, "height": 1024, "family": "flux2"}+ assert D._guard_layer_cards(pipe, object(), kw) == 1+ fraction["value"] = 0.90 # 2.4 GiB of cuda:1 kept free: the 512 MiB spare is not enough+ with pytest.raises(ValueError, match = "cuda:1"):+ D._guard_layer_cards(pipe, object(), kw)+++def test_denoiser_hold_between_calls_keeps_the_reserve_free(fraction, monkeypatch):+ torch = pytest.importorskip("torch")+ from core.inference import diffusion_multistage as MS++ param = types.SimpleNamespace(device = types.SimpleNamespace(type = "cuda"))+ dit = types.SimpleNamespace(parameters = lambda: iter([param]))+ monkeypatch.setattr(MS, "_denoisers", lambda pipe: [dit])+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda *a: (4 * GiB << 20, 24 * GiB << 20))+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda *a: 0)+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda *a: 0)+ assert MS.companions_fit_beside_denoiser(object(), ()) is True # 2 GiB margin within 4 GiB free+ fraction["value"] = 0.90 # 2.4 GiB kept free leaves 1.6 GiB, under the margin+ assert MS.companions_fit_beside_denoiser(object(), ()) is False+++def test_cfg_batch_doubled_call_keeps_the_reserve_free(fraction, monkeypatch):+ from core.inference import diffusion_cfg_batch as cb++ fake = types.SimpleNamespace(+ cuda = types.SimpleNamespace(+ mem_get_info = lambda device: (10 * GiB << 20, 24 * GiB << 20),+ memory_reserved = lambda device: 2 * GiB << 20,+ memory_allocated = lambda device: 1 * GiB << 20,+ )+ )+ monkeypatch.setattr(cb, "_torch", lambda: fake)+ assert cb._usable_free_mib("cuda:0") == 11 * GiB+ fraction["value"] = 0.75+ assert cb._usable_free_mib("cuda:0") == 11 * GiB - 6 * GiB+++def test_primary_card_rank_uses_free_less_the_reserve(fraction, monkeypatch):+ torch = pytest.importorskip("torch")+ from core.inference import diffusion_device as dd++ cards = {0: (20 * GiB << 20, 80 * GiB << 20), 1: (14 * GiB << 20, 16 * GiB << 20)}+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda o: cards[o])+ assert dd.rank_cuda_ordinals([0, 1]) == [0, 1]+ fraction["value"] = (+ 0.80 # cuda:0 keeps 16 GiB (4 GiB left), cuda:1 keeps 3.2 GiB (10.8 GiB left)+ )+ assert dd.rank_cuda_ordinals([0, 1]) == [1, 0]+++def test_primary_card_rank_uses_the_reserve_the_planner_enforces(fraction, monkeypatch):+ torch = pytest.importorskip("torch")+ from core.inference import diffusion_device as dd++ _share_of_card_reserve(monkeypatch)+ cards = {0: (12 * GiB << 20, 40 * GiB << 20), 1: (11 * GiB << 20, 16 * GiB << 20)}+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda o: cards[o])+ assert dd.rank_cuda_ordinals([0, 1]) == [0, 1]+ fraction["value"] = 0.96+ safe = {o: dm._safe_device_budget_mib(_card(f >> 20, t >> 20)) for o, (f, t) in cards.items()}+ assert safe[1] > safe[0]+ assert dd.rank_cuda_ordinals([0, 1]) == [1, 0]+++def no_pins(monkeypatch):+ monkeypatch.setattr(dm, "_LOAD_BUDGET_FRACTIONS", {})+++def test_generation_guards_keep_the_load_time_budget(fraction, no_pins):+ """Editing the Budget while a pipeline stays loaded must not move its generation-time reserve."""++ @dm.vram_budget_scope("image", load = True)+ def load():+ assert dm._user_budget_reserve_mib(10 * GiB) == 5 * GiB+ fraction["value"] = (+ 0.70 # edited mid-load: this load still plans with the value it began with+ )+ assert dm._user_budget_reserve_mib(10 * GiB) == 5 * GiB+ dm.commit_load_budget_fraction("image")++ @dm.vram_budget_scope("image")+ def generate():+ return dm._user_budget_reserve_mib(10 * GiB), dm.user_budget_reserve_share()++ fraction["value"] = 0.50+ load()+ fraction["value"] = 0.75+ assert generate() == (5 * GiB, pytest.approx(0.50))+ assert dm._user_budget_reserve_mib(10 * GiB) == 5 * GiB+ load_again = dm.vram_budget_scope("image", load = True)(+ lambda: (dm._user_budget_reserve_mib(10 * GiB), dm.commit_load_budget_fraction("image"))[0]+ )+ assert load_again() == 2560+ assert generate()[0] == 2560+ dm.release_load_budget_fraction("image")+ fraction["value"] = 0.625+ assert dm._user_budget_reserve_mib(10 * GiB) == 3840+ fraction["value"] = vram_budget_settings.VRAM_FRACTION_DEFAULT+ assert generate() == (0, 0.0)+++def test_each_backend_reads_its_own_snapshot(fraction, no_pins):+ for owner, value in (("image", 0.50), ("video", 0.75)):+ fraction["value"] = value+ dm.vram_budget_scope(owner, load = True)(lambda o = owner: dm.commit_load_budget_fraction(o))()+ fraction["value"] = vram_budget_settings.VRAM_FRACTION_DEFAULT+ image = dm.vram_budget_scope("image")(lambda: dm._user_budget_reserve_mib(10 * GiB))+ video = dm.vram_budget_scope("video")(lambda: dm._user_budget_reserve_mib(10 * GiB))+ assert (image(), video()) == (5 * GiB, 2560)+ assert dm._user_budget_reserve_mib(10 * GiB) == 5 * GiB+++def test_default_budget_reserve_stays_zero_with_a_pipeline_loaded(fraction, no_pins):+ dm.vram_budget_scope("image", load = True)(lambda: dm.commit_load_budget_fraction("image"))()+ assert dm._user_budget_reserve_mib(10 * GiB) == 0 and dm.user_budget_reserve_share() == 0.0+++def _scopes(fn, seen = None):+ """Every ``vram_budget_scope`` wrapper in ``fn``'s decorator chain, followed through ``__wrapped__`` and through closures (not every decorator here uses functools.wraps)."""+ seen = set() if seen is None else seen+ if not callable(fn) or id(fn) in seen or not hasattr(fn, "__code__"):+ return []+ seen.add(id(fn))+ cells = dict(zip(fn.__code__.co_freevars, fn.__closure__ or ()))+ found = []+ if fn.__code__ is dm.vram_budget_scope("x")(lambda: None).__code__:+ found.append((cells["owner"].cell_contents, cells["load"].cell_contents))+ for inner in [getattr(fn, "__wrapped__", None)] + [c.cell_contents for c in cells.values()]:+ found += _scopes(inner, seen)+ return found+++def test_backend_entry_points_run_under_their_budget_scope():+ from core.inference.diffusion import DiffusionBackend+ from core.inference.video import VideoBackend+ for cls, owner, loads, gens in (+ (+ DiffusionBackend,+ "image",+ ("begin_load", "_run_load", "download_plan", "load_pipeline"),+ ("generate",),+ ),+ (+ VideoBackend,+ "video",+ ("begin_load", "_run_load", "_run_load_h3_native", "download_plan", "load_pipeline"),+ ("begin_generate", "generate"),+ ),+ ):+ for name in loads:+ assert (owner, True) in _scopes(getattr(cls, name)), (cls.__name__, name)+ for name in gens:+ assert (owner, False) in _scopes(getattr(cls, name)), (cls.__name__, name)diff --git a/studio/backend/tests/test_diffusion_multigpu.py b/studio/backend/tests/test_diffusion_multigpu.pyindex 3afcf3822d8..84103ee17e9 100644--- a/studio/backend/tests/test_diffusion_multigpu.py+++ b/studio/backend/tests/test_diffusion_multigpu.py@@ -339,7 +339,7 @@ def test_refine_plan_for_multigpu(monkeypatch):}monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: sizes)monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: 12750)- monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None: 1)+ monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None, **_: 1)assert mg.refine_plan_for_multigpu(object(), plan) is planwith mg.selection_scope(mg.make_selection(0, [0, 1])):refined = mg.refine_plan_for_multigpu(object(), plan)@@ -1131,7 +1131,7 @@ def test_post_load_split_keeps_the_original_plan_as_fallback(monkeypatch):}monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: sizes)monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: 12750)- monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None: 1)+ monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None, **_: 1)with mg.selection_scope(mg.make_selection(0, [0, 1])):refined = mg.refine_plan_for_multigpu(object(), plan)assert refined.fallback_plan is plan@@ -1177,7 +1177,7 @@ def test_post_load_split_keeps_vae_tiling(monkeypatch):}monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: sizes)monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: 12750)- monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None: 1)+ monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None, **_: 1)with mg.selection_scope(mg.make_selection(0, [0, 1])):refined = mg.refine_plan_for_multigpu(object(), plan)assert refined.secondary_ordinal == 1@@ -1762,7 +1762,7 @@ def test_force_mode_refines_a_resident_plan(monkeypatch):}monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: sizes)monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: 12750)- monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None: 1)+ monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None, **_: 1)with mg.selection_scope(mg.make_selection(0, [0, 1])):assert mg.refine_plan_for_multigpu(object(), plan) is planmonkeypatch.setenv(mg.MULTIGPU_ENV, "force")@@ -2089,7 +2089,7 @@ def test_refinement_keeps_an_explicit_cpu_offload(monkeypatch):}monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: sizes)monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: 12750)- monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None: 1)+ monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None, **_: 1)legacy = _plan(explicit_offload = True)assert legacy.estimates.get("explicit_cpu_offload")moded = _plan(explicit_offload = True, requested_mode = "auto")diff --git a/studio/backend/tests/test_diffusion_small_host_prefetch.py b/studio/backend/tests/test_diffusion_small_host_prefetch.pyindex f395c5dd812..6712ae40eaa 100644--- a/studio/backend/tests/test_diffusion_small_host_prefetch.py+++ b/studio/backend/tests/test_diffusion_small_host_prefetch.py@@ -102,10 +102,14 @@ class _FakePrefetcher(sh._EncoderPrefetcher):):raise RuntimeError("copy failed")self.copies.append((group.name, threading.current_thread() is threading.main_thread()))- with self.cond:- self.peak_inflight = max(self.peak_inflight, self.inflight + group.nbytes)+ if threading.current_thread() is not threading.main_thread():+ with self.cond:+ self.peak_inflight = max(self.peak_inflight, self.inflight + group.nbytes)return [group.name], None, group.nbytes+ def _group_bytes(self, group):+ return group.nbytes+def _attach(self, group, moved, done):self.attached.append(moved[0])@@ -154,6 +158,25 @@ def test_prefetch_stays_within_the_byte_budget():assert pf.peak_inflight <= pf.budget + sh._PREFETCH_MIN_BYTES // 4+def test_prefetch_with_no_budgeted_room_starts_no_worker(monkeypatch):+ """#14816 r9: a zero budget copies every group synchronously instead of one group ahead."""+ monkeypatch.setattr(sh, "_prefetch_budget_bytes", lambda device: 0)+ groups = [_FakeGroup(f"g{i}", 10) for i in range(6)]+ pf = _FakePrefetcher(groups)+ _forward(pf, groups)+ pf.copies.clear()+ pf.begin()+ try:+ assert pf.worker is None+ for g in groups:+ pf.onload(g)+ finally:+ pf.end()+ assert pf.stats["prefetched"] == 0 and pf.stats["sync"] == 12+ assert all(main for _n, main in pf.copies) and pf.inflight == 0 and not pf.ready+ assert pf.order == [id(g) for g in groups]++def test_prefetch_one_oversized_group_still_progresses():groups = [_FakeGroup("big", sh._PREFETCH_MAX_BYTES * 4), _FakeGroup("small", 1)]pf = _FakePrefetcher(groups)@@ -162,6 +185,143 @@ def test_prefetch_one_oversized_group_still_progresses():assert pf.stats["prefetched"] == 2+def test_lowered_budget_copies_a_group_over_the_window_synchronously(monkeypatch):+ """Codex #14816 r10: under a lowered Budget a whole next group larger than the window would eat the reserve."""+ monkeypatch.setattr(sh, "_prefetch_budget_bytes", lambda device: 256 * sh._MIB)+ monkeypatch.setattr(sh, "_prefetch_budget_lowered", lambda device: True, raising = False)+ big = 1536 * sh._MIB+ groups = [+ _FakeGroup("a", big),+ _FakeGroup("s0", 100 * sh._MIB),+ _FakeGroup("b", big),+ _FakeGroup("s1", 100 * sh._MIB),+ _FakeGroup("s2", 100 * sh._MIB),+ ]+ pf = _FakePrefetcher(groups)+ _forward(pf, groups)+ pf.copies.clear()+ _forward(pf, groups)+ on_worker = [n for n, main in pf.copies if not main]+ assert "a" not in on_worker and "b" not in on_worker+ assert sorted(on_worker) == ["s0", "s1", "s2"]+ assert pf.peak_inflight <= 256 * sh._MIB+ assert pf.attached[-5:] == [g.name for g in groups]+ assert pf.stats["prefetched"] == 3 and not pf.skipped and pf.inflight == 0+++def test_lowered_budget_sync_copy_and_worker_never_share_a_staging_slot(monkeypatch):+ """#14816: a skipped group copies on the forward thread while the worker stages the next one. Without one copy+ lock the worker wraps the ring and overwrites a staging slot the forward thread wrote but has not enqueued."""+ import contextlib++ class Event:+ def record(self, stream):+ pass++ def synchronize(self):+ pass++ class Stream:+ def wait_event(self, event):+ pass++ def wait_stream(self, stream):+ pass++ stream = Stream()+ main = threading.main_thread()+ wrote = threading.Event() # forward thread wrote slot 0 and has not enqueued it+ progressed = threading.Event() # worker finished its copy, or is blocked on the copy lock+ big, small = types.SimpleNamespace(), types.SimpleNamespace()+ big.source = torch.full((40,), 1, dtype = torch.uint8)+ small.source = torch.full((32,), 2, dtype = torch.uint8)++ class Lock:+ def __init__(self):+ self.inner = threading.Lock()++ def __enter__(self):+ if threading.current_thread() is not main:+ progressed.set()+ self.inner.acquire()++ def __exit__(self, *exc):+ self.inner.release()++ class Prefetcher(sh._EncoderPrefetcher):+ def __init__(self):+ super().__init__(None, [big, small], "cpu")+ self.stage = [torch.empty(8, dtype = torch.uint8) for _ in range(4)]+ self.stage_events = [None] * 4+ self.stream = stream+ self.copy_lock = Lock()+ self.result = {}++ def _group_bytes(self, group):+ if group is small:+ assert wrote.wait(10)+ return super()._group_bytes(group)++ def _copy_group(self, group):+ out = super()._copy_group(group)+ if group is small:+ progressed.set()+ return out++ def _attach(self, group, moved, done):+ self.result[id(group)] = moved[0].clone()++ pf = Prefetcher()+ pf.order = [id(big), id(small)]+ copy = torch.Tensor.copy_+ paused = []++ def copy_(dst, src, *args, **kwargs):+ out = copy(dst, src, *args, **kwargs)+ if (+ not paused+ and threading.current_thread() is main+ and dst.data_ptr() == pf.stage[0].data_ptr()+ ):+ paused.append(True)+ wrote.set()+ assert progressed.wait(10)+ return out++ for obj, name, value in [+ (sh, "_STAGE_SLOT_BYTES", 8),+ (sh, "_STAGE_SLOTS", 4),+ (sh, "_group_tensors", lambda g: [(g.source, g.source)]),+ (sh, "_prefetch_budget_bytes", lambda dev: 32),+ (sh, "_prefetch_budget_lowered", lambda dev: True),+ (torch.cuda, "current_stream", lambda *a: stream),+ (torch.cuda, "stream", lambda *a: contextlib.nullcontext()),+ (torch.cuda, "Event", Event),+ (torch.Tensor, "record_stream", lambda *a: None),+ (torch.Tensor, "copy_", copy_),+ ]:+ monkeypatch.setattr(obj, name, value, raising = False)+ pf.begin()+ try:+ pf.onload(big)+ pf.onload(small)+ finally:+ pf.end()+ assert paused and pf.stats == {"prefetched": 1, "sync": 1, "passes": 1}+ assert torch.equal(pf.result[id(big)], big.source)+ assert torch.equal(pf.result[id(small)], small.source)+++def test_default_budget_still_prefetches_an_oversized_group(monkeypatch):+ monkeypatch.setattr(sh, "_prefetch_budget_bytes", lambda device: 256 * sh._MIB)+ monkeypatch.setattr(sh, "_prefetch_budget_lowered", lambda device: False, raising = False)+ groups = [_FakeGroup("a", 1536 * sh._MIB), _FakeGroup("s0", 1)]+ pf = _FakePrefetcher(groups)+ _forward(pf, groups)+ _forward(pf, groups)+ assert pf.stats["prefetched"] == 2++def test_prefetch_off_order_falls_back_and_rerecords():groups = [_FakeGroup(f"g{i}", 10) for i in range(6)]pf = _FakePrefetcher(groups)diff --git a/studio/backend/tests/test_diffusion_vram_budget_workspaces.py b/studio/backend/tests/test_diffusion_vram_budget_workspaces.pynew file mode 100644index 00000000000..21796113d4c--- /dev/null+++ b/studio/backend/tests/test_diffusion_vram_budget_workspaces.py@@ -0,0 +1,514 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Every runtime workspace Studio sizes from a live free-VRAM reading keeps the user's VRAM Budget reserve free."""++from __future__ import annotations++import types++import pytest++torch = pytest.importorskip("torch")++from utils import vram_budget_settings++GIB = 1024**3+++def fraction(monkeypatch):+ state = {"value": vram_budget_settings.VRAM_FRACTION_DEFAULT}+ monkeypatch.setattr(vram_budget_settings, "get_vram_budget_fraction", lambda: state["value"])+ return state+++def card(monkeypatch):+ """A fake 24 GiB CUDA card: ``state["free"]`` driver free, 1 GiB idle allocator cache."""+ state = {"free": 20 * GIB, "total": 24 * GIB, "cached": 1 * GIB}+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda *a, **k: (state["free"], state["total"]))+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda *a, **k: state["cached"])+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda *a, **k: 0)+ return state+++def _cuda_z(*shape):+ return types.SimpleNamespace(+ device = torch.device("cuda", 0), shape = tuple(shape), dim = lambda: len(shape)+ )+++def test_reserve_helper_is_zero_at_the_default_and_off_cuda(fraction):+ from core.inference.diffusion_memory import user_budget_reserve_bytes, user_budget_reserve_share++ assert user_budget_reserve_bytes("cuda:0", 24 * GIB) == 0+ assert user_budget_reserve_share() == 0.0+ fraction["value"] = 0.50+ assert user_budget_reserve_bytes(torch.device("cuda", 0), 24 * GIB) == 12 * GIB+ assert user_budget_reserve_share() == pytest.approx(0.50)+ assert user_budget_reserve_bytes("cpu", 24 * GIB) == 0+ assert user_budget_reserve_bytes("mps", 24 * GIB) == 0+ assert user_budget_reserve_bytes("cuda", None) == 0+++def test_image_vae_tile_budget_reads_free_less_the_reserve(fraction, card, monkeypatch):+ """#14816 r8: a lowered budget prices the floor tile, so the runtime tile must not grow into the reserve."""+ from core.inference import diffusion_vae_tiling as vt++ from . import test_diffusion_vae_tiling_general as G++ monkeypatch.delenv(vt.MAX_TILE_ENV, raising = False)+ monkeypatch.delenv(vt.WIDE_TILES_ENV, raising = False)+ vae = G._qwen_image()+ assert vt.install(vae)+ z = _cuda_z(1, 4, 1, 64, 64)+ default_mib, scale = vt._free_mib(vae, z)+ default_budget = vt.decode_tile_budget(vae, z)+ assert default_budget > 0+ fraction["value"] = 0.50+ mib, scale2 = vt._free_mib(vae, z)+ assert scale2 == scale+ assert mib == pytest.approx(default_mib - 12 * 1024)+ budget = vt.decode_tile_budget(vae, z)+ per_latent = vt.decode_mib_per_latent(vt._geometry(vae)[0], False, type(vae).__name__) * scale+ assert budget == max(0, int(vt.FREE_FRACTION * mib / per_latent))+ assert budget < default_budget+ card["free"] = 10 * GIB+ assert vt.decode_tile_budget(vae, z) == 0+++def test_image_vae_floor_shortfall_charges_the_reserve(fraction, card, monkeypatch):+ from core.inference import diffusion_vae_tiling as vt++ from . import test_diffusion_vae_tiling_general as G++ monkeypatch.delenv(vt.MAX_TILE_ENV, raising = False)+ vae = G._hunyuan_image()+ assert vt.install(vae)+ z = _cuda_z(1, 8, 64, 64)+ card["free"], card["cached"] = 4 * GIB, 0+ assert vt.floor_shortfall(vae, z) is None+ fraction["value"] = 0.85 # 3.6 GiB kept free leaves ~0.4 GiB: the floor tile no longer fits+ assert vt.floor_shortfall(vae, z)+++def test_fused_vae_tile_batch_reads_free_less_the_reserve(fraction, card, monkeypatch):+ from core.inference import diffusion_vae_fused as F++ monkeypatch.delenv(F.TILE_BATCH_ENV, raising = False)+ weight = torch.nn.Parameter(torch.zeros(1, dtype = torch.float16))+ decoder = types.SimpleNamespace(+ norm_out = types.SimpleNamespace(gamma = torch.zeros(96)), parameters = lambda: iter([weight])+ )+ vae = types.SimpleNamespace(+ decoder = decoder,+ tile_sample_min_height = 256,+ tile_sample_min_width = 256,+ temporal_compression_ratio = 4,+ )+ per_tile = F._TILE_PEAK_FACTOR * 256 * 256 * 4 * 96 * 2+ z = _cuda_z(1, 16, 4, 32, 32)+ card["free"] = 4 * per_tile + 12 * GIB+ assert F._tile_batch_cap(vae, z) == F._TILE_BATCH_MAX+ fraction["value"] = 0.50 # 12 GiB kept free: 4 tiles of room, half of it is the batch+ assert F._tile_batch_cap(vae, z) == 2+ card["free"] = 2 * per_tile + 12 * GIB+ assert F._tile_batch_cap(vae, z) == 1+ fraction["value"] = vram_budget_settings.VRAM_FRACTION_DEFAULT+ assert F._tile_batch_cap(vae, z) == F._TILE_BATCH_MAX+++def test_h3_vae_tile_batch_reads_free_less_the_reserve(fraction, card, monkeypatch):+ from core.inference import video_minimax_h3_vae as H++ monkeypatch.delenv(H.H3_VAE_TILE_BATCH_ENV, raising = False)+ z = _cuda_z(1, 16, 4, 32, 32)+ card["free"] = 12 * GIB + 2 * H._TILE_BATCH_BYTES_PER_TILE+ default = H._tile_batch_size(z)+ assert default == min(H._TILE_BATCH_MAX, card["free"] // H._TILE_BATCH_BYTES_PER_TILE)+ fraction["value"] = 0.50+ assert H._tile_batch_size(z) == min(H._TILE_BATCH_MAX, 2)+ assert H._tile_batch_size(z) < default+++def test_video_vae_free_bytes_less_the_reserve(fraction, card):+ from core.inference import video_vae_untiled as U++ assert U._free_bytes(torch.device("cuda", 0)) == 21 * GIB+ fraction["value"] = 0.50+ assert U._free_bytes(torch.device("cuda", 0)) == 9 * GIB+ card["free"] = 4 * GIB # inside the reserve: no room, never negative+ assert U._free_bytes(torch.device("cuda", 0)) == 0+++def test_untiled_video_decode_stays_tiled_when_only_raw_free_fits(fraction, card):+ """Codex #14816 r8: the request guard passed on budgeted room; the untiled gate must not re-read raw free."""+ from core.inference import video_vae_untiled as U++ family = sorted(U._BYTES_PER_LATENT_PIXEL)[0]+ need = U.untiled_decode_bytes(family, (1, 16, 21, 60, 104), itemsize = 2)+ assert need+ gate = int(need * U._MARGIN + U._MARGIN_BYTES)+ card["free"], card["cached"] = gate + GIB, 0+ assert U._free_bytes(torch.device("cuda", 0)) >= gate+ fraction["value"] = 0.50+ assert U._free_bytes(torch.device("cuda", 0)) < gate+++_COMMITTED = ["--offload-to-cpu", "--diffusion-fa", "--max-vram", "-1", "--stream-layers"]+++class _Rt:+ def __init__(self, free, reserve):+ self.vram_free_probe = lambda: free+ self.vram_reserve_probe = lambda: reserve+++def test_h3_tiny_budgeted_room_is_refused_not_handed_to_sd_cpp_raw_reading():+ """Codex #14816 r8: "-1" makes sd.cpp re-read RAW free; 0 GiB left inside the budget must not fall back to it."""+ import core.inference.video as V+ from core.inference.video_minimax_h3 import H3NativeMemoryRefusal++ for free in (0, 1 * GIB, {"cuda0": 2 * GIB}):+ with pytest.raises(H3NativeMemoryRefusal, match = "VRAM Budget"):+ V._h3_budgeted_launch_flags(_Rt(free, 12 * GIB), _COMMITTED)+ assert V._h3_budgeted_launch_flags(_Rt(0, 0), _COMMITTED) == _COMMITTED+++def test_h3_small_or_unread_budgeted_room_spares_the_reserve_in_sd_cpp():+ import core.inference.video as V++ out = V._h3_budgeted_launch_flags(_Rt(2 * GIB, 12 * GIB), _COMMITTED)+ assert out[3] == "-13.00" and out[:3] == _COMMITTED[:3] and out[4:] == _COMMITTED[4:]+ assert V._h3_budgeted_launch_flags(_Rt(None, 12 * GIB), _COMMITTED)[3] == "-13.00"+ assert V._h3_budgeted_launch_flags(_Rt(None, int(2.501 * GIB)), _COMMITTED)[3] == "-3.51"+ assert V._h3_budgeted_launch_flags(_Rt(None, None), _COMMITTED) == _COMMITTED+ assert V._h3_budgeted_launch_flags(_Rt(None, 12 * GIB), _COMMITTED, cap = 4.5)[3] == "4.50"+ assert V._h3_budgeted_launch_flags(_Rt(10 * GIB, 12 * GIB), _COMMITTED)[3] == "8.00"+++def test_h3_kill_switch_still_spares_the_reserve(monkeypatch):+ import core.inference.video as V+ from core.inference import sd_cpp_args as A++ monkeypatch.setenv(A.GRAPH_CUT_EXPLICIT_BUDGET_ENV, "0")+ assert V._h3_budgeted_launch_flags(_Rt(10 * GIB, 0), _COMMITTED) == _COMMITTED+ assert V._h3_budgeted_launch_flags(_Rt(10 * GIB, 12 * GIB), _COMMITTED)[3] == "-13.00"+ uma = ["--offload-to-cpu", "--max-vram", "-17.05"]+ assert V._h3_budgeted_launch_flags(_Rt(10 * GIB, 12 * GIB), uma) == uma+++def test_h3_kill_switch_still_refuses_no_room_inside_the_budget(monkeypatch):+ """Codex #14816 r10: the kill switch keeps "-1" but must still refuse a card (nearly) inside the reserve."""+ import core.inference.video as V+ from core.inference import sd_cpp_args as A+ from core.inference.video_minimax_h3 import H3NativeMemoryRefusal++ monkeypatch.setenv(A.GRAPH_CUT_EXPLICIT_BUDGET_ENV, "0")+ for free in (0, 1 * GIB, {"cuda0": 512 * 1024**2}):+ with pytest.raises(H3NativeMemoryRefusal, match = "VRAM Budget"):+ V._h3_budgeted_launch_flags(_Rt(free, 12 * GIB), _COMMITTED)+ assert V._h3_budgeted_launch_flags(_Rt(2 * GIB, 12 * GIB), _COMMITTED)[3] == "-13.00"+ assert V._h3_budgeted_launch_flags(_Rt(None, 12 * GIB), _COMMITTED)[3] == "-13.00"+ assert V._h3_budgeted_launch_flags(_Rt(0, 0), _COMMITTED) == _COMMITTED+++def test_h3_card_reserve_probe(fraction, monkeypatch):+ import contextlib++ import core.inference.video as V+ from utils import hardware+ from utils.hardware import gpu_query++ monkeypatch.setattr(gpu_query, "fresh_reads", contextlib.nullcontext)+ calls = []+ devices = [+ {"visible_ordinal": 0, "vram_total_gb": 24.0, "vram_used_gb": 4.0},+ {"visible_ordinal": 1, "vram_total_gb": 80.0, "vram_used_gb": 4.0},+ ]+ monkeypatch.setattr(+ hardware, "get_visible_gpu_utilization", lambda **k: calls.append(1) or {"devices": devices}+ )+ assert V._h3_card_reserve_bytes("cuda", 0) == 0 and not calls+ fraction["value"] = 0.50+ assert V._h3_card_reserve_bytes("cuda", 0) == 12 * GIB+ assert V._h3_card_reserve_bytes("cuda", 1) == 40 * GIB+ assert V._h3_card_reserve_bytes("cuda", None, single_card_only = True) == 12 * GIB+ assert V._h3_card_reserve_bytes("cpu", 0) == 0+ monkeypatch.setattr(hardware, "get_visible_gpu_utilization", lambda **k: {"devices": []})+ assert V._h3_card_reserve_bytes("cuda", 0) is None+++def _two_card_h3_runtime(monkeypatch, devices):+ import contextlib+ import functools++ import core.inference.video as V+ from utils import hardware+ from utils.hardware import gpu_query++ monkeypatch.setattr(gpu_query, "fresh_reads", contextlib.nullcontext)+ monkeypatch.setattr(hardware, "get_visible_gpu_utilization", lambda **k: {"devices": devices})+ return types.SimpleNamespace(+ vram_free_probe = functools.partial(+ V._h3_card_free_bytes, "cuda", None, single_card_only = True+ ),+ vram_reserve_probe = functools.partial(+ V._h3_card_reserve_bytes, "cuda", None, single_card_only = True+ ),+ )++[email protected]("explicit", [True, False])+def test_unpinned_multi_card_h3_launch_keeps_every_cards_reserve(fraction, monkeypatch, explicit):+ """An unpinned H3 load on a 24 GiB card (22 free) beside a 64 GiB one."""+ import core.inference.video as V+ from core.inference import diffusion_memory as D+ from core.inference import sd_cpp_args++ D._LOAD_BUDGET_FRACTIONS.clear()+ monkeypatch.setattr(sd_cpp_args, "explicit_vram_budget_enabled", lambda: explicit)+ devices = [+ {"visible_ordinal": 0, "vram_total_gb": 24.0, "vram_used_gb": 2.0},+ {"visible_ordinal": 1, "vram_total_gb": 64.0, "vram_used_gb": 2.0},+ ]+ runtime = _two_card_h3_runtime(monkeypatch, devices)+ flags = ["--offload-to-cpu", "--max-vram", "-1", "--stream-layers"]+ assert V._h3_budgeted_launch_flags(runtime, flags) == flags+ assert runtime.vram_free_probe() is None+ fraction["value"] = 0.50+ assert runtime.vram_free_probe() == 10 * GIB+ launch = V._h3_budgeted_launch_flags(runtime, flags)+ value = float(launch[launch.index("--max-vram") + 1])+ for raw_free, budgeted_free in ((22 * GIB, 10 * GIB), (62 * GIB, 30 * GIB)):+ resolved = value * GIB if value >= 0 else raw_free + value * GIB+ assert value > 0, launch # never a scalar negative spare on an unpinned multi-card load+ assert 0 < resolved <= budgeted_free, (launch, raw_free)+ devices[0]["vram_used_gb"] = 11.5+ from core.inference.video_minimax_h3 import H3NativeMemoryRefusal++ with pytest.raises(H3NativeMemoryRefusal):+ V._h3_budgeted_launch_flags(runtime, flags)++[email protected]("explicit", [True, False])+ "small_used, want",+ [+ (10.0, "1.00"),+ (10.5, "0.50"),+ ],+)+def test_unpinned_mixed_size_h3_small_reading_is_a_positive_cap(+ fraction, monkeypatch, explicit, small_used, want+):+ """A scalar negative spare from the smallest card's reserve must not under-budget the larger card."""+ import core.inference.video as V+ from core.inference import diffusion_memory as D+ from core.inference import sd_cpp_args++ D._LOAD_BUDGET_FRACTIONS.clear()+ monkeypatch.setattr(sd_cpp_args, "explicit_vram_budget_enabled", lambda: explicit)+ devices = [+ {"visible_ordinal": 0, "vram_total_gb": 24.0, "vram_used_gb": small_used},+ {"visible_ordinal": 1, "vram_total_gb": 64.0, "vram_used_gb": 2.0},+ ]+ runtime = _two_card_h3_runtime(monkeypatch, devices)+ flags = ["--offload-to-cpu", "--max-vram", "-1", "--stream-layers"]+ fraction["value"] = 0.50+ launch = V._h3_budgeted_launch_flags(runtime, flags)+ assert launch[2] == want, launch+ small_budgeted = (24.0 - small_used) * GIB - 12 * GIB+ for budgeted_free in (small_budgeted, 30 * GIB):+ assert 0 < float(launch[2]) * GIB <= budgeted_free++[email protected]("explicit", [True, False])+def test_unpinned_multi_card_h3_refuses_unread_or_no_room(fraction, monkeypatch, explicit):+ """Unpinned multi-card under a lowered Budget."""+ import core.inference.video as V+ from core.inference import diffusion_memory as D+ from core.inference import sd_cpp_args+ from core.inference.video_minimax_h3 import H3NativeMemoryRefusal++ D._LOAD_BUDGET_FRACTIONS.clear()+ monkeypatch.setattr(sd_cpp_args, "explicit_vram_budget_enabled", lambda: explicit)+ devices = [+ {+ "visible_ordinal": 0,+ "vram_total_gb": 24.0,+ "vram_used_gb": 11.0,+ }, # exactly 1 GiB inside the budget+ {"visible_ordinal": 1, "vram_total_gb": 64.0, "vram_used_gb": 2.0},+ ]+ runtime = _two_card_h3_runtime(monkeypatch, devices)+ flags = ["--offload-to-cpu", "--max-vram", "-1", "--stream-layers"]+ fraction["value"] = 0.50+ with pytest.raises(H3NativeMemoryRefusal, match = "VRAM Budget"):+ V._h3_budgeted_launch_flags(runtime, flags)+ devices[0]["vram_used_gb"] = None # unread usage on one card+ with pytest.raises(H3NativeMemoryRefusal, match = "VRAM Budget"):+ V._h3_budgeted_launch_flags(runtime, flags)+ fraction["value"] = vram_budget_settings.VRAM_FRACTION_DEFAULT+ assert V._h3_budgeted_launch_flags(runtime, flags) == flags++[email protected]("explicit", [True, False])+def test_h3_single_card_refusal_checks_the_rounded_spare(fraction, monkeypatch, explicit):+ """The reserve rounds UP to the emitted spare, and the refusal checks that spare."""+ import contextlib+ import functools++ import core.inference.video as V+ from core.inference import diffusion_memory as D+ from core.inference import sd_cpp_args+ from core.inference.video_minimax_h3 import H3NativeMemoryRefusal+ from utils import hardware+ from utils.hardware import gpu_query++ MIB = 1 << 20+ D._LOAD_BUDGET_FRACTIONS.clear()+ monkeypatch.setattr(sd_cpp_args, "explicit_vram_budget_enabled", lambda: explicit)+ monkeypatch.setattr(gpu_query, "fresh_reads", contextlib.nullcontext)+ fraction["value"] = 0.899+ reserve = D.user_budget_reserve_bytes("cuda", 24 * GIB)+ devices = [{"visible_ordinal": 0, "vram_total_gb": 24.0, "vram_used_gb": 0.0}]+ monkeypatch.setattr(hardware, "get_visible_gpu_utilization", lambda **k: {"devices": devices})+ runtime = types.SimpleNamespace(+ vram_free_probe = functools.partial(V._h3_card_free_bytes, "cuda", 0),+ vram_reserve_probe = functools.partial(V._h3_card_reserve_bytes, "cuda", 0),+ )+ flags = ["--offload-to-cpu", "--max-vram", "-1", "--stream-layers"]++ def launch_at(raw_free):+ devices[0]["vram_used_gb"] = 24.0 - raw_free / GIB+ return V._h3_budgeted_launch_flags(runtime, flags)++ with pytest.raises(H3NativeMemoryRefusal, match = "VRAM Budget"):+ launch_at(reserve + GIB + MIB)+ raw = reserve + GIB + 64 * MIB+ out = launch_at(raw)+ assert out[2] == "-3.43" and raw + float(out[2]) * GIB > 0+++def test_encoder_prefetch_window_reads_free_less_the_reserve(fraction, card):+ from core.inference import diffusion_small_host as S++ card["free"] = 12 * GIB + 2 * GIB+ assert S._prefetch_budget_bytes(torch.device("cuda", 0)) == S._PREFETCH_MAX_BYTES+ fraction["value"] = 0.50+ assert S._prefetch_budget_bytes(torch.device("cuda", 0)) == 2 * GIB // 8+ card["free"] = 12 * GIB + 512 * 1024**2+ assert S._prefetch_budget_bytes(torch.device("cuda", 0)) == S._PREFETCH_MIN_BYTES+++def test_encoder_prefetch_is_off_when_the_budget_leaves_under_the_floor(fraction, card):+ """#14816 r9: the 128 MiB floor must not hand the worker a group the budgeted room cannot hold."""+ from core.inference import diffusion_small_host as S++ fraction["value"] = 0.50+ for room in (0, 100 * 1024**2, S._PREFETCH_MIN_BYTES - 1):+ card["free"] = 12 * GIB + room+ assert S._prefetch_budget_bytes(torch.device("cuda", 0)) == 0+ card["free"] = 2 * GIB # under the reserve: still nothing+ assert S._prefetch_budget_bytes(torch.device("cuda", 0)) == 0+ fraction["value"] = vram_budget_settings.VRAM_FRACTION_DEFAULT+ card["free"] = 64 * 1024**2+ assert S._prefetch_budget_bytes(torch.device("cuda", 0)) == S._PREFETCH_MIN_BYTES+++def test_rocm_flash_probe_room_charges_the_reserve(fraction, card):+ from core.inference import diffusion_attention as att++ card["free"], card["cached"] = 4 * GIB, 0+ need = 2 * GIB+ assert att._rocm_flash_probe_fits("cuda:0", need) is True+ fraction["value"] = 0.90 # 2.4 GiB kept free+ assert att._rocm_flash_probe_fits("cuda:0", need) is False+++def test_segmenter_card_room_charges_the_reserve(fraction, card):+ from core.inference import diffusion_segment as seg++ # driver free plus the 1 GiB reusable allocator cache, less the reserve+ assert seg._cuda_free_mib(0) == (21 * 1024, 24 * 1024)+ fraction["value"] = 0.50+ assert seg._cuda_free_mib(0) == (9 * 1024, 24 * 1024)+ card["free"] = 4 * GIB+ assert seg._cuda_free_mib(0) == (0, 24 * 1024)+++def test_untiled_encode_shortfall_charges_the_reserve(fraction, card, monkeypatch):+ from core.inference import diffusion as D+ from core.inference import diffusion_vae_tiling as vt++ monkeypatch.setattr(vt, "_geometry", lambda vae: (8,))+ monkeypatch.setattr(vt, "_fused", lambda vae: False)+ monkeypatch.setattr(vt, "encode_mib_per_latent", lambda *a, **k: 1.0)+ param = types.SimpleNamespace(element_size = lambda: 2)+ vae = types.SimpleNamespace(encoder = types.SimpleNamespace(parameters = lambda: iter([param])))+ x = _cuda_z(1, 3, 64, 64)+ base = D._untiled_encode_shortfall_mib(vae, x)+ assert base is not None+ fraction["value"] = 0.50+ assert D._untiled_encode_shortfall_mib(vae, x) == base + 12 * 1024+++def test_vae_prebuild_child_keeps_the_reserve_free(fraction, card, monkeypatch):+ from core.inference import diffusion_vae_prebuild as P++ spawned = []+ monkeypatch.setattr(P, "enabled", lambda: True)+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.version, "hip", None, raising = False)+ monkeypatch.setattr(P, "plan", lambda pipe: {"device": 0})+ monkeypatch.setattr(P, "_spawn", lambda job, logger: spawned.append(job) or True)+ ctx = types.SimpleNamespace(hit = False)+ card["free"] = P._MIN_FREE_BYTES + 1 * GIB+ assert P.maybe_kick(object(), ctx) is True+ fraction["value"] = 0.90 # 2.4 GiB kept free+ assert P.maybe_kick(object(), ctx) is False+ assert len(spawned) == 1+++def test_ltx25_encoder_on_card_check_keeps_the_sent_share_free(card, monkeypatch):+ from core.inference import video_ltx25_te_worker as worker++ monkeypatch.setattr(worker, "_weights_mib", lambda m: 2 * 1024)+ card["free"] = (2 * 1024 + worker.ENCODE_MARGIN_MIB + 1024) << 20+ model = types.SimpleNamespace()+ assert worker._encode_device({"device": "cuda:0", "resident": False}, model) == "cuda:0"+ config = {"device": "cuda:0", "resident": False, "vram_reserve_share": 0.10} # 2.4 GiB of 24+ assert worker._encode_device(config, model) == "cpu"+++def test_ltx25_start_sends_the_reserve_share_only_below_the_default(fraction, monkeypatch):+ from core.inference import video_ltx25 as L++ started = []++ class _Client:+ def __init__(self, **kwargs):+ self.config = {}++ def start(self):+ started.append(dict(self.config))++ monkeypatch.setattr(L, "ensure_text_encoder_sidecar", lambda: "/nonexistent")+ monkeypatch.setattr(L, "Ltx25TextEncoderClient", _Client)+ kw = dict(+ repo = "Lightricks/LTX-2.5",+ revision = "abc",+ hf_token = None,+ cache_dir = None,+ local_files_only = True,+ device = "cuda:0",+ dtype = "bfloat16",+ resident = False,+ )+ L.start_text_encoder(**kw)+ assert "vram_reserve_share" not in started[-1]+ fraction["value"] = 0.75+ L.start_text_encoder(**kw)+ assert started[-1]["vram_reserve_share"] == pytest.approx(0.25)diff --git a/studio/backend/tests/test_video_quantised_offload.py b/studio/backend/tests/test_video_quantised_offload.pyindex e12b1e59f14..640556cce04 100644--- a/studio/backend/tests/test_video_quantised_offload.py+++ b/studio/backend/tests/test_video_quantised_offload.py@@ -574,6 +574,68 @@ def test_generate_refuses_below_the_offload_floor(fake_runtime, monkeypatch, tmpbackend.generate(prompt = "a sloth", width = 1280, height = 720, num_frames = 121, fps = 8)+def fraction(monkeypatch):+ from utils import vram_budget_settings++ state = {"value": vram_budget_settings.VRAM_FRACTION_DEFAULT}+ monkeypatch.setattr(vram_budget_settings, "get_vram_budget_fraction", lambda: state["value"])+ return state+++def test_conventional_video_generate_guard_charges_the_reserve(+ fraction, fake_runtime, monkeypatch, tmp_path+):+ backend = VideoBackend()+ _load_gguf(backend, tmp_path)+ torch = sys.modules["torch"]+ monkeypatch.setattr(+ torch,+ "device",+ lambda kind, index = None: types.SimpleNamespace(type = kind, index = index),+ raising = False,+ )+ monkeypatch.setattr(+ torch,+ "cuda",+ types.SimpleNamespace(+ is_available = lambda: False,+ mem_get_info = lambda device = None: (40 * GIB << 20, 80 * GIB << 20),+ memory_reserved = lambda device = None: 0,+ ),+ )++ def _as_on_cuda():+ backend._state = dataclasses.replace(+ backend._state, device = "cuda", offload_policy = "model", vram_floor_mib = 27300+ )++ _as_on_cuda()+ backend.generate(prompt = "a sloth", width = 256, height = 256, num_frames = 9, fps = 8)+ fraction["value"] = 0.80 # 40 GIB free less a 16 GIB reserve cannot hold the 27.3 GIB floor+ backend.generate(prompt = "a sloth", width = 256, height = 256, num_frames = 9, fps = 8)+ _load_gguf(backend, tmp_path)+ _as_on_cuda()+ with pytest.raises(RuntimeError, match = "needs about"):+ backend.generate(prompt = "a sloth", width = 256, height = 256, num_frames = 9, fps = 8)+++def test_video_load_refuses_a_tier_only_the_reserve_rules_out(fraction, fake_runtime, monkeypatch):+ import core.inference.video as V++ spy = _spoof(monkeypatch, tier_gib = 24) # 24 GiB card, 600 MiB in use+ monkeypatch.setattr(V, "_video_offload_vram_floor_mib", lambda pipe, plan, **k: 18000)+ VideoBackend().load_pipeline(FAMILIES["wan2.2-t2v-a14b"])+ assert spy.plans+ spy.plans.clear()+ fraction["value"] = (+ 0.70 # 7.2 GiB kept free: 16.2 GiB cannot hold 18000 MiB plus its activations+ )+ with pytest.raises(RuntimeError, match = "needs about"):+ VideoBackend().load_pipeline(FAMILIES["wan2.2-t2v-a14b"])+ assert not spy.plans++def test_quantise_stages_what_fits_on_the_card_and_unstages_it(monkeypatch):"""The DiT is quantised on the card block by block and sent back to the host when the plan moves it."""torch = pytest.importorskip("torch")diff --git a/studio/backend/tests/test_video_stream_residency.py b/studio/backend/tests/test_video_stream_residency.pyindex 77a6af1785c..6d4d4adfaff 100644--- a/studio/backend/tests/test_video_stream_residency.py+++ b/studio/backend/tests/test_video_stream_residency.py@@ -98,7 +98,8 @@ def test_video_request_path_fits_the_residency_before_the_vram_check():free_reads = [n.linenofor n in ast.walk(tree)- if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "trusted_mem_get_info"+ if isinstance(n, ast.Call)+ and getattr(n.func, "id", None) in ("trusted_mem_get_info", "_request_available_bytes")]assert any(line > fit.lineno for line in free_reads)@@ -287,6 +288,20 @@ def test_measured_peak_widens_the_next_request(monkeypatch):assert _placed(net) == ["cuda"] + ["cpu"] * 5+def test_vram_budget_caps_the_resident_prefix(monkeypatch):+ """The user's VRAM Budget keeps its share of the card free when the residency is re-fit per request."""+ torch, net, pipe, x, ref = _streamed_net()+ from utils import vram_budget_settings++ monkeypatch.setattr(vram_budget_settings, "get_vram_budget_fraction", lambda: 0.97)+ _fit(pipe, monkeypatch, 1024)+ assert _placed(net) == ["cuda"] * 6+ monkeypatch.setattr(vram_budget_settings, "get_vram_budget_fraction", lambda: 0.5)+ _fit(pipe, monkeypatch, 1024)+ assert _placed(net) == ["cpu"] * 6+ assert torch.equal(net(x.cuda()).cpu(), ref)++def _graph_handle(declined = None, **state):torch = pytest.importorskip("torch")import core.inference.diffusion_cuda_graph as cg