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.

Add unsloth install-kernels for prebuilt xformers / causal_conv1d / mamba_ssm wheels (#12732)

Daniel Han9f5a62db82eb
diff --git a/studio/backend/tests/test_kernel_install.py b/studio/backend/tests/test_kernel_install.py
new file mode 100644
index 00000000000..5edee61d5a9
--- /dev/null
+++ b/studio/backend/tests/test_kernel_install.py
@@ -0,0 +1,308 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`unsloth install-kernels`: wheel-only, CUDA-matched, torch untouched."""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+_BACKEND = Path(__file__).resolve().parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+from utils import kernel_install # noqa: E402
+
+_REPO = _BACKEND.parent.parent
+_PT = "https://download.pytorch.org/whl"
+_CC1D = "https://github.com/Dao-AILab/causal-conv1d/releases/download/v1.6.1.post4"
+
+
+def _env(
+ torch_version,
+ cuda_version,
+ python_tag = "cp313",
+ platform_tag = "linux_x86_64",
+):
+ release = torch_version.split("+", 1)[0]
+ return {
+ "python_tag": python_tag,
+ "torch_mm": ".".join(release.split(".")[:2]),
+ "torch_version": torch_version,
+ "cuda_version": cuda_version,
+ "cuda_major": cuda_version.split(".", 1)[0] if cuda_version else "",
+ "hip_version": "",
+ "cxx11abi": "TRUE",
+ "platform_tag": platform_tag,
+ }
+
+
[email protected](autouse = True)
+def _no_mirror(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_PYTORCH_MIRROR", raising = False)
+
+
+ "torch_version, cuda_version, expected",
+ [
+ (
+ "2.8.0+cu126",
+ "12.6",
+ f"{_PT}/cu126/xformers-0.0.32.post2-cp39-abi3-manylinux_2_28_x86_64.whl",
+ ),
+ (
+ "2.9.0+cu128",
+ "12.8",
+ f"{_PT}/cu128/xformers-0.0.33.post1-cp39-abi3-manylinux_2_28_x86_64.whl",
+ ),
+ (
+ "2.10.0+cu128",
+ "12.8",
+ f"{_PT}/cu128/xformers-0.0.34-cp39-abi3-manylinux_2_28_x86_64.whl",
+ ),
+ (
+ "2.11.0+cu130",
+ "13.0",
+ f"{_PT}/cu130/xformers-0.0.35-py39-none-manylinux_2_28_x86_64.whl",
+ ),
+ (
+ "2.12.1+cu130",
+ "13.0",
+ f"{_PT}/cu130/xformers-0.0.35-py39-none-manylinux_2_28_x86_64.whl",
+ ),
+ ("2.11.0+cpu", "", None),
+ ],
+)
+def test_xformers_matches_torch_and_cuda(torch_version, cuda_version, expected):
+ assert (
+ kernel_install.resolve_wheel_url("xformers", _env(torch_version, cuda_version)) == expected
+ )
+
+
+def test_causal_conv1d_reuses_torch_2_10_wheel_on_2_11():
+ url = kernel_install.resolve_wheel_url("causal_conv1d", _env("2.11.0+cu130", "13.0"))
+ assert (
+ url == f"{_CC1D}/causal_conv1d-1.6.1+cu13torch2.10cxx11abiTRUE-cp313-cp313-linux_x86_64.whl"
+ )
+
+
+ "env",
+ [
+ None,
+ _env("2.11.0+cpu", ""),
+ _env("2.11.0+cu130", "13.0", platform_tag = "win_amd64"),
+ ],
+)
+def test_causal_conv1d_has_no_wheel_off_linux_cuda(env):
+ assert kernel_install.resolve_wheel_url("causal_conv1d", env) is None
+
+
+class _Runner:
+ def __init__(self, loads):
+ self.loads = list(loads)
+ self.calls = []
+
+ def __call__(self, cmd, **kwargs):
+ self.calls.append(cmd)
+ if cmd[1] == "-c":
+ return SimpleNamespace(returncode = 0 if self.loads.pop(0) else 1, stdout = "")
+ return SimpleNamespace(returncode = 0, stdout = "")
+
+ @property
+ def installer_calls(self):
+ return [c for c in self.calls if c[1] != "-c"]
+
+
+_COLAB = _env("2.11.0+cu130", "13.0")
+_COLAB_XFORMERS = f"{_PT}/cu130/xformers-0.0.35-py39-none-manylinux_2_28_x86_64.whl"
+
+
+def uv(monkeypatch):
+ def use(available, outside_venv = False):
+ monkeypatch.setattr(
+ kernel_install.shutil, "which", lambda name: "/usr/bin/uv" if available else None
+ )
+ monkeypatch.setattr(kernel_install, "_outside_venv", lambda: outside_venv)
+
+ return use
+
+
+def test_no_published_wheel_installs_nothing(capsys):
+ run = _Runner([])
+ assert (
+ kernel_install.install_kernel("causal_conv1d", _COLAB, run = run, exists = lambda url: False)
+ == 0
+ )
+ assert run.calls == []
+ assert "using the torch fallback" in capsys.readouterr().out
+
+
+def test_pip_reinstalls_the_matched_wheel_without_deps(uv):
+ uv(False)
+ run = _Runner([False, True])
+ assert kernel_install.install_kernel("xformers", _COLAB, run = run, exists = lambda url: True) == 0
+ assert run.installer_calls == [
+ [sys.executable, "-m", "pip", "install", "--no-deps", "--force-reinstall", _COLAB_XFORMERS]
+ ]
+
+
+def test_uv_reinstalls_into_the_system_interpreter_on_colab(uv):
+ # The check failed, so the installed copy is broken: reinstall even at the same version.
+ uv(True, outside_venv = True)
+ run = _Runner([False, True])
+ assert kernel_install.install_kernel("xformers", _COLAB, run = run, exists = lambda url: True) == 0
+ assert run.installer_calls == [
+ [
+ "uv",
+ "pip",
+ "install",
+ "--system",
+ "--python",
+ sys.executable,
+ "--no-deps",
+ "--reinstall",
+ _COLAB_XFORMERS,
+ ]
+ ]
+
+
+def test_working_install_is_left_alone():
+ run = _Runner([True])
+ assert kernel_install.install_kernel("xformers", _COLAB, run = run, exists = lambda url: True) == 0
+ assert run.installer_calls == []
+
+
+ "has_uv, uninstall",
+ [
+ (False, [sys.executable, "-m", "pip", "uninstall", "-y", "causal-conv1d"]),
+ (True, ["uv", "pip", "uninstall", "--python", sys.executable, "causal-conv1d"]),
+ ],
+)
+def test_wheel_that_does_not_load_is_removed(uv, has_uv, uninstall):
+ uv(has_uv)
+ run = _Runner([False, False])
+ assert (
+ kernel_install.install_kernel("causal_conv1d", _COLAB, run = run, exists = lambda url: True)
+ == 1
+ )
+ assert run.installer_calls[-1] == uninstall
+
+
+def test_dry_run_prints_url_only(capsys):
+ run = _Runner([])
+ assert (
+ kernel_install.install_kernel(
+ "xformers", _COLAB, dry_run = True, run = run, exists = lambda url: True
+ )
+ == 0
+ )
+ assert run.calls == []
+ assert (
+ capsys.readouterr()
+ .out.strip()
+ .endswith("xformers-0.0.35-py39-none-manylinux_2_28_x86_64.whl")
+ )
+
+
+def test_console_entry_works_without_typer(tmp_path):
+ (tmp_path / "typer").mkdir()
+ (tmp_path / "typer" / "__init__.py").write_text(
+ "raise ImportError('typer must not be imported')\n"
+ )
+ env = dict(os.environ, PYTHONPATH = os.pathsep.join([str(tmp_path), str(_REPO)]))
+ result = subprocess.run(
+ [sys.executable, "-m", "unsloth_cli", "install-kernels", "--help"],
+ cwd = tmp_path,
+ env = env,
+ capture_output = True,
+ text = True,
+ timeout = 120,
+ )
+ assert result.returncode == 0, result.stderr
+ assert "usage: unsloth install-kernels" in result.stdout
+
+
+def test_host_package_run_with_dash_m_is_not_intercepted(tmp_path):
+ host = tmp_path / "hostapp"
+ host.mkdir()
+ (host / "__init__.py").write_text("import unsloth_cli\n")
+ (host / "__main__.py").write_text("print('host main ran')\n")
+ env = dict(os.environ, PYTHONPATH = os.pathsep.join([str(tmp_path), str(_REPO)]))
+ result = subprocess.run(
+ [sys.executable, "-m", "hostapp", "install-kernels", "--help"],
+ cwd = tmp_path,
+ env = env,
+ capture_output = True,
+ text = True,
+ timeout = 300,
+ )
+ assert result.returncode == 0, result.stderr
+ assert "host main ran" in result.stdout
+ assert "usage: unsloth install-kernels" not in result.stdout
+
+
+def test_mirror_credentials_are_not_printed(monkeypatch, capsys):
+ monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", "https://user:[email protected]/whl?token=abc")
+ for dry_run in (True, False):
+ kernel_install.install_kernel(
+ "xformers",
+ _COLAB,
+ dry_run = dry_run,
+ run = _Runner([False, True]),
+ exists = lambda url: True,
+ )
+ out = capsys.readouterr().out
+ assert "mirror.example/whl/cu130/xformers-0.0.35" in out
+ assert "secret" not in out and "token=abc" not in out
+
+
+def test_failed_uninstall_is_not_reported_as_removed(uv, capsys):
+ uv(False)
+
+ def run(cmd, **kwargs):
+ return SimpleNamespace(
+ returncode = 1 if cmd[1] in ("-c",) or "uninstall" in cmd else 0, stdout = ""
+ )
+
+ assert (
+ kernel_install.install_kernel("causal_conv1d", _COLAB, run = run, exists = lambda url: True)
+ == 1
+ )
+ out = capsys.readouterr().out
+ assert "removed it" not in out and "pip uninstall causal-conv1d" in out
+
+
+def test_unreachable_probe_does_not_log_mirror_credentials(caplog):
+ from utils.wheel_utils import url_exists
+
+ with caplog.at_level("WARNING"):
+ assert url_exists("https://user:[email protected]/whl/x.whl") is None
+ assert "mirror.invalid/whl/x.whl" in caplog.text
+ assert "secret" not in caplog.text
+
+
+def test_console_entry_drops_an_unwritable_ssl_keylog_file(tmp_path):
+ env = dict(
+ os.environ,
+ PYTHONPATH = str(_REPO),
+ SSLKEYLOGFILE = str(tmp_path / "missing" / "keys.log"),
+ )
+ result = subprocess.run(
+ [sys.executable, "-m", "unsloth_cli", "install-kernels", "--help"],
+ cwd = tmp_path,
+ env = env,
+ capture_output = True,
+ text = True,
+ timeout = 120,
+ )
+ assert result.returncode == 0, result.stderr
+ assert "ignoring SSLKEYLOGFILE" in result.stdout + result.stderr
diff --git a/studio/backend/utils/kernel_install.py b/studio/backend/utils/kernel_install.py
new file mode 100644
index 00000000000..eabf2475889
--- /dev/null
+++ b/studio/backend/utils/kernel_install.py
@@ -0,0 +1,162 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`unsloth install-kernels xformers causal_conv1d`: prebuilt kernel wheels matched to the resident torch.
+
+Wheel-only by design: no wheel for this torch / CUDA / Python means nothing is installed and the
+model keeps its torch fallback, never a source build. Installs use --no-deps so torch is never touched.
+"""
+
+from __future__ import annotations
+
+import argparse
+import shutil
+import subprocess
+import sys
+from typing import Callable
+
+from utils.wheel_utils import (
+ CAUSAL_CONV1D_PACKAGE_VERSION,
+ CAUSAL_CONV1D_RELEASE_BASE_URL,
+ CAUSAL_CONV1D_RELEASE_TAG,
+ MAMBA_SSM_PACKAGE_VERSION,
+ MAMBA_SSM_RELEASE_BASE_URL,
+ MAMBA_SSM_RELEASE_TAG,
+ direct_wheel_url,
+ install_wheel,
+ probe_torch_wheel_env,
+ redact_url_credentials,
+ url_exists,
+ xformers_wheel_url,
+)
+
+# name -> (pip distribution, check that loads the compiled extension). The package imports are no
+# proof: `import causal_conv1d` never loads it, and `import mamba_ssm` fails on einops under --no-deps.
+KERNELS = {
+ "xformers": (
+ "xformers",
+ "from xformers._cpp_lib import _register_extensions; _register_extensions()",
+ ),
+ "causal_conv1d": ("causal-conv1d", "import torch, causal_conv1d_cuda"),
+ "mamba_ssm": ("mamba-ssm", "import torch, selective_scan_cuda"),
+}
+
+_RELEASES = {
+ "causal_conv1d": (
+ CAUSAL_CONV1D_PACKAGE_VERSION,
+ CAUSAL_CONV1D_RELEASE_TAG,
+ CAUSAL_CONV1D_RELEASE_BASE_URL,
+ ),
+ "mamba_ssm": (MAMBA_SSM_PACKAGE_VERSION, MAMBA_SSM_RELEASE_TAG, MAMBA_SSM_RELEASE_BASE_URL),
+}
+
+
+def resolve_wheel_url(name: str, env: dict[str, str] | None) -> str | None:
+ if env is None:
+ return None
+ if name == "xformers":
+ return xformers_wheel_url(env)
+ # causal-conv1d and mamba-ssm publish Linux wheels only.
+ if not str(env.get("platform_tag") or "").startswith("linux"):
+ return None
+ package_version, release_tag, release_base_url = _RELEASES[name]
+ return direct_wheel_url(
+ filename_prefix = name,
+ package_version = package_version,
+ release_tag = release_tag,
+ release_base_url = release_base_url,
+ env = env,
+ )
+
+
+def _loads(check: str, run: Callable[..., subprocess.CompletedProcess]) -> bool:
+ result = run(
+ [sys.executable, "-c", check], stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL
+ )
+ return result.returncode == 0
+
+
+def _outside_venv() -> bool:
+ # Colab and other system interpreters: uv refuses them without --system.
+ return sys.prefix == sys.base_prefix
+
+
+def _uninstall(distribution: str, run: Callable[..., subprocess.CompletedProcess]) -> bool:
+ if shutil.which("uv"):
+ system = ["--system"] if _outside_venv() else []
+ cmd = ["uv", "pip", "uninstall", *system, "--python", sys.executable, distribution]
+ else:
+ cmd = [sys.executable, "-m", "pip", "uninstall", "-y", distribution]
+ return run(cmd, stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL).returncode == 0
+
+
+def install_kernel(
+ name: str,
+ env: dict[str, str] | None,
+ *,
+ dry_run: bool = False,
+ run: Callable[..., subprocess.CompletedProcess] = subprocess.run,
+ exists: Callable[[str], bool | None] = url_exists,
+) -> int:
+ distribution, check = KERNELS[name]
+ url = resolve_wheel_url(name, env)
+ torch_desc = f"torch {env.get('torch_version')}" if env else "this environment"
+ # Only a 404 proves nothing is published; an unreachable check falls through to the install.
+ if url is None or exists(url) is False:
+ print(f"Unsloth: no prebuilt {name} for {torch_desc}; using the torch fallback.")
+ return 0
+ # UNSLOTH_PYTORCH_MIRROR may carry credentials, and notebook output gets shared.
+ shown = redact_url_credentials(url)
+ if dry_run:
+ print(shown)
+ return 0
+ if _loads(check, run):
+ print(f"Unsloth: {name} already installed and loads.")
+ return 0
+ attempts = install_wheel(
+ url,
+ python_executable = sys.executable,
+ use_uv = True,
+ uv_needs_system = _outside_venv(),
+ reinstall = True,
+ run = run,
+ )
+ result = attempts[-1][1]
+ if result.returncode != 0:
+ print(
+ f"Unsloth: installing {name} from {shown} failed; using the torch fallback.\n"
+ + result.stdout[-2000:].replace(url, shown)
+ )
+ return 1
+ if not _loads(check, run):
+ # A wheel that imports but whose extension cannot load would be picked up and crash later.
+ removed = (
+ "removed it" if _uninstall(distribution, run) else f"run `pip uninstall {distribution}`"
+ )
+ print(
+ f"Unsloth: {name} from {shown} does not load with {torch_desc}; {removed}, using the torch fallback."
+ )
+ return 1
+ print(f"Unsloth: installed {name} ({shown.rsplit('/', 1)[-1]}).")
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ prog = "unsloth install-kernels",
+ description = "Install prebuilt kernel wheels matching the installed torch. Never builds from source or changes torch.",
+ )
+ parser.add_argument("kernels", nargs = "+", choices = sorted(KERNELS))
+ parser.add_argument(
+ "--dry-run", action = "store_true", help = "print the resolved wheel URL and install nothing"
+ )
+ args = parser.parse_args(argv)
+ env = probe_torch_wheel_env(timeout = 120, include_windows = True)
+ status = 0
+ for name in dict.fromkeys(args.kernels):
+ status = max(status, install_kernel(name, env, dry_run = args.dry_run))
+ return status
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/studio/backend/utils/ssm_runtime.py b/studio/backend/utils/ssm_runtime.py
index 0a94e6aba80..9c3afd57b9e 100644
--- a/studio/backend/utils/ssm_runtime.py
+++ b/studio/backend/utils/ssm_runtime.py
@@ -19,6 +19,12 @@ from typing import Any, Callable, Iterator, Optional
from loggers import get_logger
from utils.child_stdio import utf8_child_env
from utils.wheel_utils import (
+ CAUSAL_CONV1D_PACKAGE_VERSION,
+ CAUSAL_CONV1D_RELEASE_BASE_URL,
+ CAUSAL_CONV1D_RELEASE_TAG,
+ MAMBA_SSM_PACKAGE_VERSION,
+ MAMBA_SSM_RELEASE_BASE_URL,
+ MAMBA_SSM_RELEASE_TAG,
direct_wheel_url,
install_wheel,
probe_torch_wheel_env,
@@ -29,14 +35,6 @@ logger = get_logger(__name__)
StatusCb = Optional[Callable[[str], None]]
-# Pinned wheels, kept in lockstep with core/training/worker.py by tests/test_ssm_runtime.py.
-CAUSAL_CONV1D_PACKAGE_VERSION = "1.6.1"
-CAUSAL_CONV1D_RELEASE_TAG = "v1.6.1.post4"
-CAUSAL_CONV1D_RELEASE_BASE_URL = "https://github.com/Dao-AILab/causal-conv1d/releases/download"
-MAMBA_SSM_PACKAGE_VERSION = "2.3.1"
-MAMBA_SSM_RELEASE_TAG = "v2.3.1"
-MAMBA_SSM_RELEASE_BASE_URL = "https://github.com/state-spaces/mamba/releases/download"
-
# Lowercased-id substring matches, mirroring the training worker. mamba-ssm models are a subset of the causal-conv1d set.
SSM_MODEL_SUBSTRINGS = (
"nemotron_h",
diff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.py
index b9deada7e8b..3c693a8ba80 100644
--- a/studio/backend/utils/wheel_utils.py
+++ b/studio/backend/utils/wheel_utils.py
@@ -23,6 +23,13 @@ from utils.subprocess_compat import windows_hidden_subprocess_kwargs
_logger = logging.getLogger(__name__)
FLASH_ATTN_RELEASE_BASE_URL = "https://github.com/Dao-AILab/flash-attention/releases/download"
+# Pinned wheels, kept in lockstep with core/training/worker.py by tests/test_ssm_runtime.py.
+CAUSAL_CONV1D_PACKAGE_VERSION = "1.6.1"
+CAUSAL_CONV1D_RELEASE_TAG = "v1.6.1.post4"
+CAUSAL_CONV1D_RELEASE_BASE_URL = "https://github.com/Dao-AILab/causal-conv1d/releases/download"
+MAMBA_SSM_PACKAGE_VERSION = "2.3.1"
+MAMBA_SSM_RELEASE_TAG = "v2.3.1"
+MAMBA_SSM_RELEASE_BASE_URL = "https://github.com/state-spaces/mamba/releases/download"
# No arch gate, deliberately: has_blackwell_gpu() skipped flash-attn before sm_100+ wheels existed (#5420) and became the bug once they did (#6961), denying B200 hosts a working wheel. An arch gate encodes a snapshot of what upstream ships and goes stale silently both ways; the post-install import check catches a wheel that will not load whatever the cause.
@@ -384,6 +391,7 @@ def install_wheel(
python_executable: str,
use_uv: bool,
uv_needs_system: bool = False,
+ reinstall: bool = False,
run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
) -> list[tuple[str, subprocess.CompletedProcess[str]]]:
attempts: list[tuple[str, subprocess.CompletedProcess[str]]] = []
@@ -392,7 +400,11 @@ def install_wheel(
uv_cmd = ["uv", "pip", "install"]
if uv_needs_system:
uv_cmd.append("--system")
- uv_cmd.extend(["--python", python_executable, "--no-deps", wheel_url])
+ uv_cmd.extend(["--python", python_executable, "--no-deps"])
+ # Without it an installed same-version build (another CUDA, or a broken copy) is kept.
+ if reinstall:
+ uv_cmd.append("--reinstall")
+ uv_cmd.append(wheel_url)
result = run(
uv_cmd,
stdout = subprocess.PIPE,
@@ -406,7 +418,10 @@ def install_wheel(
if result.returncode == 0:
return attempts
- pip_cmd = [python_executable, "-m", "pip", "install", "--no-deps", wheel_url]
+ pip_cmd = [python_executable, "-m", "pip", "install", "--no-deps"]
+ if reinstall:
+ pip_cmd.append("--force-reinstall")
+ pip_cmd.append(wheel_url)
result = run(
pip_cmd,
stdout = subprocess.PIPE,
@@ -433,5 +448,11 @@ def url_exists(url: str) -> bool | None:
reason = f"HTTP {exc.code}"
except (OSError, http.client.HTTPException) as exc:
reason = str(exc)
- _logger.warning("url_exists(%s): %s; could not check prebuilt wheel availability", url, reason)
+ shown = redact_url_credentials(url)
+ if shown != url:
+ # The error text can echo the userinfo (urllib reads `user:token@host` as a port).
+ reason = reason if reason.startswith("HTTP ") else "unreachable"
+ _logger.warning(
+ "url_exists(%s): %s; could not check prebuilt wheel availability", shown, reason
+ )
return None
diff --git a/unsloth_cli/__init__.py b/unsloth_cli/__init__.py
index 515c98e6a02..e2d6a62527d 100644
--- a/unsloth_cli/__init__.py
+++ b/unsloth_cli/__init__.py
@@ -53,6 +53,22 @@ def _reconfigure_entry_point_streams():
if _is_entry_point:
_reconfigure_entry_point_streams()
+# Before typer and the command imports: notebooks run this right after `pip install --no-deps unsloth`.
+# `-m` alone could be a host package that imports us, so name the module it runs.
+_orig_argv = getattr(_sys, "orig_argv", [])
+_runs_unsloth_cli = "-munsloth_cli" in _orig_argv or any(
+ a == "-m" and b == "unsloth_cli" for a, b in zip(_orig_argv, _orig_argv[1:])
+)
+if (_is_entry_point or (_entry_base == "-m" and _runs_unsloth_cli)) and _sys.argv[1:2] == [
+ "install-kernels"
+]:
+ from unsloth_cli._install_kernels import main as _install_kernels_main
+ from unsloth_cli._ssl_keylog import drop_unwritable_ssl_keylog_file
+
+ # The availability probe and the installers open HTTPS clients.
+ drop_unwritable_ssl_keylog_file()
+ _sys.exit(_install_kernels_main(_sys.argv[2:]))
+
from unsloth_cli._system_dir_guard import check_working_directory as _check_working_directory
# Running from System32 or a subdir breaks commands; move out before the command imports, since
@@ -118,7 +134,7 @@ def _prepare_entry_point():
# Canonicalise `-np<N>` only under the console-script; imports keep their argv intact.
if _is_entry_point:
_prepare_entry_point()
-del _entry_base, _is_entry_point
+del _entry_base, _is_entry_point, _orig_argv, _runs_unsloth_cli
def show_version(value: bool):
@@ -242,3 +258,18 @@ if not _windows_studio_mutation_entry:
},
help = "Alias for `unsloth studio run`.",
)(studio_run)
+
+
+ "install-kernels",
+ context_settings = {
+ "allow_extra_args": True,
+ "ignore_unknown_options": True,
+ "help_option_names": [],
+ },
+ help = "Install prebuilt xformers / causal_conv1d / mamba_ssm wheels matching the installed torch.",
+)
+def install_kernels(ctx: typer.Context):
+ # Listed for `unsloth --help`; the console script dispatches before typer is imported.
+ from unsloth_cli._install_kernels import main as _install_kernels_main
+ raise typer.Exit(code = _install_kernels_main(ctx.args))
diff --git a/unsloth_cli/_install_kernels.py b/unsloth_cli/_install_kernels.py
new file mode 100644
index 00000000000..ef4f8b415a8
--- /dev/null
+++ b/unsloth_cli/_install_kernels.py
@@ -0,0 +1,33 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`unsloth install-kernels`, reached before typer is imported: notebooks install unsloth with --no-deps."""
+
+import sys
+from importlib.util import find_spec
+from pathlib import Path
+
+
+def main(argv):
+ spec = find_spec("studio")
+ roots = list(spec.submodule_search_locations or []) if spec else []
+ roots.append(str(Path(__file__).resolve().parent.parent / "studio"))
+ backend = next(
+ (
+ Path(r) / "backend"
+ for r in roots
+ if (Path(r) / "backend" / "utils" / "kernel_install.py").is_file()
+ ),
+ None,
+ )
+ if backend is None:
+ print(
+ "Unsloth: studio/backend is missing from this install; cannot resolve kernel wheels.",
+ file = sys.stderr,
+ )
+ return 1
+ # The backend imports its siblings as top-level `utils.*`, as the Studio server does.
+ sys.path.insert(0, str(backend))
+ from utils.kernel_install import main as install_kernels_main
+
+ return install_kernels_main(argv)