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.

Packed attention: varlen probes under fullgraph + dynamic=True compile (#15891)

Daniel Han04303567cb4e
diff --git a/tests/test_hf_packed_attention.py b/tests/test_hf_packed_attention.py
index 4e6f6e3550e..aafc2eea525 100644
--- a/tests/test_hf_packed_attention.py
+++ b/tests/test_hf_packed_attention.py
@@ -1621,6 +1621,154 @@ def test_traced_block_varlen_call_stays_in_the_graph(monkeypatch, in_graph):
assert hpa.BLOCK_VARLEN_KWARG not in seen["orig_kwargs"]
[email protected]("in_graph", [True, False])
+def test_traced_packed_probes_take_symbolic_head_dims(monkeypatch, in_graph):
+ """dynamic = True head sizes reach the probes as plain ints; the sequence dim stays dynamic."""
+ from torch._dynamo.testing import CompileCounter
+
+ keys = []
+
+ def probe(name):
+ def run(*key):
+ keys.append((name, key))
+ return in_graph if name == "varlen" else False
+
+ return run
+
+ def gqa_sdpa(
+ module,
+ q,
+ k,
+ v,
+ mask,
+ scaling = None,
+ **kwargs,
+ ):
+ out = torch.nn.functional.scaled_dot_product_attention(
+ q, k, v, attn_mask = mask, scale = scaling, enable_gqa = True
+ )
+ return out.transpose(1, 2), None
+
+ hpa._ORIG_SDPA[0] = gqa_sdpa
+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)
+ _block_flag(monkeypatch, True)
+ monkeypatch.setattr(hpa, "_static_window", lambda *args: None)
+ monkeypatch.setattr(hpa, "_VARLEN_IN_GRAPH", {})
+ monkeypatch.setattr(hpa, "_LEAVES_BLOCK", {})
+ monkeypatch.setattr(hpa, "_varlen_in_graph_probe", probe("varlen"))
+ monkeypatch.setattr(hpa, "_leaves_block_probe", probe("leaves"))
+ monkeypatch.setattr(
+ hpa,
+ "_flash_varlen",
+ lambda q, k, v, cu, m, scale, window: q.transpose(1, 2) * scale,
+ )
+ module = types.SimpleNamespace(is_causal = True, num_key_value_groups = 2, training = True)
+ torch._dynamo.reset()
+ torch._dynamo.utils.counters.clear()
+ counter = CompileCounter()
+ fn = torch.compile(
+ lambda q, k, mask, psl, cu: hpa._sdpa_packed_varlen(
+ module, q, k, k, mask, packed_seq_lengths = psl, **{hpa.BLOCK_VARLEN_KWARG: (cu, 3)}
+ )[0],
+ backend = counter,
+ fullgraph = True,
+ dynamic = True,
+ )
+ # Segment counts and lengths avoid the head sizes (4, 2, 16): duck sizing would tie them.
+ for lengths in ([2, 2, 2], [2, 5, 4, 1, 1], [7, 1, 1, 6, 2, 3]):
+ T = sum(lengths)
+ q = torch.randn(1, 4, T, 16)
+ k = torch.randn(1, 2, T, 16)
+ mask, psl = _block_causal(lengths), torch.tensor(lengths, dtype = torch.int32)
+ cu = torch.tensor([0, *torch.tensor(lengths).cumsum(0).tolist()], dtype = torch.int32)
+ out = fn(q, k, mask, psl, cu)
+ if in_graph:
+ torch.testing.assert_close(out, q.transpose(1, 2) * 16**-0.5)
+ else:
+ ref = gqa_sdpa(module, q, k, k, mask)[0]
+ torch.testing.assert_close(out, ref)
+ assert sum(torch._dynamo.utils.counters["graph_break"].values()) == 0
+ assert counter.frame_count == 1
+ expected = [("varlen", (None, torch.float32, 16, 4, 2, None))]
+ if not in_graph:
+ expected.append(("leaves", ("cpu", None, torch.float32, 16, None)))
+ assert keys == expected
+ assert all(type(x) is int for _, key in keys for x in key if isinstance(x, int))
+
+
+def test_shared_forward_with_mixed_head_dims_compiles(monkeypatch):
+ """Gemma4-style mixed head_dim: allow_unspec_int_on_nn_module (set by unsloth_zoo) makes
+ self.head_dim symbolic even with dynamic = None; the probes must still get plain ints."""
+ from torch._dynamo.testing import CompileCounter
+
+ if not hasattr(torch._dynamo.config, "allow_unspec_int_on_nn_module"):
+ pytest.skip("torch without allow_unspec_int_on_nn_module keeps module ints static")
+ keys = []
+
+ def probe(name):
+ def run(*key):
+ keys.append((name, key))
+ return False
+
+ return run
+
+ def gqa_sdpa(
+ module,
+ q,
+ k,
+ v,
+ mask,
+ scaling = None,
+ **kwargs,
+ ):
+ out = torch.nn.functional.scaled_dot_product_attention(
+ q, k, v, attn_mask = mask, scale = scaling, enable_gqa = True
+ )
+ return out.transpose(1, 2), None
+
+ class Attn(torch.nn.Module):
+ def __init__(self, heads, kv_heads, head_dim):
+ super().__init__()
+ self.head_dim, self.is_causal = head_dim, True
+ self.num_key_value_groups = heads // kv_heads
+ self.q_proj = torch.nn.Linear(64, heads * head_dim, bias = False)
+ self.k_proj = torch.nn.Linear(64, kv_heads * head_dim, bias = False)
+
+ def forward(self, h, mask, psl):
+ shape = (*h.shape[:-1], -1, self.head_dim)
+ q = self.q_proj(h).view(shape).transpose(1, 2)
+ k = self.k_proj(h).view(shape).transpose(1, 2)
+ return hpa._sdpa_packed_varlen(self, q, k, k, mask, packed_seq_lengths = psl)[0]
+
+ hpa._ORIG_SDPA[0] = gqa_sdpa
+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)
+ _block_flag(monkeypatch, True)
+ monkeypatch.setattr(hpa, "_static_window", lambda *args: None)
+ monkeypatch.setattr(hpa, "_VARLEN_IN_GRAPH", {})
+ monkeypatch.setattr(hpa, "_LEAVES_BLOCK", {})
+ monkeypatch.setattr(hpa, "_varlen_in_graph_probe", probe("varlen"))
+ monkeypatch.setattr(hpa, "_leaves_block_probe", probe("leaves"))
+ torch.manual_seed(0)
+ layers = [Attn(4, 2, 16), Attn(2, 1, 32), Attn(4, 2, 16), Attn(2, 1, 32)]
+ lengths = [2, 5, 4]
+ h = torch.randn(1, sum(lengths), 64)
+ mask, psl = _block_causal(lengths), torch.tensor(lengths, dtype = torch.int32)
+ torch._dynamo.reset()
+ torch._dynamo.utils.counters.clear()
+ counter = CompileCounter()
+ with torch._dynamo.config.patch(allow_unspec_int_on_nn_module = True):
+ compiled = torch.compile(Attn.forward, backend = counter, fullgraph = True)
+ for layer in layers:
+ out = compiled(layer, h, mask, psl)
+ shape = (*h.shape[:-1], -1, layer.head_dim)
+ q = layer.q_proj(h).view(shape).transpose(1, 2)
+ k = layer.k_proj(h).view(shape).transpose(1, 2)
+ torch.testing.assert_close(out, gqa_sdpa(layer, q, k, k, mask)[0])
+ assert sum(torch._dynamo.utils.counters["graph_break"].values()) == 0
+ assert {key[3] for name, key in keys if name == "leaves"} == {16, 32}
+ assert all(type(x) is int for _, key in keys for x in key if isinstance(x, int))
+
+
@_CUDA
@_TORCH_VARLEN_HOST
@pytest.mark.parametrize("window", [None, 4])
diff --git a/unsloth/utils/hf_packed_attention.py b/unsloth/utils/hf_packed_attention.py
index e2ed7e6ec7a..567b4f17524 100644
--- a/unsloth/utils/hf_packed_attention.py
+++ b/unsloth/utils/hf_packed_attention.py
@@ -6,6 +6,7 @@ anything else goes to the wrapped sdpa."""
import contextlib
import inspect
import logging
+import operator
import os
import weakref
@@ -519,7 +520,6 @@ def _sdpa_packed_varlen(
query.device.type,
query.device.index,
query.dtype,
- # int(): a symbolic head dim (dynamic=True) cannot be folded and would trace the probe.
int(query.shape[-1]),
_window_key(module, kwargs),
)
@@ -764,8 +764,27 @@ def _leaves_block_probe(device_type, device_index, dtype, head_dim, window):
return False
+def _constant_probe(fn):
+ """assume_constant_result only takes Python constants; int() keeps a SymInt symbolic, so
+ operator.index specialises it with a guard (head sizes are fixed per model). dynamic=None is unchanged."""
+ constant = torch._dynamo.assume_constant_result(fn)
+
+ def probe(*args):
+ return constant(
+ *(
+ operator.index(arg)
+ if isinstance(arg, (int, torch.SymInt)) and not isinstance(arg, bool)
+ else arg
+ for arg in args
+ )
+ )
+
+ probe.__name__, probe.__qualname__, probe.__doc__ = fn.__name__, fn.__qualname__, fn.__doc__
+ return probe
+
+
# Baked into the graph at trace time. Not an lru_cache: Dynamo traces those via __wrapped__ (fake tensors).
-_leaves_block = torch._dynamo.assume_constant_result(_leaves_block_eager)
+_leaves_block = _constant_probe(_leaves_block_eager)
_VARLEN_IN_GRAPH = {}
@@ -814,7 +833,7 @@ def _varlen_in_graph_probe(device_index, dtype, head_dim, n_heads, n_kv_heads, w
return False
-_varlen_in_graph = torch._dynamo.assume_constant_result(_varlen_in_graph_eager)
+_varlen_in_graph = _constant_probe(_varlen_in_graph_eager)
def block_varlen_kwargs(layer, hidden_states, kwargs):