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 small-smem tiles: keep float32 calls on the default tiles (#16172)
Daniel Han18ce989dda61
diff --git a/tests/test_flex_decode_guard_wrapper.py b/tests/test_flex_decode_guard_wrapper.pyindex 728afd93cc5..7ddd4ae1bf4 100644--- a/tests/test_flex_decode_guard_wrapper.py+++ b/tests/test_flex_decode_guard_wrapper.py@@ -1,15 +1,12 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.-"""The registered Transformers flex wrapper keeps short no-grad queries off flex_decoding where unsloth_zoo found it-cannot compile (Triton 3.9 removed the block pointers torch 2.9 - 2.12's decode template builds)."""-import sysimport typesimport pytest-import unsloth # noqa: F401 (must precede transformers)+import unsloth # noqa: F401import unsloth.models._utils as u@@ -34,13 +31,14 @@ def _wrapped_call(monkeypatch.setattr(u, "_flex_tuned_bwd_device_ok", lambda: False)monkeypatch.setattr(u, "_flex_small_smem_device_ok", lambda: small_ok)monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: needs_backward)+ monkeypatch.setattr(u, "_flex_small_smem_short_query_tiles", lambda: False)wrapped = u._wrap_flex_attention_forward(fake_flex)class M(torch.nn.Module):is_causal = True- q = torch.randn(1, 2, q_len, head_dim)- k = torch.randn(1, 2, 128, head_dim)+ q = torch.randn(1, 2, q_len, head_dim, dtype = torch.bfloat16)+ k = torch.randn(1, 2, 128, head_dim, dtype = torch.bfloat16)wrapped(M(), q, k, k.clone(), object(), **kwargs)return seen["kernel_options"]@@ -93,12 +91,10 @@ def test_an_unsloth_zoo_without_the_check_keeps_auto(monkeypatch):def _select_torch_2_9(options):- # torch 2.9 lowering: no BACKEND; flex_decoding unless FORCE_USE_FLEX_ATTENTION.return "main" if options.get("FORCE_USE_FLEX_ATTENTION", False) else "decode"def _select_torch_2_12(options):- # torch 2.10 - 2.12: BACKEND plus the legacy knob is rejected; AUTO picks flex_decoding unless forced.if "BACKEND" in options and options.get("FORCE_USE_FLEX_ATTENTION", False):raise ValueError("BACKEND cannot be combined with legacy FORCE_USE_FLEX_ATTENTION")backend = options.get("BACKEND", "AUTO")@@ -129,7 +125,6 @@ def test_an_explicit_auto_backend_takes_the_main_kernel_too(monkeypatch, needs_b@pytest.mark.parametrize("needs_backward", [False, True])@pytest.mark.parametrize("backend", ["TRITON_DECODE", "FLASH", "TRITON"])def test_a_named_backend_in_any_mapping_is_left_alone(monkeypatch, needs_backward, backend):- # torch reads kernel_options through dict(); a read-only mapping must not hide its BACKEND.from types import MappingProxyTypeopts = _wrapped_call(monkeypatch, True, 1, needs_backward, kernel_options = MappingProxyType({"BACKEND": backend})@@ -156,7 +151,6 @@ def test_an_auto_backend_in_a_read_only_mapping_takes_the_main_kernel(monkeypatc],)def test_small_memory_tiles_follow_the_kernel_that_runs(monkeypatch, requested, main_kernel):- # The fitted tiles are main-kernel tiles: a caller that keeps flex_decoding must not get them.kwargs = {} if requested is None else {"kernel_options": dict(requested)}opts = _wrapped_call(monkeypatch, True, 1, small_ok = True, head_dim = 256, **kwargs) or {}tiles = {k: opts.get(k) for k in u._FLEX_SMALL_SMEM_KERNEL_OPTIONS}diff --git a/tests/test_flex_small_smem_tiles.py b/tests/test_flex_small_smem_tiles.pyindex 7e2f7c07484..912fd487ea8 100644--- a/tests/test_flex_small_smem_tiles.py+++ b/tests/test_flex_small_smem_tiles.py@@ -1,19 +1,16 @@# 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 SimpleNamespaceimport pytest-import unsloth # noqa: F401 (must precede transformers)+import unsloth # noqa: F401import unsloth.models._utils as u@pytest.fixture(autouse = True)def _flex_decoding_available(monkeypatch):- # These pin the routing where flex_decoding compiles; test_flex_decode_guard_wrapper.py covers a host where it cannot.monkeypatch.setattr(u, "_flex_decoding_unavailable", lambda: False, raising = False)@@ -55,13 +52,13 @@ def devices(monkeypatch):((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+ ((T4,), False),+ ((A100,), False),((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+ ((RTX_PRO_6000,), False),+ ((L4, A100), False),((), False),],)@@ -103,7 +100,7 @@ def test_options_in_range(head_dim):opts = u._flex_small_smem_kernel_options(head_dim, True)assert opts == u._FLEX_SMALL_SMEM_KERNEL_OPTIONSassert all(k.startswith(("fwd_", "bwd_")) for k in opts)- opts["fwd_num_stages"] = 99 # a fresh dict per call+ opts["fwd_num_stages"] = 99assert u._FLEX_SMALL_SMEM_KERNEL_OPTIONS["fwd_num_stages"] == 1@@ -158,22 +155,23 @@ def _qkv(q_len,head_dim = 256,grad = True,+ dtype = None,):import torch- return [torch.randn(1, 2, q_len, head_dim, requires_grad = grad) for _ in range(3)]+ dtype = dtype or torch.bfloat16+ return [torch.randn(1, 2, q_len, head_dim, dtype = dtype, 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+ wrapped(_Causal(), *_qkv(16), object())for k, v in u._FLEX_SMALL_SMEM_KERNEL_OPTIONS.items():assert seen[k] == vassert seen["FORCE_USE_FLEX_ATTENTION"] is Truedef 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})@@ -202,9 +200,9 @@ def test_wrapper_no_grad_prefill_gets_tiles_decode_does_not(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- assert "FORCE_USE_FLEX_ATTENTION" not in seen # q_len >= 128 is the main kernel already+ assert "FORCE_USE_FLEX_ATTENTION" not in seenwrapped(_Causal(), *_qkv(8, grad = False), object())- assert seen == {} # flex_decoding keeps its own config+ assert seen == {}def _gqa_qkv(@@ -214,27 +212,28 @@ def _gqa_qkv(head_dim = 256,):import torch- q = torch.randn(1, q_heads, q_len, head_dim)- return [q, torch.randn(1, kv_heads, q_len, head_dim), torch.randn(1, kv_heads, q_len, head_dim)]+ return [+ torch.randn(1, heads, q_len, head_dim, dtype = torch.bfloat16)+ for heads in (q_heads, kv_heads, kv_heads)+ ]@pytest.mark.parametrize("q_len,q_heads,kv_heads,tiled",[- (1, 4, 1, False), # Gemma 3 1B decode step: 16 rows, flex_decoding fits- (16, 4, 1, False), # 64 rows still fit- (17, 4, 1, True), # 68 rows -> a 128-row tile: 114688 B- (28, 4, 1, True), # Gemma 3 1B / 270M chat prompt- (28, 8, 4, False), # Gemma 3 4B: 2 query heads per kv head, 56 rows+ (1, 4, 1, False),+ (16, 4, 1, False),+ (17, 4, 1, True),+ (28, 4, 1, True),+ (28, 8, 4, False),(40, 8, 4, True),(127, 2, 2, True),- (28, 6, 2, False), # not a power of two: transformers repeats K / V, 28 rows+ (28, 6, 2, False),],)def test_wrapper_short_prompt_whose_decode_tile_does_not_fit_gets_tiles(monkeypatch, q_len, q_heads, kv_heads, tiled):- # A failed compile here pinned flex_attention to the eager fallback for the whole process.wrapped, seen = _wrapped(monkeypatch)monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: False)wrapped(_Causal(), *_gqa_qkv(q_len, q_heads, kv_heads), object())@@ -248,7 +247,7 @@ def test_wrapper_short_prompt_whose_decode_tile_does_not_fit_gets_tiles(assert seen == {}wrapped, seen = _wrapped(monkeypatch, small_ok = False)wrapped(_Causal(), *_gqa_qkv(q_len, q_heads, kv_heads), object())- assert seen == {} # other cards keep the defaults+ assert seen == {}@pytest.mark.parametrize(@@ -269,22 +268,22 @@ def test_short_query_tiles_torch_gate(monkeypatch, version, expected):@pytest.mark.parametrize("q_len,q_heads,kv_heads,forced",[- (1, 4, 1, False), # Gemma 3 1B decode step: tiles, flex_decoding stays eligible- (4, 4, 1, False), # 16 rows: flex_decoding's own BLOCK_M would be 16- (8, 4, 1, False), # 32 rows- (16, 4, 1, False), # 64 rows- (16, 8, 4, False), # Gemma 3 4B 16-token prompt, 32 rows- (28, 8, 4, False), # Gemma 3 4B prompt, 56 rows- (28, 6, 2, False), # repeated K / V, 28 rows- (17, 4, 1, True), # 68 rows: main kernel, as in the default gate+ (1, 4, 1, False),+ (4, 4, 1, False),+ (8, 4, 1, False),+ (16, 4, 1, False),+ (16, 8, 4, False),+ (28, 8, 4, False),+ (28, 6, 2, False),+ (17, 4, 1, True),(127, 2, 2, True),],)def test_wrapper_short_no_grad_queries_get_tiles_before_torch_2_14(monkeypatch, q_len, q_heads, kv_heads, forced):- # A batch size change makes the batch dim dynamic, which moves even one-token decode from- # flex_decoding to the main kernel, whose default tile does not fit (torch 2.10 / 2.11).+ # Before 2.14, a dynamic batch can move one-token decode onto the main kernel.+import torchqkv = [t.to(torch.bfloat16) for t in _gqa_qkv(q_len, q_heads, kv_heads)]@@ -299,7 +298,7 @@ def test_wrapper_short_no_grad_queries_get_tiles_before_torch_2_14(assert seen.get("BLOCK_M") == (None if forced else 64)wrapped, seen = _wrapped(monkeypatch, small_ok = False, short_tiles = True)wrapped(_Causal(), *qkv, object())- assert seen == {} # other cards keep the defaults+ assert seen == {}@pytest.mark.parametrize(@@ -312,7 +311,6 @@ def test_wrapper_short_no_grad_queries_get_tiles_before_torch_2_14(],)def test_short_query_tiles_only_where_measured(monkeypatch, head_dim, dtype, tiled):- # fp32 needs 147456 B with these tiles on flex_decoding; head_dim 192 fails to build on 2.10.import torchwrapped, seen = _wrapped(monkeypatch, short_tiles = True)@@ -352,8 +350,6 @@ def test_a100_keeps_its_tuned_backward(monkeypatch):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())@@ -363,8 +359,8 @@ def test_small_card_with_tuned_backward_forced_keeps_fitting_tiles(monkeypatch):@pytest.mark.parametrize("requested", [{"FORCE_USE_FLEX_ATTENTION": True}, {"BACKEND": "TRITON"}])def test_wrapper_forced_main_kernel_no_grad_short_query_gets_tiles(monkeypatch, requested):- # Gradient checkpointing runs each block's first forward under no_grad, and the block compile- # hook forces the main kernel there, whose default head_dim 256 tiles do not fit (#15271).+ # Checkpoint forwards force the main kernel (#15271).+wrapped, seen = _wrapped(monkeypatch)monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: False)wrapped(_Causal(), *_qkv(64, grad = False), object(), kernel_options = dict(requested))@@ -373,12 +369,10 @@ def test_wrapper_forced_main_kernel_no_grad_short_query_gets_tiles(monkeypatch,for k, v in requested.items():assert seen[k] == vwrapped(_Causal(), *_qkv(64, grad = False), object(), kernel_options = {"BACKEND": "AUTO"})- assert "fwd_BLOCK_M" not in seen # flex_decoding may still run: its own tiles+ assert "fwd_BLOCK_M" not in seendef test_wrapper_training_calls_add_no_sequence_guard(monkeypatch):- # The grad check must short-circuit before query.shape[2] >= 128, or a dynamic-shape block- # compiles once more when the sequence crosses 128.import torchmonkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: True)@@ -398,13 +392,85 @@ def test_wrapper_training_calls_add_no_sequence_guard(monkeypatch):return wrapped(_Causal(), q, q, q, None, is_causal = False) * 2for q_len in (256, 512, 64, 32):- block(torch.randn(1, 2, q_len, 256))+ block(torch.randn(1, 2, q_len, 256, dtype = torch.bfloat16))torch._dynamo.reset()return len(graphs)assert graphs_for(True) == graphs_for(False)+ "q_len,grad,requested",+ [+ (64, False, {"FORCE_USE_FLEX_ATTENTION": True}),+ (64, False, {"BACKEND": "TRITON"}),+ (256, False, {}),+ (256, True, {}),+ ],+)+def test_float32_query_gets_no_small_tiles(monkeypatch, q_len, grad, requested):+ import torch++ monkeypatch.setattr(torch, "is_autocast_enabled", lambda *a: False)+ wrapped, seen = _wrapped(monkeypatch)+ monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: grad)+ qkv = _qkv(q_len, grad = grad, dtype = torch.float32)+ wrapped(_Causal(), *qkv, object(), kernel_options = dict(requested))+ assert not any(k in seen for k in u._FLEX_SMALL_SMEM_KERNEL_OPTIONS)+ for k, v in requested.items():+ assert seen[k] == v+ for dtype in (torch.bfloat16, torch.float16):+ qkv = _qkv(q_len, grad = grad, dtype = dtype)+ wrapped(_Causal(), *qkv, object(), kernel_options = dict(requested))+ assert seen["fwd_BLOCK_M"] == 64+++def test_flex_cuda_autocast_handler_is_detected(monkeypatch):+ from torch._higher_order_ops.flex_attention import flex_attention+ monkeypatch.setattr(+ flex_attention, "py_kernels", {u.torch._C.DispatchKey.AutocastCUDA: lambda *a: None}+ )+ assert u._flex_autocasts_cuda_inputs() is True+++def test_flex_without_cuda_autocast_handler_is_detected(monkeypatch):+ from torch._higher_order_ops.flex_attention import flex_attention+ monkeypatch.setattr(flex_attention, "py_kernels", {})+ assert u._flex_autocasts_cuda_inputs() is False++[email protected]("autocast_dtype", ["float16", "bfloat16"])[email protected]("enabled", [False, True])[email protected]("has_handler", [False, True])[email protected]("device", ["cpu", "cuda"])+def test_float32_cuda_autocast_keeps_fitting_tiles(+ monkeypatch, autocast_dtype, enabled, has_handler, device+):+ import torch++ monkeypatch.setattr(u, "_flex_autocasts_cuda_inputs", lambda: has_handler, raising = False)+ monkeypatch.setattr(+ torch, "is_autocast_enabled", lambda device: enabled if device == "cuda" else False+ )+ monkeypatch.setattr(torch, "get_autocast_dtype", lambda device: getattr(torch, autocast_dtype))+ monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: True)+ wrapped, seen = _wrapped(monkeypatch)+ query = SimpleNamespace(+ dtype = torch.float32,+ device = torch.device(device),+ shape = (1, 2, 256, 256),+ requires_grad = True,+ dim = lambda: 4,+ )+ wrapped(_Causal(), query, query, query, object())+ if device == "cuda" and has_handler and enabled:+ assert {+ k: seen.get(k) for k in u._FLEX_SMALL_SMEM_KERNEL_OPTIONS+ } == u._FLEX_SMALL_SMEM_KERNEL_OPTIONS+ else:+ assert not any(k in seen for k in u._FLEX_SMALL_SMEM_KERNEL_OPTIONS)++def test_wrapper_forced_short_prompt_drops_auto_backend(monkeypatch):# torch 2.10+ rejects BACKEND with FORCE_USE_FLEX_ATTENTION and 2.9 has no BACKEND: AUTO is dropped.wrapped, seen = _wrapped(monkeypatch)@@ -434,7 +500,6 @@ def test_wrapper_forced_short_prompt_keeps_explicit_backend_untouched(monkeypatcdef test_wrapper_forced_short_prompt_keeps_caller_force_off_untouched(monkeypatch):- # The caller's FORCE off sends 112 rows to flex_decoding, which our main-kernel tiles do not cover.wrapped, seen = _wrapped(monkeypatch)monkeypatch.setattr(u, "_flex_call_needs_backward", lambda *a: False)requested = {"FORCE_USE_FLEX_ATTENTION": False}diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex c31b7bca645..445fae78acf 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -1085,6 +1085,14 @@ def _flex_decoding_unavailable():return FLEX_DECODING_UNAVAILABLE is True+def _flex_autocasts_cuda_inputs():+ try:+ from torch._higher_order_ops.flex_attention import flex_attention+ return callable(flex_attention.py_kernels.get(torch._C.DispatchKey.AutocastCUDA))+ except (ImportError, AttributeError):+ return False++def _flex_main_kernel_forced(kwargs):"""True when the caller's kernel_options force the main flex kernel over flex_decoding."""requested = kwargs.get("kernel_options") or {}@@ -1213,6 +1221,7 @@ def _wrap_flex_attention_forward(flex_attention_forward):tuned_bwd_device_ok = _flex_tuned_bwd_device_ok()small_smem_device_ok = _flex_small_smem_device_ok()+ small_smem_autocasts = small_smem_device_ok and _flex_autocasts_cuda_inputs()small_smem_short_query_tiles = small_smem_device_ok and _flex_small_smem_short_query_tiles()# A failed flex_decoding compile makes Dynamo run flex eagerly for the rest of the process (full score matrix).decoding_unavailable = _flex_decoding_unavailable()@@ -1261,9 +1270,17 @@ def _wrap_flex_attention_forward(flex_attention_forward):and small_smem_device_okand hasattr(query, "dim")and query.dim() == 4- # Short no-grad queries go to flex_decoding, whose own tiles are left alone while they- # fit, unless the caller (the block compile hook, also for no-grad checkpoint forwards)- # forces the main kernel. Shape last, so training calls add no seq >= 128 guard.+ and (+ getattr(query, "dtype", None) in (torch.float16, torch.bfloat16)+ or (+ small_smem_autocasts+ and getattr(query, "dtype", None) == torch.float32+ and query.device.type == "cuda"+ and torch.is_autocast_enabled("cuda")+ and torch.get_autocast_dtype("cuda") in (torch.float16, torch.bfloat16)+ )+ )+ # Keep shape checks last so training adds no sequence-length guard.and (_flex_call_needs_backward(query, key, value)or _flex_main_kernel_forced(kwargs)