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.

SDPA decode: keep the caller's backend policy when avoiding cuDNN (#15525)

Daniel Hanc1dc69dd0b18
diff --git a/tests/test_sdpa_cudnn_length_bucket_masked.py b/tests/test_sdpa_cudnn_length_bucket_masked.py
index 4524eac2bb0..3eac3b120a4 100644
--- a/tests/test_sdpa_cudnn_length_bucket_masked.py
+++ b/tests/test_sdpa_cudnn_length_bucket_masked.py
@@ -309,9 +309,11 @@ def test_decode_sdpa_pins_only_where_torch_picks_cudnn(monkeypatch, masked):
real = ad._sdpa_kernel
monkeypatch.setattr(ad, "_sdpa_kernel", lambda b: entered.append(1) or real(b))
monkeypatch.setattr(ad, "_NO_CUDNN_DECODE", frozenset({q.device.index}))
- for picks in (False, True):
- monkeypatch.setattr(ad, "_decode_picks_cudnn", lambda *a, p = picks: p)
- ad.decode_scaled_dot_product_attention(q, kv, kv, attn_mask = mask)
+ # torch's default policy (importing vLLM disables cuDNN SDPA process wide).
+ with real(_policy(_ALL_BACKENDS)):
+ for picks in (False, True):
+ monkeypatch.setattr(ad, "_decode_picks_cudnn", lambda *a, p = picks: p)
+ ad.decode_scaled_dot_product_attention(q, kv, kv, attn_mask = mask)
assert entered == [1]
@@ -322,3 +324,131 @@ def test_decode_no_cudnn_devices(monkeypatch):
assert ad._decode_no_cudnn_devices() == frozenset({1, 2})
monkeypatch.setenv("UNSLOTH_SDPA_DECODE_CUDNN", "1")
assert ad._decode_no_cudnn_devices() == frozenset()
+
+
+_ALL_BACKENDS = ("FLASH_ATTENTION", "EFFICIENT_ATTENTION", "MATH", "CUDNN_ATTENTION")
+
+
+def _policy(names):
+ from torch.nn.attention import SDPBackend
+ return [getattr(SDPBackend, n) for n in names]
+
+
+ "policy",
+ [
+ None, # torch's default: every backend enabled
+ ("MATH",),
+ ("MATH", "CUDNN_ATTENTION"),
+ ("EFFICIENT_ATTENTION", "CUDNN_ATTENTION"),
+ ("CUDNN_ATTENTION",),
+ ],
+)
+def test_decode_pin_keeps_caller_backend_policy(monkeypatch, policy):
+ """The decode pin only removes cuDNN from the caller's backends: it never enables a backend the
+ caller's sdpa_kernel disabled, and a cuDNN-only policy is left as is."""
+ if not torch.cuda.is_available() or ad._CUDNN_CHOICE is None:
+ pytest.skip("needs CUDA and torch's cuDNN SDPA backend")
+ from torch.nn.attention import sdpa_kernel
+
+ cuda = torch.backends.cuda
+ flags = lambda: (
+ cuda.flash_sdp_enabled(),
+ cuda.mem_efficient_sdp_enabled(),
+ cuda.math_sdp_enabled(),
+ cuda.cudnn_sdp_enabled(),
+ )
+ seen = []
+ monkeypatch.setattr(
+ F, "scaled_dot_product_attention", lambda q, *a, **k: seen.append(flags()) or q
+ )
+ monkeypatch.setattr(ad, "_decode_picks_cudnn", lambda *a: True)
+ q = torch.randn(2, 4, 1, 64, device = "cuda", dtype = torch.bfloat16)
+ kv = torch.randn(2, 4, 300, 64, device = "cuda", dtype = torch.bfloat16)
+ monkeypatch.setattr(ad, "_NO_CUDNN_DECODE", frozenset({q.device.index}))
+ with sdpa_kernel(_policy(policy or _ALL_BACKENDS)):
+ caller = flags()
+ ad.decode_scaled_dot_product_attention(q, kv, kv)
+ if policy == ("CUDNN_ATTENTION",):
+ assert seen == [caller]
+ else:
+ assert seen == [(*caller[:3], False)]
+
+
+def _attention_ops(fn, *args):
+ fn(*args)
+ with torch.profiler.profile(activities = [torch.profiler.ProfilerActivity.CPU]) as prof:
+ fn(*args)
+ keys = {e.key for e in prof.key_averages()}
+ return {k for k in keys if k.startswith("aten::_scaled_dot_product_") or k == "aten::bmm"}
+
+
[email protected]("policy", [None, ("MATH",), ("MATH", "CUDNN_ATTENTION")]) # None: all
+def test_compiled_decode_keeps_caller_backend_policy(monkeypatch, policy):
+ """Traced decode reads the caller's policy at trace time (as SDPA's own pick does): a math-only
+ policy runs math in a fullgraph, dynamic=True graph, with no graph break."""
+ import torch._dynamo
+ import torch._inductor.config as inductor_config
+ from torch._dynamo.utils import counters
+ from torch.nn.attention import sdpa_kernel
+
+ if not torch.cuda.is_available() or ad._CUDNN_CHOICE is None:
+ pytest.skip("needs CUDA and torch's cuDNN SDPA backend")
+
+ q = torch.randn(2, 4, 1, 64, device = "cuda", dtype = torch.float16)
+ monkeypatch.setattr(ad, "_NO_CUDNN_DECODE", frozenset({q.device.index}))
+ torch._dynamo.reset()
+ counters.clear()
+ compiled = torch.compile(ad.decode_scaled_dot_product_attention, fullgraph = True, dynamic = True)
+ # A cached graph from another policy would hide the trace-time read.
+ no_cache = dict(fx_graph_cache = False)
+ if hasattr(inductor_config, "autograd_cache"):
+ no_cache["autograd_cache"] = False
+ with inductor_config.patch(no_cache), sdpa_kernel(_policy(policy or _ALL_BACKENDS)):
+ for L in (128, 300):
+ kv = torch.randn(2, 4, L, 64, device = "cuda", dtype = torch.float16)
+ ops = _attention_ops(compiled, q, kv, kv)
+ torch.testing.assert_close(
+ compiled(q, kv, kv), F.scaled_dot_product_attention(q, kv, kv), atol = 2e-3, rtol = 2e-3
+ )
+ assert "aten::_scaled_dot_product_cudnn_attention" not in ops, ops
+ if policy is None:
+ assert "aten::bmm" not in ops, ops # default policy: a fused kernel, as on main
+ else:
+ assert ops == {"aten::bmm"}, ops
+ assert not counters["graph_break"], dict(counters["graph_break"])
+ assert counters["stats"]["unique_graphs"] == 1, dict(counters["stats"])
+
+
+def test_decode_picks_cudnn_cache_keys_on_every_backend_flag(monkeypatch):
+ """A later sdpa_kernel toggle of flash / efficient / math or the priority order re-probes."""
+ if not torch.cuda.is_available() or ad._CUDNN_CHOICE is None:
+ pytest.skip("needs CUDA and torch's cuDNN SDPA backend")
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ probed = []
+
+ def probe(*args, **kwargs):
+ probed.append(args[9])
+ return ad._CUDNN_CHOICE, ad._CUDNN_CHOICE
+
+ monkeypatch.setattr(ad, "_sdpa_gqa_choices", probe)
+ ad._DECODE_PICKS_CUDNN.clear()
+ q = torch.randn(2, 4, 1, 64, device = "cuda", dtype = torch.bfloat16)
+ kv = torch.randn(2, 4, 300, 64, device = "cuda", dtype = torch.bfloat16)
+ policies = (
+ [
+ SDPBackend.FLASH_ATTENTION,
+ SDPBackend.EFFICIENT_ATTENTION,
+ SDPBackend.MATH,
+ SDPBackend.CUDNN_ATTENTION,
+ ],
+ [SDPBackend.MATH, SDPBackend.CUDNN_ATTENTION],
+ [SDPBackend.EFFICIENT_ATTENTION, SDPBackend.CUDNN_ATTENTION],
+ [SDPBackend.FLASH_ATTENTION, SDPBackend.CUDNN_ATTENTION],
+ )
+ for backends in policies * 2:
+ with sdpa_kernel(backends):
+ ad._decode_picks_cudnn(q, kv, None, False)
+ assert len(probed) == len(policies) and len(set(probed)) == len(policies), probed
+ ad._DECODE_PICKS_CUDNN.clear()
diff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.py
index 97314af6cbb..5b0ac7f67b6 100644
--- a/unsloth/utils/attention_dispatch.py
+++ b/unsloth/utils/attention_dispatch.py
@@ -237,18 +237,23 @@ def _cudnn_length_bucketed_sdpa(
if attn_mask is None:
out = scaled_dot_product_attention(Q, K, V, is_causal = True, **kwargs)
return out[..., :q_len, :]
+ padded = _padded_bucket_mask(attn_mask, pad)
+ out = scaled_dot_product_attention(Q, K, V, attn_mask = padded, **kwargs)
+ return out[..., :q_len, :]
+
+
+def _padded_bucket_mask(attn_mask, pad):
# Padded query rows attend everything (no fully masked row) and are sliced off; padded keys are masked.
- rows = attn_mask.shape[-2]
- shape = (*attn_mask.shape[:-2], rows if rows == 1 else rows + pad, q_len + pad)
+ rows, k_len = attn_mask.shape[-2], attn_mask.shape[-1]
+ shape = (*attn_mask.shape[:-2], rows if rows == 1 else rows + pad, k_len + pad)
if attn_mask.dtype == torch.bool:
padded = attn_mask.new_ones(shape)
- padded[..., :rows, q_len:] = False
+ padded[..., :rows, k_len:] = False
else:
padded = attn_mask.new_zeros(shape)
- padded[..., :rows, q_len:] = torch.finfo(attn_mask.dtype).min
- padded[..., :rows, :q_len] = attn_mask
- out = scaled_dot_product_attention(Q, K, V, attn_mask = padded, **kwargs)
- return out[..., :q_len, :]
+ padded[..., :rows, k_len:] = torch.finfo(attn_mask.dtype).min
+ padded[..., :rows, :k_len] = attn_mask
+ return padded
def _rerouted_sdpa(*args, **kwargs):
@@ -262,16 +267,22 @@ def _rerouted_sdpa(*args, **kwargs):
# Module level: reading SDPBackend's attributes while traced breaks the graph.
try:
from torch.nn.attention import SDPBackend as _SDPBackend, sdpa_kernel as _sdpa_kernel
+
_XFORMERS_LIKE_BACKENDS = [
_SDPBackend.FLASH_ATTENTION,
_SDPBackend.EFFICIENT_ATTENTION,
_SDPBackend.MATH,
]
+ # Decode pins, indexed by _decode_cudnn_free_index: the caller's enabled flash / efficient / math.
+ _DECODE_CUDNN_FREE_BACKENDS = (None,) + tuple(
+ [b for j, b in enumerate(_XFORMERS_LIKE_BACKENDS) if i >> j & 1] for i in range(1, 8)
+ )
_CUDNN_CHOICE = (
int(_SDPBackend.CUDNN_ATTENTION) if hasattr(_SDPBackend, "CUDNN_ATTENTION") else None
)
except Exception:
_rerouted_sdpa = scaled_dot_product_attention
+ _DECODE_CUDNN_FREE_BACKENDS = (None,) * 8
_CUDNN_CHOICE = None
@@ -329,6 +340,17 @@ _DECODE_PICKS_CUDNN = {}
def _decode_picks_cudnn(query, key, attn_mask, enable_gqa):
"""Whether torch would pick cuDNN for this decode call (else sdpa_kernel is ~25 us of overhead)."""
+ cuda = torch.backends.cuda
+ # Everything torch's pick reads: toggling any backend or the priority order re-probes.
+ backends = (
+ cuda.flash_sdp_enabled(),
+ cuda.cudnn_sdp_enabled(),
+ cuda.mem_efficient_sdp_enabled(),
+ cuda.math_sdp_enabled(),
+ tuple(getattr(torch._C, "_get_sdp_priority_order", tuple)()),
+ torch.are_deterministic_algorithms_enabled(),
+ torch.is_deterministic_algorithms_warn_only_enabled(),
+ )
cache_key = (
query.device.index,
query.dtype,
@@ -337,18 +359,10 @@ def _decode_picks_cudnn(query, key, attn_mask, enable_gqa):
key.shape[1],
attn_mask is not None,
enable_gqa,
- torch.backends.cuda.cudnn_sdp_enabled(),
+ backends,
)
picks = _DECODE_PICKS_CUDNN.get(cache_key)
if picks is None:
- cuda = torch.backends.cuda
- backends = (
- cuda.flash_sdp_enabled(),
- cuda.cudnn_sdp_enabled(),
- cuda.mem_efficient_sdp_enabled(),
- cuda.math_sdp_enabled(),
- tuple(getattr(torch._C, "_get_sdp_priority_order", tuple)()),
- )
gqa, mha = _sdpa_gqa_choices(
str(query.device), query.dtype, query.shape[-1], query.shape[1], key.shape[1],
False, attn_mask is not None, False, 0.0, backends, single_query = True,
@@ -374,11 +388,27 @@ def decode_scaled_dot_product_attention(query, key, value, *args, **kwargs):
)
) # fmt: skip
):
- with _sdpa_kernel(_XFORMERS_LIKE_BACKENDS):
- return F.scaled_dot_product_attention(query, key, value, *args, **kwargs)
+ # Only the caller's own non-cuDNN backends (sdpa_kernel([MATH]) stays math); a cuDNN-only
+ # policy is left as is.
+ backends = _DECODE_CUDNN_FREE_BACKENDS[_decode_cudnn_free_index()]
+ if backends is not None:
+ with _sdpa_kernel(backends):
+ return F.scaled_dot_product_attention(query, key, value, *args, **kwargs)
return F.scaled_dot_product_attention(query, key, value, *args, **kwargs)
+def _decode_cudnn_free_index():
+ """Bit 0 / 1 / 2: flash / efficient / math SDPA enabled; 0 when cuDNN is disabled (nothing to avoid)."""
+ cuda = torch.backends.cuda
+ if not cuda.cudnn_sdp_enabled():
+ return 0
+ return (
+ (1 if cuda.flash_sdp_enabled() else 0)
+ | (2 if cuda.mem_efficient_sdp_enabled() else 0)
+ | (4 if cuda.math_sdp_enabled() else 0)
+ )
+
+
decode_scaled_dot_product_attention.__doc__ = (
F.scaled_dot_product_attention.__doc__ or ""
) + decode_scaled_dot_product_attention.__doc__
@@ -683,6 +713,8 @@ def _constant_probe(fn):
_sdpa_backend_state = _constant_probe(_sdpa_backend_state)
_sdpa_masked_choice = _constant_probe(_sdpa_masked_choice)
+# Traced: read under the caller's sdpa_kernel at trace time, like SDPA's own backend pick.
+_decode_cudnn_free_index = _constant_probe(_decode_cudnn_free_index)
@functools.lru_cache(maxsize = 128)