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: fail fast when the installed llama.cpp prebuilt has no kernels for this GPU (#8841)
Nilay9d1dcfe58a26
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 100bdad6b22..f255df4a689 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -6140,6 +6140,102 @@ class LlamaCppBackend:logger.debug(f"install marker arch read failed: {e}")return None+ @staticmethod+ def _installed_llama_cuda_sms(binary: Optional[str] = None) -> Optional[frozenset]:+ """SM targets the installed CUDA prebuilt was built for (``supported_sms``+ in UNSLOTH_PREBUILT_INFO.json). None when unknown (no marker, older+ install, non-CUDA bundle), so callers fail open. Never raises."""+ try:+ from utils.llama_cpp_freshness import read_install_marker++ marker = read_install_marker(binary or LlamaCppBackend._find_llama_server_binary())+ if not marker:+ return None+ sms = marker.get("supported_sms")+ if not isinstance(sms, list) or not sms:+ return None+ if not all(str(s).strip().isdigit() for s in sms):+ return None+ return frozenset(int(s) for s in sms)+ except Exception as e:+ logger.debug(f"install marker supported_sms read failed: {e}")+ return None++ @staticmethod+ def _cuda_compute_caps() -> dict:+ """Physical id -> SM (90 for sm_90) via nvidia-smi, honoring+ CUDA_VISIBLE_DEVICES; {} when unknown. Never raises."""+ try:+ result = subprocess.run(+ ["nvidia-smi", "--query-gpu=index,compute_cap", "--format=csv,noheader"],+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = 10,+ env = child_env_without_native_path_secret(),+ **_windows_hidden_subprocess_kwargs(),+ )+ if result.returncode != 0:+ return {}+ allowed = LlamaCppBackend._visible_devices_mask("CUDA_VISIBLE_DEVICES")+ if allowed is not None and os.environ.get("CUDA_DEVICE_ORDER") != "PCI_BUS_ID":+ # Numeric mask entries are CUDA ordinals; nvidia-smi reports PCI+ # physical indices. Without a shared order, fail open.+ return {}+ caps = {}+ for line in result.stdout.strip().splitlines():+ parts = [p.strip() for p in line.split(",")]+ if len(parts) < 2:+ continue+ try:+ idx = int(parts[0])+ major, minor = parts[1].split(".")+ sm = int(major) * 10 + int(minor)+ except ValueError:+ continue+ if allowed is not None and idx not in allowed:+ continue+ caps[idx] = sm+ return caps+ except Exception as e:+ logger.debug(f"compute_cap probe failed: {e}")+ return {}++ @classmethod+ def _cuda_sm_gate_error(cls, binary: Optional[str] = None) -> Optional[str]:+ """Error message when every visible GPU is OLDER than the oldest arch the+ installed CUDA bundle was built for, or None to proceed. Fails open on+ unknown coverage or caps.++ Only the too-old direction is broken. The bundles compile plain arch+ numbers, so each fatbin carries PTX beside its cubins, and the driver JITs+ that PTX forward onto a newer card; ggml_cuda_highest_compiled_arch picks+ the highest compiled arch <= the device and only aborts ("not compiled with+ any CUDA arch <= N") when the device is below every one of them. So an+ exact-SM test would refuse working installs: the legacy PTX-only bundle+ (sm_50-61) drives an sm_86/sm_89 host at full speed. Missing native cubins+ cost a one-time JIT, not a launch. The installer's exact-membership check+ is a different question -- which bundle is BEST to install -- not whether+ the installed one can run."""+ # Resolved once so the marker read and the remedy name the same binary.+ binary = binary or cls._find_llama_server_binary()+ supported = cls._installed_llama_cuda_sms(binary)+ if supported is None:+ return None+ caps = cls._cuda_compute_caps()+ oldest = min(supported)+ if not caps or any(sm >= oldest for sm in caps.values()):+ return None+ present = ", ".join(f"GPU {idx} is sm_{sm}" for idx, sm in sorted(caps.items()))+ # The updater cannot replace a pinned LLAMA_SERVER_PATH or a llama-server+ # found on PATH, so the remedy follows the binary's provenance.+ return (+ f"The installed llama.cpp build only has GPU code for sm_{oldest} and "+ f"newer, but {present} -- it was likely installed on a machine with a "+ f"newer GPU, so {cls._runtime_remedy(binary)}."+ )+@classmethoddef _arch_gate_survivors(cls, binary: Optional[str] = None) -> list[int]:"""Physical ids the ROCm arch gate leaves, or [] when there is nothing to@@ -16872,6 +16968,18 @@ class LlamaCppBackend:and not is_vulkan_backendand not self._zero_offload_keeps_gpu_visible(cmd, env))+ # The CUDA SM gate goes here, where the child's GPU visibility is+ # finally known: both arms below write CUDA_VISIBLE_DEVICES=-1, so no+ # kernel image loads and the abort this pre-empts cannot happen.+ # Deciding it from the request over-refused -- speculative "auto", a+ # --no-mmproj-offload projector and a --spec-draft-ngl 0 drafter all+ # read as GPU-bearing there, only the resolved argv knows. Still+ # before every spawn below and outside the fit's try/except, so the+ # refusal cannot be swallowed into the --fit on fallback.+ if not (_cpu_only_zero_offload or _arch_gate_forced_cpu):+ _sm_gate = self._cuda_sm_gate_error(binary)+ if _sm_gate:+ raise RuntimeError(_sm_gate)# The arch gate emptying the pool lands here for the same reason# (#7624): no device set this binary can launch on, so the child must# not see the cards it would enumerate and abort on. gpu_indices isdiff --git a/studio/backend/tests/test_cuda_sm_gate.py b/studio/backend/tests/test_cuda_sm_gate.pynew file mode 100644index 00000000000..47ba316192e--- /dev/null+++ b/studio/backend/tests/test_cuda_sm_gate.py@@ -0,0 +1,396 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The CUDA SM gate: a prebuilt whose oldest compiled arch is newer than every+GPU on this host (e.g. a cloud image baked on an H100, run on a T4) must fail+fast instead of llama-server aborting on every launch attempt. The reverse,+a bundle older than the card, JITs its PTX forward and must still run."""++import json+import os+import struct+import subprocess+import types+from pathlib import Path+from unittest.mock import patch++import pytest++from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend+++def _binary_with_marker(tmp_path, payload):+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(json.dumps(payload), encoding = "utf-8")+ return str(tmp_path / "build" / "bin" / "llama-server")+++class TestInstalledLlamaCudaSms:+ def test_reads_supported_sms(self, tmp_path):+ binary = _binary_with_marker(tmp_path, {"supported_sms": ["75", "80", 86, " 89 "]})+ assert LlamaCppBackend._installed_llama_cuda_sms(binary) == frozenset({75, 80, 86, 89})++ def test_no_marker_is_unknown(self, tmp_path):+ assert LlamaCppBackend._installed_llama_cuda_sms(str(tmp_path / "llama-server")) is None++ def test_no_binary_is_unknown(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: None)+ )+ assert LlamaCppBackend._installed_llama_cuda_sms() is None++ @pytest.mark.parametrize("sms", [None, [], ["gfx1100"], ["86", "abc"], "86"])+ def test_missing_or_malformed_is_unknown(self, tmp_path, sms):+ binary = _binary_with_marker(+ tmp_path, {"supported_sms": sms} if sms is not None else {"asset": "x.tar.gz"}+ )+ assert LlamaCppBackend._installed_llama_cuda_sms(binary) is None++ def test_unreadable_marker_is_unknown(self, tmp_path, monkeypatch):+ import utils.llama_cpp_freshness as freshness++ def _boom(_binary):+ raise OSError("marker read failed")++ monkeypatch.setattr(freshness, "read_install_marker", _boom)+ assert LlamaCppBackend._installed_llama_cuda_sms(str(tmp_path / "llama-server")) is None+++def _fake_smi(+ monkeypatch,+ stdout,+ returncode = 0,+):+ def _run(cmd, **_kwargs):+ assert cmd[0] == "nvidia-smi"+ return types.SimpleNamespace(returncode = returncode, stdout = stdout)++ monkeypatch.setattr(subprocess, "run", _run)+++class TestCudaComputeCaps:+ def test_parses_index_and_cap(self, monkeypatch):+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ _fake_smi(monkeypatch, "0, 9.0\n1, 12.0\n")+ assert LlamaCppBackend._cuda_compute_caps() == {0: 90, 1: 120}++ def test_honors_visible_devices_mask(self, monkeypatch):+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1")+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")+ _fake_smi(monkeypatch, "0, 7.5\n1, 9.0\n")+ assert LlamaCppBackend._cuda_compute_caps() == {1: 90}++ def test_numeric_mask_with_non_physical_order_fails_open(self, monkeypatch):+ # Under FASTEST_FIRST, CUDA ordinal 0 can name physical GPU 1.+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")+ _fake_smi(monkeypatch, "0, 7.5\n1, 9.0\n")+ assert LlamaCppBackend._cuda_compute_caps() == {}++ def test_bad_lines_are_skipped(self, monkeypatch):+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ _fake_smi(monkeypatch, "0, 9.0\nno-cap-line\n1, N/A\n")+ assert LlamaCppBackend._cuda_compute_caps() == {0: 90}++ def test_probe_failure_is_empty(self, monkeypatch):+ _fake_smi(monkeypatch, "", returncode = 1)+ assert LlamaCppBackend._cuda_compute_caps() == {}++ def _raise(*_args, **_kwargs):+ raise OSError("no nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _raise)+ assert LlamaCppBackend._cuda_compute_caps() == {}+++class TestCudaSmGateError:+ def _caps(self, monkeypatch, caps):+ monkeypatch.setattr(LlamaCppBackend, "_cuda_compute_caps", staticmethod(lambda: caps))++ def _managed(self, monkeypatch, managed):+ monkeypatch.setattr(+ LlamaCppBackend, "_is_unsloth_managed_binary", staticmethod(lambda _binary: managed)+ )++ def test_a_gpu_older_than_every_compiled_arch_errors(self, tmp_path, monkeypatch):+ # The shape that really aborts: a cuda13-newer bundle (lowest compute_86)+ # on an sm_75 host, so no cubin and no back-compatible PTX exists.+ self._caps(monkeypatch, {0: 75})+ self._managed(monkeypatch, True)+ binary = _binary_with_marker(tmp_path, {"supported_sms": ["86", "89", "120"]})+ error = LlamaCppBackend._cuda_sm_gate_error(binary)+ assert error is not None+ assert "sm_86 and newer" in error+ assert "GPU 0 is sm_75" in error+ assert "unsloth studio update" in error++ def test_a_custom_binary_is_told_to_rebuild_not_to_update(self, tmp_path, monkeypatch):+ # A tree reached through LLAMA_SERVER_PATH or PATH still carries the marker,+ # but the updater cannot replace it, so "update" would loop back here.+ self._caps(monkeypatch, {0: 75})+ self._managed(monkeypatch, False)+ binary = _binary_with_marker(tmp_path, {"supported_sms": ["86", "89", "120"]})+ error = LlamaCppBackend._cuda_sm_gate_error(binary)+ assert error is not None+ assert "GPU 0 is sm_75" in error+ assert "reinstall or rebuild that custom llama.cpp" in error+ assert "unsloth studio update" not in error++ def test_covered_gpu_passes(self, tmp_path, monkeypatch):+ self._caps(monkeypatch, {0: 90})+ binary = _binary_with_marker(tmp_path, {"supported_sms": ["86", "89", "90", "120"]})+ assert LlamaCppBackend._cuda_sm_gate_error(binary) is None++ def test_fastest_first_numeric_mask_does_not_reject_a_supported_gpu(+ self, tmp_path, monkeypatch+ ):+ # Ordinal 0 selects the faster physical GPU 1 (sm_90), not smi row 0.+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")+ _fake_smi(monkeypatch, "0, 7.5\n1, 9.0\n")+ binary = _binary_with_marker(tmp_path, {"supported_sms": ["90"]})+ assert LlamaCppBackend._cuda_sm_gate_error(binary) is None++ def test_a_newer_gpu_jits_the_bundles_ptx(self, tmp_path, monkeypatch):+ # The direction the first cut of this gate wrongly refused: a 75-89 bundle+ # on an sm_90 host, where compute_89 PTX JITs forward and the load runs.+ self._caps(monkeypatch, {0: 90})+ binary = _binary_with_marker(tmp_path, {"supported_sms": ["75", "80", "86", "89"]})+ assert LlamaCppBackend._cuda_sm_gate_error(binary) is None++ def test_a_ptx_only_legacy_bundle_runs_on_modern_cards(self, tmp_path, monkeypatch):+ # Measured: the PTX-only cuda12-legacy bundle (sm_50-61) drives an RTX 6000+ # Ada + RTX 3090 host at full speed despite zero overlap with either card.+ self._caps(monkeypatch, {0: 89, 1: 86})+ binary = _binary_with_marker(tmp_path, {"supported_sms": ["50", "52", "60", "61"]})+ assert LlamaCppBackend._cuda_sm_gate_error(binary) is None++ def test_any_gpu_at_or_above_the_floor_passes_a_mixed_host(self, tmp_path, monkeypatch):+ self._caps(monkeypatch, {0: 90, 1: 61})+ binary = _binary_with_marker(tmp_path, {"supported_sms": ["86", "89", "90"]})+ assert LlamaCppBackend._cuda_sm_gate_error(binary) is None++ def test_unknown_coverage_fails_open(self, tmp_path, monkeypatch):+ self._caps(monkeypatch, {0: 90})+ binary = _binary_with_marker(tmp_path, {"asset": "x.tar.gz"})+ assert LlamaCppBackend._cuda_sm_gate_error(binary) is None++ def test_unknown_caps_fail_open(self, tmp_path, monkeypatch):+ self._caps(monkeypatch, {})+ binary = _binary_with_marker(tmp_path, {"supported_sms": ["75", "80"]})+ assert LlamaCppBackend._cuda_sm_gate_error(binary) is None+++def _gated_backend(+ tmp_path,+ monkeypatch,+ *,+ supported_sms = ("86", "89", "120"),+):+ """A load on the incident host: the installed bundle's oldest image is+ compute_86 and the only GPU is an sm_75 T4, so no cubin and no back-compatible+ PTX exists and the gate wants to refuse. Everything below the placement+ decision is faked -- Popen never runs and health answers True."""+ install = tmp_path / "llama.cpp"+ (install / "build" / "bin").mkdir(parents = True)+ binary = _binary_with_marker(install, {"supported_sms": list(supported_sms)})+ Path(binary).write_text("", encoding = "utf-8")+ os.chmod(binary, 0o755)++ gguf = tmp_path / "model.gguf"++ def _string(value):+ data = value.encode()+ return struct.pack("<Q", len(data)) + data++ gguf.write_bytes(+ struct.pack("<IIQQ", 0x46554747, 3, 0, 1)+ + _string("general.architecture")+ + struct.pack("<I", 8)+ + _string("llama")+ )++ monkeypatch.setattr(LlamaCppBackend, "_cuda_compute_caps", staticmethod(lambda: {0: 75}))+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda *_a, **_kw: False)+ )+ # Pinned so the refusal wording does not depend on where the runner puts tmp_path.+ monkeypatch.setattr(+ LlamaCppBackend, "_is_unsloth_managed_binary", staticmethod(lambda _binary: True)+ )+ backend = LlamaCppBackend()+ backend._get_gpu_memory = lambda _binary = None, **_kw: []+ backend._get_gpu_free_memory = lambda _binary = None, **_kw: []+ backend._read_gguf_metadata = lambda _path: None+ backend._can_estimate_kv = lambda: False+ backend._get_gguf_size_bytes = lambda _path: 1024+ backend._mmproj_vram_bytes = lambda _path: 0+ backend._resolve_launch_mmproj_path = lambda **_kw: None+ backend._apu_ram_shortfall_message = lambda *_a, **_kw: None+ backend._amd_apu_wants_unified_memory = lambda *_a, **_kw: False+ backend._find_llama_server_binary = lambda include_denied = False: binary+ backend._fit_off_retry_eligible = lambda *_a, **_kw: False+ backend.probe_server_capabilities = lambda _binary: {"found": True}+ backend._record_server_pid = lambda _pid: None+ backend._clear_server_pid = lambda: None+ backend._prepare_cpu_fallback_launch = lambda *_a, **_kw: None+ backend._detect_audio_type_strict = lambda: None+ backend._apply_detected_audio = lambda _detected: True+ backend._wait_for_health = lambda timeout: True+ backend._llama_server_env_for_binary = lambda _binary: {"PATH": os.environ.get("PATH", "")}+ return backend, gguf+++def _drive_load(backend, gguf, **intent_kwargs):+ """Return (launches, error): a refusal has no launch to point at, so the+ exception is handed back rather than raised through the harness."""+ launches = []++ class _Process:+ pid = 123+ stdout = ()+ returncode = None++ def poll(self):+ return None++ def terminate(self):+ return None++ def wait(self, timeout = None):+ return 0++ def kill(self):+ return None++ def _popen(cmd, **kwargs):+ launches.append((list(cmd), dict(kwargs.get("env") or {})))+ return _Process()++ error = None+ with patch.object(subprocess, "Popen", side_effect = _popen):+ try:+ backend.load_model(+ GgufLoadIntent(+ gguf_path = str(gguf),+ model_identifier = "owner/model",+ **intent_kwargs,+ )+ )+ except Exception as exc:+ error = exc+ return launches, error+++class TestTheGateSparesADeliberateCpuOnlyLoad:+ """A manual zero-offload load launches with CUDA_VISIBLE_DEVICES=-1, so the+ child never initialises CUDA and the missing kernels cannot reach it. Gating+ it turned a load that works on the mismatched host into a hard refusal."""++ def test_manual_zero_offload_still_launches_on_cpu(self, tmp_path, monkeypatch):+ backend, gguf = _gated_backend(tmp_path, monkeypatch)+ launches, error = _drive_load(backend, gguf, gpu_memory_mode = "manual", gpu_layers = 0)+ assert error is None, f"the SM gate refused a CPU-only load: {error}"+ assert len(launches) == 1+ _cmd, env = launches[0]+ assert env.get("CUDA_VISIBLE_DEVICES") == "-1"++ def test_a_gpu_offload_request_is_still_refused(self, tmp_path, monkeypatch):+ backend, gguf = _gated_backend(tmp_path, monkeypatch)+ launches, error = _drive_load(backend, gguf, gpu_memory_mode = "auto")+ assert isinstance(error, RuntimeError)+ assert "unsloth studio update" in str(error)+ assert launches == []++ @pytest.mark.parametrize(+ "companion",+ [+ {"extra_args": ["--device", "CUDA0"]},+ {"extra_args": ["--model-draft", "/tmp/draft.gguf"]},+ ],+ ids = ["device_pin", "gpu_drafter"],+ )+ def test_a_gpu_companion_keeps_the_gate(self, tmp_path, monkeypatch, companion):+ # These keep the GPUs visible, so the kernels are needed after all.+ backend, gguf = _gated_backend(tmp_path, monkeypatch)+ launches, error = _drive_load(+ backend, gguf, gpu_memory_mode = "manual", gpu_layers = 0, **companion+ )+ assert isinstance(error, RuntimeError)+ assert launches == []++ def test_the_uis_default_speculative_auto_still_launches_on_cpu(self, tmp_path, monkeypatch):+ # The chat store defaults speculativeType to "auto", so nearly every /load+ # carries it. Auto resolves to a drafterless ngram mode and the launch still+ # masks the GPUs away, so gating on the requested mode over-refused.+ backend, gguf = _gated_backend(tmp_path, monkeypatch)+ launches, error = _drive_load(+ backend,+ gguf,+ gpu_memory_mode = "manual",+ gpu_layers = 0,+ speculative_type = "auto",+ )+ assert error is None, f"the SM gate refused the default CPU-only load: {error}"+ assert len(launches) == 1+ _cmd, env = launches[0]+ assert env.get("CUDA_VISIBLE_DEVICES") == "-1"++ def test_a_cpu_pinned_drafter_still_launches_on_cpu(self, tmp_path, monkeypatch):+ # --spec-draft-ngl 0 keeps the drafter off the GPU, so the GPUs are masked.+ backend, gguf = _gated_backend(tmp_path, monkeypatch)+ launches, error = _drive_load(+ backend,+ gguf,+ gpu_memory_mode = "manual",+ gpu_layers = 0,+ speculative_type = "auto",+ extra_args = ["--spec-draft-ngl", "0"],+ )+ assert error is None, f"the SM gate refused a CPU-pinned drafter: {error}"+ assert len(launches) == 1+ _cmd, env = launches[0]+ assert env.get("CUDA_VISIBLE_DEVICES") == "-1"++ def test_a_cpu_pinned_projector_still_launches_on_cpu(self, tmp_path, monkeypatch):+ # --no-mmproj-offload clears mmproj_use_gpu, so the launch hides the GPUs:+ # the gate follows the mask, not the fact that a projector was resolved.+ backend, gguf = _gated_backend(tmp_path, monkeypatch)+ mmproj = tmp_path / "mmproj.gguf"+ mmproj.write_bytes(b"")+ backend._resolve_launch_mmproj_path = lambda **_kw: str(mmproj)+ launches, error = _drive_load(+ backend,+ gguf,+ gpu_memory_mode = "manual",+ gpu_layers = 0,+ is_vision = True,+ extra_args = ["--no-mmproj-offload"],+ )+ assert error is None, f"the SM gate refused a CPU-pinned projector: {error}"+ assert len(launches) == 1+ cmd, env = launches[0]+ assert "--no-mmproj-offload" in cmd+ assert env.get("CUDA_VISIBLE_DEVICES") == "-1"++ def test_a_gpu_projector_keeps_the_gate(self, tmp_path, monkeypatch):+ # Without the CPU pin the projector is offloaded and the GPUs stay visible.+ backend, gguf = _gated_backend(tmp_path, monkeypatch)+ mmproj = tmp_path / "mmproj.gguf"+ mmproj.write_bytes(b"")+ backend._resolve_launch_mmproj_path = lambda **_kw: str(mmproj)+ launches, error = _drive_load(+ backend, gguf, gpu_memory_mode = "manual", gpu_layers = 0, is_vision = True+ )+ assert isinstance(error, RuntimeError)+ assert launches == []++ def test_an_auto_placement_device_none_keeps_the_gate(self, tmp_path, monkeypatch):+ # Auto placement writes no CPU mask, so the child still enumerates the+ # uncovered card: --device none empties model->devices only AFTER+ # ggml_cuda_init runs. The exemption tracks the mask, not the argv.+ backend, gguf = _gated_backend(tmp_path, monkeypatch)+ launches, error = _drive_load(+ backend, gguf, gpu_memory_mode = "auto", extra_args = ["--device", "none"]+ )+ assert isinstance(error, RuntimeError)+ assert launches == []diff --git a/studio/backend/tests/test_cuda_sm_gate_os_matrix.py b/studio/backend/tests/test_cuda_sm_gate_os_matrix.pynew file mode 100644index 00000000000..5ee5cefc6a4--- /dev/null+++ b/studio/backend/tests/test_cuda_sm_gate_os_matrix.py@@ -0,0 +1,263 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""OS x GPU-vendor matrix for the CUDA SM gate, the sibling of+``test_gpu_arch_gate_os_matrix_7624.py`` for the ROCm arch gate.++The gate refuses a launch only when every visible GPU is OLDER than the oldest+arch the bundle was compiled for, and must be inert everywhere else. Output+alone cannot show that: a gate that ran and passed returns None exactly like one+that never ran, so the marker reader and the nvidia-smi probe are spied and+asserted un-called on the cells that must not reach them.++Matrix: [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, CPU-only]. No NVIDIA GPU is+needed; nvidia-smi, the marker and the masks are faked in the shapes the+installer writes (digit-string ``supported_sms``, ``compute_cap`` as "8.6").+"""++from __future__ import annotations++import subprocess++import pytest++from core.inference.llama_cpp import LlamaCppBackend++# sys.platform / platform.system() pair per simulated host.+_OS_CELLS = {+ "windows": ("win32", "Windows"),+ "linux": ("linux", "Linux"),+ "wsl": ("linux", "Linux"),+ "macos": ("darwin", "Darwin"),+}+OS_KEYS = list(_OS_CELLS)+VENDORS = ["nvidia", "amd", "cpu"]++# As the installer writes them.+CUDA12_OLDER = ["75", "80", "86", "89"]+CUDA13_NEWER = ["100", "120"]+++def _smi(rows: str, *, returncode: int = 0):+ """A fake nvidia-smi returning ``rows`` for the compute_cap query."""++ def _run(cmd, **kwargs):+ return subprocess.CompletedProcess(cmd, returncode, stdout = rows, stderr = "")++ return _run+++def _no_smi(cmd, **kwargs):+ raise FileNotFoundError("nvidia-smi")+++def marker_spy(monkeypatch):+ """Records marker reads so a cell can assert it never happened."""+ calls: list = []+ from utils import llama_cpp_freshness as freshness++ def _spy(binary_path):+ calls.append(binary_path)+ return None++ monkeypatch.setattr(freshness, "read_install_marker", _spy)+ return calls+++def smi_spy(monkeypatch):+ """Records every nvidia-smi invocation the gate makes."""+ calls: list = []++ def _spy(cmd, **kwargs):+ calls.append(cmd)+ raise FileNotFoundError("nvidia-smi")++ monkeypatch.setattr(subprocess, "run", _spy)+ return calls++[email protected](autouse = True)+def _no_inherited_visibility(monkeypatch):+ """A box pinning CUDA_VISIBLE_DEVICES would otherwise mask rows out of+ every fake nvidia-smi table below."""+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.delenv("CUDA_DEVICE_ORDER", raising = False)+++def host(monkeypatch):+ """Applies one OS cell."""++ def _apply(os_key: str):+ sys_platform, system = _OS_CELLS[os_key]+ monkeypatch.setattr("sys.platform", sys_platform)+ monkeypatch.setattr("platform.system", lambda: system)++ return _apply+++def _gate(monkeypatch, *, sms, caps_rows):+ """Run the gate with a given marker coverage and nvidia-smi output."""+ monkeypatch.setattr(+ LlamaCppBackend, "_installed_llama_cuda_sms", staticmethod(lambda binary = None: sms)+ )+ if caps_rows is None:+ monkeypatch.setattr(subprocess, "run", _no_smi)+ else:+ monkeypatch.setattr(subprocess, "run", _smi(caps_rows))+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "/x/llama-server")+ )+ monkeypatch.setattr(+ LlamaCppBackend,+ "_runtime_remedy",+ classmethod(lambda cls, b: "run `unsloth studio update`"),+ )+ return LlamaCppBackend._cuda_sm_gate_error()+++class TestTheGateAcrossTheOsAndVendorMatrix:+ @pytest.mark.parametrize("os_key", OS_KEYS)+ @pytest.mark.parametrize("vendor", VENDORS)+ def test_only_an_nvidia_host_can_be_refused(self, os_key, vendor, monkeypatch, host):+ """No nvidia-smi means unknowable coverage, so the gate opens whatever+ the marker claims."""+ host(os_key)+ rows = "0, 7.5\n" if vendor == "nvidia" else None+ error = _gate(monkeypatch, sms = frozenset({86, 89}), caps_rows = rows)+ if vendor == "nvidia":+ assert error and "sm_75" in error, error+ else:+ assert error is None, f"{os_key}/{vendor} was refused: {error}"++ @pytest.mark.parametrize("os_key", OS_KEYS)+ @pytest.mark.parametrize("vendor", VENDORS)+ def test_an_unmarked_install_never_probes_the_gpu(+ self, os_key, vendor, monkeypatch, host, marker_spy, smi_spy+ ):+ """Unknown coverage must short-circuit before shelling out to+ nvidia-smi on every load."""+ host(os_key)+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "/x/llama-server")+ )+ assert LlamaCppBackend._cuda_sm_gate_error() is None+ assert marker_spy, "the gate must consult the install marker"+ assert smi_spy == [], f"{os_key}/{vendor} probed the GPU on unknown coverage"++ @pytest.mark.parametrize("os_key", OS_KEYS)+ def test_a_non_cuda_bundle_is_inert(self, os_key, monkeypatch, host):+ """Vulkan/CPU/ROCm bundles declare no supported_sms. That invariant is+ why the call site needs no explicit is_vulkan_backend guard."""+ host(os_key)+ assert _gate(monkeypatch, sms = None, caps_rows = "0, 7.5\n") is None+++class TestTheSmFloorDecision:+ @pytest.mark.parametrize(+ "sms, cap, refused",+ [+ (CUDA12_OLDER, "7.5", False), # exactly the floor+ (CUDA12_OLDER, "7.0", True), # below every compiled arch+ (CUDA12_OLDER, "9.0", False), # newer card JITs the PTX forward+ (CUDA13_NEWER, "8.9", True), # sm_89 below an sm_100 floor+ (CUDA13_NEWER, "12.0", False),+ (["120"], "12.1", False), # GB10 on a 5090 bundle, same major+ (["121"], "12.0", True), # sm_121 PTX cannot JIT down to sm_120+ ],+ )+ def test_floor_not_exact_membership(self, sms, cap, refused, monkeypatch):+ """Only the too-old direction is broken: an exact-SM test would refuse+ the legacy sm_50-61 PTX bundle that drives an sm_86 host fine."""+ error = _gate(monkeypatch, sms = frozenset(int(s) for s in sms), caps_rows = f"0, {cap}\n")+ assert bool(error) is refused, error++ def test_a_mixed_host_passes_on_its_newest_card(self, monkeypatch):+ assert _gate(monkeypatch, sms = frozenset({86}), caps_rows = "0, 7.5\n1, 8.6\n") is None++ def test_every_card_too_old_names_them_all(self, monkeypatch):+ error = _gate(monkeypatch, sms = frozenset({86}), caps_rows = "0, 7.5\n1, 7.0\n")+ assert error and "GPU 0 is sm_75" in error and "GPU 1 is sm_70" in error++ @pytest.mark.parametrize("rows", ["", "0, N/A\n", "garbage\n", "0\n"])+ def test_unreadable_caps_fail_open(self, rows, monkeypatch):+ assert _gate(monkeypatch, sms = frozenset({86}), caps_rows = rows) is None++ def test_a_failing_probe_fails_open(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend,+ "_installed_llama_cuda_sms",+ staticmethod(lambda binary = None: frozenset({86})),+ )+ monkeypatch.setattr(subprocess, "run", _smi("0, 7.5\n", returncode = 9))+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "/x/llama-server")+ )+ assert LlamaCppBackend._cuda_sm_gate_error() is None+++class TestVisibilityMasks:+ """Mask entries are ordinals in CUDA's order while nvidia-smi reports+ physical PCI indices, so the mask is trusted only when both agree."""++ def test_a_numeric_mask_hiding_the_old_card_opens_the_gate(self, monkeypatch):+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1")+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")+ assert _gate(monkeypatch, sms = frozenset({86}), caps_rows = "0, 7.5\n1, 8.6\n") is None++ def test_a_numeric_mask_hiding_the_new_card_still_refuses(self, monkeypatch):+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")+ error = _gate(monkeypatch, sms = frozenset({86}), caps_rows = "0, 7.5\n1, 8.6\n")+ assert error and "GPU 0 is sm_75" in error++ def test_an_unordered_numeric_mask_fails_open(self, monkeypatch):+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")+ monkeypatch.delenv("CUDA_DEVICE_ORDER", raising = False)+ assert _gate(monkeypatch, sms = frozenset({86}), caps_rows = "0, 7.5\n") is None++ def test_an_empty_mask_hides_everything_and_opens_the_gate(self, monkeypatch):+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "")+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")+ assert _gate(monkeypatch, sms = frozenset({86}), caps_rows = "0, 7.5\n") is None++ @pytest.mark.parametrize(+ "mask",+ [+ "GPU-c0ffee00-1111-2222-3333-444455556666",+ "MIG-GPU-c0ffee00-1111-2222-3333-444455556666/1/0",+ ],+ )+ def test_a_uuid_or_mig_mask_is_ignored_and_the_whole_host_is_judged(self, mask, monkeypatch):+ """Neither names a physical index we can map back, so the mask is+ dropped and every card is weighed. That errs toward launching and only+ refuses when nothing on the host could run, whichever instance wins."""+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", mask)+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")+ assert _gate(monkeypatch, sms = frozenset({86}), caps_rows = "0, 7.5\n1, 8.6\n") is None+ error = _gate(monkeypatch, sms = frozenset({86}), caps_rows = "0, 7.5\n")+ assert error and "sm_75" in error+++class TestMarkerParsing:+ @pytest.mark.parametrize("raw", [None, [], "86", ["gfx1100"], ["86", "abc"], ["8.6"], [""]])+ def test_unusable_coverage_reads_as_unknown(self, raw, monkeypatch, tmp_path):+ from utils import llama_cpp_freshness as freshness+ monkeypatch.setattr(+ freshness,+ "read_install_marker",+ lambda b: {"supported_sms": raw} if raw is not None else {},+ )+ assert LlamaCppBackend._installed_llama_cuda_sms("/x/llama-server") is None++ @pytest.mark.parametrize("raw", [["86"], [86], [" 86 "], ["75", "86"]])+ def test_the_installer_string_format_round_trips(self, raw, monkeypatch):+ """The installer writes sorted digit strings; the reader must take+ those plus the ints an older marker may hold."""+ from utils import llama_cpp_freshness as freshness++ monkeypatch.setattr(freshness, "read_install_marker", lambda b: {"supported_sms": raw})+ got = LlamaCppBackend._installed_llama_cuda_sms("/x/llama-server")+ assert got == frozenset(int(str(s).strip()) for s in raw)diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex 6c81aa51387..535115a80b2 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -6073,6 +6073,8 @@ def write_prebuilt_metadata(# their next refresh."gfx_target": choice.gfx_target,"mapped_targets": list(choice.mapped_targets or []),+ # CUDA analog of mapped_targets: SM coverage for the same runtime gate.+ "supported_sms": [str(s) for s in (choice.supported_sms or [])],"install_fingerprint": fingerprint,"prebuilt_fallback_used": prebuilt_fallback_used,"installed_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),@@ -6207,6 +6209,9 @@ def _marker_selection_patch():patch["gfx_target"] = choice.gfx_targetpatch["mapped_targets"] = targets+ sms = [str(s).strip() for s in (choice.supported_sms or []) if str(s).strip()]+ if sms and marker.get("supported_sms") != sms:+ patch["supported_sms"] = smsreturn patchdiff --git a/tests/studio/install/test_install_llama_prebuilt_logic.py b/tests/studio/install/test_install_llama_prebuilt_logic.pyindex 4b9a0ba037a..4d74b9a2e64 100644--- a/tests/studio/install/test_install_llama_prebuilt_logic.py+++ b/tests/studio/install/test_install_llama_prebuilt_logic.py@@ -2245,6 +2245,73 @@ def test_marker_rewrite_preserves_arch_fields(tmp_path: Path):assert marker["ggml_tree"] == "tree-abc"+def _cuda_choice(**overrides):+ fields = dict(+ repo = "unslothai/llama.cpp",+ tag = "b10360",+ name = "app-b10360-linux-x64-cuda13-older.tar.gz",+ url = "https://example.invalid/app.tar.gz",+ source_label = "published",+ install_kind = "linux-cuda",+ bundle_profile = "app",+ runtime_line = "cuda13",+ coverage_class = "older",+ supported_sms = ["75", "80", "86", "89"],+ expected_sha256 = "a" * 64,+ )+ fields.update(overrides)+ return AssetChoice(**fields)+++def test_write_prebuilt_metadata_records_supported_sms(tmp_path: Path):+ """The runtime SM gate reads supported_sms from the marker; without it a+ bundle installed on one GPU fails open when run on another."""+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ choice = _cuda_choice()+ write_prebuilt_metadata(+ install_dir,+ requested_tag = "latest",+ llama_tag = "b10360",+ release_tag = "b10360",+ choice = choice,+ approved_checksums = approved_release_checksums_for_asset(choice.name, "a" * 64),+ prebuilt_fallback_used = False,+ )+ marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text())+ assert marker["supported_sms"] == ["75", "80", "86", "89"]+++def test_reused_install_backfills_supported_sms(tmp_path: Path):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ marker_path.write_text(+ json.dumps({"release_tag": "b10360", "llama_backend": "auto"}) + "\n",+ encoding = "utf-8",+ )++ _sync_arch_coverage(install_dir, _cuda_choice())++ marker = json.loads(marker_path.read_text(encoding = "utf-8"))+ assert marker["supported_sms"] == ["75", "80", "86", "89"]+ assert marker["release_tag"] == "b10360"++[email protected]("sms", [None, [], ["", " "]])+def test_a_bundle_that_declares_no_sms_leaves_the_marker_alone(tmp_path: Path, sms):+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"+ original = {"release_tag": "b10360", "supported_sms": ["86", "89", "90"]}+ marker_path.write_text(json.dumps(original) + "\n", encoding = "utf-8")++ _sync_arch_coverage(install_dir, _cuda_choice(supported_sms = sms))++ marker = json.loads(marker_path.read_text(encoding = "utf-8"))+ assert marker["supported_sms"] == original["supported_sms"]++def test_existing_install_fingerprint_changes_when_cudart_pair_added(tmp_path: Path):"""A pre-#5322 CUDA install must go stale once the choice gains a runtime archive (#5106 fingerprint half)."""install_dir = tmp_path / "llama.cpp"@@ -4992,3 +5059,70 @@ def test_the_validator_stubs_still_model_the_real_signature(name):f"{name} keyword-only parameters are now {actual}; update the "f"fake_validate stubs in this file, then this list")+++def test_supported_sms_stays_out_of_the_install_fingerprint():+ """The CUDA analog of the mapped_targets fingerprint guard. Backfilling+ supported_sms onto existing markers only works while it is not hashed: in+ the payload, every install predating the field reinstalls on upgrade."""+ base = dict(+ repo = "unslothai/llama.cpp",+ tag = "b9001",+ name = "app-b9001-linux-x64-cuda13-older.tar.gz",+ url = "https://example.invalid/app.tar.gz",+ source_label = "published",+ install_kind = "linux-cuda",+ bundle_profile = "app",+ runtime_line = "cuda13",+ coverage_class = "older",+ expected_sha256 = "a" * 64,+ )+ checksums = ApprovedReleaseChecksums(+ repo = "unslothai/llama.cpp",+ release_tag = "release-1",+ upstream_tag = "b9001",+ source_commit = "deadbeef",+ artifacts = {+ source_archive_logical_name("b9001"): ApprovedArtifactHash(+ asset_name = source_archive_logical_name("b9001"),+ sha256 = "b" * 64,+ repo = "ggml-org/llama.cpp",+ kind = "upstream-source",+ ),+ },+ )+ kwargs = dict(llama_tag = "b9001", release_tag = "release-1", approved_checksums = checksums)+ without = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(+ choice = AssetChoice(**base), **kwargs+ )+ with_sms = INSTALL_LLAMA_PREBUILT.expected_install_fingerprint(+ choice = AssetChoice(**base, supported_sms = ["75", "80", "86", "89"]), **kwargs+ )+ assert without and without == with_sms, (+ "recording supported_sms changed the install fingerprint; every existing "+ "install would refresh on upgrade"+ )+++ "install_kind, runtime_line",+ [("linux-vulkan", "vulkan"), ("linux-cpu", "cpu"), ("linux-rocm", "rocm")],+)+def test_a_non_cuda_bundle_declares_no_supported_sms(tmp_path: Path, install_kind, runtime_line):+ """The runtime gate has no is_vulkan_backend guard; it stays inert there+ only because a non-CUDA bundle records an empty list, which reads as unknown+ coverage. Pin that at the writing end."""+ install_dir = tmp_path / "llama.cpp"+ install_dir.mkdir()+ choice = _cuda_choice(install_kind = install_kind, runtime_line = runtime_line, supported_sms = None)+ write_prebuilt_metadata(+ install_dir,+ requested_tag = "latest",+ llama_tag = "b10360",+ release_tag = "b10360",+ choice = choice,+ approved_checksums = approved_release_checksums_for_asset(choice.name, "a" * 64),+ prebuilt_fallback_used = False,+ )+ marker = json.loads((install_dir / "UNSLOTH_PREBUILT_INFO.json").read_text())+ assert marker["supported_sms"] == []