Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio sd.cpp: explicit VRAM budget for MiniMax-H3 and a CUDA capability fallback (#13714)
Daniel Han9322afbe096f
diff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.pyindex 7fb711d8b54..5d40be2cfd1 100644--- a/studio/backend/core/inference/sd_cpp_args.py+++ b/studio/backend/core/inference/sd_cpp_args.py@@ -371,6 +371,160 @@ GRAPH_CUT_STREAM_FLAGS: tuple[str, ...] = ("--stream-layers",)# The full set, for callers that already offload to CPU.GRAPH_CUT_AUTO_FLAGS: tuple[str, ...] = GRAPH_CUT_VRAM_FLAGS + GRAPH_CUT_STREAM_FLAGS+# The committed "-1" is a placeholder (live server signatures compare on it); a launch swaps it for an explicit GiB+# budget read before the spawn, so the 2 GiB reserve also covers the child's own CUDA context and cuBLAS workspaces.+# Other negative values (UMA pinned-weight reserve) are applied by sd.cpp itself and never replaced.+GRAPH_CUT_BUDGET_RESERVE_BYTES = 2 << 30+GRAPH_CUT_MIN_BUDGET_BYTES = 1 << 30+GRAPH_CUT_RETRY_SCALE = 0.75+GRAPH_CUT_EXPLICIT_BUDGET_ENV = "UNSLOTH_SD_CPP_EXPLICIT_VRAM_BUDGET"+++def explicit_vram_budget_enabled(env: Optional[dict] = None) -> bool:+ """Kill switch: ``UNSLOTH_SD_CPP_EXPLICIT_VRAM_BUDGET=0`` keeps sd.cpp's own "-1" free-VRAM reading."""+ import os++ environ = os.environ if env is None else env+ return str(environ.get(GRAPH_CUT_EXPLICIT_BUDGET_ENV, "")).strip().lower() not in (+ "0",+ "false",+ "no",+ "off",+ )+++def graph_cut_budget_gib(+ free_bytes: Optional[int],+ *,+ reserve_bytes: int = GRAPH_CUT_BUDGET_RESERVE_BYTES,+ scale: float = 1.0,+) -> Optional[float]:+ """``--max-vram`` GiB for ``free_bytes`` free, or None (keep "-1"). Rounded DOWN so it never exceeds the plan."""+ if free_bytes is None:+ return None+ budget = (int(free_bytes) - int(reserve_bytes)) * float(scale)+ if budget < GRAPH_CUT_MIN_BUDGET_BYTES:+ return None+ return int(budget / float(1 << 30) * 100) / 100.0+++def _format_gib(value: float) -> str:+ return f"{value:.2f}"+++def max_vram_value(flags: Sequence[str]) -> Optional[str]:+ items = list(flags)+ for i, flag in enumerate(items):+ if flag == "--max-vram":+ return items[i + 1] if i + 1 < len(items) else None+ return None+++def max_vram_is_auto(value: Optional[str]) -> bool:+ if value is None or "=" in value or "," in value:+ return False+ try:+ return float(value) < 0+ except ValueError:+ return False+++def max_vram_is_placeholder(value: Optional[str]) -> bool:+ """Only the committed ``-1``; a computed UMA reserve (``-17.05``) is sd.cpp's to apply, not a placeholder."""+ if not max_vram_is_auto(value):+ return False+ return float(value) == float(GRAPH_CUT_VRAM_FLAGS[1]) # type: ignore[arg-type]+++def with_max_vram_budget(+ flags: Sequence[str], budget: "Optional[float | dict[str, float]]"+) -> list[str]:+ """Replace only the ``-1`` placeholder (dict -> ``cuda0=6.25,cuda1=12.50``), never a user or UMA-fit value."""+ out = list(flags)+ if not budget:+ return out+ for i, flag in enumerate(out):+ if flag != "--max-vram" or i + 1 >= len(out) or not max_vram_is_placeholder(out[i + 1]):+ continue+ if isinstance(budget, dict):+ out[i + 1] = ",".join(f"{name}={_format_gib(gib)}" for name, gib in budget.items())+ else:+ out[i + 1] = _format_gib(float(budget))+ return out+++def explicit_max_vram_gib(flags: Sequence[str]) -> "Optional[float | dict[str, float]]":+ value = max_vram_value(flags)+ if value is None or max_vram_is_auto(value):+ return None+ try:+ if "=" in value:+ out: dict[str, float] = {}+ for part in value.split(","):+ name, _, gib = part.partition("=")+ out[name.strip()] = float(gib)+ return out+ gib = float(value)+ except ValueError:+ return None+ return gib if gib > 0 else None+++def scaled_vram_budget(+ budget: "float | dict[str, float]", scale: float+) -> "Optional[float | dict[str, float]]":+ """``budget * scale`` per device, or None once any device falls below ``GRAPH_CUT_MIN_BUDGET_BYTES``."""+ floor_gib = GRAPH_CUT_MIN_BUDGET_BYTES / float(1 << 30)++ def one(gib: float) -> Optional[float]:+ value = int(float(gib) * float(scale) * 100) / 100.0+ return value if value >= floor_gib else None++ if isinstance(budget, dict):+ out = {name: one(gib) for name, gib in budget.items()}+ if not out or any(v is None for v in out.values()):+ return None+ return out # type: ignore[return-value]+ return one(float(budget))+++# Not the model manager's "cannot make enough memory available": completed renders print it too.+_DEVICE_OOM_MARKERS: tuple[str, ...] = (+ "erroroutofdevicememory",+ "out_of_device_memory",+ "cudaerrormemoryallocation",+ "hiperroroutofmemory",+ "failed to allocate cuda",+ "failed to allocate rocm",+ "failed to allocate vulkan",+ "failed to allocate metal",+ "failed during workspace capacity check",+ "failed during workspace allocation",+ "failed during allocated capacity check",+)+# Bare "out of memory" counts only beside a device API name; host OOM is not cured by a smaller VRAM budget.+_DEVICE_OOM_CONTEXT: tuple[str, ...] = ("cuda", "hip", "rocm", "vulkan", "metal", "ggml_backend")+_HOST_OOM_MARKERS: tuple[str, ...] = (+ "host malloc",+ "host memory",+ "out_of_host_memory",+ "bad_alloc",+ "cannot allocate memory",+)+++def is_device_oom_text(text: Optional[str]) -> bool:+ if not text:+ return False+ for line in str(text).lower().splitlines():+ if any(marker in line for marker in _HOST_OOM_MARKERS):+ continue+ if any(marker in line for marker in _DEVICE_OOM_MARKERS):+ return True+ if "out of memory" in line and any(word in line for word in _DEVICE_OOM_CONTEXT):+ return True+ return False+def device_backend_flags(device_name: Optional[str], offload: Optional[list[str]] = Nonediff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 4729e7be51d..09f7d57d4ad 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -664,6 +664,56 @@ def sd_cpp_cuda_compute_capability(return caps.get(int(device_name[len(head) :]))+def sd_cpp_device_listing_known(binary: Optional[str]) -> bool:+ if not binary:+ return False+ seen = _LAST_DEVICE_LISTING.get(binary)+ return seen is not None and seen[0] == _binary_stat_identity(binary)+++# Runs when --list-devices timed out (possibly a stalled driver); CUDA calls have no deadline, so bound the wait.+TORCH_CC_TIMEOUT_S = 10.0+++def torch_cuda_compute_capability(+ ordinal: Optional[int], *, timeout_s: Optional[float] = None+) -> Optional[tuple[int, int]]:+ """torch's compute capability for ``ordinal`` (lowest visible when None), or None on ROCm (not sm numbers),+ error or timeout (the daemon thread is left behind). Same runtime and mask as CUDA sd.cpp, so indices agree."""+ import threading++ result: list = []++ def read() -> None:+ result.append(_torch_cuda_compute_capability(ordinal))++ worker = threading.Thread(target = read, daemon = True, name = "sd-cpp-torch-cc")+ worker.start()+ worker.join(TORCH_CC_TIMEOUT_S if timeout_s is None else timeout_s)+ return result[0] if result else None+++def _torch_cuda_compute_capability(ordinal: Optional[int]) -> Optional[tuple[int, int]]:+ try:+ import torch++ if getattr(torch.version, "hip", None) or not getattr(torch.version, "cuda", None):+ return None+ if not torch.cuda.is_available():+ return None+ if ordinal is None:+ caps = [+ tuple(torch.cuda.get_device_capability(i)) for i in range(torch.cuda.device_count())+ ]+ return min(caps) if caps else None # type: ignore[return-value]+ if not 0 <= int(ordinal) < torch.cuda.device_count():+ return None+ major, minor = torch.cuda.get_device_capability(int(ordinal))+ return (int(major), int(minor))+ except Exception: # noqa: BLE001 -- unknown stays unknown+ return None++_VULKAN_DEVICE_UMA_RE = re.compile(r"^ggml_vulkan: (\d+) = .*?\| uma: ([01]) \|", re.MULTILINE)diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex bdf056ab64a..5479a46cf7b 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -1749,6 +1749,164 @@ def _h3_launch_flags(return list(flags + tuple(device_backend_flags(inputs.device_name, list(flags))))+def _h3_budgeted_launch_flags(+ runtime: Any,+ flags: "Sequence[str]",+ *,+ cap: Any = None,+) -> list[str]:+ """Swap ``--max-vram -1`` for a budget from free VRAM read now, never above ``cap``; anything unknown keeps -1."""+ from .sd_cpp_args import (+ explicit_vram_budget_enabled,+ graph_cut_budget_gib,+ max_vram_is_placeholder,+ max_vram_value,+ with_max_vram_budget,+ )++ 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)):+ return out+ probe = getattr(runtime, "vram_free_probe", None)+ try:+ free = probe() if probe is not None else None+ except Exception: # noqa: BLE001 -- an unreadable card keeps sd.cpp's own reading+ free = None+ # Too little free now: "-1" is already below this reading, while an earlier retry cap could exceed it.+ known_small = False+ if isinstance(free, dict):+ budget: Any = {}+ for name, value in free.items():+ gib = graph_cut_budget_gib(value)+ limit = cap.get(name) if isinstance(cap, dict) else cap+ if gib is None:+ known_small = known_small or value is not None+ budget = None+ break+ budget[name] = min(gib, float(limit)) if limit is not None else gib+ else:+ budget = graph_cut_budget_gib(free)+ known_small = budget is None and free is not None+ if budget is not None and cap is not None and not isinstance(cap, dict):+ budget = min(budget, float(cap))+ if not budget:+ if cap is not None and not known_small:+ out = with_max_vram_budget(out, cap)+ 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",+ )+ return out+ out = with_max_vram_budget(out, budget)+ logger.info(+ "video.h3_native_vram_budget: --max-vram %s (free %s at launch%s)",+ max_vram_value(out),+ free,+ f", capped by retry budget {cap}" if cap is not None else "",+ )+ 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)+ if restart is not None:+ return bool(restart(reason))+ if getattr(slot, "release_pending", None) is not None:+ return False+ slot.stop(reason)+ return True+++def _h3_retry_vram_cap(launched: "Optional[Sequence[str]]", error: str) -> Any:+ from .sd_cpp_args import (+ GRAPH_CUT_RETRY_SCALE,+ explicit_max_vram_gib,+ is_device_oom_text,+ scaled_vram_budget,+ )++ if not launched or not is_device_oom_text(error):+ return None+ budget = explicit_max_vram_gib(launched)+ if budget is None:+ return None+ return scaled_vram_budget(budget, GRAPH_CUT_RETRY_SCALE)+++def _h3_cuda_cc_fallback(+ cuda_cc: "Optional[tuple[int, int]]",+ *,+ binary: Optional[str],+ native_device: Optional[str],+ listed_accelerator: Optional[bool],+ accelerator_names: "Sequence[Any]",+ device_name: Optional[str],+) -> "Optional[tuple[int, int]]":+ """torch's compute capability when ``--list-devices`` was unreadable (else sm80+ fell to exact kernels: 29.3 vs+ ~5 s/step). Unpinned reads visible ordinal 0, sd.cpp's default, never the lowest across a mixed host."""+ from .sd_cpp_backend import (+ _accelerator_class_of,+ sd_cpp_device_listing_known,+ torch_cuda_compute_capability,+ )++ if cuda_cc is not None or native_device == "cpu" or listed_accelerator is None:+ return cuda_cc+ if sd_cpp_device_listing_known(binary):+ return cuda_cc+ # Only the install record says what the build targets; an unowned SD_CLI_PATH build may be Vulkan / CPU.+ if not any(+ isinstance(name, str) and _accelerator_class_of(name) == "cuda"+ for name in accelerator_names+ ):+ return cuda_cc+ ordinal: Optional[int] = 0+ if device_name:+ head = device_name.rstrip("0123456789")+ if head.upper() != "CUDA" or not device_name[len(head) :]:+ return cuda_cc+ ordinal = int(device_name[len(head) :])+ fallback = torch_cuda_compute_capability(ordinal)+ logger.warning(+ "video.h3_cuda_cc_fallback: sd-cli --list-devices was unreadable; compute capability %s from torch "+ "(device %s)",+ fallback,+ device_name or "CUDA0, sd.cpp's default",+ )+ return fallback+++def _pairs(flags: "Sequence[str]") -> "list[tuple[str, str]]":+ items = list(flags or ())+ return [(items[i], items[i + 1]) for i in range(len(items) - 1) if items[i].startswith("--")]+++def _h3_one_shot_with_vram_retry(+ runtime: Any,+ run: "Callable[[list[str]], Any]",+ render_flags: "Sequence[str]",+ cancel: threading.Event,+) -> Any:+ launch = _h3_budgeted_launch_flags(runtime, render_flags)+ try:+ return run(launch)+ except RuntimeError as exc:+ if cancel.is_set():+ raise+ cap = _h3_retry_vram_cap(launch, str(exc))+ if cap is None:+ raise+ logger.warning(+ "video.h3_native_vram_retry: device out of memory under --max-vram %s (sd-cli); retrying once with %s",+ dict(_pairs(launch)).get("--max-vram"),+ cap,+ )+ return run(_h3_budgeted_launch_flags(runtime, render_flags, cap = cap))++def _torch_pci_slot(ordinal: Optional[int]) -> Optional[str]:"""``DDDD:BB:DD`` of the torch-visible card at *ordinal* (no function digit: torch does not report it)."""if ordinal is None:@@ -2303,7 +2461,7 @@ def _h3_card_memory_bytes(from utils.hardware import get_visible_gpu_utilization, gpu_querywith gpu_query.fresh_reads():- devices = get_visible_gpu_utilization().get("devices", [])+ devices = get_visible_gpu_utilization(no_context = True).get("devices", [])want = 0 if ordinal is None else int(ordinal)for entry in devices:if entry.get("visible_ordinal") != want:@@ -2319,11 +2477,30 @@ def _h3_card_memory_bytes(return None, None-def _h3_card_free_bytes(device: Optional[str], ordinal: Optional[int]) -> Optional[int]:- """Free VRAM of the H3 render card, or None (keeps the committed offload flags)."""+def _h3_card_free_bytes(+ device: Optional[str],+ ordinal: Optional[int],+ *,+ single_card_only: bool = False,+) -> 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."""+ if single_card_only and _h3_visible_card_count(device) != 1:+ return Nonereturn _h3_card_memory_bytes(device, ordinal)[0]+def _h3_visible_card_count(device: Optional[str]) -> Optional[int]:+ if device != "cuda":+ return None+ try:+ from utils.hardware import get_visible_gpu_utilization, gpu_query+ with gpu_query.fresh_reads():+ return len(get_visible_gpu_utilization(no_context = True).get("devices", []))+ except Exception: # noqa: BLE001 -- unknown count reads as not single+ return None++def _h3_native_server_pressure(device: Optional[str], ordinal: Optional[int]) -> Optional[str]:"""Why the resident H3 sd-server should not outlive a render (``h3_native_server_pressure``), or None."""from .diffusion_memory import _available_system_memory_mib, _host_ram_capacity_mib@@ -5116,6 +5293,14 @@ class VideoBackend:if native_device != "cpu" and listed_accelerator is not Noneelse None)+ native_cuda_cc = _h3_cuda_cc_fallback(+ native_cuda_cc,+ binary = binary,+ native_device = native_device,+ listed_accelerator = listed_accelerator,+ accelerator_names = (decided_accelerator,),+ device_name = native_device_name,+ )# What the executable itself renders on: an unowned build (SD_CLI_PATH) has no install record.native_listed_class, native_listed_description = (sd_cpp_listed_device(binary, native_device_name, probe = False)@@ -5322,6 +5507,16 @@ class VideoBackend:offloaded_flags = native_fit_flags,offload_refusal = native_fit_refusal,fit_inputs = native_fit_inputs,+ vram_free_probe = (+ functools.partial(+ _h3_card_free_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 = (@@ -12353,53 +12548,94 @@ class VideoBackend:)render_flags = list(runtime.offload_flags) if flags is None else list(flags)render_env = dict(runtime.env) if env is None else dict(env)+ from .sd_cpp_args import is_device_oom_text+slot.begin_render()try:- try:- server = slot.get(- render_flags,- render_env,- cancel_event = cancel,- pre_spawn = functools.partial(- _h3_launch_flags,- runtime,+ retry_cap: Any = None+ while True:+ try:+ server = slot.get(render_flags,- memory_mode,- compute_bytes = h3_native_compute_bytes(- params.width, params.height, params.num_frames+ render_env,+ cancel_event = cancel,+ pre_spawn = functools.partial(+ _h3_launch_flags,+ runtime,+ render_flags,+ memory_mode,+ compute_bytes = h3_native_compute_bytes(+ params.width, params.height, params.num_frames+ ),+ ),+ launch_transform = functools.partial(+ _h3_budgeted_launch_flags, runtime, cap = retry_cap),- ),- )- except (SdCppCancelled, H3NativeMemoryRefusal):- raise- except Exception as exc: # noqa: BLE001 - any start failure leaves the one-shot path- if cancel.is_set():- raise SdCppCancelled("sd-server start was cancelled.") from exc- logger.warning("video.h3_native_server_start_failed (using sd-cli): %s", exc)- slot.disable(f"start failed: {exc}")- return None- try:- data = server.vid_gen(payload, on_step = on_log, cancel_event = cancel)- except SdCppServerUnsupported as exc:- logger.warning("video.h3_native_server_unsupported (using sd-cli): %s", exc)- slot.disable(str(exc))- return None- except SdCppCancelled:- raise- except RuntimeError as exc:- if cancel.is_set():- raise SdCppCancelled("sd-server generation was cancelled.") from exc- if not server.is_alive():- logger.warning(- "video.h3_native_server_died (retrying once on sd-cli, staying one-shot): %s",- exc,)- slot.disable(f"server died: {exc}")+ except (SdCppCancelled, H3NativeMemoryRefusal):+ raise+ except Exception as exc: # noqa: BLE001 - any start failure leaves the one-shot path+ if cancel.is_set():+ raise SdCppCancelled("sd-server start was cancelled.") from exc+ if retry_cap is not None and is_device_oom_text(str(exc)):+ slot.stop("render failed")+ raise+ # A start-time device OOM gets one smaller retry instead of disabling the server.+ cap = _h3_retry_vram_cap(getattr(slot, "attempted_flags", None), str(exc))+ if cap is not None and _h3_restart_for_retry(+ slot, "server start out of memory"+ ):+ logger.warning(+ "video.h3_native_vram_retry: server start out of device memory; retrying once with %s",+ cap,+ )+ retry_cap = cap+ continue+ logger.warning("video.h3_native_server_start_failed (using sd-cli): %s", exc)+ slot.disable(f"start failed: {exc}")return None- slot.stop("render failed")- raise- Path(output_path).write_bytes(data)- return Path(output_path)+ try:+ data = server.vid_gen(payload, on_step = on_log, cancel_event = cancel)+ except SdCppServerUnsupported as exc:+ logger.warning("video.h3_native_server_unsupported (using sd-cli): %s", exc)+ slot.disable(str(exc))+ return None+ except SdCppCancelled:+ raise+ except RuntimeError as exc:+ if cancel.is_set():+ raise SdCppCancelled("sd-server generation was cancelled.") from exc+ cap = (+ _h3_retry_vram_cap(getattr(slot, "launched_flags", None), str(exc))+ if retry_cap is None+ else None+ )+ if cap is not None and _h3_restart_for_retry(+ slot, "device out of memory; retrying with a smaller VRAM budget"+ ):+ logger.warning(+ "video.h3_native_vram_retry: device out of memory under --max-vram %s; "+ "retrying once with %s: %s",+ dict(_pairs(getattr(slot, "launched_flags", ()))).get("--max-vram"),+ cap,+ str(exc).splitlines()[0] if str(exc) else exc,+ )+ retry_cap = cap+ continue+ if retry_cap is not None and is_device_oom_text(str(exc)):+ slot.stop("render failed")+ raise+ if not server.is_alive():+ logger.warning(+ "video.h3_native_server_died (retrying once on sd-cli, staying one-shot): %s",+ exc,+ )+ slot.disable(f"server died: {exc}")+ return None+ slot.stop("render failed")+ raise+ Path(output_path).write_bytes(data)+ return Path(output_path)finally:try:slot.end_render()@@ -12623,16 +12859,21 @@ class VideoBackend:compute_bytes = compute_bytes,)from .sd_cpp_backend import _explicit_threads- generated = runtime.engine.generate_video(- runtime.files,- video_params,- output_path = str(output_path),- offload = render_flags,- # sd.cpp's default undercounts M5 Pro / Max and ignores env / cgroup quota- threads = _explicit_threads(),- env = dict(runtime.env) or None,- on_log = on_log,- cancel_event = cancel,+ generated = _h3_one_shot_with_vram_retry(+ runtime,+ lambda launch_flags: runtime.engine.generate_video(+ runtime.files,+ video_params,+ output_path = str(output_path),+ offload = launch_flags,+ # sd.cpp's default undercounts M5 Pro / Max and ignores env / cgroup quota+ threads = _explicit_threads(),+ env = dict(runtime.env) or None,+ on_log = on_log,+ cancel_event = cancel,+ ),+ render_flags,+ cancel,)except SdCppCancelled:raise RuntimeError(VIDEO_CANCELLED_MSG) from Nonediff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.pyindex 447cc48f69c..2f8c2e30260 100644--- a/studio/backend/core/inference/video_minimax_h3.py+++ b/studio/backend/core/inference/video_minimax_h3.py@@ -1814,6 +1814,8 @@ class MiniMaxH3NativeRuntime:offload_refusal: Optional[str] = None# Auto only: re-fit inputs, so an offloaded render is judged on live readings rather than the load's.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# 0 / false / off: every render on a fresh one-shot sd-cli.@@ -1924,6 +1926,9 @@ class H3NativeServerSlot:self._server: Any = Noneself._stopping: Any = Noneself._signature: Optional[tuple] = None+ self.launched_flags: Optional[tuple[str, ...]] = None+ # Set before a start runs; ``launched_flags`` only after it succeeds.+ self.attempted_flags: Optional[tuple[str, ...]] = Noneself._lock = threading.RLock()self._busy = 0self._release_pending: Optional[str] = None@@ -1959,11 +1964,14 @@ class H3NativeServerSlot:*,cancel_event: Any = None,pre_spawn: "Optional[Callable[[], Any]]" = None,+ launch_transform: "Optional[Callable[[tuple[str, ...]], Any]]" = None,) -> Any:"""The live server for this (flags, env), (re)spawning one if needed. ``cancel_event`` aborts a start: therender holds the generate lock through the model load, so unload and Cancel would otherwise wait it out.``pre_spawn`` runs only when a process is about to start, under the slot lock and after any old server has- stopped: it returns the flags to start with (a live memory fit) or raises to refuse the start."""+ stopped: it returns the flags to start with (a live memory fit) or raises to refuse the start.+ ``launch_transform`` rewrites only the argv; the signature keeps untransformed flags so a varying budget+ never makes a reusable server look stale."""import threadingfrom .sd_cpp_backend import register_tree_holder, unregister_tree_holder@@ -1987,6 +1995,10 @@ class H3NativeServerSlot:# Reuse was decided above, under this lock: from here a process starts, so it is fitted now.flag_tuple = tuple(pre_spawn())wanted = self._signature_for(flag_tuple, env_pairs)+ launch_tuple = (+ tuple(launch_transform(flag_tuple)) if launch_transform is not None else flag_tuple+ )+ self.attempted_flags = launch_tupleserver = SdCppServer(self.server_binary)managed = is_managed_binary(self.server_binary)self._server = server@@ -2011,7 +2023,7 @@ class H3NativeServerSlot:from .sd_cpp_backend import _explicit_threadsserver.start(self.files,- offload = list(flag_tuple),+ offload = list(launch_tuple),threads = _explicit_threads(),env = dict(env_pairs) or None,# A context flag on sd-server (per-run on sd-cli); same RNG keeps seeds identical across paths.@@ -2029,6 +2041,7 @@ class H3NativeServerSlot:unregister_tree_holder(self)raisestarted.set()+ self.launched_flags = launch_tupleif cancel_event is not None and cancel_event.is_set() and not server.is_alive():self._stop_locked("cancelled")raise SdCppCancelled("sd-server start was cancelled.")@@ -2043,7 +2056,12 @@ class H3NativeServerSlot:"""Stop the server (pending release, memory pressure, idle 0) or arm the idle timer. Returns the stop reason."""with self._lock:self._busy = max(0, self._busy - 1)- if self._busy or self._server is None:+ if self._busy:+ return None+ if self._server is None:+ self._release_pending = (+ None # nothing left to release; a stale one would refuse the next retry+ )return Nonereason = self._release_pendingif reason is None and self.pressure_probe is not None:@@ -2074,16 +2092,30 @@ class H3NativeServerSlot:self._release_pending = reasonreturn Truetry:- if self._server is None:- return False+ # Busy first: between restart_for_retry's stop and the respawn the render still owns the slot.if self._busy:self._release_pending = reasonreturn True+ if self._server is None:+ return Falseself._stop_locked(reason)return Truefinally:self._lock.release()+ @property+ def release_pending(self) -> Optional[str]:+ return self._release_pending++ def restart_for_retry(self, reason: str) -> bool:+ """Stop for a retry unless a release is pending. One locked step: a release racing a separate check would be+ cleared by ``_stop_locked`` and the fresh server would outlive the render asked to free its memory."""+ with self._lock:+ if self._release_pending is not None:+ return False+ self._stop_locked(reason)+ return True+def stop(self, reason: str = "stopped") -> None:with self._lock:self._stop_locked(reason)diff --git a/studio/backend/tests/test_h3_native_server.py b/studio/backend/tests/test_h3_native_server.pyindex 2371167cf90..9c0dff93d35 100644--- a/studio/backend/tests/test_h3_native_server.py+++ b/studio/backend/tests/test_h3_native_server.py@@ -238,6 +238,7 @@ class _FakeSlot:*,cancel_event = None,pre_spawn = None,+ launch_transform = None,):if self.start_exc is not None:self.got.append((flags, env))@@ -245,6 +246,8 @@ class _FakeSlot:if pre_spawn is not None:# The real slot fits a start under its lock and starts with the flags the fit returns.flags = list(pre_spawn())+ if launch_transform is not None:+ self.launched_flags = tuple(launch_transform(tuple(flags or ())))self.got.append((flags, env))return self.serverdiff --git a/studio/backend/tests/test_sd_cpp_vram_budget.py b/studio/backend/tests/test_sd_cpp_vram_budget.pynew file mode 100644index 00000000000..0a09d9c44b5--- /dev/null+++ b/studio/backend/tests/test_sd_cpp_vram_budget.py@@ -0,0 +1,752 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""sd.cpp graph-cut VRAM budget and the H3 CUDA compute-capability fallback.++The committed H3 flags keep ``--max-vram -1`` (sd.cpp's own free-VRAM reading) as a placeholder; each process launch+replaces it with an explicit budget read by Studio right before the spawn, and a device OOM under that budget is+retried once at a smaller one. Hermetic: no binary, no GPU, no socket."""++from __future__ import annotations++import sys+import threading+from pathlib import Path++import pytest++from core.inference import sd_cpp_args as args_mod+from core.inference import sd_cpp_backend+from core.inference import sd_cpp_server as srv+from core.inference import video as video_mod+from core.inference import video_minimax_h3 as h3+from core.inference.sd_cpp_args import SdCppModelFiles, SdCppVideoGenParams+from core.inference.video import VideoBackend++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++GiB = 1 << 30++# The failure the offload audit recorded (H3 Q4_K, 12 GB card, another process moved VRAM mid-render).+_AUDIT_OOM = (+ "sd-server generation failed: generation_failed: generate_video returned no results\n"+ "Last output:\n"+ "[E] ggml: ggml_backend_cuda_buffer_type_alloc_buffer: allocating 210.08 MiB on device 0: "+ "cudaMalloc failed: out of memory\n"+ "[E] ggml: alloc_tensor_range: failed to allocate CUDA0 buffer of size 220288512\n"+ "[E] minimax_h3 failed to capture graph cut tensor: ggml_runner_cut:minimax_h3.blocks.7|hidden_states|\n"+ "[E] minimax_h3 segment 11/54 (minimax_h3.blocks.7) failed during output caching\n"+)++_FILES = SdCppModelFiles(+ diffusion_model = "/m/h3.gguf",+ vae = "/m/vae.safetensors",+ audio_vae = "/m/audio_vae.safetensors",+ llm = "/m/te.gguf",+)+_COMMITTED = ("--offload-to-cpu", "--diffusion-fa", "--max-vram", "-1", "--stream-layers")++[email protected](autouse = True)+def _no_kill_switch(monkeypatch):+ monkeypatch.delenv(args_mod.GRAPH_CUT_EXPLICIT_BUDGET_ENV, raising = False)+++def test_budget_is_free_minus_reserve_rounded_down():+ assert args_mod.graph_cut_budget_gib(None) is None+ assert args_mod.graph_cut_budget_gib(int(8.0 * GiB)) == 6.0+ assert args_mod.graph_cut_budget_gib(int(7.999 * GiB)) == 5.99+ # Under the floor after the reserve: keep sd.cpp's own reading.+ assert args_mod.graph_cut_budget_gib(int(2.9 * GiB)) is None+ assert args_mod.graph_cut_budget_gib(int(8 * GiB), scale = 0.5) == 3.0+++def test_only_the_auto_placeholder_is_replaced():+ assert args_mod.with_max_vram_budget(_COMMITTED, 6.25)[3] == "6.25"+ per_device = args_mod.with_max_vram_budget(_COMMITTED, {"cuda0": 6.0, "cuda1": 12.5})+ assert per_device[3] == "cuda0=6.00,cuda1=12.50"+ # An explicit value (the user's, or an earlier launch's) is never widened or rewritten.+ explicit = ["--max-vram", "4"]+ assert args_mod.with_max_vram_budget(explicit, 20.0) == explicit+ assert args_mod.with_max_vram_budget(["--max-vram", "cuda0=4"], 20.0) == [+ "--max-vram",+ "cuda0=4",+ ]+ assert args_mod.with_max_vram_budget(["--offload-to-cpu"], 6.0) == ["--offload-to-cpu"]+ assert args_mod.with_max_vram_budget(_COMMITTED, None) == list(_COMMITTED)+ assert args_mod.with_max_vram_budget(_COMMITTED, {}) == list(_COMMITTED)+++def test_explicit_budget_round_trips_and_scales():+ assert args_mod.explicit_max_vram_gib(_COMMITTED) is None+ assert args_mod.explicit_max_vram_gib(["--max-vram", "6.25"]) == 6.25+ assert args_mod.explicit_max_vram_gib(["--max-vram", "0"]) is None+ assert args_mod.explicit_max_vram_gib(["--max-vram", "cuda0=6,cuda1=12.5"]) == {+ "cuda0": 6.0,+ "cuda1": 12.5,+ }+ assert args_mod.explicit_max_vram_gib(["--max-vram", "garbage"]) is None+ assert args_mod.scaled_vram_budget(8.0, 0.75) == 6.0+ assert args_mod.scaled_vram_budget({"cuda0": 8.0, "cuda1": 4.0}, 0.75) == {+ "cuda0": 6.0,+ "cuda1": 3.0,+ }+ # Below the floor a smaller budget is not a working one.+ assert args_mod.scaled_vram_budget(1.2, 0.75) is None+ assert args_mod.scaled_vram_budget({"cuda0": 8.0, "cuda1": 1.2}, 0.75) is None+++def test_device_oom_text():+ assert args_mod.is_device_oom_text(_AUDIT_OOM)+ assert args_mod.is_device_oom_text(+ "ggml_vulkan: vk::Device::allocateMemory: ErrorOutOfDeviceMemory"+ )+ assert args_mod.is_device_oom_text("hipMalloc failed: out of memory")+ assert not args_mod.is_device_oom_text(+ "sd-cli exited 1. Last output:\n[E] unknown argument --foo"+ )+ assert not args_mod.is_device_oom_text(None)+++def test_a_host_allocation_failure_is_not_a_device_oom():+ # A smaller --max-vram keeps more on the host: it cannot cure exhausted RAM.+ for text in (+ "sd-server generation failed\n[E] host malloc failed: out of memory",+ "terminate called after throwing an instance of 'std::bad_alloc'",+ "[E] vk::Device::allocateMemory: ErrorOutOfHostMemory out_of_host_memory",+ "load failed: out of memory",+ ):+ assert not args_mod.is_device_oom_text(text), text+ # The graph-cut executor's own segment capacity failures are device ones.+ assert args_mod.is_device_oom_text(+ "[E] minimax_h3 segment 3/54 (minimax_h3.blocks.1) failed during workspace capacity check"+ )+ assert args_mod.is_device_oom_text("CUDA error: out of memory\n current device: 0")+++class _Rt:+ def __init__(self, free):+ self.calls = 0+ self._free = free++ def probe():+ self.calls += 1+ if isinstance(self._free, Exception):+ raise self._free+ return self._free++ self.vram_free_probe = probe+++def test_launch_flags_read_the_card_at_launch():+ rt = _Rt(int(10 * GiB))+ out = video_mod._h3_budgeted_launch_flags(rt, _COMMITTED)+ assert out[3] == "8.00" and rt.calls == 1+ # A retry cap is a ceiling, never a floor.+ assert video_mod._h3_budgeted_launch_flags(rt, _COMMITTED, cap = 5.5)[3] == "5.50"+ assert video_mod._h3_budgeted_launch_flags(rt, _COMMITTED, cap = 50.0)[3] == "8.00"+ rt = _Rt({"cuda0": int(10 * GiB), "cuda1": int(16 * GiB)})+ assert video_mod._h3_budgeted_launch_flags(rt, _COMMITTED)[3] == "cuda0=8.00,cuda1=14.00"++[email protected]("free", [None, int(2 * GiB), RuntimeError("nvidia-smi timed out")])+def test_unknown_or_tiny_reading_keeps_the_placeholder(free):+ rt = _Rt(free)+ assert video_mod._h3_budgeted_launch_flags(rt, _COMMITTED) == list(_COMMITTED)++[email protected]("free", [None, RuntimeError("nvidia-smi timed out")])+def test_an_unreadable_card_still_retries_below_the_budget_that_failed(free):+ assert video_mod._h3_budgeted_launch_flags(_Rt(free), _COMMITTED, cap = 4.5)[3] == "4.50"+++def test_a_known_small_reading_never_takes_a_larger_retry_cap():+ # 2 GiB free now: a 4.5 / 6 GiB cap from the earlier launch would exceed the card; sd.cpp's own -1 does not.+ for cap in (4.5, 6.0, {"cuda0": 6.0}):+ assert video_mod._h3_budgeted_launch_flags(_Rt(int(2 * GiB)), _COMMITTED, cap = cap) == list(+ _COMMITTED+ )+ rt = _Rt({"cuda0": int(10 * GiB), "cuda1": int(2 * GiB)})+ assert video_mod._h3_budgeted_launch_flags(+ rt, _COMMITTED, cap = {"cuda0": 6.0, "cuda1": 6.0}+ ) == list(_COMMITTED)+++def test_a_uma_pinned_weight_reserve_is_never_replaced():+ """#13786: a negative --max-vram other than the -1 placeholder is sd.cpp's reading less the GTT-pinned weights; an+ explicit free-minus-2-GiB budget in its place would hand those weights' memory back to the graph."""+ uma = ["--offload-to-cpu", "--diffusion-fa", "--max-vram", "-17.05", "--stream-layers"]+ rt = _Rt(int(22 * GiB))+ assert video_mod._h3_budgeted_launch_flags(rt, uma) == uma+ assert video_mod._h3_budgeted_launch_flags(rt, uma, cap = 6.0) == uma+ assert rt.calls == 0+ assert args_mod.with_max_vram_budget(uma, 8.0) == uma+ assert args_mod.explicit_max_vram_gib(uma) is None+ assert video_mod._h3_retry_vram_cap(uma, _AUDIT_OOM) is None+ assert args_mod.max_vram_is_placeholder("-1") and not args_mod.max_vram_is_placeholder("-17.05")+++def test_kill_switch_and_no_probe_keep_the_placeholder(monkeypatch):+ class _NoProbe:+ pass++ assert video_mod._h3_budgeted_launch_flags(_NoProbe(), _COMMITTED) == list(_COMMITTED)+ monkeypatch.setenv(args_mod.GRAPH_CUT_EXPLICIT_BUDGET_ENV, "0")+ rt = _Rt(int(10 * GiB))+ assert video_mod._h3_budgeted_launch_flags(rt, _COMMITTED) == list(_COMMITTED)+ assert rt.calls == 0+++def test_flags_without_graph_cut_are_untouched():+ rt = _Rt(int(10 * GiB))+ flags = ["--offload-to-cpu", "--diffusion-fa"]+ assert video_mod._h3_budgeted_launch_flags(rt, flags) == flags+ assert rt.calls == 0+++def test_retry_cap():+ launched = ["--offload-to-cpu", "--max-vram", "8.00"]+ assert video_mod._h3_retry_vram_cap(launched, _AUDIT_OOM) == 6.0+ assert video_mod._h3_retry_vram_cap(launched, "sd-cli exited 1: bad flag") is None+ assert (+ video_mod._h3_retry_vram_cap(list(_COMMITTED), _AUDIT_OOM) is None+ ) # sd.cpp's own reading: no retry+ assert video_mod._h3_retry_vram_cap(None, _AUDIT_OOM) is None+++def test_slot_launches_with_the_budget_but_reuses_on_the_placeholder(monkeypatch):+ started = []++ class _Srv:+ def __init__(self, binary):+ self.alive = False++ def start(+ self,+ files,+ *,+ offload = None,+ threads = None,+ env = None,+ extra_args = None,+ ):+ started.append(list(offload))+ self.alive = True++ def is_alive(self):+ return self.alive++ def stop(self):+ self.alive = False++ monkeypatch.setattr(srv, "SdCppServer", _Srv)+ monkeypatch.setattr("core.inference.sd_cpp_engine.is_managed_binary", lambda b: False)+ slot = h3.H3NativeServerSlot("/x/sd-server", _FILES, _COMMITTED)+ budgets = iter(["8.00", "7.00"])++ def transform(flags):+ out = list(flags)+ out[out.index("--max-vram") + 1] = next(budgets)+ return out++ first = slot.get(_COMMITTED, launch_transform = transform)+ # Same committed flags, a different launch-time budget: the live server is reused, not respawned.+ assert slot.get(_COMMITTED, launch_transform = transform) is first+ assert started == [+ ["--offload-to-cpu", "--diffusion-fa", "--max-vram", "8.00", "--stream-layers"]+ ]+ assert slot.launched_flags[3] == "8.00"+ assert slot.alive_signature()[2] == _COMMITTED+ slot.stop()+++class _Server:+ def __init__(self, outcomes):+ self.outcomes = outcomes+ self.alive = True++ def is_alive(self):+ return self.alive++ def vid_gen(+ self,+ payload,+ *,+ on_step = None,+ cancel_event = None,+ ):+ outcome = self.outcomes.pop(0)+ if isinstance(outcome, Exception):+ raise outcome+ return outcome+++class _Slot:+ def __init__(self, server):+ self.server = server+ self.disabled_reason = None+ self.launched_flags = None+ self.launches = []+ self.stops = []++ def get(+ self,+ flags = None,+ env = None,+ *,+ cancel_event = None,+ pre_spawn = None,+ launch_transform = None,+ ):+ if pre_spawn is not None:+ flags = list(pre_spawn())+ self.launched_flags = tuple(launch_transform(tuple(flags)))+ self.launches.append(self.launched_flags)+ return self.server++ def begin_render(self):+ pass++ def end_render(self):+ pass++ def stop(self, reason = "stopped"):+ self.stops.append(reason)++ def disable(self, reason):+ self.disabled_reason = reason++ def release(self, reason):+ return True++ def alive_signature(self):+ return None+++class _ServerRuntime:+ def __init__(self, slot, free):+ self.server_slot = slot+ self.offload_flags = _COMMITTED+ self.env = ()+ self.vram_free_probe = lambda: free+++def _params():+ return SdCppVideoGenParams(+ prompt = "p", width = 864, height = 480, num_frames = 39, fps = 24, steps = 4, cfg_scale = 1.0, seed = 1+ )+++def _server_render(slot, free, tmp_path):+ return VideoBackend._h3_native_server_render(+ None,+ _ServerRuntime(slot, free),+ _params(),+ output_path = tmp_path / "out.avi",+ on_log = lambda line: None,+ cancel = threading.Event(),+ )+++def test_server_render_retries_once_smaller_on_device_oom(tmp_path, monkeypatch):+ monkeypatch.delenv(h3.H3_NATIVE_SERVER_ENV, raising = False)+ slot = _Slot(_Server([RuntimeError(_AUDIT_OOM), b"AVI"]))+ out = _server_render(slot, int(10 * GiB), tmp_path)+ assert out.read_bytes() == b"AVI"+ budgets = [launch[launch.index("--max-vram") + 1] for launch in slot.launches]+ assert budgets == ["8.00", "6.00"]+ assert len(slot.stops) == 1 and "smaller VRAM budget" in slot.stops[0]+++def test_server_render_retries_only_once(tmp_path, monkeypatch):+ monkeypatch.delenv(h3.H3_NATIVE_SERVER_ENV, raising = False)+ slot = _Slot(_Server([RuntimeError(_AUDIT_OOM), RuntimeError(_AUDIT_OOM)]))+ with pytest.raises(RuntimeError, match = "out of memory"):+ _server_render(slot, int(10 * GiB), tmp_path)+ assert len(slot.launches) == 2+++def test_server_render_does_not_fall_back_to_sd_cli_after_the_retry_dies(tmp_path, monkeypatch):+ monkeypatch.delenv(h3.H3_NATIVE_SERVER_ENV, raising = False)+ server = _Server([RuntimeError(_AUDIT_OOM), RuntimeError(_AUDIT_OOM)])+ vid_gen = server.vid_gen++ def dies_on_retry(*args, **kwargs):+ if len(server.outcomes) == 1:+ server.alive = False+ return vid_gen(*args, **kwargs)++ server.vid_gen = dies_on_retry+ slot = _Slot(server)+ with pytest.raises(RuntimeError, match = "out of memory"):+ _server_render(slot, int(10 * GiB), tmp_path)+ assert len(slot.launches) == 2+ assert slot.disabled_reason is None+++def test_server_render_does_not_fall_back_when_the_retry_start_runs_out_of_memory(+ tmp_path, monkeypatch+):+ monkeypatch.delenv(h3.H3_NATIVE_SERVER_ENV, raising = False)+ slot = _Slot(_Server([RuntimeError(_AUDIT_OOM)]))+ get = slot.get++ def oom_on_second_start(*args, **kwargs):+ server = get(*args, **kwargs)+ if len(slot.launches) == 2:+ raise RuntimeError(_AUDIT_OOM)+ return server++ slot.get = oom_on_second_start+ with pytest.raises(RuntimeError, match = "out of memory"):+ _server_render(slot, int(10 * GiB), tmp_path)+ assert len(slot.launches) == 2+ assert slot.disabled_reason is None+++def test_server_render_does_not_restart_over_a_pending_release(tmp_path, monkeypatch):+ monkeypatch.delenv(h3.H3_NATIVE_SERVER_ENV, raising = False)+ slot = _Slot(_Server([RuntimeError(_AUDIT_OOM)]))+ slot.release_pending = "another model is loading"+ with pytest.raises(RuntimeError, match = "out of memory"):+ _server_render(slot, int(10 * GiB), tmp_path)+ assert len(slot.launches) == 1+++def test_a_server_start_that_runs_out_of_memory_retries_once_smaller_on_the_server(+ tmp_path, monkeypatch+):+ monkeypatch.delenv(h3.H3_NATIVE_SERVER_ENV, raising = False)+ slot = _Slot(_Server([b"AVI"]))+ get = slot.get++ def oom_on_first_start(*args, **kwargs):+ server = get(*args, **kwargs)+ slot.attempted_flags = slot.launched_flags+ if len(slot.launches) == 1:+ slot.launched_flags = None # a failed start never records launched flags+ raise RuntimeError(_AUDIT_OOM)+ return server++ slot.get = oom_on_first_start+ out = _server_render(slot, int(10 * GiB), tmp_path)+ assert out.read_bytes() == b"AVI"+ budgets = [launch[launch.index("--max-vram") + 1] for launch in slot.launches]+ assert budgets == ["8.00", "6.00"]+ assert slot.disabled_reason is None # the server path is kept, not given up for the session+++def test_restart_for_retry_keeps_a_release_that_landed_before_the_stop(monkeypatch):+ stopped = []++ class _Srv:+ def __init__(self, binary):+ self.alive = False++ def start(+ self,+ files,+ *,+ offload = None,+ threads = None,+ env = None,+ extra_args = None,+ ):+ self.alive = True++ def is_alive(self):+ return self.alive++ def stop(self):+ stopped.append(1)+ self.alive = False++ monkeypatch.setattr(srv, "SdCppServer", _Srv)+ monkeypatch.setattr("core.inference.sd_cpp_engine.is_managed_binary", lambda b: False)+ slot = h3.H3NativeServerSlot("/x/sd-server", _FILES, _COMMITTED)+ slot.get(_COMMITTED)+ slot.begin_render()+ assert slot.release("another model needs the memory") is True # busy: left pending+ assert slot.restart_for_retry("device out of memory") is False+ assert slot.release_pending == "another model needs the memory" and stopped == []+ assert (+ slot.end_render() == "another model needs the memory"+ ) # the release is honoured at the end+ assert stopped == [1]+ # With nothing pending the retry stops the server in the same locked step.+ slot.get(_COMMITTED)+ assert slot.restart_for_retry("device out of memory") is True and slot.release_pending is None+ # A release landing in the gap between the retry's stop and its respawn still stops the fresh server at the end.+ slot.begin_render()+ assert slot.release("another load") is True and slot.release_pending == "another load"+ slot.get(_COMMITTED)+ assert slot.end_render() == "another load" and stopped == [1, 1, 1]+ # A release left with no server to stop does not outlive the render (it would refuse the next retry).+ slot.begin_render()+ slot.release("late")+ assert slot.end_render() is None and slot.release_pending is None+++def test_h3_card_probes_read_nothing_on_rocm_without_a_context(monkeypatch):+ from utils.hardware import hardware++ monkeypatch.setattr(hardware, "get_device", lambda: hardware.DeviceType.CUDA)+ monkeypatch.setattr(hardware, "IS_ROCM", True)+ monkeypatch.setattr(+ hardware,+ "_smi_visible_utilization",+ lambda spec: pytest.fail("amd-smi rows need a torch context"),+ )+ assert video_mod._h3_card_memory_bytes("cuda", 0) == (None, None)+ assert video_mod._h3_visible_card_count("cuda") == 0+++def test_a_slot_start_records_what_it_attempted_even_when_it_fails(monkeypatch):+ class _Srv:+ def __init__(self, binary):+ pass++ def start(+ self,+ files,+ *,+ offload = None,+ threads = None,+ env = None,+ extra_args = None,+ ):+ raise RuntimeError(_AUDIT_OOM)++ def is_alive(self):+ return False++ def stop(self):+ pass++ monkeypatch.setattr(srv, "SdCppServer", _Srv)+ monkeypatch.setattr("core.inference.sd_cpp_engine.is_managed_binary", lambda b: False)+ slot = h3.H3NativeServerSlot("/x/sd-server", _FILES, _COMMITTED)+ with pytest.raises(RuntimeError):+ slot.get(_COMMITTED, launch_transform = lambda f: [*f[:3], "8.00", *f[4:]])+ assert slot.launched_flags is None and slot.attempted_flags[3] == "8.00"+++def test_server_render_does_not_retry_other_failures_or_auto_budget(tmp_path, monkeypatch):+ monkeypatch.delenv(h3.H3_NATIVE_SERVER_ENV, raising = False)+ slot = _Slot(_Server([RuntimeError("sd-server generation failed: bad prompt")]))+ with pytest.raises(RuntimeError, match = "bad prompt"):+ _server_render(slot, int(10 * GiB), tmp_path)+ assert len(slot.launches) == 1+ # Unreadable card: "-1" as before, and an OOM under it is not retried here (nothing smaller to try).+ slot = _Slot(_Server([RuntimeError(_AUDIT_OOM)]))+ with pytest.raises(RuntimeError, match = "out of memory"):+ _server_render(slot, None, tmp_path)+ assert [launch[3] for launch in slot.launches] == ["-1"]+++def test_one_shot_retries_once_smaller_on_device_oom():+ rt = _Rt(int(12 * GiB))+ seen = []++ def run(flags):+ seen.append(flags[flags.index("--max-vram") + 1])+ if len(seen) == 1:+ raise RuntimeError("sd-cli exited 1. Last output:\n" + _AUDIT_OOM)+ return "/out.avi"++ assert (+ video_mod._h3_one_shot_with_vram_retry(rt, run, _COMMITTED, threading.Event()) == "/out.avi"+ )+ assert seen == ["10.00", "7.50"]++ def bad(flags):+ raise RuntimeError("sd-cli exited 1. Last output:\n[E] unknown argument")++ with pytest.raises(RuntimeError, match = "unknown argument"):+ video_mod._h3_one_shot_with_vram_retry(rt, bad, _COMMITTED, threading.Event())+++def _load(monkeypatch, tmp_path, **kw):+ from test_video_backend import _SAGE_HELP, _load_h3_native_offload+ return _load_h3_native_offload(monkeypatch, tmp_path, help_text = _SAGE_HELP, **kw)+++def test_load_commits_the_placeholder_and_a_probe(monkeypatch, tmp_path):+ from test_video_backend import _GRAPH_CUT_HELP, _load_h3_native_offload++ reads = []+ monkeypatch.setattr(+ video_mod,+ "_h3_card_free_bytes",+ lambda device, ordinal, **kw: reads.append((device, ordinal)) or int(9 * GiB),+ )+ state, offload = _load_h3_native_offload(monkeypatch, tmp_path, help_text = _GRAPH_CUT_HELP)+ assert offload[offload.index("--max-vram") + 1] == "-1"+ probe = state.pipe.vram_free_probe+ assert probe is not None+ assert (+ video_mod._h3_budgeted_launch_flags(state.pipe, offload)[offload.index("--max-vram") + 1]+ == "7.00"+ )+ assert reads and reads[-1][0] == "cuda"+++ "torch_cc, reason",+ [+ ((10, 0), "sd.cpp BF16 cuBLAS matmuls"),+ ((8, 9), "sd.cpp BF16 cuBLAS matmuls"),+ ((7, 5), "sd.cpp exact kernels"),+ ],+)+def test_unreadable_listing_falls_back_to_torch_cc(monkeypatch, tmp_path, torch_cc, reason):+ """--list-devices unreadable (timed out / non-zero exit): nothing is cached, the verdict keeps the GPU, and the+ capability comes from torch instead of silently routing a sm80+ card to the exact kernels."""+ monkeypatch.delenv("UNSLOTH_H3_SAGE_ATTN", raising = False)+ monkeypatch.delenv("GGML_CUDA_QUANT_CUBLAS_MIN_BATCH", raising = False)+ monkeypatch.setattr(sd_cpp_backend, "_LAST_DEVICE_LISTING", {})+ monkeypatch.setattr(sd_cpp_backend, "_remember_device_listing", lambda *_a: None)+ asked = []+ monkeypatch.setattr(+ sd_cpp_backend,+ "torch_cuda_compute_capability",+ lambda ordinal: asked.append(ordinal) or torch_cc,+ )+ state, _offload = _load(monkeypatch, tmp_path, devices = "", installed_accelerator = "cuda")+ assert asked, "torch was not consulted"+ assert state.resolved["speed_mode"]["reason"] == reason+ assert (dict(state.pipe.env).get("GGML_CUDA_QUANT_CUBLAS_MIN_BATCH") is not None) == (+ torch_cc >= (8, 0)+ )+++def test_base_behaviour_without_fallback_is_exact_kernels(monkeypatch, tmp_path):+ """The defect itself: the same unreadable listing with torch giving no answer routes to the exact kernels."""+ monkeypatch.delenv("UNSLOTH_H3_SAGE_ATTN", raising = False)+ monkeypatch.delenv("GGML_CUDA_QUANT_CUBLAS_MIN_BATCH", raising = False)+ monkeypatch.setattr(sd_cpp_backend, "_LAST_DEVICE_LISTING", {})+ monkeypatch.setattr(sd_cpp_backend, "_remember_device_listing", lambda *_a: None)+ monkeypatch.setattr(sd_cpp_backend, "torch_cuda_compute_capability", lambda ordinal: None)+ state, _offload = _load(monkeypatch, tmp_path, devices = "", installed_accelerator = "cuda")+ assert state.resolved["speed_mode"]["reason"] == "sd.cpp exact kernels"+++def test_torch_is_not_consulted_when_the_listing_was_read(monkeypatch, tmp_path):+ from test_video_backend import _cuda_devices++ monkeypatch.delenv("GGML_CUDA_QUANT_CUBLAS_MIN_BATCH", raising = False)+ monkeypatch.setattr(sd_cpp_backend, "_LAST_DEVICE_LISTING", {})+ monkeypatch.setattr(+ sd_cpp_backend,+ "torch_cuda_compute_capability",+ lambda ordinal: pytest.fail("torch consulted"),+ )+ state, _ = _load(+ monkeypatch, tmp_path, devices = _cuda_devices("7.5"), installed_accelerator = "cuda"+ )+ assert state.resolved["speed_mode"]["reason"] == "sd.cpp exact kernels"+++def test_cc_fallback_rules(monkeypatch):+ monkeypatch.setattr(sd_cpp_backend, "_LAST_DEVICE_LISTING", {})+ monkeypatch.setattr(+ sd_cpp_backend,+ "torch_cuda_compute_capability",+ lambda ordinal: (9, 0) if ordinal in (0, 1) else None,+ )+ kw = dict(binary = "/x/sd-cli", native_device = "cuda", listed_accelerator = True)+ fb = video_mod._h3_cuda_cc_fallback+ assert fb((8, 6), accelerator_names = ("cuda",), device_name = "CUDA0", **kw) == (8, 6)+ assert fb(None, accelerator_names = ("cuda",), device_name = "CUDA1", **kw) == (9, 0)+ assert fb(None, accelerator_names = ("cuda",), device_name = None, **kw) == (9, 0)+ # Not a CUDA build, not a CUDA device name, a CPU target: unknown stays unknown.+ assert fb(None, accelerator_names = ("vulkan",), device_name = None, **kw) is None+ assert fb(None, accelerator_names = ("rocm",), device_name = "ROCm0", **kw) is None+ assert fb(None, accelerator_names = ("cuda",), device_name = "Vulkan0", **kw) is None+ assert (+ fb(+ None,+ binary = "/x/sd-cli",+ native_device = "cpu",+ listed_accelerator = True,+ accelerator_names = ("cuda",),+ device_name = None,+ )+ is None+ )+++def test_cc_fallback_reads_the_card_sd_cpp_runs_on_and_only_an_owned_cuda_build(monkeypatch):+ monkeypatch.setattr(sd_cpp_backend, "_LAST_DEVICE_LISTING", {})+ asked = []+ monkeypatch.setattr(+ sd_cpp_backend,+ "torch_cuda_compute_capability",+ lambda ordinal: asked.append(ordinal) or {0: (7, 5), 1: (8, 9)}.get(ordinal),+ )+ kw = dict(binary = "/x/sd-cli", native_device = "cuda", listed_accelerator = True)+ fb = video_mod._h3_cuda_cc_fallback+ # No device name means no --backend pin: sd.cpp renders on CUDA0, so that card is read (not the lowest across cards).+ assert fb(None, accelerator_names = ("cuda",), device_name = None, **kw) == (7, 5)+ assert asked == [0]+ assert fb(None, accelerator_names = ("cuda",), device_name = "CUDA1", **kw) == (8, 9)+ assert asked == [0, 1]+ # No install record (an SD_CLI_PATH build): its accelerator is unknown, so no CUDA route from torch.+ assert fb(None, accelerator_names = (None,), device_name = None, **kw) is None+ # The requested ordinal is not an input: it names a card sd.cpp only uses through a resolved pin.+ import inspect++ assert "native_ordinal" not in inspect.signature(fb).parameters+++def test_a_stalled_torch_capability_reading_is_bounded(monkeypatch):+ import time++ monkeypatch.setattr(+ sd_cpp_backend, "_torch_cuda_compute_capability", lambda ordinal: time.sleep(5) or (9, 0)+ )+ t0 = time.monotonic()+ assert sd_cpp_backend.torch_cuda_compute_capability(0, timeout_s = 0.2) is None+ assert time.monotonic() - t0 < 2.0+ monkeypatch.setattr(sd_cpp_backend, "_torch_cuda_compute_capability", lambda ordinal: (9, 0))+ assert sd_cpp_backend.torch_cuda_compute_capability(0) == (9, 0)+++def test_an_unpinned_render_on_several_cards_takes_no_scalar_budget(monkeypatch):+ monkeypatch.setattr(+ video_mod, "_h3_card_memory_bytes", lambda device, ordinal: (int(9 * GiB), int(24 * GiB))+ )+ monkeypatch.setattr(video_mod, "_h3_visible_card_count", lambda device: 2)+ assert video_mod._h3_card_free_bytes("cuda", None, single_card_only = True) is None+ monkeypatch.setattr(video_mod, "_h3_visible_card_count", lambda device: 1)+ assert video_mod._h3_card_free_bytes("cuda", None, single_card_only = True) == int(9 * GiB)+ monkeypatch.setattr(video_mod, "_h3_visible_card_count", lambda device: 2)+ assert video_mod._h3_card_free_bytes("cuda", 1) == int(9 * GiB)+++def test_torch_cc_helper_is_none_off_cuda(monkeypatch):+ import torch++ monkeypatch.setattr(torch.version, "cuda", None, raising = False)+ assert sd_cpp_backend.torch_cuda_compute_capability(0) is None+ monkeypatch.setattr(torch.version, "cuda", "13.0", raising = False)+ monkeypatch.setattr(torch.version, "hip", "7.0", raising = False)+ assert sd_cpp_backend.torch_cuda_compute_capability(0) is None+++def test_h3_card_probes_never_fall_back_to_a_torch_context(monkeypatch):+ from utils.hardware import hardware++ monkeypatch.setattr(hardware, "get_device", lambda: hardware.DeviceType.CUDA)+ monkeypatch.setattr(hardware, "_smi_visible_utilization", lambda spec: None)+ monkeypatch.setattr(hardware, "IS_ROCM", False)+ monkeypatch.setattr(hardware, "get_parent_visible_gpu_ids", lambda: [0])+ touched = []+ monkeypatch.setattr(+ hardware, "_torch_get_per_device_info", lambda idx: touched.append(idx) or []+ )+ assert video_mod._h3_visible_card_count("cuda") == 0+ assert video_mod._h3_card_memory_bytes("cuda", 0) == (None, None)+ assert touched == []diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 937d0129a67..56320d6a5e9 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -4929,8 +4929,18 @@ def _overlay_system_wide_vram(devices: list[Dict[str, Any]]) -> None:_apply_system_wide_vram(devices, _rocm_system_wide_vram_by_index(devices))-def get_visible_gpu_utilization() -> Dict[str, Any]:+def get_visible_gpu_utilization(*, no_context: bool = False) -> Dict[str, Any]:+ """``no_context``: skip torch's per-device reading (it leaves a resident driver context); devices are then empty+ when nvidia-smi cannot answer, and always on ROCm, whose amd-smi rows need that reading."""device = get_device()+ if no_context and IS_ROCM and device == DeviceType.CUDA:+ return {+ "available": False,+ "backend": _backend_label(device),+ "parent_visible_gpu_ids": [],+ "devices": [],+ "index_kind": "relative",+ }if device == DeviceType.CUDA:parent_visible_spec = _get_parent_visible_gpu_spec()@@ -5034,7 +5044,7 @@ def get_visible_gpu_utilization() -> Dict[str, Any]:"index_kind": index_kind,}- torch_devices = _torch_get_per_device_info(torch_indices)+ torch_devices = [] if no_context else _torch_get_per_device_info(torch_indices)if torch_devices:devices = []for td in torch_devices: