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: pin sd.cpp to the mirror build with Windows CUDA, sharing llama.cpp's CUDA runtime (#13175)

Daniel Han2a81fc4f8cd9
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.py
index 8b8d8c8c3d9..c840363093a 100644
--- a/studio/backend/core/inference/diffusion_engine_router.py
+++ b/studio/backend/core/inference/diffusion_engine_router.py
@@ -50,6 +50,7 @@ from core.inference.sd_cpp_backend import (
_card_lookup_inventory,
_install_allowed,
_managed_tree_in_use,
+ _pin_moved,
_server_binary_runnable,
ensure_sd_cpp_binary,
ensure_sd_server_binary,
@@ -625,6 +626,19 @@ def native_binary_installed(
return bool(binary and SdCppEngine(binary = binary).version() is not None)
+def _resident_build_upgrades_on_load(gpu_ordinal: Optional[int]) -> bool:
+ backend = resolve_diffusion_device_target().backend
+ if off_torch_sd_cpp_device(backend) is not None:
+ gpu_ordinal = None
+ accelerator = preferred_accelerator(
+ image_install_accelerator(backend), _selected_card(gpu_ordinal)
+ )
+ resident = ensure_sd_server_binary(
+ allow_install = False, accelerator = accelerator
+ ) or ensure_sd_cpp_binary(allow_install = False, accelerator = accelerator)
+ return bool(resident) and _pin_moved(resident, accelerator)
+
+
def predict_engine(
fam: DiffusionFamily,
*,
@@ -669,10 +683,14 @@ def predict_engine(
# A permitted install counts as available only where selection would actually perform one.
# ``ensure_*_binary`` keeps a runnable build of the right accelerator untouched, so a resident
# build that cannot run this family is never upgraded away, and predicting native for it would
- # stage sd-cli's companions for a load the router sends to diffusers. With nothing resident the
- # install happens and lands on the pinned prebuilt, which is current by definition.
+ # stage sd-cli's companions for a load the router sends to diffusers. With nothing resident (or
+ # a moved pin) the install lands on the pinned prebuilt, which is current by definition.
native_available = native_binary_installed(gpu_ordinal = gpu_ordinal, fam = fam) or (
- _install_allowed() and not native_binary_installed(gpu_ordinal = gpu_ordinal)
+ _install_allowed()
+ and (
+ not native_binary_installed(gpu_ordinal = gpu_ordinal)
+ or _resident_build_upgrades_on_load(gpu_ordinal)
+ )
)
return select_diffusion_engine(
backend, native_available = native_available, prefer_native = prefer_native
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 32c3ddd7f71..f90f755bf90 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -2109,6 +2109,16 @@ def note_unlaunchable_accelerator_build(
logger.debug("could not record the sd.cpp launch failure: %s", exc)
+def _install_kwargs(accelerator: str) -> dict[str, Any]:
+ kwargs: dict[str, Any] = {"accelerator": accelerator}
+ if _accelerator_class_of(accelerator) == "cuda":
+ from core.inference.sd_cpp_engine import host_cuda_runtime_major
+ major = host_cuda_runtime_major()
+ if major:
+ kwargs["cuda_major"] = major
+ return kwargs
+
+
def ensure_sd_cpp_binary(*, allow_install: bool = True, accelerator: str = "cpu") -> Optional[str]:
"""Path to a usable ``sd-cli`` binary, installing the prebuilt once if needed. Returns the
binary path, or None when it is absent and cannot be installed (install disabled, no network,
@@ -2139,7 +2149,7 @@ def ensure_sd_cpp_binary(*, allow_install: bool = True, accelerator: str = "cpu"
if not claimed:
return fallback # something is running in there; retry on a later load
try:
- path = _install(accelerator = accelerator)
+ path = _install(**_install_kwargs(accelerator))
logger.info("sd-cli installed at %s", path)
return str(path)
except Exception as exc: # noqa: BLE001 -- download/extract failure -> fall back
@@ -2198,7 +2208,7 @@ def ensure_sd_server_binary(
if not claimed:
return fallback # something is running in there; retry on a later load
try:
- _install(accelerator = accelerator) # extracts sd-cli AND sd-server
+ _install(**_install_kwargs(accelerator)) # extracts sd-cli AND sd-server
except Exception as exc: # noqa: BLE001 -- download/extract failure -> fall back
logger.warning("sd-server auto-install failed: %s", exc)
# Also when only the CLI survives (a legacy server-less tree): the router probes ensure_sd_cpp_binary
diff --git a/studio/backend/core/inference/sd_cpp_engine.py b/studio/backend/core/inference/sd_cpp_engine.py
index fb46434fb72..17d83dedc4a 100644
--- a/studio/backend/core/inference/sd_cpp_engine.py
+++ b/studio/backend/core/inference/sd_cpp_engine.py
@@ -322,11 +322,76 @@ def runtime_env(binary: str, base_env: Optional[dict[str, str]] = None) -> dict[
env = child_env_without_native_path_secret(os.environ if base_env is None else base_env)
var = _lib_path_var()
bindir = str(Path(binary).resolve().parent)
+ dirs = [bindir]
+ if _needs_host_cuda_runtime(bindir):
+ dirs.extend(d for d in host_cuda_runtime_dirs() if d not in dirs)
existing = env.get(var, "")
- env[var] = bindir + (os.pathsep + existing if existing else "")
+ env[var] = os.pathsep.join(dirs) + (os.pathsep + existing if existing else "")
return env
+def _needs_host_cuda_runtime(bindir: str) -> bool:
+ try:
+ names = [n.lower() for n in os.listdir(bindir)]
+ except OSError:
+ return False
+ cuda = any(n == "ggml-cuda.dll" or n.startswith("libggml-cuda.so") for n in names)
+ runtime = any(n.startswith(("cudart64_", "libcudart.so")) for n in names)
+ return cuda and not runtime
+
+
+def _llama_server_binary() -> Optional[str]:
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend
+ return LlamaCppBackend._find_llama_server_binary()
+ except Exception: # noqa: BLE001 -- no llama.cpp install: nothing to share
+ return None
+
+
+def host_cuda_runtime_dirs() -> list[str]:
+ """llama-server's CUDA runtime dirs. Its build dir is dropped off Windows: its libggml*.so share
+ sonames with the bundle's (Windows searches the executable's dir first)."""
+ binary = _llama_server_binary()
+ if not binary:
+ return []
+ try:
+ from core.inference.llama_cpp import LlamaCppBackend, _llama_lib_dir
+
+ var = _lib_path_var()
+ inherited = {d for d in os.environ.get(var, "").split(os.pathsep) if d}
+ llama_dir = os.path.normcase(str(_llama_lib_dir(binary)))
+ out: list[str] = []
+ for d in (
+ LlamaCppBackend._llama_server_env_for_binary(binary).get(var, "").split(os.pathsep)
+ ):
+ if not d or d in inherited or d in out:
+ continue
+ if sys.platform != "win32" and os.path.normcase(d) == llama_dir:
+ continue
+ out.append(d)
+ return out
+ except Exception as exc: # noqa: BLE001 -- a launch must not fail on a path lookup
+ logger.debug("sd.cpp: CUDA runtime dirs from llama.cpp unavailable: %s", exc)
+ return []
+
+
+def host_cuda_runtime_major() -> Optional[str]:
+ """CUDA major the installed llama.cpp links, else torch's."""
+ binary = _llama_server_binary()
+ if binary:
+ try:
+ from utils.llama_cpp_freshness import read_install_marker
+
+ line = (read_install_marker(binary) or {}).get("runtime_line")
+ match = re.fullmatch(r"cuda(\d+)", line if isinstance(line, str) else "")
+ if match:
+ return match.group(1)
+ except Exception: # noqa: BLE001
+ pass
+ version = getattr(getattr(sys.modules.get("torch"), "version", None), "cuda", None)
+ return version.split(".")[0] if isinstance(version, str) and version else None
+
+
def _layout_candidates(root: Path, stem: str = _BINARY_STEM) -> list[Path]:
"""``stem`` locations under a stable-diffusion.cpp ``root``, highest priority first: the cmake
``build/bin`` tree, a Windows Release subdir, the root, then the prebuilt's versioned subdir."""
diff --git a/studio/backend/tests/test_diffusion_engine_router.py b/studio/backend/tests/test_diffusion_engine_router.py
index 67e6c6fdba6..3429446bb68 100644
--- a/studio/backend/tests/test_diffusion_engine_router.py
+++ b/studio/backend/tests/test_diffusion_engine_router.py
@@ -473,3 +473,19 @@ def test_the_prediction_agrees_with_the_selection_about_an_incapable_build(monke
_set_binary(monkeypatch, None)
monkeypatch.setattr(r, "ensure_sd_server_binary", lambda **_: None)
assert r.predict_engine(fam, model_kind = "gguf") == ENGINE_SD_CPP
+
+
+def test_the_prediction_counts_the_upgrade_a_load_performs_for_a_moved_pin(monkeypatch, tmp_path):
+ # #12470: the load replaces a moved-pin build before selecting, so the plan must not stage diffusers.
+ _set_device(monkeypatch, "cpu")
+ _set_runnable(monkeypatch)
+ old = _write_binary(tmp_path, "sd-cli-old4", marker = False)
+ _set_binary(monkeypatch, old)
+ monkeypatch.setattr(r, "ensure_sd_server_binary", lambda **_: None)
+ moved: list = []
+ monkeypatch.setattr(r, "_pin_moved", lambda binary, accel: moved.append(binary) or True)
+ fam = detect_family("qwen-image-2.1")
+ assert r.predict_engine(fam, model_kind = "gguf") == ENGINE_SD_CPP
+ assert moved == [old]
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP_INSTALL", "0")
+ assert r.predict_engine(fam, model_kind = "gguf") == ENGINE_DIFFUSERS
diff --git a/studio/backend/tests/test_diffusion_more_families.py b/studio/backend/tests/test_diffusion_more_families.py
index 438eab9f3a1..ad22294d41b 100644
--- a/studio/backend/tests/test_diffusion_more_families.py
+++ b/studio/backend/tests/test_diffusion_more_families.py
@@ -839,10 +839,11 @@ def test_qwen_image_21_gguf_reaches_sd_cpp_with_its_own_vae_and_a_qwen3vl_encode
def test_the_pinned_prebuilt_is_one_that_can_load_qwen_image_21():
"""The route is only real if the binary the installer pins understands the architecture.
- The tag STRING cannot answer this: every mirror build resolves to the same master-813 base, so
- the August build and the current one are indistinguishable by name. What is asserted here is the
- pin itself, against the release verified to render this family (26.9s at 1024 on one B200,
- Q4_K_M denoiser, bf16 VAE, Q4_K_M Qwen3-VL encoder). Bump both together or not at all.
+ The tag STRING cannot answer this: two mirror builds can share an upstream base, so the name does
+ not say whether a build carries the architecture. What is asserted here is the pin itself,
+ against the release verified to render this family through Studio's native engine (512x512,
+ 12 steps, Q4_K_M, one B200: cuda12 and cuda13 bundles, 26s / 36s, identical images). Bump both
+ together or not at all.
"""
import importlib.util
from pathlib import Path
@@ -852,7 +853,7 @@ def test_the_pinned_prebuilt_is_one_that_can_load_qwen_image_21():
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
- assert module.DEFAULT_TAG == "master-813-bfbef5b-u1d02858", (
+ assert module.DEFAULT_TAG == "master-951-f89d9b1-uafac7a7", (
"the pinned prebuilt must be one built from a tree carrying Qwen-Image-2.1; "
f"{module.DEFAULT_TAG} is not"
)
diff --git a/studio/backend/tests/test_sd_cpp_engine.py b/studio/backend/tests/test_sd_cpp_engine.py
index c44ac64f4f2..1660f8cb3cc 100644
--- a/studio/backend/tests/test_sd_cpp_engine.py
+++ b/studio/backend/tests/test_sd_cpp_engine.py
@@ -500,6 +500,92 @@ def test_runtime_env_prepends_binary_dir_to_lib_path():
assert "/existing" in env[var]
+def _bundle(tmp_path, *names):
+ d = tmp_path / "bundle"
+ d.mkdir()
+ for n in names:
+ (d / n).write_bytes(b"x")
+ return str(d / ("sd-cli.exe" if sys.platform == "win32" else "sd-cli"))
+
+
+_CUDA_LIB = "ggml-cuda.dll" if sys.platform == "win32" else "libggml-cuda.so.0"
+_CUDART = "cudart64_13.dll" if sys.platform == "win32" else "libcudart.so.13"
+
+
+def test_runtime_env_adds_llama_cuda_runtime_dirs_for_a_runtime_less_cuda_bundle(
+ monkeypatch, tmp_path
+):
+ var = eng._lib_path_var()
+ monkeypatch.setattr(eng, "host_cuda_runtime_dirs", lambda: ["/venv/nvidia/cu13/lib"])
+ binary = _bundle(tmp_path, _CUDA_LIB)
+ parts = runtime_env(binary, {var: "/existing"})[var].split(os.pathsep)
+ assert parts == [str(Path(binary).resolve().parent), "/venv/nvidia/cu13/lib", "/existing"]
+
+
[email protected]("names", [(), (_CUDA_LIB, _CUDART)])
+def test_runtime_env_leaves_other_bundles_alone(monkeypatch, tmp_path, names):
+ var = eng._lib_path_var()
+ monkeypatch.setattr(
+ eng, "host_cuda_runtime_dirs", lambda: pytest.fail("no host CUDA dirs for this bundle")
+ )
+ binary = _bundle(tmp_path, *names)
+ assert runtime_env(binary, {var: "/existing"})[var].split(os.pathsep) == [
+ str(Path(binary).resolve().parent),
+ "/existing",
+ ]
+
+
+def test_host_cuda_runtime_dirs_reuse_llama_server_env_minus_its_ggml(monkeypatch, tmp_path):
+ import core.inference.llama_cpp as llama
+
+ var = eng._lib_path_var()
+ llama_dir = tmp_path / "llama" / "build" / "bin"
+ monkeypatch.setattr(eng, "_llama_server_binary", lambda: str(llama_dir / "llama-server"))
+ monkeypatch.setattr(llama, "_llama_lib_dir", lambda _b: llama_dir)
+ monkeypatch.setenv(var, "/inherited")
+ monkeypatch.setattr(
+ llama.LlamaCppBackend,
+ "_llama_server_env_for_binary",
+ staticmethod(
+ lambda _b, **_k: {
+ var: os.pathsep.join([str(llama_dir), "/venv/nvidia/cu13/lib", "/inherited"])
+ }
+ ),
+ )
+ dirs = eng.host_cuda_runtime_dirs()
+ if sys.platform == "win32":
+ assert dirs == [str(llama_dir), "/venv/nvidia/cu13/lib"]
+ else:
+ # llama.cpp's libggml*.so share sonames with the bundle's.
+ assert dirs == ["/venv/nvidia/cu13/lib"]
+
+
+def test_host_cuda_runtime_dirs_without_llama_cpp(monkeypatch):
+ monkeypatch.setattr(eng, "_llama_server_binary", lambda: None)
+ assert eng.host_cuda_runtime_dirs() == []
+
+
+ "marker, torch_cuda, want",
+ [
+ ({"runtime_line": "cuda13"}, "12.8", "13"),
+ ({"runtime_line": "cuda12"}, None, "12"),
+ ({"backend": "vulkan"}, "13.0", "13"),
+ (None, None, None),
+ ],
+)
+def test_host_cuda_runtime_major_follows_llama_cpp_then_torch(
+ monkeypatch, marker, torch_cuda, want
+):
+ import utils.llama_cpp_freshness as fresh
+
+ monkeypatch.setattr(eng, "_llama_server_binary", lambda: "/llama/llama-server")
+ monkeypatch.setattr(fresh, "read_install_marker", lambda _b: marker)
+ fake_torch = types.SimpleNamespace(version = types.SimpleNamespace(cuda = torch_cuda))
+ monkeypatch.setitem(sys.modules, "torch", fake_torch)
+ assert eng.host_cuda_runtime_major() == want
+
+
def test_runtime_env_scrubs_native_path_lease_secret(monkeypatch):
# The sd-cli child is an external process and must never receive the native-path lease secret; every launch funnels through runtime_env.
monkeypatch.setenv("UNSLOTH_STUDIO_NATIVE_PATH_LEASE_SECRET", "top-secret")
@@ -1041,3 +1127,20 @@ def test_run_forwards_clean_redraws_to_on_log(tmp_path, monkeypatch):
" |=========> | 2/2 - 21.50s/it",
]
assert not any("\x1b" in s for s in seen)
+
+
+ "accelerator, major, want",
+ [
+ ("cuda", "13", {"accelerator": "cuda", "cuda_major": "13"}),
+ ("cuda", None, {"accelerator": "cuda"}),
+ ("vulkan", "13", {"accelerator": "vulkan"}),
+ ("cpu", "12", {"accelerator": "cpu"}),
+ ],
+)
+def test_a_cuda_install_names_the_host_runtime_major(monkeypatch, accelerator, major, want):
+ import core.inference.sd_cpp_backend as backend
+
+ monkeypatch.setattr(eng, "host_cuda_runtime_major", lambda: major)
+ monkeypatch.setattr(backend, "_accelerator_class_of", lambda a: a)
+ assert backend._install_kwargs(accelerator) == want
diff --git a/studio/backend/tests/test_sd_cpp_install.py b/studio/backend/tests/test_sd_cpp_install.py
index 447114fb8e8..415067676e1 100644
--- a/studio/backend/tests/test_sd_cpp_install.py
+++ b/studio/backend/tests/test_sd_cpp_install.py
@@ -276,6 +276,46 @@ def test_windows_cuda_picks_cuda12():
assert _resolve("Windows", "AMD64", "cuda") == "sd-master-8caa3f9-bin-win-cuda12-x64.zip"
+_CUDA_SPLIT = [
+ "sd-x-bin-Linux-Ubuntu-22.04-x86_64-cuda12.zip",
+ "sd-x-bin-Linux-Ubuntu-22.04-x86_64-cuda13.zip",
+ "sd-x-bin-win-cuda12-x64.zip",
+ "sd-x-bin-win-cuda13-x64.zip",
+ "sd-x-bin-win-cpu-x64.zip",
+]
+
+
+ "system, machine, major, want",
+ [
+ ("Linux", "x86_64", "13", "sd-x-bin-Linux-Ubuntu-22.04-x86_64-cuda13.zip"),
+ ("Linux", "x86_64", "12", "sd-x-bin-Linux-Ubuntu-22.04-x86_64-cuda12.zip"),
+ ("Windows", "AMD64", "13", "sd-x-bin-win-cuda13-x64.zip"),
+ ("Windows", "AMD64", "12", "sd-x-bin-win-cuda12-x64.zip"),
+ ("Windows", "AMD64", None, "sd-x-bin-win-cuda12-x64.zip"),
+ ],
+)
+def test_cuda_bundles_follow_the_host_runtime_major(system, machine, major, want):
+ assert (
+ resolve_release_asset(
+ _CUDA_SPLIT, system = system, machine = machine, accelerator = "cuda", cuda_major = major
+ )
+ == want
+ )
+
+
+def test_a_release_without_the_hosts_cuda_major_still_offers_its_cuda_build():
+ for system, machine in (("Linux", "x86_64"), ("Windows", "AMD64")):
+ got = resolve_release_asset(
+ [n for n in _CUDA_SPLIT if "cuda13" not in n],
+ system = system,
+ machine = machine,
+ accelerator = "cuda",
+ cuda_major = "13",
+ )
+ assert got is not None and "cuda12" in got
+
+
def test_windows_vulkan_picks_vulkan():
assert _resolve("Windows", "AMD64", "vulkan") == "sd-master-8caa3f9-bin-win-vulkan-x64.zip"
@@ -1402,6 +1442,42 @@ def test_upstream_fallback_asks_for_the_translated_pin_not_latest(monkeypatch):
assert not any(tag is None for _repo_name, tag in seen)
+def test_the_shipped_pin_falls_back_to_an_upstream_release_that_runs_qwen_image_2_1(monkeypatch):
+ """#12470: the previous pin's upstream base (master-813) predated Qwen-Image-2.1, so hosts the mirror skips got a build the router refuses."""
+ monkeypatch.delenv("UNSLOTH_SD_CPP_REPO", raising = False)
+ monkeypatch.delenv("UNSLOTH_SD_CPP_TAG", raising = False)
+ monkeypatch.setattr(sdmod.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(sdmod.platform, "machine", lambda: "AMD64")
+ seen = []
+
+ def fake_fetch(
+ tag = None,
+ *,
+ repo = None,
+ token = None,
+ timeout = 30.0,
+ allow_latest = True,
+ ):
+ seen.append((repo, tag))
+ if repo == sdmod.DEFAULT_REPO and tag == DEFAULT_TAG:
+ return {"tag_name": tag, "assets": [{"name": f"sd-{tag}-bin-win-cpu-x64.zip"}]}
+ if repo == sdmod.UPSTREAM_FALLBACK_REPO and tag:
+ short = tag.rsplit("-", 1)[-1]
+ return {
+ "tag_name": tag,
+ "assets": [{"name": f"sd-master-{short}-bin-win-cuda12-x64.zip"}],
+ }
+ raise urllib.error.HTTPError(f"https://api/{repo}", 404, "not found", None, None)
+
+ monkeypatch.setattr(sdmod, "_fetch_release", fake_fetch)
+ repo, release, chosen = sdmod._resolve_with_fallback("cuda", None)
+ assert repo == sdmod.UPSTREAM_FALLBACK_REPO
+ assert chosen.endswith("-win-cuda12-x64.zip")
+ assert release["tag_name"] == upstream_tag_for(DEFAULT_TAG)
+ # Qwen-Image-2.1 landed upstream in master-883, its reference-alpha fix in master-896.
+ assert int(release["tag_name"].split("-")[1]) >= 896
+
+
# ── mirror -> upstream fallback in install() ─────────────────────────────────
diff --git a/studio/backend/tests/test_sd_cpp_pin_upgrade.py b/studio/backend/tests/test_sd_cpp_pin_upgrade.py
index da8c6270813..cee642a0497 100644
--- a/studio/backend/tests/test_sd_cpp_pin_upgrade.py
+++ b/studio/backend/tests/test_sd_cpp_pin_upgrade.py
@@ -187,6 +187,39 @@ def test_an_old_record_holding_the_upstream_form_of_the_pin_is_current(tmp_path,
assert bk.ensure_sd_cpp_binary(accelerator = "vulkan") == str(cli)
[email protected]("with_requested_tag", [True, False])
+def test_the_previous_pins_upstream_fallback_is_upgraded(tmp_path, monkeypatch, with_requested_tag):
+ # #12470: leejet master-813, the previous pin's upstream fallback, cannot run Qwen-Image-2.1.
+ record = {
+ "accelerator": "cuda",
+ "repo": sdmod.UPSTREAM_FALLBACK_REPO,
+ "tag": "master-813-bfbef5b",
+ }
+ if with_requested_tag:
+ record["requested_tag"] = "master-813-bfbef5b-u1d02858"
+ bk, root, cli, server = _tree(tmp_path, monkeypatch, record)
+ installs: list = []
+
+ def _install(**kwargs):
+ installs.append(kwargs)
+ cli.write_bytes(b"new-build")
+ server.write_bytes(b"new-build")
+ sdmod._write_install_record(
+ root,
+ accelerator = kwargs["accelerator"],
+ repo = sdmod.UPSTREAM_FALLBACK_REPO,
+ tag = sdmod.upstream_tag_for(sdmod.DEFAULT_TAG),
+ )
+ return cli
+
+ monkeypatch.setattr(sdmod, "install", _install)
+ assert bk.ensure_sd_cpp_binary(accelerator = "cuda") == str(cli)
+ assert cli.read_bytes() == b"new-build"
+ assert bk.ensure_sd_cpp_binary(accelerator = "cuda") == str(cli)
+ assert bk.ensure_sd_server_binary(accelerator = "cuda") == str(server)
+ assert len(installs) == 1
+
+
def test_kill_switch_keeps_the_installed_bundle(tmp_path, monkeypatch):
bk, root, cli, server = _tree(
tmp_path, monkeypatch, {"accelerator": "cuda", "repo": "r", "tag": OLD}
diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.py
index b552ea46a90..e0e6478da19 100644
--- a/studio/install_sd_cpp_prebuilt.py
+++ b/studio/install_sd_cpp_prebuilt.py
@@ -39,11 +39,10 @@ else:
DEFAULT_REPO = "unslothai/stable-diffusion.cpp"
UPSTREAM_FALLBACK_REPO = "leejet/stable-diffusion.cpp"
# Pinned for reproducibility; UNSLOTH_SD_CPP_TAG overrides (empty tracks latest) and a missing tag falls back to latest. The -u<id> suffix is the mirror's patch set: an unpatched build aborts on the default --cfg-scale and on --vae-on-cpu, and quantizes MiniMax-H3's 1-D norms into an output uncorrelated with its own bf16 reference (leejet/stable-diffusion.cpp#1861, #1862, #1863).
-# The Qwen-Image-2.1 line: the tag STRING still resolves to the master-813 base, because that is the
-# newest upstream release our ancestry names, but this build is the mirror's current tree and carries
-# the architecture (upstream 137f7409bb, 2026-09-20). The u13b9d92 build this replaces is from
-# 2026-08-09 and cannot load it at all, so the native route for that family is only real from here.
-DEFAULT_TAG = "master-813-bfbef5b-u1d02858"
+# The base must carry every family's sd_cpp_arch_marker / sd_cpp_edit_marker: hosts the mirror does
+# not build (ROCm) install it from upstream. master-813, the previous base, predates Qwen-Image-2.1
+# (master-883) and its reference-alpha fix (master-896). CUDA bundles carry no CUDA runtime.
+DEFAULT_TAG = "master-951-f89d9b1-uafac7a7"
REPO = DEFAULT_REPO
@@ -195,7 +194,7 @@ def upstream_tag_for(tag: Optional[str]) -> Optional[str]:
_LINUX_ACCEL_TOKEN = {"rocm": "rocm", "vulkan": "vulkan"}
_WINDOWS_ACCEL_TOKEN = {
- "cuda": "cuda12",
+ "cuda": "cuda",
"vulkan": "vulkan",
"rocm": "rocm",
"cpu": "avx2",
@@ -216,14 +215,24 @@ def _arch_tokens(machine: str) -> tuple[str, ...]:
return _ARCH_TOKENS.get(machine.lower(), (machine.lower(),))
+def _prefer_cuda_major(names: list[str], cuda_major: Optional[str]) -> list[str]:
+ """The mirror's CUDA bundles load the host's cudart, so the major must match; others stay as fallback for older self-contained releases."""
+ if not cuda_major:
+ return names
+ want = f"cuda{cuda_major}"
+ exact = [a for a in names if re.search(rf"{want}(?!\d)", a.lower())]
+ return exact + [a for a in names if a not in exact]
+
+
def resolve_release_asset(
asset_names: Sequence[str],
*,
system: str,
machine: str,
accelerator: str = "auto",
+ cuda_major: Optional[str] = None,
) -> Optional[str]:
- """Pick the best release asset for a host, or None if none matches. ``system`` / ``machine`` are ``platform.system()`` / ``platform.machine()`` values; ``accelerator`` is ``auto`` (CPU/Metal default), ``vulkan``, ``rocm``, or ``cuda`` (Windows only). Pure: the caller passes the release's asset name list."""
+ """Pick the best release asset for a host, or None if none matches. ``system`` / ``machine`` are ``platform.system()`` / ``platform.machine()`` values; ``accelerator`` is ``auto`` (CPU/Metal default), ``vulkan``, ``rocm``, or ``cuda``; ``cuda_major`` ("12" / "13") prefers that CUDA line. Pure: the caller passes the release's asset name list."""
system = system.lower()
accel = accelerator.lower()
arch = _arch_tokens(machine)
@@ -246,6 +255,8 @@ def resolve_release_asset(
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 accel == "cuda":
+ sel = _prefer_cuda_major(sel, cuda_major or "12")
if sel:
return sel[0]
# An explicit GPU accelerator with no asset returns None, so the caller falls back instead of installing a CPU build.
@@ -259,6 +270,8 @@ def resolve_release_asset(
# Explicit GPU accelerator: require its marker, never hand back a plain CPU build.
marker = _LINUX_ACCEL_TOKEN.get(accel, accel)
sel = [a for a in pool if marker in a.lower()]
+ if accel == "cuda":
+ sel = _prefer_cuda_major(sel, cuda_major)
else:
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
@@ -689,6 +702,7 @@ def _resolve_repo_asset(
token: Optional[str],
*,
allow_latest: bool = True,
+ cuda_major: Optional[str] = None,
) -> tuple[Optional[dict], Optional[str]]:
"""Fetch ``repo``'s release and pick the asset for this host. Returns ``(release, asset_name)`` or ``(None, None)`` when the repo has no usable release (fetch failed, or the pinned tag is missing and ``allow_latest`` is False) or no asset for this host, so the caller can fall back. A quota refusal raises ``GitHubRateLimited`` instead: every rung shares that quota."""
try:
@@ -706,12 +720,15 @@ def _resolve_repo_asset(
system = platform.system(),
machine = platform.machine(),
accelerator = accelerator,
+ cuda_major = cuda_major,
)
return release, chosen
def _resolve_with_fallback(
- accelerator: str, token: Optional[str]
+ accelerator: str,
+ token: Optional[str],
+ cuda_major: Optional[str] = None,
) -> tuple[str, Optional[dict], Optional[str]]:
"""Resolve ``(used_repo, release, asset_name)`` for this host across the primary repo and, only when the built-in default is in use and the user did not pin a repo, the upstream fallback. Ordering guarantees reproducibility: a pinned tag is tried EXACTLY on every candidate repo before any repo's unpinned latest, so a mirror missing the pinned release prefers the pinned upstream build over an unpinned mirror-latest. Returns ``(primary, None, None)`` when nothing serves this host. Shared by ``install`` and ``--print-asset`` so both honour the same fallback."""
tag = _pinned_tag()
@@ -740,7 +757,7 @@ def _resolve_with_fallback(
for repo, want_tag, allow_latest in attempts:
release, chosen = _resolve_repo_asset(
- repo, want_tag, accelerator, token, allow_latest = allow_latest
+ repo, want_tag, accelerator, token, allow_latest = allow_latest, cuda_major = cuda_major
)
if release is not None and chosen:
if repo != primary:
@@ -769,6 +786,7 @@ def install(
install_dir: Optional[Path] = None,
accelerator: str = "auto",
token: Optional[str] = None,
+ cuda_major: Optional[str] = None,
) -> Path:
"""Download and extract the prebuilt for this host, returning the sd-cli path. Resolves against the Unsloth mirror (``DEFAULT_REPO``) first; if the mirror cannot serve this host AND the default repo is in use, falls back to leejet upstream so native install still works. Raises ``RuntimeError`` only when neither source has an asset for the host, or the archive has no ``sd-cli``."""
target = install_dir or default_install_dir()
@@ -791,7 +809,7 @@ def install(
f"into your files. Remove or move that directory, or install into a different, empty "
f"location (pass a different --install-dir / set the Unsloth sd.cpp install dir)."
)
- used_repo, release, chosen = _resolve_with_fallback(accelerator, token)
+ used_repo, release, chosen = _resolve_with_fallback(accelerator, token, cuda_major)
if release is None or not chosen:
raise RuntimeError(
@@ -891,6 +909,9 @@ def main(argv: Optional[list[str]] = None) -> int:
"--accelerator", default = "auto", choices = ["auto", "cpu", "vulkan", "rocm", "cuda"]
)
p.add_argument("--install-dir", default = None)
+ p.add_argument(
+ "--cuda-major", default = None, help = "CUDA line the host runtime provides (12 / 13)"
+ )
p.add_argument(
"--print-asset", action = "store_true", help = "resolve + print the asset, don't download"
)
@@ -899,7 +920,9 @@ def main(argv: Optional[list[str]] = None) -> int:
if args.print_asset:
# Same primary/fallback resolution as install(), so a host the mirror skips reports the upstream asset, not a false miss.
try:
- _used, _release, chosen = _resolve_with_fallback(args.accelerator, None)
+ _used, _release, chosen = _resolve_with_fallback(
+ args.accelerator, None, args.cuda_major
+ )
except GitHubRateLimited as exc:
print(f"error: {exc}", file = sys.stderr)
return 2
@@ -910,6 +933,7 @@ def main(argv: Optional[list[str]] = None) -> int:
install(
install_dir = Path(args.install_dir).expanduser() if args.install_dir else None,
accelerator = args.accelerator,
+ cuda_major = args.cuda_major,
)
except RuntimeError as exc:
print(f"error: {exc}", file = sys.stderr)