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: give minimax-h3 the sd.cpp graph-cut flags so it renders on a smaller card (#8644)
Maheswar Kumar753ed3120932
diff --git a/studio/backend/core/inference/sd_cpp_args.py b/studio/backend/core/inference/sd_cpp_args.pyindex 37330ba32be..723b32059f8 100644--- a/studio/backend/core/inference/sd_cpp_args.py+++ b/studio/backend/core/inference/sd_cpp_args.py@@ -174,6 +174,13 @@ def metal_text_encoder_flags() -> list[str]:# Everything on the CPU backend. sd.cpp prefers GPU -> integrated GPU -> CPU and only `--backend` changes which backend EXECUTES the graph (`--offload-to-cpu` moves parameters, not compute), so this is the one flag that removes ggml-metal entirely.CPU_BACKEND_FLAGS: tuple[str, ...] = ("--backend", "cpu")+# Graph-cut segmented execution; a negative --max-vram auto-detects free VRAM per device, sparing that many GiB. It segments on its own, so it stands alone.+GRAPH_CUT_VRAM_FLAGS: tuple[str, ...] = ("--max-vram", "-1")+# Upstream only honours --stream-layers when the diffusion params backend is CPU, i.e. under --offload-to-cpu; otherwise it warns and ignores the flag.+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+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 6990a65ba04..50d44280091 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -325,6 +325,26 @@ def sd_cpp_binary_vets_for_h3(binary: str) -> bool:return help_text_identifies_sd_cpp(text) and help_text_supports_minimax_h3(text)+# The ``--help`` tokens marking a build with the graph-cut executor; both are required, since --stream-layers does nothing without --max-vram.+_GRAPH_CUT_HELP_MARKERS: tuple[str, ...] = ("--max-vram", "--stream-layers")+++def sd_cpp_supports_graph_cut(binary: Optional[str]) -> bool:+ """True only when ``binary``'s ``--help`` advertises the graph-cut executor.++ The opposite default to ``sd_cpp_supports_minimax_h3``, and for the same reason each is safe:+ that gate refuses a build, so "cannot tell" has to keep it, while this one ADDS flags, and+ sd-cli exits non-zero on an option it does not know. Guessing yes from an unreadable ``--help``+ would therefore break every generation on an older build instead of merely leaving it as slow+ as it is today."""+ if not binary:+ return False+ text = _sd_cpp_probe_output(binary, "--help")+ if text is None:+ return False+ return all(marker in text for marker in _GRAPH_CUT_HELP_MARKERS)++def sd_cpp_lists_accelerator_device(binary: Optional[str]) -> bool:"""True unless ``binary`` demonstrably enumerates the CPU ggml device and nothing else.diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 60fd1cca84b..5bc86449586 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -1583,13 +1583,20 @@ class VideoBackend:"""Download and commit the four-file stable-diffusion.cpp H3 runtime."""from huggingface_hub import HfApi- from .sd_cpp_args import SdCppModelFiles, device_backend_flags, offload_flags+ from .sd_cpp_args import (+ GRAPH_CUT_STREAM_FLAGS,+ GRAPH_CUT_VRAM_FLAGS,+ SdCppModelFiles,+ device_backend_flags,+ offload_flags,+ )from .diffusion_engine_router import _install_accelerator_forfrom .sd_cpp_backend import (_install_allowed,ensure_h3_sd_cpp_binary,sd_cpp_device_name_for_ordinal,sd_cpp_lists_accelerator_device,+ sd_cpp_supports_graph_cut,)from .sd_cpp_engine import SdCppEnginefrom .video_minimax_h3 import (@@ -1806,6 +1813,8 @@ class VideoBackend:"again.")binary_identity = _sd_cli_identity(binary)+ # Under the claim like every other probe here, and never on CPU, which allocates from system RAM.+ supports_graph_cut = native_device != "cpu" and sd_cpp_supports_graph_cut(binary)# Dropped with the accelerator: the CPU fallback runs on no card, so a recorded ordinal# would outlive the decision and be committed against a runtime that never used it.native_ordinal = None if native_device == "cpu" else gpu_ordinal@@ -1844,6 +1853,12 @@ class VideoBackend:native_offload = tuple(offload_flags(policy, vae_tiling = False, diffusion_fa = True, vae_on_cpu = False))+ # H3 allocates each module WHOLE on the device (20.5 GB DiT, 17 GB encoder), so --offload-to-cpu alone still cudaMallocs; not gated on memory mode because auto and fast are what OOM.+ # --max-vram segments on its own, but upstream ignores --stream-layers unless the params are on the CPU, so it only rides along with --offload-to-cpu.+ if supports_graph_cut:+ native_offload += GRAPH_CUT_VRAM_FLAGS+ if "--offload-to-cpu" in native_offload:+ native_offload += GRAPH_CUT_STREAM_FLAGS# After the policy, so the pin can see which modules it left on the CPU; without it sd.cpp uses ordinal 0 whatever was selected.native_offload += tuple(device_backend_flags(native_device_name, list(native_offload)))from .video_minimax_h3 import MiniMaxH3NativeRuntimediff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex e734c9974d7..7dade471217 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -1194,6 +1194,27 @@ def test_lists_accelerator_device_reads_the_ggml_device_list(monkeypatch):assert bk.sd_cpp_lists_accelerator_device(None) is False+def test_supports_graph_cut_needs_both_flags_and_fails_closed(monkeypatch):+ # The opposite default to the H3 gate: sd-cli exits non-zero on an unknown option, so "cannot tell" must not emit these.+ monkeypatch.setattr(+ bk,+ "_sd_cpp_probe_output",+ lambda *_a: " --max-vram budget\n --stream-layers residency\n",+ )+ assert bk.sd_cpp_supports_graph_cut("/existing/sd-cli") is True++ # --stream-layers is a no-op without --max-vram, so half a build is not a build to emit on.+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: " --stream-layers residency\n")+ assert bk.sd_cpp_supports_graph_cut("/existing/sd-cli") is False++ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: _PRE_H3_HELP)+ assert bk.sd_cpp_supports_graph_cut("/existing/sd-cli") is False++ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: None)+ assert bk.sd_cpp_supports_graph_cut("/existing/sd-cli") is False+ assert bk.sd_cpp_supports_graph_cut(None) is False++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.pyindex 1521ec6fa9d..c32f1059d18 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -3534,6 +3534,135 @@ def test_the_load_time_accelerator_probe_runs_under_the_reader_claim(monkeypatchassert sd_cpp_backend._tree_readers == 0, "the claim must be released after the probe"+def _load_h3_native_offload(+ monkeypatch,+ tmp_path,+ *,+ help_text,+ accelerator = True,+ memory_mode = None,+):+ """Run the native H3 load against a stubbed sd-cli and hand back its committed offload flags.++ ``help_text`` is what the binary answers ``--help`` with, which is the only thing the graph-cut+ gate reads. ``accelerator = False`` reproduces the Linux CUDA host with only the CPU prebuilt,+ where the load commits to ``native_device = "cpu"``.+ """+ from core.inference import gpu_arbiter+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine++ class _Api:+ def __init__(self, **_kwargs):+ pass++ def model_info(self, *_args, **_kwargs):+ return _PlanInfo([])++ monkeypatch.setattr("huggingface_hub.HfApi", _Api)+ monkeypatch.setattr(+ video_mod,+ "resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(backend = "cuda", device = "cuda", dtype = None),+ )+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)+ monkeypatch.setattr(+ sd_cpp_backend,+ "ensure_sd_cpp_binary",+ lambda *, allow_install, accelerator: "/existing/sd-cli",+ )+ # One probe helper serves both --list-devices and --help, so the ggml device line rides along or the CPU case is unreachable.+ devices = "CUDA0\tNVIDIA GeForce RTX 4070 Ti\n" if accelerator else "CPU\tAMD Ryzen 9\n"+ monkeypatch.setattr(sd_cpp_backend, "_sd_cpp_probe_output", lambda *_a: devices + help_text)++ class _Engine:+ def __init__(self, binary):+ self.binary = binary++ def version(self):+ return "stub-version"++ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ def _download(_repo, wanted, *_args, **_kwargs):+ path = tmp_path / Path(wanted).name+ path.write_bytes(b"x")+ return str(path)++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.VIDEO)++ backend = VideoBackend()+ fam = _detect_load_family("leejet/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ backend._run_load_h3_native(+ fam = fam,+ token = None,+ cancel_event = threading.Event(),+ repo_id = "leejet/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ memory_mode = memory_mode,+ )+ assert backend._state is not None+ return backend._state, list(backend._state.pipe.offload_flags)+++# Both fixtures carry the project banner the identity gate reads and the H3 marker+# ensure_h3_sd_cpp_binary gates on, and differ only in the graph-cut options.+_H3_HELP = (+ "stable-diffusion.cpp version master-813\n"+ " --ref-video MiniMax-H3 Ref2VA reference video frame directory\n"+)+_GRAPH_CUT_HELP = (+ _H3_HELP + " --max-vram <string> VRAM budget\n --stream-layers prefetch\n"+)+_NO_GRAPH_CUT_HELP = _H3_HELP + " --offload-to-cpu place the weights in RAM\n"+++def test_h3_native_emits_the_graph_cut_flags_on_an_accelerator(monkeypatch, tmp_path):+ """H3's modules are individually larger than the cards it is offered on, so --offload-to-cpu+ alone still allocates each one whole and cudaMallocs before any tensor is resident. The graph+ cut is what makes the checkpoint renderable, and auto -- not low_vram -- is the default mode+ that has to carry it."""+ state, offload = _load_h3_native_offload(monkeypatch, tmp_path, help_text = _GRAPH_CUT_HELP)+ assert state.device == "cuda"+ # auto offloads, which is what makes --stream-layers take effect.+ assert "--offload-to-cpu" in offload+ assert offload[-3:] == ["--max-vram", "-1", "--stream-layers"]+ # A negative budget auto-detects per device. A fixed number would misjudge the other card.+ assert "0" not in offload+++def test_h3_native_drops_stream_layers_without_cpu_offload(monkeypatch, tmp_path):+ """fast keeps the params resident on the device, and upstream only honours --stream-layers when+ the diffusion params backend is CPU: without --offload-to-cpu it warns and ignores the flag.+ The budget still segments on its own, so --max-vram stays."""+ _state, offload = _load_h3_native_offload(+ monkeypatch, tmp_path, help_text = _GRAPH_CUT_HELP, memory_mode = "fast"+ )+ assert "--offload-to-cpu" not in offload+ assert offload[-2:] == ["--max-vram", "-1"]+ assert "--stream-layers" not in offload+++def test_h3_native_skips_the_graph_cut_flags_on_an_older_build(monkeypatch, tmp_path):+ """sd-cli exits non-zero on an option it does not know, so emitting these unconditionally+ would break every generation on a build that predates the executor."""+ _state, offload = _load_h3_native_offload(monkeypatch, tmp_path, help_text = _NO_GRAPH_CUT_HELP)+ assert "--max-vram" not in offload+ assert "--stream-layers" not in offload+++def test_h3_native_skips_the_graph_cut_flags_on_cpu(monkeypatch, tmp_path):+ """The cut splits a module to fit a device budget; the CPU backend allocates from system RAM,+ so there is nothing to size against."""+ state, offload = _load_h3_native_offload(+ monkeypatch, tmp_path, help_text = _GRAPH_CUT_HELP, accelerator = False+ )+ assert state.device == "cpu"+ assert "--max-vram" not in offload++def test_h3_native_reused_cpu_binary_still_commits_to_cpu(monkeypatch, tmp_path):"""The second load on a Linux CUDA host. The first one installed the CPU prebuilt (upstreampublishes no Linux CUDA asset for the pinned tag), and from then on ensure_sd_cpp_binary finds