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: Mamba-2 hybrids use the extension-free mamba-ssm wheel when unsloth-zoo runs their conv on Triton (#14160)
Daniel Han0d7e6a4473ac
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex ad0212de98b..b4bbf31cd19 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -430,9 +430,19 @@ def _ensure_ssm_kernels(else [])if stale:+ from utils.ssm_runtime import REMOVED_PREFIX++ # "removed mamba_ssm" entries mark an uninstall, which changes the kernels as much+ # as an install does; say which happened.+ changes = ", ".join(+ f"Removed {name[len(REMOVED_PREFIX):]}"+ if name.startswith(REMOVED_PREFIX)+ else f"Installed {name}"+ for name in installed+ )logger.info(- "Installed %s after %s was imported; restarting the worker to pick it up",- ", ".join(installed),+ "%s after %s was imported; restarting the worker to pick it up",+ changes,", ".join(stale),)_send_response(@@ -441,8 +451,8 @@ def _ensure_ssm_kernels("type": "loaded","success": False,"message": (- f"Installed {', '.join(installed)} for this model; "- "restarting the model worker to use it."+ f"{changes} for this model; restarting the model worker to "+ "pick up the change."),"error_kind": SSM_RESTART_REQUIRED,},diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 0c0812db074..f34e00cc2e3 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -1367,14 +1367,23 @@ def _is_importable_isolated(import_name: str) -> bool:"""Probe the import in a child process. A wrong-arch wheel can abort or segfault in itsinitialiser instead of raising, which would kill this worker rather than fall back. A childturns that into a return code (negative = fatal signal)."""+ return _import_probe_isolated(+ import_name, "import importlib, sys; importlib.import_module(sys.argv[1])"+ )+++def _extension_importable_isolated(extension: str) -> bool:+ """_is_importable_isolated for a bare torch extension (selective_scan_cuda), which needs+ torch's libraries loaded first."""+ return _import_probe_isolated(+ extension, "import torch, importlib, sys; importlib.import_module(sys.argv[1])"+ )+++def _import_probe_isolated(import_name: str, code: str) -> bool:try:result = _sp.run(- [- sys.executable,- "-c",- "import importlib, sys; importlib.import_module(sys.argv[1])",- import_name,- ],+ [sys.executable, "-c", code, import_name],stdout = _sp.DEVNULL,stderr = _sp.DEVNULL,timeout = _IMPORT_PROBE_TIMEOUT,@@ -1444,6 +1453,7 @@ def _install_package_wheel_first(display_name: str,pypi_name: str,required: bool = False,+ extension: str | None = None,**kwargs: Any,) -> bool:"""Install a fast-path package, wheel first, and never leave an unusable one behind. The two@@ -1451,22 +1461,65 @@ def _install_package_wheel_first(before any subprocess, and offline changes nothing. Everything after them is an installattempt, so ANY unsuccessful exit -- timeout, failed install, bad import -- discards what isleft rather than leaving metadata the in-process import would pick up. Enforced here rather- than at each return because four separate exits have now been found that forgot to clean up."""- if _is_importable(import_name):+ than at each return because four separate exits have now been found that forgot to clean up.+ With *extension*, a copy without that compiled module (the extension-free mamba_ssm wheel) is+ replaced rather than accepted."""+ from utils.ssm_runtime import _unblock_import, forget_imported_modules++ _unblock_import(import_name) # an earlier in-process block; this call probes afresh++ def kernel_usable() -> bool:+ return _is_importable(import_name) and (extension is None or _is_importable(extension))++ if kernel_usable():logger.info("%s already installed", display_name)return True+ def drop_extension_free_copy() -> None:+ # The CUDA route cannot use an extension-free copy: left in place, transformers takes+ # mamba_ssm's fast path and fails in selective_scan_fn. Removing it is local (allowed+ # offline) and runs under the same per-env lock as an install.+ if extension is None or not _is_importable(import_name):+ return+ from utils.kernel_install import OPTIONAL_KERNEL_LOCK_WAIT, kernel_install_lock+ with kernel_install_lock(import_name, wait_seconds = OPTIONAL_KERNEL_LOCK_WAIT) as held:+ if not _is_importable(import_name) or _is_importable(extension):+ return+ if not held:+ # Cannot uninstall without the lock: hide it from this process instead.+ from utils.ssm_runtime import block_import, refresh_transformers_kernel_gates++ logger.info(+ "Hiding the extension-free %s from this run: its install lock is busy",+ display_name,+ )+ block_import(import_name, extension)+ refresh_transformers_kernel_gates(removed = True)+ return+ logger.info(+ "Removing the extension-free %s: this run needs its CUDA kernels", display_name+ )+ _uninstall_package(pypi_name, display_name)+ forget_imported_modules(import_name, extension)+ if _is_importable(import_name) and not _is_importable(extension):+ # Uninstall failed (read-only env, locked files): hide it from this process.+ from utils.ssm_runtime import block_import, refresh_transformers_kernel_gates+ block_import(import_name, extension)+ refresh_transformers_kernel_gates(removed = True)+if _model_offline_mode_enabled() or _package_installs_offline():logger.info("Skipping %s installation while offline", display_name)+ drop_extension_free_copy()return False# The runtime's failed-attempt memo (same key): the eager install and the fast-path hook, or a# chat load in the same process, never repeat a failed (possibly half-hour) build.from utils.ssm_runtime import _FAILED_INSTALLS, _failure_key- failure_key = _failure_key(import_name)+ failure_key = _failure_key(import_name, kwargs.get("wheel_url_builder"))if failure_key in _FAILED_INSTALLS:logger.info("%s already failed to install in this process; not retrying", display_name)+ drop_extension_free_copy()return Falsefrom utils.kernel_install import (@@ -1491,10 +1544,28 @@ def _install_package_wheel_first(f"Could not take the {display_name} install lock (another process is installing ""it, or the lock is unavailable); continuing without it",)+ if (+ extension is not None+ and _is_importable(import_name)+ and not _is_importable(extension)+ ):+ # Not ours to uninstall without the lock, but this run must not use it: hidden from+ # this process, transformers takes its torch path instead of selective_scan_fn.+ from utils.ssm_runtime import block_import, refresh_transformers_kernel_gates+ block_import(import_name, extension)+ refresh_transformers_kernel_gates(removed = True)return False- if _is_importable(import_name):+ if kernel_usable():logger.info("%s installed by another process", display_name)+ if extension is not None:+ forget_imported_modules(import_name, extension)return True+ # Importable but without the compiled module: the extension-free wheel, replaced here.+ replacing = extension is not None and _is_importable(import_name)+ if replacing:+ _send_status(+ event_queue, f"Replacing the extension-free {display_name} with its CUDA kernels..."+ )installed = Falsetry:installed = _attempt_package_install(@@ -1502,13 +1573,24 @@ def _install_package_wheel_first(import_name = import_name,display_name = display_name,pypi_name = pypi_name,+ extension = extension,+ replacing = replacing,**kwargs,)return installedfinally:+ if replacing:+ # The process imported the extension-free copy: the next import must load what is+ # installed now (or nothing, after a failed replacement removes it).+ forget_imported_modules(import_name, extension)if not installed:_FAILED_INSTALLS.add(failure_key)_reject_install(event_queue, pypi_name, display_name, "will not import")+ if extension is not None and _is_importable(import_name):+ # The extension-free copy could not be removed: hide it from this process.+ from utils.ssm_runtime import block_import, refresh_transformers_kernel_gates+ block_import(import_name, extension)+ refresh_transformers_kernel_gates(removed = True)def _attempt_package_install(@@ -1525,8 +1607,17 @@ def _attempt_package_install(pypi_spec: str | None = None,pypi_status_message: str | None = None,allow_source_build: bool = True,+ extension: str | None = None,+ replacing: bool = False,) -> bool:"""The install itself. Call it through _install_package_wheel_first, never directly."""++ def _verify() -> bool:+ # Out of process: a bad wheel can take the worker down with it.+ if not _is_importable_isolated(import_name):+ return False+ return extension is None or _extension_importable_isolated(extension)+# Set when a wheel installed but would not import; see the uninstall before the fallback.wheel_rejected = False@@ -1565,8 +1656,7 @@ def _attempt_package_install(outcome = install_prebuilt(wheel_url,install = install_wheel,- # Out of process: a bad wheel can take the worker down with it.- verify = lambda: _is_importable_isolated(import_name),+ verify = _verify,on_failed = lambda installer, result: logger.warning("%s failed to install %s wheel:\n%s",installer,@@ -1575,6 +1665,8 @@ def _attempt_package_install(),use_uv = bool(shutil.which("uv")),run = _sp.run,+ # Over the extension-free copy of the same version, which uv / pip would keep.+ **({"reinstall": True} if replacing else {}),)if outcome == "installed":logger.info("Installed prebuilt %s wheel successfully", display_name)@@ -1629,8 +1721,9 @@ def _attempt_package_install(else:pypi_status_message = f"Installing {display_name} from PyPI for faster training..."- if wheel_rejected:- # Remove it rather than install over it: pip/uv would report the broken distribution as already satisfying the+ if wheel_rejected or replacing:+ # Remove it rather than install over it (a broken wheel, or the extension-free copy being+ # replaced): pip/uv would report the broken distribution as already satisfying the# spec and do nothing. --force-reinstall is not the answer either, since both scope it to the whole resolved# transaction, which for flash-attn means torch and the running CUDA stack. A failure here is caught by the# _reject_install in the finally below, which is reached from every exit.@@ -1708,7 +1801,7 @@ def _attempt_package_install(# rc=0 is not proof again here: pip/uv exit 0 on "Requirement already satisfied" without installing anything.# Returning False is enough; the caller's finally discards it.- if not _is_importable_isolated(import_name):+ if not _verify():logger.warning("%s installed from PyPI but will not import", display_name)return False@@ -1766,7 +1859,8 @@ def _ensure_mamba_ssm(*,required: bool | None = None,essential: bool | None = None,-) -> None:+ triton_only: bool = False,+) -> bool | None:# `required` is the config-resolved answer (resolved_model_is_ssm); the name is the fallback.# `essential`: Nemotron-H, Falcon-H1, Granite-4.0-H, which may build it from source. Training# stays best effort as at 9f5b13325: their native transformers path can run without it, so a@@ -1788,6 +1882,18 @@ def _ensure_mamba_ssm(_send_status(event_queue, "mamba-ssm needs Triton on Windows (triton-windows); skipping it")return+ if triton_only:+ from utils.wheel_utils import mamba_ssm_pure_wheel_url+ logger.info("Mamba-2 model on Triton kernels; setting up the extension-free mamba-ssm")+ # True when it imports; the caller then skips causal-conv1d and the CUDA mamba-ssm.+ return _install_package_wheel_first(+ event_queue = event_queue,+ **_pinned_kernel_kwargs(MAMBA_SSM),+ wheel_url_builder = mamba_ssm_pure_wheel_url,+ allow_source_build = False,+ required = essential,+ )+if not essential and not _is_importable(MAMBA_SSM.import_name):from utils.ssm_runtime import _mamba_ssm_floor_reasonreason = _mamba_ssm_floor_reason()@@ -1796,11 +1902,15 @@ def _ensure_mamba_ssm(returnlogger.info("SSM model detected; setting up mamba-ssm after causal-conv1d")+ from utils.ssm_runtime import MAMBA_SSM_EXTENSION+_install_package_wheel_first(event_queue = event_queue,**_pinned_kernel_kwargs(MAMBA_SSM),allow_source_build = essential,required = essential,+ # Never settle for the extension-free wheel a Mamba-2 load may have left here.+ extension = MAMBA_SSM_EXTENSION,)@@ -4180,9 +4290,36 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->model_load_target,_worker_hf_token(config),adapter_base = config.get("adapter_base_pin") or None,+ # Whether the load runs a checkpoint's remote code, not just whether it has some.+ trust_remote_code = bool(config.get("trust_remote_code", False)),)is_ssm = kernels.mamba_ssmwants_causal_conv1d = kernels.causal_conv1d+ from utils.ssm_runtime import mamba2_runs_on_triton++ # Mamba-2 families on a zoo with the Triton conv drop-ins: no causal-conv1d, and the+ # extension-free mamba_ssm wheel.+ triton_only = mamba2_runs_on_triton(kernels)+ if triton_only:+ # The extension-free wheel first. Not published, refused or not importable: this+ # run takes the CUDA-wheel route (causal-conv1d, then mamba-ssm) instead.+ triton_only = bool(+ _ensure_mamba_ssm(+ event_queue,+ model_name,+ required = is_ssm,+ essential = kernels.mamba_ssm_required,+ triton_only = True,+ )+ )+ if triton_only:+ wants_causal_conv1d = False+ else:+ _send_status(+ event_queue,+ "The extension-free mamba-ssm wheel is not available; using the CUDA "+ "kernels instead",+ )_ensure_causal_conv1d_fast_path(event_queue,model_name,@@ -4193,12 +4330,13 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->model_name,install_causal_conv1d = wants_causal_conv1d,)- _ensure_mamba_ssm(- event_queue,- model_name,- required = is_ssm,- essential = kernels.mamba_ssm_required,- )+ if not triton_only:+ _ensure_mamba_ssm(+ event_queue,+ model_name,+ required = is_ssm,+ essential = kernels.mamba_ssm_required,+ )_ensure_flash_attn_for_long_context(event_queue,int(config.get("max_seq_length", 2048)),diff --git a/studio/backend/tests/test_ssm_mamba2_triton.py b/studio/backend/tests/test_ssm_mamba2_triton.pynew file mode 100644index 00000000000..b67c1d5bcf9--- /dev/null+++ b/studio/backend/tests/test_ssm_mamba2_triton.py@@ -0,0 +1,896 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Mamba-2 families on a zoo with Triton causal conv drop-ins take the extension-free mamba_ssm+wheel and skip causal-conv1d; everything else keeps the CUDA wheels."""++import sys+import types+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++from utils import ssm_runtime, wheel_utils # noqa: E402+++def _kernels(+ model_types,+ *,+ fatal = False,+ remote = frozenset(),+ remote_used = False,+ ssm = True,+):+ return ssm_runtime.SsmKernels(+ causal_conv1d = True,+ mamba_ssm = ssm,+ mamba_ssm_required = True,+ probe = "m",+ model_types = frozenset(model_types),+ remote_code = remote,+ mamba_ssm_fatal = fatal,+ remote_code_used = remote_used,+ )+++def capable(monkeypatch, tmp_path):+ """A host where every gate passes; tests flip one at a time."""+ zoo = tmp_path / "unsloth_zoo"+ (zoo / "temporary_patches").mkdir(parents = True)+ (zoo / "temporary_patches" / "gdn_causal_conv1d.py").write_text(+ '_MAMBA2_MODELING = ("nemotron_h",)\ndef install_mamba_ssm_triton_conv():\n return True\n'+ )+ real_find_spec = ssm_runtime.importlib.util.find_spec++ def find_spec(name, *a, **k):+ if name == "unsloth_zoo":+ return types.SimpleNamespace(submodule_search_locations = [str(zoo)])+ if name == "triton":+ return object()+ return real_find_spec(name, *a, **k)++ monkeypatch.setattr(ssm_runtime.importlib.util, "find_spec", find_spec)+ monkeypatch.setattr(+ ssm_runtime, "_torch_env", lambda: {"cuda_version": "13.0", "cuda_major": "13"}+ )+ monkeypatch.setattr(ssm_runtime, "_transformers_resolves_kernels_per_function", lambda: True)+ monkeypatch.setattr(ssm_runtime, "_mamba_ssm_floor_reason", lambda: None)+ monkeypatch.delenv("UNSLOTH_MAMBA_CUDA_KERNELS", raising = False)+ return zoo+++ "types_",+ [{"nemotron_h"}, {"falcon_h1"}, {"granitemoehybrid"}, {"bamba"}, {"zamba2"}, {"mamba2"}],+)+def test_mamba2_families_run_on_triton(capable, types_):+ assert ssm_runtime.mamba2_runs_on_triton(_kernels(types_))+++ "types_", [{"mamba"}, {"falcon_mamba"}, {"jamba"}, {"zamba"}, set(), {"nemotron_h", "jamba"}]+)+def test_mamba1_families_and_unknown_types_keep_cuda_wheels(capable, types_):+ assert not ssm_runtime.mamba2_runs_on_triton(_kernels(types_))+++def test_each_gate_keeps_the_cuda_wheels(capable, monkeypatch):+ k = _kernels({"nemotron_h"})+ assert ssm_runtime.mamba2_runs_on_triton(k)+ assert not ssm_runtime.mamba2_runs_on_triton(_kernels({"nemotron_h"}, fatal = True))+ assert not ssm_runtime.mamba2_runs_on_triton(+ _kernels({"nemotron_h"}, remote = frozenset({("a", "b")}), remote_used = True)+ )+ # A config that only advertises remote code (native class used) keeps the Triton route.+ assert ssm_runtime.mamba2_runs_on_triton(+ _kernels({"nemotron_h"}, remote = frozenset({("a", "b")}))+ )+ assert not ssm_runtime.mamba2_runs_on_triton(_kernels({"nemotron_h"}, ssm = False))+ monkeypatch.setenv("UNSLOTH_MAMBA_CUDA_KERNELS", "1")+ assert not ssm_runtime.mamba2_runs_on_triton(k)+ monkeypatch.delenv("UNSLOTH_MAMBA_CUDA_KERNELS")+ monkeypatch.setattr(+ ssm_runtime, "_torch_env", lambda: {"hip_version": "7.0", "cuda_version": None}+ )+ assert not ssm_runtime.mamba2_runs_on_triton(k)+ monkeypatch.setattr(+ ssm_runtime, "_torch_env", lambda: {"cuda_version": "13.0", "cuda_major": "13"}+ )+ monkeypatch.setattr(ssm_runtime, "_transformers_resolves_kernels_per_function", lambda: False)+ assert not ssm_runtime.mamba2_runs_on_triton(k)+ monkeypatch.setattr(ssm_runtime, "_transformers_resolves_kernels_per_function", lambda: True)+ (capable / "temporary_patches" / "gdn_causal_conv1d.py").write_text(+ "def patch_gdn_causal_conv1d():\n pass\n"+ )+ assert not ssm_runtime.mamba2_runs_on_triton(k)+++def test_triton_load_installs_only_the_pure_mamba_ssm_wheel(monkeypatch):+ calls = []+ monkeypatch.setattr(ssm_runtime, "_install_kernel", lambda **k: calls.append(k) or True)+ ssm_runtime.ensure_ssm_runtime(+ "nvidia/NVIDIA-Nemotron-Nano-9B-v2",+ wants_causal_conv1d = True,+ is_ssm = True,+ mamba_ssm_required = True,+ mamba_ssm_fatal = False,+ mamba2_triton = True,+ )+ assert [c["import_name"] for c in calls] == ["mamba_ssm"]+ assert calls[0]["allow_source_build"] is False+ url = calls[0]["wheel_url_builder"]({"platform_tag": "win_amd64"})+ assert url.endswith("/prebuilt-wheels-cu13/mamba_ssm-2.3.2.post1-py3-none-any.whl")+ assert url == wheel_utils.mamba_ssm_pure_wheel_url(None)+++def test_cuda_load_still_installs_both_kernels(monkeypatch):+ calls = []+ monkeypatch.setattr(ssm_runtime, "_install_kernel", lambda **k: calls.append(k) or True)+ monkeypatch.setattr(ssm_runtime.sys, "platform", "linux")+ ssm_runtime.ensure_ssm_runtime(+ "nvidia/NVIDIA-Nemotron-Nano-9B-v2",+ wants_causal_conv1d = True,+ is_ssm = True,+ mamba_ssm_required = True,+ mamba_ssm_fatal = False,+ )+ assert [c["import_name"] for c in calls] == ["causal_conv1d", "mamba_ssm"]+ assert all(c.get("wheel_url_builder") is None for c in calls)+++def test_install_kernel_uses_the_wheel_url_builder(monkeypatch):+ seen = {}+ monkeypatch.setattr(+ ssm_runtime,+ "_torch_env",+ lambda: {"cuda_version": "13.0", "cuda_major": "13", "platform_tag": "linux_x86_64"},+ )+ monkeypatch.setattr(ssm_runtime, "url_exists", lambda url: seen.setdefault("url", url) and True)+ monkeypatch.setattr(+ ssm_runtime,+ "install_prebuilt",+ lambda url, **k: seen.setdefault("installed", url) and "installed",+ )+ monkeypatch.setattr(+ ssm_runtime,+ "direct_wheel_url",+ lambda **k: pytest.fail("platform wheel must not be resolved"),+ )+ assert ssm_runtime._install_kernel_locked(+ **ssm_runtime._pinned_kwargs(ssm_runtime.MAMBA_SSM),+ status_cb = None,+ run = None,+ allow_source_build = False,+ wheel_url_builder = wheel_utils.mamba_ssm_pure_wheel_url,+ )+ assert seen["installed"] == wheel_utils.mamba_ssm_pure_wheel_url()+++def test_training_worker_routes_triton_loads_to_the_pure_wheel(monkeypatch):+ from unittest import mock++ from core.training import worker++ install_mock = mock.Mock(return_value = True)+ monkeypatch.setattr(worker, "_install_package_wheel_first", install_mock)+ monkeypatch.setattr(worker.sys, "platform", "linux")+ worker._ensure_mamba_ssm(+ event_queue = [],+ model_name = "nvidia/NVIDIA-Nemotron-Nano-9B-v2",+ required = True,+ essential = True,+ triton_only = True,+ )+ kwargs = install_mock.call_args.kwargs+ assert kwargs["wheel_url_builder"] is wheel_utils.mamba_ssm_pure_wheel_url+ assert kwargs["allow_source_build"] is False and kwargs["import_name"] == "mamba_ssm"+ # And the worker's load path asks the shared predicate before installing anything.+ src = (_BACKEND / "core" / "training" / "worker.py").read_text(encoding = "utf-8")+ assert "triton_only = mamba2_runs_on_triton(kernels)" in src+++# ── Fallback: no usable extension-free wheel -> the CUDA-wheel route ──────────+++def _route(monkeypatch, *, pure_ok):+ calls = []++ def install(**kwargs):+ calls.append((kwargs["import_name"], kwargs.get("wheel_url_builder")))+ if kwargs.get("wheel_url_builder") is wheel_utils.mamba_ssm_pure_wheel_url:+ return pure_ok+ return True++ monkeypatch.setattr(ssm_runtime, "_install_kernel", install)+ monkeypatch.setattr(ssm_runtime.sys, "platform", "linux")+ ssm_runtime.ensure_ssm_runtime(+ "nvidia/NVIDIA-Nemotron-Nano-9B-v2",+ wants_causal_conv1d = True,+ is_ssm = True,+ mamba_ssm_required = True,+ mamba_ssm_fatal = False,+ mamba2_triton = True,+ )+ return calls+++def test_a_missing_pure_wheel_falls_back_to_the_cuda_route(monkeypatch):+ pure = wheel_utils.mamba_ssm_pure_wheel_url+ assert _route(monkeypatch, pure_ok = False) == [+ ("mamba_ssm", pure),+ ("causal_conv1d", None),+ ("mamba_ssm", None),+ ]+ assert _route(monkeypatch, pure_ok = True) == [("mamba_ssm", pure)]+++def real_install(monkeypatch, tmp_path):+ """_install_kernel for real (lock, memo, cleanup), with the network and pip faked."""+ monkeypatch.setenv("UNSLOTH_KERNEL_LOCK_DIR", str(tmp_path / "locks"))+ monkeypatch.setattr(ssm_runtime, "_FAILED_INSTALLS", set())+ monkeypatch.setattr(ssm_runtime.sys, "platform", "linux")+ monkeypatch.setattr(+ ssm_runtime,+ "_torch_env",+ lambda: {+ "cuda_version": "13.0",+ "cuda_major": "13",+ "platform_tag": "linux_x86_64",+ "torch_mm": "2.13",+ },+ )+ import utils.utils as utils_utils++ monkeypatch.setattr(utils_utils, "package_installs_offline", lambda: False)+ monkeypatch.setattr(ssm_runtime, "_remove_broken", lambda *a, **k: None)+ state = {"importable": set(), "installed": [], "probed": []}+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: name in state["importable"])+ cuda_url = "https://example.invalid/mamba_ssm-2.3.2.post1+cu13torch2.13-cp313-linux_x86_64.whl"+ monkeypatch.setattr(ssm_runtime, "direct_wheel_url", lambda **k: cuda_url)+ state["cuda_url"] = cuda_url+ return state+++def _pure_then_cuda(+ state,+ monkeypatch,+ *,+ pure_exists,+ pure_outcome = "installed",+):+ pure_url = wheel_utils.mamba_ssm_pure_wheel_url()++ def url_exists(url):+ state["probed"].append(url)+ return pure_exists if url == pure_url else True++ def install_prebuilt(url, *, verify, **kwargs):+ state["installed"].append(url)+ if url == pure_url and pure_outcome != "installed":+ return pure_outcome+ state["importable"].add("mamba_ssm")+ if url != pure_url:+ state["importable"].add(ssm_runtime.MAMBA_SSM_EXTENSION) # the CUDA wheel's scan+ return "installed" if verify() else "rejected"++ monkeypatch.setattr(ssm_runtime, "url_exists", url_exists)+ monkeypatch.setattr(ssm_runtime, "install_prebuilt", install_prebuilt)+ ssm_runtime.ensure_ssm_runtime(+ "nvidia/NVIDIA-Nemotron-Nano-9B-v2",+ wants_causal_conv1d = False,+ is_ssm = True,+ mamba_ssm_required = True,+ mamba_ssm_fatal = False,+ mamba2_triton = True,+ )+ return pure_url+++def test_a_404_on_the_pure_wheel_installs_the_cuda_wheel(real_install, monkeypatch):+ pure_url = _pure_then_cuda(real_install, monkeypatch, pure_exists = False)+ assert real_install["probed"] == [pure_url, real_install["cuda_url"]]+ assert real_install["installed"] == [real_install["cuda_url"]]+ assert "mamba_ssm" in real_install["importable"]++[email protected]("outcome", ["rejected", "failed"])+def test_a_pure_wheel_that_does_not_install_or_import_falls_back(+ real_install, monkeypatch, outcome+):+ pure_url = _pure_then_cuda(real_install, monkeypatch, pure_exists = True, pure_outcome = outcome)+ assert real_install["installed"] == [pure_url, real_install["cuda_url"]]+ assert "mamba_ssm" in real_install["importable"]+++def test_the_pure_failure_is_remembered_on_its_own_key(real_install, monkeypatch):+ pure_url = _pure_then_cuda(real_install, monkeypatch, pure_exists = False)+ keys = ssm_runtime._FAILED_INSTALLS+ assert ssm_runtime._failure_key("mamba_ssm", wheel_utils.mamba_ssm_pure_wheel_url) in keys+ # The CUDA mamba-ssm installed: nothing remembered against it.+ assert ssm_runtime._failure_key("mamba_ssm") not in keys+ # A later load in this process skips the pure probe and goes straight to the CUDA wheel.+ real_install["importable"].clear()+ real_install["probed"].clear()+ real_install["installed"].clear()+ _pure_then_cuda(real_install, monkeypatch, pure_exists = False)+ assert pure_url not in real_install["probed"]+ assert real_install["installed"] == [real_install["cuda_url"]]+++def test_training_worker_reports_whether_the_pure_wheel_took(monkeypatch):+ from unittest import mock++ from core.training import worker++ monkeypatch.setattr(worker.sys, "platform", "linux")+ for result in (True, False):+ monkeypatch.setattr(worker, "_install_package_wheel_first", mock.Mock(return_value = result))+ assert (+ worker._ensure_mamba_ssm(+ event_queue = [],+ model_name = "nvidia/NVIDIA-Nemotron-Nano-9B-v2",+ required = True,+ essential = True,+ triton_only = True,+ )+ is result+ )+ src = (_BACKEND / "core" / "training" / "worker.py").read_text(encoding = "utf-8")+ # On a False answer the run takes the CUDA route: causal-conv1d, then the CUDA mamba-ssm.+ start = src.index("triton_only = mamba2_runs_on_triton(kernels)")+ block = src[start : src.index("_ensure_flash_attn_for_long_context(", start)]+ assert "if not triton_only:" in block+ assert block.index("_ensure_causal_conv1d_fast_path(") < block.index("if not triton_only:")+++def test_training_failure_memo_follows_the_wheel_source(monkeypatch):+ from core.training import worker++ seen = []+ monkeypatch.setattr(worker, "_is_importable", lambda name: False)+ monkeypatch.setattr(worker, "_model_offline_mode_enabled", lambda: False)+ monkeypatch.setattr(worker, "_package_installs_offline", lambda: False)+ pure_failed = ssm_runtime._failure_key("mamba_ssm", wheel_utils.mamba_ssm_pure_wheel_url)+ monkeypatch.setattr(ssm_runtime, "_FAILED_INSTALLS", {pure_failed})+ monkeypatch.setattr(+ worker,+ "_attempt_package_install",+ lambda **k: seen.append(k.get("wheel_url_builder")) or True,+ )+ kwargs = worker._pinned_kernel_kwargs(worker.MAMBA_SSM)+ # The remembered pure failure skips the pure attempt ...+ assert (+ worker._install_package_wheel_first(+ event_queue = [], **kwargs, wheel_url_builder = wheel_utils.mamba_ssm_pure_wheel_url+ )+ is False+ )+ # ... but not the CUDA wheel.+ assert worker._install_package_wheel_first(event_queue = [], **kwargs) is True+ assert seen == [None]+++# ── The CUDA route never settles for the extension-free wheel ─────────────────+++def _cuda_route(+ state,+ monkeypatch,+ *,+ cuda_exists = True,+ required = True,+ outcome = "installed",+):+ state["kwargs"] = []+ state["removed"] = []+ state["importable"].add("causal_conv1d") # every SSM load also wants it; already present here++ def install_prebuilt(url, *, verify, **kwargs):+ state["installed"].append(url)+ state["kwargs"].append(kwargs)+ if outcome != "installed":+ return outcome+ state["importable"].update({"mamba_ssm", ssm_runtime.MAMBA_SSM_EXTENSION})+ return "installed" if verify() else "rejected"++ monkeypatch.setattr(ssm_runtime, "url_exists", lambda url: cuda_exists)+ monkeypatch.setattr(ssm_runtime, "install_prebuilt", install_prebuilt)+ monkeypatch.setattr(+ ssm_runtime,+ "_remove_broken",+ lambda pypi_name, *a, **k: state["removed"].append(pypi_name)+ or state["importable"].discard("mamba_ssm"),+ )+ return ssm_runtime.ensure_ssm_runtime(+ "tiiuae/falcon-mamba-7b",+ wants_causal_conv1d = False,+ is_ssm = True,+ mamba_ssm_required = required,+ mamba_ssm_fatal = False,+ )+++def test_cuda_route_replaces_the_extension_free_wheel(real_install, monkeypatch):+ real_install["importable"].add("mamba_ssm") # a Mamba-2 load left the extension-free wheel+ monkeypatch.setitem(sys.modules, "mamba_ssm", types.ModuleType("mamba_ssm"))+ monkeypatch.setitem(sys.modules, "mamba_ssm.ops", types.ModuleType("mamba_ssm.ops"))+ installed = _cuda_route(real_install, monkeypatch)+ assert real_install["installed"] == [real_install["cuda_url"]]+ assert real_install["kwargs"][0].get("reinstall") is True+ assert installed == ["mamba_ssm"] # new to this worker: restart detection sees it+ # The stale extension-free modules are gone, so the next import loads the CUDA copy.+ assert "mamba_ssm" not in sys.modules and "mamba_ssm.ops" not in sys.modules+++def test_cuda_route_accepts_a_mamba_ssm_with_its_scan(real_install, monkeypatch):+ real_install["importable"].update({"mamba_ssm", ssm_runtime.MAMBA_SSM_EXTENSION})+ assert _cuda_route(real_install, monkeypatch) == []+ assert real_install["installed"] == []+++def test_a_failed_replacement_removes_the_extension_free_wheel(real_install, monkeypatch):+ real_install["importable"].add("mamba_ssm")+ installed = _cuda_route(real_install, monkeypatch, cuda_exists = False, required = False)+ assert installed == [f"{ssm_runtime.REMOVED_PREFIX}mamba_ssm"] # reported like an install+ # Left behind, a Mamba-1 load would take the fast path and fail in selective_scan_fn.+ assert real_install["removed"] == ["mamba-ssm"]+ assert "mamba_ssm" not in real_install["importable"]+++def test_a_remembered_cuda_failure_still_drops_a_reinstalled_extension_free_wheel(+ real_install, monkeypatch+):+ # The CUDA route failed earlier in this process, then a Mamba-2 load put the extension-free+ # wheel back: a Mamba-1 load must not keep it, even without retrying the CUDA install.+ real_install["importable"].add("mamba_ssm")+ ssm_runtime._FAILED_INSTALLS.add(ssm_runtime._failure_key("mamba_ssm", None))+ installed = _cuda_route(real_install, monkeypatch, required = False)+ assert installed == [f"{ssm_runtime.REMOVED_PREFIX}mamba_ssm"]+ assert real_install["installed"] == [] # not retried+ assert real_install["removed"] == ["mamba-ssm"]+ assert "mamba_ssm" not in real_install["importable"]+++def test_the_pure_route_keeps_an_installed_cuda_mamba_ssm(real_install, monkeypatch):+ real_install["importable"].update({"mamba_ssm", ssm_runtime.MAMBA_SSM_EXTENSION})+ monkeypatch.setattr(+ ssm_runtime, "install_prebuilt", lambda *a, **k: pytest.fail("no downgrade")+ )+ assert (+ ssm_runtime.ensure_ssm_runtime(+ "nvidia/NVIDIA-Nemotron-Nano-9B-v2",+ wants_causal_conv1d = True,+ is_ssm = True,+ mamba_ssm_required = True,+ mamba_ssm_fatal = False,+ mamba2_triton = True,+ )+ == []+ )+++def test_training_cuda_route_replaces_the_extension_free_wheel(monkeypatch, tmp_path):+ from core.training import worker++ importable = {"mamba_ssm"}+ seen = {}+ monkeypatch.setattr(worker, "_is_importable", lambda name: name in importable)+ monkeypatch.setattr(worker, "_model_offline_mode_enabled", lambda: False)+ monkeypatch.setattr(worker, "_package_installs_offline", lambda: False)+ monkeypatch.setattr(ssm_runtime, "_FAILED_INSTALLS", set())+ monkeypatch.setenv("UNSLOTH_KERNEL_LOCK_DIR", str(tmp_path / "locks"))++ def attempt(**kwargs):+ seen.update(kwargs)+ importable.add(ssm_runtime.MAMBA_SSM_EXTENSION)+ return True++ monkeypatch.setattr(worker, "_attempt_package_install", attempt)+ monkeypatch.setitem(sys.modules, "mamba_ssm", types.ModuleType("mamba_ssm"))+ from unittest import mock++ assert worker._install_package_wheel_first(+ event_queue = mock.Mock(),+ **worker._pinned_kernel_kwargs(worker.MAMBA_SSM),+ extension = ssm_runtime.MAMBA_SSM_EXTENSION,+ )+ assert seen["replacing"] is True and seen["extension"] == ssm_runtime.MAMBA_SSM_EXTENSION+ assert "mamba_ssm" not in sys.modules+ # And the CUDA-route call asks for the extension.+ src = (_BACKEND / "core" / "training" / "worker.py").read_text(encoding = "utf-8")+ assert "extension = MAMBA_SSM_EXTENSION" in src+++# ── Remote code counts only when the load runs it ─────────────────────────────+++ "trust, native, used", [(False, True, False), (True, True, True), (False, False, True)]+)+def test_remote_code_used_follows_the_selected_implementation(monkeypatch, trust, native, used):+ config = {+ "model_type": "nemotron_h",+ "architectures": ["NemotronHForCausalLM"],+ "auto_map": {"AutoModelForCausalLM": "modeling_nemotron_h.NemotronHForCausalLM"},+ }+ monkeypatch.setattr(ssm_runtime, "native_modeling_available", lambda t: native)+ monkeypatch.setattr(ssm_runtime, "_remote_source_text", lambda *a, **k: "import torch\n")+ kernels = ssm_runtime.resolve_ssm_kernels(+ "nvidia/NVIDIA-Nemotron-Nano-9B-v2",+ "nvidia/NVIDIA-Nemotron-Nano-9B-v2",+ None,+ model_config = config,+ trust_remote_code = trust,+ )+ assert kernels.remote_code # restart detection still knows the remote modules+ assert kernels.remote_code_used is used+++# ── Round 3: nested auto_map, offline removal, GPU floor, source replacement, removal reporting ─+++def test_the_triton_route_follows_the_mamba_triton_gpu_floor(capable, monkeypatch):+ k = _kernels({"nemotron_h"})+ assert ssm_runtime.mamba2_runs_on_triton(k)+ monkeypatch.setattr(ssm_runtime, "_mamba_ssm_floor_reason", lambda: "needs an sm80 GPU")+ assert not ssm_runtime.mamba2_runs_on_triton(k)+++def test_a_nested_auto_map_counts_as_remote_code(monkeypatch):+ config = {+ "model_type": "composite",+ "text_config": {+ "model_type": "nemotron_h",+ "auto_map": {"AutoModelForCausalLM": "modeling_nemotron_h.NemotronHForCausalLM"},+ },+ }+ monkeypatch.setattr(ssm_runtime, "native_modeling_available", lambda t: True)+ monkeypatch.setattr(ssm_runtime, "_remote_source_text", lambda *a, **k: "import torch\n")+ assert ssm_runtime._remote_model_sources("org/m", config) == [+ ("org/m", "modeling_nemotron_h.py")+ ]+ kernels = ssm_runtime.resolve_ssm_kernels(+ "org/m", "org/m", None, model_config = config, trust_remote_code = True+ )+ assert kernels.remote_code and kernels.remote_code_used+ assert not ssm_runtime.mamba2_runs_on_triton(kernels)+++def test_offline_still_drops_an_extension_free_copy(real_install, monkeypatch):+ import utils.utils as utils_utils++ monkeypatch.setattr(utils_utils, "package_installs_offline", lambda: True)+ real_install["importable"].update({"mamba_ssm", "causal_conv1d"})+ removed = []+ monkeypatch.setattr(+ ssm_runtime,+ "_remove_broken",+ lambda pypi_name, *a, **k: removed.append(pypi_name)+ or real_install["importable"].discard("mamba_ssm"),+ )+ monkeypatch.setattr(ssm_runtime, "install_prebuilt", lambda *a, **k: pytest.fail("offline"))+ installed = ssm_runtime.ensure_ssm_runtime(+ "tiiuae/falcon-mamba-7b",+ wants_causal_conv1d = False,+ is_ssm = True,+ mamba_ssm_required = False,+ mamba_ssm_fatal = False,+ )+ assert removed == ["mamba-ssm"]+ assert installed == [f"{ssm_runtime.REMOVED_PREFIX}mamba_ssm"]+++def test_a_failed_replacement_is_reported_like_an_install(real_install, monkeypatch):+ real_install["importable"].add("mamba_ssm")+ installed = _cuda_route(real_install, monkeypatch, cuda_exists = False, required = False)+ assert installed == [f"{ssm_runtime.REMOVED_PREFIX}mamba_ssm"]+++def test_a_removal_refreshes_cached_kernel_modules(monkeypatch):+ calls = []++ def provision_ensure(*a, **k):+ return [f"{ssm_runtime.REMOVED_PREFIX}mamba_ssm"]++ monkeypatch.setattr(ssm_runtime, "ensure_ssm_runtime", provision_ensure)+ monkeypatch.setattr(+ ssm_runtime, "resolve_ssm_kernels", lambda *a, **k: _kernels({"falcon_mamba"})+ )+ monkeypatch.setattr(+ ssm_runtime, "refresh_transformers_kernel_gates", lambda **k: calls.append(k)+ )+ ssm_runtime.provision_ssm_kernels("m", "m", None)+ assert calls == [{"removed": True}]+++def test_refresh_after_a_removal_drops_cached_modules(monkeypatch):+ kernel_module = types.ModuleType("mamba_ssm")+ mapping = {"mamba-ssm": kernel_module, "flash-attn": kernel_module}+ monkeypatch.setitem(sys.modules, "transformers", types.SimpleNamespace())+ monkeypatch.setitem(sys.modules, "transformers.utils.import_utils", types.SimpleNamespace())+ monkeypatch.setitem(+ sys.modules,+ "transformers.integrations.hub_kernels",+ types.SimpleNamespace(_KERNEL_MODULE_MAPPING = mapping),+ )+ ssm_runtime.refresh_transformers_kernel_gates()+ assert "mamba-ssm" in mapping # an install only clears cached None+ ssm_runtime.refresh_transformers_kernel_gates(removed = True)+ assert mapping == {"flash-attn": kernel_module}+++def _training_env(+ monkeypatch,+ tmp_path,+ importable,+ offline = False,+):+ from core.training import worker++ uninstalled = []+ monkeypatch.setattr(worker, "_is_importable", lambda name: name in importable)+ monkeypatch.setattr(worker, "_model_offline_mode_enabled", lambda: offline)+ monkeypatch.setattr(worker, "_package_installs_offline", lambda: offline)+ monkeypatch.setattr(ssm_runtime, "_FAILED_INSTALLS", set())+ monkeypatch.setenv("UNSLOTH_KERNEL_LOCK_DIR", str(tmp_path / "locks"))+ monkeypatch.setattr(+ worker,+ "_uninstall_package",+ lambda pypi_name, display_name: uninstalled.append(pypi_name)+ or importable.discard("mamba_ssm")+ or True,+ )+ return worker, uninstalled+++def test_training_offline_drops_an_extension_free_copy(monkeypatch, tmp_path):+ from unittest import mock++ importable = {"mamba_ssm"}+ worker, uninstalled = _training_env(monkeypatch, tmp_path, importable, offline = True)+ assert not worker._install_package_wheel_first(+ event_queue = mock.Mock(),+ **worker._pinned_kernel_kwargs(worker.MAMBA_SSM),+ extension = ssm_runtime.MAMBA_SSM_EXTENSION,+ )+ assert uninstalled == ["mamba-ssm"]+++def test_training_remembered_failure_drops_an_extension_free_copy(monkeypatch, tmp_path):+ from unittest import mock++ importable = {"mamba_ssm"}+ worker, uninstalled = _training_env(monkeypatch, tmp_path, importable)+ ssm_runtime._FAILED_INSTALLS.add(ssm_runtime._failure_key("mamba_ssm"))+ assert not worker._install_package_wheel_first(+ event_queue = mock.Mock(),+ **worker._pinned_kernel_kwargs(worker.MAMBA_SSM),+ extension = ssm_runtime.MAMBA_SSM_EXTENSION,+ )+ assert uninstalled == ["mamba-ssm"]+++def test_training_source_build_replaces_the_extension_free_copy(monkeypatch, tmp_path):+ from unittest import mock++ importable = {"mamba_ssm"}+ worker, uninstalled = _training_env(monkeypatch, tmp_path, importable)+ events = []+ monkeypatch.setattr(+ worker,+ "probe_torch_wheel_env",+ lambda **k: {+ "cuda_version": "12.8",+ "cuda_major": "12",+ "torch_mm": "2.11",+ "platform_tag": "linux_x86_64",+ },+ )+ monkeypatch.setattr(worker, "url_exists", lambda url: False) # no prebuilt: source path+ monkeypatch.setattr(worker, "pinned_source_build_supported", lambda env: True)+ monkeypatch.setattr(worker.sys, "platform", "linux")++ def build(cmd, **kwargs):+ events.append(("build", list(uninstalled)))+ importable.update({"mamba_ssm", ssm_runtime.MAMBA_SSM_EXTENSION})+ return types.SimpleNamespace(returncode = 0, stdout = "")++ import utils.kernel_install as kernel_install++ monkeypatch.setattr(kernel_install, "run_process_tree", build)+ probes = []+ for probe in ("_is_importable_isolated", "_extension_importable_isolated"):+ monkeypatch.setattr(worker, probe, lambda name: probes.append(name) or name in importable)+ assert worker._install_package_wheel_first(+ event_queue = mock.Mock(),+ **worker._pinned_kernel_kwargs(worker.MAMBA_SSM),+ allow_source_build = True,+ extension = ssm_runtime.MAMBA_SSM_EXTENSION,+ )+ # The extension-free copy went before the build (pip / uv would call it satisfied) ...+ assert events == [("build", ["mamba-ssm"])]+ # ... and the build is only accepted with the compiled scan importable.+ assert ssm_runtime.MAMBA_SSM_EXTENSION in probes+++# ── Round 4: lock not held, zoo kill switch, other conv consumers ─────────────+++def test_zoo_kill_switch_keeps_the_cuda_wheels(capable, monkeypatch):+ k = _kernels({"nemotron_h"})+ assert ssm_runtime.mamba2_runs_on_triton(k)+ monkeypatch.setenv("UNSLOTH_DISABLE_TRITON_CAUSAL_CONV1D", "1")+ assert not ssm_runtime.mamba2_runs_on_triton(k)+++def test_another_conv_consumer_keeps_the_cuda_wheels(capable, monkeypatch):+ monkeypatch.setattr(+ ssm_runtime, "_transformers_model_type_uses_causal_conv1d", lambda t: t == "lfm2"+ )+ assert not ssm_runtime.mamba2_runs_on_triton(_kernels({"nemotron_h", "lfm2"}))+ # A sub-model with no causal conv (a vision tower) does not stop the Triton route.+ assert ssm_runtime.mamba2_runs_on_triton(_kernels({"nemotron_h", "siglip_vision_model"}))+++def unheld_lock(monkeypatch):+ import contextlib++ import utils.kernel_install as kernel_install++ @contextlib.contextmanager+ def lock(*a, **k):+ yield False++ monkeypatch.setattr(kernel_install, "kernel_install_lock", lock)+ yield+ if "mamba_ssm" in sys.modules and sys.modules["mamba_ssm"] is None:+ del sys.modules["mamba_ssm"]+++def test_an_unheld_lock_hides_the_extension_free_copy(real_install, monkeypatch, unheld_lock):+ import importlib.util++ real_install["importable"].update({"mamba_ssm", "causal_conv1d"})+ monkeypatch.setattr(ssm_runtime, "install_prebuilt", lambda *a, **k: pytest.fail("no lock"))+ installed = ssm_runtime.ensure_ssm_runtime(+ "tiiuae/falcon-mamba-7b",+ wants_causal_conv1d = False,+ is_ssm = True,+ mamba_ssm_required = False,+ mamba_ssm_fatal = False,+ )+ # transformers' gates (find_spec) and imports now see no mamba_ssm: the torch path, not+ # selective_scan_fn.+ assert sys.modules["mamba_ssm"] is None+ assert importlib.util.find_spec("mamba_ssm") is None+ with pytest.raises(ImportError):+ import mamba_ssm # noqa: F401+ assert installed == [f"{ssm_runtime.REMOVED_PREFIX}mamba_ssm"]+ # A later install in this process probes afresh instead of trusting the block.+ ssm_runtime._unblock_import("mamba_ssm")+ assert "mamba_ssm" not in sys.modules+++def test_training_unheld_lock_hides_the_extension_free_copy(monkeypatch, tmp_path, unheld_lock):+ from unittest import mock++ importable = {"mamba_ssm"}+ worker, uninstalled = _training_env(monkeypatch, tmp_path, importable)+ refreshed = []+ monkeypatch.setattr(+ ssm_runtime, "refresh_transformers_kernel_gates", lambda **k: refreshed.append(k)+ )+ assert not worker._install_package_wheel_first(+ event_queue = mock.Mock(),+ **worker._pinned_kernel_kwargs(worker.MAMBA_SSM),+ extension = ssm_runtime.MAMBA_SSM_EXTENSION,+ )+ assert uninstalled == [] # not ours to remove without the lock+ assert sys.modules["mamba_ssm"] is None+ assert refreshed == [{"removed": True}]+++def test_offline_with_a_busy_lock_hides_the_extension_free_copy(+ real_install, monkeypatch, unheld_lock+):+ import utils.utils as utils_utils++ monkeypatch.setattr(utils_utils, "package_installs_offline", lambda: True)+ real_install["importable"].update({"mamba_ssm", "causal_conv1d"})+ monkeypatch.setattr(ssm_runtime, "_remove_broken", lambda *a, **k: pytest.fail("no lock"))+ monkeypatch.setattr(ssm_runtime, "install_prebuilt", lambda *a, **k: pytest.fail("offline"))+ installed = ssm_runtime.ensure_ssm_runtime(+ "tiiuae/falcon-mamba-7b",+ wants_causal_conv1d = False,+ is_ssm = True,+ mamba_ssm_required = False,+ mamba_ssm_fatal = False,+ )+ assert sys.modules["mamba_ssm"] is None+ assert installed == [f"{ssm_runtime.REMOVED_PREFIX}mamba_ssm"]+++def test_remembered_failure_with_a_busy_lock_hides_the_extension_free_copy(+ real_install, monkeypatch, unheld_lock+):+ real_install["importable"].update({"mamba_ssm", "causal_conv1d"})+ ssm_runtime._FAILED_INSTALLS.add(ssm_runtime._failure_key("mamba_ssm", None))+ monkeypatch.setattr(ssm_runtime, "_remove_broken", lambda *a, **k: pytest.fail("no lock"))+ installed = ssm_runtime.ensure_ssm_runtime(+ "tiiuae/falcon-mamba-7b",+ wants_causal_conv1d = False,+ is_ssm = True,+ mamba_ssm_required = False,+ mamba_ssm_fatal = False,+ )+ assert sys.modules["mamba_ssm"] is None+ assert installed == [f"{ssm_runtime.REMOVED_PREFIX}mamba_ssm"]+++def test_training_offline_with_a_busy_lock_hides_the_extension_free_copy(+ monkeypatch, tmp_path, unheld_lock+):+ from unittest import mock++ importable = {"mamba_ssm"}+ worker, uninstalled = _training_env(monkeypatch, tmp_path, importable, offline = True)+ refreshed = []+ monkeypatch.setattr(+ ssm_runtime, "refresh_transformers_kernel_gates", lambda **k: refreshed.append(k)+ )+ assert not worker._install_package_wheel_first(+ event_queue = mock.Mock(),+ **worker._pinned_kernel_kwargs(worker.MAMBA_SSM),+ extension = ssm_runtime.MAMBA_SSM_EXTENSION,+ )+ assert uninstalled == []+ assert sys.modules["mamba_ssm"] is None+ assert refreshed == [{"removed": True}]+++def test_a_failed_uninstall_hides_the_extension_free_copy(real_install, monkeypatch):+ # Remembered CUDA failure, lock held, but the uninstall cannot remove the files.+ real_install["importable"].update({"mamba_ssm", "causal_conv1d"})+ ssm_runtime._FAILED_INSTALLS.add(ssm_runtime._failure_key("mamba_ssm", None))+ monkeypatch.setattr(ssm_runtime, "_remove_broken", lambda *a, **k: None) # nothing removed+ try:+ installed = ssm_runtime.ensure_ssm_runtime(+ "tiiuae/falcon-mamba-7b",+ wants_causal_conv1d = False,+ is_ssm = True,+ mamba_ssm_required = False,+ mamba_ssm_fatal = False,+ )+ assert sys.modules["mamba_ssm"] is None+ assert installed == [f"{ssm_runtime.REMOVED_PREFIX}mamba_ssm"]+ finally:+ ssm_runtime._unblock_import("mamba_ssm")+++def test_training_failed_uninstall_hides_the_extension_free_copy(monkeypatch, tmp_path):+ from unittest import mock++ importable = {"mamba_ssm"}+ worker, uninstalled = _training_env(monkeypatch, tmp_path, importable, offline = True)+ monkeypatch.setattr(worker, "_uninstall_package", lambda *a, **k: False) # files stay+ refreshed = []+ monkeypatch.setattr(+ ssm_runtime, "refresh_transformers_kernel_gates", lambda **k: refreshed.append(k)+ )+ try:+ assert not worker._install_package_wheel_first(+ event_queue = mock.Mock(),+ **worker._pinned_kernel_kwargs(worker.MAMBA_SSM),+ extension = ssm_runtime.MAMBA_SSM_EXTENSION,+ )+ assert sys.modules["mamba_ssm"] is None+ assert refreshed == [{"removed": True}]+ finally:+ ssm_runtime._unblock_import("mamba_ssm")diff --git a/studio/backend/tests/test_ssm_runtime.py b/studio/backend/tests/test_ssm_runtime.pyindex a727f2359cd..12aa23c7a06 100644--- a/studio/backend/tests/test_ssm_runtime.py+++ b/studio/backend/tests/test_ssm_runtime.py@@ -1368,7 +1368,13 @@ class _Host:)monkeypatch.setattr(ssm_runtime, "url_exists", lambda url: head)monkeypatch.setattr(ssm_runtime, "install_wheel", self.install_wheel)- monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: name in self.imports)+ # Every mamba_ssm this fake installs (CUDA wheel or source build) carries its compiled scan.+ monkeypatch.setattr(+ ssm_runtime,+ "_is_importable",+ lambda name: name in self.imports+ or (name == ssm_runtime.MAMBA_SSM_EXTENSION and "mamba_ssm" in self.imports),+ )monkeypatch.setattr(ssm_runtime,"_installed_distribution",diff --git a/studio/backend/tests/test_training_worker_flash_attn.py b/studio/backend/tests/test_training_worker_flash_attn.pyindex 3c091e2a25e..3019ca1bdab 100644--- a/studio/backend/tests/test_training_worker_flash_attn.py+++ b/studio/backend/tests/test_training_worker_flash_attn.py@@ -698,6 +698,7 @@ def test_mamba_ssm_path_preserves_wheel_first_install_args(monkeypatch):release_base_url = "https://github.com/state-spaces/mamba/releases/download",allow_source_build = True,required = True,+ extension = "selective_scan_cuda",)diff --git a/studio/backend/utils/ssm_runtime.py b/studio/backend/utils/ssm_runtime.pyindex db7f1b1fdaa..e0e33eedd0a 100644--- a/studio/backend/utils/ssm_runtime.py+++ b/studio/backend/utils/ssm_runtime.py@@ -36,6 +36,7 @@ from utils.wheel_utils import (direct_wheel_url,install_wheel,is_windows_wheel_env,+ mamba_ssm_pure_wheel_url,pinned_source_build_supported,probe_torch_wheel_env,url_exists,@@ -103,6 +104,14 @@ ZOO_TRITON_CAUSAL_CONV1D_KILL_SWITCH = "UNSLOTH_DISABLE_TRITON_CAUSAL_CONV1D"# Present in the zoo source from the release that added the decode kernel._ZOO_GDN_DECODE_KERNEL_MARKER = "def triton_causal_conv1d_update("_TRANSFORMERS_CAUSAL_CONV1D_MODEL_TYPE_CACHE: dict[tuple[str, str], bool | None] = {}+# Mamba-2 mixers (transformers >= 5.15 resolves each kernel through the hub decorator) that+# unsloth_zoo runs on Triton alone: the pure mamba_ssm wheel for the scan, zoo's causal conv+# drop-ins for prefill, the fused training path and decode. Mamba-1 families need selective_scan_cuda.+MAMBA2_TRITON_MODEL_TYPES = frozenset(+ {"nemotron_h", "falcon_h1", "granitemoehybrid", "bamba", "zamba2", "mamba2"}+)+_ZOO_MAMBA2_TRITON_MARKERS = ("def install_mamba_ssm_triton_conv", "_MAMBA2_MODELING")+_TRANSFORMERS_HUB_DECORATOR_FLOOR = (5, 15)def zoo_triton_causal_conv1d_enabled() -> bool:@@ -182,6 +191,10 @@ class SsmKernels(NamedTuple):# Falcon-H1, Granite-4.0-H) only means "worth a source build": their native transformers# models run without it.mamba_ssm_fatal: bool = False+ # Whether this load runs the remote implementation: an auto_map plus trust_remote_code, or a+ # model type this transformers has no native class for. A config that merely advertises remote+ # code still loads the native class when trust_remote_code is off.+ remote_code_used: bool = Falsedef _base_model_type(model_type: str) -> str:@@ -439,15 +452,31 @@ def _hub_cached_text(repo: str, filename: str) -> str | None:return None-def _remote_model_sources(checkpoint: str, model_config: dict) -> list[tuple[str, str]]:- """(repo, file) of the model classes the config's ``auto_map`` names."""- auto_map = model_config.get("auto_map") if isinstance(model_config, dict) else None- if not isinstance(auto_map, dict):+def _auto_maps(model_config) -> list[dict]:+ """Every ``auto_map`` in a config, top level and sub-configs: the loader runs a composite+ model's ``text_config.auto_map`` too (the remote-code consent gate reads the same set)."""+ if not isinstance(model_config, dict):return []+ try:+ from utils.security.remote_code_scan import iter_auto_maps+ except Exception:+ auto_map = model_config.get("auto_map")+ return [auto_map] if isinstance(auto_map, dict) else []+ return list(iter_auto_maps(model_config))+++def _auto_model_entries(model_config):+ """(key, value) of every ``AutoModel*`` entry across the config's auto_maps."""+ for auto_map in _auto_maps(model_config):+ for key, value in auto_map.items():+ if str(key).startswith("AutoModel"):+ yield key, value+++def _remote_model_sources(checkpoint: str, model_config: dict) -> list[tuple[str, str]]:+ """(repo, file) of the model classes the config's ``auto_map`` names, at any nesting level."""sources = []- for key, value in auto_map.items():- if not str(key).startswith("AutoModel"):- continue+ for _key, value in _auto_model_entries(model_config):for reference in value if isinstance(value, (list, tuple)) else (value,):if not isinstance(reference, str) or "." not in reference:continue@@ -602,6 +631,12 @@ def resolve_ssm_kernels(required = model_requires_mamba_ssm(probe)if wants is None:wants = model_wants_causal_conv1d(probe)+ ssm_types = {t for t in model_types if t in SSM_MODEL_TYPES}+ remote_code_used = bool(remote_code) and (+ bool(trust_remote_code)+ or not ssm_types+ or not all(native_modeling_available(t) for t in ssm_types)+ )fatal = Falseif is_ssm and required:if model_config is not None and model_types:@@ -623,6 +658,7 @@ def resolve_ssm_kernels(model_types = model_types,remote_code = remote_code,mamba_ssm_fatal = bool(fatal),+ remote_code_used = remote_code_used,)@@ -652,7 +688,7 @@ def resolved_model_is_ssm().mamba_ssm-def refresh_transformers_kernel_gates() -> None:+def refresh_transformers_kernel_gates(removed: bool = False) -> None:"""After an in-process install, let an already-imported transformers see the new kernels: itsavailability gates are lru_cached and the hub-kernel map can hold a cached None. Never raises.This cannot rebind functions a modeling module already captured; see@@ -675,7 +711,8 @@ def refresh_transformers_kernel_gates() -> None:hub_kernels = sys.modules.get("transformers.integrations.hub_kernels")mapping = getattr(hub_kernels, "_KERNEL_MODULE_MAPPING", None)if isinstance(mapping, dict):- for key in [key for key, value in mapping.items() if value is None]:+ # A removal also invalidates a cached module, not only a cached None.+ for key in [key for key, value in mapping.items() if removed or value is None]:if any(kernel in str(key) for kernel in ("causal-conv1d", "causal_conv1d", "mamba")):@@ -710,14 +747,10 @@ def remote_code_modules(checkpoint: str, model_config: dict) -> frozenset:"""The (namespace, module) pairs of the model classes a config's ``auto_map`` points at: anentry ``"model.CustomForCausalLM"`` is module ``model`` of *checkpoint*, and``"org/repo--model.Custom"`` module ``model`` of ``org/repo``. Any module name counts, not just- ``modeling_*``; AutoConfig / AutoTokenizer / processor entries capture no kernels."""- auto_map = model_config.get("auto_map") if isinstance(model_config, dict) else None- if not isinstance(auto_map, dict):- return frozenset()+ ``modeling_*``; AutoConfig / AutoTokenizer / processor entries capture no kernels. Sub-configs+ count: the loader runs a composite model's ``text_config.auto_map`` as well."""pairs = set()- for key, value in auto_map.items():- if not str(key).startswith("AutoModel"):- continue+ for _key, value in _auto_model_entries(model_config):for reference in value if isinstance(value, (list, tuple)) else (value,):if not isinstance(reference, str) or "." not in reference:continue@@ -861,7 +894,128 @@ def _kernel_backend(env: dict[str, str] | None) -> str | None:return None-def _failure_key(import_name: str) -> tuple:+def _zoo_has_mamba2_triton_drop_ins() -> bool:+ """Whether the installed unsloth_zoo runs Mamba-2 causal convs on Triton, read from its source+ (importing unsloth_zoo here would patch the process)."""+ try:+ spec = importlib.util.find_spec("unsloth_zoo")+ roots = list(spec.submodule_search_locations or []) if spec is not None else []+ except Exception:+ return False+ for root in roots:+ try:+ with open(+ os.path.join(root, "temporary_patches", "gdn_causal_conv1d.py"), encoding = "utf-8"+ ) as f:+ text = f.read()+ except OSError:+ continue+ return all(marker in text for marker in _ZOO_MAMBA2_TRITON_MARKERS)+ return False+++def _transformers_resolves_kernels_per_function() -> bool:+ try:+ from importlib.metadata import version as _version++ from packaging.version import Version+ return Version(_version("transformers")).release[:2] >= _TRANSFORMERS_HUB_DECORATOR_FLOOR+ except Exception:+ return False+++def _model_type_uses_causal_conv1d(model_type: str) -> bool:+ """Whether one model type runs a causal conv: an SSM family, a modeling file that uses+ causal_conv1d, or a name on the causal-conv1d list."""+ if model_type in SSM_MODEL_TYPES or _transformers_model_type_uses_causal_conv1d(model_type):+ return True+ identifier = _normalized_model_identifier(model_type)+ return any(+ _normalized_model_identifier(needle) in identifier+ for needle in CAUSAL_CONV1D_MODEL_SUBSTRINGS+ )+++def mamba2_runs_on_triton(kernels: "SsmKernels") -> bool:+ """True when this load can take the extension-free mamba_ssm wheel and skip causal-conv1d: a+ config-resolved Mamba-2 family on a CUDA torch with Triton, transformers >= 5.15 and a zoo with+ the Triton drop-ins. Never for a load whose own code needs mamba_ssm (``mamba_ssm_fatal``) or a+ name-only guess."""+ if not kernels.mamba_ssm or kernels.mamba_ssm_fatal or kernels.remote_code_used:+ return False+ ssm_types = {t for t in kernels.model_types if t in SSM_MODEL_TYPES}+ if not ssm_types or not ssm_types <= MAMBA2_TRITON_MODEL_TYPES:+ return False+ # The zoo drop-ins cover only these families' causal conv: any other consumer in the config+ # (an LFM2 or other conv sub-model in a composite) still needs causal-conv1d.+ if any(+ _model_type_uses_causal_conv1d(t) for t in kernels.model_types - MAMBA2_TRITON_MODEL_TYPES+ ):+ return False+ if os.environ.get("UNSLOTH_MAMBA_CUDA_KERNELS", "0") == "1":+ return False # opt back into the CUDA wheels+ if os.environ.get("UNSLOTH_DISABLE_TRITON_CAUSAL_CONV1D", "0") == "1":+ return False # zoo's own kill switch: no Triton conv, so the CUDA wheels+ if importlib.util.find_spec("triton") is None:+ return False+ if _kernel_backend(_torch_env()) != "cuda":+ return False # zoo's drop-ins are CUDA only; ROCm keeps its source builds+ if not (_transformers_resolves_kernels_per_function() and _zoo_has_mamba2_triton_drop_ins()):+ return False+ # mamba_ssm's own Triton kernels (scan, state update) follow setup's GPU floor: none below+ # sm75, Triton >= 3.4 on sm75. Below it this load keeps today's route.+ return _mamba_ssm_floor_reason() is None+++# The compiled Mamba-1 scan. The extension-free mamba_ssm wheel imports fine without it, so a load on+# the CUDA route (Mamba-1 families, remote code, UNSLOTH_MAMBA_CUDA_KERNELS=1) must check for it: with+# it missing, transformers still takes mamba_ssm's fast path and selective_scan_fn raises.+MAMBA_SSM_EXTENSION = "selective_scan_cuda"+++def kernel_usable(import_name: str, extension: str | None = None) -> bool:+ """The package imports and, when *extension* is named, so does its compiled module."""+ return _is_importable(import_name) and (extension is None or _is_importable(extension))+++def block_import(import_name: str, extension: str | None = None) -> None:+ """Make *import_name* unavailable to this process (``sys.modules[name] = None``: ``import``+ raises ImportError and ``importlib.util.find_spec`` returns None, so transformers' availability+ gates read it as missing). For an extension-free mamba_ssm that could not be removed without+ the install lock: this load then takes the torch path instead of selective_scan_fn."""+ forget_imported_modules(import_name, extension)+ sys.modules[import_name] = None+++def _hide_if_still_extension_free(import_name: str, extension: str) -> None:+ """After an uninstall attempt: if the extension-free copy is still installed (read-only env,+ locked files), hide it from this process so transformers does not pick selective_scan_fn."""+ if _is_importable(import_name) and not _is_importable(extension):+ logger.info(+ "Could not uninstall the extension-free %s; hiding it from this load", import_name+ )+ block_import(import_name, extension)+++def _unblock_import(import_name: str) -> None:+ if import_name in sys.modules and sys.modules[import_name] is None:+ del sys.modules[import_name]+ importlib.invalidate_caches()+++def forget_imported_modules(import_name: str, extension: str | None = None) -> None:+ """Drop a replaced package from sys.modules so the next import loads the new copy: mamba_ssm+ binds selective_scan_cuda (or None) when its modules are first imported."""+ for name in list(sys.modules):+ if name == import_name or name.startswith(import_name + ".") or name == extension:+ sys.modules.pop(name, None)+ importlib.invalidate_caches()+++def _failure_key(import_name: str, wheel_url_builder: Callable[..., Any] | None = None) -> tuple:+ """What a failed install is remembered by. A non-default wheel source (the extension-free+ mamba_ssm wheel) is its own attempt, so its failure does not also block the CUDA-wheel route+ the load falls back to."""try:import importlib.metadata as metadatatorch_version = metadata.version("torch")@@ -869,6 +1023,7 @@ def _failure_key(import_name: str) -> tuple:torch_version = Nonereturn (import_name,+ getattr(wheel_url_builder, "__qualname__", None) if wheel_url_builder is not None else None,sys.executable,torch_version,shutil.which("nvcc"),@@ -923,12 +1078,17 @@ def _install_kernel(newly_installed: list[str] | None = None,allow_source_build: bool = True,required: bool = False,+ wheel_url_builder: Callable[[dict[str, str] | None], str | None] | None = None,+ extension: str | None = None,) -> bool:"""Install one kernel wheel-first, then (when *allow_source_build*) a HIP-aware PyPI source build(never on Windows). Returns True iff importable afterwards; idempotent (no-op when alreadyinstalled). An install this call made is appended to *newly_installed*. One install per kernel- runs at a time across processes; a failed one is not retried in this process."""- if _is_importable(import_name):+ runs at a time across processes; a failed one is not retried in this process. With+ *extension*, an installed copy without that compiled module (the extension-free mamba_ssm+ wheel) is replaced rather than accepted."""+ _unblock_import(import_name) # a previous load's in-process block; this one probes afresh+ if kernel_usable(import_name, extension):logger.info("%s already installed", display_name)return True@@ -937,11 +1097,20 @@ def _install_kernel(if package_installs_offline():# No URL probe, no source build, and no uv-to-pip fallback that would reach the network.logger.info("Skipping %s installation while offline", display_name)+ if extension is not None and _is_importable(import_name):+ # Removing is local, so offline still drops an extension-free copy this load cannot use.+ if _drop_extension_free_copy(import_name, display_name, pypi_name, extension, run):+ _note_removed(newly_installed, import_name)return False- failure_key = _failure_key(import_name)+ failure_key = _failure_key(import_name, wheel_url_builder)if failure_key in _FAILED_INSTALLS:logger.info("%s already failed to install in this process; not retrying", display_name)+ if extension is not None and _is_importable(import_name):+ # A later load reinstalled the extension-free copy after this route failed: drop it, or+ # this load takes mamba_ssm's fast path and fails in selective_scan_fn.+ if _drop_extension_free_copy(import_name, display_name, pypi_name, extension, run):+ _note_removed(newly_installed, import_name)return Falsefrom utils.kernel_install import (@@ -964,14 +1133,31 @@ def _install_kernel(f"Could not take the {display_name} install lock (another process is installing ""it, or the lock is unavailable); continuing without it.",)+ if (+ extension is not None+ and _is_importable(import_name)+ and not _is_importable(extension)+ ):+ # Not ours to uninstall without the lock, but this load must not use it: hidden+ # from this process, transformers takes its torch path.+ block_import(import_name, extension)+ _note_removed(newly_installed, import_name)return False# Another process may have installed it while this one waited: new to this worker all the# same, so its already-imported modeling modules are refreshed or restarted.- if _is_importable(import_name):+ if kernel_usable(import_name, extension):logger.info("%s installed by another process", display_name)+ if extension is not None:+ forget_imported_modules(import_name, extension)if newly_installed is not None:newly_installed.append(import_name)return True+ # Importable but without the compiled module: the extension-free wheel, replaced here.+ replacing = extension is not None and _is_importable(import_name)+ if replacing:+ _emit(+ status_cb, f"Replacing the extension-free {display_name} with its CUDA kernels..."+ )installed: bool | None = Falsetry:installed = _install_kernel_locked(@@ -984,6 +1170,9 @@ def _install_kernel(status_cb = status_cb,run = run,allow_source_build = allow_source_build,+ wheel_url_builder = wheel_url_builder,+ extension = extension,+ replacing = replacing,)except Exception as exc:# An installer that cannot even start (OSError) fails like any other attempt.@@ -991,7 +1180,14 @@ def _install_kernel(installed = Falsefinally:if installed is False:+ # A failed replacement removes the extension-free copy too: left in place, a Mamba-1+ # load would take mamba_ssm's fast path and fail in selective_scan_fn._remove_broken(pypi_name, display_name, run)+ if replacing:+ forget_imported_modules(import_name, extension)+ _hide_if_still_extension_free(import_name, extension)+ if not _is_importable(import_name):+ _note_removed(newly_installed, import_name)_FAILED_INSTALLS.add(failure_key)if installed is None:return False # nothing attempted (unsupported torch backend)@@ -1000,6 +1196,43 @@ def _install_kernel(return bool(installed)+# A runtime removal is reported in the list of newly installed kernels under this prefix: it changes+# what transformers' cached availability gates and already-imported modeling modules saw, so the+# caller refreshes the gates and runs its stale-module / restart check exactly as for an install.+REMOVED_PREFIX = "removed "+++def _note_removed(newly_installed: list[str] | None, import_name: str) -> None:+ if newly_installed is not None:+ newly_installed.append(f"{REMOVED_PREFIX}{import_name}")+++def _drop_extension_free_copy(+ import_name: str, display_name: str, pypi_name: str, extension: str, run: Callable[..., Any]+) -> bool:+ """Uninstall an installed copy that lacks *extension*, under the per-env install lock. True+ when it was removed."""+ from utils.kernel_install import OPTIONAL_KERNEL_LOCK_WAIT, kernel_install_lock+ with kernel_install_lock(import_name, wait_seconds = OPTIONAL_KERNEL_LOCK_WAIT) as held:+ if kernel_usable(import_name, extension) or not _is_importable(import_name):+ return False+ if not held:+ # Cannot uninstall without the lock: hide it from this process instead.+ logger.info(+ "Hiding the extension-free %s from this load: its install lock is busy",+ display_name,+ )+ block_import(import_name, extension)+ return True+ logger.info(+ "Removing the extension-free %s: this load needs its CUDA kernels", display_name+ )+ _remove_broken(pypi_name, display_name, run)+ forget_imported_modules(import_name, extension)+ _hide_if_still_extension_free(import_name, extension)+ return True++def _install_kernel_locked(*,import_name: str,@@ -1011,8 +1244,17 @@ def _install_kernel_locked(status_cb: StatusCb,run: Callable[..., Any],allow_source_build: bool,+ wheel_url_builder: Callable[[dict[str, str] | None], str | None] | None = None,+ extension: str | None = None,+ replacing: bool = False,) -> bool | None:"""The install itself, under the kernel's lock. None when nothing was attempted."""++ def _verify() -> bool:+ if replacing:+ forget_imported_modules(import_name, extension)+ return kernel_usable(import_name, extension)+env = _torch_env()backend = _kernel_backend(env)if backend is None:@@ -1022,13 +1264,16 @@ def _install_kernel_locked()return Nonewheel_only = sys.platform == "win32" or is_windows_wheel_env(env)- wheel_url = direct_wheel_url(- filename_prefix = import_name,- package_version = package_version,- release_tag = release_tag,- release_base_url = release_base_url,- env = env,- )+ if wheel_url_builder is not None:+ wheel_url = wheel_url_builder(env)+ else:+ wheel_url = direct_wheel_url(+ filename_prefix = import_name,+ package_version = package_version,+ release_tag = release_tag,+ release_base_url = release_base_url,+ env = env,+ )wheel_available = url_exists(wheel_url) if wheel_url else False# Only a 404 proves nothing is published: an unanswered HEAD (a proxy refusing HEAD but serving# the download) still tries the wheel, as setup always did.@@ -1048,7 +1293,7 @@ def _install_kernel_locked(outcome = install_prebuilt(wheel_url,install = install_wheel,- verify = lambda: _is_importable(import_name),+ verify = _verify,on_failed = lambda installer, result: logger.warning("%s could not install %s wheel:\n%s",installer,@@ -1057,6 +1302,8 @@ def _install_kernel_locked(),use_uv = bool(shutil.which("uv")),run = run,+ # Over the extension-free copy of the same version, which uv / pip would keep.+ **({"reinstall": True} if replacing else {}),)if outcome == "installed":logger.info("Installed prebuilt %s wheel", display_name)@@ -1121,7 +1368,7 @@ def _install_kernel_locked(return Falseif getattr(result, "returncode", 1) != 0:logger.warning("%s source install failed:\n%s", display_name, getattr(result, "stdout", ""))- return _is_importable(import_name)+ return _verify()def _pinned_kwargs(kernel: PinnedKernel) -> dict[str, str]:@@ -1145,6 +1392,7 @@ def ensure_ssm_runtime(is_ssm: bool | None = None,mamba_ssm_required: bool | None = None,mamba_ssm_fatal: bool | None = None,+ mamba2_triton: bool = False,) -> list[str]:"""Install the SSM kernels *model_name* needs before load, wheel-first; a no-op for non-SSM models and idempotent. Returns the kernels newly installed by this call. Nemotron-H, Falcon-H1 and Granite-4.0-H (*mamba_ssm_required*) are worth a source build; a load fails on a missing ``mamba_ssm`` (``RuntimeError`` instead of a cryptic mid-load failure) only when *mamba_ssm_fatal*: it imports code that cannot run without it. Everything else, and ``causal_conv1d``, leaves transformers' torch path."""# The caller's config-resolved answers win; the name match is the default.@@ -1164,7 +1412,12 @@ def ensure_ssm_runtime(if not (wants_causal_conv1d or is_ssm):return installed- def _install(kernel: PinnedKernel, *, allow_source_build: bool = True) -> bool:+ def _install(+ kernel: PinnedKernel,+ *,+ allow_source_build: bool = True,+ **kwargs: Any,+ ) -> bool:return _install_kernel(**_pinned_kwargs(kernel),status_cb = status_cb,@@ -1173,6 +1426,21 @@ def ensure_ssm_runtime(allow_source_build = allow_source_build,# Nemotron-H, Falcon-H1, Granite-4.0-H wait out a peer's install; the rest move on.required = mamba_ssm_required,+ **kwargs,+ )++ if mamba2_triton and is_ssm:+ # unsloth_zoo serves the causal conv on Triton and the extension-free mamba_ssm wheel the+ # scan: 224 KB instead of two CUDA wheels, nothing to build, same wheel on every platform.+ if _install(+ MAMBA_SSM, allow_source_build = False, wheel_url_builder = mamba_ssm_pure_wheel_url+ ):+ return installed+ # Not published yet, refused, or not importable (removed again by _install_kernel): this+ # load takes the CUDA-wheel route below, exactly as without the Triton drop-ins.+ _emit(+ status_cb,+ "The extension-free mamba-ssm wheel is not available; using the CUDA kernels instead.",)# causal-conv1d first: SSM modeling files lazy-import it, and mamba-ssm's fast path uses it.@@ -1204,7 +1472,9 @@ def ensure_ssm_runtime(if reason is not None:_emit(status_cb, f"Skipping mamba-ssm, which {reason}; using the model's torch path.")return installed- if not _install(MAMBA_SSM, allow_source_build = mamba_ssm_required):+ if not _install(+ MAMBA_SSM, allow_source_build = mamba_ssm_required, extension = MAMBA_SSM_EXTENSION+ ):if mamba_ssm_fatal:# The model cannot load without mamba-ssm (its remote code imports it), so no torch# path exists to fall back on. On a CPU / XPU torch no install could have helped, so@@ -1284,7 +1554,10 @@ def provision_ssm_kernels(is_ssm = kernels.mamba_ssm,mamba_ssm_required = kernels.mamba_ssm_required,mamba_ssm_fatal = kernels.mamba_ssm_fatal,+ mamba2_triton = mamba2_runs_on_triton(kernels),)if installed:- refresh_transformers_kernel_gates()+ refresh_transformers_kernel_gates(+ removed = any(name.startswith(REMOVED_PREFIX) for name in installed)+ )return kernels, installeddiff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.pyindex 5aacab241a6..f922760a43c 100644--- a/studio/backend/utils/wheel_utils.py+++ b/studio/backend/utils/wheel_utils.py@@ -123,6 +123,22 @@ def prebuilt_wheel_torch_mm(torch_mm: str) -> str:UNSLOTH_PREBUILT_RELEASE_BASE_URL = "https://github.com/unslothai/unsloth/releases/download"UNSLOTH_PREBUILT_RELEASE_TAG = "prebuilt-wheels-cu13"+# mamba_ssm with no compiled extension (MAMBA_KEEP_CUDA_BUILD unset), one py3-none-any wheel for every+# torch, interpreter and platform. Its Triton kernels are all the Mamba-2 mixers call; unsloth_zoo+# serves their causal conv (prefill, fused training path, decode) on Triton, so with a zoo that has+# those drop-ins the Mamba-2 hybrids need neither CUDA wheel. Built and signed by+# prebuilt-cuda-wheels.yml on the same tag.+MAMBA_SSM_PURE_VERSION = "2.3.2.post1"+MAMBA_SSM_PURE_WHEEL = f"mamba_ssm-{MAMBA_SSM_PURE_VERSION}-py3-none-any.whl"+++def mamba_ssm_pure_wheel_url(env: dict[str, str] | None = None) -> str:+ """The extension-free mamba_ssm wheel (the same file for every environment)."""+ return (+ f"{UNSLOTH_PREBUILT_RELEASE_BASE_URL}/{UNSLOTH_PREBUILT_RELEASE_TAG}/{MAMBA_SSM_PURE_WHEEL}"+ )++# Keyed on the torch minor, and exact rather than a floor: a wheel is built against one minor and there is no evidence any future one will load it, which is exactly the assumption that made the upstream wheels stop working here. A new torch minor adds a row only after the workflow has built and smoke-tested it._UNSLOTH_PREBUILT_TORCH_MM = frozenset({"2.13", "2.14"})