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
Flex attention: fitting tiles for Gemma 3 on sm86 / sm89 (L4, A10, RTX 4090) instead of eager (#15271)
Daniel Han47aaa263061f
diff --git a/tests/test_flex_preferred_shared_memory.py b/tests/test_flex_preferred_shared_memory.pyindex 207aaf91ae2..8f6b64d658b 100644--- a/tests/test_flex_preferred_shared_memory.py+++ b/tests/test_flex_preferred_shared_memory.py@@ -21,6 +21,8 @@ class SupportsFlex:L4 = 101376A100 = 166912B200 = 232448+# capability per shared memory class, so the sm8x small-tile gate sees a real-looking card+CAPABILITY = {L4: (8, 9), A100: (8, 0), B200: (10, 0)}def _gemma3(head_dim = 256, model_type = "gemma3_text"):@@ -45,6 +47,11 @@ def cards(monkeypatch):"get_device_properties",lambda index = 0: SimpleNamespace(shared_memory_per_block_optin = shared_memory[index]),)+ monkeypatch.setattr(+ _utils.torch.cuda,+ "get_device_capability",+ lambda index = 0: CAPABILITY[shared_memory[index]],+ )return install@@ -53,7 +60,11 @@ def _resolve(config):return _utils.resolve_attention_implementation(SupportsFlex, config, supports_sdpa = False)-def test_gemma3_leaves_flex_where_the_template_does_not_fit(cards):[email protected]("torch_version,env", [("2.9.1", ""), ("2.14.0", "0")])+def test_gemma3_leaves_flex_where_the_template_does_not_fit(cards, monkeypatch, torch_version, env):+ # Without the sm8x small tiles (torch < 2.10, or switched off) the default template must not run.+ monkeypatch.setattr(_utils.torch, "__version__", torch_version)+ monkeypatch.setenv("UNSLOTH_FLEX_SMALL_SMEM_TILES", env)cards(L4)config = _gemma3()assert _resolve(config) == "eager"@@ -66,6 +77,13 @@ def test_gemma3_keeps_flex_where_the_template_fits(cards, shared_memory):assert _resolve(_gemma3()) == "flex_attention"+def test_l4_keeps_flex_with_small_tiles(cards, monkeypatch):+ monkeypatch.setattr(_utils.torch, "__version__", "2.10.0+cu130")+ monkeypatch.delenv("UNSLOTH_FLEX_SMALL_SMEM_TILES", raising = False)+ cards(L4)+ assert _resolve(_gemma3()) == "flex_attention"++def test_a_mixed_box_follows_its_smallest_card(cards):cards(A100, L4)assert _resolve(_gemma3()) == "eager"diff --git a/tests/test_flex_small_smem_tiles.py b/tests/test_flex_small_smem_tiles.pynew file mode 100644index 00000000000..0cd4cd1ee89--- /dev/null+++ b/tests/test_flex_small_smem_tiles.py@@ -0,0 +1,226 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""sm86 / sm89 flex at 128 < head_dim <= 256: fwd_* / bwd_* tiles that fit 101376 bytes."""++from types import SimpleNamespace++import pytest++import unsloth # noqa: F401 (must precede transformers)+import unsloth.models._utils as u++T4 = ((7, 5), 65536)+A10 = ((8, 6), 101376)+RTX3090 = ((8, 6), 101376)+L4 = ((8, 9), 101376)+L40S = ((8, 9), 101376)+ORIN = ((8, 7), 166912)+A100 = ((8, 0), 166912)+H100 = ((9, 0), 232448)+B200 = ((10, 0), 232448)+RTX_PRO_6000 = ((12, 0), 101376)+++def devices(monkeypatch):+ monkeypatch.delenv(u._FLEX_SMALL_SMEM_ENV_VAR, raising = False)+ monkeypatch.setattr(u.torch.version, "hip", None, raising = False)+ monkeypatch.setattr(u.torch, "__version__", "2.10.0+cu130")++ def install(*cards):+ monkeypatch.setattr(u.torch.cuda, "is_available", lambda: bool(cards))+ monkeypatch.setattr(u.torch.cuda, "device_count", lambda: len(cards))+ monkeypatch.setattr(u.torch.cuda, "get_device_capability", lambda index = 0: cards[index][0])+ monkeypatch.setattr(+ u.torch.cuda,+ "get_device_properties",+ lambda index = 0: SimpleNamespace(shared_memory_per_block_optin = cards[index][1]),+ )++ return install+++ "cards,expected",+ [+ ((A10,), True),+ ((RTX3090,), True),+ ((L4,), True),+ ((L40S, L4), True),+ ((T4,), False), # pre-Ampere never reaches flex (_FLEX_ATTENTION_MIN_CAPABILITY)+ ((A100,), False), # the default template fits: unchanged+ ((ORIN,), False),+ ((H100,), False),+ ((B200,), False),+ ((RTX_PRO_6000,), False), # sm120 has its own Inductor table, not measured here+ ((L4, A100), False), # every visible device must be in the class+ ((), False),+ ],+)+def test_device_gate(devices, cards, expected):+ devices(*cards)+ assert u._flex_small_smem_device_ok() is expected+++ "version,expected", [("2.9.1", False), ("2.10.0", True), ("2.14.1+cu130", True)]+)+def test_needs_torch_with_prefixed_keys(devices, monkeypatch, version, expected):+ devices(L4)+ monkeypatch.setattr(u.torch, "__version__", version)+ assert u._flex_small_smem_device_ok() is expected+++def test_kill_switch_and_rocm(devices, monkeypatch):+ devices(L4)+ monkeypatch.setenv(u._FLEX_SMALL_SMEM_ENV_VAR, "0")+ assert u._flex_small_smem_device_ok() is False+ monkeypatch.delenv(u._FLEX_SMALL_SMEM_ENV_VAR)+ monkeypatch.setattr(u.torch.version, "hip", "7.2.0", raising = False)+ assert u._flex_small_smem_device_ok() is False+++def test_unreadable_device_is_off(devices, monkeypatch):+ devices(L4)++ def boom(index = 0):+ raise RuntimeError("probe")++ monkeypatch.setattr(u.torch.cuda, "get_device_properties", boom)+ assert u._flex_small_smem_device_ok() is False++[email protected]("head_dim", [129, 192, 256])+def test_options_in_range(head_dim):+ opts = u._flex_small_smem_kernel_options(head_dim, True)+ assert opts == u._FLEX_SMALL_SMEM_KERNEL_OPTIONS+ assert all(k.startswith(("fwd_", "bwd_")) for k in opts)+ opts["fwd_num_stages"] = 99 # a fresh dict per call+ assert u._FLEX_SMALL_SMEM_KERNEL_OPTIONS["fwd_num_stages"] == 1++[email protected]("head_dim", [64, 128, 257, 512, None, "256"])+def test_options_out_of_range(head_dim):+ assert u._flex_small_smem_kernel_options(head_dim, True) is None+++def test_options_need_the_device():+ assert u._flex_small_smem_kernel_options(256, False) is None+++def test_tiles_divide_the_default_sparse_block():+ o = u._FLEX_SMALL_SMEM_KERNEL_OPTIONS+ for k in (+ "fwd_BLOCK_M",+ "fwd_BLOCK_N",+ "bwd_BLOCK_M1",+ "bwd_BLOCK_N1",+ "bwd_BLOCK_M2",+ "bwd_BLOCK_N2",+ ):+ assert 128 % o[k] == 0+ assert o["bwd_BLOCK_N1"] % o["bwd_BLOCK_M1"] == 0+ assert o["bwd_BLOCK_M2"] % o["bwd_BLOCK_N2"] == 0+++class _Causal:+ is_causal = True+++def _wrapped(+ monkeypatch,+ small_ok = True,+ tuned_ok = False,+):+ seen = {}++ def fake_flex(module, query, key, value, *args, **kwargs):+ seen.clear()+ seen.update(kwargs.get("kernel_options") or {})+ return query++ monkeypatch.setattr(u, "_flex_small_smem_device_ok", lambda: small_ok)+ monkeypatch.setattr(u, "_flex_tuned_bwd_device_ok", lambda: tuned_ok)+ return u._wrap_flex_attention_forward(fake_flex), seen+++def _qkv(+ q_len,+ head_dim = 256,+ grad = True,+):+ import torch+ return [torch.randn(1, 2, q_len, head_dim, requires_grad = grad) for _ in range(3)]+++def test_wrapper_passes_tiles_for_training_calls(monkeypatch):+ wrapped, seen = _wrapped(monkeypatch)+ monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: True)+ wrapped(_Causal(), *_qkv(16), object()) # a non-None mask stays on flex+ for k, v in u._FLEX_SMALL_SMEM_KERNEL_OPTIONS.items():+ assert seen[k] == v+ assert seen["FORCE_USE_FLEX_ATTENTION"] is True+++def test_wrapper_leaves_caller_tiles_alone(monkeypatch):+ # A partial caller set merged with ours could break the templates' tile divisibility checks.+ wrapped, seen = _wrapped(monkeypatch)+ monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: True)+ wrapped(_Causal(), *_qkv(256), object(), kernel_options = {"fwd_num_stages": 3, "BLOCK_M": 16})+ assert seen["fwd_num_stages"] == 3 and seen["BLOCK_M"] == 16+ assert "fwd_BLOCK_N" not in seen and "bwd_num_stages" not in seen+ wrapped(_Causal(), *_qkv(256), object(), kernel_options = {"BACKEND": "TRITON"})+ assert seen["BACKEND"] == "TRITON" and seen["fwd_BLOCK_N"] == 64+++class _Mask:+ def __init__(self, block):+ self.BLOCK_SIZE = (block, block)+++def test_wrapper_skips_sparse_blocks_our_tiles_do_not_divide(monkeypatch):+ wrapped, seen = _wrapped(monkeypatch)+ monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: True)+ wrapped(_Causal(), *_qkv(256), _Mask(16))+ assert "fwd_BLOCK_M" not in seen+ wrapped(_Causal(), *_qkv(256), _Mask(64))+ assert seen["fwd_BLOCK_M"] == 64+++def test_wrapper_no_grad_prefill_gets_tiles_decode_does_not(monkeypatch):+ wrapped, seen = _wrapped(monkeypatch)+ monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: False)+ wrapped(_Causal(), *_qkv(128, grad = False), object())+ assert seen.get("fwd_BLOCK_M") == 64+ wrapped(_Causal(), *_qkv(8, grad = False), object())+ assert seen == {} # flex_decoding keeps its own config+++def test_wrapper_untouched_off_class_and_outside_range(monkeypatch):+ wrapped, seen = _wrapped(monkeypatch, small_ok = False)+ monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: True)+ wrapped(_Causal(), *_qkv(256), object())+ assert "fwd_BLOCK_M" not in seen+ wrapped, seen = _wrapped(monkeypatch, small_ok = True)+ wrapped(_Causal(), *_qkv(256, head_dim = 128), object())+ assert "fwd_BLOCK_M" not in seen+++def test_a100_keeps_its_tuned_backward(monkeypatch):+ wrapped, seen = _wrapped(monkeypatch, small_ok = False, tuned_ok = True)+ monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: True)+ wrapped(_Causal(), *_qkv(256), object())+ for k, v in u._FLEX_TUNED_BWD_KERNEL_OPTIONS.items():+ assert seen[k] == v+ assert "fwd_BLOCK_M" not in seen+++def test_small_card_with_tuned_backward_forced_keeps_fitting_tiles(monkeypatch):+ # UNSLOTH_FLEX_TUNED_BACKWARD=1 on an L4: backward-only keys would leave the default forward+ # tile, which does not fit, so the full small-memory set wins.+ wrapped, seen = _wrapped(monkeypatch, small_ok = True, tuned_ok = True)+ monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: True)+ wrapped(_Causal(), *_qkv(256), object())+ for k, v in u._FLEX_SMALL_SMEM_KERNEL_OPTIONS.items():+ assert seen[k] == vdiff --git a/tests/test_flex_small_smem_tiles_gpu.py b/tests/test_flex_small_smem_tiles_gpu.pynew file mode 100644index 00000000000..452daf1e35e--- /dev/null+++ b/tests/test_flex_small_smem_tiles_gpu.py@@ -0,0 +1,100 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""GPU: the sm86 / sm89 tiles reach Inductor through the registered flex_attention.++The gate is forced on (any CUDA card), then the compiled flex forward kernel's shared memory+must fit 101376 bytes, against the default tile that does not; output and grads match SDPA.+"""++import pytest+import torch++import unsloth # noqa: F401 (must precede transformers)+import unsloth.models._utils as u++pytestmark = pytest.mark.skipif(+ not torch.cuda.is_available()+ or getattr(torch.version, "hip", None)+ or torch.cuda.get_device_capability(0) < (8, 0)+ or u.Version(torch.__version__.split("+")[0]) < u.Version("2.10"),+ reason = "needs an Ampere+ CUDA card and torch >= 2.10",+)++L4_SHARED_MEMORY = 101376+++def _flex_kernels_shared(monkeypatch, small_ok):+ import triton.compiler.compiler as tc+ from transformers.integrations.flex_attention import flex_attention_forward+ from torch.nn.attention.flex_attention import create_block_mask++ shared = []+ orig = tc.CompiledKernel.__init__++ def rec(self, *a, **k):+ orig(self, *a, **k)+ if "flex_attention" in self.name:+ shared.append((self.name, int(self.metadata.shared)))++ monkeypatch.setattr(tc.CompiledKernel, "__init__", rec)+ monkeypatch.setattr(torch._inductor.config, "compile_threads", 1)+ monkeypatch.setattr(torch._inductor.config, "force_disable_caches", True)+ monkeypatch.setattr(u, "_flex_small_smem_device_ok", lambda: small_ok)+ monkeypatch.setattr(u, "_flex_tuned_bwd_device_ok", lambda: False)+ torch._dynamo.reset()+ # unsloth may already have wrapped the module function at import: wrap the original+ base = getattr(flex_attention_forward, "_unsloth_original_forward", flex_attention_forward)+ wrapped = u._wrap_flex_attention_forward(base)++ torch.manual_seed(0)+ B, H, KV, L, D = 1, 8, 4, 512, 256+ q = torch.randn(B, H, L, D, device = "cuda", dtype = torch.bfloat16, requires_grad = True)+ k = torch.randn(B, KV, L, D, device = "cuda", dtype = torch.bfloat16, requires_grad = True)+ v = torch.randn(B, KV, L, D, device = "cuda", dtype = torch.bfloat16, requires_grad = True)+ mask = create_block_mask(lambda b, h, qi, ki: qi >= ki, None, None, L, L, device = "cuda")++ class Module(torch.nn.Module):+ is_causal = True+ training = True+ num_key_value_groups = H // KV++ out, _ = wrapped(Module(), q, k, v, mask, scaling = D**-0.5)+ out.float().square().sum().backward()+ grads = [t.grad.float().clone() for t in (q, k, v)]+ torch._dynamo.reset()+ return list(shared), out.detach().float(), grads, (q, k, v)+++def _sdpa_reference(q, k, v):+ qr, kr, vr = (t.detach().clone().requires_grad_(True) for t in (q, k, v))+ rep = qr.shape[1] // kr.shape[1]+ o = torch.nn.functional.scaled_dot_product_attention(+ qr.float(),+ kr.float().repeat_interleave(rep, 1),+ vr.float().repeat_interleave(rep, 1),+ is_causal = True,+ scale = q.shape[-1] ** -0.5,+ )+ o.transpose(1, 2).square().sum().backward()+ return o.transpose(1, 2).detach(), [t.grad.float() for t in (qr, kr, vr)]+++def test_small_tiles_reach_the_compiled_flex_kernel(monkeypatch):+ on, out_on, grads_on, qkv = _flex_kernels_shared(monkeypatch, True)+ fwd_on = [s for n, s in on if "backward" not in n]+ bwd_on = [s for n, s in on if "backward" in n]+ assert fwd_on, on+ # engagement: with the gate on, every flex forward kernel fits an L4 / A10+ assert max(fwd_on) <= L4_SHARED_MEMORY, on+ assert bwd_on and max(bwd_on) <= L4_SHARED_MEMORY, on+ smem = torch.cuda.get_device_properties(0).shared_memory_per_block_optin+ if smem >= u._FLEX_TEMPLATE_HEAD_DIM_256_SHARED_MEMORY:+ # control (only where the default tiles fit): the kill-switch path compiles another tile+ off, _, _, _ = _flex_kernels_shared(monkeypatch, False)+ fwd_off = [s for n, s in off if "backward" not in n]+ assert fwd_off and sorted(fwd_on) != sorted(fwd_off), (on, off)+ ref_out, ref_grads = _sdpa_reference(*qkv)+ assert torch.nn.functional.cosine_similarity(out_on.flatten(), ref_out.flatten(), dim = 0) > 0.999+ for g, r in zip(grads_on, ref_grads):+ assert torch.nn.functional.cosine_similarity(g.flatten(), r.flatten(), dim = 0) > 0.999diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 2afbae2fa87..ad8e6191022 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -801,24 +801,88 @@ def _flex_tuned_bwd_kernel_options(head_dim, device_ok):return dict(_FLEX_TUNED_BWD_KERNEL_OPTIONS)-def _flex_tuned_bwd_fits(args, kwargs):- """Whether the tuned backward tiles can join this call. Not when the caller set its own tiles- (a partial set merged with ours can break bwd_BLOCK_N1 % bwd_BLOCK_M1 == 0), nor when the block- mask's sparse blocks are not multiples of our tiles (Inductor's defaults shrink to fit those)."""+def _flex_tuned_bwd_fits(+ args,+ kwargs,+ options = None,+ caller_prefixes = ("bwd_", "BLOCK_", "num_"),+):+ """Whether our tiles (default: the tuned backward ones) can join this call. Not when the caller set+ its own tiles (a partial set merged with ours can break bwd_BLOCK_N1 % bwd_BLOCK_M1 == 0), nor when+ the block mask's sparse blocks are not multiples of our tiles (Inductor's defaults shrink to fit)."""+ if options is None:+ options = _FLEX_TUNED_BWD_KERNEL_OPTIONSrequested = kwargs.get("kernel_options") or {}- if any(k.startswith(("bwd_", "BLOCK_", "num_")) for k in requested):+ if any(k.startswith(caller_prefixes) for k in requested):return Falsemask = args[0] if len(args) > 0 else kwargs.get("attention_mask", None)block_size = getattr(mask, "BLOCK_SIZE", None)if block_size is None:return Truetry:- tiles = [v for k, v in _FLEX_TUNED_BWD_KERNEL_OPTIONS.items() if "_BLOCK_" in k]+ tiles = [v for k, v in options.items() if "_BLOCK_" in k]return all(int(size) % tile == 0 for size in block_size for tile in tiles)except Exception:return False+# sm86 / sm89 (A10, RTX 3090 / 4090, A6000, L4, L40S; 101376 B shared memory): Inductor's default+# flex tiles at 128 < head_dim <= 256 need 114688-151552 B and fail to compile, so Gemma 3 went to+# eager. These fit and were the fastest that compiled on an L4. "fwd_" / "bwd_" keys need torch 2.10+.+_FLEX_SMALL_SMEM_KERNEL_OPTIONS = {+ "fwd_BLOCK_M": 64,+ "fwd_BLOCK_N": 64,+ "fwd_num_stages": 1,+ "fwd_num_warps": 4,+ "bwd_BLOCK_M1": 32,+ "bwd_BLOCK_N1": 32,+ "bwd_BLOCK_M2": 32,+ "bwd_BLOCK_N2": 32,+ "bwd_num_stages": 1,+ "bwd_num_warps": 4,+}+# Smallest shared memory per block the tiles above were measured to fit (sm86 / sm89).+_FLEX_SMALL_SMEM_MIN_SHARED_MEMORY = 101376+_FLEX_SMALL_SMEM_CAPABILITY_MAJOR = 8+_FLEX_SMALL_SMEM_ENV_VAR = "UNSLOTH_FLEX_SMALL_SMEM_TILES"+++def _flex_small_smem_device_ok():+ """Every visible device is sm8x with too little shared memory for the default head_dim 256 tiles+ but enough for ours, torch >= 2.10. Read at wrap time. UNSLOTH_FLEX_SMALL_SMEM_TILES=0 disables."""+ if os.environ.get(_FLEX_SMALL_SMEM_ENV_VAR, "").strip() == "0":+ return False+ try:+ if getattr(torch.version, "hip", None) or not torch.cuda.is_available():+ return False+ if Version(torch.__version__.split("+")[0]) < Version(_FLEX_TUNED_BWD_MIN_TORCH):+ return False+ count = torch.cuda.device_count()+ if count < 1:+ return False+ for index in range(count):+ if torch.cuda.get_device_capability(index)[0] != _FLEX_SMALL_SMEM_CAPABILITY_MAJOR:+ return False+ shared_memory = torch.cuda.get_device_properties(index).shared_memory_per_block_optin+ if not (+ _FLEX_SMALL_SMEM_MIN_SHARED_MEMORY+ <= shared_memory+ < _FLEX_TEMPLATE_HEAD_DIM_256_SHARED_MEMORY+ ):+ return False+ return True+ except Exception:+ return False+++def _flex_small_smem_kernel_options(head_dim, device_ok):+ """fwd_* / bwd_* kernel_options that fit an sm86 / sm89 card at this head dim, else None."""+ low, high = _FLEX_TUNED_BWD_HEAD_DIM_RANGE+ if not device_ok or not isinstance(head_dim, int) or not (low < head_dim <= high):+ return None+ return dict(_FLEX_SMALL_SMEM_KERNEL_OPTIONS)++def _flex_call_needs_backward(query, key, value):"""True when this flex call is recorded for autograd on an accelerator."""try:@@ -948,6 +1012,7 @@ def _wrap_flex_attention_forward(flex_attention_forward):return flex_attention_forwardtuned_bwd_device_ok = _flex_tuned_bwd_device_ok()+ small_smem_device_ok = _flex_small_smem_device_ok()@functools.wraps(flex_attention_forward)def unsloth_flex_attention_forward(module, query, key, value, *args, **kwargs):@@ -973,6 +1038,20 @@ def _wrap_flex_attention_forward(flex_attention_forward):)except Exception:kernel_options = None+ # First: on these cards the default forward tile does not fit, so this full set beats a forced+ # UNSLOTH_FLEX_TUNED_BACKWARD=1 (backward keys only).+ if (+ kernel_options is None+ and small_smem_device_ok+ and hasattr(query, "dim")+ and query.dim() == 4+ # Short no-grad queries go to flex_decoding, whose own tiles are left alone.+ and (query.shape[2] >= 128 or _flex_call_needs_backward(query, key, value))+ and _flex_tuned_bwd_fits(+ args, kwargs, _FLEX_SMALL_SMEM_KERNEL_OPTIONS, ("fwd_", "bwd_", "BLOCK_", "num_")+ )+ ):+ kernel_options = _flex_small_smem_kernel_options(query.shape[-1], small_smem_device_ok)if (kernel_options is Noneand tuned_bwd_device_ok@@ -1409,6 +1488,9 @@ def _flex_preferred_fits(config):try:if getattr(torch.version, "hip", None) or not torch.cuda.is_available():return True+ # sm86 / sm89 with torch >= 2.10: the flex wrapper passes tiles that fit.+ if _flex_small_smem_device_ok():+ return Truereturn all(torch.cuda.get_device_properties(index).shared_memory_per_block_optin>= _FLEX_TEMPLATE_HEAD_DIM_256_SHARED_MEMORY