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: support current native builds and preserve CPU asset selection (#12902)

oobabooga5a3d8923c7fa
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 004102922fc..3c7d6f653a5 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -313,40 +313,25 @@ def help_text_supports_minimax_h3(help_text: str) -> bool:
def sd_cpp_binary_vets_for_h3(binary: str) -> bool:
- """Both of ``ensure_h3_sd_cpp_binary``'s questions against a live binary, on ONE ``--help``. The
- capability marker cannot stand alone here: ``--ref-video`` is a plain option name that
- unrelated reference-video tools expose too, so a caller re-checking only capability would
- accept a program the gate itself would have refused on identity -- the difference between "an
- sd.cpp build too old for H3" and "not sd.cpp at all" (#8507). Same conservative default as
- ``sd_cpp_supports_minimax_h3``: an unreadable ``--help`` is "could not tell", and the
- caller's own ``version()`` gate already refuses a binary that will not run."""
+ """rejects unrelated --ref-video tools; version() rejects binaries an unreadable probe keeps."""
text = _sd_cpp_probe_output(binary, "--help")
if text is None:
return True
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
- break every generation on an older build instead of merely leaving it as slow as it is today."""
+def sd_cpp_graph_cut_options(binary: Optional[str]) -> frozenset[str]:
+ """returns advertised graph-cut flags; missing help emits none because sd-cli rejects them."""
if not binary:
- return False
+ return frozenset()
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)
+ if text is None or "--max-vram" not in text:
+ return frozenset()
+ return frozenset(flag for flag in ("--max-vram", "--stream-layers") if flag in text)
def sd_cpp_supports_sage_attn(binary: Optional[str]) -> bool:
- """Fails closed: sd-cli exits non-zero on an unknown option (u13b9d92 predates --sage-attn)."""
+ """fails closed because sd-cli rejects unknown flags (u13b9d92 predates --sage-attn)."""
if not binary:
return False
text = _sd_cpp_probe_output(binary, "--help")
diff --git a/studio/backend/core/inference/sd_cpp_engine.py b/studio/backend/core/inference/sd_cpp_engine.py
index 4d5169412c1..5e3317ec0d8 100644
--- a/studio/backend/core/inference/sd_cpp_engine.py
+++ b/studio/backend/core/inference/sd_cpp_engine.py
@@ -24,6 +24,7 @@ import subprocess
import sys
import threading
import time
+from collections import deque
from pathlib import Path
from typing import Callable, Iterator, Optional
@@ -49,6 +50,40 @@ from core.inference.sd_cpp_args import (
logger = logging.getLogger(__name__)
+# Lines worth keeping from a failed native process's output whatever their position.
+_DIAGNOSTIC_MARKERS = (
+ "error",
+ "abort",
+ "assert",
+ "unsupported",
+ "not implemented",
+ "out of memory",
+ "failed",
+ "exception",
+)
+
+
+def _diagnostic_tail(
+ lines,
+ *,
+ keep: int = 20,
+ limit: int = 1500,
+) -> str:
+ """The most useful part of the captured output, not merely its last lines.
+
+ A native abort prints its REASON first and then a long backtrace, so taking the last N lines
+ reported nothing but stack frames: a Metal host that died on an unimplemented op showed twenty
+ addresses and no cause. Marked lines come first (in order), then the last few lines for
+ context, deduplicated."""
+ captured = list(lines)
+ marked = [line for line in captured if any(m in line.lower() for m in _DIAGNOSTIC_MARKERS)]
+ chosen: list[str] = []
+ for line in marked[-keep:] + captured[-max(keep // 2, 4) :]:
+ if line not in chosen:
+ chosen.append(line)
+ return "\n".join(chosen)[:limit]
+
+
# sd-cli (sd-cli.exe on Windows); older builds shipped ``sd`` -- both probed on PATH.
_BINARY_STEM = "sd-cli"
_LEGACY_STEM = "sd"
@@ -870,7 +905,7 @@ class SdCppEngine:
# line in proc.stdout` blocks until EOF). Lines, then a None sentinel, go to a queue the main loop polls against
# a wall-clock deadline. iter_sd_cpp_records also splits sd-cli's in-place progress redraws, which carry no
# newline of their own, so sampling progress reaches on_log while sampling is still running.
- tail: list[str] = []
+ tail: deque[str] = deque(maxlen = 200)
line_q: "queue.Queue[Optional[str]]" = queue.Queue()
def _drain() -> None:
@@ -907,8 +942,6 @@ class SdCppEngine:
break
continue
tail.append(line)
- if len(tail) > 40:
- tail.pop(0)
if on_log is not None:
on_log(line)
ret = proc.wait(timeout = 5.0)
@@ -919,11 +952,11 @@ class SdCppEngine:
forget_pid(proc.pid)
if ret != 0:
- raise RuntimeError(f"sd-cli exited {ret}. Last output:\n" + "\n".join(tail[-12:]))
+ raise RuntimeError(f"sd-cli exited {ret}. Last output:\n" + _diagnostic_tail(tail))
if not out.is_file():
raise RuntimeError(
f"sd-cli reported success but no image at {out}. Last output:\n"
- + "\n".join(tail[-12:])
+ + _diagnostic_tail(tail)
)
elapsed = time.time() - t0
if verbose_logs:
diff --git a/studio/backend/core/inference/sd_cpp_server.py b/studio/backend/core/inference/sd_cpp_server.py
index 8d1d23b58f0..bbc95a2633f 100644
--- a/studio/backend/core/inference/sd_cpp_server.py
+++ b/studio/backend/core/inference/sd_cpp_server.py
@@ -52,6 +52,7 @@ from core.inference.sd_cpp_args import SdCppModelFiles, build_sd_cpp_server_comm
from core.inference.sd_cpp_engine import (
NATIVE_GENERATION_TIMEOUT_S,
SdCppCancelled,
+ _diagnostic_tail,
_sd_cpp_command_for_log,
_sd_cpp_command_summary,
_verbose_native_logs,
@@ -94,40 +95,6 @@ _TERMINAL_OK = "completed"
_TERMINAL_FAIL = "failed"
_TERMINAL_CANCELLED = "cancelled"
-# Lines worth keeping from a dead server's output whatever their position.
-_DIAGNOSTIC_MARKERS = (
- "error",
- "abort",
- "assert",
- "unsupported",
- "not implemented",
- "out of memory",
- "failed",
- "exception",
-)
-
-
-def _diagnostic_tail(
- lines,
- *,
- keep: int = 20,
- limit: int = 1500,
-) -> str:
- """The most useful part of the captured output, not merely its last lines.
-
- A native abort prints its REASON first and then a long backtrace, so taking the last N lines
- reported nothing but stack frames: a Metal host that died on an unimplemented op showed twenty
- addresses and no cause. Marked lines come first (in order), then the last few lines for
- context, deduplicated."""
- captured = list(lines)
- marked = [line for line in captured if any(m in line.lower() for m in _DIAGNOSTIC_MARKERS)]
- chosen: list[str] = []
- for line in marked[-keep:] + captured[-max(keep // 2, 4) :]:
- if line not in chosen:
- chosen.append(line)
- return "\n".join(chosen)[:limit]
-
-
# Grace for the best-effort native cancel to show in job status; without the cap a lost cancel would hold the generate
# lock until the job ends.
_CANCEL_GRACE_S = 5.0
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index e85bfc51b8a..06193fb2d8c 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -3358,7 +3358,7 @@ class VideoBackend:
selected_card_identity,
sd_cpp_accelerator_device_verdict,
sd_cpp_device_name_for_ordinal,
- sd_cpp_supports_graph_cut,
+ sd_cpp_graph_cut_options,
sd_cpp_supports_sage_attn,
)
from .sd_cpp_engine import SdCppEngine
@@ -3639,9 +3639,10 @@ class VideoBackend:
"again."
)
binary_identity = _sd_cli_identity(binary)
- # Under the claim like every other probe here; None on the CPU fallback, which has no card to choose
- # between.
- supports_graph_cut = native_device != "cpu" and sd_cpp_supports_graph_cut(binary)
+ # probe under the claim; the CPU fallback has no card to select.
+ graph_cut_options = (
+ sd_cpp_graph_cut_options(binary) if native_device != "cpu" else frozenset()
+ )
# Lossy (INT8 QK^T), so only on an explicit speed_mode="max".
h3_sage = (
native_device != "cpu"
@@ -3697,13 +3698,10 @@ 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:
+ # H3's 20.5 GB DiT and 17 GB encoder OOM in auto and fast; --max-vram segments them, and streaming needs CPU offload.
+ if "--max-vram" in graph_cut_options:
native_offload += GRAPH_CUT_VRAM_FLAGS
- if "--offload-to-cpu" in native_offload:
+ if "--offload-to-cpu" in native_offload and "--stream-layers" in graph_cut_options:
native_offload += GRAPH_CUT_STREAM_FLAGS
native_env: tuple[tuple[str, str], ...] = ()
if h3_sage:
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index 9af70b011e2..d46fd69caea 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -1323,25 +1323,29 @@ 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.
+def test_graph_cut_options_support_legacy_and_current_builds_and_fail_closed(monkeypatch):
+ # unknown flags fail closed because sd-cli rejects them.
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
+ assert bk.sd_cpp_graph_cut_options("/existing/sd-cli") == {"--max-vram", "--stream-layers"}
- # --stream-layers is a no-op without --max-vram, so half a build is not a build to emit on.
+ # current builds stream automatically and reject the removed --stream-layers flag.
+ monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: " --max-vram budget\n")
+ assert bk.sd_cpp_graph_cut_options("/existing/sd-cli") == {"--max-vram"}
+
+ # --stream-layers requires --max-vram, so a partial advertisement emits neither.
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
+ assert bk.sd_cpp_graph_cut_options("/existing/sd-cli") == frozenset()
monkeypatch.setattr(bk, "_sd_cpp_probe_output", lambda *_a: _PRE_H3_HELP)
- assert bk.sd_cpp_supports_graph_cut("/existing/sd-cli") is False
+ assert bk.sd_cpp_graph_cut_options("/existing/sd-cli") == frozenset()
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
+ assert bk.sd_cpp_graph_cut_options("/existing/sd-cli") == frozenset()
+ assert bk.sd_cpp_graph_cut_options(None) == frozenset()
def test_device_name_for_ordinal_reads_the_ggml_device_list(monkeypatch):
diff --git a/studio/backend/tests/test_sd_cpp_engine.py b/studio/backend/tests/test_sd_cpp_engine.py
index 5f78bd18323..c44ac64f4f2 100644
--- a/studio/backend/tests/test_sd_cpp_engine.py
+++ b/studio/backend/tests/test_sd_cpp_engine.py
@@ -714,6 +714,23 @@ def test_generate_raises_on_nonzero_exit(tmp_path, monkeypatch):
_shared_setup_2(e, out)
[email protected]("returncode", [-6, 0])
+def test_native_failure_keeps_reason_before_long_backtrace(tmp_path, monkeypatch, returncode):
+ e = _engine(tmp_path)
+ out = tmp_path / "img.png"
+ reason = "CUDA error: no kernel image is available for execution on the device"
+ lines = [reason] + [f"#{i} 0x123456 in native_frame_{i}()" for i in range(80)]
+ _patch_popen(monkeypatch, lines = lines, returncode = returncode, out_file = out, write = False)
+
+ with pytest.raises(RuntimeError) as failure:
+ _shared_setup_2(e, out)
+
+ detail = str(failure.value).split("Last output:\n", 1)[1]
+ assert detail.startswith(reason)
+ assert "native_frame_79" in detail
+ assert len(detail) <= 1500
+
+
def test_generate_raises_when_no_output_despite_success(tmp_path, monkeypatch):
e = _engine(tmp_path)
out = tmp_path / "img.png"
diff --git a/studio/backend/tests/test_sd_cpp_install.py b/studio/backend/tests/test_sd_cpp_install.py
index 202e6e12860..447114fb8e8 100644
--- a/studio/backend/tests/test_sd_cpp_install.py
+++ b/studio/backend/tests/test_sd_cpp_install.py
@@ -227,13 +227,51 @@ def test_linux_arm64_has_no_prebuilt():
assert _resolve("Linux", "aarch64") is None
-# ── Windows ─────────────────────────────────────────────────────────────────
-
-
def test_windows_auto_picks_avx2():
assert _resolve("Windows", "AMD64") == "sd-master-8caa3f9-bin-win-avx2-x64.zip"
[email protected]("accelerator", ["auto", "cpu"])
[email protected]("reverse", [False, True])
+def test_windows_cpu_selection_with_unsloth_vulkan_asset(accelerator, reverse):
+ cpu = "sd-master-813-bfbef5b-u1d02858-bin-win-cpu-x64.zip"
+ vulkan = "sd-master-813-bfbef5b-u1d02858-bin-win-vulkan-x64.zip"
+ assets = [cpu, vulkan]
+ if reverse:
+ assets.reverse()
+ assert (
+ resolve_release_asset(assets, system = "Windows", machine = "AMD64", accelerator = accelerator)
+ == cpu
+ )
+
+
[email protected]("accelerator", ["auto", "cpu"])
[email protected]("gpu", ["cuda12", "vulkan", "rocm", "sycl", "musa"])
+def test_windows_cpu_selection_never_uses_accelerator_build(accelerator, gpu):
+ assets = [f"sd-master-test-bin-win-{gpu}-avx2-x64.zip"]
+ assert (
+ resolve_release_asset(assets, system = "Windows", machine = "AMD64", accelerator = accelerator)
+ is None
+ )
+ cpu = "sd-master-test-bin-win-cpu-x64.zip"
+ assert (
+ resolve_release_asset(
+ [*assets, cpu], system = "Windows", machine = "AMD64", accelerator = accelerator
+ )
+ == cpu
+ )
+
+
[email protected]("accelerator", ["auto", "cpu"])
+def test_windows_cpu_selection_keeps_upstream_avx2_preference(accelerator):
+ avx2 = "sd-master-test-bin-win-avx2-x64.zip"
+ assets = ["sd-master-test-bin-win-cpu-x64.zip", avx2]
+ assert (
+ resolve_release_asset(assets, system = "Windows", machine = "AMD64", accelerator = accelerator)
+ == avx2
+ )
+
+
def test_windows_cuda_picks_cuda12():
assert _resolve("Windows", "AMD64", "cuda") == "sd-master-8caa3f9-bin-win-cuda12-x64.zip"
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 61a0d3ba59b..28ace3b644c 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -4124,6 +4124,15 @@ def test_h3_native_emits_the_graph_cut_flags_on_an_accelerator(monkeypatch, tmp_
assert "0" not in offload
+def test_h3_native_preserves_vram_headroom_on_current_builds(monkeypatch, tmp_path):
+ _state, offload = _load_h3_native_offload(
+ monkeypatch, tmp_path, help_text = _H3_HELP + " --max-vram <string> VRAM budget\n"
+ )
+ assert "--offload-to-cpu" in offload
+ assert offload[-2:] == ["--max-vram", "-1"]
+ assert "--stream-layers" 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.
diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.py
index 7ab25ecaf29..b552ea46a90 100644
--- a/studio/install_sd_cpp_prebuilt.py
+++ b/studio/install_sd_cpp_prebuilt.py
@@ -201,8 +201,8 @@ _WINDOWS_ACCEL_TOKEN = {
"cpu": "avx2",
"auto": "avx2",
}
-# Tokens that mark an accelerator-specific Linux build; "auto"/"cpu" want none of them.
-_LINUX_ACCEL_MARKERS = ("rocm", "vulkan", "cuda", "sycl", "musa")
+# Tokens that mark an accelerator-specific build; "auto"/"cpu" want none of them.
+_ACCEL_MARKERS = ("rocm", "vulkan", "cuda", "sycl", "musa")
_ARCH_TOKENS = {
"x86_64": ("x86_64", "x64", "amd64"),
@@ -242,6 +242,8 @@ def resolve_release_asset(
if system == "windows":
# Filter by host arch: an arm64 host must not install an unrunnable x64 sd-cli. No match returns None so the caller falls back.
pool = [a for a in zips if "bin-win" in a.lower() and any(t in a.lower() for t in arch)]
+ if accel in ("auto", "cpu"):
+ pool = [a for a in pool if not any(m in a.lower() for m in _ACCEL_MARKERS)]
token = _WINDOWS_ACCEL_TOKEN.get(accel, accel)
sel = [a for a in pool if token in a.lower()]
if sel:
@@ -258,7 +260,7 @@ def resolve_release_asset(
marker = _LINUX_ACCEL_TOKEN.get(accel, accel)
sel = [a for a in pool if marker in a.lower()]
else:
- sel = [a for a in pool if not any(m in a.lower() for m in _LINUX_ACCEL_MARKERS)]
+ sel = [a for a in pool if not any(m in a.lower() for m in _ACCEL_MARKERS)]
return sel[0] if sel else None