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.

Gemma 3: keep flex attention only where its head_dim 256 template fits the card (#14670)

Daniel Han137a0932bff5
diff --git a/tests/test_flex_preferred_shared_memory.py b/tests/test_flex_preferred_shared_memory.py
new file mode 100644
index 00000000000..207aaf91ae2
--- /dev/null
+++ b/tests/test_flex_preferred_shared_memory.py
@@ -0,0 +1,97 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""Gemma 3 keeps flex attention only where its head_dim 256 template fits the card (#14439)."""
+
+from types import SimpleNamespace
+from unittest import mock
+
+import pytest
+
+import unsloth # noqa: F401
+from transformers.utils import import_utils
+
+from unsloth.models import _utils
+
+
+class SupportsFlex:
+ _supports_flash_attn_2 = True
+ _supports_flex_attn = True
+ _supports_sdpa = True
+
+
+L4 = 101376
+A100 = 166912
+B200 = 232448
+
+
+def _gemma3(head_dim = 256, model_type = "gemma3_text"):
+ return SimpleNamespace(
+ model_type = model_type, head_dim = head_dim, num_attention_heads = 4, attention_dropout = 0
+ )
+
+
+def cards(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_ENABLE_FLEX_ATTENTION", "1")
+ monkeypatch.setattr(import_utils, "is_torch_flex_attn_available", lambda: True, raising = False)
+ monkeypatch.setattr(_utils, "HAS_FLASH_ATTENTION", False)
+ monkeypatch.setattr(_utils, "_flex_attention_gpu_is_supported", lambda: True)
+ monkeypatch.setattr(_utils.torch.version, "hip", None, raising = False)
+
+ def install(*shared_memory):
+ monkeypatch.setattr(_utils.torch.cuda, "is_available", lambda: bool(shared_memory))
+ monkeypatch.setattr(_utils.torch.cuda, "device_count", lambda: len(shared_memory))
+ monkeypatch.setattr(
+ _utils.torch.cuda,
+ "get_device_properties",
+ lambda index = 0: SimpleNamespace(shared_memory_per_block_optin = shared_memory[index]),
+ )
+
+ return install
+
+
+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):
+ cards(L4)
+ config = _gemma3()
+ assert _resolve(config) == "eager"
+ assert config._attn_implementation == "eager"
+
+
[email protected]("shared_memory", [A100, B200])
+def test_gemma3_keeps_flex_where_the_template_fits(cards, shared_memory):
+ cards(shared_memory)
+ assert _resolve(_gemma3()) == "flex_attention"
+
+
+def test_a_mixed_box_follows_its_smallest_card(cards):
+ cards(A100, L4)
+ assert _resolve(_gemma3()) == "eager"
+
+
+def test_gemma3_27b_head_dim_128_keeps_flex(cards):
+ cards(L4)
+ assert _resolve(_gemma3(head_dim = 128)) == "flex_attention"
+
+
+def test_models_that_do_not_prefer_flex_are_untouched(cards):
+ cards(L4)
+ config = SimpleNamespace(
+ model_type = "llama", head_dim = 256, num_attention_heads = 4, attention_dropout = 0
+ )
+ assert _utils._supports_flex_attention(SupportsFlex, config, "llama") is True
+
+
+def test_rocm_cpu_and_a_failing_probe_keep_flex(cards, monkeypatch):
+ cards() # no CUDA device
+ assert _resolve(_gemma3()) == "flex_attention"
+ cards(L4)
+ monkeypatch.setattr(_utils.torch.version, "hip", "6.2.0", raising = False)
+ assert _resolve(_gemma3()) == "flex_attention"
+ monkeypatch.setattr(_utils.torch.version, "hip", None, raising = False)
+ with mock.patch.object(
+ _utils.torch.cuda, "get_device_properties", side_effect = RuntimeError("probe")
+ ):
+ assert _resolve(_gemma3()) == "flex_attention"
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 46d449572ba..65de0380a32 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -1301,6 +1301,29 @@ def _enable_flex_attention_support(model_class, model_type = ""):
return True
+# Inductor's head_dim 256 flex template; with less, Gemma 3's flex backward is wrong (#14439).
+_FLEX_TEMPLATE_HEAD_DIM_256_SHARED_MEMORY = 151552
+
+
+def _flex_preferred_fits(config):
+ """False when a visible CUDA card lacks that shared memory; fails open on ROCm / no CUDA."""
+ head_dim = _text_attention_head_dim(config)
+ if head_dim is None or not (
+ _SDPA_FLASH_MAX_HEAD_DIM < head_dim <= _FLEX_KERNEL_OPTIONS_SAFE_HEAD_DIM
+ ):
+ return True
+ try:
+ if getattr(torch.version, "hip", None) or not torch.cuda.is_available():
+ return True
+ return all(
+ torch.cuda.get_device_properties(index).shared_memory_per_block_optin
+ >= _FLEX_TEMPLATE_HEAD_DIM_256_SHARED_MEMORY
+ for index in range(torch.cuda.device_count())
+ )
+ except Exception:
+ return True
+
+
def _supports_flex_attention(model_class, config, model_type):
if os.environ.get("UNSLOTH_ENABLE_FLEX_ATTENTION", "1") == "0":
return False
@@ -1310,6 +1333,8 @@ def _supports_flex_attention(model_class, config, model_type):
return False
if not _flex_attention_gpu_is_supported():
return False
+ if _config_prefers_flex_attention(config) and not _flex_preferred_fits(config):
+ return False
for attention_config in _iter_attention_configs(config):
attention_dropout = _config_get(attention_config, "attention_dropout", 0) or 0
if attention_dropout != 0: