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: verify the flash-attn import after installing it (#8465)

Daniel Han947b4bbd7c33
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index 52470da90ed..d4f7be7e93c 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -12,6 +12,8 @@ version-switching. Pattern follows core/data_recipe/jobs/worker.py.
from __future__ import annotations
from loggers import get_logger
+import importlib
+import importlib.metadata
import math
import os
import shutil
@@ -56,7 +58,6 @@ from utils.training_runs import build_default_output_dir_name
from utils.wheel_utils import (
direct_wheel_url,
flash_attn_wheel_url,
- has_blackwell_gpu,
install_wheel,
probe_torch_wheel_env,
url_exists,
@@ -966,7 +967,144 @@ def _hipcc_gcc_install_dir() -> str | None:
return None
+def _is_importable(import_name: str) -> bool:
+ # Invalidate finder caches so a package installed earlier in this process is seen.
+ importlib.invalidate_caches()
+ try:
+ __import__(import_name)
+ return True
+ except Exception as exc:
+ # A wrong-arch/ABI wheel raises OSError/RuntimeError ("undefined symbol"), not
+ # ImportError, so catch everything and let the caller fall back.
+ logger.debug("%s is not importable (%s: %s)", import_name, type(exc).__name__, exc)
+ return False
+
+
+# Kept in step with install_python_stack._FLASH_ATTN_IMPORT_PROBE_TIMEOUT.
+_IMPORT_PROBE_TIMEOUT = 300
+
+
+def _is_importable_isolated(import_name: str) -> bool:
+ """Probe the import in a child process.
+
+ A wrong-arch wheel can abort or segfault in its initialiser instead of raising, which
+ would kill this worker rather than fall back. A child turns that into a return code
+ (negative = fatal signal).
+ """
+ try:
+ result = _sp.run(
+ [
+ sys.executable,
+ "-c",
+ "import importlib, sys; importlib.import_module(sys.argv[1])",
+ import_name,
+ ],
+ stdout = _sp.DEVNULL,
+ stderr = _sp.DEVNULL,
+ timeout = _IMPORT_PROBE_TIMEOUT,
+ # No env override: the probe must see what the real in-process import will.
+ )
+ except (OSError, _sp.TimeoutExpired) as exc:
+ logger.debug("%s import probe did not complete (%s)", import_name, exc)
+ return False
+ if result.returncode != 0:
+ logger.debug("%s import probe exited %s", import_name, result.returncode)
+ return result.returncode == 0
+
+
+def _uninstall_package(pypi_name: str, display_name: str) -> bool:
+ """Remove a distribution. True iff it is gone afterwards."""
+ if shutil.which("uv"):
+ cmd = ["uv", "pip", "uninstall", "--python", sys.executable, pypi_name]
+ else:
+ cmd = [sys.executable, "-m", "pip", "uninstall", "-y", pypi_name]
+ result = _sp.run(
+ cmd,
+ stdout = _sp.PIPE,
+ stderr = _sp.STDOUT,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ env = utf8_child_env(),
+ )
+ if result.returncode != 0:
+ logger.warning("Could not remove the rejected %s install:\n%s", display_name, result.stdout)
+ return False
+ return True
+
+
+def _distribution_present(pypi_name: str) -> bool:
+ """Whether the distribution's METADATA is installed, without importing it.
+
+ Metadata is what matters: unsloth/models/_utils.py gates on ``_package_available`` and
+ only then imports the native module, so metadata left behind is what turns a rejected
+ wheel into an in-process crash. Reading it never loads the extension, so this is safe
+ even for a wheel that would abort.
+ """
+ importlib.invalidate_caches()
+ try:
+ importlib.metadata.distribution(pypi_name)
+ return True
+ except Exception:
+ return False
+
+
+def _reject_install(event_queue: Any, pypi_name: str, display_name: str, reason: str) -> None:
+ """Discard an install that will not import, and say which state we ended in.
+
+ Idempotent, so it is safe on EVERY exit rather than only the ones somebody remembered:
+ it no-ops when the distribution is already gone. Leaving it in place is not the same as
+ never having installed it, since the metadata gate above imports it anyway.
+ """
+ if not _distribution_present(pypi_name):
+ return
+ logger.warning("%s %s", display_name, reason)
+ if _uninstall_package(pypi_name, display_name):
+ _send_status(event_queue, f"{display_name} is not usable on this GPU; removed it")
+ else:
+ _send_status(
+ event_queue,
+ f"{display_name} is not usable on this GPU and could not be removed; "
+ f"uninstall {pypi_name} manually before training",
+ )
+
+
def _install_package_wheel_first(
+ *, event_queue: Any, import_name: str, display_name: str, pypi_name: str, **kwargs: Any
+) -> bool:
+ """Install a fast-path package, wheel first, and never leave an unusable one behind.
+
+ The two "touch nothing" guards run here, outside the cleanup: an already-working
+ package returns before any subprocess, and offline changes nothing. Everything after
+ them is an install attempt, so ANY unsuccessful exit -- timeout, failed install, bad
+ import -- discards what is left 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):
+ logger.info("%s already installed", display_name)
+ return True
+
+ if _model_offline_mode_enabled():
+ logger.info("Skipping %s installation while offline", display_name)
+ return False
+
+ installed = False
+ try:
+ installed = _attempt_package_install(
+ event_queue = event_queue,
+ import_name = import_name,
+ display_name = display_name,
+ pypi_name = pypi_name,
+ **kwargs,
+ )
+ return installed
+ finally:
+ if not installed:
+ _reject_install(event_queue, pypi_name, display_name, "will not import")
+
+
+def _attempt_package_install(
*,
event_queue: Any,
import_name: str,
@@ -980,16 +1118,9 @@ def _install_package_wheel_first(
pypi_spec: str | None = None,
pypi_status_message: str | None = None,
) -> bool:
- try:
- __import__(import_name)
- logger.info("%s already installed", display_name)
- return True
- except ImportError:
- pass
-
- if _model_offline_mode_enabled():
- logger.info("Skipping %s installation while offline", display_name)
- return False
+ """The install itself. Call it through _install_package_wheel_first, never directly."""
+ # Set when a wheel installed but would not import; see the uninstall before the fallback.
+ wheel_rejected = False
env = probe_torch_wheel_env(timeout = 30)
if wheel_url_builder is not None:
@@ -1014,8 +1145,18 @@ def _install_package_wheel_first(
run = _sp.run,
):
if result.returncode == 0:
- logger.info("Installed prebuilt %s wheel successfully", display_name)
- return True
+ # A wheel can install yet fail to import (CUDA/ABI or arch mismatch), so
+ # verify rather than trust the exit code, and do it out of process: a bad
+ # one can take the worker down with it.
+ if _is_importable_isolated(import_name):
+ logger.info("Installed prebuilt %s wheel successfully", display_name)
+ return True
+ logger.warning(
+ "%s wheel installed but is not importable; falling back to PyPI",
+ display_name,
+ )
+ wheel_rejected = True
+ break
logger.warning(
"%s failed to install %s wheel:\n%s",
installer,
@@ -1049,6 +1190,16 @@ def _install_package_wheel_first(
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 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 rather than only the ones that remember to clean up.
+ _uninstall_package(pypi_name, display_name)
+
_send_status(event_queue, pypi_status_message)
plain_pypi_install = pypi_version is None
@@ -1169,6 +1320,12 @@ def _install_package_wheel_first(
)
return False
+ # 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):
+ logger.warning("%s installed from PyPI but will not import", display_name)
+ return False
+
if is_hip:
logger.info("Compiled and installed %s from source for ROCm", display_name)
else:
@@ -1964,12 +2121,6 @@ def _should_try_runtime_flash_attn_install(max_seq_length: int) -> bool:
def _ensure_flash_attn_for_long_context(event_queue: Any, max_seq_length: int) -> None:
if not _should_try_runtime_flash_attn_install(max_seq_length):
return
- if has_blackwell_gpu():
- _send_status(
- event_queue,
- "Skipping flash-attn install: Blackwell GPU detected (sm_100+); no compatible prebuilt wheel",
- )
- return
installed = _install_package_wheel_first(
event_queue = event_queue,
diff --git a/studio/backend/tests/test_mlx_training_worker_config.py b/studio/backend/tests/test_mlx_training_worker_config.py
index bd881ef6ff4..4f89f0b9478 100644
--- a/studio/backend/tests/test_mlx_training_worker_config.py
+++ b/studio/backend/tests/test_mlx_training_worker_config.py
@@ -19,6 +19,7 @@ def _load_worker_module():
"utils.child_stdio",
"utils.hardware",
"utils.hf_dataset_options",
+ "utils.native_tls",
"utils.training_runs",
"utils.wheel_utils",
)
@@ -47,6 +48,13 @@ def _load_worker_module():
hf_dataset_options.hf_dataset_split_instruction_names = lambda *_args, **_kwargs: ()
sys.modules["utils.hf_dataset_options"] = hf_dataset_options
+ # worker.py calls this at import time. Without the stub the module only loads when
+ # some other test happened to import the real utils.native_tls first, so this file
+ # passed in a full run and failed on its own.
+ native_tls = types.ModuleType("utils.native_tls")
+ native_tls.activate_native_tls = lambda *_args, **_kwargs: None
+ sys.modules["utils.native_tls"] = native_tls
+
training_runs = types.ModuleType("utils.training_runs")
training_runs.build_default_output_dir_name = lambda *_args, **_kwargs: "training-run"
sys.modules["utils.training_runs"] = training_runs
@@ -55,7 +63,6 @@ def _load_worker_module():
for name in (
"direct_wheel_url",
"flash_attn_wheel_url",
- "has_blackwell_gpu",
"install_wheel",
"probe_torch_wheel_env",
"url_exists",
diff --git a/studio/backend/tests/test_training_worker_flash_attn.py b/studio/backend/tests/test_training_worker_flash_attn.py
index 6f31f4b8c1c..2b6f34dd2e2 100644
--- a/studio/backend/tests/test_training_worker_flash_attn.py
+++ b/studio/backend/tests/test_training_worker_flash_attn.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import builtins
import subprocess
import sys
+import types
from typing import Any
from unittest import mock
@@ -55,6 +56,32 @@ def _missing_flash_attn_import():
return fake_import
+def _flash_attn_import_until_installed(state: dict[str, bool]):
+ """Import stub for a flash_attn that appears only once ``state['installed']`` is set.
+
+ The installers verify the import, so a mock that keeps failing models a broken wheel,
+ not a working one: "the wheel worked" means flipping the flag when install_wheel runs.
+ """
+ real_import = builtins.__import__
+
+ def fake_import(
+ name,
+ globals = None,
+ locals = None,
+ fromlist = (),
+ level = 0,
+ ):
+ if name == "flash_attn":
+ if not state.get("installed"):
+ raise ImportError
+ # A stub, not a real import: flash_attn is not installed in the test env, and
+ # whether it happens to be is not what these tests are about.
+ return types.ModuleType("flash_attn")
+ return real_import(name, globals, locals, fromlist, level)
+
+ return fake_import
+
+
def _missing_module_import(missing: str):
real_import = builtins.__import__
@@ -72,6 +99,178 @@ def _missing_module_import(missing: str):
return fake_import
+class TestIsImportableIsolated:
+ """The probe runs in a child so a bad native extension cannot take the worker with it."""
+
+ def test_clean_exit_is_importable(self, monkeypatch):
+ monkeypatch.setattr(worker._sp, "run", lambda *a, **k: subprocess.CompletedProcess(a[0], 0))
+ assert worker._is_importable_isolated("flash_attn") is True
+
+ def test_import_error_exit_is_not_importable(self, monkeypatch):
+ monkeypatch.setattr(worker._sp, "run", lambda *a, **k: subprocess.CompletedProcess(a[0], 1))
+ assert worker._is_importable_isolated("flash_attn") is False
+
+ def test_fatal_signal_is_not_importable(self, monkeypatch):
+ # SIGSEGV in the extension's initialiser: rc -11, and no Python exception to catch.
+ monkeypatch.setattr(
+ worker._sp, "run", lambda *a, **k: subprocess.CompletedProcess(a[0], -11)
+ )
+ assert worker._is_importable_isolated("flash_attn") is False
+
+ def test_timeout_is_not_importable(self, monkeypatch):
+ def _hang(*_args, **_kwargs):
+ raise subprocess.TimeoutExpired(cmd = "python", timeout = 300)
+
+ monkeypatch.setattr(worker._sp, "run", _hang)
+ assert worker._is_importable_isolated("flash_attn") is False
+
+ def test_the_module_name_is_passed_as_an_argument(self, monkeypatch):
+ captured: list[list[str]] = []
+
+ def _record(cmd, **_kwargs):
+ captured.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0)
+
+ monkeypatch.setattr(worker._sp, "run", _record)
+ worker._is_importable_isolated("flash_attn")
+
+ # argv, not string-formatted into the -c body.
+ assert captured[0][-1] == "flash_attn"
+ assert "import flash_attn" not in " ".join(captured[0])
+
+
+class TestNoExitLeavesAnUnusableInstall:
+ """Every unsuccessful exit discards the distribution, not just the ones with a call.
+
+ The metadata gate in unsloth/models/_utils.py imports the extension in process, so
+ anything left behind is loaded anyway. Four rounds of review found four separate exits
+ that forgot to clean up, which is why this is enforced in one place.
+ """
+
+ def _run(self, monkeypatch, *, run_side_effect):
+ removals: list[list[str]] = []
+
+ def _spy(cmd, **kwargs):
+ if "uninstall" in cmd:
+ removals.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0, "")
+ return run_side_effect(cmd, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _missing_flash_attn_import())
+ monkeypatch.setattr(worker, "_is_importable_isolated", lambda name: False)
+ # Metadata says it is installed, which is exactly the state that must not survive.
+ monkeypatch.setattr(worker, "_distribution_present", lambda name: True)
+ monkeypatch.setattr(worker, "flash_attn_wheel_url", lambda env: None)
+ monkeypatch.setattr(worker, "url_exists", lambda url: False)
+ monkeypatch.setattr(worker.shutil, "which", lambda name: None)
+ monkeypatch.setattr(worker, "_send_status", lambda q, m: None)
+ monkeypatch.setattr(worker._sp, "run", _spy)
+
+ installed = worker._install_package_wheel_first(
+ event_queue = [],
+ import_name = "flash_attn",
+ display_name = "flash-attn",
+ pypi_name = "flash-attn",
+ pypi_spec = "flash-attn",
+ )
+ return installed, removals
+
+ def test_a_failed_fallback_install_still_cleans_up(self, monkeypatch):
+ installed, removals = self._run(
+ monkeypatch,
+ run_side_effect = lambda cmd, **kw: subprocess.CompletedProcess(cmd, 1, "boom"),
+ )
+ assert installed is False
+ assert removals, "a non-zero fallback exit must not leave the distribution installed"
+
+ def test_a_timed_out_fallback_still_cleans_up(self, monkeypatch):
+ """Only the ROCm source build sets a timeout, so this is the path that can raise."""
+ removals: list[list[str]] = []
+
+ def _spy(cmd, **kwargs):
+ if "uninstall" in cmd:
+ removals.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0, "")
+ raise subprocess.TimeoutExpired(cmd = cmd, timeout = 1800)
+
+ monkeypatch.setattr(builtins, "__import__", _missing_flash_attn_import())
+ monkeypatch.setattr(worker, "_is_importable_isolated", lambda name: False)
+ monkeypatch.setattr(worker, "_distribution_present", lambda name: True)
+ monkeypatch.setattr(
+ worker,
+ "probe_torch_wheel_env",
+ lambda timeout = 30: {
+ "python_tag": "cp313",
+ "torch_mm": "2.10",
+ "cuda_major": "",
+ "hip_version": "6.2",
+ "cxx11abi": "TRUE",
+ "platform_tag": "linux_x86_64",
+ },
+ )
+ monkeypatch.setattr(worker, "flash_attn_wheel_url", lambda env: None)
+ monkeypatch.setattr(worker, "url_exists", lambda url: False)
+ # hipcc present, so the ROCm build is attempted rather than skipped.
+ monkeypatch.setattr(worker.shutil, "which", lambda name: "/opt/rocm/bin/hipcc")
+ monkeypatch.setattr(worker, "_send_status", lambda q, m: None)
+ monkeypatch.setattr(worker._sp, "run", _spy)
+
+ installed = worker._install_package_wheel_first(
+ event_queue = [],
+ import_name = "flash_attn",
+ display_name = "flash-attn",
+ pypi_name = "flash-attn",
+ pypi_spec = "flash-attn",
+ )
+
+ assert installed is False
+ assert removals, "a timed-out build must not leave the distribution installed"
+
+ def test_nothing_installed_means_nothing_to_remove(self, monkeypatch):
+ """The discard is state-based, so a clean failure does not run a pointless uninstall."""
+ removals: list[list[str]] = []
+
+ def _spy(cmd, **_kwargs):
+ if "uninstall" in cmd:
+ removals.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 1, "")
+
+ monkeypatch.setattr(builtins, "__import__", _missing_flash_attn_import())
+ monkeypatch.setattr(worker, "_is_importable_isolated", lambda name: False)
+ monkeypatch.setattr(worker, "_distribution_present", lambda name: False)
+ monkeypatch.setattr(worker, "flash_attn_wheel_url", lambda env: None)
+ monkeypatch.setattr(worker, "url_exists", lambda url: False)
+ monkeypatch.setattr(worker.shutil, "which", lambda name: None)
+ monkeypatch.setattr(worker, "_send_status", lambda q, m: None)
+ monkeypatch.setattr(worker._sp, "run", _spy)
+
+ worker._install_package_wheel_first(
+ event_queue = [],
+ import_name = "flash_attn",
+ display_name = "flash-attn",
+ pypi_name = "flash-attn",
+ pypi_spec = "flash-attn",
+ )
+
+ assert removals == []
+
+ def test_a_working_package_is_never_touched(self, monkeypatch):
+ """The guard runs before the cleanup, so an install that works is left alone."""
+ calls: list[list[str]] = []
+ monkeypatch.setattr(worker, "_is_importable", lambda name: True)
+ monkeypatch.setattr(worker._sp, "run", lambda cmd, **kw: calls.append(list(cmd)))
+
+ installed = worker._install_package_wheel_first(
+ event_queue = [],
+ import_name = "flash_attn",
+ display_name = "flash-attn",
+ pypi_name = "flash-attn",
+ )
+
+ assert installed is True
+ assert calls == [], "a working package must not be probed, installed or removed"
+
+
def test_should_try_runtime_flash_attn_install_threshold_and_skip(monkeypatch):
monkeypatch.delenv(worker._FLASH_ATTN_SKIP_ENV, raising = False)
assert worker._should_try_runtime_flash_attn_install(32767) is False
@@ -84,9 +283,48 @@ def test_should_try_runtime_flash_attn_install_threshold_and_skip(monkeypatch):
@linux_only
def test_runtime_flash_attn_prefers_prebuilt_wheel(monkeypatch):
statuses: list[str] = []
+ state: dict[str, bool] = {"installed": False}
+
+ def _install(*_args, **_kwargs):
+ state["installed"] = True
+ return [("pip", subprocess.CompletedProcess(["pip"], 0, ""))]
monkeypatch.delenv(worker._FLASH_ATTN_SKIP_ENV, raising = False)
+ monkeypatch.setattr(builtins, "__import__", _flash_attn_import_until_installed(state))
+ # The post-install probe runs in a child; model it off the same flag.
+ monkeypatch.setattr(worker, "_is_importable_isolated", lambda name: state["installed"])
+ monkeypatch.setattr(
+ worker,
+ "flash_attn_wheel_url",
+ lambda env: "https://example.com/fa.whl",
+ )
+ monkeypatch.setattr(worker, "url_exists", lambda url: True)
+ monkeypatch.setattr(
+ worker,
+ "_send_status",
+ lambda queue, message: statuses.append(message),
+ )
+ monkeypatch.setattr(worker, "install_wheel", _install)
+
+ worker._ensure_flash_attn_for_long_context(event_queue = [], max_seq_length = 32768)
+
+ assert statuses == ["Installing flash-attn for faster training..."]
+
+
+@linux_only
+def test_runtime_flash_attn_wheel_that_does_not_import_falls_back(monkeypatch):
+ """A wrong-arch/ABI wheel installs with rc=0 and then will not load.
+
+ The Blackwell shape (#5420, #6961): trusting the exit code left a flash_attn that
+ raised on import mid-training. It must be treated as not installed.
+ """
+ statuses: list[str] = []
+ pypi_calls: list[list[str]] = []
+
+ monkeypatch.delenv(worker._FLASH_ATTN_SKIP_ENV, raising = False)
+ # Never becomes importable, however the install exits.
monkeypatch.setattr(builtins, "__import__", _missing_flash_attn_import())
+ monkeypatch.setattr(worker, "_is_importable_isolated", lambda name: False)
monkeypatch.setattr(
worker,
"flash_attn_wheel_url",
@@ -103,19 +341,125 @@ def test_runtime_flash_attn_prefers_prebuilt_wheel(monkeypatch):
"install_wheel",
lambda *args, **kwargs: [("pip", subprocess.CompletedProcess(["pip"], 0, ""))],
)
+ monkeypatch.setattr(worker.shutil, "which", lambda name: None)
+ monkeypatch.setattr(
+ worker._sp,
+ "run",
+ lambda cmd, **kwargs: pypi_calls.append(cmd) or subprocess.CompletedProcess(cmd, 1, ""),
+ )
worker._ensure_flash_attn_for_long_context(event_queue = [], max_seq_length = 32768)
- assert statuses == ["Installing flash-attn for faster training..."]
+ # The wheel is not silently trusted: it falls through to the PyPI path.
+ assert "Installing flash-attn from PyPI for long-context training..." in statuses
+ installs = [cmd for cmd in pypi_calls if "install" in cmd]
+ assert installs, "expected a PyPI install attempt after the wheel failed to import"
+ # The rejected wheel is removed first. Installing over it is a no-op (pip reports it as
+ # already satisfied), and --force-reinstall would widen the transaction to torch.
+ assert any("uninstall" in cmd for cmd in pypi_calls), pypi_calls
+ assert not any("--force-reinstall" in cmd for cmd in installs), installs
+
+
+@linux_only
+def test_runtime_flash_attn_rejected_wheel_is_not_reported_installed(monkeypatch):
+ """A no-op fallback must not be read as success.
+
+ pip exits 0 on "Requirement already satisfied" and uv on "Would make no changes", so
+ the exit code alone would report the rejected wheel as a working install.
+ """
+ statuses: list[str] = []
+
+ monkeypatch.delenv(worker._FLASH_ATTN_SKIP_ENV, raising = False)
+ monkeypatch.setattr(builtins, "__import__", _missing_flash_attn_import())
+ monkeypatch.setattr(worker, "_is_importable_isolated", lambda name: False)
+ # The discard is state-based, so the installed-but-broken state has to be stated here.
+ # Without this the test only passes on a machine that happens to have flash-attn.
+ monkeypatch.setattr(worker, "_distribution_present", lambda name: True)
+ monkeypatch.setattr(
+ worker,
+ "flash_attn_wheel_url",
+ lambda env: "https://example.com/fa.whl",
+ )
+ monkeypatch.setattr(worker, "url_exists", lambda url: True)
+ monkeypatch.setattr(
+ worker,
+ "_send_status",
+ lambda queue, message: statuses.append(message),
+ )
+ monkeypatch.setattr(
+ worker,
+ "install_wheel",
+ lambda *args, **kwargs: [("pip", subprocess.CompletedProcess(["pip"], 0, ""))],
+ )
+ monkeypatch.setattr(worker.shutil, "which", lambda name: None)
+ # The fallback "succeeds" the way an already-satisfied install does: rc=0, nothing done.
+ monkeypatch.setattr(
+ worker._sp,
+ "run",
+ lambda cmd, **kwargs: subprocess.CompletedProcess(cmd, 0, "Requirement already satisfied"),
+ )
+
+ installed = worker._install_package_wheel_first(
+ event_queue = [],
+ import_name = "flash_attn",
+ display_name = "flash-attn",
+ pypi_name = "flash-attn",
+ wheel_url_builder = worker.flash_attn_wheel_url,
+ pypi_spec = "flash-attn",
+ pypi_status_message = "Installing flash-attn from PyPI for long-context training...",
+ )
+
+ assert installed is False
+ # and it is removed, not left where _package_available would advertise it.
+ assert "flash-attn is not usable on this GPU; removed it" in statuses
+
+
+@linux_only
+def test_runtime_flash_attn_says_so_when_the_rejected_install_cannot_be_removed(monkeypatch):
+ """A distribution still on disk is not the same state as never having installed one."""
+ statuses: list[str] = []
+
+ monkeypatch.delenv(worker._FLASH_ATTN_SKIP_ENV, raising = False)
+ monkeypatch.setattr(builtins, "__import__", _missing_flash_attn_import())
+ monkeypatch.setattr(worker, "_is_importable_isolated", lambda name: False)
+ # State the installed-but-broken state explicitly; see the note above.
+ monkeypatch.setattr(worker, "_distribution_present", lambda name: True)
+ monkeypatch.setattr(worker, "flash_attn_wheel_url", lambda env: None)
+ monkeypatch.setattr(worker, "url_exists", lambda url: False)
+ monkeypatch.setattr(worker.shutil, "which", lambda name: None)
+ monkeypatch.setattr(
+ worker,
+ "_send_status",
+ lambda queue, message: statuses.append(message),
+ )
+ # Install exits 0; every uninstall attempt fails (read-only or locked site-packages).
+ monkeypatch.setattr(
+ worker._sp,
+ "run",
+ lambda cmd, **kw: subprocess.CompletedProcess(cmd, 1 if "uninstall" in cmd else 0, ""),
+ )
+
+ installed = worker._install_package_wheel_first(
+ event_queue = [],
+ import_name = "flash_attn",
+ display_name = "flash-attn",
+ pypi_name = "flash-attn",
+ pypi_spec = "flash-attn",
+ )
+
+ assert installed is False
+ assert any("could not be removed" in s for s in statuses), statuses
+ assert not any("removed it" in s for s in statuses), statuses
@linux_only
def test_runtime_flash_attn_falls_back_to_pypi(monkeypatch):
calls: list[list[str]] = []
statuses: list[str] = []
+ state: dict[str, bool] = {"installed": False}
monkeypatch.delenv(worker._FLASH_ATTN_SKIP_ENV, raising = False)
- monkeypatch.setattr(builtins, "__import__", _missing_flash_attn_import())
+ monkeypatch.setattr(builtins, "__import__", _flash_attn_import_until_installed(state))
monkeypatch.setattr(
worker,
"probe_torch_wheel_env",
@@ -134,6 +478,7 @@ def test_runtime_flash_attn_falls_back_to_pypi(monkeypatch):
)
monkeypatch.setattr(worker, "url_exists", lambda url: False)
monkeypatch.setattr(worker.shutil, "which", lambda name: None)
+ monkeypatch.setattr(worker, "_is_importable_isolated", lambda name: state["installed"])
monkeypatch.setattr(
worker,
"_send_status",
@@ -143,6 +488,8 @@ def test_runtime_flash_attn_falls_back_to_pypi(monkeypatch):
def fake_run(cmd, **kwargs):
calls.append(list(cmd))
+ # A real install makes the module importable; the post-install check requires it.
+ state["installed"] = True
return subprocess.CompletedProcess(cmd, 0, "")
monkeypatch.setattr(worker._sp, "run", fake_run)
@@ -150,6 +497,7 @@ def test_runtime_flash_attn_falls_back_to_pypi(monkeypatch):
worker._ensure_flash_attn_for_long_context(event_queue = [], max_seq_length = 32768)
assert statuses == ["Installing flash-attn from PyPI for long-context training..."]
+ # No wheel was installed here (url_exists is False), so nothing needs replacing.
assert calls == [[sys.executable, "-m", "pip", "install", "flash-attn"]]
diff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.py
index 0d8d6099d91..a5f65e9fef8 100644
--- a/studio/backend/utils/wheel_utils.py
+++ b/studio/backend/utils/wheel_utils.py
@@ -3,7 +3,6 @@
from __future__ import annotations
-import functools
import json
import logging
import os
@@ -25,48 +24,11 @@ _logger = logging.getLogger(__name__)
FLASH_ATTN_RELEASE_BASE_URL = "https://github.com/Dao-AILab/flash-attention/releases/download"
[email protected]_cache(maxsize = 1)
-def has_blackwell_gpu() -> bool:
- """Return True if any visible NVIDIA GPU has compute capability >= 10.0 (Blackwell).
-
- Cached for the process lifetime; tests mocking nvidia-smi must call
- ``has_blackwell_gpu.cache_clear()`` first.
- """
- # Detection disabled for now: Dao-AILab ships Blackwell (sm_100+) flash-attn
- # wheels and url_exists() already gates resolution, so we no longer skip
- # flash-attn on Blackwell. The nvidia-smi probe below is kept for possible
- # future arch-based gating; drop this early return to re-enable it.
- return False
- exe = shutil.which("nvidia-smi")
- if not exe:
- return False
- try:
- result = subprocess.run(
- [exe, "--query-gpu=compute_cap", "--format=csv,noheader"],
- stdout = subprocess.PIPE,
- stderr = subprocess.DEVNULL,
- text = True,
- encoding = "utf-8",
- errors = "replace",
- timeout = 10,
- env = child_env_without_native_path_secret(),
- )
- except (OSError, subprocess.TimeoutExpired):
- return False
- if result.returncode != 0:
- return False
- for line in result.stdout.splitlines():
- cap = line.strip()
- if not cap:
- continue
- major_part = cap.split(".", 1)[0]
- try:
- major = int(major_part)
- except ValueError:
- continue
- if major >= 10:
- return True
- return False
+# No arch gate here, deliberately. has_blackwell_gpu() skipped flash-attn when upstream
+# published no sm_100+ wheels (#5420), then became the bug once it did, denying B200 hosts
+# a working wheel (#6961). An arch gate encodes a snapshot of what upstream ships and goes
+# stale silently both ways; the callers' post-install import check catches a wheel that
+# will not load whatever the cause.
def wheel_platform_tag() -> str | None:
diff --git a/studio/install_python_stack.py b/studio/install_python_stack.py
index 8c63f67bf76..2448aadbe99 100644
--- a/studio/install_python_stack.py
+++ b/studio/install_python_stack.py
@@ -36,7 +36,6 @@ import install_manifest # noqa: E402
from backend.utils.wheel_utils import (
flash_attn_package_version,
flash_attn_wheel_url,
- has_blackwell_gpu,
install_wheel,
probe_torch_wheel_env,
url_exists,
@@ -3649,28 +3648,56 @@ def _flash_attn_install_disabled() -> bool:
return os.getenv("UNSLOTH_STUDIO_SKIP_FLASHATTN_INSTALL") == "1"
+# Matches worker._is_importable_isolated: the same untrusted import, bounded the same way.
+_FLASH_ATTN_IMPORT_PROBE_TIMEOUT = 300
+
+
+def _flash_attn_importable() -> bool:
+ """Whether flash_attn imports, checked out of process.
+
+ A wrong-arch/ABI wheel installs fine and raises on import, so a zero pip exit code is
+ not proof the install is usable. In a child, so a half-loaded native extension cannot
+ poison the installer, and bounded, since initialisation can hang rather than fail.
+ """
+ try:
+ result = subprocess.run(
+ [sys.executable, "-c", "import flash_attn"],
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ timeout = _FLASH_ATTN_IMPORT_PROBE_TIMEOUT,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return result.returncode == 0
+
+
+def _remove_rejected_flash_attn() -> bool:
+ """Uninstall a flash-attn that installed but will not import. True iff it is gone.
+
+ Targets the interpreter install_wheel installed into, always ``sys.executable``: its uv
+ command passes --python as well as --system, and its pip fallback runs that interpreter.
+ --system ALONE would remove from the system Python, leaving the rejected wheel in the
+ venv while setup reported it gone.
+ """
+ if USE_UV and shutil.which("uv"):
+ cmd = ["uv", "pip", "uninstall"]
+ if UV_NEEDS_SYSTEM:
+ cmd.append("--system")
+ cmd.extend(["--python", sys.executable, "flash-attn"])
+ else:
+ cmd = [sys.executable, "-m", "pip", "uninstall", "-y", "flash-attn"]
+ removed = subprocess.run(cmd, stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL)
+ return removed.returncode == 0
+
+
def _ensure_flash_attn() -> None:
if _flash_attn_install_disabled():
return
if NO_TORCH:
return
- if has_blackwell_gpu():
- _step(
- "warning",
- "Skipping flash-attn: Blackwell GPU detected (sm_100+); no compatible prebuilt wheel",
- _cyan,
- )
- return
if IS_WINDOWS or IS_MACOS:
return
- if (
- subprocess.run(
- [sys.executable, "-c", "import flash_attn"],
- stdout = subprocess.DEVNULL,
- stderr = subprocess.DEVNULL,
- ).returncode
- == 0
- ):
+ if _flash_attn_importable():
return
env = probe_torch_wheel_env()
@@ -3683,7 +3710,28 @@ def _ensure_flash_attn() -> None:
uv_needs_system = UV_NEEDS_SYSTEM,
):
if wheel_result.returncode == 0:
- return
+ # Verify rather than trust the exit code, so setup reports what happened.
+ if _flash_attn_importable():
+ return
+ # Remove it before giving up. Left installed, unsloth/models/_utils.py finds
+ # it by metadata (_package_available) and then imports the native module
+ # in process, so a wheel that killed the probe would kill training too.
+ if _remove_rejected_flash_attn():
+ _step(
+ "warning",
+ "flash-attn wheel installed but is not importable on this GPU; removed it",
+ _cyan,
+ )
+ else:
+ # Say so plainly: it is still importable in process, so this is not the
+ # same state as never having installed it.
+ _step(
+ "warning",
+ "flash-attn wheel is not importable on this GPU and could not be "
+ "removed; uninstall flash-attn manually before training",
+ _cyan,
+ )
+ break
_print_optional_install_failure(
f"Installing flash-attn prebuilt wheel with {installer}",
wheel_result,
diff --git a/tests/python/test_flash_attn_install_python_stack.py b/tests/python/test_flash_attn_install_python_stack.py
index 2cdb7450146..54f6ee6fbdb 100644
--- a/tests/python/test_flash_attn_install_python_stack.py
+++ b/tests/python/test_flash_attn_install_python_stack.py
@@ -149,10 +149,50 @@ class TestFlashAttnWheelSelection:
)
+class TestFlashAttnImportProbe:
+ """The probe is bounded: a native extension can hang in its initialiser, not just fail."""
+
+ def test_clean_exit_is_importable(self):
+ with mock.patch(
+ "subprocess.run",
+ return_value = subprocess.CompletedProcess(["python"], 0),
+ ):
+ assert ips._flash_attn_importable() is True
+
+ def test_non_zero_exit_is_not_importable(self):
+ with mock.patch(
+ "subprocess.run",
+ return_value = subprocess.CompletedProcess(["python"], 1),
+ ):
+ assert ips._flash_attn_importable() is False
+
+ def test_a_hung_import_is_not_importable(self):
+ with mock.patch(
+ "subprocess.run",
+ side_effect = subprocess.TimeoutExpired(cmd = "python", timeout = 300),
+ ):
+ assert ips._flash_attn_importable() is False
+
+ def test_the_probe_is_bounded(self):
+ with mock.patch(
+ "subprocess.run",
+ return_value = subprocess.CompletedProcess(["python"], 0),
+ ) as run:
+ ips._flash_attn_importable()
+
+ assert run.call_args.kwargs["timeout"] == ips._FLASH_ATTN_IMPORT_PROBE_TIMEOUT
+
+
class TestEnsureFlashAttn:
def _import_check(self, code: int = 1):
return subprocess.CompletedProcess(["python", "-c", "import flash_attn"], code)
+ def _import_fails_removal_works(self, cmd, **_kwargs):
+ """flash_attn never imports, but uninstalling it succeeds."""
+ if "uninstall" in cmd:
+ return subprocess.CompletedProcess(cmd, 0)
+ return self._import_check()
+
def test_prefers_exact_match_wheel(self):
install_calls = []
@@ -226,6 +266,232 @@ class TestEnsureFlashAttn:
_, kwargs = install_calls[0]
assert kwargs["uv_needs_system"] is True
+ def test_wheel_that_does_not_import_is_not_trusted(self):
+ """pip exits 0 on a wrong-arch/ABI wheel; the import is what decides.
+
+ The #5420 / #6961 Blackwell shape: setup must report that rather than claim
+ flash-attn is ready.
+ """
+ step_messages: list[tuple[str, str]] = []
+
+ with (
+ mock.patch.object(ips, "NO_TORCH", False),
+ mock.patch.object(ips, "IS_WINDOWS", False),
+ mock.patch.object(ips, "IS_MACOS", False),
+ mock.patch.object(
+ ips,
+ "probe_torch_wheel_env",
+ return_value = {
+ "python_tag": "cp313",
+ "torch_mm": "2.10",
+ "cuda_major": "13",
+ "cxx11abi": "TRUE",
+ "platform_tag": "linux_x86_64",
+ },
+ ),
+ mock.patch.object(ips, "url_exists", return_value = True),
+ mock.patch.object(
+ ips,
+ "install_wheel",
+ return_value = [("uv", subprocess.CompletedProcess(["uv"], 0, ""))],
+ ),
+ mock.patch.object(
+ ips,
+ "_step",
+ side_effect = lambda label, value, color_fn = None: step_messages.append(
+ (label, value)
+ ),
+ ),
+ # Import never succeeds, before or after the install; the removal does.
+ mock.patch("subprocess.run", side_effect = self._import_fails_removal_works),
+ ):
+ ips._ensure_flash_attn()
+
+ assert (
+ "warning",
+ "flash-attn wheel installed but is not importable on this GPU; removed it",
+ ) in step_messages
+ assert ("warning", "Continuing without flash-attn") in step_messages
+
+ def test_rejected_wheel_is_uninstalled(self):
+ """Leaving it installed is not "continuing without flash-attn".
+
+ unsloth/models/_utils.py finds it by metadata (_package_available) and then imports
+ the native module in process, so a wheel that killed the probe kills training too.
+ """
+ step_messages: list[tuple[str, str]] = []
+ removals: list[list[str]] = []
+
+ def fake_run(cmd, **kwargs):
+ if "uninstall" in cmd:
+ removals.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0)
+ return self._import_check()
+
+ with (
+ mock.patch.object(ips, "NO_TORCH", False),
+ mock.patch.object(ips, "IS_WINDOWS", False),
+ mock.patch.object(ips, "IS_MACOS", False),
+ mock.patch.object(
+ ips,
+ "probe_torch_wheel_env",
+ return_value = {
+ "python_tag": "cp313",
+ "torch_mm": "2.10",
+ "cuda_major": "13",
+ "cxx11abi": "TRUE",
+ "platform_tag": "linux_x86_64",
+ },
+ ),
+ mock.patch.object(ips, "url_exists", return_value = True),
+ mock.patch.object(
+ ips,
+ "install_wheel",
+ return_value = [("uv", subprocess.CompletedProcess(["uv"], 0, ""))],
+ ),
+ mock.patch.object(
+ ips,
+ "_step",
+ side_effect = lambda label, value, color_fn = None: step_messages.append(
+ (label, value)
+ ),
+ ),
+ mock.patch("subprocess.run", side_effect = fake_run),
+ ):
+ ips._ensure_flash_attn()
+
+ assert removals, "the rejected wheel must be uninstalled, not left in site-packages"
+ assert any("flash-attn" in cmd for cmd in removals), removals
+ assert ("warning", "Continuing without flash-attn") in step_messages
+
+ def test_uninstall_targets_the_interpreter_install_wheel_used(self):
+ """install_wheel passes --python as well as --system, and its pip fallback runs
+ sys.executable directly, so --system alone would uninstall from the wrong Python."""
+ commands: list[list[str]] = []
+
+ def fake_run(cmd, **kwargs):
+ commands.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0)
+
+ with (
+ mock.patch.object(ips, "USE_UV", True),
+ mock.patch.object(ips, "UV_NEEDS_SYSTEM", True),
+ mock.patch.object(ips.shutil, "which", return_value = "/usr/bin/uv"),
+ mock.patch("subprocess.run", side_effect = fake_run),
+ ):
+ assert ips._remove_rejected_flash_attn() is True
+
+ assert commands == [
+ ["uv", "pip", "uninstall", "--system", "--python", sys.executable, "flash-attn"]
+ ]
+
+ def test_uninstall_targets_the_interpreter_without_system_mode(self):
+ commands: list[list[str]] = []
+
+ def fake_run(cmd, **kwargs):
+ commands.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0)
+
+ with (
+ mock.patch.object(ips, "USE_UV", True),
+ mock.patch.object(ips, "UV_NEEDS_SYSTEM", False),
+ mock.patch.object(ips.shutil, "which", return_value = "/usr/bin/uv"),
+ mock.patch("subprocess.run", side_effect = fake_run),
+ ):
+ assert ips._remove_rejected_flash_attn() is True
+
+ assert commands == [["uv", "pip", "uninstall", "--python", sys.executable, "flash-attn"]]
+
+ def test_a_failed_removal_is_not_reported_as_removed(self):
+ """Still importable in process, so it must not read like a clean skip."""
+ step_messages: list[tuple[str, str]] = []
+
+ def fake_run(cmd, **kwargs):
+ if "uninstall" in cmd:
+ return subprocess.CompletedProcess(cmd, 1)
+ return self._import_check()
+
+ with (
+ mock.patch.object(ips, "NO_TORCH", False),
+ mock.patch.object(ips, "IS_WINDOWS", False),
+ mock.patch.object(ips, "IS_MACOS", False),
+ mock.patch.object(
+ ips,
+ "probe_torch_wheel_env",
+ return_value = {
+ "python_tag": "cp313",
+ "torch_mm": "2.10",
+ "cuda_major": "13",
+ "cxx11abi": "TRUE",
+ "platform_tag": "linux_x86_64",
+ },
+ ),
+ mock.patch.object(ips, "url_exists", return_value = True),
+ mock.patch.object(
+ ips,
+ "install_wheel",
+ return_value = [("uv", subprocess.CompletedProcess(["uv"], 0, ""))],
+ ),
+ mock.patch.object(
+ ips,
+ "_step",
+ side_effect = lambda label, value, color_fn = None: step_messages.append(
+ (label, value)
+ ),
+ ),
+ mock.patch("subprocess.run", side_effect = fake_run),
+ ):
+ ips._ensure_flash_attn()
+
+ warnings = [value for _, value in step_messages]
+ assert any("could not be removed" in value for value in warnings), warnings
+ assert not any("removed it" in value for value in warnings), warnings
+
+ def test_working_wheel_reports_no_warning(self):
+ """The happy path stays silent: install exits 0 and the module imports."""
+ step_messages: list[tuple[str, str]] = []
+ import_calls: list[int] = []
+
+ def fake_run(cmd, **kwargs):
+ # First call is the pre-install check (missing), the second verifies the install.
+ import_calls.append(1)
+ return self._import_check(1 if len(import_calls) == 1 else 0)
+
+ with (
+ mock.patch.object(ips, "NO_TORCH", False),
+ mock.patch.object(ips, "IS_WINDOWS", False),
+ mock.patch.object(ips, "IS_MACOS", False),
+ mock.patch.object(
+ ips,
+ "probe_torch_wheel_env",
+ return_value = {
+ "python_tag": "cp313",
+ "torch_mm": "2.10",
+ "cuda_major": "13",
+ "cxx11abi": "TRUE",
+ "platform_tag": "linux_x86_64",
+ },
+ ),
+ mock.patch.object(ips, "url_exists", return_value = True),
+ mock.patch.object(
+ ips,
+ "install_wheel",
+ return_value = [("uv", subprocess.CompletedProcess(["uv"], 0, ""))],
+ ),
+ mock.patch.object(
+ ips,
+ "_step",
+ side_effect = lambda label, value, color_fn = None: step_messages.append(
+ (label, value)
+ ),
+ ),
+ mock.patch("subprocess.run", side_effect = fake_run),
+ ):
+ ips._ensure_flash_attn()
+
+ assert step_messages == []
+ assert len(import_calls) == 2, "expected a verification import after the install"
+
def test_wheel_failure_warns_and_continues(self):
step_messages: list[tuple[str, str]] = []
printed_failures: list[str] = []