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.

Attention: let the SDPA GQA probe trace under torch.compile(dynamic=True) (#14779)

Daniel Han32650d2f17b4
diff --git a/tests/test_attention_dispatch_compiled_block.py b/tests/test_attention_dispatch_compiled_block.py
index 40d0bfe6414..1a9c15b9ade 100644
--- a/tests/test_attention_dispatch_compiled_block.py
+++ b/tests/test_attention_dispatch_compiled_block.py
@@ -81,3 +81,103 @@ def test_rerouted_xformers_keeps_the_fp32_downcast(monkeypatch):
torch.testing.assert_close(
out.float().reshape(1, 8, 4, 16), _reference(Q, K, V), atol = 3e-2, rtol = 3e-2
)
+
+
+def _compile_counts(fn, *inputs, dynamic):
+ """Run fn compiled fullgraph over each input tuple; return (outputs, unique graphs, graph breaks)."""
+ from torch._dynamo.utils import counters
+
+ torch._dynamo.reset()
+ counters.clear()
+ compiled = torch.compile(fn, fullgraph = True, backend = "eager", dynamic = dynamic)
+ outs = [compiled(*args) for args in inputs]
+ return outs, counters["stats"]["unique_graphs"], sum(counters["graph_break"].values())
+
+
[email protected]("dynamic", [False, True])
+def test_gqa_probe_takes_symbolic_head_sizes(dynamic):
+ # dynamic=True makes head_dim and the head counts SymInts; the constant-result probe must still trace.
+ def state(Q, K):
+ takes = ad._sdpa_gqa_state(str(Q.device), Q.dtype, Q.shape[-1], Q.shape[1], K.shape[1], False, True)
+ return Q.sum() + K.sum() + (1 if takes else 2)
+
+ inputs = [(torch.zeros(b, 8, t, 64), torch.zeros(b, 2, t, 64)) for b, t in ((3, 10), (5, 12), (6, 14))]
+ outs, graphs, breaks = _compile_counts(state, *inputs, dynamic = dynamic)
+ want = 1 if ad._sdpa_gqa_state("cpu", torch.float32, 64, 8, 2, False, True) else 2
+ assert [out.item() for out in outs] == [want] * 3
+ assert breaks == 0
+ # Batch and length stay dynamic: one graph when dynamic, one per shape when static. Sizes avoid
+ # the head counts: duck sizing would share a symbol, and the specialised head count with it.
+ assert graphs == (1 if dynamic else 3)
+
+
[email protected]("dynamic", [False, True])
+def test_varlen_probe_takes_symbolic_head_sizes(dynamic):
+ def beats(Q, K):
+ return Q.sum() + K.sum() + (1 if ad._torch_varlen_beats_segments(Q, K, (5, 3), 2, True) else 2)
+
+ Q, K = torch.zeros(1, 4, 8, 16), torch.zeros(1, 2, 8, 16)
+ outs, _, breaks = _compile_counts(beats, (Q, K), dynamic = dynamic)
+ want = 1 if ad._torch_varlen_beats_segments(Q, K, (5, 3), 2, True) else 2
+ assert [out.item() for out in outs] == [want]
+ assert breaks == 0
+
+
+def _has_real_cuda():
+ try:
+ from real_accelerator import has_real_cuda # tests/_shared, on sys.path via tests/conftest.py
+ except Exception:
+ return torch.cuda.is_available()
+ return has_real_cuda()
+
+
[email protected](not _has_real_cuda(), reason = "needs a real CUDA device")
[email protected]("dynamic", [False, True])
+def test_cuda_gqa_sdpa_compiles_fullgraph(dynamic):
+ # The CUDA GQA probe runs only on CUDA tensors: noncausal bf16 GQA, no mask, forward + backward.
+ def attend(Q, K, V):
+ bsz, n_heads, q_len, head_dim = Q.shape
+ config = ad.AttentionConfig(
+ backend = ad.SDPA, n_kv_heads = K.shape[1], n_groups = n_heads // K.shape[1]
+ )
+ context = ad.AttentionContext(
+ bsz = bsz,
+ q_len = q_len,
+ kv_seq_len = K.shape[-2],
+ n_heads = n_heads,
+ head_dim = head_dim,
+ requires_grad = True,
+ seq_info = None,
+ attention_mask = None,
+ causal_mask = None,
+ is_causal = False,
+ sliding_window = None,
+ )
+ out = ad.run_attention(config = config, context = context, Q = Q, K = K, V = V)
+ # Flatten the heads as the o_proj input does (torch 2.13's dynamic-shape cuDNN backward
+ # mishandles a transposed incoming gradient, independent of the dispatcher).
+ return out.reshape(bsz, q_len, n_heads * head_dim)
+
+ from torch._dynamo.utils import counters
+
+ torch._dynamo.reset()
+ counters.clear()
+ compiled = torch.compile(attend, fullgraph = True, dynamic = dynamic)
+ shapes = ((3, 32), (5, 48), (3, 40)) # no size equal to a head count (duck sizing)
+ for bsz, q_len in shapes:
+ g = torch.Generator(device = "cuda").manual_seed(q_len)
+ Q, K, V = (
+ torch.randn(bsz, h, q_len, 64, device = "cuda", generator = g, dtype = torch.bfloat16).requires_grad_()
+ for h in (8, 2, 2)
+ )
+ out = compiled(Q, K, V)
+ out.float().square().sum().backward()
+ Qe, Ke, Ve = (t.detach().clone().requires_grad_() for t in (Q, K, V))
+ ref = attend(Qe, Ke, Ve)
+ ref.float().square().sum().backward()
+ torch.testing.assert_close(out, ref, atol = 2e-2, rtol = 2e-2)
+ for got, want in zip((Q, K, V), (Qe, Ke, Ve)):
+ torch.testing.assert_close(got.grad, want.grad, atol = 2e-1, rtol = 2e-2)
+ assert sum(counters["graph_break"].values()) == 0
+ # Head sizes are specialised, batch and length are not: dynamic compiles once.
+ assert counters["stats"]["unique_graphs"] == (1 if dynamic else len(shapes))
diff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.py
index 753e8c324dd..3e2a9ea1f4e 100644
--- a/unsloth/utils/attention_dispatch.py
+++ b/unsloth/utils/attention_dispatch.py
@@ -15,6 +15,7 @@
from __future__ import annotations
import functools
+import operator
import os
from dataclasses import dataclass
from typing import Any, Optional, Tuple
@@ -265,8 +266,31 @@ def _sdpa_backend_state(device, dtype, head_dim, n_heads, n_kv_heads, is_causal,
return backends[0], choice
-if hasattr(torch.compiler, "assume_constant_result"):
- _sdpa_backend_state = torch.compiler.assume_constant_result(_sdpa_backend_state)
+def _constant_probe(fn):
+ """torch.compiler.assume_constant_result for a shape probe. Dynamo can only hand it Python
+ constants, and dynamic=True makes head counts / head_dim SymInts, so those are specialised
+ (operator.index guards them) first: they are fixed per model, batch and length stay dynamic.
+ Plain ints pass through unchanged, so eager and static-shape answers are the same."""
+ if not hasattr(torch.compiler, "assume_constant_result"):
+ return fn
+ # Marks fn itself, so no functools.wraps: copying its __dict__ would mark the wrapper too.
+ constant = torch.compiler.assume_constant_result(fn)
+
+ def probe(*args, **kwargs):
+ concrete = []
+ for arg in args:
+ # Dynamo reports a SymInt as an int; index() on a plain int is the identity.
+ if isinstance(arg, (int, torch.SymInt)) and not isinstance(arg, bool):
+ arg = operator.index(arg)
+ concrete.append(arg)
+ return constant(*concrete, **kwargs)
+
+ probe.__name__, probe.__qualname__, probe.__doc__ = fn.__name__, fn.__qualname__, fn.__doc__
+ probe.__wrapped__ = fn
+ return probe
+
+
+_sdpa_backend_state = _constant_probe(_sdpa_backend_state)
@functools.lru_cache(maxsize = 128)
@@ -378,8 +402,7 @@ def _sdpa_gqa_state(
return not (gqa == math and mha not in (math, -1))
-if hasattr(torch.compiler, "assume_constant_result"):
- _sdpa_gqa_state = torch.compiler.assume_constant_result(_sdpa_gqa_state)
+_sdpa_gqa_state = _constant_probe(_sdpa_gqa_state)
def _sdpa_takes_gqa(