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: give the MiniMax-H3 sd.cpp engine a CUDA-12 cuDNN for fused attention on sm80+ Linux (#12662)

Daniel Han858afa7d4a30
diff --git a/studio/backend/core/inference/sd_cpp_cudnn.py b/studio/backend/core/inference/sd_cpp_cudnn.py
new file mode 100644
index 00000000000..b080133a120
--- /dev/null
+++ b/studio/backend/core/inference/sd_cpp_cudnn.py
@@ -0,0 +1,599 @@
+# 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 CUDA 12 cuDNN for sd.cpp fork builds with cuDNN attention (sm80+ Linux), named to the child via GGML_CUDA_CUDNN_LIB.
+
+torch cu130's cuDNN (CUDA 13) loads in a CUDA 12 binary but builds no plan. Installed with ``--target`` outside the venv:
+the cu12 and cu13 wheels both write ``nvidia/cudnn/lib/libcudnn.so.9``. Never loaded into this process.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+CUDNN_INSTALL_ENV = "UNSLOTH_SD_CPP_CUDNN"
+GGML_CUDNN_LIB_ENV = "GGML_CUDA_CUDNN_LIB"
+GGML_CUDNN_ATTN_ENV = "GGML_CUDA_CUDNN_ATTN"
+# The fork never opens cuDNN below cc 8.0.
+CUDNN_MIN_CC = (8, 0)
+
+_CUDNN_BUILD_MARKER = b"GGML_CUDA_CUDNN_LIB"
+_CUDART_MARKERS = {12: b"libcudart.so.12\x00", 13: b"libcudart.so.13\x00"}
+
+
+@dataclass(frozen = True)
+class CudnnRuntime:
+ """Exact pins, never a floor: another cuDNN release can pick other SDPA engines, and only this one was measured."""
+
+ cuda_major: int
+ cudnn_package: str
+ cudnn_version: str
+ nvrtc_package: str
+ nvrtc_version: str
+
+ @property
+ def cudnn_numeric(self) -> int:
+ major, minor, patch = (int(x) for x in self.cudnn_version.split(".")[:3])
+ return major * 10000 + minor * 100 + patch
+
+ @property
+ def dirname(self) -> str:
+ return f"cu{self.cuda_major}-cudnn{self.cudnn_version}-nvrtc{self.nvrtc_version}"
+
+ def requirements(self) -> list[str]:
+ return [
+ f"{self.cudnn_package}=={self.cudnn_version}",
+ f"{self.nvrtc_package}=={self.nvrtc_version}",
+ ]
+
+
+# cuDNN's runtime-compiled engines find NVRTC via RUNPATH ($ORIGIN/../../cuda_nvrtc/lib); cuBLAS is the prebuilt's own.
+CUDNN_RUNTIMES: dict[int, CudnnRuntime] = {
+ 12: CudnnRuntime(12, "nvidia-cudnn-cu12", "9.27.0.42", "nvidia-cuda-nvrtc-cu12", "12.8.93"),
+}
+
+_LIB_RELPATH = Path("nvidia") / "cudnn" / "lib" / "libcudnn.so.9"
+_NVRTC_RELPATH = Path("nvidia") / "cuda_nvrtc" / "lib" / "libnvrtc.so.12"
+_MARKER_NAME = "unsloth-cudnn.json"
+_MIN_FREE_BYTES = 4 << 30
+_INSTALL_TIMEOUT_S = 1800
+_VERIFY_TIMEOUT_S = 120
+_LOCK_TIMEOUT_S = _INSTALL_TIMEOUT_S + _VERIFY_TIMEOUT_S + 120
+_PYPI_PROBE_URL = "https://pypi.org/simple/nvidia-cudnn-cu12/"
+_CANCELLED = "cancelled"
+
+_SCAN_MEMO: dict[tuple[str, int, int], tuple[bool, Optional[int]]] = {}
+_SCAN_LOCK = threading.Lock()
+_INSTALL_LOCK = threading.Lock()
+# Never retry a 0.85 GB download that just failed in this process.
+_FAILED: dict[int, str] = {}
+
+StatusCb = Optional[Callable[[str], None]]
+
+
+class InstallCancelled(Exception):
+ """Not memoised: the next load installs."""
+
+
+class _Refused(str):
+ """Disk / network preflight refusal: rechecked next load, never memoised."""
+
+
+def _off(value: Optional[str]) -> bool:
+ return str(value or "").strip().lower() in ("0", "false", "no", "off")
+
+
+def install_enabled(environ: Optional[dict] = None) -> bool:
+ environ = os.environ if environ is None else environ
+ return not _off(environ.get(CUDNN_INSTALL_ENV))
+
+
+def _scan_file(path: Path) -> tuple[bool, Optional[int]]:
+ try:
+ st = path.stat()
+ except OSError:
+ return False, None
+ key = (str(path.resolve()), st.st_size, st.st_mtime_ns)
+ with _SCAN_LOCK:
+ if key in _SCAN_MEMO:
+ return _SCAN_MEMO[key]
+ needles = [_CUDNN_BUILD_MARKER, *_CUDART_MARKERS.values()]
+ overlap = max(len(n) for n in needles)
+ found: set[bytes] = set()
+ try:
+ with path.open("rb") as fh:
+ tail = b""
+ while True:
+ chunk = fh.read(8 << 20)
+ if not chunk:
+ break
+ window = tail + chunk
+ for needle in needles:
+ if needle not in found and needle in window:
+ found.add(needle)
+ tail = window[-overlap:]
+ except OSError:
+ return False, None
+ major = next((m for m, n in _CUDART_MARKERS.items() if n in found), None)
+ result = (_CUDNN_BUILD_MARKER in found, major)
+ with _SCAN_LOCK:
+ _SCAN_MEMO[key] = result
+ return result
+
+
+def binary_cudnn_build(binary: Optional[str]) -> tuple[bool, Optional[int]]:
+ """(built with cuDNN attention, linked CUDA major); ggml may be static or a ``libggml*.so`` beside the binary."""
+ if not binary:
+ return False, None
+ path = Path(binary)
+ carries, major = _scan_file(path)
+ if carries and major is not None:
+ return carries, major
+ try:
+ siblings = sorted(path.resolve().parent.glob("libggml*.so*"))
+ except OSError:
+ siblings = []
+ for lib in siblings:
+ lib_carries, lib_major = _scan_file(lib)
+ carries = carries or lib_carries
+ major = major or lib_major
+ if major is None:
+ for m in _CUDART_MARKERS:
+ if (path.resolve().parent / f"libcudart.so.{m}").exists():
+ major = m
+ break
+ return carries, major
+
+
+def managed_root() -> Path:
+ from utils.paths.storage_roots import studio_bin_root
+ return studio_bin_root() / "sd-cpp-cudnn"
+
+
+def _verified_library(directory: Path, runtime: CudnnRuntime) -> Optional[str]:
+ try:
+ marker = json.loads((directory / _MARKER_NAME).read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ return None
+ if marker.get("requirements") != runtime.requirements():
+ return None
+ lib = directory / _LIB_RELPATH
+ if not lib.is_file() or not (directory / _NVRTC_RELPATH).is_file():
+ return None
+ return str(lib)
+
+
+def installed_library(runtime: CudnnRuntime, root: Optional[Path] = None) -> Optional[str]:
+ return _verified_library((root or managed_root()) / runtime.dirname, runtime)
+
+
+def _uv_executable() -> Optional[str]:
+ try:
+ from utils.mlx_repair import _uv_executable as find_uv
+ return find_uv()
+ except Exception: # noqa: BLE001
+ return shutil.which("uv")
+
+
+def _child_env() -> dict[str, str]:
+ try:
+ from utils.child_stdio import utf8_child_env
+ from utils.native_path_leases import child_env_without_native_path_secret
+ return utf8_child_env(child_env_without_native_path_secret())
+ except Exception: # noqa: BLE001
+ env = dict(os.environ)
+ env["PYTHONIOENCODING"] = "utf-8"
+ return env
+
+
+def _reachable(url: str) -> bool:
+ try:
+ from .diffusion_nvfp4_install import _reachable as probe
+ return probe(url)
+ except Exception: # noqa: BLE001 - an unanswerable probe means no network
+ return False
+
+
+def _installer_config(uv: Optional[str]) -> dict[str, Any]:
+ try:
+ from .diffusion_nvfp4_install import _installer_config as read
+ return read(uv, subprocess.run)
+ except Exception: # noqa: BLE001 - unreadable config: let the installer decide
+ return {"mirror": True, "unprobed": False}
+
+
+def install_command(
+ runtime: CudnnRuntime,
+ target: Path,
+ uv: Optional[str],
+ *,
+ own_index: bool = False,
+) -> list[str]:
+ try:
+ # uv ignores PIP_INDEX_URL and pip ignores uv's; this carries each over.
+ from .diffusion_nvfp4_install import _installer_prefix
+ cmd = _installer_prefix(uv, own_index = own_index)
+ except Exception: # noqa: BLE001
+ cmd = (
+ [uv, "pip", "install", "--python", sys.executable]
+ if uv
+ else [sys.executable, "-m", "pip", "install", "--disable-pip-version-check"]
+ )
+ if not uv:
+ cmd = [*cmd, "--no-input"]
+ return [
+ *cmd,
+ "--target",
+ str(target),
+ "--no-deps",
+ "--only-binary",
+ ":all:",
+ *runtime.requirements(),
+ ]
+
+
+def _verify_command(lib: Path) -> list[str]:
+ # Fresh interpreter: a CUDA 12 cuDNN must never be mapped beside torch's own.
+ code = (
+ "import ctypes,sys;"
+ "h=ctypes.CDLL(sys.argv[1],mode=ctypes.RTLD_LOCAL);"
+ "f=h.cudnnGetVersion;f.restype=ctypes.c_size_t;print(f())"
+ )
+ return [sys.executable, "-c", code, str(lib)]
+
+
+def _venv_snapshot() -> dict[str, str]:
+ try:
+ import importlib.metadata as md
+ except Exception: # noqa: BLE001
+ return {}
+ out: dict[str, str] = {}
+ for dist in md.distributions():
+ name = str(dist.metadata.get("Name") or "").lower()
+ if name == "torch" or name.startswith("nvidia-"):
+ out[name] = str(dist.version)
+ return out
+
+
+def _redact(text: str) -> str:
+ # Index URLs in installer output can carry credentials.
+ try:
+ from utils.log_redaction import redact_log_text
+ return redact_log_text(text)
+ except Exception: # noqa: BLE001
+ return re.sub(r"://[^/\s@]+@", "://***@", text)
+
+
+def _kill_tree(proc: subprocess.Popen) -> None:
+ try:
+ os.killpg(proc.pid, 9)
+ except Exception: # noqa: BLE001
+ try:
+ proc.kill()
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ proc.communicate(timeout = 10)
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _run(
+ cmd: list[str],
+ timeout: int,
+ cancel_event: Optional[threading.Event] = None,
+) -> tuple[bool, str]:
+ env = _child_env()
+ # A linked target breaks when uv's cache is pruned.
+ env["UV_LINK_MODE"] = "copy"
+ try:
+ proc = subprocess.Popen(
+ cmd,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ env = env,
+ start_new_session = True,
+ )
+ except Exception as exc: # noqa: BLE001
+ return False, f"{type(exc).__name__}: {exc}"
+ deadline = time.monotonic() + timeout
+ while True:
+ try:
+ out, _ = proc.communicate(timeout = 0.5)
+ break
+ except subprocess.TimeoutExpired:
+ if cancel_event is not None and cancel_event.is_set():
+ _kill_tree(proc)
+ raise InstallCancelled()
+ if time.monotonic() >= deadline:
+ _kill_tree(proc)
+ return False, f"timed out after {timeout}s"
+ return proc.returncode == 0, _redact((out or "").strip()[-2000:])
+
+
+def _file_lock(path: Path):
+ try:
+ from filelock import FileLock
+ except ImportError:
+ return None
+ return FileLock(str(path))
+
+
+def ensure_library(
+ runtime: CudnnRuntime,
+ *,
+ allow_install: bool = True,
+ status_cb: StatusCb = None,
+ root: Optional[Path] = None,
+ cancel_event: Optional[threading.Event] = None,
+) -> tuple[Optional[str], Optional[str]]:
+ """``(library, None)`` or ``(None, why not)``; a failure leaves sd.cpp on its ggml kernels."""
+ root = root or managed_root()
+ dest = root / runtime.dirname
+ found = _verified_library(dest, runtime)
+ if found:
+ return found, None
+ if not allow_install:
+ return None, "the CUDA 12 cuDNN is not installed and this load does not download"
+ if not install_enabled():
+ return None, f"{CUDNN_INSTALL_ENV}=0"
+ if runtime.cuda_major in _FAILED:
+ return None, _FAILED[runtime.cuda_major]
+ with _INSTALL_LOCK:
+ found = _verified_library(dest, runtime)
+ if found:
+ return found, None
+ if runtime.cuda_major in _FAILED:
+ return None, _FAILED[runtime.cuda_major]
+ try:
+ root.mkdir(parents = True, exist_ok = True)
+ except OSError as exc:
+ return None, f"cannot create {root.name}: {exc}"
+ lock = _file_lock(root / ".install.lock")
+ if lock is not None:
+ deadline = time.monotonic() + _LOCK_TIMEOUT_S
+ while True:
+ try:
+ lock.acquire(timeout = 1)
+ break
+ except Exception as exc: # noqa: BLE001
+ if type(exc).__name__ != "Timeout":
+ return None, _redact(f"cannot lock {root.name}: {exc}")
+ if cancel_event is not None and cancel_event.is_set():
+ return None, _CANCELLED
+ if time.monotonic() >= deadline:
+ return None, "another Studio process is installing cuDNN"
+ try:
+ found = _verified_library(dest, runtime)
+ if found:
+ return found, None
+ try:
+ reason = _install_locked(runtime, root, dest, status_cb, cancel_event)
+ except InstallCancelled:
+ return None, _CANCELLED
+ found = _verified_library(dest, runtime)
+ if found:
+ return found, None
+ if isinstance(reason, _Refused):
+ return None, str(reason)
+ reason = reason or "the installed cuDNN failed verification"
+ _FAILED[runtime.cuda_major] = reason
+ return None, reason
+ finally:
+ if lock is not None:
+ try:
+ lock.release()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def _install_locked(
+ runtime: CudnnRuntime,
+ root: Path,
+ dest: Path,
+ status_cb: StatusCb,
+ cancel_event: Optional[threading.Event] = None,
+) -> Optional[str]:
+ try:
+ free = shutil.disk_usage(root).free
+ except OSError:
+ free = None
+ if free is not None and free < _MIN_FREE_BYTES:
+ return _Refused(
+ f"needs {_MIN_FREE_BYTES >> 30} GiB free beside the Studio home, {free / 2**30:.1f} GiB free"
+ )
+ uv = _uv_executable()
+ config = _installer_config(uv)
+ if not (config.get("mirror") or config.get("unprobed")) and not _reachable(_PYPI_PROBE_URL):
+ return _Refused("pypi.org is not reachable")
+ staging = Path(tempfile.mkdtemp(prefix = ".staging-", dir = str(root)))
+ try:
+ before = _venv_snapshot()
+ msg = f"Installing {', '.join(runtime.requirements())} for sd.cpp cuDNN attention"
+ logger.info("sd_cpp.cudnn: %s into %s", msg, dest)
+ if status_cb is not None:
+ try:
+ status_cb(msg)
+ except Exception: # noqa: BLE001
+ pass
+ cmd = install_command(runtime, staging, uv, own_index = bool(config.get("own_index")))
+ ok, output = _run(cmd, _INSTALL_TIMEOUT_S, cancel_event)
+ after = _venv_snapshot()
+ if before != after:
+ drift = {
+ k: (before.get(k), after.get(k))
+ for k in set(before) | set(after)
+ if before.get(k) != after.get(k)
+ }
+ logger.error("sd_cpp.cudnn: the install changed this environment: %s", drift)
+ return f"the install changed this environment ({sorted(drift)})"
+ if not ok:
+ return f"install failed: {output[-400:]}"
+ lib = staging / _LIB_RELPATH
+ if not lib.is_file() or not (staging / _NVRTC_RELPATH).is_file():
+ return "install finished without libcudnn.so.9 and libnvrtc.so.12"
+ ok, output = _run(_verify_command(lib), _VERIFY_TIMEOUT_S, cancel_event)
+ version = output.strip().splitlines()[-1] if ok and output.strip() else ""
+ if not ok or not version.isdigit() or int(version) != runtime.cudnn_numeric:
+ return f"verification failed: libcudnn.so.9 reports {version or output[-200:]!r}, expected {runtime.cudnn_numeric}"
+ (staging / _MARKER_NAME).write_text(
+ json.dumps(
+ {"requirements": runtime.requirements(), "cudnn_version": int(version)}, indent = 1
+ ),
+ encoding = "utf-8",
+ )
+ if dest.exists():
+ shutil.rmtree(dest, ignore_errors = True)
+ os.replace(staging, dest)
+ logger.info("sd_cpp.cudnn: cuDNN %s ready at %s", version, dest)
+ return None
+ finally:
+ if staging.exists():
+ shutil.rmtree(staging, ignore_errors = True)
+
+
+# The fork prints these once per process / shape.
+
+_LOADED_RE = re.compile(r"cuDNN (\d+) loaded from \S+ for attention")
+_PLAN_RE = re.compile(r"cuDNN SDPA plan b=\d+ hq=\d+ hk=\d+ sq=(\d+) skv=(\d+) d=(\d+)")
+_NO_PLAN_RE = re.compile(r"no cuDNN SDPA plan for")
+_EXEC_FAIL_RE = re.compile(r"cuDNN SDPA execute failed")
+_TOO_OLD_RE = re.compile(r"reports cuDNN \d+, need 9\.0 or newer")
+
+STATE_READY = "ready" # library named to the child, no render seen yet
+STATE_ENGAGED = "engaged"
+STATE_FALLBACK = "fallback"
+STATE_UNAVAILABLE = "unavailable" # eligible, but no CUDA 12 cuDNN could be provided
+STATE_OFF = "off"
+
+
+@dataclass
+class CudnnAttention:
+ state: Optional[str] = None
+ reason: Optional[str] = None
+ env: tuple[tuple[str, str], ...] = ()
+ cudnn_version: Optional[int] = None
+ shapes: set = field(default_factory = set)
+ _render: dict = field(default_factory = dict)
+ _lock: threading.Lock = field(default_factory = threading.Lock, repr = False)
+
+ def begin_render(self) -> None:
+ with self._lock:
+ self._render = {"loaded": False, "plans": 0, "fallbacks": 0}
+
+ def feed(self, line: str) -> None:
+ if (
+ self.state is None
+ or self.state in (STATE_UNAVAILABLE, STATE_OFF)
+ or "cuDNN" not in line
+ ):
+ return
+ with self._lock:
+ m = _LOADED_RE.search(line)
+ if m:
+ self._render["loaded"] = True
+ self.cudnn_version = int(m.group(1))
+ return
+ m = _PLAN_RE.search(line)
+ if m:
+ self._render["plans"] = self._render.get("plans", 0) + 1
+ self.shapes.add(tuple(int(g) for g in m.groups()))
+ self.state, self.reason = STATE_ENGAGED, None
+ return
+ if _EXEC_FAIL_RE.search(line):
+ self._render["fallbacks"] = self._render.get("fallbacks", 0) + 1
+ self.state, self.reason = (
+ STATE_FALLBACK,
+ "cuDNN attention failed to run; the ggml kernels ran",
+ )
+ return
+ if _NO_PLAN_RE.search(line) or _TOO_OLD_RE.search(line):
+ self._render["fallbacks"] = self._render.get("fallbacks", 0) + 1
+
+ def end_render(self, ok: bool = True) -> None:
+ """A reused sd-server prints nothing again, so only a still-``ready`` state settles here."""
+ with self._lock:
+ seen = self._render
+ self._render = {}
+ if not ok or self.state != STATE_READY:
+ return
+ if seen.get("plans"):
+ self.state, self.reason = STATE_ENGAGED, None
+ elif seen.get("fallbacks"):
+ self.state, self.reason = (
+ STATE_FALLBACK,
+ "cuDNN built no attention plan; the ggml kernels ran",
+ )
+ elif not seen.get("loaded"):
+ self.state, self.reason = STATE_FALLBACK, "sd.cpp did not load the cuDNN library"
+
+ def status_fields(self) -> dict[str, Any]:
+ return {"sd_cpp_cudnn_attention": self.state, "sd_cpp_cudnn_reason": self.reason}
+
+
+def plan_cudnn_attention(
+ binary: Optional[str],
+ cuda_cc: "Optional[tuple[int, int]]",
+ *,
+ allow_install: bool = True,
+ status_cb: StatusCb = None,
+ platform: Optional[str] = None,
+ environ: Optional[dict] = None,
+ root: Optional[Path] = None,
+ cancel_event: Optional[threading.Event] = None,
+) -> CudnnAttention:
+ """Inert (state None, no env) unless Linux, a cuDNN-attention build, a known cc >= 8.0 and a tested CUDA major."""
+ platform = sys.platform if platform is None else platform
+ environ = os.environ if environ is None else environ
+ if not platform.startswith("linux") or not binary or cuda_cc is None:
+ return CudnnAttention()
+ if tuple(cuda_cc) < CUDNN_MIN_CC:
+ return CudnnAttention()
+ carries, major = binary_cudnn_build(binary)
+ if not carries:
+ return CudnnAttention()
+ if _off(environ.get(GGML_CUDNN_ATTN_ENV)):
+ return CudnnAttention(STATE_OFF, f"{GGML_CUDNN_ATTN_ENV}=0")
+ user_lib = str(environ.get(GGML_CUDNN_LIB_ENV) or "").strip()
+ if user_lib:
+ return CudnnAttention(STATE_READY, f"{GGML_CUDNN_LIB_ENV} set by the user")
+ runtime = CUDNN_RUNTIMES.get(major) if major is not None else None
+ if runtime is None:
+ return CudnnAttention(
+ STATE_UNAVAILABLE,
+ f"no tested cuDNN runtime for a CUDA {major if major is not None else 'unknown'} build",
+ )
+ if not install_enabled(environ):
+ return CudnnAttention(STATE_OFF, f"{CUDNN_INSTALL_ENV}=0")
+ try:
+ lib, reason = ensure_library(
+ runtime,
+ allow_install = allow_install,
+ status_cb = status_cb,
+ root = root,
+ cancel_event = cancel_event,
+ )
+ except Exception as exc: # noqa: BLE001 - eligible, so report it rather than read as not applicable
+ lib, reason = None, _redact(f"cuDNN install failed: {type(exc).__name__}: {exc}")
+ if lib is None:
+ logger.info("sd_cpp.cudnn: attention stays on the ggml kernels: %s", reason)
+ return CudnnAttention(STATE_UNAVAILABLE, reason)
+ return CudnnAttention(STATE_READY, None, env = ((GGML_CUDNN_LIB_ENV, lib),))
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index b9ad66468ca..f3cefcef01d 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -3575,6 +3575,25 @@ class VideoBackend:
if native_device != "cpu":
from .video_minimax_h3 import h3_quant_cublas_env
native_env += h3_quant_cublas_env(native_cuda_cc, sage = h3_sage)
+ from .sd_cpp_cudnn import CudnnAttention, plan_cudnn_attention
+
+ try:
+ native_cudnn = (
+ plan_cudnn_attention(
+ binary,
+ native_cuda_cc,
+ allow_install = allow_install,
+ cancel_event = cancel_event,
+ )
+ if native_device != "cpu"
+ else CudnnAttention()
+ )
+ except Exception as exc: # noqa: BLE001 - an optional speedup never fails a load
+ logger.warning("video.h3_cudnn_plan_failed (ggml kernels): %s", exc)
+ native_cudnn = CudnnAttention()
+ native_env += native_cudnn.env
+ if cancel_event.is_set():
+ raise RuntimeError(VIDEO_CANCELLED_MSG)
from .video_minimax_h3 import H3_QUANT_CUBLAS_ENV, H3_QUANT_CUBLAS_MIN_CC
# The fork ignores the env below sm80, so a user value there is not the route.
@@ -3612,6 +3631,7 @@ class VideoBackend:
files = native_files,
offload_flags = native_offload,
env = native_env,
+ cudnn = native_cudnn,
server_slot = (
H3NativeServerSlot(
server_binary,
@@ -9167,9 +9187,14 @@ class VideoBackend:
denoise_close = re.compile(r"sampling completed", re.IGNORECASE)
step_bar = re.compile(r"\|\s*(\d+)\s*/\s*(\d+)\s*-\s*[\d.]+\s*(?:it/s|s/it)")
denoising = False
+ cudnn = getattr(runtime, "cudnn", None)
+ if cudnn is not None:
+ cudnn.begin_render()
def on_log(line: str) -> None:
nonlocal denoising
+ if cudnn is not None:
+ cudnn.feed(line)
if denoise_open.search(line):
denoising = True
return
@@ -9286,6 +9311,8 @@ class VideoBackend:
raise
if cancel.is_set():
raise RuntimeError(VIDEO_CANCELLED_MSG)
+ if cudnn is not None:
+ cudnn.end_render()
self._gen.update(phase = "export", eta_seconds = None)
actual_width, actual_height, actual_frames, has_audio = inspect_video(generated)
mp4_bytes = transcode_video_to_mp4(generated, fps = fps)
@@ -9547,6 +9574,8 @@ class VideoBackend:
"speed_mode": None,
"speed_optims": [],
"attention_backend": None,
+ "sd_cpp_cudnn_attention": None,
+ "sd_cpp_cudnn_reason": None,
"transformer_cache": None,
"transformer_cache_stats": None,
"transformer_quant": None,
@@ -9605,6 +9634,7 @@ class VideoBackend:
if getattr(state, "bg_compile", None) is not None
else None,
"attention_backend": state.attention_backend,
+ **_sd_cpp_cudnn_status(state),
"transformer_cache": state.transformer_cache,
"transformer_cache_stats": (
static_skip_stats(state.pipe) if state.transformer_cache == TC_STATIC else None
@@ -9641,6 +9671,14 @@ class VideoBackend:
}
+def _sd_cpp_cudnn_status(state: Any) -> dict[str, Any]:
+ """Whether the native runtime's sd.cpp children run attention on cuDNN; nulls for every other runtime."""
+ cudnn = getattr(getattr(state, "pipe", None), "cudnn", None)
+ if cudnn is None or state.engine != "sd_cpp":
+ return {"sd_cpp_cudnn_attention": None, "sd_cpp_cudnn_reason": None}
+ return cudnn.status_fields()
+
+
_backend: Optional[VideoBackend] = None
_backend_lock = threading.Lock()
diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.py
index 8112fd8fc28..8e3657471bc 100644
--- a/studio/backend/core/inference/video_minimax_h3.py
+++ b/studio/backend/core/inference/video_minimax_h3.py
@@ -1349,6 +1349,8 @@ class MiniMaxH3NativeRuntime:
# The card the load resolved, kept for failure records: re-resolving at failure time can read None.
selected_card: Optional[str] = None
env: tuple[tuple[str, str], ...] = ()
+ # sd_cpp_cudnn.CudnnAttention; its env is already in ``env``.
+ cudnn: Any = None
# H3NativeServerSlot, or None for one-shot sd-cli only.
server_slot: Any = None
diff --git a/studio/backend/hub/utils/host_paths.py b/studio/backend/hub/utils/host_paths.py
index c8f69ea9ffb..53cbf4d6636 100644
--- a/studio/backend/hub/utils/host_paths.py
+++ b/studio/backend/hub/utils/host_paths.py
@@ -54,7 +54,14 @@ HOST_PATH_HANDLE_FIELDS = frozenset(
# Scrubbed, not blanked: the only account of WHY a run failed.
HOST_PATH_TEXT_FIELDS = frozenset(
- {"error_message", "error", "detail", "message", "transformer_quant_backend_reason"}
+ {
+ "error_message",
+ "error",
+ "detail",
+ "message",
+ "transformer_quant_backend_reason",
+ "sd_cpp_cudnn_reason",
+ }
)
# The same text, one per entry. A run's warnings quote the file they are about ("missing
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index c1a8b618c19..206cc8b6821 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -5718,6 +5718,17 @@ class VideoStatusResponse(BaseModel):
description = "Attention backend engaged via the diffusers dispatcher (e.g. "
"_native_cudnn), or null for the default SDPA",
)
+ sd_cpp_cudnn_attention: Optional[str] = Field(
+ None,
+ description = "MiniMax-H3 on stable-diffusion.cpp only: cuDNN fused attention state. ready (a "
+ "CUDA 12 cuDNN is named to sd.cpp, no render yet) | engaged | fallback (sd.cpp kept its own "
+ "kernels) | unavailable (no CUDA 12 cuDNN could be provided) | off (switched off) | null "
+ "(not applicable: the build has no cuDNN attention, or the card, platform or engine is not "
+ "eligible).",
+ )
+ sd_cpp_cudnn_reason: Optional[str] = Field(
+ None, description = "Why sd_cpp_cudnn_attention is not engaged or ready, when known"
+ )
transformer_cache: Optional[str] = Field(
None, description = "Step cache engaged: fbcache | static | null"
)
diff --git a/studio/backend/tests/test_sd_cpp_cudnn.py b/studio/backend/tests/test_sd_cpp_cudnn.py
new file mode 100644
index 00000000000..64b12c09472
--- /dev/null
+++ b/studio/backend/tests/test_sd_cpp_cudnn.py
@@ -0,0 +1,495 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""cuDNN fused attention for the sd.cpp fork: who gets a CUDA 12 cuDNN, how it is installed, what the status says."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+from core.inference import sd_cpp_cudnn as cd
+
+RT = cd.CUDNN_RUNTIMES[12]
+
+# Sibling imports (the H3 load harness) need the tests dir on the path: pytest inserts rootdir, not this package.
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+# Lines the fork prints at INFO level (copied from a B200 sd-server log of the cuDNN build).
+LOADED = "[INFO ] ggml - load_locked: cuDNN 92700 loaded from /x/nvidia/cudnn/lib/libcudnn.so.9 for attention"
+PLAN_DIT = (
+ "[INFO ] ggml - ggml_cuda_cudnn_sdpa_prepare: cuDNN SDPA plan b=1 hq=56 hk=56 sq=19315 skv=19315 "
+ "d=128 f16, workspace 0 B, built in 1321 ms"
+)
+NO_PLAN = (
+ "[INFO ] ggml - ggml_cuda_cudnn_sdpa_prepare: no cuDNN SDPA plan for b=1 hq=56 hk=56 sq=19315 "
+ "skv=19315 d=128, keeping the ggml kernel"
+)
+
+
+def _binary(
+ tmp_path: Path,
+ *,
+ cudnn: bool,
+ cudart: int | None = 12,
+ name = "sd-cli",
+) -> str:
+ blob = b"\x7fELF" + b"\0" * 64
+ if cudart is not None:
+ blob += f"libcudart.so.{cudart}".encode() + b"\0"
+ blob += b"x" * (9 << 20) # past one scan chunk, so the marker straddles reads
+ if cudnn:
+ blob += b"GGML_CUDA_CUDNN_LIB\0"
+ path = tmp_path / name
+ path.write_bytes(blob)
+ return str(path)
+
+
+def _preinstall(root: Path, runtime = RT) -> str:
+ d = root / runtime.dirname
+ (d / "nvidia/cudnn/lib").mkdir(parents = True)
+ (d / "nvidia/cuda_nvrtc/lib").mkdir(parents = True)
+ (d / "nvidia/cudnn/lib/libcudnn.so.9").write_bytes(b"lib")
+ (d / "nvidia/cuda_nvrtc/lib/libnvrtc.so.12").write_bytes(b"lib")
+ (d / "unsloth-cudnn.json").write_text(json.dumps({"requirements": runtime.requirements()}))
+ return str(d / "nvidia/cudnn/lib/libcudnn.so.9")
+
+
[email protected](autouse = True)
+def _clean(monkeypatch):
+ for var in (cd.CUDNN_INSTALL_ENV, cd.GGML_CUDNN_LIB_ENV, cd.GGML_CUDNN_ATTN_ENV):
+ monkeypatch.delenv(var, raising = False)
+ cd._FAILED.clear()
+ cd._SCAN_MEMO.clear()
+ yield
+ cd._FAILED.clear()
+
+
+def _no_install(*_a, **_k):
+ raise AssertionError("must not install")
+
+
+# --- who is eligible -------------------------------------------------------------------------------------------------
+
+
+def test_binary_scan_reads_the_build_marker_and_cuda_major(tmp_path):
+ assert cd.binary_cudnn_build(_binary(tmp_path, cudnn = True)) == (True, 12)
+ assert cd.binary_cudnn_build(_binary(tmp_path, cudnn = False, name = "old")) == (False, 12)
+ assert cd.binary_cudnn_build(_binary(tmp_path, cudnn = True, cudart = 13, name = "c13")) == (True, 13)
+ assert cd.binary_cudnn_build(str(tmp_path / "missing")) == (False, None)
+
+
+def test_binary_scan_reads_a_shared_ggml_beside_the_binary(tmp_path):
+ exe = _binary(tmp_path, cudnn = False, cudart = None)
+ (tmp_path / "libggml-cuda.so").write_bytes(b"GGML_CUDA_CUDNN_LIB\0libcudart.so.12\0")
+ assert cd.binary_cudnn_build(exe) == (True, 12)
+
+
+ "platform, cc",
+ [
+ ("win32", (10, 0)),
+ ("darwin", (10, 0)),
+ ("linux", (7, 5)),
+ ("linux", (6, 1)),
+ ("linux", None),
+ ],
+)
+def test_inert_off_linux_below_sm80_and_unknown_card(monkeypatch, tmp_path, platform, cc):
+ """Windows, macOS, a T4 (sm75) and a card whose capability the build did not report (AMD, Vulkan, CPU):
+ no install, no env, no status."""
+ monkeypatch.setattr(cd, "ensure_library", _no_install)
+ plan = cd.plan_cudnn_attention(
+ _binary(tmp_path, cudnn = True), cc, platform = platform, root = tmp_path
+ )
+ assert plan.env == () and plan.state is None
+ assert plan.status_fields() == {"sd_cpp_cudnn_attention": None, "sd_cpp_cudnn_reason": None}
+
+
+def test_inert_for_a_prebuilt_without_the_cudnn_build(monkeypatch, tmp_path):
+ monkeypatch.setattr(cd, "ensure_library", _no_install)
+ plan = cd.plan_cudnn_attention(
+ _binary(tmp_path, cudnn = False), (10, 0), platform = "linux", root = tmp_path
+ )
+ assert plan.env == () and plan.state is None
+
+
[email protected]("cc", [(8, 0), (8, 6), (8, 9), (9, 0), (10, 0), (12, 0)])
+def test_sm80_plus_gets_the_managed_library_for_the_child_only(monkeypatch, tmp_path, cc):
+ lib = _preinstall(tmp_path)
+ monkeypatch.setattr(cd, "_install_locked", _no_install)
+ before = dict(os.environ)
+ plan = cd.plan_cudnn_attention(
+ _binary(tmp_path, cudnn = True), cc, platform = "linux", root = tmp_path
+ )
+ assert plan.env == ((cd.GGML_CUDNN_LIB_ENV, lib),)
+ assert plan.state == cd.STATE_READY
+ # This process's environment is untouched: only the sd.cpp spawn gets the variable.
+ assert dict(os.environ) == before
+
+
+def test_user_values_win(monkeypatch, tmp_path):
+ monkeypatch.setattr(cd, "ensure_library", _no_install)
+ exe = _binary(tmp_path, cudnn = True)
+ monkeypatch.setenv(cd.GGML_CUDNN_LIB_ENV, "/opt/cudnn/libcudnn.so.9")
+ plan = cd.plan_cudnn_attention(exe, (10, 0), platform = "linux", root = tmp_path)
+ assert plan.env == () and plan.state == cd.STATE_READY
+ monkeypatch.delenv(cd.GGML_CUDNN_LIB_ENV)
+ monkeypatch.setenv(cd.GGML_CUDNN_ATTN_ENV, "0")
+ plan = cd.plan_cudnn_attention(exe, (10, 0), platform = "linux", root = tmp_path)
+ assert plan.env == () and plan.state == cd.STATE_OFF
+ monkeypatch.delenv(cd.GGML_CUDNN_ATTN_ENV)
+ monkeypatch.setenv(cd.CUDNN_INSTALL_ENV, "0")
+ plan = cd.plan_cudnn_attention(exe, (10, 0), platform = "linux", root = tmp_path)
+ assert plan.env == () and plan.state == cd.STATE_OFF
+
+
+def test_cuda13_build_gets_no_cuda12_library(monkeypatch, tmp_path):
+ monkeypatch.setattr(cd, "ensure_library", _no_install)
+ exe = _binary(tmp_path, cudnn = True, cudart = 13)
+ plan = cd.plan_cudnn_attention(exe, (10, 0), platform = "linux", root = tmp_path)
+ assert plan.env == () and plan.state == cd.STATE_UNAVAILABLE
+
+
+def test_offline_load_never_installs(monkeypatch, tmp_path):
+ monkeypatch.setattr(cd, "_install_locked", _no_install)
+ plan = cd.plan_cudnn_attention(
+ _binary(tmp_path, cudnn = True), (10, 0), platform = "linux", root = tmp_path, allow_install = False
+ )
+ assert plan.env == () and plan.state == cd.STATE_UNAVAILABLE
+
+
+# --- install safety --------------------------------------------------------------------------------------------------
+
+
[email protected]("uv", ["/usr/bin/uv", None])
+def test_install_command_targets_a_studio_dir_never_the_venv(tmp_path, uv):
+ """The CUDA 12 and CUDA 13 cuDNN wheels both write nvidia/cudnn/lib/libcudnn.so.9: installed into the venv,
+ nvidia-cudnn-cu12 would replace torch's own. --target a separate dir, --no-deps, exact pins, wheels only."""
+ cmd = cd.install_command(RT, tmp_path / "stage", uv)
+ assert cmd[cmd.index("--target") + 1] == str(tmp_path / "stage")
+ assert "--no-deps" in cmd and cmd[cmd.index("--only-binary") + 1] == ":all:"
+ assert cmd[-2:] == ["nvidia-cudnn-cu12==9.27.0.42", "nvidia-cuda-nvrtc-cu12==12.8.93"]
+ for banned in (
+ "--upgrade",
+ "-U",
+ "--force-reinstall",
+ "--reinstall",
+ "--system",
+ "--break-system-packages",
+ ):
+ assert banned not in cmd
+
+
+def test_managed_root_is_under_the_studio_bin_dir_not_site_packages(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "home"))
+ root = cd.managed_root()
+ assert root == (tmp_path / "home").resolve() / "bin" / "sd-cpp-cudnn"
+ import sysconfig
+
+ for key in ("purelib", "platlib"):
+ site = Path(sysconfig.get_paths()[key]).resolve()
+ assert site != root.resolve() and site not in root.resolve().parents
+
+
+def _fake_installer(
+ monkeypatch,
+ *,
+ version = "92700",
+ write_files = True,
+ drift = False,
+):
+ calls = []
+ snaps = iter([{"torch": "2.12.1"}, {"torch": "2.12.1" if not drift else "2.13.0"}])
+ monkeypatch.setattr(cd, "_venv_snapshot", lambda: next(snaps))
+ monkeypatch.setattr(cd, "_reachable", lambda _url: True)
+ monkeypatch.setattr(cd, "_uv_executable", lambda: None)
+ monkeypatch.setattr(cd, "_installer_config", lambda _uv: {"mirror": False, "unprobed": False})
+
+ def run(
+ cmd,
+ timeout,
+ cancel_event = None,
+ ):
+ calls.append(cmd)
+ if "--target" in cmd:
+ target = Path(cmd[cmd.index("--target") + 1])
+ if write_files:
+ (target / "nvidia/cudnn/lib").mkdir(parents = True)
+ (target / "nvidia/cuda_nvrtc/lib").mkdir(parents = True)
+ (target / "nvidia/cudnn/lib/libcudnn.so.9").write_bytes(b"lib")
+ (target / "nvidia/cuda_nvrtc/lib/libnvrtc.so.12").write_bytes(b"lib")
+ return True, "Installed 2 packages"
+ return True, version + "\n"
+
+ monkeypatch.setattr(cd, "_run", run)
+ return calls
+
+
+def test_install_stages_verifies_and_publishes_atomically(monkeypatch, tmp_path):
+ calls = _fake_installer(monkeypatch)
+ lib, reason = cd.ensure_library(RT, root = tmp_path)
+ assert reason is None and lib == str(tmp_path / RT.dirname / "nvidia/cudnn/lib/libcudnn.so.9")
+ # Verified in a fresh interpreter, never dlopened in this one.
+ assert calls[1][0] == sys.executable and ".staging-" in calls[1][-1]
+ assert not [p for p in tmp_path.iterdir() if p.name.startswith(".staging-")]
+ # A second load reuses it without running anything.
+ monkeypatch.setattr(cd, "_run", _no_install)
+ assert cd.ensure_library(RT, root = tmp_path) == (lib, None)
+
+
+ "kwargs, needle",
+ [
+ ({"version": "92000"}, "verification failed"),
+ ({"write_files": False}, "without libcudnn"),
+ ({"drift": True}, "changed this environment"),
+ ],
+)
+def test_failed_install_publishes_nothing_and_is_not_retried(monkeypatch, tmp_path, kwargs, needle):
+ calls = _fake_installer(monkeypatch, **kwargs)
+ lib, reason = cd.ensure_library(RT, root = tmp_path)
+ assert lib is None and needle in reason
+ assert not (tmp_path / RT.dirname).exists()
+ assert not [p for p in tmp_path.iterdir() if p.name.startswith(".staging-")]
+ n = len(calls)
+ assert cd.ensure_library(RT, root = tmp_path) == (None, reason)
+ assert len(calls) == n
+
+
+def test_unreachable_index_refuses_before_downloading(monkeypatch, tmp_path):
+ monkeypatch.setattr(cd, "_reachable", lambda _url: False)
+ monkeypatch.setattr(cd, "_run", _no_install)
+ monkeypatch.setattr(cd, "_installer_config", lambda _uv: {"mirror": False, "unprobed": False})
+ lib, reason = cd.ensure_library(RT, root = tmp_path)
+ assert lib is None and "not reachable" in reason
+
+
+def test_a_configured_mirror_skips_the_pypi_probe(monkeypatch, tmp_path):
+ """A mirror named only in uv.toml / pip.conf (read by the NVFP4 installer's config reader) is the installer's to
+ reach, so an unreachable pypi.org does not refuse the install."""
+ calls = _fake_installer(monkeypatch)
+ monkeypatch.setattr(cd, "_reachable", _no_install)
+ monkeypatch.setattr(cd, "_installer_config", lambda _uv: {"mirror": True, "unprobed": False})
+ lib, reason = cd.ensure_library(RT, root = tmp_path)
+ assert reason is None and lib and "--target" in calls[0]
+
+
+def test_a_pip_only_mirror_reaches_uv(monkeypatch, tmp_path):
+ """uv does not read PIP_INDEX_URL: the command carries it over as --index-url."""
+ for var in ("UV_INDEX_URL", "UV_DEFAULT_INDEX"):
+ monkeypatch.delenv(var, raising = False)
+ monkeypatch.setenv("PIP_INDEX_URL", "https://mirror.example/simple")
+ cmd = cd.install_command(RT, tmp_path / "stage", "/usr/bin/uv")
+ assert cmd[cmd.index("--index-url") + 1] == "https://mirror.example/simple"
+
+
+def test_cancel_kills_the_install_and_is_not_remembered(monkeypatch, tmp_path):
+ """A cancelled load stops the installer at once; the next load installs again."""
+ import threading
+ import time
+
+ cancel = threading.Event()
+ monkeypatch.setattr(cd, "_venv_snapshot", lambda: {})
+ monkeypatch.setattr(cd, "_installer_config", lambda _uv: {"mirror": True, "unprobed": False})
+ monkeypatch.setattr(cd, "_uv_executable", lambda: None)
+ monkeypatch.setattr(
+ cd,
+ "install_command",
+ lambda *_a, **_k: [sys.executable, "-c", "import time; time.sleep(60)"],
+ )
+ threading.Timer(0.5, cancel.set).start()
+ t = time.monotonic()
+ lib, reason = cd.ensure_library(RT, root = tmp_path, cancel_event = cancel)
+ assert lib is None and reason == "cancelled" and time.monotonic() - t < 10
+ assert RT.cuda_major not in cd._FAILED
+ assert not [p for p in tmp_path.iterdir() if p.name.startswith(".staging-")]
+
+
+def test_low_disk_refuses(monkeypatch, tmp_path):
+ monkeypatch.setattr(cd.shutil, "disk_usage", lambda _p: type("U", (), {"free": 1 << 30})())
+ monkeypatch.setattr(cd, "_run", _no_install)
+ lib, reason = cd.ensure_library(RT, root = tmp_path)
+ assert lib is None and "GiB free" in reason
+
+
+# --- engagement status -----------------------------------------------------------------------------------------------
+
+
+def test_status_engaged_from_the_fork_log_and_kept_on_a_reused_server():
+ a = cd.CudnnAttention(cd.STATE_READY, env = ((cd.GGML_CUDNN_LIB_ENV, "/l"),))
+ a.begin_render()
+ for line in ("[INFO ] sampling", LOADED, PLAN_DIT):
+ a.feed(line)
+ a.end_render()
+ assert a.state == cd.STATE_ENGAGED and a.cudnn_version == 92700
+ assert (19315, 19315, 128) in a.shapes
+ # The resident server prints nothing about cuDNN on its second render.
+ a.begin_render()
+ a.feed("[INFO ] sampling completed, taking 5.69s")
+ a.end_render()
+ assert a.state == cd.STATE_ENGAGED
+
+
+def test_status_fallback_when_no_plan_or_library_not_loaded():
+ a = cd.CudnnAttention(cd.STATE_READY)
+ a.begin_render()
+ a.feed(LOADED)
+ a.feed(NO_PLAN)
+ a.end_render()
+ assert a.state == cd.STATE_FALLBACK and "no attention plan" in a.reason
+ b = cd.CudnnAttention(cd.STATE_READY)
+ b.begin_render()
+ b.feed("[INFO ] sampling completed")
+ b.end_render()
+ assert b.state == cd.STATE_FALLBACK and "did not load" in b.reason
+ # A failed render settles nothing.
+ c = cd.CudnnAttention(cd.STATE_READY)
+ c.begin_render()
+ c.end_render(ok = False)
+ assert c.state == cd.STATE_READY
+
+
+# --- through the H3 native load --------------------------------------------------------------------------------------
+
+
+def _h3_load(
+ monkeypatch,
+ tmp_path,
+ *,
+ devices,
+ carries = True,
+):
+ import test_video_backend as tvb
+
+ monkeypatch.setattr(cd, "binary_cudnn_build", lambda _b: (carries, 12))
+ root = tmp_path / "cudnn_root"
+ lib = _preinstall(root)
+ monkeypatch.setattr(cd, "managed_root", lambda: root)
+ monkeypatch.setattr(cd, "_install_locked", _no_install)
+ monkeypatch.delenv("GGML_CUDA_QUANT_CUBLAS_MIN_BATCH", raising = False)
+ state, _offload = tvb._load_h3_native_offload(
+ monkeypatch, tmp_path, help_text = tvb._SAGE_HELP, speed_mode = "max", devices = devices
+ )
+ return state, lib
+
+
+def test_h3_load_on_sm100_names_the_library_and_reports_ready(monkeypatch, tmp_path):
+ import test_video_backend as tvb
+ from core.inference.video import _sd_cpp_cudnn_status
+
+ state, lib = _h3_load(monkeypatch, tmp_path, devices = tvb._cuda_devices("10.0"))
+ env = dict(state.pipe.env)
+ assert env[cd.GGML_CUDNN_LIB_ENV] == lib
+ assert env["GGML_CUDA_QUANT_CUBLAS_MIN_BATCH"] == "1024"
+ assert _sd_cpp_cudnn_status(state) == {
+ "sd_cpp_cudnn_attention": "ready",
+ "sd_cpp_cudnn_reason": None,
+ }
+
+
[email protected]("cc, carries", [("7.5", True), ("10.0", False)])
+def test_h3_load_on_t4_or_old_prebuilt_is_unchanged(monkeypatch, tmp_path, cc, carries):
+ import test_video_backend as tvb
+ from core.inference.video import _sd_cpp_cudnn_status
+
+ state, _lib = _h3_load(monkeypatch, tmp_path, devices = tvb._cuda_devices(cc), carries = carries)
+ assert cd.GGML_CUDNN_LIB_ENV not in dict(state.pipe.env)
+ assert _sd_cpp_cudnn_status(state) == {
+ "sd_cpp_cudnn_attention": None,
+ "sd_cpp_cudnn_reason": None,
+ }
+
+
+def test_status_route_model_carries_the_fields():
+ from models.inference import VideoStatusResponse
+ fields = VideoStatusResponse.model_fields
+ assert "sd_cpp_cudnn_attention" in fields and "sd_cpp_cudnn_reason" in fields
+
+
+# --- round 2 ---------------------------------------------------------------------------------------------------------
+
+
+def test_preflight_refusals_are_rechecked_on_the_next_load(monkeypatch, tmp_path):
+ """Low disk and an unreachable index are rechecked; only a real install failure is remembered."""
+ calls = _fake_installer(monkeypatch)
+ monkeypatch.setattr(cd, "_reachable", lambda _url: False)
+ lib, reason = cd.ensure_library(RT, root = tmp_path)
+ assert lib is None and "not reachable" in reason and RT.cuda_major not in cd._FAILED
+ monkeypatch.setattr(cd, "_reachable", lambda _url: True)
+ lib, reason = cd.ensure_library(RT, root = tmp_path)
+ assert reason is None and lib and "--target" in calls[0]
+
+
+def test_a_plan_that_fails_to_execute_reports_fallback():
+ a = cd.CudnnAttention(cd.STATE_READY, env = ((cd.GGML_CUDNN_LIB_ENV, "/l"),))
+ a.begin_render()
+ for line in (
+ LOADED,
+ PLAN_DIT,
+ "ggml_cuda_cudnn_sdpa: cuDNN SDPA execute failed, keeping the ggml kernel for this shape: x",
+ ):
+ a.feed(line)
+ a.end_render()
+ assert a.state == cd.STATE_FALLBACK and "failed to run" in a.reason
+
+
+def test_the_installer_own_index_is_not_overridden(monkeypatch, tmp_path):
+ """A uv config naming its own default index keeps it; PIP_INDEX_URL is not forced over it."""
+ monkeypatch.delenv("UV_INDEX_URL", raising = False)
+ monkeypatch.delenv("UV_DEFAULT_INDEX", raising = False)
+ monkeypatch.setenv("PIP_INDEX_URL", "https://mirror.example/simple")
+ cmd = cd.install_command(RT, tmp_path / "stage", "/usr/bin/uv", own_index = True)
+ assert "--index-url" not in cmd
+
+
+def test_status_reason_is_redacted_for_remote_callers():
+ from hub.utils.host_paths import HOST_PATH_TEXT_FIELDS
+ assert "sd_cpp_cudnn_reason" in HOST_PATH_TEXT_FIELDS
+
+
+def test_installer_output_is_redacted_and_copies_files(monkeypatch):
+ """Index credentials in installer output never reach the status reason; uv copies, never links, the target."""
+
+ def fake_child_env():
+ return {"UV_LINK_MODE": "symlink", "PATH": os.environ.get("PATH", "")}
+
+ monkeypatch.setattr(cd, "_child_env", fake_child_env)
+ code = (
+ "import os; print('https://user:[email protected]/simple', os.environ['UV_LINK_MODE'])"
+ )
+ ok, out = cd._run([sys.executable, "-c", code], 60)
+ assert ok and "s3cret" not in out and out.endswith("copy")
+
+
+def test_an_unusable_lock_fails_at_once(monkeypatch, tmp_path):
+ class BrokenLock:
+ def acquire(self, timeout):
+ raise PermissionError("read-only file system")
+
+ monkeypatch.setattr(cd, "_file_lock", lambda _p: BrokenLock())
+ monkeypatch.setattr(cd, "_run", _no_install)
+ import time
+
+ t = time.monotonic()
+ lib, reason = cd.ensure_library(RT, root = tmp_path)
+ assert lib is None and "cannot lock" in reason and time.monotonic() - t < 5
+
+
+def test_an_unexpected_install_error_reports_unavailable(monkeypatch, tmp_path):
+ monkeypatch.setattr(cd, "binary_cudnn_build", lambda _b: (True, 12))
+
+ def boom(*_a, **_k):
+ raise OSError("disk went away")
+
+ monkeypatch.setattr(cd, "ensure_library", boom)
+ plan = cd.plan_cudnn_attention(
+ "/x/sd-cli", (10, 0), platform = "linux", environ = {}, root = tmp_path
+ )
+ assert plan.state == cd.STATE_UNAVAILABLE and "disk went away" in plan.reason and plan.env == ()