Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Keep xFormers working when flash-attn 4 is installed, and guard the varlen int32 overflow (#8957)
Daniel Han2cf7a28880f9
diff --git a/tests/test_flash_attn_4_namespace_shadow.py b/tests/test_flash_attn_4_namespace_shadow.pynew file mode 100644index 00000000000..c8f273a6a1c--- /dev/null+++ b/tests/test_flash_attn_4_namespace_shadow.py@@ -0,0 +1,271 @@+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Lesser General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Lesser General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.++"""flash-attn 4 installs the CuTe build as `flash_attn.cute` with no `flash_attn/__init__.py`,+so `flash_attn` becomes an implicit namespace package with no `flash_attn_func`,+no `flash_attn_varlen_func` and no `flash_attn.flash_attn_interface`.++xFormers imports `flash_attn.flash_attn_interface` unconditionally once `find_spec("flash_attn")`+hits, so that layout makes `import xformers.ops` raise, unsloth swallows it into+`xformers = None`, `HAS_XFORMERS` goes False and every fast-path model silently degrades to+plain SDPA (measured on a B200 at seq_len 8192 with Qwen3-0.6B + LoRA: 547 -> 2154 ms/step,+2.69 -> 19.02 GB peak).++These tests build the three module layouts on disk and check the classifier, because the+whole fix hangs off getting the classification exactly right: a real flash-attn 2 install must+not be touched, and neither must a machine with BOTH installed.+"""++import importlib.util+import pathlib+import subprocess+import sys+import textwrap++import pytest++_REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]+++def _load_import_fixes():+ """The module by path, not `from unsloth import import_fixes`.++ Importing the package runs unsloth/__init__.py, which refuses to import without an+ accelerator, so the package form cannot be collected on the CPU-only CI job. This+ module is stdlib plus packaging at import time, so it loads on its own.+ """+ spec = importlib.util.spec_from_file_location(+ "unsloth_import_fixes_under_test", _REPO_ROOT / "unsloth" / "import_fixes.py"+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++import_fixes = _load_import_fixes()+++def _write_layout(tmp_path, layout):+ """Materialise a site-packages-like directory for one flash_attn layout."""+ root = tmp_path / layout+ pkg = root / "flash_attn"+ if layout == "absent":+ root.mkdir(parents = True, exist_ok = True)+ return root+ if layout in ("flash_attn_4_only", "both"):+ # flash-attn 4: a `cute` subpackage and deliberately NO flash_attn/__init__.py.+ (pkg / "cute").mkdir(parents = True, exist_ok = True)+ (pkg / "cute" / "__init__.py").write_text("def flash_attn_func(*a, **k): ...\n")+ if layout in ("flash_attn_2", "both"):+ pkg.mkdir(parents = True, exist_ok = True)+ if layout == "flash_attn_2":+ # A real flash-attn 2 wheel is a regular package.+ (pkg / "__init__.py").write_text(+ "__version__ = '2.8.3'\n"+ "def flash_attn_func(*a, **k): ...\n"+ "def flash_attn_varlen_func(*a, **k): ...\n"+ )+ (pkg / "flash_attn_interface.py").write_text("flash_attn_gpu = object()\n")+ return root+++# The same by-path load as _load_import_fixes, for the subprocess cases.+_LOAD_MODULE = """+ import importlib.util, pathlib, sys+ _path = pathlib.Path(sys.argv[2]) / "unsloth" / "import_fixes.py"+ _spec = importlib.util.spec_from_file_location("unsloth_import_fixes", _path)+ import_fixes = importlib.util.module_from_spec(_spec)+ _spec.loader.exec_module(import_fixes)+"""++_CLASSIFY = textwrap.dedent(+ _LOAD_MODULE+ + """+ sys.path.insert(0, sys.argv[1])+ print("LAYOUT=" + import_fixes._flash_attn_layout())+ """+)+++ "layout, expected",+ [+ ("absent", "absent"),+ ("flash_attn_2", "flash_attn_2"),+ ("flash_attn_4_only", "flash_attn_4_only"),+ # Both installed: the regular FA2 package wins the path search, so nothing to repair.+ ("both", "flash_attn_2"),+ ],+)+def test_layout_is_classified_correctly(tmp_path, layout, expected):+ root = _write_layout(tmp_path, layout)+ # A subprocess per layout: `flash_attn` cannot be un-imported cleanly between cases.+ out = subprocess.run(+ [sys.executable, "-c", _CLASSIFY, str(root), str(_REPO_ROOT)],+ capture_output = True,+ text = True,+ )+ assert out.returncode == 0, out.stdout + out.stderr+ assert f"LAYOUT={expected}" in out.stdout, out.stdout + out.stderr+++_NO_EAGER_IMPORT = textwrap.dedent(+ # Load the module BEFORE the layout is visible, so this measures the classifier only.+ _LOAD_MODULE+ + """+ sys.modules.pop("flash_attn", None)+ sys.path.insert(0, sys.argv[1])+ import importlib+ importlib.invalidate_caches()+ import_fixes._flash_attn_layout()+ import_fixes._flash_attn_4_present()+ mod = sys.modules.get("flash_attn")+ # A namespace package has no __file__ and executes nothing; a REGULAR flash-attn 2 package+ # would have run its __init__ (and loaded flash_attn_2_cuda) if we had imported it.+ print("EXECUTED=" + str(getattr(mod, "__file__", None) is not None))+ """+)++[email protected]("layout", ["absent", "flash_attn_2", "flash_attn_4_only", "both"])+def test_classification_never_imports_flash_attn(tmp_path, layout):+ """`import unsloth` must not drag in flash-attn.++ `importlib.util.find_spec("flash_attn.flash_attn_interface")` resolves the dotted name by+ IMPORTING the parent first, so classifying that way would execute `flash_attn/__init__.py`+ (and its CUDA extension) on every machine that has flash-attn 2, for users who never asked+ for it. The classifier probes the package's search locations on disk instead.+ """+ root = _write_layout(tmp_path, layout)+ out = subprocess.run(+ [sys.executable, "-c", _NO_EAGER_IMPORT, str(root), str(_REPO_ROOT)],+ capture_output = True,+ text = True,+ )+ assert out.returncode == 0, out.stdout + out.stderr+ assert "EXECUTED=False" in out.stdout, out.stdout + out.stderr+++def test_fix_is_a_noop_when_flash_attn_is_absent(monkeypatch):+ """Nothing here may change behaviour on a machine with no flash-attn."""+ monkeypatch.setattr(import_fixes, "_flash_attn_layout", lambda: "absent")+ called = []+ monkeypatch.setattr(+ import_fixes.importlib.util,+ "find_spec",+ lambda *a, **k: called.append(a) or None,+ )+ import_fixes.fix_flash_attn_4_namespace_shadow()+ assert called == [], "the fix probed for xformers on a machine with no flash-attn"+++def test_fix_is_a_noop_for_a_real_flash_attn_2(monkeypatch):+ monkeypatch.setattr(import_fixes, "_flash_attn_layout", lambda: "flash_attn_2")+ called = []+ monkeypatch.setattr(+ import_fixes.importlib.util,+ "find_spec",+ lambda *a, **k: called.append(a) or None,+ )+ import_fixes.fix_flash_attn_4_namespace_shadow()+ assert called == []+++def test_fix_is_a_noop_without_xformers(monkeypatch):+ """With no xformers there is nothing to protect: this machine was on SDPA either way, and+ the `attn_implementation=` delegation path never reaches flash-attn (transformers'+ `is_flash_attn_2_available()` looks up metadata for `flash_attn`, which the `flash-attn-4`+ distribution does not provide)."""+ monkeypatch.setattr(import_fixes, "_flash_attn_layout", lambda: "flash_attn_4_only")+ asked = []+ real_find_spec = import_fixes.importlib.util.find_spec++ def _find_spec(name, package = None):+ asked.append(name)+ return None if name == "xformers" else real_find_spec(name, package)++ monkeypatch.setattr(import_fixes.importlib.util, "find_spec", _find_spec)+ import_fixes._FA4_NAMESPACE_WARNED[0] = False+ import_fixes.fix_flash_attn_4_namespace_shadow()+ # Asked once, got nothing, stopped: no import, no warning, find_spec never left swapped.+ assert asked == ["xformers"]+ assert import_fixes.importlib.util.find_spec is _find_spec+ assert import_fixes._FA4_NAMESPACE_WARNED[0] is False+++_BROKEN_XFORMERS = textwrap.dedent(+ _LOAD_MODULE+ + """+ import importlib.machinery, importlib.util++ # An xformers whose `ops` submodule explodes on import, standing in for an install the+ # repair cannot rescue. The top-level package is stubbed too, because the repair gates on+ # `find_spec("xformers")` first: without the stub this case would silently become the+ # no-xformers early return on any machine that has no xformers (the CPU-only CI job).+ class _StubLoader:+ def create_module(self, spec):+ return None+ def exec_module(self, module):+ pass++ class _Boom:+ def find_spec(self, fullname, path=None, target=None):+ if fullname == "xformers.ops":+ raise RuntimeError("boom")+ if fullname == "xformers":+ spec = importlib.machinery.ModuleSpec("xformers", _StubLoader())+ spec.submodule_search_locations = []+ return spec+ return None+ sys.meta_path.insert(0, _Boom())+ for name in [m for m in sys.modules if m == "xformers" or m.startswith("xformers.")]:+ sys.modules.pop(name, None)++ import_fixes._flash_attn_layout = lambda: "flash_attn_4_only"+ import_fixes._flash_attn_4_present = lambda: True+ import_fixes._FA4_NAMESPACE_WARNED[0] = False++ before = importlib.util.find_spec+ import_fixes.fix_flash_attn_4_namespace_shadow()+ print("RESTORED=" + str(importlib.util.find_spec is before))+ print("WARNED=" + str(import_fixes._FA4_NAMESPACE_WARNED[0]))+ """+)+++def test_find_spec_is_restored_even_when_xformers_import_fails():+ """The repair patches `importlib.util.find_spec` for exactly one import. If that import+ raises, the patch must still come off, or every later find_spec in the process lies --+ and the unrepairable state must warn rather than degrade in silence."""+ out = subprocess.run(+ [sys.executable, "-c", _BROKEN_XFORMERS, "", str(_REPO_ROOT)],+ capture_output = True,+ text = True,+ )+ assert "RESTORED=True" in out.stdout, out.stdout + out.stderr+ assert "WARNED=True" in out.stdout, out.stdout + out.stderr+++def test_the_warning_names_the_cost_and_the_remedy(monkeypatch):+ messages = []+ monkeypatch.setattr(import_fixes.logger, "warning", lambda m: messages.append(m))+ monkeypatch.setattr(import_fixes, "_flash_attn_4_present", lambda: True)+ import_fixes._FA4_NAMESPACE_WARNED[0] = False+ import_fixes._warn_flash_attn_4_shadow_once("test")+ import_fixes._warn_flash_attn_4_shadow_once("test") # once only+ assert len(messages) == 1+ text = messages[0]+ for needed in ("flash-attn 4", "SDPA", "3.9x", "flash_attn.cute", "pip uninstall"):+ assert needed in text, f"missing {needed!r} from:\n{text}"diff --git a/tests/utils/test_varlen_int32_overflow_guard.py b/tests/utils/test_varlen_int32_overflow_guard.pynew file mode 100644index 00000000000..bbe772fa02b--- /dev/null+++ b/tests/utils/test_varlen_int32_overflow_guard.py@@ -0,0 +1,242 @@+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.+#+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Lesser General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Lesser General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.++"""A packed row holding more than a few thousand documents used to abort a training run with+`CUDA error: an illegal memory access was encountered`, which poisons the CUDA context so every+later op in the process fails too.++Root cause: flash-attn 2's varlen BACKWARD allocates+``dq_accum = zeros(total_q + 128 * n_seqs, n_heads, round_up(head_dim, 32))`` and indexes it+with int32, so the kernel faults once that element count reaches 2**31. xFormers dispatches a+BlockDiagonal* bias to the same flash-2 op, which is why the crash showed up on the xformers+path. Forward-only never allocates the buffer and never faults.++The parametrised bounds below are measurements from a B200 (bf16, one flattened row,+forward + backward), bisected on document count.+"""++import pytest+import torch++import unsloth # noqa: F401+from unsloth.utils import attention_dispatch as ad+++# (n_heads, head_dim, doc_len, last document count observed to run clean on a B200)+_MEASURED = [+ (16, 128, 1, 8129),+ (16, 96, 1, 10838),+ (16, 64, 1, 16257),+ (16, 128, 4, 7944),+]++[email protected]("n_heads, head_dim, doc_len, last_ok", _MEASURED)+def test_guard_matches_the_measured_crash_threshold(n_heads, head_dim, doc_len, last_ok):+ """The predicted limit must sit within one document of the observed one, and must never+ sit ABOVE it -- a guard that trips late is a guard that does not exist."""++ def trips(n_docs):+ return ad._varlen_backward_overflows_int32(n_docs, n_docs * doc_len, n_heads, head_dim)++ # Inside the safe region: never give up the fast kernel for nothing.+ assert not trips(last_ok // 2)+ assert not trips(last_ok - 2)+ assert trips(last_ok + 1)+ assert trips(last_ok * 2)+++def test_head_dim_is_rounded_up_to_a_multiple_of_32():+ # head_dim 96 rounds to 96, not 128, which is why that case lands at 10838 not 8129.+ assert ad._varlen_backward_dq_accum_elements(1, 0, 1, 96) == 128 * 96+ assert ad._varlen_backward_dq_accum_elements(1, 0, 1, 100) == 128 * 128+ assert ad._varlen_backward_dq_accum_elements(1, 0, 1, 64) == 128 * 64+++def test_empty_partition_never_trips():+ assert not ad._varlen_backward_overflows_int32(0, 0, 16, 128)+++def _context(+ n_docs,+ total_q,+ requires_grad,+ n_heads = 16,+ head_dim = 128,+):+ lengths = torch.zeros(n_docs, dtype = torch.int32)+ return ad.AttentionContext(+ bsz = 1,+ q_len = total_q,+ kv_seq_len = total_q,+ n_heads = n_heads,+ head_dim = head_dim,+ requires_grad = requires_grad,+ seq_info = (lengths, None, 1),+ attention_mask = None,+ causal_mask = None,+ )+++def _run(+ monkeypatch,+ backend,+ n_docs,+ requires_grad,+ guard_disabled = False,+ softcap = None,+):+ """Drive run_attention with every real kernel stubbed, and report which branch it took."""+ taken = {}++ def _fake_xformers(*args, **kwargs):+ taken["backend"] = ad.XFORMERS+ return torch.zeros((1, 4, 16, 128))++ def _fake_flash_varlen(*args, **kwargs):+ taken["backend"] = ad.FLASH_VARLEN+ return torch.zeros((4, 16, 128))++ def _fake_sdpa(*args, **kwargs):+ taken["backend"] = ad.SDPA+ return torch.zeros((1, 16, 4, 128))++ monkeypatch.setattr(ad, "xformers_attention", _fake_xformers, raising = False)+ monkeypatch.setattr(ad, "flash_attn_varlen_func", _fake_flash_varlen, raising = False)+ monkeypatch.setattr(ad, "scaled_dot_product_attention", _fake_sdpa, raising = False)+ monkeypatch.setattr(ad, "build_xformers_block_causal_mask", lambda *a, **k: object())+ monkeypatch.setattr(ad, "build_sdpa_packed_attention_mask", lambda *a, **k: None)+ monkeypatch.setattr(ad, "_VARLEN_INT32_GUARD_DISABLED", guard_disabled)+ monkeypatch.setattr(ad, "HAS_FLASH_ATTENTION", True)+ ad._VARLEN_INT32_WARNED[0] = False++ q = torch.zeros((1, 16, 4, 128), requires_grad = requires_grad)+ kwargs = {"softcap": softcap} if softcap is not None else None+ config = ad.AttentionConfig(+ backend = backend,+ n_kv_heads = 16,+ n_groups = 1,+ flash_varlen_kwargs = kwargs,+ flash_dense_kwargs = kwargs,+ )+ ad.run_attention(config = config, context = _context(n_docs, 4, requires_grad), Q = q, K = q, V = q)+ return taken.get("backend")+++# 8129 documents at 16 heads / head_dim 128 is the last count that ran; 20000 is well past it.[email protected]("backend", [ad.XFORMERS, ad.FLASH_VARLEN])+def test_oversized_partition_falls_back_to_sdpa(monkeypatch, backend):+ assert _run(monkeypatch, backend, n_docs = 20000, requires_grad = True) == ad.SDPA++[email protected]("backend", [ad.XFORMERS, ad.FLASH_VARLEN])+def test_softcapped_model_raises_instead_of_silently_dropping_the_softcap(monkeypatch, backend):+ """Gemma 2 hands `attn_logit_softcapping` to the fast kernels through+ `flash_varlen_kwargs` alone (unsloth/models/gemma2.py), and the SDPA branch has no+ softcap at all. Downgrading a softcapped model would keep the run alive on wrong logits+ and wrong gradients, which is worse than the fault the guard prevents, so it must stop."""+ with pytest.raises(RuntimeError) as excinfo:+ _run(monkeypatch, backend, n_docs = 20000, requires_grad = True, softcap = 50.0)+ message = str(excinfo.value)+ assert "softcap=50.0" in message+ assert "Pack fewer documents per row" in message++[email protected]("backend", [ad.XFORMERS, ad.FLASH_VARLEN])+def test_softcap_of_none_or_zero_still_falls_back(monkeypatch, backend):+ """Only a real softcap blocks the fallback; every other model keeps the rescue."""+ assert _run(monkeypatch, backend, n_docs = 20000, requires_grad = True, softcap = 0.0) == ad.SDPA++[email protected]("backend", [ad.XFORMERS, ad.FLASH_VARLEN])+def test_softcapped_model_under_the_bound_is_untouched(monkeypatch, backend):+ """A softcapped model that does not overflow must keep its fast kernel, not raise."""+ assert _run(monkeypatch, backend, n_docs = 64, requires_grad = True, softcap = 50.0) == backend++[email protected]("backend", [ad.XFORMERS, ad.FLASH_VARLEN])+def test_normal_partition_keeps_the_fast_backend(monkeypatch, backend):+ assert _run(monkeypatch, backend, n_docs = 64, requires_grad = True) == backend++[email protected]("backend", [ad.XFORMERS, ad.FLASH_VARLEN])+def test_forward_only_is_never_downgraded(monkeypatch, backend):+ """Inference allocates no dq_accum and never faulted (20000 documents ran clean), so the+ guard must not cost generation anything."""+ assert _run(monkeypatch, backend, n_docs = 20000, requires_grad = False) == backend++[email protected]("backend", [ad.XFORMERS, ad.FLASH_VARLEN])+def test_gradient_checkpointing_picks_the_same_backend_in_both_passes(monkeypatch, backend):+ """torch.utils.checkpoint runs its first forward under no_grad and recomputes with grad on.+ If the guard keyed only on the tensors, the two passes would take different backends and+ the backward would see activations the reported loss never came from."""++ def go(grad_enabled):+ with torch.set_grad_enabled(grad_enabled):+ taken = {}++ def _fake_xformers(*a, **k):+ taken["b"] = ad.XFORMERS+ return torch.zeros((1, 4, 16, 128))++ def _fake_flash_varlen(*a, **k):+ taken["b"] = ad.FLASH_VARLEN+ return torch.zeros((4, 16, 128))++ def _fake_sdpa(*a, **k):+ taken["b"] = ad.SDPA+ return torch.zeros((1, 16, 4, 128))++ monkeypatch.setattr(ad, "xformers_attention", _fake_xformers, raising = False)+ monkeypatch.setattr(ad, "flash_attn_varlen_func", _fake_flash_varlen, raising = False)+ monkeypatch.setattr(ad, "scaled_dot_product_attention", _fake_sdpa, raising = False)+ monkeypatch.setattr(ad, "build_xformers_block_causal_mask", lambda *a, **k: object())+ monkeypatch.setattr(ad, "build_sdpa_packed_attention_mask", lambda *a, **k: None)+ monkeypatch.setattr(ad, "_VARLEN_INT32_GUARD_DISABLED", False)+ monkeypatch.setattr(ad, "HAS_FLASH_ATTENTION", True)+ ad._VARLEN_INT32_WARNED[0] = False+ q = torch.zeros((1, 16, 4, 128))+ # The checkpointed hidden state keeps requires_grad = True in both passes.+ ctx = _context(20000, 4, requires_grad = True)+ ad.run_attention(+ config = ad.AttentionConfig(backend = backend, n_kv_heads = 16, n_groups = 1),+ context = ctx,+ Q = q,+ K = q,+ V = q,+ )+ return taken.get("b")++ assert go(False) == go(True) == ad.SDPA+++def test_guard_can_be_disabled_by_env(monkeypatch):+ assert (+ _run(monkeypatch, ad.XFORMERS, n_docs = 20000, requires_grad = True, guard_disabled = True)+ == ad.XFORMERS+ )+++def test_guard_warns_once_naming_the_cost(capsys):+ ad._VARLEN_INT32_WARNED[0] = False+ ad._warn_varlen_int32_overflow_once(ad.XFORMERS, 20000, 20000, 2**32)+ first = capsys.readouterr().out+ assert "illegal memory access" in first+ assert "SDPA" in first+ assert "20000 documents" in first+ # Once per process: it fires per layer per step.+ ad._warn_varlen_int32_overflow_once(ad.XFORMERS, 20000, 20000, 2**32)+ assert capsys.readouterr().out == ""diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.pyindex cb8fb74ce7a..13451776105 100644--- a/unsloth/_gpu_init.py+++ b/unsloth/_gpu_init.py@@ -194,6 +194,7 @@ from unsloth_zoo.device_type import (from .import_fixes import (fix_transformers5_bare_annotation_configs,fix_xformers_performance_issue,+ fix_flash_attn_4_namespace_shadow,fix_vllm_aimv2_issue,fix_vllm_lora_tokenizer_module,fix_torchao_nf4tensor_move,@@ -228,6 +229,9 @@ from .import_fixes import (# Must run first: guards PretrainedConfig before vLLM defines its config classes.fix_transformers5_bare_annotation_configs()fix_xformers_performance_issue()+# Must run AFTER fix_xformers_performance_issue (it rewrites xformers' cutlass.py on disk, so it+# must precede any xformers import) and BEFORE models/_utils.py imports xformers.ops.+fix_flash_attn_4_namespace_shadow()fix_vllm_aimv2_issue()fix_vllm_lora_tokenizer_module()# torchao 0.18.0 moved nf4tensor; torchtune (via xcodec2) still imports the@@ -272,6 +276,7 @@ patch_accelerate_recursively_apply()del fix_transformers5_bare_annotation_configsdel fix_xformers_performance_issue+del fix_flash_attn_4_namespace_shadowdel fix_vllm_aimv2_issuedel fix_vllm_lora_tokenizer_moduledel fix_torchao_nf4tensor_movediff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex 66ea987e604..47de9769b99 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -359,6 +359,145 @@ def fix_xformers_performance_issue():logger.info(f"Unsloth: Failed patching Xformers with error = {str(e)}")+# flash-attn 4 ships `flash_attn/cute/` with NO `flash_attn/__init__.py`, so `flash_attn`+# resolves as a namespace package with no `flash_attn.flash_attn_interface`. xformers gates on+# `find_spec("flash_attn")` and then imports that submodule unguarded, so `import xformers.ops`+# raises, `models/_utils.py` swallows it into `xformers = None`, HAS_XFORMERS goes False and+# every fast-path model silently drops to SDPA. Measured on a B200 at seq_len 8192 with+# Qwen3-0.6B + LoRA: 547 ms/step / 2.69 GB peak with xformers versus 2154 ms/step / 19.02 GB+# peak on SDPA -- 3.9x slower, 7x memory, no message. flash-attn 2 has no wheel for torch 2.9 /+# cp313, so flash-attn 4 is what a Blackwell user reaches for.+#+# The repair imports xformers ONCE with `flash_attn` hidden from `find_spec`, so xformers takes+# the next branch of its own elif chain exactly as it would with no flash-attn at all, and the+# working module is cached in `sys.modules`. Nothing is written to any third-party package.+_FLASH_ATTN_INTERFACE_NAME = "flash_attn_interface"+_FLASH_ATTN_INTERFACE_MODULE = "flash_attn." + _FLASH_ATTN_INTERFACE_NAME+_FA4_NAMESPACE_WARNED = [False]+++def _flash_attn_submodule_exists(name):+ """True iff `flash_attn.<name>` exists on disk, WITHOUT importing `flash_attn`.++ `importlib.util.find_spec("flash_attn.x")` looks cheap but is not: resolving a dotted name+ IMPORTS the parent package first, so on every machine with a real flash-attn 2 it would run+ `flash_attn/__init__.py` (and load `flash_attn_2_cuda`) during `import unsloth`, for users+ who never asked for flash attention. Probing the package's own search locations answers the+ same question with a stat() and no side effects.+ """+ try:+ spec = importlib.util.find_spec("flash_attn")+ if spec is None:+ return False+ locations = list(spec.submodule_search_locations or ())+ except Exception:+ return False+ for location in locations:+ base = os.path.join(location, name)+ if os.path.isdir(base):+ return True+ for suffix in importlib.machinery.all_suffixes():+ if os.path.isfile(base + suffix):+ return True+ return False+++def _flash_attn_layout():+ """Classify the installed `flash_attn` module tree.++ Returns ``"absent"`` (no `flash_attn` at all), ``"flash_attn_2"`` (a real flash-attn 2/3+ layout -- `flash_attn.flash_attn_interface` is present, which is precisely what xformers+ imports, so it works whether or not flash-attn 4 is installed ALONGSIDE it), or+ ``"flash_attn_4_only"`` (importable `flash_attn` with no FA2 entry points).++ Never imports `flash_attn`. A real flash-attn 2 whose extension fails to load is still+ classified as FA2 here and is left completely alone -- that breakage is separate and+ already reported by `models/_utils.py`.+ """+ try:+ if importlib.util.find_spec("flash_attn") is None:+ return "absent"+ except Exception:+ # A parent package that explodes on import is not something to second-guess.+ return "absent"+ if _flash_attn_submodule_exists(_FLASH_ATTN_INTERFACE_NAME):+ return "flash_attn_2"+ return "flash_attn_4_only"+++def _flash_attn_4_present():+ return _flash_attn_submodule_exists("cute")+++def _warn_flash_attn_4_shadow_once(detail):+ if _FA4_NAMESPACE_WARNED[0]:+ return+ _FA4_NAMESPACE_WARNED[0] = True+ if _flash_attn_4_present():+ head = (+ "Unsloth: flash-attn 4 is installed as the namespace package `flash_attn` (only "+ "`flash_attn.cute`), which has no `flash_attn_func` / `flash_attn_varlen_func` and "+ "no `flash_attn.flash_attn_interface`."+ )+ else:+ head = (+ "Unsloth: `flash_attn` resolves to a namespace package with no "+ "`flash_attn.flash_attn_interface` (a partial or shadowed flash-attn install)."+ )+ logger.warning(+ head + "\n"+ f"xFormers imports that module unconditionally, so it is unusable here ({detail}), and "+ "Unsloth has fallen back to PyTorch SDPA. Measured cost on a B200 at seq_len 8192 "+ "(Qwen3-0.6B + LoRA): 547 ms/step -> 2154 ms/step (3.9x slower) and 2.69 GB -> 19.02 GB "+ "peak (7x more memory).\n"+ "Unsloth cannot use flash-attn 4 either: its entry point is "+ "`from flash_attn.cute import flash_attn_func` and it returns a (out, softmax_lse) "+ "tuple rather than a tensor.\n"+ "To get the fast path back, install a flash-attn 2 that xFormers accepts (it enforces "+ '>=2.7.1: `pip install --no-build-isolation "flash-attn>=2.7.1"`) or uninstall '+ "flash-attn 4 (`pip uninstall flash-attn-4`) so xFormers can load."+ )+++def fix_flash_attn_4_namespace_shadow():+ """Keep xFormers importable when only flash-attn 4 is installed."""+ if _flash_attn_layout() != "flash_attn_4_only":+ return+ if importlib.util.find_spec("xformers") is None:+ # Nothing to protect: no xformers means SDPA regardless, and transformers'+ # `is_flash_attn_2_available()` is False here (the distribution is `flash-attn-4`, so+ # the metadata lookup for `flash_attn` misses).+ return+ if "xformers.ops.fmha.flash" in sys.modules:+ # Already imported successfully. A FAILED import leaves nothing in sys.modules, so this+ # does not mask the case we are here to fix.+ return++ real_find_spec = importlib.util.find_spec++ def _find_spec_without_flash_attn(name, package = None):+ if name == "flash_attn" or name.startswith("flash_attn."):+ return None+ return real_find_spec(name, package)++ # Process-global swap, scoped to this one import and restored in `finally`. Any other thread+ # calling find_spec("flash_attn*") in the ~1.0s window is told the package is absent, which+ # is the honest answer for the FA2 namespace xformers is asking about anyway.+ importlib.util.find_spec = _find_spec_without_flash_attn+ try:+ import xformers.ops # noqa: F401+ except Exception as error:+ _warn_flash_attn_4_shadow_once(f"xFormers still failed to import: {error}")+ return+ finally:+ importlib.util.find_spec = real_find_spec++ logger.info(+ "Unsloth: Hid the flash-attn 4 namespace package from xFormers' import so xFormers "+ "keeps working. Unsloth cannot use flash-attn 4 itself."+ )++def patch_vllm_for_notebooks():import sysdiff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.pyindex 07df8f1be21..fa229279802 100644--- a/unsloth/utils/attention_dispatch.py+++ b/unsloth/utils/attention_dispatch.py@@ -97,6 +97,98 @@ SDPA = "sdpa"XFORMERS_BLOCK_DIAG_CLS = xformers.attn_bias.BlockDiagonalCausalMask if HAS_XFORMERS else None+# ---- flash-attn 2 varlen backward int32 overflow guard -------------------------------------+# The varlen BACKWARD kernel (used by flash-attn 2 directly and by the flash-2 op xFormers+# dispatches a BlockDiagonal* bias to) allocates+#+# dq_accum = zeros(total_q + 128 * n_seqs, n_heads, round_up(head_dim, 32), dtype = fp32)+#+# and indexes it with int32, so once that element count reaches 2**31 the kernel faults with+# "CUDA error: an illegal memory access was encountered". That poisons the CUDA context, so the+# run dies hours in, far from the cause.+#+# Measured on a B200 (bf16, one flattened row, forward + backward) by bisecting the document+# count in a packed row: the last working count and the count at which+# (total_q + 128 * n_seqs) * n_heads * round_up(head_dim, 32) crosses 2**31 agree to within one+# document across every shape tried:+#+# heads head_dim doc_len predicted last OK+# 16 128 1 8128 8129+# 16 96 1 10837 10838+# 16 64 1 16257 16257+# 8 128 1 16257 >= 16257, fails by 16400+# 16 128 2 8065 8060 OK, 8200 fails+# 16 128 4 7944 7944+# 4 128 1 32518 no failure up to 20000 (below the bound)+#+# Forward-only never allocates dq_accum and never faults (20000 documents ran clean), so the+# guard requires a backward to be possible. Plain SDPA is unaffected.+_INT32_ELEMENTS = 2**31+_VARLEN_INT32_GUARD_DISABLED = os.environ.get(+ "UNSLOTH_DISABLE_VARLEN_INT32_GUARD", "0"+).lower() in (+ "1",+ "true",+ "yes",+ "on",+)+_VARLEN_INT32_WARNED = [False]+++def _varlen_backward_dq_accum_elements(+ n_seqs: int, total_q: int, n_heads: int, head_dim: int+) -> int:+ """Element count of flash-attn 2's varlen-backward ``dq_accum`` for these shapes."""+ head_dim_rounded = ((head_dim + 31) // 32) * 32+ return (total_q + 128 * n_seqs) * n_heads * head_dim_rounded+++def _varlen_backward_overflows_int32(+ n_seqs: int, total_q: int, n_heads: int, head_dim: int+) -> bool:+ if n_seqs <= 0:+ return False+ return _varlen_backward_dq_accum_elements(n_seqs, total_q, n_heads, head_dim) >= _INT32_ELEMENTS+++def _configured_softcap(config) -> Optional[float]:+ """The attention logit softcap this layer asked the fast kernels for, if any.++ Only flash and the xformers ops take a `softcap`; the SDPA branch below has no way to+ apply one. Gemma 2 passes it exclusively through these kwargs+ (`unsloth/models/gemma2.py`), so a backend swap that ignores them would train on+ uncapped logits.+ """+ for kwargs in (+ config.flash_varlen_kwargs,+ config.flash_dense_kwargs,+ config.xformers_kwargs,+ ):+ if not kwargs:+ continue+ softcap = kwargs.get("softcap")+ if softcap:+ return softcap+ return None+++def _warn_varlen_int32_overflow_once(backend: str, n_seqs: int, total_q: int, elements: int):+ if _VARLEN_INT32_WARNED[0]:+ return+ _VARLEN_INT32_WARNED[0] = True+ print(+ f"Unsloth: A packed row holds {n_seqs} documents over {total_q} tokens. The "+ f"{backend} backward kernel would index a {elements:,}-element buffer with int32 "+ f"(limit {_INT32_ELEMENTS:,}), which faults with 'CUDA error: an illegal memory "+ "access was encountered' and poisons the CUDA context for the rest of the process.\n"+ "Unsloth has fallen back to SDPA for these batches, which is CORRECT but far slower "+ "and far heavier: SDPA's packed path materialises a dense mask and can use ~10x the "+ "memory, so it may OOM instead.\n"+ "To keep the fast kernel, pack fewer documents per row -- lower the packing length, or "+ "filter out very short documents so one row cannot collect thousands of them."+ )++@dataclassclass AttentionConfig:"""@@ -249,6 +341,51 @@ def run_attention():backend = SDPA+ # Both varlen-capable backends land in the same flash-attn 2 backward kernel, so guard both+ # before the int32 overflow aborts the process. Integer arithmetic only, no device sync.+ if backend in (FLASH_VARLEN, XFORMERS) and not _VARLEN_INT32_GUARD_DISABLED:+ # Both terms are needed. Q/K/V: a frozen hidden state feeding trainable LoRA q/k/v+ # still yields a Q that requires grad, which context.requires_grad alone would miss.+ # context.requires_grad: gradient checkpointing runs its FIRST forward under no_grad+ # and recomputes with grad on, so keying only on the tensors would pick a different+ # backend per pass and the backward would see activations the loss never came from.+ # The hidden state keeps requires_grad = True across both passes; inference has it False.+ will_backward = context.requires_grad or (+ torch.is_grad_enabled() and (Q.requires_grad or K.requires_grad or V.requires_grad)+ )+ if will_backward:+ seq_info = context.seq_info+ # seq_info[0] is the per-document length tensor; .numel() needs no D2H copy.+ n_seqs = seq_info[0].numel() if seq_info is not None else context.bsz+ total_q = context.bsz * context.q_len+ if _varlen_backward_overflows_int32(n_seqs, total_q, context.n_heads, context.head_dim):+ # SDPA cannot apply logit softcapping, so rerouting a softcapped model (Gemma 2)+ # would keep it training on wrong logits and gradients -- worse than the fault+ # this guard avoids. Stop and name the ways out instead.+ softcap = _configured_softcap(config)+ if softcap:+ raise RuntimeError(+ f"Unsloth: A packed row holds {n_seqs} documents over {total_q} "+ f"tokens, so the {backend} backward kernel would index a "+ f"{_varlen_backward_dq_accum_elements(n_seqs, total_q, context.n_heads, context.head_dim):,}"+ f"-element buffer with int32 (limit {_INT32_ELEMENTS:,}) and fault "+ "with 'CUDA error: an illegal memory access was encountered'.\n"+ f"This model softcaps attention logits (softcap={softcap}), and the "+ "SDPA fallback cannot reproduce that, so falling back would silently "+ "train on wrong logits.\n"+ "Pack fewer documents per row: lower the packing length, or filter "+ "out very short documents so one row cannot collect thousands of them."+ )+ _warn_varlen_int32_overflow_once(+ backend,+ n_seqs,+ total_q,+ _varlen_backward_dq_accum_elements(+ n_seqs, total_q, context.n_heads, context.head_dim+ ),+ )+ backend = SDPA+flash_dense_kwargs = config.flash_dense_kwargs or {}flash_varlen_kwargs = config.flash_varlen_kwargs or {}sdpa_kwargs = config.sdpa_kwargs or {}