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.

Offer FlexAttention when head_dim puts every flash kernel out of reach (#11102)

Daniel Hanc99204e819e6
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 0ac4c600def..2c66d6bb15e 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -5063,7 +5063,13 @@ def _determine_attention_impl_for_gpu_estimate(config) -> str:
except Exception:
continue
- return resolve_attention_implementation(model_class, config_copy)
+ impl = resolve_attention_implementation(model_class, config_copy)
+ # A per-sub-config mapping collapses to the decoder's name for the frozenset lookup. Inlined
+ # because callers stub the unsloth import.
+ if isinstance(impl, dict):
+ named = [value for key, value in impl.items() if key != "" and value is not None]
+ impl = named[0] if named else impl.get("", "eager")
+ return impl
def _estimate_fp16_model_size_bytes_from_config(config) -> Optional[int]:
diff --git a/tests/test_flex_gemma4_sliding_scope.py b/tests/test_flex_gemma4_sliding_scope.py
new file mode 100644
index 00000000000..3dca3852cbe
--- /dev/null
+++ b/tests/test_flex_gemma4_sliding_scope.py
@@ -0,0 +1,116 @@
+# SPDX-License-Identifier: AGPL-3.0-or-later
+"""Gemma 4 stays on SDPA: all its layers share one _attn_implementation, and flex would
+disable unsloth_zoo's gemma4_flash_sliding router ("sdpa" key) for its 25 sliding layers."""
+
+import pytest
+
+import unsloth # noqa: F401 (must precede transformers)
+import unsloth.models._utils as u
+
+
+class _Cfg:
+ def __init__(self, **kw):
+ for k, v in kw.items():
+ setattr(self, k, v)
+
+
[email protected](autouse = True)
+def _clean(monkeypatch):
+ monkeypatch.delenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, raising = False)
+ monkeypatch.setattr(u, "_sdpa_reaches_cudnn_at_head_dim_256", lambda: False)
+ monkeypatch.setattr(u, "_flex_kernels_fit_large_head_dim", lambda: True)
+
+
+def _gemma4():
+ text = _Cfg(
+ model_type = "gemma4_text",
+ head_dim = 256,
+ global_head_dim = 512,
+ sliding_window = 1024,
+ num_attention_heads = 16,
+ )
+ return _Cfg(
+ model_type = "gemma4",
+ text_config = text,
+ vision_config = _Cfg(model_type = "gemma4_vision", head_dim = 72, num_attention_heads = 16),
+ )
+
+
+def test_gemma4_is_not_routed_to_flex():
+ assert u._prefers_flex_for_head_dim(_gemma4()) is False
+
+
+def test_gemma4_text_only_is_not_routed_either():
+ # A text-only load presents gemma4_text at the top.
+ text_only = _Cfg(
+ model_type = "gemma4_text",
+ head_dim = 256,
+ global_head_dim = 512,
+ num_attention_heads = 16,
+ )
+ assert u._prefers_flex_for_head_dim(text_only) is False
+
+
+def test_the_head_dim_is_still_large_so_this_really_is_the_exclusion_talking():
+ assert u._text_attention_head_dim(_gemma4()) == 512
+
+
+def test_gemma2_stays_excluded():
+ cfg = _Cfg(model_type = "gemma2", head_dim = 256, num_attention_heads = 8)
+ assert u._prefers_flex_for_head_dim(cfg) is False
+
+
[email protected]("model_type", ["qwen3_5", "qwen3_5_moe", "qwen3_next"])
+def test_the_models_this_routing_is_for_are_unaffected(model_type):
+ cfg = _Cfg(model_type = model_type, head_dim = 256, num_attention_heads = 8)
+ assert u._prefers_flex_for_head_dim(cfg) is True
+
+
+def test_an_explicit_request_can_still_force_flex_on_gemma4(monkeypatch):
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, "1")
+ assert u._prefers_flex_for_head_dim(_gemma4()) is True
+
+
+class _Proxy:
+ """A forwarding proxy with no instance dict, like unsloth_zoo's Gemma 4 one."""
+
+ __slots__ = ("_real",)
+
+ def __init__(self, real):
+ object.__setattr__(self, "_real", real)
+
+ def __getattr__(self, name):
+ return getattr(object.__getattribute__(self, "_real"), name)
+
+
+def test_a_proxied_text_config_is_still_recognised_by_name():
+ # unsloth_zoo's proxy means get_text_config() is not `config.text_config`.
+ u._ATTN_IMPL_MAPPING_SUPPORTED.clear()
+ u._ATTN_IMPL_MAPPING_SUPPORTED.append(True)
+ try:
+ text = _Cfg(model_type = "fake_text", head_dim = 256, num_attention_heads = 8)
+ cfg = _Cfg(
+ model_type = "fake_vl",
+ text_config = text,
+ vision_config = _Cfg(model_type = "fake_vision", head_dim = 64, num_attention_heads = 8),
+ )
+ cfg.get_text_config = lambda: _Proxy(text)
+ got = u._flex_attn_impl_for(cfg, "sdpa")
+ assert got == {"": "sdpa", "text_config": "flex_attention"}
+ finally:
+ u._ATTN_IMPL_MAPPING_SUPPORTED.clear()
+
+
+def test_an_unnameable_text_config_declines_rather_than_flexing_everything():
+ u._ATTN_IMPL_MAPPING_SUPPORTED.clear()
+ u._ATTN_IMPL_MAPPING_SUPPORTED.append(True)
+ try:
+ stranger = _Cfg(model_type = "fake_text", head_dim = 256, num_attention_heads = 8)
+ cfg = _Cfg(
+ model_type = "fake_vl",
+ vision_config = _Cfg(model_type = "fake_vision", head_dim = 64, num_attention_heads = 8),
+ )
+ cfg.get_text_config = lambda: stranger
+ assert u._flex_attn_impl_for(cfg, "sdpa") is None
+ finally:
+ u._ATTN_IMPL_MAPPING_SUPPORTED.clear()
diff --git a/tests/test_flex_head_dim_version_gate.py b/tests/test_flex_head_dim_version_gate.py
new file mode 100644
index 00000000000..31d32ba0ead
--- /dev/null
+++ b/tests/test_flex_head_dim_version_gate.py
@@ -0,0 +1,170 @@
+# SPDX-License-Identifier: AGPL-3.0-or-later
+"""head_dim 256 routes to flex only until SDPA reaches cuDNN with a mask (torch 2.14, sm100).
+Above 256 no cuDNN build helps, so it routes on every version."""
+
+import pytest
+
+import unsloth # noqa: F401 (must precede transformers)
+import unsloth.models._utils as u
+
+
+class _Cfg:
+ def __init__(self, **kw):
+ for k, v in kw.items():
+ setattr(self, k, v)
+
+
+def _cfg(head_dim):
+ return _Cfg(model_type = "fake", head_dim = head_dim, num_attention_heads = 8)
+
+
[email protected](autouse = True)
+def _no_env_override(monkeypatch):
+ # The env var short-circuits before the gate, so it must be clear for these.
+ monkeypatch.delenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, raising = False)
+ monkeypatch.setattr(u, "_flex_kernels_fit_large_head_dim", lambda: True)
+
+
+def cudnn_reaches_256(monkeypatch):
+ def _set(value):
+ monkeypatch.setattr(u, "_sdpa_reaches_cudnn_at_head_dim_256", lambda: value)
+
+ return _set
+
+
+def test_head_dim_256_takes_flex_while_sdpa_cannot_reach_cudnn(cudnn_reaches_256):
+ cudnn_reaches_256(False)
+ assert u._prefers_flex_for_head_dim(_cfg(256)) is True
+
+
+def test_head_dim_256_stays_on_sdpa_once_cudnn_takes_the_mask(cudnn_reaches_256):
+ cudnn_reaches_256(True)
+ assert u._prefers_flex_for_head_dim(_cfg(256)) is False
+
+
[email protected]("head_dim", [264, 512])
+def test_above_256_takes_flex_on_every_version(head_dim, cudnn_reaches_256):
+ for reaches in (False, True):
+ cudnn_reaches_256(reaches)
+ assert u._prefers_flex_for_head_dim(_cfg(head_dim)) is True
+
+
[email protected]("head_dim", [64, 128])
+def test_at_or_below_128_never_takes_flex(head_dim, cudnn_reaches_256):
+ for reaches in (False, True):
+ cudnn_reaches_256(reaches)
+ assert u._prefers_flex_for_head_dim(_cfg(head_dim)) is False
+
+
+def test_no_head_dim_means_no_routing(cudnn_reaches_256):
+ cudnn_reaches_256(False)
+ assert u._prefers_flex_for_head_dim(_Cfg(model_type = "fake")) is False
+
+
+def test_env_var_forces_flex_even_when_cudnn_would_serve_it(monkeypatch, cudnn_reaches_256):
+ cudnn_reaches_256(True)
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, "1")
+ assert u._prefers_flex_for_head_dim(_cfg(256)) is True
+
+
+def test_env_var_keeps_sdpa_even_above_256(monkeypatch, cudnn_reaches_256):
+ cudnn_reaches_256(False)
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, "0")
+ assert u._prefers_flex_for_head_dim(_cfg(512)) is False
+
+
+def test_gate_is_off_below_torch_2_14(monkeypatch):
+ monkeypatch.setattr(u.torch, "__version__", "2.13.0+cu130")
+ assert u._sdpa_reaches_cudnn_at_head_dim_256() is False
+
+
+def test_gate_is_off_on_rocm(monkeypatch):
+ monkeypatch.setattr(u.torch, "__version__", "2.14.0+cu130")
+ monkeypatch.setattr(u.torch.version, "hip", "6.2.0", raising = False)
+ assert u._sdpa_reaches_cudnn_at_head_dim_256() is False
+
+
+def test_gate_is_off_with_no_cuda(monkeypatch):
+ monkeypatch.setattr(u.torch, "__version__", "2.14.0+cu130")
+ monkeypatch.setattr(u.torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(u.torch.cuda, "is_available", lambda: False)
+ assert u._sdpa_reaches_cudnn_at_head_dim_256() is False
+
+
+def test_gate_is_off_below_blackwell(monkeypatch):
+ monkeypatch.setattr(u.torch, "__version__", "2.14.0+cu130")
+ monkeypatch.setattr(u.torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(u.torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(u.torch.cuda, "device_count", lambda: 1)
+ monkeypatch.setattr(u.torch.cuda, "get_device_capability", lambda index: (9, 0))
+ assert u._sdpa_reaches_cudnn_at_head_dim_256() is False
+
+
+def test_gate_is_on_for_blackwell_on_torch_2_14(monkeypatch):
+ monkeypatch.setattr(u.torch, "__version__", "2.14.0+cu130")
+ monkeypatch.setattr(u.torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(u.torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(u.torch.cuda, "device_count", lambda: 1)
+ monkeypatch.setattr(u.torch.cuda, "get_device_capability", lambda index: (10, 0))
+ assert u._sdpa_reaches_cudnn_at_head_dim_256() is True
+
+
+def test_a_mixed_box_falls_back_to_the_weakest_card(monkeypatch):
+ monkeypatch.setattr(u.torch, "__version__", "2.14.0+cu130")
+ monkeypatch.setattr(u.torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(u.torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(u.torch.cuda, "device_count", lambda: 2)
+ monkeypatch.setattr(
+ u.torch.cuda, "get_device_capability", lambda index: (10, 0) if index == 0 else (9, 0)
+ )
+ assert u._sdpa_reaches_cudnn_at_head_dim_256() is False
+
+
+def _cuda_box(monkeypatch, shared_memory):
+ class _Props:
+ def __init__(self, index):
+ self.shared_memory_per_block_optin = shared_memory[index]
+
+ monkeypatch.setattr(u.torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(u.torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(u.torch.cuda, "device_count", lambda: len(shared_memory))
+ monkeypatch.setattr(u.torch.cuda, "get_device_properties", _Props)
+
+
[email protected]("shared_memory", [101376, 166912]) # sm86/sm89/sm120, A100
+def test_flex_kernels_do_not_fit_small_shared_memory(monkeypatch, shared_memory):
+ monkeypatch.undo()
+ _cuda_box(monkeypatch, [shared_memory])
+ assert u._flex_kernels_fit_large_head_dim() is False
+
+
+def test_flex_kernels_fit_the_measured_class(monkeypatch):
+ monkeypatch.undo()
+ _cuda_box(monkeypatch, [232448])
+ assert u._flex_kernels_fit_large_head_dim() is True
+
+
+def test_flex_kernels_fit_needs_every_card(monkeypatch):
+ monkeypatch.undo()
+ _cuda_box(monkeypatch, [232448, 101376])
+ assert u._flex_kernels_fit_large_head_dim() is False
+
+
+def test_flex_kernels_fit_is_off_on_rocm_and_without_cuda(monkeypatch):
+ monkeypatch.undo()
+ _cuda_box(monkeypatch, [232448])
+ monkeypatch.setattr(u.torch.version, "hip", "6.2.0", raising = False)
+ assert u._flex_kernels_fit_large_head_dim() is False
+ monkeypatch.setattr(u.torch.version, "hip", None, raising = False)
+ monkeypatch.setattr(u.torch.cuda, "is_available", lambda: False)
+ assert u._flex_kernels_fit_large_head_dim() is False
+
+
[email protected]("head_dim", [256, 512])
+def test_small_shared_memory_keeps_sdpa(monkeypatch, cudnn_reaches_256, head_dim):
+ cudnn_reaches_256(False)
+ monkeypatch.setattr(u, "_flex_kernels_fit_large_head_dim", lambda: False)
+ assert u._prefers_flex_for_head_dim(_cfg(head_dim)) is False
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, "1")
+ assert u._prefers_flex_for_head_dim(_cfg(head_dim)) is True
diff --git a/tests/test_flex_large_head_dim_fallback.py b/tests/test_flex_large_head_dim_fallback.py
new file mode 100644
index 00000000000..c204c21cc8c
--- /dev/null
+++ b/tests/test_flex_large_head_dim_fallback.py
@@ -0,0 +1,324 @@
+# SPDX-License-Identifier: AGPL-3.0-or-later
+"""The large-head-dim flex routing: decoder-only scoping, opt-outs, config-driven detection,
+and why the mask is always present under Unsloth."""
+
+import pytest
+
+import unsloth # noqa: F401 (must precede transformers)
+import unsloth.models._utils as u
+
+
+class _Cfg:
+ def __init__(self, **kw):
+ for k, v in kw.items():
+ setattr(self, k, v)
+
+
+def _text_only():
+ return _Cfg(model_type = "fake", head_dim = 256, num_attention_heads = 8)
+
+
+def _multimodal():
+ text = _Cfg(model_type = "fake", head_dim = 256, num_attention_heads = 8)
+ return _Cfg(
+ model_type = "fake_vl",
+ text_config = text,
+ vision_config = _Cfg(model_type = "fake_vision", head_dim = 64, num_attention_heads = 8),
+ )
+
+
[email protected](autouse = True)
+def _reset_probe_cache(monkeypatch):
+ monkeypatch.setattr(u, "_flex_kernels_fit_large_head_dim", lambda: True)
+ u._ATTN_IMPL_MAPPING_SUPPORTED.clear()
+ yield
+ u._ATTN_IMPL_MAPPING_SUPPORTED.clear()
+
+
+def test_no_mapping_support_refuses_flex_on_multimodal():
+ u._ATTN_IMPL_MAPPING_SUPPORTED.append(False)
+ assert u._flex_attn_impl_for(_multimodal(), "sdpa") is None
+
+
+def test_no_mapping_support_still_allows_flex_on_text_only():
+ u._ATTN_IMPL_MAPPING_SUPPORTED.append(False)
+ assert u._flex_attn_impl_for(_text_only(), "sdpa") == "flex_attention"
+
+
+def test_mapping_support_scopes_flex_to_the_decoder():
+ u._ATTN_IMPL_MAPPING_SUPPORTED.append(True)
+ got = u._flex_attn_impl_for(_multimodal(), "sdpa")
+ assert isinstance(got, dict)
+ assert got[""] == "sdpa"
+ assert got["text_config"] == "flex_attention"
+ assert "vision_config" not in got
+
+
+def test_mapping_support_text_only_is_a_plain_string():
+ u._ATTN_IMPL_MAPPING_SUPPORTED.append(True)
+ assert u._flex_attn_impl_for(_text_only(), "sdpa") == "flex_attention"
+
+
+# getattr cannot tell an inherited False (qwen3_5) from a deliberate one (T5Gemma2).
+
+
+def _real_model_class(module_path, class_name):
+ pytest.importorskip("transformers")
+ import importlib
+
+ try:
+ mod = importlib.import_module(module_path)
+ except Exception:
+ pytest.skip(f"{module_path} not available in this transformers")
+ cls = getattr(mod, class_name, None)
+ if cls is None:
+ pytest.skip(f"{class_name} not available in this transformers")
+ return cls
+
+
+def test_qwen3_5_only_inherits_the_base_default():
+ cls = _real_model_class(
+ "transformers.models.qwen3_5.modeling_qwen3_5", "Qwen3_5ForConditionalGeneration"
+ )
+ assert u._declares_flex_support(cls) is None
+
+
+def test_t5gemma2_declares_its_own_opt_out():
+ cls = _real_model_class(
+ "transformers.models.t5gemma2.modeling_t5gemma2", "T5Gemma2ForConditionalGeneration"
+ )
+ assert u._declares_flex_support(cls) is False
+
+
+def test_force_enable_refuses_an_explicit_opt_out():
+ cls = _real_model_class(
+ "transformers.models.t5gemma2.modeling_t5gemma2", "T5Gemma2ForConditionalGeneration"
+ )
+ u._FLEX_SUPPORT_FORCED.clear()
+ assert u._enable_flex_attention_support(cls, "t5gemma2") is False
+ # and it must not have mutated the class on the way out
+ assert u._declares_flex_support(cls) is False
+
+
+def test_force_enable_still_opts_in_qwen3_5():
+ cls = _real_model_class(
+ "transformers.models.qwen3_5.modeling_qwen3_5", "Qwen3_5ForConditionalGeneration"
+ )
+ u._FLEX_SUPPORT_FORCED.clear()
+ assert u._enable_flex_attention_support(cls, "qwen3_5") is True
+
+
+def _no_env(monkeypatch):
+ monkeypatch.delenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, raising = False)
+
+
+def test_large_head_dim_is_detected_from_config_by_default(_no_env):
+ assert u._prefers_flex_for_head_dim(_text_only()) is True
+
+
+def test_small_head_dim_is_left_on_sdpa_by_default(_no_env):
+ assert (
+ u._prefers_flex_for_head_dim(_Cfg(model_type = "llama", head_dim = 128, num_attention_heads = 8))
+ is False
+ )
+
+
+def test_head_dim_derived_from_hidden_size_when_absent(_no_env):
+ # older configs omit head_dim; hidden_size / num_attention_heads is the same quantity
+ assert (
+ u._prefers_flex_for_head_dim(
+ _Cfg(model_type = "fake", hidden_size = 2048, num_attention_heads = 8)
+ )
+ is True
+ )
+ assert (
+ u._prefers_flex_for_head_dim(
+ _Cfg(model_type = "fake", hidden_size = 1024, num_attention_heads = 8)
+ )
+ is False
+ )
+
+
+def test_per_layer_head_dims_take_the_maximum(_no_env):
+ # 5.x per_layer_config: the largest layer decides.
+ cfg = _Cfg(
+ model_type = "fake",
+ head_dim = 128,
+ num_attention_heads = 8,
+ per_layer_config = [
+ _Cfg(head_dim = 128),
+ _Cfg(head_dim = 128),
+ _Cfg(head_dim = 512),
+ ],
+ )
+ assert u._text_attention_head_dim(cfg) == 512
+ assert u._prefers_flex_for_head_dim(cfg) is True
+
+
+def test_a_homogeneous_small_config_is_unaffected_by_the_per_layer_read(_no_env):
+ # 4.x configs have no per_layer_config at all; the global head_dim must still decide.
+ assert (
+ u._prefers_flex_for_head_dim(_Cfg(model_type = "fake", head_dim = 128, num_attention_heads = 8))
+ is False
+ )
+
+
+def test_excluded_model_stays_on_sdpa_even_at_large_head_dim(_no_env):
+ assert (
+ u._prefers_flex_for_head_dim(_Cfg(model_type = "gemma2", head_dim = 256, num_attention_heads = 8))
+ is False
+ )
+
+
+def test_a_vision_tower_alone_never_turns_it_on(_no_env):
+ cfg = _Cfg(
+ model_type = "fake_vl",
+ text_config = _Cfg(model_type = "fake", head_dim = 64, num_attention_heads = 8),
+ vision_config = _Cfg(model_type = "fake_vision", head_dim = 256, num_attention_heads = 8),
+ )
+ assert u._prefers_flex_for_head_dim(cfg) is False
+
+
+def test_missing_head_dim_is_not_a_guess(_no_env):
+ assert u._prefers_flex_for_head_dim(_Cfg(model_type = "fake")) is False
+
+
[email protected]("value", ["0", " 0 "])
+def test_env_var_zero_forces_sdpa(monkeypatch, value):
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, value)
+ assert u._prefers_flex_for_head_dim(_text_only()) is False
+
+
[email protected]("value", ["1", "true", " 1 "])
+def test_env_var_nonzero_forces_flex(monkeypatch, value):
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, value)
+ assert (
+ u._prefers_flex_for_head_dim(_Cfg(model_type = "llama", head_dim = 64, num_attention_heads = 8))
+ is True
+ )
+
+
+def test_empty_env_var_falls_back_to_the_config(monkeypatch):
+ # an exported-but-empty variable is the shell's "unset", not a request to disable
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, "")
+ assert u._prefers_flex_for_head_dim(_text_only()) is True
+ assert (
+ u._prefers_flex_for_head_dim(_Cfg(model_type = "llama", head_dim = 64, num_attention_heads = 8))
+ is False
+ )
+
+
[email protected]("env, expected", [("1", "flex_attention"), (None, "flash_attention_2")])
+def test_forcing_the_env_var_outranks_flash_attention(monkeypatch, env, expected):
+ import transformers as T
+
+ monkeypatch.setattr(u, "HAS_FLASH_ATTENTION", True)
+ if env is None:
+ monkeypatch.delenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, raising = False)
+ else:
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, env)
+ cfg = T.LlamaConfig(
+ hidden_size = 512,
+ num_attention_heads = 4,
+ num_key_value_heads = 4,
+ head_dim = 128,
+ num_hidden_layers = 1,
+ intermediate_size = 64,
+ vocab_size = 128,
+ )
+ resolved = u.resolve_attention_implementation(T.LlamaForCausalLM, cfg)
+ assert resolved == expected
+
+
+ "mapping, expected",
+ [(False, "flash_attention_2"), (True, {"": "sdpa", "text_config": "flex_attention"})],
+)
+def test_forcing_flex_that_cannot_be_scoped_keeps_flash_attention(monkeypatch, mapping, expected):
+ import transformers as T
+
+ monkeypatch.setattr(u, "HAS_FLASH_ATTENTION", True)
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, "1")
+ u._ATTN_IMPL_MAPPING_SUPPORTED.append(mapping)
+ resolved = u.resolve_attention_implementation(T.LlamaForCausalLM, _multimodal())
+ assert resolved == expected
+
+
+def test_forcing_the_env_var_cannot_override_an_architecture_opt_out(monkeypatch):
+ # a deliberate _supports_flex_attn = False still wins over the env var
+ monkeypatch.setenv(u._FLEX_LARGE_HEAD_DIM_ENV_VAR, "1")
+ cls = _real_model_class(
+ "transformers.models.t5gemma2.modeling_t5gemma2", "T5Gemma2ForConditionalGeneration"
+ )
+ u._FLEX_SUPPORT_FORCED.clear()
+ assert u._enable_flex_attention_support(cls, "t5gemma2") is False
+
+
+# Upstream skips the mask for an unpadded batch, but `_ignore_causal_mask_sdpa` returns False
+# while tracing, so Unsloth's compiled create_causal_mask always builds one. Pins both halves.
+
+
+def _mask_for(
+ create,
+ attention_mask,
+ q_len = 64,
+ head_dim = 256,
+ bsz = 2,
+):
+ import torch
+ import transformers as T
+
+ cfg = T.LlamaConfig(
+ hidden_size = 2048,
+ num_attention_heads = 8,
+ num_key_value_heads = 8,
+ num_hidden_layers = 1,
+ head_dim = head_dim,
+ vocab_size = 128,
+ )
+ cfg._attn_implementation = "sdpa"
+ return create(
+ config = cfg,
+ inputs_embeds = torch.zeros(bsz, q_len, cfg.hidden_size, dtype = torch.bfloat16),
+ attention_mask = attention_mask,
+ past_key_values = None,
+ position_ids = torch.arange(q_len).unsqueeze(0).expand(bsz, -1),
+ )
+
+
+def _uncompiled_create_causal_mask():
+ from transformers import masking_utils
+
+ original = getattr(masking_utils, "_unsloth_original_create_causal_mask", None)
+ if original is None:
+ pytest.skip("this transformers/unsloth pair does not stash the original")
+ return original
+
+
+def test_upstream_skips_the_mask_for_an_unpadded_batch():
+ import torch
+
+ create = _uncompiled_create_causal_mask()
+ assert _mask_for(create, None) is None
+ assert _mask_for(create, torch.ones(2, 64, dtype = torch.long)) is None
+
+
+def test_upstream_still_materialises_a_mask_when_padded():
+ import torch
+
+ create = _uncompiled_create_causal_mask()
+ right = torch.ones(2, 64, dtype = torch.long)
+ right[0, -8:] = 0
+ left = torch.ones(2, 64, dtype = torch.long)
+ left[0, :8] = 0
+ assert _mask_for(create, right) is not None
+ assert _mask_for(create, left) is not None
+
+
+def test_our_compiled_wrapper_is_what_defeats_the_skip():
+ """Pins the cause, so this is a deliberate trade and not an accident nobody noticed."""
+ from transformers import masking_utils
+
+ _uncompiled_create_causal_mask() # skip when the pair does not stash it
+ assert _mask_for(masking_utils.create_causal_mask, None) is not None
diff --git a/tests/test_flex_large_head_dim_kernel_options.py b/tests/test_flex_large_head_dim_kernel_options.py
new file mode 100644
index 00000000000..72f8d435e57
--- /dev/null
+++ b/tests/test_flex_large_head_dim_kernel_options.py
@@ -0,0 +1,124 @@
+# SPDX-License-Identifier: AGPL-3.0-or-later
+"""FlexAttention above head_dim 256 needs explicit kernel_options, or the launch faults with
+`CUDA error: misaligned address`."""
+
+import pytest
+
+import unsloth # noqa: F401 (must precede transformers)
+import unsloth.models._utils as u
+
+
[email protected]("head_dim", [32, 64, 128, 192, 256])
+def test_no_kernel_options_at_or_below_256(head_dim):
+ assert u._flex_kernel_options_for_head_dim(head_dim) is None
+
+
[email protected]("head_dim", [264, 272, 288, 320, 384, 512])
+def test_kernel_options_above_256(head_dim):
+ # 264 is the first multiple of 8 above the boundary and already faults without these.
+ assert u._flex_kernel_options_for_head_dim(head_dim) == {
+ "BLOCK_M": 32,
+ "BLOCK_N": 32,
+ "BLOCK_M1": 16,
+ "BLOCK_N1": 32,
+ "BLOCK_M2": 32,
+ "BLOCK_N2": 16,
+ }
+
+
+def test_block_m_is_32_not_64():
+ # 64 fits the naive shared-memory estimate and still faults.
+ assert u._flex_kernel_options_for_head_dim(512)["BLOCK_M"] == 32
+ assert u._flex_kernel_options_for_head_dim(512)["BLOCK_N"] == 32
+
+
+def test_a_non_integer_head_dim_is_left_alone():
+ assert u._flex_kernel_options_for_head_dim(None) is None
+ assert u._flex_kernel_options_for_head_dim("512") is None
+
+
+class _Tensor:
+ """Just enough of a tensor for the wrapper's head-dim probe."""
+
+ def __init__(self, shape):
+ self.shape = shape
+
+ def dim(self):
+ return len(self.shape)
+
+
+def _record():
+ seen = {}
+
+ def flex_attention_forward(module, query, key, value, attention_mask, **kwargs):
+ seen.update(kwargs)
+ seen["called"] = True
+ return ("out", "lse")
+
+ return flex_attention_forward, seen
+
+
+def _call(head_dim, **kwargs):
+ original, seen = _record()
+ wrapped = u._wrap_flex_attention_forward(original)
+ query = _Tensor((1, 16, 2048, head_dim))
+ assert wrapped(None, query, query, query, None, **kwargs) == ("out", "lse")
+ assert seen["called"]
+ return seen
+
+
+def test_wrapper_injects_kernel_options_above_256():
+ assert _call(512)["kernel_options"]["BLOCK_M"] == 32
+
+
+def test_wrapper_leaves_256_alone():
+ # Not "injects an empty dict": it must not appear at all, so torch keeps its own default.
+ assert _call(256).get("kernel_options") is None
+
+
+def test_a_caller_that_asked_for_something_keeps_it():
+ got = _call(512, kernel_options = {"BLOCK_M": 16, "num_warps": 8})["kernel_options"]
+ assert got["BLOCK_M"] == 16 # caller's
+ assert got["num_warps"] == 8 # caller's
+ assert got["BLOCK_N"] == 32 # ours, filling the gap
+
+
+def test_other_kwargs_are_passed_through_untouched():
+ seen = _call(512, scaling = 0.125, softcap = 30.0)
+ assert seen["scaling"] == 0.125
+ assert seen["softcap"] == 30.0
+
+
+def test_a_non_4d_query_is_left_alone():
+ original, seen = _record()
+ wrapped = u._wrap_flex_attention_forward(original)
+ wrapped(None, _Tensor((1, 2048, 512)), None, None, None)
+ assert seen.get("kernel_options") is None
+
+
+def test_wrapping_is_idempotent():
+ original, _seen = _record()
+ once = u._wrap_flex_attention_forward(original)
+ assert u._wrap_flex_attention_forward(once) is once
+
+
+def test_the_patch_is_installed_and_reapplying_it_changes_nothing():
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
+
+ registered = ALL_ATTENTION_FUNCTIONS["flex_attention"]
+ assert getattr(
+ registered, "_unsloth_flex_kernel_options", False
+ ), "importing unsloth must leave the flex attention function wrapped"
+ assert u.patch_flex_attention_kernel_options()
+ assert ALL_ATTENTION_FUNCTIONS["flex_attention"] is registered
+
+
+def test_the_wrapper_keeps_the_original_signature():
+ # Registered attention functions are introspected, so functools.wraps must keep the signature.
+ import inspect
+
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
+
+ parameters = inspect.signature(ALL_ATTENTION_FUNCTIONS["flex_attention"]).parameters
+ for name in ("module", "query", "key", "value", "attention_mask"):
+ assert name in parameters
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index a0c479dfac1..f30583e32db 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -103,6 +103,7 @@ __all__ = [
"make_fast_generate_wrapper",
"_mark_unsloth_disable_data_parallel",
"_patch_transformers_trainer_data_parallel",
+ "patch_flex_attention_kernel_options",
]
import torch
@@ -433,6 +434,367 @@ def _flex_attention_gpu_is_supported():
return True
+# head_dim > 128 with an explicit mask drops torch <= 2.13 SDPA to an sm80 CUTLASS kernel (8.82x
+# the unmasked cost at head_dim 256, T=8192, B200). Flex's BlockMask carries causal, padding and
+# packed-sequence masks exactly as sdpa_mask does. Not FA2 (padding needs varlen), FA3 (no sm100
+# cubin) or FA4 (Hub build broken against nvidia-cutlass-dsl 4.6.0).
+_SDPA_FLASH_MAX_HEAD_DIM = 128
+_FLEX_LARGE_HEAD_DIM_ENV_VAR = "UNSLOTH_FLEX_ATTENTION_FOR_LARGE_HEAD_DIM"
+# gemma2 measured slower under flex. gemma4 shares one _attn_implementation across all layers, so
+# flex would also pull its 25 sliding layers off unsloth_zoo's faster gemma4_flash_sliding router,
+# which is registered under "sdpa".
+_FLEX_LARGE_HEAD_DIM_EXCLUDED_MODELS = ("gemma2", "gemma4", "gemma4_text")
+# Interface dispatch, and a BlockMask from create_causal_mask rather than a hand-built 4D mask.
+_FLEX_INTERFACE_MARKERS = ("ALL_ATTENTION_FUNCTIONS", "create_causal_mask")
+_FLEX_SUPPORT_FORCED = set()
+_ATTN_IMPL_MAPPING_SUPPORTED = []
+
+
+def _text_attention_configs(config):
+ """The decoder's attention sub-configs. A VLM vision tower is excluded: small head dim, and
+ per-image lengths would recompile flex per shape."""
+ text_config = None
+ getter = getattr(config, "get_text_config", None)
+ if callable(getter):
+ try:
+ text_config = getter()
+ except Exception:
+ text_config = None
+ if text_config is None:
+ text_config = _config_get(config, "text_config", None)
+ if text_config is None:
+ text_config = config
+ return list(_iter_attention_configs(text_config))
+
+
+def _text_attention_head_dim(config):
+ head_dims = []
+ for attention_config in _text_attention_configs(config):
+ head_dims.extend(_collect_attention_head_dims(attention_config))
+ return max(head_dims) if len(head_dims) != 0 else None
+
+
+# torch 2.14 lets cuDNN take a masked head_dim 256 on sm100, matching flex with no compile. Measured
+# on Blackwell only, so other cards keep flex.
+_CUDNN_LARGE_HEAD_DIM_TORCH_VERSION = "2.14"
+_CUDNN_LARGE_HEAD_DIM_MIN_CAPABILITY = (10, 0)
+
+
+def _sdpa_reaches_cudnn_at_head_dim_256():
+ """True when plain SDPA already dispatches cuDNN for a MASKED head_dim 256 on this box."""
+ try:
+ if Version(torch.__version__.split("+")[0]) < Version(_CUDNN_LARGE_HEAD_DIM_TORCH_VERSION):
+ return False
+ if getattr(torch.version, "hip", None):
+ return False
+ if not torch.cuda.is_available():
+ return False
+ return all(
+ torch.cuda.get_device_capability(index) >= _CUDNN_LARGE_HEAD_DIM_MIN_CAPABILITY
+ for index in range(torch.cuda.device_count())
+ )
+ except Exception:
+ return False
+
+
+# Inductor's default flex template needs 151552 bytes of shared memory at head_dim 256 (172032 at
+# 192), more than sm86/sm89/sm120 cards (101376) or an A100 (166912) have. There the compile
+# fails, unsloth_zoo's suppress_errors falls back to unfused eager flex, and training runs slower
+# and in more memory than on SDPA. Offer flex only on the 227 KiB class it was measured on.
+_FLEX_LARGE_HEAD_DIM_MIN_SHARED_MEMORY = 232448
+
+
+def _flex_kernels_fit_large_head_dim():
+ """True when every CUDA device has the shared memory Inductor's default flex template needs."""
+ try:
+ if getattr(torch.version, "hip", None):
+ return False
+ if not torch.cuda.is_available():
+ return False
+ return all(
+ torch.cuda.get_device_properties(index).shared_memory_per_block_optin
+ >= _FLEX_LARGE_HEAD_DIM_MIN_SHARED_MEMORY
+ for index in range(torch.cuda.device_count())
+ )
+ except Exception:
+ return False
+
+
+def _flex_large_head_dim_override():
+ """True / False when UNSLOTH_FLEX_ATTENTION_FOR_LARGE_HEAD_DIM forces flex on / off, else None."""
+ override = os.environ.get(_FLEX_LARGE_HEAD_DIM_ENV_VAR)
+ if override is None or override.strip() == "":
+ return None
+ return override.strip() != "0"
+
+
+def _prefers_flex_for_head_dim(config):
+ """True when the decoder's head dim leaves masked SDPA without a flash kernel.
+
+ Unsloth's compiled create_causal_mask always passes a mask (see
+ test_our_compiled_wrapper_is_what_defeats_the_skip), so the masked case is the training case.
+ Flex costs a 4-12 s compile per (shape, length) that a 60-step run does not repay;
+ UNSLOTH_FLEX_ATTENTION_FOR_LARGE_HEAD_DIM="0" keeps SDPA and "1" forces flex. head_dim 256
+ routes only until SDPA reaches cuDNN; above 256 always, with patch_flex_attention_kernel_options.
+ """
+ _override = _flex_large_head_dim_override()
+ if _override is not None:
+ return _override
+ for attention_config in _text_attention_configs(config):
+ if (
+ _config_get(attention_config, "model_type", "").lower()
+ in _FLEX_LARGE_HEAD_DIM_EXCLUDED_MODELS
+ ):
+ return False
+ if _config_get(config, "model_type", "").lower() in _FLEX_LARGE_HEAD_DIM_EXCLUDED_MODELS:
+ return False
+ head_dim = _text_attention_head_dim(config)
+ if head_dim is None or head_dim <= _SDPA_FLASH_MAX_HEAD_DIM:
+ return False
+ if not _flex_kernels_fit_large_head_dim():
+ return False
+ # No cuDNN build takes head_dim > 256, so the version gate does not apply.
+ if head_dim > _FLEX_KERNEL_OPTIONS_SAFE_HEAD_DIM:
+ return True
+ return not _sdpa_reaches_cudnn_at_head_dim_256()
+
+
+# Above head_dim 256 Inductor's default flex template overflows shared memory and the launch
+# faults with `misaligned address` (torch 2.13, 2.14). Measured: 64x64 still faults, 32x32 passes.
+_FLEX_KERNEL_OPTIONS_SAFE_HEAD_DIM = 256
+# BLOCK_M/N drive the forward template, BLOCK_M1/N1/M2/N2 the two backward passes.
+_FLEX_LARGE_HEAD_DIM_KERNEL_OPTIONS = {
+ "BLOCK_M": 32,
+ "BLOCK_N": 32,
+ "BLOCK_M1": 16,
+ "BLOCK_N1": 32,
+ "BLOCK_M2": 32,
+ "BLOCK_N2": 16,
+}
+
+
+def _flex_kernel_options_for_head_dim(head_dim):
+ """The kernel_options flex needs at this head dim, or None when the default config is fine."""
+ if not isinstance(head_dim, int) or head_dim <= _FLEX_KERNEL_OPTIONS_SAFE_HEAD_DIM:
+ return None
+ return dict(_FLEX_LARGE_HEAD_DIM_KERNEL_OPTIONS)
+
+
+def _wrap_flex_attention_forward(flex_attention_forward):
+ """Add kernel_options to a registered `flex_attention` function, for large head dims only."""
+ if getattr(flex_attention_forward, "_unsloth_flex_kernel_options", False):
+ return flex_attention_forward
+
+ @functools.wraps(flex_attention_forward)
+ def unsloth_flex_attention_forward(module, query, key, value, *args, **kwargs):
+ try:
+ # Some vision callers reuse the interface with a non-4D query.
+ kernel_options = (
+ _flex_kernel_options_for_head_dim(query.shape[-1])
+ if hasattr(query, "dim") and query.dim() == 4
+ else None
+ )
+ except Exception:
+ kernel_options = None
+ if kernel_options is not None:
+ # A caller that already asked for something keeps it: only fill the gaps.
+ requested = kwargs.get("kernel_options") or {}
+ kernel_options.update(requested)
+ kwargs["kernel_options"] = kernel_options
+ return flex_attention_forward(module, query, key, value, *args, **kwargs)
+
+ unsloth_flex_attention_forward._unsloth_flex_kernel_options = True
+ unsloth_flex_attention_forward._unsloth_original_forward = flex_attention_forward
+ return unsloth_flex_attention_forward
+
+
+def patch_flex_attention_kernel_options():
+ """Wrap the registered flex_attention to pass kernel_options above head_dim 256.
+
+ Unconditional, since explicit requests and _FLEX_PREFERRED_MODELS reach flex too. Returns True
+ when the registered function is wrapped.
+ """
+ try:
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
+ except Exception:
+ return False
+
+ # The interface holds the function captured at import, so wrap what is registered.
+ try:
+ registered = ALL_ATTENTION_FUNCTIONS["flex_attention"]
+ except Exception:
+ return False
+ if registered is None:
+ return False
+
+ wrapped = _wrap_flex_attention_forward(registered)
+ if wrapped is registered:
+ return True # Already ours.
+
+ # __setitem__ covers the shared instance; register() covers the class mapping that models
+ # building their own AttentionInterface (doge) read.
+ try:
+ ALL_ATTENTION_FUNCTIONS["flex_attention"] = wrapped
+ except Exception:
+ return False
+ try:
+ register = getattr(type(ALL_ATTENTION_FUNCTIONS), "register", None)
+ if register is not None:
+ register("flex_attention", wrapped)
+ except Exception:
+ pass
+
+ try:
+ import transformers.integrations.flex_attention as _flex_module
+ if getattr(_flex_module, "flex_attention_forward", None) is registered:
+ _flex_module.flex_attention_forward = wrapped
+ except Exception:
+ pass
+
+ return True
+
+
+def _transformers_supports_attn_impl_mapping():
+ """True when Transformers accepts a per-sub-config `attn_implementation` mapping."""
+ if _ATTN_IMPL_MAPPING_SUPPORTED:
+ return _ATTN_IMPL_MAPPING_SUPPORTED[0]
+ supported = False
+ try:
+ from transformers.modeling_utils import PreTrainedModel
+ source = inspect.getsource(PreTrainedModel.set_attn_implementation)
+ supported = "isinstance(attn_implementation, dict)" in source
+ except Exception:
+ supported = False
+ _ATTN_IMPL_MAPPING_SUPPORTED.append(supported)
+ return supported
+
+
+def _text_sub_config(config):
+ """The separate text sub-config, or None when the config is text-only."""
+ getter = getattr(config, "get_text_config", None)
+ if callable(getter):
+ try:
+ text_config = getter()
+ except Exception:
+ text_config = None
+ else:
+ text_config = None
+ if text_config is None:
+ text_config = _config_get(config, "text_config", None)
+ if text_config is config:
+ return None
+ return text_config
+
+
+def _is_same_config(config, other_config):
+ """Identity, also through a forwarding proxy (unsloth_zoo wraps Gemma 4's text config), whose
+ vars() is the wrapped config's."""
+ if config is other_config:
+ return True
+ if config is None or other_config is None:
+ return False
+ try:
+ return vars(config) is vars(other_config)
+ except TypeError:
+ return False
+
+
+def _flex_attn_impl_for(config, other_attn_implementation):
+ """`flex_attention` for the decoder, `other_attn_implementation` for every other sub-config.
+
+ None when that cannot be scoped: without the Transformers 4.57+ mapping form, a plain string
+ would also move a VLM's vision tower.
+ """
+ text_config = _text_sub_config(config)
+ if not _transformers_supports_attn_impl_mapping():
+ return "flex_attention" if text_config is None else None
+ if text_config is None:
+ return "flex_attention"
+ for field_name, child_config in _config_items(config):
+ if (
+ isinstance(field_name, str)
+ and field_name.endswith("_config")
+ and _is_same_config(child_config, text_config)
+ ):
+ return {"": other_attn_implementation, field_name: "flex_attention"}
+ # An unnamed text sub-config: a plain string would move every sibling, so decline.
+ return None
+
+
+def _flex_support_anchor_class(model_class):
+ """The architecture's own PreTrainedModel base, so `_supports_flex_attn` also covers the inner
+ text model Transformers validates separately under a mapping."""
+ try:
+ from transformers.modeling_utils import PreTrainedModel
+ except Exception:
+ return model_class
+ module_name = getattr(model_class, "__module__", "")
+ anchor = model_class
+ for klass in getattr(model_class, "__mro__", ()):
+ if klass is PreTrainedModel:
+ break
+ if not isinstance(klass, type) or not issubclass(klass, PreTrainedModel):
+ continue
+ if getattr(klass, "__module__", "") == module_name:
+ anchor = klass
+ return anchor
+
+
+def _modeling_module_is_interface_based(model_class):
+ import sys
+
+ module = sys.modules.get(getattr(model_class, "__module__", "") or "", None)
+ if module is None:
+ return False
+ try:
+ source = inspect.getsource(module)
+ except Exception:
+ return False
+ return all(marker in source for marker in _FLEX_INTERFACE_MARKERS)
+
+
+def _declares_flex_support(model_class):
+ """The architecture's own `_supports_flex_attn`, or None when inherited. Not getattr:
+ PreTrainedModel sets False for every model, which hides a deliberate opt-out."""
+ try:
+ from transformers.modeling_utils import PreTrainedModel
+ except Exception:
+ return None
+ for klass in getattr(model_class, "__mro__", ()):
+ if klass is PreTrainedModel:
+ break
+ if not isinstance(klass, type):
+ continue
+ if "_supports_flex_attn" in vars(klass):
+ return vars(klass)["_supports_flex_attn"]
+ return None
+
+
+def _enable_flex_attention_support(model_class, model_type = ""):
+ """Set `_supports_flex_attn` on an interface-based architecture that leaves it unset (qwen3_5,
+ qwen3_5_moe). Returns True when flex is now permitted."""
+ if model_class is None:
+ return False
+ if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "1") == "0":
+ return False
+ if _is_flex_excluded(str(model_type).lower()):
+ return False
+ if not _modeling_module_is_interface_based(model_class):
+ return False
+ if _declares_flex_support(model_class) is False:
+ # A deliberate opt-out, e.g. T5Gemma2, whose custom masks cannot merge under flex.
+ return False
+ anchor = _flex_support_anchor_class(model_class)
+ key = f"{getattr(anchor, '__module__', '')}.{getattr(anchor, '__name__', '')}"
+ if key not in _FLEX_SUPPORT_FORCED:
+ try:
+ anchor._supports_flex_attn = True
+ except Exception:
+ return False
+ _FLEX_SUPPORT_FORCED.add(key)
+ return True
+
+
def _supports_flex_attention(model_class, config, model_type):
if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "1") == "0":
return False
@@ -654,16 +1016,26 @@ def _disable_flash_attention_if_needed(
fallback_attn_implementation = "flex_attention"
else:
fallback_attn_implementation = "eager"
+ # Only replaces an sdpa fallback; flex and eager fallbacks are left alone.
+ if (
+ fallback_attn_implementation == "sdpa"
+ and supports_flex_attention
+ and _prefers_flex_for_head_dim(config)
+ ):
+ _flex_fallback = _flex_attn_impl_for(config, "sdpa")
+ if _flex_fallback is not None:
+ fallback_attn_implementation = _flex_fallback
if _is_flash_attention_requested(requested_attn_implementation) or would_use_flash_attention:
logged_attn_implementation = (
requested_attn_implementation
if _is_flash_attention_requested(requested_attn_implementation)
else "flash_attention_2"
)
+ fallback_label = _attn_impl_label(fallback_attn_implementation)
warning_key = (
model_type,
logged_attn_implementation,
- fallback_attn_implementation,
+ fallback_label,
disable_reason,
)
if warning_key not in _FLASH_ATTENTION_DISABLED_WARNED:
@@ -671,17 +1043,44 @@ def _disable_flash_attention_if_needed(
print(
f"Unsloth: `{logged_attn_implementation}` is not supported "
f"for `{model_type}` because {disable_reason} - "
- f"defaulting to `{fallback_attn_implementation}`."
+ f"defaulting to `{fallback_label}`."
)
return _set_attn_impl(config, fallback_attn_implementation)
+def _attn_impl_label(impl):
+ """A printable, hashable name for an attention implementation, which may be a mapping."""
+ if isinstance(impl, dict):
+ named = [v for k, v in impl.items() if k != ""]
+ if len(set(named)) == 1:
+ return named[0]
+ return ", ".join(f"{k or 'default'}={v}" for k, v in impl.items())
+ return impl
+
+
+def _write_attn_impl(config, impl):
+ _config_set(config, "_attn_implementation", impl)
+ if isinstance(config, dict) or hasattr(config, "attn_implementation"):
+ _config_set(config, "attn_implementation", impl)
+
+
def _set_attn_impl(config, impl):
- if config is not None:
- _config_set(config, "_attn_implementation", impl)
- if isinstance(config, dict) or hasattr(config, "attn_implementation"):
- _config_set(config, "attn_implementation", impl)
+ if config is None:
+ return impl
+ if isinstance(impl, dict):
+ # `""` is Transformers' key for the top level and every unnamed sub-config.
+ default_impl = impl.get("")
+ if default_impl is not None:
+ _write_attn_impl(config, default_impl)
+ for field_name, sub_impl in impl.items():
+ if field_name == "":
+ continue
+ sub_config = _config_get(config, field_name, None)
+ if sub_config is not None:
+ _write_attn_impl(sub_config, sub_impl)
+ return impl
+ _write_attn_impl(config, impl)
return impl
@@ -822,6 +1221,18 @@ def resolve_attention_implementation(
and not _is_flash_excluded(model_type)
)
supports_flex_attention = _supports_flex_attention(model_class, config, model_type)
+ # Before the ladder, since every branch below reads supports_flex_attention.
+ prefers_flex_for_head_dim = _prefers_flex_for_head_dim(config)
+ if prefers_flex_for_head_dim and not supports_flex_attention:
+ if _enable_flex_attention_support(model_class, model_type):
+ supports_flex_attention = _supports_flex_attention(model_class, config, model_type)
+ # The automatic routing only replaces the sdpa fallback, but an explicit "1" forces flex
+ # over flash_attention_2 as well, when flex can be scoped to the decoder.
+ flex_forced_for_head_dim = (
+ _flex_large_head_dim_override() is True
+ and supports_flex_attention
+ and _flex_attn_impl_for(config, "sdpa") is not None
+ )
disable_reason = _get_flash_attention_disable_reason(config)
float32_is_only_disable_reason = disable_reason is None and dtype is torch.float32
if float32_is_only_disable_reason:
@@ -838,7 +1249,12 @@ def resolve_attention_implementation(
elif prefers_flex_attention and supports_flex_attention:
# _FLEX_PREFERRED_MODELS (the gemma3 family) prefer flex_attention over flash; a caller can still override with requested_attn_implementation="sdpa".
attn_impl = _set_attn_impl(config, "flex_attention")
- elif not flash_attention_disabled and HAS_FLASH_ATTENTION and supports_flash_attention:
+ elif (
+ not flash_attention_disabled
+ and HAS_FLASH_ATTENTION
+ and supports_flash_attention
+ and not flex_forced_for_head_dim
+ ):
attn_impl = _set_attn_impl(config, "flash_attention_2")
elif flash_attention_disabled:
attn_impl = _disable_flash_attention_if_needed(
@@ -855,6 +1271,12 @@ def resolve_attention_implementation(
disable_reason = disable_reason,
honor_config_attn_implementation = not float32_is_only_disable_reason,
)
+ elif prefers_flex_for_head_dim and supports_flex_attention:
+ _flex_impl = _flex_attn_impl_for(config, "sdpa" if supports_sdpa else "eager")
+ if _flex_impl is None:
+ attn_impl = _set_attn_impl(config, "sdpa" if supports_sdpa else "eager")
+ else:
+ attn_impl = _set_attn_impl(config, _flex_impl)
elif supports_sdpa:
attn_impl = _set_attn_impl(config, "sdpa")
elif supports_flex_attention:
@@ -4791,3 +5213,9 @@ if (
transformers.integrations.bitsandbytes.should_convert_module = patched_should_convert_module
except Exception:
pass
+
+
+try:
+ patch_flex_attention_kernel_options()
+except Exception:
+ pass