Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio setup: install causal-conv1d and mamba-ssm prebuilt wheels next to flash-attn (#13396)

Daniel Han9f4a868d43f7
diff --git a/studio/backend/tests/test_kernel_install.py b/studio/backend/tests/test_kernel_install.py
index d8a55409c38..88af6d8cf6c 100644
--- a/studio/backend/tests/test_kernel_install.py
+++ b/studio/backend/tests/test_kernel_install.py
@@ -453,6 +453,28 @@ def test_causal_conv1d_still_installs_below_sm80(uv):
assert run.installer_calls[0][-1].startswith(f"{_CC1D}/causal_conv1d-1.6.1+cu13torch2.10")
+ "without_gpu, capability, installs",
+ [(False, "None", False), (True, "None", True), (True, "7 0", False), (True, "9 0", True)],
+)
+def test_setup_installs_mamba_ssm_before_a_gpu_is_visible(
+ uv, monkeypatch, without_gpu, capability, installs
+):
+ # An image build sees no GPU; a visible pre-Ampere one still skips. Linux, so Windows'
+ # triton-windows gate (its own test) does not answer first.
+ uv(False)
+ monkeypatch.setattr(kernel_install.sys, "platform", "linux")
+ monkeypatch.setattr(kernel_install, "_triton_version", lambda run: (3, 3))
+ run = _Runner([False, True], capability = capability)
+ assert (
+ kernel_install.install_kernel(
+ "mamba_ssm", _COLAB, run = run, exists = lambda url: True, install_without_gpu = without_gpu
+ )
+ == 0
+ )
+ assert bool(run.installer_calls) is installs
+
+
def test_the_gpu_is_probed_once_for_every_sm80_kernel(capsys, monkeypatch):
monkeypatch.setattr(kernel_install, "_triton_version", lambda run: (3, 3))
run = _Runner([], capability = "7 5")
diff --git a/studio/backend/utils/kernel_install.py b/studio/backend/utils/kernel_install.py
index 130f8a7ab2a..364f90c2fd6 100644
--- a/studio/backend/utils/kernel_install.py
+++ b/studio/backend/utils/kernel_install.py
@@ -328,15 +328,17 @@ def install_kernel(
dry_run: bool = False,
run: Callable[..., subprocess.CompletedProcess] = subprocess.run,
exists: Callable[[str], bool | None] = url_exists,
+ install_without_gpu: bool = False,
) -> int:
+ # install_without_gpu (setup): no visible GPU yet, e.g. an image build, still installs.
distribution, check = KERNELS[name]
url = resolve_wheel_url(name, env)
if name in _GPU_GATED and url is not None:
capability = _gpu_capability(run)
- if capability is None:
+ if capability is None and not install_without_gpu:
print(f"Unsloth: skipping {name}, which needs sm80 or newer (no CUDA GPU is visible).")
return 0
- if capability < (8, 0):
+ if capability is not None and capability < (8, 0):
reason = _pre_ampere_skip_reason(name, capability, run)
if reason is not None:
print(
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index af6cedf54e1..a07e14d403d 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -12,10 +12,12 @@ activated. Expects `pip` and `python` on PATH to point at the venv.
from __future__ import annotations
import ast
+import contextlib
import functools
import glob
import importlib
import importlib.util
+import io
import json
import locale
import os
@@ -51,7 +53,12 @@ def _nvidia_library_inventory():
return _nvidia_probe.probe() if _nvidia_probe is not None else None
-from backend.utils.kernel_install import install_prebuilt, uninstall_command
+from backend.utils.kernel_install import (
+ KERNELS,
+ install_kernel,
+ install_prebuilt,
+ uninstall_command,
+)
from backend.utils.wheel_utils import (
flash_attn_package_version,
flash_attn_wheel_url,
@@ -8550,6 +8557,89 @@ def _ensure_flash_attn() -> None:
_remove_stale_flash_attn()
+def _ssm_kernel_install_disabled() -> bool:
+ return os.getenv("UNSLOTH_STUDIO_SKIP_SSM_KERNELS_INSTALL") == "1"
+
+
+def _ensure_ssm_kernels() -> None:
+ """causal-conv1d and mamba-ssm prebuilt wheels at setup, via the wheel-only install_kernel."""
+ if _ssm_kernel_install_disabled() or NO_TORCH or IS_MACOS:
+ return
+ # Bounded on every platform, and a probe that cannot launch skips this optional step.
+ try:
+ env = probe_torch_wheel_env(timeout = _FLASH_ATTN_IMPORT_PROBE_TIMEOUT, include_windows = True)
+ except OSError:
+ return
+ if env is None:
+ return
+
+ # A new runner per call resets install_kernel's per-runner GPU / Triton cache after a torch
+ # repair; it bounds import probes, not installs.
+ def run(cmd, *args, **kwargs):
+ if list(cmd[:2]) == [sys.executable, "-c"]:
+ kwargs.setdefault("timeout", _FLASH_ATTN_IMPORT_PROBE_TIMEOUT)
+ return subprocess.run(cmd, *args, **kwargs)
+
+ def loads(check: str) -> bool | None:
+ try:
+ return (
+ run(
+ [sys.executable, "-c", check],
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ ).returncode
+ == 0
+ )
+ except (subprocess.TimeoutExpired, OSError):
+ return None
+
+ for name in ("causal_conv1d", "mamba_ssm"):
+ distribution, check = KERNELS[name]
+ installed = _installed_distribution_version(distribution) is not None
+ # Local first, so an offline re-run does not wait on a wheel HEAD request.
+ if installed and loads(check):
+ _note(f"{name} already installed and loads.")
+ continue
+ status = 0
+ buffer = io.StringIO()
+ if _uv_is_offline():
+ # install_wheel's pip fallback ignores UV_OFFLINE; stale removal below still runs.
+ if not installed:
+ _note(
+ f"{name} not installed: UV_OFFLINE is set; run `unsloth install-kernels` online"
+ )
+ else:
+ try:
+ with contextlib.redirect_stdout(buffer):
+ status = install_kernel(name, env, run = run, install_without_gpu = True)
+ except Exception as exc:
+ status = 1
+ buffer.write(f"{type(exc).__name__}: {exc}")
+ # install_kernel redacts only the wheel URL; uv / pip failure text can name another index.
+ for line in _redact_install_output(buffer.getvalue()).splitlines():
+ if line.strip():
+ _note(line.removeprefix("Unsloth: "))
+ if status or f"Unsloth: installed {name} " in buffer.getvalue():
+ _count_install_action()
+ if _installed_distribution_version(distribution) is not None and loads(check) is False:
+ _count_install_action()
+ try:
+ removed = _uninstall_distribution(distribution)
+ except OSError:
+ removed = False
+ if removed:
+ _step("warning", f"{name} does not load with this torch; removed it", _cyan)
+ else:
+ _step(
+ "warning",
+ f"{name} does not load with this torch and could not be removed; "
+ f"uninstall {distribution} manually",
+ _cyan,
+ )
+ elif status:
+ _step("warning", f"Continuing without {name}", _cyan)
+
+
# -- uv bootstrap ------------------------------------------------------
USE_UV = False # Set by _bootstrap_uv() at the start of install_python_stack()
@@ -12287,6 +12377,7 @@ def install_python_stack() -> int:
if not IS_MACOS and not NO_TORCH:
base_total += 1 # ROCm torch check (step 2b), non-macOS
base_total += 1 # flash-attn, Linux and Windows
+ base_total += 1 # causal-conv1d + mamba-ssm, same gate
if not IS_WINDOWS:
base_total += 1 # torch final repair (step 13), Linux
else:
@@ -12697,6 +12788,8 @@ def install_python_stack() -> int:
if not IS_MACOS and not NO_TORCH:
_progress("flash-attn")
_ensure_flash_attn()
+ _progress("mamba kernels")
+ _ensure_ssm_kernels()
# # 6. Patch: override llama_cpp.py with fix from unsloth-zoo feature/llama-cpp-windows-support branch
# patch_package_file(
@@ -12880,8 +12973,9 @@ def install_python_stack() -> int:
"flash-attn"
)
_install_torchao_for_torch(_torch_after_repair)
- # resync flash-attn because the repair can invalidate the wheel selected earlier.
+ # resync the kernels because the repair can invalidate the wheels selected earlier.
_ensure_flash_attn()
+ _ensure_ssm_kernels()
# Unguarded: torch==2.10.0 accepts 2.10.0+rocm7.1, and an earlier run may have moved it.
_evict_xformers_built_for_another_torch(scope = "linux torch repair", family_only = True)
_evict_xformers_requiring_another_torch()
@@ -12896,8 +12990,9 @@ def install_python_stack() -> int:
return 1
_torch_after_flavor = str(_probe_installed_torch_version() or "")
if _torch_after_flavor and _torch_after_flavor != _torch_before_flavor:
- # flash-attn was chosen for the torch the invariant just replaced, as in step 13.
+ # The kernels were chosen for the torch the invariant just replaced, as in step 13.
_ensure_flash_attn()
+ _ensure_ssm_kernels()
# A direct run has no setup.ps1 postlude to swap triton back. After the invariant,
# because the swap keys off the installed +xpu label.
_ensure_xpu_triton()
diff --git a/tests/python/test_ssm_kernels_install_python_stack.py b/tests/python/test_ssm_kernels_install_python_stack.py
new file mode 100644
index 00000000000..ee385104c4c
--- /dev/null
+++ b/tests/python/test_ssm_kernels_install_python_stack.py
@@ -0,0 +1,275 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Setup installs causal-conv1d and mamba-ssm prebuilt wheels next to flash-attn, so a Mamba /
+hybrid model does not wait on a download at load time."""
+
+from __future__ import annotations
+
+import re
+import subprocess
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+import pytest
+
+STUDIO_DIR = Path(__file__).resolve().parents[2] / "studio"
+sys.path.insert(0, str(STUDIO_DIR))
+sys.path.insert(0, str(STUDIO_DIR / "backend"))
+
+import install_python_stack as ips # noqa: E402
+
+SOURCE = (STUDIO_DIR / "install_python_stack.py").read_text(encoding = "utf-8")
+ENV = {"platform_tag": "linux_x86_64", "torch_mm": "2.13", "torch_version": "2.13.0+cu130"}
+DISTS = {"causal_conv1d": "causal-conv1d", "mamba_ssm": "mamba-ssm"}
+
+
+class _Host:
+ """Which kernels are installed and whether they import; the fake install_kernel edits it."""
+
+ def __init__(
+ self,
+ installed = (),
+ loading = (),
+ hangs = (),
+ unlaunchable = (),
+ ):
+ self.installed = set(installed)
+ self.loading = set(loading)
+ self.hangs = set(hangs)
+ self.unlaunchable = set(unlaunchable)
+ self.timeouts = []
+
+ def version(self, distribution):
+ return "1.0" if distribution in self.installed else None
+
+ def run(self, cmd, *args, **kwargs):
+ self.timeouts.append(kwargs.get("timeout"))
+ for name, distribution in DISTS.items():
+ if cmd[-1] == ips.KERNELS[name][1]:
+ if distribution in self.hangs:
+ raise subprocess.TimeoutExpired(cmd, kwargs.get("timeout"))
+ if distribution in self.unlaunchable:
+ raise PermissionError(13, "Access is denied")
+ return SimpleNamespace(returncode = 0 if distribution in self.loading else 1)
+ return SimpleNamespace(returncode = 0)
+
+
+def _run(
+ host,
+ install_kernel,
+ *,
+ env = ENV,
+ no_torch = False,
+ macos = False,
+ disabled = False,
+ offline = False,
+):
+ steps, notes = [], []
+ with (
+ mock.patch.object(ips, "NO_TORCH", no_torch),
+ mock.patch.object(ips, "IS_MACOS", macos),
+ mock.patch.object(ips, "IS_WINDOWS", False),
+ mock.patch.object(ips, "_uv_is_offline", return_value = offline),
+ mock.patch.object(ips, "probe_torch_wheel_env", return_value = env) as probe,
+ mock.patch.object(ips, "install_kernel", side_effect = install_kernel) as kernel,
+ mock.patch.object(ips, "_installed_distribution_version", side_effect = host.version),
+ mock.patch.object(ips.subprocess, "run", side_effect = host.run),
+ mock.patch.object(
+ ips, "_uninstall_distribution", side_effect = lambda d: host.installed.discard(d) or True
+ ) as uninstall,
+ mock.patch.object(ips, "_count_install_action") as counted,
+ mock.patch.object(ips, "_step", side_effect = lambda label, value, *_: steps.append(value)),
+ mock.patch.object(ips, "_note", side_effect = lambda message, *_: notes.append(message)),
+ mock.patch.dict(
+ "os.environ", {"UNSLOTH_STUDIO_SKIP_SSM_KERNELS_INSTALL": "1" if disabled else ""}
+ ),
+ ):
+ ips._ensure_ssm_kernels()
+ return SimpleNamespace(
+ kernel = kernel,
+ probe = probe,
+ uninstall = uninstall,
+ counted = counted,
+ steps = steps,
+ notes = notes,
+ )
+
+
+def _installer(host):
+ def install(name, env, **kwargs):
+ print(f"Unsloth: installed {name} ({name}-x.whl).")
+ host.installed.add(DISTS[name])
+ host.loading.add(DISTS[name])
+ return 0
+
+ return install
+
+
+def test_both_kernels_install_for_the_resident_torch():
+ host = _Host()
+ r = _run(host, _installer(host))
+ assert [c.args for c in r.kernel.call_args_list] == [("causal_conv1d", ENV), ("mamba_ssm", ENV)]
+ for call in r.kernel.call_args_list:
+ assert call.kwargs["install_without_gpu"] is True
+ assert r.probe.call_args.kwargs["include_windows"] is True
+ assert r.counted.call_count == 2
+ assert r.steps == [] and r.uninstall.call_count == 0
+ assert r.notes == [
+ "installed causal_conv1d (causal_conv1d-x.whl).",
+ "installed mamba_ssm (mamba_ssm-x.whl).",
+ ]
+
+
+def test_a_kernel_that_already_loads_is_not_looked_up_online():
+ host = _Host(installed = DISTS.values(), loading = DISTS.values())
+ r = _run(host, _installer(host))
+ assert r.kernel.call_count == 0 and r.counted.call_count == 0
+ assert r.notes == [
+ "causal_conv1d already installed and loads.",
+ "mamba_ssm already installed and loads.",
+ ]
+
+
+def test_a_resident_build_that_no_longer_loads_is_removed_when_nothing_replaces_it():
+ host = _Host(installed = DISTS.values())
+
+ def no_wheel(name, env, **kwargs):
+ print(f"Unsloth: no prebuilt {name} for torch 2.15.0; using the torch fallback.")
+ return 0
+
+ r = _run(host, no_wheel)
+ assert [c.args[0] for c in r.uninstall.call_args_list] == ["causal-conv1d", "mamba-ssm"]
+ assert r.steps == [
+ "causal_conv1d does not load with this torch; removed it",
+ "mamba_ssm does not load with this torch; removed it",
+ ]
+
+
+def test_offline_mode_neither_looks_up_nor_installs_but_keeps_what_loads():
+ host = _Host(installed = ["causal-conv1d"], loading = ["causal-conv1d"])
+ r = _run(host, _installer(host), offline = True)
+ assert r.kernel.call_count == 0 and r.uninstall.call_count == 0
+ assert r.notes == [
+ "causal_conv1d already installed and loads.",
+ "mamba_ssm not installed: UV_OFFLINE is set; run `unsloth install-kernels` online",
+ ]
+
+
+def test_offline_still_removes_a_resident_build_that_no_longer_loads():
+ host = _Host(installed = ["mamba-ssm"])
+ r = _run(host, _installer(host), offline = True)
+ assert r.kernel.call_count == 0
+ assert [c.args[0] for c in r.uninstall.call_args_list] == ["mamba-ssm"]
+
+
+def test_a_probe_that_cannot_be_launched_is_inconclusive_not_fatal():
+ host = _Host(installed = ["mamba-ssm"], unlaunchable = ["mamba-ssm"])
+ r = _run(host, lambda name, env, **kwargs: 0)
+ assert r.kernel.call_count == 2 and r.uninstall.call_count == 0
+
+
+def test_the_torch_probe_is_bounded_everywhere_and_a_launch_failure_skips_the_step():
+ host = _Host()
+ r = _run(host, _installer(host))
+ assert r.probe.call_args.kwargs["timeout"] == ips._FLASH_ATTN_IMPORT_PROBE_TIMEOUT
+ with mock.patch.object(ips, "probe_torch_wheel_env", side_effect = OSError("no fork")):
+ with mock.patch.object(ips, "install_kernel") as kernel:
+ ips._ensure_ssm_kernels()
+ assert kernel.call_count == 0
+
+
+def test_an_uninstall_that_cannot_launch_warns_instead_of_aborting():
+ host = _Host(installed = DISTS.values())
+ with mock.patch.object(ips, "_uninstall_distribution", side_effect = OSError("no fork")):
+ steps = []
+ with (
+ mock.patch.object(ips, "NO_TORCH", False),
+ mock.patch.object(ips, "IS_MACOS", False),
+ mock.patch.object(ips, "_uv_is_offline", return_value = True),
+ mock.patch.object(ips, "probe_torch_wheel_env", return_value = ENV),
+ mock.patch.object(ips, "_installed_distribution_version", side_effect = host.version),
+ mock.patch.object(ips.subprocess, "run", side_effect = host.run),
+ mock.patch.object(ips, "_count_install_action"),
+ mock.patch.object(ips, "_note"),
+ mock.patch.object(
+ ips, "_step", side_effect = lambda label, value, *_: steps.append(value)
+ ),
+ ):
+ ips._ensure_ssm_kernels()
+ assert steps == [
+ "causal_conv1d does not load with this torch and could not be removed; "
+ "uninstall causal-conv1d manually",
+ "mamba_ssm does not load with this torch and could not be removed; "
+ "uninstall mamba-ssm manually",
+ ]
+
+
+def test_captured_failure_text_is_redacted():
+ host = _Host()
+
+ def leaks(name, env, **kwargs):
+ raise RuntimeError("index https://user:[email protected]/simple?token=abc failed")
+
+ r = _run(host, leaks)
+ joined = "\n".join(r.notes)
+ assert "s3cret" not in joined and "token=abc" not in joined
+ assert "<redacted>" in joined
+
+
+def test_a_failure_warns_and_the_next_kernel_still_runs():
+ host = _Host()
+ install = _installer(host)
+
+ def first_fails(name, env, **kwargs):
+ if name == "causal_conv1d":
+ raise OSError("disk full")
+ return install(name, env, **kwargs)
+
+ r = _run(host, first_fails)
+ assert r.kernel.call_count == 2
+ assert r.steps == ["Continuing without causal_conv1d"]
+ assert "OSError: disk full" in r.notes
+
+
+def test_a_hung_import_probe_is_bounded_and_never_read_as_broken():
+ host = _Host(installed = ["mamba-ssm"], hangs = ["mamba-ssm"])
+ r = _run(host, lambda name, env, **kwargs: 0)
+ assert r.uninstall.call_count == 0
+ assert host.timeouts
+ assert all(t == ips._FLASH_ATTN_IMPORT_PROBE_TIMEOUT for t in host.timeouts)
+
+
+def test_each_call_gets_a_fresh_runner_so_a_repaired_torch_is_probed_again():
+ runners = []
+
+ def record(name, env, **kwargs):
+ runners.append(kwargs["run"])
+ return 0
+
+ _run(_Host(), record)
+ _run(_Host(), record)
+ assert runners[0] is runners[1] and runners[2] is runners[3]
+ assert runners[0] is not runners[2]
+
+
+ "kwargs",
+ [{"no_torch": True}, {"macos": True}, {"disabled": True}, {"env": None}],
+ ids = ["no-torch", "macos", "opted-out", "no-cuda-torch"],
+)
+def test_nothing_is_installed_when_it_cannot_apply(kwargs):
+ host = _Host()
+ r = _run(host, _installer(host), **kwargs)
+ assert r.kernel.call_count == 0
+
+
+def test_every_flash_attn_site_also_resyncs_the_ssm_kernels():
+ calls = [m.start() for m in re.finditer(r"\n\s+_ensure_flash_attn\(\)\n", SOURCE)]
+ assert len(calls) == 3
+ for start in calls:
+ following = SOURCE[start : start + 200]
+ assert "_ensure_ssm_kernels()" in following, following
+ assert "base_total += 1 # causal-conv1d + mamba-ssm, same gate" in SOURCE