Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio sd.cpp: verify a new bundle starts before it replaces the installed one; Windows ROCm without the HIP SDK uses Vulkan (#15371)
Daniel Han7d9f122d119c
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 661ef154ada..7c70b2317c0 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -2087,13 +2087,75 @@ def output_shows_decisive_accelerator_failure(text: Optional[str]) -> bool:return any(marker in lowered for marker in _ACCELERATOR_DECISIVE_FAILURE_MARKERS)+# Imported by the Windows ROCm bundle but not shipped in it; only the AMD HIP SDK provides it.+_WINDOWS_ROCM_HOST_DLLS: tuple[str, ...] = ("hipblas.dll",)+_windows_rocm_skip_logged = False+++def _on_windows() -> bool:+ return os.name == "nt"+++def windows_rocm_build_mode() -> str:+ """``UNSLOTH_SD_CPP_WINDOWS_ROCM``: ``auto`` (ROCm only if the HIP SDK is on PATH), ``1`` always, ``0`` never."""+ raw = (os.environ.get("UNSLOTH_SD_CPP_WINDOWS_ROCM", "auto") or "").strip().lower()+ if raw in ("1", "on", "true", "yes", "force"):+ return "force"+ if raw in ("0", "off", "false", "no", "never"):+ return "off"+ return "auto"+++def _windows_dll_search_dirs() -> list[str]:+ dirs: list[str] = []+ system_root = os.environ.get("SystemRoot") or os.environ.get("windir") or r"C:\Windows"+ dirs.append(os.path.join(system_root, "System32"))+ dirs.append(system_root)+ dirs.extend(d.strip().strip('"') for d in os.environ.get("PATH", "").split(os.pathsep))+ return [d for d in dirs if d]+++def windows_hip_runtime_missing_dlls() -> Optional[list[str]]:+ """Missing HIP SDK DLLs, or None off Windows. File search only: loading hipblas.dll here would clash with torch's rocBLAS."""+ if not _on_windows():+ return None+ dirs = _windows_dll_search_dirs()+ missing = []+ for dll in _WINDOWS_ROCM_HOST_DLLS:+ if not any(os.path.isfile(os.path.join(d, dll)) for d in dirs):+ missing.append(dll)+ return missing+++def windows_rocm_build_skipped() -> bool:+ """Whether a Windows ROCm request goes to Vulkan (HIP SDK missing would fail with 0xC0000135)."""+ if not _on_windows() or not sd_cpp_vulkan_fallback_enabled():+ return False+ mode = windows_rocm_build_mode()+ if mode == "force":+ return False+ if mode == "off":+ return True+ return bool(windows_hip_runtime_missing_dlls())++def preferred_accelerator(accelerator: Optional[str], card: Optional[str] = None) -> str:"""``accelerator``, or its fallback once shown unrunnable here. Applied at the TOP of an ensure ladder, so a crashed build is not installed and probed again.- A function of the stored record only, never of the live host: the loader preflight is applied- where the runtime verdict is interpreted, so this stays reproducible."""+ On Windows a ROCm request starts at Vulkan when ``windows_rocm_build_skipped``."""+ global _windows_rocm_skip_loggedchosen = accelerator or "auto"klass = _accelerator_class_of(accelerator) or chosen+ if klass == "rocm" and windows_rocm_build_skipped():+ if not _windows_rocm_skip_logged:+ _windows_rocm_skip_logged = True+ logger.info(+ "sd_cpp.windows_rocm_skipped: using the Vulkan stable-diffusion.cpp build; the ROCm "+ "build needs the AMD HIP SDK runtime (%s) on PATH (UNSLOTH_SD_CPP_WINDOWS_ROCM=1 "+ "to use it anyway)",+ ", ".join(windows_hip_runtime_missing_dlls() or _WINDOWS_ROCM_HOST_DLLS),+ )+ chosen = klass = "vulkan"seen: set[str] = set()# Walk the ladder (rocm -> vulkan -> cpu) past every rung already shown unrunnable.while klass not in seen:@@ -2491,6 +2553,60 @@ def _install_kwargs(accelerator: str) -> dict[str, Any]:return kwargs+def _unrunnable_build(exc: BaseException) -> bool:+ try:+ return isinstance(exc, _installer_module().UnrunnableBuildError)+ except Exception: # noqa: BLE001 -- an installer without the probe raises nothing of the kind+ return False+++def _install_down_the_ladder(_install: Callable[..., Any], accelerator: str) -> tuple[Any, str]:+ """Install ``accelerator``, stepping down (rocm -> vulkan -> cpu) while the loader refuses the bundle.+ Returns ``(path, accelerator installed)``."""+ current = accelerator+ tried: set[str] = set()+ refused: list[str] = []++ def _note_refused(fingerprint: dict) -> None:+ for klass in refused:+ note_accelerator_runtime_failure(klass, proven = True, fingerprint = fingerprint)++ while True:+ try:+ path = _install(**_install_kwargs(current))+ except Exception as exc: # noqa: BLE001+ if not _unrunnable_build(exc):+ if refused:+ _note_refused(_pin_fingerprint())+ raise+ klass = _accelerator_class_of(current)+ tried.add(klass)+ refused.append(klass)+ nxt = fallback_accelerator_for(klass)+ logger.warning(+ "sd_cpp.unrunnable_build: %s; %s",+ exc,+ f"installing the {nxt} build instead" if nxt else "no fallback build to try",+ )+ if not nxt or _accelerator_class_of(nxt) in tried:+ _note_refused(_pin_fingerprint())+ raise+ current = nxt+ continue+ # Keyed on the installed build: a fallback may carry a tag other than the pin.+ if refused:+ _note_refused(_accelerator_fingerprint(path) if path else _pin_fingerprint())+ return path, current+++def _pin_fingerprint() -> dict:+ try:+ want = _installer_module()._pinned_tag()+ except Exception: # noqa: BLE001+ want = None+ return {"bundle": want, **_host_fingerprint()}++def ensure_sd_cpp_binary(*, allow_install: bool = True, accelerator: str = "cpu") -> Optional[str]:"""Never raises: None means no usable binary and tells the router to fall back to diffusers."""found = find_sd_cpp_binary()@@ -2516,7 +2632,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 loadtry:- path = _install(**_install_kwargs(accelerator))+ path, _used = _install_down_the_ladder(_install, accelerator)logger.info("sd-cli installed at %s", path)return str(path)except Exception as exc: # noqa: BLE001 -- download/extract failure -> fall back@@ -2562,7 +2678,7 @@ def ensure_sd_server_binary(if not claimed:return fallback # something is running in there; retry on a later loadtry:- _install(**_install_kwargs(accelerator)) # extracts sd-cli AND sd-server+ _path, accelerator = _install_down_the_ladder(_install, accelerator)except Exception as exc: # noqa: BLE001 -- download/extract failure -> fall backlogger.warning("sd-server auto-install failed: %s", exc)# Also when only the CLI survives: the following ensure_sd_cpp_binary probe would re-download.diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 7f89cccf804..07c1ae30469 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -111,6 +111,11 @@ def _zoo_without_gdn_decode_kernel(monkeypatch):monkeypatch.setattr(ssm_runtime, "_zoo_gdn_decode_kernel_present", lambda: False, raising = False)[email protected](autouse = True)+def _sd_cpp_windows_rocm_ignores_the_host_dlls(monkeypatch):+ monkeypatch.setenv("UNSLOTH_SD_CPP_WINDOWS_ROCM", "1")++@pytest.fixture(autouse = True)def _no_real_mxc_drive_aliases(monkeypatch):# Windows hosts would map real drive letters; MXC tests opt back in.diff --git a/studio/backend/tests/test_sd_cpp_install_verify.py b/studio/backend/tests/test_sd_cpp_install_verify.pynew file mode 100644index 00000000000..392d138c47f--- /dev/null+++ b/studio/backend/tests/test_sd_cpp_install_verify.py@@ -0,0 +1,323 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A new sd.cpp bundle must start before replacing the installed one; Windows ROCm without the HIP SDK uses Vulkan."""++from __future__ import annotations++import io+import os+import re+import sys+import types+import zipfile+from pathlib import Path++import pytest++_STUDIO = Path(__file__).resolve().parents[2]+if str(_STUDIO) not in sys.path:+ sys.path.insert(0, str(_STUDIO))++import install_sd_cpp_prebuilt as sdmod # noqa: E402++_CLI, _SERVER = sdmod._binary_names()+_WIN = sys.platform == "win32"+++def _starting_binary() -> bytes:+ if _WIN:+ return (+ Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "where.exe"+ ).read_bytes()+ return b"#!/bin/sh\necho 'usage: sd-cli [options]'\n"+++def _refused_binary() -> bytes:+ """An executable the loader refuses (Windows: python.exe with its pythonXY.dll import renamed)."""+ if _WIN:+ data = (Path(sys.base_prefix) / "python.exe").read_bytes()+ dll = f"python{sys.version_info[0]}{sys.version_info[1]}".encode()+ patched = re.sub(re.escape(dll) + rb"(?=\.dll)", b"z" * len(dll), data, flags = re.I)+ assert patched != data+ return patched+ return (+ b"#!/bin/sh\necho 'sd-cli: error while loading shared libraries: libhipblas.so.3: "+ b"cannot open shared object file: No such file or directory' >&2\nexit 127\n"+ )+++def _bundle(payload: bytes, subdir: str = "") -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ for name in (_CLI, _SERVER):+ zf.writestr(f"{subdir}{name}", payload)+ zf.writestr(f"{subdir}stable-diffusion.dll", b"payload")+ return buf.getvalue()+++def _names():+ if _WIN:+ return {+ "rocm": "sd-master-0518b34-bin-win-rocm-10.1.0-x64.zip",+ "vulkan": "sd-master-0518b34-bin-win-vulkan-x64.zip",+ }+ return {+ "rocm": "sd-master-0518b34-bin-Linux-Ubuntu-24.04-x86_64-rocm-7.2.1.zip",+ "vulkan": "sd-master-0518b34-bin-Linux-Ubuntu-24.04-x86_64-vulkan.zip",+ }+++def _stub_release(monkeypatch, zips: dict):+ names = _names()+ release = {+ "tag_name": "master-982-0518b34",+ "assets": [+ {"name": names[k], "browser_download_url": f"https://example.invalid/{names[k]}"}+ for k in zips+ ],+ }+ by_name = {names[k]: v for k, v in zips.items()}+ monkeypatch.setenv("UNSLOTH_SD_CPP_TAG", "")+ monkeypatch.setattr(sdmod, "_fetch_release", lambda *a, **k: release)+ monkeypatch.setattr(+ sdmod, "_download", lambda url, dest, **k: dest.write_bytes(by_name[url.rsplit("/", 1)[1]])+ )+ monkeypatch.setattr(sdmod.platform, "system", lambda: "Windows" if _WIN else "Linux")+ monkeypatch.setattr(sdmod.platform, "machine", lambda: "AMD64" if _WIN else "x86_64")+++def _managed_root(tmp_path, monkeypatch) -> Path:+ root = tmp_path / "sd-home" / "stable-diffusion.cpp"+ root.mkdir(parents = True)+ (root / sdmod.OWNERSHIP_MARKER).touch()+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()+ return root+++def _working_vulkan_install(root: Path) -> Path:+ """What the affected host had: the mirror's Vulkan build in its versioned subdirectory."""+ sub = root / "sd-master-982-0518b34-ud331c66-bin-win-vulkan-x64"+ sub.mkdir()+ for name in (_CLI, _SERVER):+ (sub / name).write_bytes(_starting_binary())+ if not _WIN:+ (sub / name).chmod(0o755)+ sdmod._write_install_record(root, accelerator = "vulkan", repo = sdmod.DEFAULT_REPO, tag = "t")+ return sub / _SERVER+++def test_the_loader_refusal_is_read_from_the_exit_status_and_output():+ assert "not found" in sdmod.loader_refusal(0xC0000135)+ # Python reports the NTSTATUS signed on some builds.+ assert sdmod.loader_refusal(0xC0000135 - (1 << 32))+ assert sdmod.loader_refusal(0xC0000139)+ assert sdmod.loader_refusal(+ 127, "sd-cli: error while loading shared libraries: libhipblas.so.3"+ )+ # A process that reached main is not refused, whatever it exits with.+ assert sdmod.loader_refusal(0) is None+ assert sdmod.loader_refusal(1, "unknown option --help") is None+ assert sdmod.loader_refusal(127) is None+ assert sdmod.loader_refusal(None) is None+++def test_probe_reports_a_refused_binary_and_passes_a_starting_one(tmp_path):+ bad = tmp_path / "bad" / _CLI+ good = tmp_path / "good" / _CLI+ for path, data in ((bad, _refused_binary()), (good, _starting_binary())):+ path.parent.mkdir()+ path.write_bytes(data)+ if not _WIN:+ path.chmod(0o755)+ assert sdmod.probe_binary_starts(bad)+ assert sdmod.probe_binary_starts(good) is None+++def test_a_bundle_that_cannot_start_never_replaces_the_working_one(tmp_path, monkeypatch):+ """Regression: a refused ROCm zip must not sweep the working Vulkan build."""+ root = _managed_root(tmp_path, monkeypatch)+ old_server = _working_vulkan_install(root)+ before = old_server.read_bytes()+ _stub_release(monkeypatch, {"rocm": _bundle(_refused_binary())})++ with pytest.raises(RuntimeError, match = "cannot start"):+ sdmod.install(install_dir = root, accelerator = "rocm")++ assert old_server.is_file() and old_server.read_bytes() == before+ assert (old_server.parent / _CLI).is_file()+ # Nothing of the refused bundle reached the tree, and its record still names the working build.+ assert not (root / _CLI).exists() and not (root / _SERVER).exists()+ assert sdmod.read_install_record(root).get("accelerator") == "vulkan"+ assert not list(root.parent.glob(".sd-cpp-verify-*"))+++def test_the_refusal_names_what_was_asked_for(tmp_path, monkeypatch):+ root = _managed_root(tmp_path, monkeypatch)+ _stub_release(monkeypatch, {"rocm": _bundle(_refused_binary())})+ with pytest.raises(sdmod.UnrunnableBuildError) as info:+ sdmod.install(install_dir = root, accelerator = "rocm")+ assert info.value.accelerator == "rocm"+ assert info.value.asset == _names()["rocm"]+++def test_a_bundle_that_starts_still_replaces_the_previous_one(tmp_path, monkeypatch):+ root = _managed_root(tmp_path, monkeypatch)+ old_server = _working_vulkan_install(root)+ _stub_release(monkeypatch, {"rocm": _bundle(_starting_binary())})++ cli = sdmod.install(install_dir = root, accelerator = "rocm")++ assert cli == root / _CLI+ assert not old_server.exists()+ assert sdmod.read_install_record(root).get("accelerator") == "rocm"+ assert not list(root.parent.glob(".sd-cpp-verify-*"))+++def test_the_kill_switch_restores_the_unverified_install(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_SD_CPP_VERIFY_INSTALL", "0")+ root = _managed_root(tmp_path, monkeypatch)+ old_server = _working_vulkan_install(root)+ _stub_release(monkeypatch, {"rocm": _bundle(_refused_binary())})++ sdmod.install(install_dir = root, accelerator = "rocm")++ assert not old_server.exists()+ assert (root / _SERVER).is_file()+++def test_cuda_bundles_are_not_probed(tmp_path):+ # They load the host / llama.cpp CUDA runtime the backend adds at spawn; a bare probe would refuse them.+ assert sdmod._should_verify("sd-master-x-bin-win-cuda12-x64.zip") is False+ assert sdmod._should_verify("sd-master-x-bin-win-rocm-10.1.0-x64.zip") is True+++# --- backend: the Windows ROCm request and the install ladder ---------------------------------+++def fake_settings(monkeypatch):+ from storage import studio_db++ store: dict = {}+ monkeypatch.setattr(+ studio_db, "get_app_setting", lambda key, fallback = None: store.get(key, fallback)+ )+ monkeypatch.setattr(+ studio_db,+ "upsert_app_settings",+ lambda settings, **_k: store.update(settings) or dict(store),+ )+ return store+++def backend(monkeypatch, fake_settings):+ from core.inference import sd_cpp_backend as bk++ monkeypatch.setattr(bk, "_accelerator_runtime_failures", {}, raising = False)+ monkeypatch.setattr(+ bk,+ "_HOST_FINGERPRINT_MEMO",+ {"runtime": "7.1", "gpus": ["AMD Radeon 8060S"]},+ raising = False,+ )+ monkeypatch.setattr(bk, "_failed_accelerator_upgrades", set(), raising = False)+ monkeypatch.setattr(bk, "_failed_pin_upgrades", set(), raising = False)+ monkeypatch.delenv("UNSLOTH_DIFFUSION_SD_CPP_VULKAN_FALLBACK", raising = False)+ return bk+++def windows_host(monkeypatch, backend, tmp_path):+ """A Windows host whose loader search path is ``dirs``; add hipblas.dll to one to install the HIP SDK."""+ sdk = tmp_path / "hip-sdk-bin"+ system32 = tmp_path / "System32"+ sdk.mkdir()+ system32.mkdir()+ # The Adrenalin driver puts amdhip64 in System32; hipblas only comes with the HIP SDK.+ (system32 / "amdhip64_7.dll").write_bytes(b"")+ monkeypatch.delenv("UNSLOTH_SD_CPP_WINDOWS_ROCM", raising = False)+ monkeypatch.setattr(backend, "_on_windows", lambda: True, raising = False)+ monkeypatch.setattr(+ backend, "_windows_dll_search_dirs", lambda: [str(system32), str(sdk)], raising = False+ )+ return types.SimpleNamespace(sdk = sdk, system32 = system32)+++def test_windows_rocm_without_the_hip_sdk_starts_at_vulkan(windows_host, backend):+ assert backend.preferred_accelerator("rocm") == "vulkan"+++def test_windows_rocm_with_the_hip_sdk_on_path_keeps_rocm(windows_host, backend):+ (windows_host.sdk / "hipblas.dll").write_bytes(b"")+ assert backend.preferred_accelerator("rocm") == "rocm"+++ "env,value,want",+ [+ ("UNSLOTH_SD_CPP_WINDOWS_ROCM", "1", "rocm"),+ ("UNSLOTH_SD_CPP_WINDOWS_ROCM", "0", "vulkan"),+ ("UNSLOTH_DIFFUSION_SD_CPP_VULKAN_FALLBACK", "0", "rocm"),+ ],+)+def test_windows_rocm_kill_switches(windows_host, backend, monkeypatch, env, value, want):+ monkeypatch.setenv(env, value)+ assert backend.preferred_accelerator("rocm") == want+++def test_other_hosts_and_accelerators_are_untouched(backend, monkeypatch):+ monkeypatch.delenv("UNSLOTH_SD_CPP_WINDOWS_ROCM", raising = False)+ monkeypatch.setattr(backend, "_on_windows", lambda: False, raising = False)+ assert backend.preferred_accelerator("rocm") == "rocm"+ monkeypatch.setattr(backend, "_on_windows", lambda: True, raising = False)+ monkeypatch.setattr(backend, "_windows_dll_search_dirs", lambda: [], raising = False)+ assert backend.preferred_accelerator("cuda") == "cuda"+ assert backend.preferred_accelerator("vulkan") == "vulkan"+++def test_an_unstartable_rocm_bundle_falls_to_the_vulkan_build(tmp_path, monkeypatch, backend):+ """A fresh install with a refused ROCm bundle ends on Vulkan and records the host."""+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()+ root = sdmod.default_install_dir()+ _stub_release(+ monkeypatch,+ {"rocm": _bundle(_refused_binary()), "vulkan": _bundle(_starting_binary(), "vk/")},+ )+ monkeypatch.setattr(backend, "_managed_tree_in_use", lambda: False)+ monkeypatch.setattr(backend, "is_managed_binary", lambda _b: True)++ server = backend.ensure_sd_server_binary(accelerator = "rocm")++ assert server is not None and Path(server) == root / "vk" / _SERVER+ assert sdmod.read_install_record(root).get("accelerator") == "vulkan"+ assert backend.accelerator_runtime_failed("rocm") is True+ assert backend.preferred_accelerator("rocm") == "vulkan"+ cli = backend.ensure_sd_cpp_binary(accelerator = backend.preferred_accelerator("rocm"))+ assert cli is not None and Path(cli) == root / "vk" / _CLI+++def test_the_refusal_record_survives_a_fallback_from_another_release(+ tmp_path, monkeypatch, backend+):+ """The record applies even when the Vulkan fallback comes from a non-pinned release."""+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "sd-home" / "studio"))+ sdmod._INSTALLED_ACCELERATOR_MEMO.clear()+ root = sdmod.default_install_dir()+ _stub_release(+ monkeypatch,+ {"rocm": _bundle(_refused_binary()), "vulkan": _bundle(_starting_binary(), "vk/")},+ )+ monkeypatch.setattr(sdmod, "_pinned_tag", lambda: "master-982-0518b34-ud331c66")+ monkeypatch.setattr(backend, "_managed_tree_in_use", lambda: False)+ monkeypatch.setattr(backend, "is_managed_binary", lambda _b: True)++ server = backend.ensure_sd_server_binary(accelerator = "rocm")++ assert server is not None+ assert sdmod.read_install_record(root).get("tag") != "master-982-0518b34-ud331c66"+ assert backend.accelerator_runtime_failed("rocm") is True+ assert backend.preferred_accelerator("rocm") == "vulkan"diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.pyindex 24a71f40443..b85613c4195 100644--- a/studio/install_sd_cpp_prebuilt.py+++ b/studio/install_sd_cpp_prebuilt.py@@ -687,6 +687,171 @@ def _maybe_fetch_windows_cudart(release: dict, chosen: str, target: Path) -> Nondest.unlink(missing_ok = True)+class UnrunnableBuildError(RuntimeError):+ """The OS loader refused the new bundle in a scratch dir; raised before the managed tree is touched."""++ def __init__(self, message: str, *, accelerator: str, asset: str, tag: Optional[str]) -> None:+ super().__init__(message)+ self.accelerator = accelerator+ self.asset = asset+ self.tag = tag+++# Windows NTSTATUS exits of a process the loader killed before main(): it prints nothing.+_WINDOWS_LOADER_FAILURES = {+ 0xC0000135: "a DLL it imports was not found", # STATUS_DLL_NOT_FOUND+ 0xC0000139: "a DLL it imports is the wrong build", # STATUS_ENTRYPOINT_NOT_FOUND+ 0xC0000142: "a DLL it imports failed to initialise", # STATUS_DLL_INIT_FAILED+}+_POSIX_LOADER_MARKERS = ("error while loading shared libraries", "Library not loaded")+++def verify_install_enabled() -> bool:+ """``UNSLOTH_SD_CPP_VERIFY_INSTALL=0`` skips probing the new bundle before install."""+ raw = (os.environ.get("UNSLOTH_SD_CPP_VERIFY_INSTALL", "1") or "").strip().lower()+ return raw not in ("0", "off", "false", "no")+++def loader_refusal(returncode: Optional[int], output: str = "") -> Optional[str]:+ """Loader refusal reason, else None. Any exit after reaching ``main`` (sd-cli may exit 1 on ``--help``) counts as starting."""+ if returncode is None:+ return None+ code = returncode + (1 << 32) if returncode < 0 else returncode+ if code in _WINDOWS_LOADER_FAILURES:+ return f"{_WINDOWS_LOADER_FAILURES[code]} (exit 0x{code:08X})"+ text = output or ""+ if any(marker in text for marker in _POSIX_LOADER_MARKERS):+ line = next(+ (ln.strip() for ln in text.splitlines() if any(m in ln for m in _POSIX_LOADER_MARKERS)),+ "",+ )+ return f"the dynamic loader refused it: {line}"[:400]+ return None+++def _probe_env(binary: Path) -> dict:+ env = dict(os.environ)+ if sys.platform == "win32":+ var = "PATH"+ elif sys.platform == "darwin":+ var = "DYLD_LIBRARY_PATH"+ else:+ var = "LD_LIBRARY_PATH"+ existing = env.get(var, "")+ env[var] = str(binary.parent) + (os.pathsep + existing if existing else "")+ return env+++def _windows_error_mode_suppressed():+ """On Windows, suppress the missing-DLL dialog so a refusal returns an exit status."""+ import contextlib++ @contextlib.contextmanager+ def _cm():+ if sys.platform != "win32":+ yield+ return+ try:+ import ctypes+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]+ # SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX+ previous = kernel32.SetErrorMode(0x0001 | 0x0002 | 0x8000)+ except Exception: # noqa: BLE001 -- best effort; the probe still runs+ yield+ return+ try:+ yield+ finally:+ try:+ kernel32.SetErrorMode(previous)+ except Exception: # noqa: BLE001+ pass++ return _cm()+++def probe_binary_starts(binary: Path, *, timeout: float = 30.0) -> Optional[str]:+ """Run ``binary --help``; return the loader's refusal, or None (started, or no verdict)."""+ import subprocess++ kwargs: dict = {}+ if sys.platform == "win32":+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0)+ try:+ with _windows_error_mode_suppressed():+ proc = subprocess.run(+ [str(binary), "--help"],+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = timeout,+ env = _probe_env(binary),+ stdin = subprocess.DEVNULL,+ **kwargs,+ )+ except Exception: # noqa: BLE001 -- not exec-able / timeout: no verdict either way+ return None+ return loader_refusal(proc.returncode, (proc.stdout or "") + (proc.stderr or ""))+++def _should_verify(chosen: str) -> bool:+ """Skip CUDA: its runtime is added at spawn, so a bare probe would refuse a working build."""+ return verify_install_enabled() and "cuda" not in chosen.lower()+++def _verify_bundle_starts(+ archive: Path, target: Path, *, accelerator: str, chosen: str, tag: Optional[str]+) -> None:+ """Start the archive's executables in a scratch dir; raise ``UnrunnableBuildError`` on a loader refusal."""+ import tempfile++ names = _binary_names()+ refusal: Optional[tuple[str, str]] = None+ scratch: Optional[Path] = None+ try:+ try:+ # Beside, never inside, the managed tree: the finders rglob it.+ scratch = Path(tempfile.mkdtemp(prefix = ".sd-cpp-verify-", dir = str(target.parent)))+ with zipfile.ZipFile(archive) as zf:+ _safe_extractall(zf, scratch)+ except Exception as exc: # noqa: BLE001+ print(f"sd-cli: could not verify {chosen} before installing it ({exc})", flush = True)+ return+ for name in names:+ for found in sorted(scratch.rglob(name)):+ if not found.is_file():+ continue+ if sys.platform != "win32":+ try:+ _make_executable(found)+ except OSError:+ continue+ why = probe_binary_starts(found)+ if why:+ refusal = (name, why)+ break+ if refusal:+ break+ finally:+ if scratch is not None:+ shutil.rmtree(scratch, ignore_errors = True)+ if refusal:+ name, why = refusal+ hint = ""+ if sys.platform == "win32" and accelerator_class(accelerator) == "rocm":+ hint = (+ " The ROCm build needs the AMD HIP SDK runtime (hipblas.dll, rocblas.dll) on PATH."+ )+ raise UnrunnableBuildError(+ f"{chosen}: {name} cannot start on this host: {why}. Kept the existing install.{hint}",+ accelerator = accelerator,+ asset = chosen,+ tag = tag,+ )+ print(f"verified {chosen} starts on this host", flush = True)++def _resolve_repo_asset(repo: str,tag: Optional[str],@@ -823,6 +988,15 @@ def install(try:_download(url, archive)_verify_sha256(archive, asset.get("digest"))+ # Probe before touching the tree so a refused bundle never sweeps a working one.+ if _should_verify(chosen):+ _verify_bundle_starts(+ archive,+ target,+ accelerator = accelerator,+ chosen = chosen,+ tag = release.get("tag_name"),+ )print("extracting ...", flush = True)with zipfile.ZipFile(archive) as zf:supplied = _archive_binary_paths(zf, target)