Skip to content

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.

Studio: reserve MiniMax-H3's pinned weights from sd.cpp's budget on integrated AMD GPUs (#13786)

oobabooga4232f63920e3
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index efa7b48aa11..f2c64f238ed 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -568,6 +568,36 @@ def sd_cpp_cuda_compute_capability(
return caps.get(int(device_name[len(head) :]))
+_VULKAN_DEVICE_UMA_RE = re.compile(r"^ggml_vulkan: (\d+) = .*?\| uma: ([01]) \|", re.MULTILINE)
+
+
+def sd_cpp_vulkan_device_is_uma(
+ binary: Optional[str],
+ device_name: Optional[str],
+ *,
+ probe: bool = True,
+) -> Optional[bool]:
+ """Whether ggml-vulkan reports ``device_name`` (``Vulkan<i>``; Vulkan0 when unpinned) as unified memory. Its free
+ memory for such a device sums every heap, the GTT the pinned weights come from included. None when unsure."""
+ if not binary:
+ return None
+ text = None
+ seen = _LAST_DEVICE_LISTING.get(binary)
+ if seen is not None and seen[0] == _binary_stat_identity(binary):
+ text = seen[1]
+ elif probe:
+ text = _sd_cpp_probe_output(binary, "--list-devices")
+ if text is None:
+ return None
+ uma = {int(m.group(1)): m.group(2) == "1" for m in _VULKAN_DEVICE_UMA_RE.finditer(text)}
+ if device_name is None:
+ return uma.get(0)
+ head = device_name.rstrip("0123456789")
+ if head.upper() != "VULKAN" or not device_name[len(head) :]:
+ return None
+ return uma.get(int(device_name[len(head) :]))
+
+
# Every namespace ggml names a device in; the narrower list above is physical-index schemes only.
_GGML_DEVICE_PREFIXES: tuple[str, ...] = ("CUDA", "ROCM", "VULKAN", "SYCL", "METAL", "OPENCL")
@@ -1734,6 +1764,12 @@ _ACCELERATOR_CAPACITY_FAILURE_MARKERS: tuple[str, ...] = (
"allocation failure",
"insufficient memory",
"not enough memory",
+ # sd.cpp's graph-cut executor when a segment's device memory cannot be made available (ggml_runner.cpp's
+ # fail_segment). Not the model manager's "cannot make enough memory available" warning: it precedes recoveries
+ # too, and renders that complete print it.
+ "failed during workspace capacity check",
+ "failed during workspace allocation",
+ "failed during allocated capacity check",
)
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 3323cf291d0..de446371902 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1417,6 +1417,7 @@ def _h3_offloaded_render_flags(
render_resident: bool,
memory_mode: Optional[str],
reuse_live_server: bool = True,
+ compute_bytes: Optional[int] = None,
) -> list[str]:
"""The flags an H3 native render runs with once Auto chose resident or offloaded. Every offloaded render is
re-fitted on live RAM, swap and GTT readings (file reads only) before a process starts, so pressure since the load
@@ -1464,6 +1465,7 @@ def _h3_offloaded_render_flags(
render_flags,
memory_mode,
hint = H3_NATIVE_RENDER_RUNNING_HINT if released == "pending" else "",
+ compute_bytes = compute_bytes,
)
@@ -1480,12 +1482,18 @@ def _h3_launch_flags(
memory_mode: Optional[str],
*,
hint: str = "",
+ compute_bytes: Optional[int] = None,
) -> list[str]:
"""The live fit for one process launch, with no server-slot calls (it also runs under the slot's lock, from
``H3NativeServerSlot.get``'s ``pre_spawn``). Auto may move the encoder; an explicit mode runs exactly its flags
- or is refused. A resident render or a runtime without fit inputs passes through."""
+ or is refused. A resident render or a runtime without fit inputs passes through. ``compute_bytes`` is the
+ render's denoiser compute buffer."""
from .sd_cpp_args import device_backend_flags
- from .video_minimax_h3 import H3NativeMemoryRefusal, h3_native_live_fit
+ from .video_minimax_h3 import (
+ H3NativeMemoryRefusal,
+ h3_native_live_fit,
+ h3_native_with_max_vram,
+ )
from .video_minimax_h3 import h3_native_fit_check_enabled
@@ -1497,13 +1505,14 @@ def _h3_launch_flags(
_h3_check_render_overhead(hint)
return list(render_flags)
mode = memory_mode or "auto"
- fit = h3_native_live_fit(inputs, mode)
+ fit = h3_native_live_fit(inputs, mode, compute_bytes)
if fit.refusal:
raise H3NativeMemoryRefusal(fit.refusal + hint)
if fit.note:
logger.info("video.h3_native_memory_fit (launch): %s", fit.note)
if mode != "auto":
- return list(render_flags)
+ # The placement is the mode's; only a UMA device's --max-vram reserve is applied.
+ return h3_native_with_max_vram(render_flags, fit.max_vram)
flags = tuple(fit.flags)
return list(flags + tuple(device_backend_flags(inputs.device_name, list(flags))))
@@ -3930,6 +3939,7 @@ class VideoBackend:
sd_cpp_graph_cut_options,
sd_cpp_listed_device,
sd_cpp_supports_sage_attn,
+ sd_cpp_vulkan_device_is_uma,
)
from .sd_cpp_engine import SdCppEngine
from .video_minimax_h3 import (
@@ -4341,6 +4351,7 @@ class VideoBackend:
from .video_minimax_h3 import (
H3_NATIVE_RENDER_RUNNING_HINT,
H3NativeFitInputs,
+ h3_native_compute_bytes,
h3_native_live_fit,
h3_native_render_flags,
h3_native_resident_bytes,
@@ -4376,8 +4387,17 @@ class VideoBackend:
te_bytes = _size(resolved[1]),
vae_bytes = _size(resolved[2]) + _size(resolved[3]),
device_name = native_device_name,
+ uma = check_gtt
+ and sd_cpp_vulkan_device_is_uma(binary, native_device_name, probe = False) is True,
+ )
+ # The smallest clip's estimate: a load is refused only when even that is not expected to fit.
+ fam_presets = [p for p in (fam.resolution_presets or ()) if len(p) == 2]
+ small_w, small_h = (
+ min(fam_presets, key = lambda p: p[0] * p[1]) if fam_presets else (864, 480)
)
- fit = h3_native_live_fit(native_fit_inputs, requested_mode)
+ small_frames = fam.min_num_frames or fam.default_num_frames or 1
+ small_compute = h3_native_compute_bytes(small_w, small_h, small_frames)
+ fit = h3_native_live_fit(native_fit_inputs, requested_mode, small_compute)
release_pending = False
if fit.refusal or fit.note:
# Free the replaced model's idle sd-server (it respawns on demand) and re-measure.
@@ -4385,7 +4405,7 @@ class VideoBackend:
"a new MiniMax-H3 load is measuring host memory"
)
if released == "stopped":
- fit = h3_native_live_fit(native_fit_inputs, requested_mode)
+ fit = h3_native_live_fit(native_fit_inputs, requested_mode, small_compute)
release_pending = released == "pending"
if fit.refusal and release_pending:
fit = dataclasses.replace(fit, refusal = fit.refusal + H3_NATIVE_RENDER_RUNNING_HINT)
@@ -4403,11 +4423,6 @@ class VideoBackend:
)
if requested_mode == "auto" and (fit.refusal or fit.note):
# Auto decides resident vs offloaded at render time; refuse only if even the smallest clip cannot fit.
- fam_presets = [p for p in (fam.resolution_presets or ()) if len(p) == 2]
- small_w, small_h = (
- min(fam_presets, key = lambda p: p[0] * p[1]) if fam_presets else (864, 480)
- )
- small_frames = fam.min_num_frames or fam.default_num_frames or 1
resident_need = h3_native_resident_bytes(
sum(_size(p) for p in resolved[:4]), small_w, small_h, small_frames
)
@@ -11087,7 +11102,7 @@ class VideoBackend:
from .sd_cpp_engine import SdCppCancelled
from .sd_cpp_server import SdCppServerUnsupported
from .video_minimax_h3 import H3NativeMemoryRefusal
- from .video_minimax_h3 import h3_native_server_enabled
+ from .video_minimax_h3 import h3_native_compute_bytes, h3_native_server_enabled
slot = getattr(runtime, "server_slot", None)
if slot is None or slot.disabled_reason is not None:
@@ -11123,7 +11138,13 @@ class VideoBackend:
render_env,
cancel_event = cancel,
pre_spawn = functools.partial(
- _h3_launch_flags, runtime, render_flags, memory_mode
+ _h3_launch_flags,
+ runtime,
+ render_flags,
+ memory_mode,
+ compute_bytes = h3_native_compute_bytes(
+ params.width, params.height, params.num_frames
+ ),
),
)
except (SdCppCancelled, H3NativeMemoryRefusal):
@@ -11188,6 +11209,7 @@ class VideoBackend:
from .sd_cpp_args import SdCppVideoGenParams
from .sd_cpp_engine import SdCppCancelled
from .video_minimax_h3 import (
+ h3_native_compute_bytes,
h3_native_render_flags,
h3_native_resident_bytes,
inspect_video,
@@ -11236,8 +11258,13 @@ class VideoBackend:
need_bytes = need,
)
# The GTT fit the load prepared for an offloaded Auto render; a resident one never needed it.
+ compute_bytes = h3_native_compute_bytes(width, height, frames)
render_flags = _h3_offloaded_render_flags(
- runtime, render_flags, render_resident = render_resident, memory_mode = state.memory_mode
+ runtime,
+ render_flags,
+ render_resident = render_resident,
+ memory_mode = state.memory_mode,
+ compute_bytes = compute_bytes,
)
if seed is None:
seed = random.SystemRandom().randrange(0, 2**53)
@@ -11370,6 +11397,7 @@ class VideoBackend:
render_resident = render_resident,
memory_mode = state.memory_mode,
reuse_live_server = False,
+ compute_bytes = compute_bytes,
)
generated = runtime.engine.generate_video(
runtime.files,
diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.py
index 5786faa39c2..2177af9f46b 100644
--- a/studio/backend/core/inference/video_minimax_h3.py
+++ b/studio/backend/core/inference/video_minimax_h3.py
@@ -1338,12 +1338,17 @@ H3_NATIVE_RESIDENT_MARGIN_BYTES = 2 * 1024**3
_H3_STREAM_ONLY_FLAGS = ("--offload-to-cpu", "--stream-layers")
-def h3_native_resident_bytes(file_bytes: int, width: int, height: int, frames: int) -> int:
+def h3_native_compute_bytes(width: int, height: int, frames: int) -> int:
volume = max(1, int(width)) * max(1, int(height)) * max(1, int(frames))
- compute = math.ceil(
- H3_NATIVE_DIT_COMPUTE_BYTES_H1 * max(1.0, volume / H3_NATIVE_H1_PIXEL_VOLUME)
+ return math.ceil(H3_NATIVE_DIT_COMPUTE_BYTES_H1 * max(1.0, volume / H3_NATIVE_H1_PIXEL_VOLUME))
+
+
+def h3_native_resident_bytes(file_bytes: int, width: int, height: int, frames: int) -> int:
+ return (
+ int(file_bytes)
+ + h3_native_compute_bytes(width, height, frames)
+ + H3_NATIVE_RESIDENT_MARGIN_BYTES
)
- return int(file_bytes) + compute + H3_NATIVE_RESIDENT_MARGIN_BYTES
def h3_native_render_flags(
@@ -1448,6 +1453,29 @@ def amdgpu_gtt_reading(
return max(pool - used_all, 0), known
+def amdgpu_vram_free_bytes(
+ pci_slot: Optional[str] = None, sysfs_root: str = "/sys"
+) -> Optional[int]:
+ """Free VRAM of the amdgpu card at ``pci_slot``, or of the only amdgpu card when no slot is given. None when no
+ such single card reports both readings."""
+ want = pci_slot.lower() if pci_slot else None
+ found: list[int] = []
+ for total_path in Path(sysfs_root, "class", "drm").glob("card*/device/mem_info_vram_total"):
+ device = total_path.parent
+ if _sysfs_int(device / "vendor") != 0x1002:
+ continue
+ if want is not None:
+ slot = _sysfs_pci_slot(device)
+ if not (slot == want or (slot or "").startswith(want + ".")):
+ continue
+ total = _sysfs_int(total_path)
+ used = _sysfs_int(device / "mem_info_vram_used")
+ if total is None or used is None:
+ return None
+ found.append(max(total - used, 0))
+ return found[0] if len(found) == 1 else None
+
+
def amdgpu_gtt_free_bytes(
pci_slot: Optional[str] = None, sysfs_root: str = "/sys"
) -> Optional[int]:
@@ -1491,6 +1519,20 @@ class H3NativeFit:
note: Optional[str] = None
# A user-facing reason to refuse the load, or None.
refusal: Optional[str] = None
+ # The --max-vram value a UMA device needs (its budget less the pinned weights), or None to keep the committed one.
+ max_vram: Optional[str] = None
+
+
+def h3_native_with_max_vram(
+ flags: "tuple[str, ...] | list[str]", value: Optional[str]
+) -> list[str]:
+ """``flags`` with the value after ``--max-vram`` replaced by ``value`` (unchanged when None or absent)."""
+ out = list(flags)
+ if value is not None:
+ for i in range(len(out) - 1):
+ if out[i] == "--max-vram":
+ out[i + 1] = value
+ return out
def _gib(value: int) -> str:
@@ -1509,10 +1551,15 @@ def h3_native_memory_fit(
host_ram_bytes: Optional[int],
host_swap_bytes: int = 0,
pinned_used_unknown: bool = False,
+ device_spill_bytes: int = 0,
+ reserve_pinned: bool = False,
env: Optional[dict] = None,
) -> H3NativeFit:
"""Fit offloaded sd-cli flags to the host: pinned weights must fit RAM alone (swap covers only CPU-run modules)
- and ``pinned_free_bytes`` (free GTT, None skips). ``auto`` may move the text encoder to the CPU; else refuse."""
+ and ``pinned_free_bytes`` (free GTT, None skips). ``device_spill_bytes`` is the part of the render's device memory
+ that VRAM cannot hold, which a Vulkan build takes from GTT too. ``reserve_pinned`` (a UMA device, whose free memory
+ sd.cpp reads before it pins anything) sets ``--max-vram`` to reserve the pinned weights. ``auto`` may move the text
+ encoder to the CPU; else refuse."""
flags = tuple(flags)
if not h3_native_fit_check_enabled(env):
return H3NativeFit(flags)
@@ -1526,16 +1573,24 @@ def h3_native_memory_fit(
swap = max(int(host_swap_bytes or 0), 0)
vulkan_gtt = (accelerator or "").strip().lower() == "vulkan" and pinned_free_bytes is not None
budget = int(pinned_free_bytes) - H3_NATIVE_PINNED_MARGIN_BYTES if vulkan_gtt else None
+ spill = max(int(device_spill_bytes or 0), 0) if vulkan_gtt else 0
+ activations = (
+ f" That includes about {_gib(spill)} of activations, which this GPU keeps in the same memory as the "
+ f"weights; they grow with resolution and length."
+ if spill
+ else ""
+ )
+ mapped = "weights and activations" if spill else "weights"
def pinned(te_on_cpu: bool) -> int:
- return dit_bytes + (0 if te_on_cpu else te_bytes) + (0 if vae_on_cpu else vae_bytes)
+ return spill + dit_bytes + (0 if te_on_cpu else te_bytes) + (0 if vae_on_cpu else vae_bytes)
def host_problem(te_on_cpu: bool) -> Optional[str]:
if host_ram_bytes is None:
return None
if pinned(te_on_cpu) + overhead > host_ram_bytes:
return "pinned"
- if total + overhead > host_ram_bytes + swap:
+ if total + spill + overhead > host_ram_bytes + swap:
return "total"
return None
@@ -1548,8 +1603,21 @@ def h3_native_memory_fit(
def ok(te_on_cpu: bool) -> bool:
return host_problem(te_on_cpu) is None and gtt_ok(te_on_cpu)
+ def admit(
+ fitted: tuple[str, ...],
+ te_on_cpu: bool,
+ note: Optional[str] = None,
+ ) -> H3NativeFit:
+ # Only where GTT was read: without sysfs (Windows) nothing measured the pool the reserve is taken from.
+ if not (reserve_pinned and vulkan_gtt and "--max-vram" in fitted):
+ return H3NativeFit(fitted, note = note)
+ # A negative --max-vram reserves that much of the free memory sd.cpp reads at startup.
+ reserve = pinned(te_on_cpu) - spill + H3_NATIVE_PINNED_MARGIN_BYTES
+ value = f"-{reserve / 1024**3:.2f}"
+ return H3NativeFit(tuple(h3_native_with_max_vram(fitted, value)), note = note, max_vram = value)
+
if ok(te_given):
- return H3NativeFit(flags)
+ return admit(flags, te_given)
ram = _gib(int(host_ram_bytes)) if host_ram_bytes is not None else "unknown"
limit = _gib(int(pinned_free_bytes)) if vulkan_gtt else None
if (
@@ -1576,9 +1644,9 @@ def h3_native_memory_fit(
)
refusal = (
f"MiniMax-H3 GGUF cannot run in this memory mode on the Vulkan build: it maps "
- f"{_gib(pinned(False))} of weights into GPU-accessible system memory (GTT), and {limit} of it is "
+ f"{_gib(pinned(False))} of {mapped} into GPU-accessible system memory (GTT), and {limit} of it is "
f"free. Set Memory mode to Auto or Low VRAM, which runs the text encoder on the CPU "
- f"({_gib(pinned(True))})."
+ f"({_gib(pinned(True))}).{activations}"
)
else:
note = (
@@ -1587,29 +1655,29 @@ def h3_native_memory_fit(
)
refusal = (
f"MiniMax-H3 GGUF cannot run in this memory mode: it locks {_gib(pinned(False) + overhead)} of "
- f"weights in system RAM, which cannot be swapped, and {ram} of RAM is available. Set Memory mode "
+ f"{mapped} in system RAM, which cannot be swapped, and {ram} of RAM is available. Set Memory mode "
f"to Auto or Low VRAM, which runs the text encoder on the CPU ({_gib(pinned(True) + overhead)} "
f"locked)."
)
if mode == "auto":
- return H3NativeFit(flags + ("--clip-on-cpu",), note = note)
+ return admit(flags + ("--clip-on-cpu",), True, note)
return H3NativeFit(flags, refusal = refusal)
q2_dit, q2_te = H3_NATIVE_Q2_PAIR_BYTES
- q2_pinned = q2_dit + (0 if vae_on_cpu else vae_bytes)
- q2_total = q2_dit + q2_te + vae_bytes + overhead
+ q2_pinned = spill + q2_dit + (0 if vae_on_cpu else vae_bytes)
+ q2_total = spill + q2_dit + q2_te + vae_bytes + overhead
problem = host_problem(True)
if problem == "total":
smaller = (
f" The Q2_K denoiser (with its Q2_K_M encoder) needs about {_gib(q2_total)}."
- if q2_total < total + overhead
+ if q2_total < total + spill + overhead
else ""
)
return H3NativeFit(
flags,
refusal = (
f"MiniMax-H3 GGUF keeps its denoiser, text encoder and VAEs in system RAM while it renders: about "
- f"{_gib(total + overhead)} for this quant, and {ram} of RAM plus {_gib(swap)} of swap is "
- f"available. Close other applications or load a smaller quant.{smaller}"
+ f"{_gib(total + spill + overhead)} for this quant, and {ram} of RAM plus {_gib(swap)} of swap is "
+ f"available. Close other applications or load a smaller quant.{smaller}{activations}"
),
)
if problem == "pinned":
@@ -1621,9 +1689,9 @@ def h3_native_memory_fit(
return H3NativeFit(
flags,
refusal = (
- f"MiniMax-H3 GGUF locks the weights of its GPU-run parts in system RAM, which cannot be swapped: "
+ f"MiniMax-H3 GGUF locks the {mapped} of its GPU-run parts in system RAM, which cannot be swapped: "
f"about {_gib(pinned(True) + overhead)} even with the text encoder on the CPU, and {ram} of RAM "
- f"is available. Close other applications or load a smaller quant.{smaller}"
+ f"is available. Close other applications or load a smaller quant.{smaller}{activations}"
),
)
smaller = (
@@ -1635,8 +1703,9 @@ def h3_native_memory_fit(
flags,
refusal = (
f"MiniMax-H3 GGUF does not fit this system on the Vulkan build: even with the text encoder on the CPU it "
- f"maps {_gib(pinned(True))} of weights into GPU-accessible system memory (GTT), and {limit} of it is free "
+ f"maps {_gib(pinned(True))} of {mapped} into GPU-accessible system memory (GTT), and {limit} of it is free "
f"(the pool is half of system RAM by default; raise it with the ttm.pages_limit kernel parameter).{smaller}"
+ f"{activations}"
),
)
@@ -1654,6 +1723,8 @@ class H3NativeFitInputs:
te_bytes: int
vae_bytes: int
device_name: Optional[str]
+ # ggml-vulkan's "uma: 1": device memory and the pinned weights come from one pool.
+ uma: bool = False
def h3_native_host_budgets() -> "tuple[Optional[int], int]":
@@ -1684,8 +1755,13 @@ def h3_native_host_budgets() -> "tuple[Optional[int], int]":
return ram, swap
-def h3_native_live_fit(inputs: H3NativeFitInputs, memory_mode: Optional[str]) -> H3NativeFit:
- """``h3_native_memory_fit`` on live RAM, swap and GTT readings: /proc, cgroup and sysfs files only."""
+def h3_native_live_fit(
+ inputs: H3NativeFitInputs,
+ memory_mode: Optional[str],
+ compute_bytes: Optional[int] = None,
+) -> H3NativeFit:
+ """``h3_native_memory_fit`` on live RAM, swap, GTT and VRAM readings: /proc, cgroup and sysfs files only.
+ ``compute_bytes`` is the render's denoiser compute buffer; None leaves activations out."""
ram, swap = h3_native_host_budgets()
gtt_free, gtt_known = (
amdgpu_gtt_reading(inputs.gtt_pci_slot) if inputs.check_gtt else (None, True)
@@ -1693,6 +1769,13 @@ def h3_native_live_fit(inputs: H3NativeFitInputs, memory_mode: Optional[str]) ->
if inputs.check_gtt and gtt_free is None and inputs.gtt_pci_slot:
# The device is AMD but its slot matched no amdgpu card: read the tightest card rather than skip the check.
gtt_free, gtt_known = amdgpu_gtt_reading(None)
+ spill = 0
+ if inputs.check_gtt and inputs.uma and compute_bytes:
+ # What the carve-out cannot hold of the compute buffer comes from GTT. A segment's weights come on top, but
+ # sd.cpp's own capacity check reports that remainder, so only the compute buffer is charged here.
+ # An unreadable or ambiguous carve-out (several cards, no slot) holds none of it, like the tightest GTT.
+ vram_free = amdgpu_vram_free_bytes(inputs.gtt_pci_slot) or 0
+ spill = max(int(compute_bytes) - vram_free, 0)
return h3_native_memory_fit(
inputs.base_flags,
accelerator = inputs.accelerator,
@@ -1704,6 +1787,8 @@ def h3_native_live_fit(inputs: H3NativeFitInputs, memory_mode: Optional[str]) ->
pinned_used_unknown = not gtt_known,
host_ram_bytes = ram,
host_swap_bytes = swap,
+ device_spill_bytes = spill,
+ reserve_pinned = inputs.check_gtt and inputs.uma,
)
diff --git a/studio/backend/tests/test_h3_native_memory_fit.py b/studio/backend/tests/test_h3_native_memory_fit.py
index b60d73d2d6b..fefbbb26124 100644
--- a/studio/backend/tests/test_h3_native_memory_fit.py
+++ b/studio/backend/tests/test_h3_native_memory_fit.py
@@ -13,6 +13,8 @@ from core.inference.video_minimax_h3 import (
H3_NATIVE_FIT_ENV,
H3NativeMemoryRefusal,
amdgpu_gtt_free_bytes,
+ amdgpu_vram_free_bytes,
+ h3_native_compute_bytes,
h3_native_memory_fit,
h3_native_offloaded_render_flags,
vulkan_device_is_amd,
@@ -45,6 +47,8 @@ def _fit(
sizes = Q4,
env = None,
swap = 0,
+ spill = 0,
+ uma = False,
):
return h3_native_memory_fit(
flags,
@@ -53,6 +57,8 @@ def _fit(
pinned_free_bytes = gtt,
host_ram_bytes = host,
host_swap_bytes = swap,
+ device_spill_bytes = spill,
+ reserve_pinned = uma,
env = env or {},
**sizes,
)
@@ -142,6 +148,59 @@ def test_the_16gb_card_48gb_host_decision_is_unchanged():
assert fit.flags == AUTO + ("--clip-on-cpu",) and "GTT" in fit.note
+def test_a_uma_card_reserves_its_pinned_weights_from_the_device_budget():
+ """gfx1151 with a 0.5 GiB carve-out and 22.5 GiB of GTT free: sd.cpp reads that free memory at startup, before it
+ pins the denoiser and VAEs in the same pool, so --max-vram -1 planned one segment and the 864x480x124 render
+ failed its capacity check. Reserving the pinned set leaves the budget the compute buffer really has."""
+ spill = h3_native_compute_bytes(864, 480, 124) - (GIB // 2)
+ fit = _fit(AUTO, "auto", gtt = int(22.5 * GIB), spill = spill, host = 100 * GIB, uma = True)
+ assert fit.refusal is None
+ pinned = Q4["dit_bytes"] + Q4["vae_bytes"] + GIB
+ assert fit.max_vram == f"-{pinned / GIB:.2f}"
+ assert fit.flags == (
+ "--offload-to-cpu",
+ "--diffusion-fa",
+ "--max-vram",
+ fit.max_vram,
+ "--clip-on-cpu",
+ )
+ assert fit.max_vram == "-17.05" # measured: sd.cpp budgeted 5.73 GiB and rendered 864x480x124
+ # Measured with the same reserve: 20 GiB free leaves no room for the compute buffer, 30 GiB renders 1344x768x124.
+ assert _fit(AUTO, "auto", gtt = 20 * GIB, spill = spill, host = 100 * GIB, uma = True).refusal
+ spill = h3_native_compute_bytes(1344, 768, 124) - (GIB // 2)
+ fit = _fit(AUTO, "auto", gtt = int(22.5 * GIB), spill = spill, host = 100 * GIB, uma = True)
+ assert "weights and activations into GPU-accessible system memory (GTT)" in fit.refusal
+ assert _fit(AUTO, "auto", gtt = 30 * GIB, spill = spill, host = 100 * GIB, uma = True).refusal is None
+
+
+def test_an_explicit_mode_on_a_uma_card_keeps_its_placement_and_gets_the_reserve():
+ fit = _fit(LOW_VRAM, "low_vram", gtt = 30 * GIB, host = 100 * GIB, uma = True)
+ assert fit.refusal is None and fit.max_vram is not None
+ assert [f for f in fit.flags if f != fit.max_vram] == [f for f in LOW_VRAM if f != "-1"]
+
+
+def test_a_uma_card_without_a_gtt_reading_keeps_max_vram_minus_one():
+ """Windows has no amdgpu sysfs, so no GTT reading: the reserve stays off and the committed -1 is kept."""
+ fit = _fit(AUTO, "auto", gtt = None, host = 100 * GIB, uma = True)
+ assert fit.refusal is None and fit.max_vram is None and fit.flags == AUTO
+
+
+def test_a_discrete_card_keeps_max_vram_minus_one():
+ fit = _fit(AUTO, "auto")
+ assert fit.max_vram is None and fit.flags[:4] == AUTO
+
+
+def test_the_compute_estimate_covers_the_measured_buffers():
+ """sd-cli's minimax_h3 compute buffer on gfx1151: 5175.60 MB at 864x480x124, 10595.71 MB at 1344x768x124."""
+ assert 5175.60 * 2**20 <= h3_native_compute_bytes(864, 480, 124) <= 6 * GIB
+ assert 10595.71 * 2**20 <= h3_native_compute_bytes(1344, 768, 124) <= 11 * GIB
+
+
+def test_a_spill_only_binds_a_vulkan_gtt_pool():
+ fit = _fit(AUTO, "auto", accelerator = "rocm", spill = 64 * GIB)
+ assert fit.refusal is None and fit.flags == AUTO
+
+
def test_the_kill_switch_restores_the_old_flags():
fit = _fit(AUTO, "auto", host = 1 * GIB, env = {H3_NATIVE_FIT_ENV: "0"})
assert fit.flags == AUTO and fit.refusal is None
@@ -155,6 +214,7 @@ def _card(
total,
used = None,
vendor = "0x1002",
+ vram = None,
):
dev = root / "class" / "drm" / card / "device"
dev.mkdir(parents = True)
@@ -163,6 +223,9 @@ def _card(
(dev / "mem_info_gtt_total").write_text(f"{total}\n", encoding = "utf-8")
if used is not None:
(dev / "mem_info_gtt_used").write_text(f"{used}\n", encoding = "utf-8")
+ if vram is not None:
+ (dev / "mem_info_vram_total").write_text(f"{vram[0]}\n", encoding = "utf-8")
+ (dev / "mem_info_vram_used").write_text(f"{vram[1]}\n", encoding = "utf-8")
def test_the_gtt_reading_subtracts_what_is_already_used(tmp_path):
@@ -194,6 +257,17 @@ def test_gtt_used_on_another_amd_card_shrinks_the_selected_cards_pool(tmp_path):
assert amdgpu_gtt_free_bytes("0000:03:00", sysfs_root = str(tmp_path)) == 22 * GIB
+def test_the_vram_reading_takes_the_selected_card_or_the_only_one(tmp_path):
+ _card(tmp_path, "card0", "0000:03:00.0", total = 24 * GIB, vram = (16 * GIB, 1 * GIB))
+ assert amdgpu_vram_free_bytes(sysfs_root = str(tmp_path)) == 15 * GIB
+ _card(tmp_path, "card1", "0000:c5:00.0", total = 24 * GIB, vram = (GIB // 2, GIB // 4))
+ assert amdgpu_vram_free_bytes("0000:c5:00", sysfs_root = str(tmp_path)) == GIB // 4
+ assert amdgpu_vram_free_bytes("0000:03:00.0", sysfs_root = str(tmp_path)) == 15 * GIB
+ # Two cards and no selection: which one sd.cpp renders on is unknown.
+ assert amdgpu_vram_free_bytes(sysfs_root = str(tmp_path)) is None
+ assert amdgpu_vram_free_bytes("0000:81:00", sysfs_root = str(tmp_path)) is None
+
+
def test_a_non_amd_drm_card_is_never_read(tmp_path):
_card(tmp_path, "card0", "0000:00:02.0", total = 8 * GIB, vendor = "0x8086")
assert amdgpu_gtt_free_bytes(sysfs_root = str(tmp_path)) is None
@@ -332,6 +406,52 @@ def test_the_radv_failure_reads_as_memory_with_the_settings_that_help():
assert "Low VRAM" in detail and "864x480" in detail and "quant" in detail
+def test_sd_cpps_segment_capacity_failure_reads_as_memory():
+ """sd.cpp's graph-cut executor reports a device it cannot fit this way, without any generic OOM wording."""
+ tail = (
+ "sd-cli exited 1. Last output:\n"
+ "[W] model manager cannot make enough memory available on Vulkan0: need 5687.60 MB device / 5175.60 MB "
+ "budget, available 1356.88 MB device / 11346.88 MB budget --- model_manager.cpp:1944\n"
+ "[E] minimax_h3 segment 1/1 (graph) failed during workspace capacity check --- ggml_runner.cpp:898\n"
+ "[E] generate failed --- main.cpp:939\n"
+ )
+ detail = video_failure_detail(RuntimeError(tail))
+ assert "ran out of GPU or system memory" in detail and "864x480" in detail
+ assert not sd_cpp_backend.output_shows_accelerator_failure(tail)
+ assert sd_cpp_backend.output_shows_capacity_failure(
+ "[E] minimax_h3 segment 2/9 (graph) failed during workspace capacity check"
+ )
+ assert sd_cpp_backend.output_shows_capacity_failure(
+ "[E] minimax_h3 segment 1/4 (graph) failed during allocated capacity check"
+ )
+
+
+# sd.cpp's model manager logs this when one eviction pass falls short, then recovers: renders that complete print it
+# (gfx1151, 864x480x124 with the pinned reserve: rc 0, a full video, two of these lines in its log).
+_RECOVERED_CAPACITY_WARNING = (
+ "[W] model manager cannot make enough memory available on Vulkan0: need 1038.05 MB device / 5701.21 MB "
+ "budget, available 17290.44 MB device / 5690.66 MB budget --- model_manager.cpp:1944\n"
+)
+
+
+def test_a_recovered_capacity_warning_is_not_a_capacity_failure():
+ """Only the failing segment's [E] line is a capacity failure. Read as one, the warning would hide what really
+ stopped the render: the build-level failure below must still be recorded, and an unrelated crash must not be
+ explained as memory."""
+ assert not sd_cpp_backend.output_shows_capacity_failure(_RECOVERED_CAPACITY_WARNING)
+ build_failure = (
+ "sd-cli exited 1. Last output:\n"
+ + _RECOVERED_CAPACITY_WARNING
+ + "ggml_cuda_compute_forward: error: invalid device function\n"
+ )
+ assert sd_cpp_backend.output_shows_accelerator_failure(build_failure)
+ assert sd_cpp_backend.output_shows_decisive_accelerator_failure(build_failure)
+ crash = (
+ "sd-cli exited -11. Last output:\n" + _RECOVERED_CAPACITY_WARNING + "Segmentation fault\n"
+ )
+ assert "renderer stopped unexpectedly" in video_failure_detail(RuntimeError(crash))
+
+
def test_a_bare_device_loss_is_explained_as_likely_memory():
detail = video_failure_detail(
RuntimeError("sd-cli exited 1. Last output:\nggml_vulkan: device lost")
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index 7660b2ccfd5..e4a7c9e85b8 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -1348,6 +1348,24 @@ def test_graph_cut_options_support_legacy_and_current_builds_and_fail_closed(mon
assert bk.sd_cpp_graph_cut_options(None) == frozenset()
+def test_vulkan_uma_reads_ggml_vulkans_own_device_line(monkeypatch):
+ listing = (
+ "ggml_vulkan: Found 2 Vulkan devices:\n"
+ "ggml_vulkan: 0 = AMD Radeon RX 7900 XTX (RADV NAVI31) (radv) | uma: 0 | fp16: 1 | bf16: 0 |\n"
+ "ggml_vulkan: 1 = AMD Radeon Graphics (RADV RAPHAEL_MENDOCINO) (radv) | uma: 1 | fp16: 1 | bf16: 0 |\n"
+ "Vulkan0\tAMD Radeon RX 7900 XTX (RADV NAVI31)\nVulkan1\tAMD Radeon Graphics\nCPU\tAMD Ryzen 9 9900X\n"
+ )
+ monkeypatch.setattr(bk, "_LAST_DEVICE_LISTING", {})
+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: listing)
+ assert bk.sd_cpp_vulkan_device_is_uma("/existing/sd-cli", None) is False
+ assert bk.sd_cpp_vulkan_device_is_uma("/existing/sd-cli", "Vulkan1") is True
+ assert bk.sd_cpp_vulkan_device_is_uma("/existing/sd-cli", "Vulkan2") is None
+ assert bk.sd_cpp_vulkan_device_is_uma("/existing/sd-cli", "ROCm0") is None
+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: "Vulkan0\tAMD Radeon\n")
+ assert bk.sd_cpp_vulkan_device_is_uma("/existing/sd-cli", None) is None
+ assert bk.sd_cpp_vulkan_device_is_uma(None, None) is None
+
+
def test_device_name_for_ordinal_reads_the_ggml_device_list(monkeypatch):
monkeypatch.setattr(
bk,
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index b7c311bb9e3..59c85db8efe 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -4285,6 +4285,11 @@ def test_h3_native_drops_stream_layers_without_cpu_offload(monkeypatch, tmp_path
_AMD_VULKAN = "Vulkan0\tAMD Radeon RX 7800 XT (RADV NAVI32)\n"
+# ggml-vulkan's init line rides along on stderr; "uma: 1" is an integrated GPU.
+_AMD_UMA_VULKAN = (
+ "ggml_vulkan: 0 = AMD Radeon Graphics (RADV GFX1151) (radv) | uma: 1 | fp16: 1 | bf16: 0 |\n"
+ "Vulkan0\tAMD Radeon Graphics (RADV GFX1151)\n"
+)
def _tiny_gtt(
@@ -4302,6 +4307,13 @@ def _tiny_gtt(
limit = video_minimax_h3.H3_NATIVE_PINNED_MARGIN_BYTES + (4 if encoder_fits else 3)
monkeypatch.setattr(video_minimax_h3, "amdgpu_gtt_reading", lambda *a, **k: (limit, True))
monkeypatch.setattr(video_mod, "_h3_card_free_bytes", lambda *a, **k: free_vram)
+ _discrete_vram(monkeypatch)
+
+
+def _discrete_vram(monkeypatch, free = 1 << 50):
+ """The selected card's sysfs free VRAM; the default holds any render's activations, so nothing spills to GTT."""
+ from core.inference import video_minimax_h3
+ monkeypatch.setattr(video_minimax_h3, "amdgpu_vram_free_bytes", lambda *a, **k: free)
def test_h3_native_auto_prepares_the_encoder_on_the_cpu_for_an_offloaded_render(
@@ -4368,6 +4380,7 @@ def _no_gtt_room(monkeypatch, free_vram):
monkeypatch.setattr(video_minimax_h3, "amdgpu_gtt_reading", lambda *a, **k: (0, True))
monkeypatch.setattr(video_mod, "_h3_card_free_bytes", lambda *a, **k: free_vram)
+ _discrete_vram(monkeypatch)
def test_h3_native_auto_refuses_at_load_only_when_no_render_could_go_resident(
@@ -4397,6 +4410,32 @@ def test_h3_native_auto_defers_the_gtt_refusal_when_a_resident_render_fits(monke
assert "GTT" in state.pipe.offload_refusal
+def test_h3_native_refuses_a_uma_card_whose_gtt_cannot_hold_the_smallest_clips_activations(
+ monkeypatch, tmp_path
+):
+ """A UMA card (small carve-out) serves the denoiser's compute buffer from GTT too. Measured on a gfx1151 with the
+ pool held to 22.5 GiB free: the weights fit, every default-size render failed in sd.cpp's capacity check."""
+ _tiny_gtt(monkeypatch, encoder_fits = True)
+ _discrete_vram(monkeypatch, free = 512 << 20)
+ with pytest.raises(RuntimeError, match = "activations"):
+ _load_h3_native_offload(
+ monkeypatch,
+ tmp_path,
+ help_text = _GRAPH_CUT_HELP,
+ devices = _AMD_UMA_VULKAN,
+ installed_accelerator = "vulkan",
+ )
+ # A discrete card's VRAM is not GTT: the same reading leaves its load alone.
+ state, offload = _load_h3_native_offload(
+ monkeypatch,
+ tmp_path,
+ help_text = _GRAPH_CUT_HELP,
+ devices = _AMD_VULKAN,
+ installed_accelerator = "vulkan",
+ )
+ assert state.pipe.offload_refusal is None and state.pipe.fit_inputs.uma is False
+
+
def test_h3_native_refuses_balanced_on_an_overflowing_vulkan_gtt_pool(monkeypatch, tmp_path):
_tiny_gtt(monkeypatch, encoder_fits = False)
with pytest.raises(RuntimeError, match = "Low VRAM"):
@@ -4477,6 +4516,7 @@ def test_h3_native_replacement_frees_the_outgoing_idle_server_before_refusing(
lambda *a, **k: (roomy if slot.released else 0, True),
)
monkeypatch.setattr(video_mod, "_h3_card_free_bytes", lambda *a, **k: 1)
+ _discrete_vram(monkeypatch)
state, offload = _load_h3_native_offload(
monkeypatch,
tmp_path,
@@ -4506,6 +4546,7 @@ def test_h3_native_a_busy_outgoing_server_is_not_counted_as_freed(monkeypatch, t
monkeypatch.setattr(video_minimax_h3, "amdgpu_gtt_reading", gtt)
monkeypatch.setattr(video_mod, "_h3_card_free_bytes", lambda *a, **k: 1)
+ _discrete_vram(monkeypatch)
with pytest.raises(RuntimeError, match = "still running"):
_load_h3_native_offload(
monkeypatch,
@@ -4523,6 +4564,7 @@ def _render_runtime(
base = ("--offload-to-cpu", "--diffusion-fa"),
slot = None,
snapshot_refusal = None,
+ uma = False,
):
from core.inference.video_minimax_h3 import H3NativeFitInputs
inputs = H3NativeFitInputs(
@@ -4534,6 +4576,7 @@ def _render_runtime(
te_bytes = 1,
vae_bytes = 2,
device_name = "Vulkan0",
+ uma = uma,
)
return types.SimpleNamespace(
fit_inputs = inputs,
@@ -4582,6 +4625,78 @@ def test_an_offloaded_auto_render_lifts_a_refusal_once_memory_is_free(monkeypatc
assert flags[-2:] == ["--backend", "diffusion=Vulkan0,te=cpu,vae=Vulkan0"]
+def test_an_offloaded_render_charges_activations_vram_cannot_hold_to_gtt(monkeypatch):
+ from core.inference import video_minimax_h3
+ from core.inference.video import _h3_offloaded_render_flags
+ from core.inference.video_minimax_h3 import H3NativeMemoryRefusal, h3_native_compute_bytes
+
+ compute = h3_native_compute_bytes(864, 480, 124)
+ # Room for the weights and this clip's activations beside them, nothing more.
+ _live_gtt(
+ monkeypatch,
+ video_minimax_h3.H3_NATIVE_PINNED_MARGIN_BYTES + 4 + compute,
+ )
+ _discrete_vram(monkeypatch, free = 0)
+
+ def render(compute_bytes, uma = True):
+ return _h3_offloaded_render_flags(
+ _render_runtime(uma = uma),
+ ["--offload-to-cpu", "--diffusion-fa"],
+ render_resident = False,
+ memory_mode = "auto",
+ reuse_live_server = False,
+ compute_bytes = compute_bytes,
+ )
+
+ assert "--clip-on-cpu" not in render(compute)
+ with pytest.raises(H3NativeMemoryRefusal, match = "activations"):
+ render(h3_native_compute_bytes(1344, 768, 124))
+ # A discrete card's compute buffer is in VRAM, whatever sysfs says is free there.
+ assert "--clip-on-cpu" not in render(h3_native_compute_bytes(1344, 768, 124), uma = False)
+ # A UMA card whose carve-out holds the activations keeps them out of GTT.
+ _discrete_vram(monkeypatch, free = 16 << 30)
+ assert "--clip-on-cpu" not in render(h3_native_compute_bytes(1344, 768, 124))
+ # Several cards and no slot: the carve-out cannot be read, so the activations count against GTT.
+ _discrete_vram(monkeypatch, free = None)
+ with pytest.raises(H3NativeMemoryRefusal, match = "activations"):
+ render(h3_native_compute_bytes(1344, 768, 124))
+
+
+def test_an_explicit_mode_on_a_uma_card_launches_with_the_pinned_reserve(monkeypatch):
+ """Low VRAM keeps its placement; the --max-vram reserve only corrects the budget sd.cpp reads at startup."""
+ from core.inference import video_minimax_h3
+ from core.inference.video import _h3_offloaded_render_flags
+
+ _live_gtt(monkeypatch, 1 << 50)
+ _discrete_vram(monkeypatch, free = 0)
+ base = ("--offload-to-cpu", "--clip-on-cpu", "--diffusion-fa", "--max-vram", "-1")
+ pinned = (
+ 1 + 2 + video_minimax_h3.H3_NATIVE_PINNED_MARGIN_BYTES
+ ) # denoiser + VAEs, the encoder on the CPU
+ flags = _h3_offloaded_render_flags(
+ _render_runtime(base = base, uma = True),
+ list(base),
+ render_resident = False,
+ memory_mode = "low_vram",
+ compute_bytes = 1,
+ )
+ assert flags == [
+ "--offload-to-cpu",
+ "--clip-on-cpu",
+ "--diffusion-fa",
+ "--max-vram",
+ f"-{pinned / 1024**3:.2f}",
+ ]
+ discrete = _h3_offloaded_render_flags(
+ _render_runtime(base = base),
+ list(base),
+ render_resident = False,
+ memory_mode = "low_vram",
+ compute_bytes = 1,
+ )
+ assert discrete == list(base)
+
+
def test_a_live_offloaded_server_keeps_its_flags_without_a_reading(monkeypatch):
from core.inference.video import _h3_offloaded_render_flags
from core.inference import video_minimax_h3