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
Probe xformers support on sm_120 instead of disabling it by version (#6828)
oobaboogaed427027305c
diff --git a/tests/utils/test_attention_dispatch_dora_dtype.py b/tests/utils/test_attention_dispatch_dora_dtype.pyindex a6586dea8d0..f0496ee6a89 100644--- a/tests/utils/test_attention_dispatch_dora_dtype.py+++ b/tests/utils/test_attention_dispatch_dora_dtype.py@@ -71,3 +71,59 @@ def test_varlen_flash_downcasts_fp32_qkv(monkeypatch):def test_bf16_qkv_left_untouched(monkeypatch):# Standard LoRA path (already bf16) must not be altered.assert _run(monkeypatch, torch.bfloat16, ad.FLASH_DENSE) == torch.bfloat16+++def _run_xformers(monkeypatch, qkv_dtype, fp32_unsupported):+ # Same #1013 fp32 downcast, but for the xformers backend. On sm_100+ (B200, sm_120)+ # xformers' fp32-capable cutlass op is capability-rejected and only its flash-2 op+ # runs (fp16/bf16 only), so fp32 must be downcast there too or the op raises.+ captured = {}++ def fake_xformers_attention(+ Q,+ K,+ V,+ attn_bias = None,+ **kwargs,+ ):+ captured["dtype"] = Q.dtype+ # Mirror the flash-2 op's real dtype constraint so an unfixed dispatch fails loudly.+ if fp32_unsupported and Q.dtype not in (torch.float16, torch.bfloat16):+ raise RuntimeError("no operator found for memory_efficient_attention with fp32")+ return torch.zeros_like(Q)++ monkeypatch.setattr(ad, "_XFORMERS_FP32_UNSUPPORTED", fp32_unsupported, raising = False)+ monkeypatch.setattr(ad, "xformers_attention", fake_xformers_attention, raising = False)+ monkeypatch.setattr(+ ad, "build_xformers_block_causal_mask", lambda *a, **k: object(), raising = False+ )++ bsz, n_heads, q_len, head_dim = 1, 2, 4, 8+ Q = torch.randn(bsz, n_heads, q_len, head_dim, dtype = qkv_dtype)+ K = torch.randn(bsz, n_heads, q_len, head_dim, dtype = qkv_dtype)+ V = torch.randn(bsz, n_heads, q_len, head_dim, dtype = qkv_dtype)++ config = ad.AttentionConfig(backend = ad.XFORMERS, n_kv_heads = n_heads, n_groups = 1)+ context = ad.AttentionContext(+ bsz = bsz,+ q_len = q_len,+ kv_seq_len = q_len,+ n_heads = n_heads,+ head_dim = head_dim,+ requires_grad = False,+ seq_info = None,+ attention_mask = None,+ causal_mask = None,+ )+ ad.run_attention(config = config, context = context, Q = Q, K = K, V = V)+ return captured["dtype"]+++def test_xformers_downcasts_fp32_qkv_on_sm100_plus(monkeypatch):+ # sm_100+ (fp32 op gone): fp32 DoRA output must be downcast, else the flash-2 op raises.+ assert _run_xformers(monkeypatch, torch.float32, True) in (torch.bfloat16, torch.float16)+++def test_xformers_leaves_fp32_qkv_below_sm100(monkeypatch):+ # Below sm_100 the cutlass op handles fp32 natively, so it must be passed through as-is.+ assert _run_xformers(monkeypatch, torch.float32, False) == torch.float32diff --git a/tests/utils/test_xformers_capability_gate.py b/tests/utils/test_xformers_capability_gate.pynew file mode 100644index 00000000000..7514c623e37--- /dev/null+++ b/tests/utils/test_xformers_capability_gate.py@@ -0,0 +1,102 @@+"""Regression test for unslothai/unsloth#4631: xformers must not be blanket-disabled+on sm_120 GPUs where its kernel actually runs (a ~57% attention-memory saving over the+SDPA packed-mask fallback). The gate now probes the real op instead of guessing by the+compute-capability major version."""++import pytest+import torch+import unsloth # noqa: F401++from unsloth.utils import attention_dispatch as ad+++ "capability, probe_result, expect_disabled",+ [+ ((8, 9), None, False), # Ada: below sm_120, never probed, always kept+ ((9, 0), None, False), # Hopper: below sm_120, kept+ ((10, 0), None, False), # Blackwell B200 (sm_100): below sm_120, kept+ ((12, 0), True, False), # sm_120 where the kernel runs: keep xformers+ ((12, 0), False, True), # sm_120 where the kernel can't run: fall back to SDPA+ ],+)+def test_capability_gate(capability, probe_result, expect_disabled):+ calls = {"n": 0}++ def probe():+ calls["n"] += 1+ return probe_result++ assert ad._xformers_disabled_for_capability(capability, probe = probe) is expect_disabled+ # Below sm_120 the probe must not run at all (no import-time kernel launch there).+ assert calls["n"] == (0 if capability[0] < 12 else 1)+++ not (torch.cuda.is_available() and ad.HAS_XFORMERS),+ reason = "needs a CUDA GPU with a working xformers build",+)+ torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 12,+ reason = "on real sm_120+ the probe legitimately returns False when the build ships no "+ "sm_120 kernel, so asserting True there would be a false failure",+)+def test_probe_shapes_are_valid_on_working_gpu():+ # Guards against a malformed probe that raises on every GPU and would silently+ # disable xformers on Blackwell even where it works. On a pre-sm_120 GPU with a+ # functional xformers the real probe must succeed; sm_120+ is skipped above because+ # there a False is a correct answer, not a malformed probe.+ assert ad._xformers_runs_on_device() is True+++ "supports_bf16, expected_dtype",+ [(True, torch.bfloat16), (False, torch.float16)],+)+def test_probe_dtype_follows_bf16_support(monkeypatch, supports_bf16, expected_dtype):+ # Pre-Ampere GPUs (sm < 80: Turing/Volta, e.g. T4/V100) run xformers fine in+ # float16 but have no bfloat16 attention kernel, so a hardcoded bf16 probe would+ # raise there, get swallowed to False, and misreport a working xformers as broken.+ # The probe must pick its dtype from SUPPORTS_BFLOAT16 (no Turing GPU needed here).+ captured = {}++ def fake_zeros(+ *args,+ dtype = None,+ **kwargs,+ ):+ captured["dtype"] = dtype+ raise RuntimeError("stop after capturing the probe dtype")++ monkeypatch.setattr(ad, "SUPPORTS_BFLOAT16", supports_bf16)+ monkeypatch.setattr(ad.torch, "zeros", fake_zeros)+ ad._xformers_runs_on_device() # RuntimeError is swallowed; only the dtype matters+ assert captured["dtype"] is expected_dtype+++def test_probe_syncs_and_fails_on_deferred_async_error(monkeypatch):+ # A CUDA kernel launch is async: xformers_attention can return before the GPU+ # reports a failure. The probe must synchronize so a deferred launch/runtime error+ # is caught and disables xformers here, instead of surfacing later on an unrelated+ # CUDA call (unslothai/unsloth#6828 review). No GPU needed: everything is stubbed.+ _bias = type(+ "B",+ (),+ {+ "BlockDiagonalCausalMask": type(+ "M", (), {"from_seqlens": staticmethod(lambda seqlens: None)}+ )+ },+ )+ monkeypatch.setattr(ad, "SUPPORTS_BFLOAT16", True)+ monkeypatch.setattr(ad.torch, "zeros", lambda *a, **k: object())+ monkeypatch.setattr(ad, "xformers", type("X", (), {"attn_bias": _bias}))+ monkeypatch.setattr(ad, "xformers_attention", lambda *a, **k: None) # "succeeds"++ def deferred_cuda_error():+ raise RuntimeError("CUDA error: an illegal memory access was encountered")++ monkeypatch.setattr(ad.torch.cuda, "synchronize", deferred_cuda_error)+ # Without the synchronize the stubbed op returns cleanly and the probe wrongly+ # reports True; the sync surfaces the deferred error so the probe returns False.+ assert ad._xformers_runs_on_device() is Falsediff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.pyindex 68fb33dad9b..eda6103d5b3 100644--- a/unsloth/utils/attention_dispatch.py+++ b/unsloth/utils/attention_dispatch.py@@ -35,12 +35,44 @@ if HAS_FLASH_ATTENTION:from flash_attn import flash_attn_func, flash_attn_varlen_funcHAS_XFORMERS = xformers is not None-# xformers kernels (FA3, FA2, cutlass) only support compute capability <= 9.0.-# Disable xformers on newer GPUs (e.g. RTX 5070 Ti / sm_120) and fall back to SDPA.-if HAS_XFORMERS and torch.cuda.is_available():- _cc = torch.cuda.get_device_capability()- if _cc[0] >= 12:++def _xformers_runs_on_device() -> bool:+ """One tiny attention forward; True iff the xformers kernel actually runs here."""+ try:+ # Pre-Ampere GPUs (sm < 80: Turing/Volta) have no bfloat16 attention kernel+ # but run xformers fine in float16, so pick the dtype the device supports.+ dtype = torch.bfloat16 if SUPPORTS_BFLOAT16 else torch.float16+ q = torch.zeros((1, 8, 1, 64), device = "cuda", dtype = dtype)+ attn_bias = xformers.attn_bias.BlockDiagonalCausalMask.from_seqlens([8])+ xformers_attention(q, q, q, attn_bias = attn_bias)+ # Launches are async; synchronize so a deferred kernel failure fails the probe here.+ torch.cuda.synchronize()+ return True+ except Exception:+ return False+++def _xformers_disabled_for_capability(capability, probe = _xformers_runs_on_device) -> bool:+ # At sm_120 (RTX 50-series) xformers' cutlass op is capability-rejected (caps at+ # sm_90) and its flash-2 op runs only if the build ships an sm_120 kernel, so run+ # one real forward to decide. Below sm_120 xformers always works; skip the probe.+ if capability[0] < 12:+ return False+ return not probe()+++# FlashAttention always wins in select_attention_backend and nothing downgrades+# flash -> xformers, so when it's installed xformers is never selected: skip the probe.+if HAS_XFORMERS and not HAS_FLASH_ATTENTION and torch.cuda.is_available():+ if _xformers_disabled_for_capability(torch.cuda.get_device_capability()):HAS_XFORMERS = False++# On sm_100+ (B200, sm_120) xformers' fp32-capable cutlass op is capability-rejected and+# only its fp16/bf16 flash-2 op runs, so fp32 Q/K/V (DoRA, #1013) must be downcast there;+# below sm_100 cutlass handles fp32 natively. Read once from device 0, like the probe gate.+_XFORMERS_FP32_UNSUPPORTED = (+ torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 10+)SDPA_HAS_GQA = "enable_gqa" in (scaled_dot_product_attention.__doc__ or "")# PrefixGrouper kernel, resolved once when the env gate is on so PG-off users never load@@ -201,9 +233,13 @@ def run_attention(requires_grad = context.requires_gradsliding_window = context.sliding_window- # DoRA promotes q/k/v_proj outputs to fp32, which FlashAttention rejects, so- # downcast any fp32 Q/K/V to a flash-supported dtype (#1013).- if backend in (FLASH_DENSE, FLASH_VARLEN) and torch.float32 in (+ # DoRA promotes q/k/v_proj outputs to fp32, which FlashAttention rejects (and so does+ # the xformers flash-2 op on sm_100+, see _XFORMERS_FP32_UNSUPPORTED), so downcast any+ # fp32 Q/K/V to a supported dtype (#1013).+ if (+ backend in (FLASH_DENSE, FLASH_VARLEN)+ or (backend == XFORMERS and _XFORMERS_FP32_UNSUPPORTED)+ ) and torch.float32 in (Q.dtype,K.dtype,V.dtype,@@ -211,14 +247,16 @@ def run_attention(# Prefer the autocast dtype, else a non-fp32 input's dtype, then clamp.if torch.is_autocast_enabled():try:- flash_dtype = torch.get_autocast_dtype("cuda")+ downcast_dtype = torch.get_autocast_dtype("cuda")except (AttributeError, TypeError):- flash_dtype = torch.get_autocast_gpu_dtype()+ downcast_dtype = torch.get_autocast_gpu_dtype()else:- flash_dtype = next((d for d in (Q.dtype, K.dtype, V.dtype) if d != torch.float32), None)- if flash_dtype not in (torch.float16, torch.bfloat16):- flash_dtype = torch.bfloat16 if SUPPORTS_BFLOAT16 else torch.float16- Q, K, V = Q.to(flash_dtype), K.to(flash_dtype), V.to(flash_dtype)+ downcast_dtype = next(+ (d for d in (Q.dtype, K.dtype, V.dtype) if d != torch.float32), None+ )+ if downcast_dtype not in (torch.float16, torch.bfloat16):+ downcast_dtype = torch.bfloat16 if SUPPORTS_BFLOAT16 else torch.float16+ Q, K, V = Q.to(downcast_dtype), K.to(downcast_dtype), V.to(downcast_dtype)if backend == FLASH_VARLEN:Q_f = Q.transpose(1, 2).reshape(bsz * q_len, n_heads, head_dim)