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.

head_dim 512 attention: leave mask plus is_causal to SDPA, fall back on mask-scan OOM (#14691)

Daniel Han36f8f79df834
diff --git a/tests/test_large_head_attention.py b/tests/test_large_head_attention.py
index e90195fed87..b9bd2cef347 100644
--- a/tests/test_large_head_attention.py
+++ b/tests/test_large_head_attention.py
@@ -502,6 +502,40 @@ def test_router_skips_the_mask_scan_when_it_cannot_use_the_result(monkeypatch):
assert len(calls) == 1
[email protected](not _SM80, reason = "the router engages on sm80+ only")
+def test_router_leaves_an_explicit_is_causal_beside_a_mask_to_sdpa():
+ calls, original = _sentinel()
+ router = LH._make_router(original)
+ dtype = _cuda_dtype()
+ q = torch.randn(1, 4, 24, 512, device = "cuda", dtype = dtype)
+ kv = torch.randn(1, 2, 24, 512, device = "cuda", dtype = dtype)
+ allowed = torch.ones(1, 1, 24, 24, device = "cuda", dtype = torch.bool)
+ before = LH.LARGE_HEAD_ENGAGED["calls"]
+ assert router(_Module(), q, kv, kv, allowed, is_causal = True)[0] == "original"
+ assert calls[-1]["is_causal"] is True and LH.LARGE_HEAD_ENGAGED["calls"] == before
+ causal = _causal(24).cuda()[None, None]
+ assert router(_Module(), q, kv, kv, causal)[0] != "original"
+ assert router(_Module(), q, kv, kv, causal, is_causal = False)[0] != "original"
+ assert LH.LARGE_HEAD_ENGAGED["calls"] == before + 2 and len(calls) == 1
+
+
[email protected](not _SM80, reason = "the router engages on sm80+ only")
+def test_router_falls_back_to_sdpa_on_mask_scan_oom(monkeypatch):
+ def oom(*args, **kwargs):
+ raise torch.cuda.OutOfMemoryError("CUDA out of memory.")
+
+ calls, original = _sentinel()
+ router = LH._make_router(original)
+ device, dtype = torch.device("cuda", torch.cuda.current_device()), _cuda_dtype()
+ assert LH._self_check(device, dtype) is True
+ monkeypatch.setattr(LH, "intervals_from_mask", oom)
+ q = torch.randn(1, 4, 24, 512, device = "cuda", dtype = dtype)
+ kv = torch.randn(1, 2, 24, 512, device = "cuda", dtype = dtype)
+ before = LH.LARGE_HEAD_ENGAGED["fallback"]
+ assert router(_Module(), q, kv, kv, _causal(24).cuda()[None, None])[0] == "original"
+ assert LH.LARGE_HEAD_ENGAGED["fallback"] == before + 1 and len(calls) == 1
+
+
def test_pre_ampere_keeps_sdpa_without_compiling(monkeypatch):
def kernel(*args, **kwargs):
raise AssertionError("kernel compiled on sm75")
diff --git a/unsloth/kernels/large_head_attention.py b/unsloth/kernels/large_head_attention.py
index 95b7eb32d2f..f39638b788e 100644
--- a/unsloth/kernels/large_head_attention.py
+++ b/unsloth/kernels/large_head_attention.py
@@ -887,6 +887,10 @@ def _make_router(original):
and not dropout
# The kernel only reads the mask's structure, so a trainable mask would get no grad.
and not (torch.is_tensor(attention_mask) and attention_mask.requires_grad)
+ # transformers 4.x pairs is_causal with a mask (SDPA applies both); intervals carry only the mask.
+ and not (
+ attention_mask is not None and is_causal is not None and is_causal is not False
+ )
and kwargs.get("position_bias", None) is None
and kwargs.get("softcap", None) is None
and not kwargs.get("output_attentions", False)
@@ -913,7 +917,11 @@ def _make_router(original):
# Reading a mask's structure needs a host sync; compiled graphs keep SDPA. Inference
# masks cannot cache the verdict, so they are rescanned per layer: one sync each, only
# at prefill (decode never qualifies), cheaper than SDPA's repeated KV heads and mask.
- intervals = intervals_from_mask(attention_mask, B, S)
+ try:
+ intervals = intervals_from_mask(attention_mask, B, S)
+ except torch.cuda.OutOfMemoryError:
+ # The mask scan allocates row chunks; near capacity, SDPA below decides as before.
+ LARGE_HEAD_ENGAGED["fallback"] += 1
if compiling or capturing:
checked = _SELF_CHECK.get((str(query.device), query.dtype), False)
elif intervals is not None: