Skip to content

Commit 33f100b

Browse files
install-kernels: add flash-attn and install every kernel by default (#12744)
* install-kernels: add flash-attn and install every kernel by default `unsloth install-kernels` with no names now installs xformers, flash-attn, causal_conv1d and mamba_ssm in that order (mamba_ssm's fast path imports causal_conv1d), each skipped when no wheel matches this torch / CUDA / Python, so notebooks can call it once. flash-attn resolves through wheel_utils.flash_attn_wheel_url, which covers the upstream wheels up to torch 2.12 and the prebuilt-wheels-cu13 builds for torch 2.13 / 2.14. It is skipped below sm80, where FlashAttention 2 does not run and Unsloth never enables it, so a T4 does not download it. * install-kernels: probe the GPU only when a flash-attn wheel exists, bounded, across all GPUs Resolve the wheel first, so a torch probe that already failed or timed out skips flash-attn without a second, unbounded torch import. The capability probe now has a timeout and takes the best visible GPU, so a pre-Ampere device 0 does not hide an Ampere card next to it. * install-kernels: decode the GPU probe as UTF-8
1 parent 7ccf3fc commit 33f100b

3 files changed

Lines changed: 142 additions & 6 deletions

File tree

‎studio/backend/tests/test_kernel_install.py‎

Lines changed: 91 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,19 @@ def test_causal_conv1d_has_no_wheel_off_linux_cuda(env):
105105

106106

107107
class _Runner:
108-
def __init__(self, loads):
108+
def __init__(
109+
self,
110+
loads,
111+
capability = "9 0",
112+
):
109113
self.loads = list(loads)
114+
self.capability = capability
110115
self.calls = []
111116

112117
def __call__(self, cmd, **kwargs):
113118
self.calls.append(cmd)
119+
if cmd[1] == "-c" and "get_device_capability" in cmd[2]:
120+
return SimpleNamespace(returncode = 0, stdout = self.capability)
114121
if cmd[1] == "-c":
115122
return SimpleNamespace(returncode = 0 if self.loads.pop(0) else 1, stdout = "")
116123
return SimpleNamespace(returncode = 0, stdout = "")
@@ -306,3 +313,86 @@ def test_console_entry_drops_an_unwritable_ssl_keylog_file(tmp_path):
306313
)
307314
assert result.returncode == 0, result.stderr
308315
assert "ignoring SSLKEYLOGFILE" in result.stdout + result.stderr
316+
317+
318+
@pytest.mark.parametrize(
319+
"env, expected",
320+
[
321+
(
322+
_env("2.11.0+cu130", "13.0"),
323+
"https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.1/"
324+
"flash_attn-2.8.1+cu13torch2.10cxx11abiTRUE-cp313-cp313-linux_x86_64.whl",
325+
),
326+
(
327+
_env("2.13.0+cu130", "13.0"),
328+
"https://github.com/unslothai/unsloth/releases/download/prebuilt-wheels-cu13/"
329+
"flash_attn-2.8.4+cu13torch2.13cxx11abiTRUE-cp313-cp313-linux_x86_64.whl",
330+
),
331+
(_env("2.11.0+cu130", "13.0", platform_tag = "win_amd64"), None),
332+
(_env("2.11.0+cpu", ""), None),
333+
],
334+
)
335+
def test_flash_attn_resolution(env, expected):
336+
assert kernel_install.resolve_wheel_url("flash_attn", env) == expected
337+
338+
339+
@pytest.mark.parametrize("capability", ["7 5", "None"])
340+
def test_flash_attn_is_skipped_below_sm80(capability, capsys):
341+
run = _Runner([], capability = capability)
342+
assert (
343+
kernel_install.install_kernel("flash_attn", _COLAB, run = run, exists = lambda url: True) == 0
344+
)
345+
assert run.installer_calls == []
346+
assert "skipping flash_attn" in capsys.readouterr().out
347+
348+
349+
def test_flash_attn_installs_on_sm80_and_newer(uv):
350+
uv(False)
351+
run = _Runner([False, True], capability = "8 0")
352+
assert (
353+
kernel_install.install_kernel("flash_attn", _COLAB, run = run, exists = lambda url: True) == 0
354+
)
355+
assert run.installer_calls[0][-1].endswith(
356+
"flash_attn-2.8.1+cu13torch2.10cxx11abiTRUE-cp313-cp313-linux_x86_64.whl"
357+
)
358+
359+
360+
@pytest.mark.parametrize(
361+
"argv, expected",
362+
[
363+
([], ["xformers", "flash_attn", "causal_conv1d", "mamba_ssm"]),
364+
(["mamba_ssm", "causal_conv1d", "mamba_ssm"], ["causal_conv1d", "mamba_ssm"]),
365+
],
366+
)
367+
def test_main_installs_all_by_default_in_dependency_order(monkeypatch, argv, expected):
368+
order = []
369+
monkeypatch.setattr(kernel_install, "probe_torch_wheel_env", lambda **kwargs: _COLAB)
370+
monkeypatch.setattr(
371+
kernel_install, "install_kernel", lambda name, env, dry_run = False: order.append(name) or 0
372+
)
373+
assert kernel_install.main(argv) == 0
374+
assert order == expected
375+
376+
377+
def test_flash_attn_without_a_wheel_never_probes_the_gpu():
378+
run = _Runner([])
379+
assert kernel_install.install_kernel("flash_attn", None, run = run, exists = lambda url: True) == 0
380+
assert run.calls == []
381+
382+
383+
def test_capability_probe_timeout_counts_as_no_gpu():
384+
def run(cmd, **kwargs):
385+
raise subprocess.TimeoutExpired(cmd, kwargs.get("timeout"))
386+
387+
assert kernel_install._gpu_capability(run) is None
388+
389+
390+
def test_capability_probe_takes_the_best_visible_gpu():
391+
seen = {}
392+
393+
def run(cmd, **kwargs):
394+
seen["check"], seen["timeout"] = cmd[2], kwargs.get("timeout")
395+
return SimpleNamespace(returncode = 0, stdout = "9 0\n")
396+
397+
assert kernel_install._gpu_capability(run) == (9, 0)
398+
assert "max(torch.cuda.get_device_capability(i)" in seen["check"] and seen["timeout"]

‎studio/backend/utils/kernel_install.py‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# SPDX-License-Identifier: AGPL-3.0-only
22
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
33

4-
"""`unsloth install-kernels xformers causal_conv1d`: prebuilt kernel wheels matched to the resident torch.
4+
"""`unsloth install-kernels [names]`: prebuilt kernel wheels matched to the resident torch, all by default.
55
66
Wheel-only by design: no wheel for this torch / CUDA / Python means nothing is installed and the
77
model keeps its torch fallback, never a source build. Installs use --no-deps so torch is never touched.
@@ -23,6 +23,7 @@
2323
MAMBA_SSM_RELEASE_BASE_URL,
2424
MAMBA_SSM_RELEASE_TAG,
2525
direct_wheel_url,
26+
flash_attn_wheel_url,
2627
install_wheel,
2728
probe_torch_wheel_env,
2829
redact_url_credentials,
@@ -32,11 +33,13 @@
3233

3334
# name -> (pip distribution, check that loads the compiled extension). The package imports are no
3435
# proof: `import causal_conv1d` never loads it, and `import mamba_ssm` fails on einops under --no-deps.
36+
# Install order: mamba_ssm's fast path imports causal_conv1d.
3537
KERNELS = {
3638
"xformers": (
3739
"xformers",
3840
"from xformers._cpp_lib import _register_extensions; _register_extensions()",
3941
),
42+
"flash_attn": ("flash-attn", "import torch, flash_attn_2_cuda"),
4043
"causal_conv1d": ("causal-conv1d", "import torch, causal_conv1d_cuda"),
4144
"mamba_ssm": ("mamba-ssm", "import torch, selective_scan_cuda"),
4245
}
@@ -56,9 +59,11 @@ def resolve_wheel_url(name: str, env: dict[str, str] | None) -> str | None:
5659
return None
5760
if name == "xformers":
5861
return xformers_wheel_url(env)
59-
# causal-conv1d and mamba-ssm publish Linux wheels only.
62+
# flash-attn, causal-conv1d and mamba-ssm publish Linux wheels only.
6063
if not str(env.get("platform_tag") or "").startswith("linux"):
6164
return None
65+
if name == "flash_attn":
66+
return flash_attn_wheel_url(env)
6267
package_version, release_tag, release_base_url = _RELEASES[name]
6368
return direct_wheel_url(
6469
filename_prefix = name,
@@ -69,6 +74,31 @@ def resolve_wheel_url(name: str, env: dict[str, str] | None) -> str | None:
6974
)
7075

7176

77+
def _gpu_capability(run: Callable[..., subprocess.CompletedProcess]) -> tuple[int, int] | None:
78+
"""The best compute capability across the visible GPUs, or None."""
79+
check = (
80+
"import torch; n = torch.cuda.device_count() if torch.cuda.is_available() else 0; "
81+
"print(*max(torch.cuda.get_device_capability(i) for i in range(n))) if n else None"
82+
)
83+
try:
84+
result = run(
85+
[sys.executable, "-c", check],
86+
stdout = subprocess.PIPE,
87+
stderr = subprocess.DEVNULL,
88+
text = True,
89+
encoding = "utf-8",
90+
errors = "replace",
91+
timeout = 120,
92+
)
93+
except subprocess.TimeoutExpired:
94+
return None
95+
try:
96+
major, minor = (int(part) for part in result.stdout.split())
97+
except ValueError:
98+
return None
99+
return major, minor
100+
101+
72102
def _loads(check: str, run: Callable[..., subprocess.CompletedProcess]) -> bool:
73103
result = run(
74104
[sys.executable, "-c", check], stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL
@@ -100,6 +130,17 @@ def install_kernel(
100130
) -> int:
101131
distribution, check = KERNELS[name]
102132
url = resolve_wheel_url(name, env)
133+
if name == "flash_attn" and url is not None:
134+
# FlashAttention 2 needs Ampere or newer, and Unsloth only enables it there.
135+
capability = _gpu_capability(run)
136+
if capability is None or capability < (8, 0):
137+
gpu = (
138+
"no CUDA GPU is visible"
139+
if capability is None
140+
else "the best GPU is sm%d%d" % capability
141+
)
142+
print(f"Unsloth: skipping flash_attn, which needs sm80 or newer ({gpu}).")
143+
return 0
103144
torch_desc = f"torch {env.get('torch_version')}" if env else "this environment"
104145
# Only a 404 proves nothing is published; an unreachable check falls through to the install.
105146
if url is None or exists(url) is False:
@@ -146,14 +187,19 @@ def main(argv: list[str] | None = None) -> int:
146187
prog = "unsloth install-kernels",
147188
description = "Install prebuilt kernel wheels matching the installed torch. Never builds from source or changes torch.",
148189
)
149-
parser.add_argument("kernels", nargs = "+", choices = sorted(KERNELS))
190+
parser.add_argument(
191+
"kernels",
192+
nargs = "*",
193+
choices = list(KERNELS),
194+
help = "kernels to install (default: all, each skipped when no wheel matches)",
195+
)
150196
parser.add_argument(
151197
"--dry-run", action = "store_true", help = "print the resolved wheel URL and install nothing"
152198
)
153199
args = parser.parse_args(argv)
154200
env = probe_torch_wheel_env(timeout = 120, include_windows = True)
155201
status = 0
156-
for name in dict.fromkeys(args.kernels):
202+
for name in [name for name in KERNELS if not args.kernels or name in args.kernels]:
157203
status = max(status, install_kernel(name, env, dry_run = args.dry_run))
158204
return status
159205

‎unsloth_cli/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ def main(
267267
"ignore_unknown_options": True,
268268
"help_option_names": [],
269269
},
270-
help = "Install prebuilt xformers / causal_conv1d / mamba_ssm wheels matching the installed torch.",
270+
help = "Install prebuilt xformers / flash-attn / causal_conv1d / mamba_ssm wheels matching the installed torch (all by default).",
271271
)
272272
def install_kernels(ctx: typer.Context):
273273
# Listed for `unsloth --help`; the console script dispatches before typer is imported.

0 commit comments

Comments
 (0)