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.

Compiled blocks: packed rows run the flash varlen kernel inside the graph (#15325)

Daniel Han85c9d2021f90
diff --git a/tests/test_hf_packed_attention.py b/tests/test_hf_packed_attention.py
index cce2c231577..e3d4e1c5a22 100644
--- a/tests/test_hf_packed_attention.py
+++ b/tests/test_hf_packed_attention.py
@@ -1246,3 +1246,253 @@ def test_tiny_gemma4_packed_row_matches_each_document(_efficient_fresh, monkeypa
fast_logits[:, start : start + n], alone, atol = 3e-2, rtol = 3e-2
)
start += n
+
+
+def _block_layer(
+ window = None,
+ impl = "sdpa",
+ head_dim = 16,
+ n_heads = 4,
+):
+ config = types.SimpleNamespace(_attn_implementation = impl, num_attention_heads = n_heads)
+ attn = types.SimpleNamespace(config = config, head_dim = head_dim, sliding_window = window)
+ return types.SimpleNamespace(self_attn = attn)
+
+
+ "case", ["cpu", "unpacked", "eager_impl", "bad_window", "no_attention", "disabled"]
+)
+def test_block_varlen_kwargs_refusals_keep_the_dense_path(monkeypatch, case):
+ """Every refusal leaves the compiled block on its previous path (SDPA over the dense mask)."""
+ hpa._ORIG_SDPA[0] = _plain_sdpa
+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)
+ lengths = [3, 3]
+ hidden = torch.randn(1, 6, 8)
+ kwargs = {"packed_seq_lengths": torch.tensor(lengths), "attention_mask": _block_causal(lengths)}
+ layer = _block_layer()
+ if case == "cpu":
+ pass # hidden states on CPU
+ else:
+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
+ if case == "unpacked":
+ kwargs.pop("packed_seq_lengths")
+ elif case == "eager_impl":
+ layer = _block_layer(impl = "eager")
+ elif case == "bad_window":
+ layer = _block_layer(window = 0)
+ elif case == "no_attention":
+ layer = types.SimpleNamespace()
+ elif case == "disabled":
+ monkeypatch.setenv("UNSLOTH_HF_PACKED_VARLEN", "0")
+ if case != "cpu":
+ # No CUDA here: refusals must come before any device work.
+ monkeypatch.setattr(
+ hpa, "_torch_varlen", lambda device: None if case == "cpu" else object()
+ )
+ monkeypatch.setattr(
+ "unsloth.utils.packing.get_packed_info_from_kwargs",
+ lambda *a, **k: pytest.fail("refused rows must not build packed metadata"),
+ )
+ assert hpa.block_varlen_kwargs(layer, hidden, kwargs) is None
+
+
+def test_block_varlen_kwargs_prepares_metadata_and_checks_the_mask(monkeypatch):
+ hpa._ORIG_SDPA[0] = _plain_sdpa
+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)
+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
+ monkeypatch.setattr(hpa, "_torch_varlen", lambda device: object())
+ monkeypatch.setattr(hpa, "_sdpa_policy_requested", lambda *args: False)
+ monkeypatch.setattr(hpa, "_BLOCK_PREP", {})
+ lengths = [3, 5]
+ cu = torch.tensor([0, 3, 8], dtype = torch.int32)
+ monkeypatch.setattr(
+ "unsloth.utils.packing.get_packed_info_from_kwargs",
+ lambda kwargs, device: (torch.tensor(lengths), cu, 5),
+ )
+ hidden = torch.randn(1, 8, 8)
+ kwargs = {"packed_seq_lengths": torch.tensor(lengths), "attention_mask": _block_causal(lengths)}
+ before = hpa.HF_PACKED_ATTENTION_STATS["compiled"]
+ assert hpa.block_varlen_kwargs(_block_layer(), hidden, kwargs) == (cu, 5)
+ assert hpa.HF_PACKED_ATTENTION_STATS["compiled"] == before + 1
+ # A mask that is not this block-causal one (one causal span over both documents) is refused.
+ kwargs["attention_mask"] = _block_causal([8])
+ assert hpa.block_varlen_kwargs(_block_layer(), hidden, kwargs) is None
+
+
+def test_block_varlen_kwargs_rechecks_a_mask_edited_in_place(monkeypatch):
+ """The per-forward cache keys on tensor versions: a mask edited in place is checked again."""
+ hpa._ORIG_SDPA[0] = _plain_sdpa
+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)
+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
+ monkeypatch.setattr(hpa, "_torch_varlen", lambda device: object())
+ monkeypatch.setattr(hpa, "_sdpa_policy_requested", lambda *args: False)
+ monkeypatch.setattr(hpa, "_BLOCK_PREP", {})
+ lengths = [3, 5]
+ cu = torch.tensor([0, 3, 8], dtype = torch.int32)
+ monkeypatch.setattr(
+ "unsloth.utils.packing.get_packed_info_from_kwargs",
+ lambda kwargs, device: (torch.tensor(lengths), cu, 5),
+ )
+ hidden = torch.randn(1, 8, 8)
+ mask = _block_causal(lengths)
+ kwargs = {"packed_seq_lengths": torch.tensor(lengths), "attention_mask": mask}
+ assert hpa.block_varlen_kwargs(_block_layer(), hidden, kwargs) == (cu, 5)
+ mask[..., 4, 0] = True # the second document now sees the first
+ assert hpa.block_varlen_kwargs(_block_layer(), hidden, kwargs) is None
+
+
+def test_block_varlen_kwargs_survives_a_collected_mask_then_none(monkeypatch):
+ """Same lengths, the cached mask collected, then a call without a mask: refused, not a crash."""
+ hpa._ORIG_SDPA[0] = _plain_sdpa
+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)
+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
+ monkeypatch.setattr(hpa, "_torch_varlen", lambda device: object())
+ monkeypatch.setattr(hpa, "_sdpa_policy_requested", lambda *args: False)
+ monkeypatch.setattr(hpa, "_BLOCK_PREP", {})
+ lengths = torch.tensor([3, 5])
+ cu = torch.tensor([0, 3, 8], dtype = torch.int32)
+ monkeypatch.setattr(
+ "unsloth.utils.packing.get_packed_info_from_kwargs", lambda kwargs, device: (lengths, cu, 5)
+ )
+ hidden = torch.randn(1, 8, 8)
+ kwargs = {"packed_seq_lengths": lengths, "attention_mask": _block_causal([3, 5])}
+ assert hpa.block_varlen_kwargs(_block_layer(), hidden, kwargs) == (cu, 5)
+ del kwargs["attention_mask"] # the only reference: the cached weakref is now dead
+ assert hpa.block_varlen_kwargs(_block_layer(), hidden, kwargs) is None
+
+
+def test_block_varlen_kwargs_honours_the_sdpa_policy_each_step(monkeypatch):
+ """Deterministic mode / a math-only sdpa_kernel is read per step, not cached with the hardware
+ verdict: while it asks for SDPA the block keeps the dense path, and the fast path returns after."""
+ hpa._ORIG_SDPA[0] = _plain_sdpa
+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)
+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
+ monkeypatch.setattr(hpa, "_torch_varlen", lambda device: object())
+ monkeypatch.setattr(hpa, "_BLOCK_PREP", {})
+ lengths = [3, 5]
+ cu = torch.tensor([0, 3, 8], dtype = torch.int32)
+ monkeypatch.setattr(
+ "unsloth.utils.packing.get_packed_info_from_kwargs",
+ lambda kwargs, device: (torch.tensor(lengths), cu, 5),
+ )
+ policy = [True]
+ monkeypatch.setattr(hpa, "_sdpa_policy_requested", lambda *args: policy[0])
+ hidden = torch.randn(1, 8, 8)
+ for wants_sdpa in (True, False):
+ policy[0] = wants_sdpa
+ # A new step: new lengths and mask objects.
+ kwargs = {
+ "packed_seq_lengths": torch.tensor(lengths),
+ "attention_mask": _block_causal(lengths),
+ }
+ got = hpa.block_varlen_kwargs(_block_layer(), hidden, kwargs)
+ assert got is None if wants_sdpa else got == (cu, 5)
+
+
[email protected]("in_graph", [True, False])
+def test_traced_block_varlen_call_stays_in_the_graph(monkeypatch, in_graph):
+ """With prepared metadata the traced wrapper calls the varlen op without a graph break; when the
+ op cannot take the shape it keeps the wrapped sdpa, and the private kwarg never reaches it."""
+ seen = {}
+
+ def orig(module, q, k, v, mask, **kwargs):
+ seen["orig_kwargs"] = set(kwargs)
+ return _plain_sdpa(module, q, k, v, mask, **kwargs)
+
+ hpa._ORIG_SDPA[0] = orig
+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)
+ # Fake tensors keep their real (CPU) device here; the GPU test below covers the real checks.
+ monkeypatch.setattr(hpa, "_static_window", lambda *args: None)
+ monkeypatch.setattr(hpa, "_varlen_in_graph", lambda *args: in_graph)
+ monkeypatch.setattr(
+ hpa,
+ "_flash_varlen",
+ lambda q, k, v, cu, m, scale, window: q.transpose(1, 2) * scale,
+ )
+ lengths = [3, 3]
+ module = types.SimpleNamespace(is_causal = True, num_key_value_groups = 1, training = True)
+ q = torch.randn(1, 4, 6, 16, dtype = torch.bfloat16)
+ mask, psl = _block_causal(lengths), torch.tensor(lengths, dtype = torch.int32)
+ cu = torch.tensor([0, 3, 6], dtype = torch.int32)
+ torch._dynamo.reset()
+ torch._dynamo.utils.counters.clear()
+ fn = torch.compile(
+ lambda q: hpa._sdpa_packed_varlen(
+ module, q, q, q, mask, packed_seq_lengths = psl, **{hpa.BLOCK_VARLEN_KWARG: (cu, 3)}
+ )[0],
+ backend = "eager",
+ fullgraph = True,
+ )
+ out = fn(q)
+ assert sum(torch._dynamo.utils.counters["graph_break"].values()) == 0
+ if in_graph:
+ torch.testing.assert_close(out, q.transpose(1, 2) * 16**-0.5)
+ assert "orig_kwargs" not in seen
+ else:
+ assert hpa.BLOCK_VARLEN_KWARG not in seen["orig_kwargs"]
+
+
+@_CUDA
+@_TORCH_VARLEN_HOST
[email protected]("window", [None, 4])
+def test_block_varlen_runs_inside_the_graph_and_matches_dense_sdpa(monkeypatch, window):
+ """Real op, compiled fullgraph with the sequence dim dynamic like _block_compile: no graph break,
+ one graph across segment layouts after the first change, forward and backward match SDPA."""
+ if hpa._torch_varlen(torch.device("cuda", 0)) is None:
+ pytest.skip(
+ reason = "varlen kernel needs torch's varlen_attn with window_size (CUDA torch >= 2.11)"
+ )
+ from transformers.integrations.sdpa_attention import sdpa_attention_forward
+
+ # Engagement without a Python side effect (Dynamo would guard on a counter): the dense fallback
+ # fails the test, so every layout below ran the in-graph kernel.
+ def _dense(*args, **kwargs):
+ raise AssertionError("packed row fell back to SDPA over the dense mask")
+
+ hpa._ORIG_SDPA[0] = _dense
+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)
+ monkeypatch.setattr(hpa, "_VARLEN_IN_GRAPH", {})
+ H, n_kv, D = 8, 2, 64
+ module = types.SimpleNamespace(
+ is_causal = True, num_key_value_groups = H // n_kv, training = True, sliding_window = window
+ )
+ fn = torch.compile(
+ lambda q, k, v, mask, psl, varlen: hpa._sdpa_packed_varlen(
+ module,
+ q,
+ k,
+ v,
+ mask,
+ scaling = 0.11,
+ packed_seq_lengths = psl,
+ **{hpa.BLOCK_VARLEN_KWARG: varlen},
+ )[0],
+ fullgraph = True,
+ )
+ torch._dynamo.reset()
+ torch._dynamo.utils.counters.clear()
+ torch.manual_seed(0)
+ for lengths in ([37, 100, 2, 5, 230], [64, 64, 9], [300, 1, 41, 7], [128] * 3):
+ T = sum(lengths)
+ q, k, v = (
+ torch.randn(1, h, T, D, device = "cuda", dtype = torch.bfloat16, requires_grad = True)
+ for h in (H, n_kv, n_kv)
+ )
+ mask = _block_causal(lengths, "cuda")
+ if window is not None:
+ idx = torch.arange(T, device = "cuda")
+ mask = mask & (idx[None, :] > idx[:, None] - window)[None, None]
+ cu = torch.tensor([0] + lengths, device = "cuda").cumsum(0).to(torch.int32)
+ for t, dims in ((q, (2,)), (k, (2,)), (v, (2,)), (mask, (2, 3)), (cu, (0,))):
+ torch._dynamo.maybe_mark_dynamic(t, dims)
+ out = fn(q, k, v, mask, torch.tensor(lengths, dtype = torch.int32), (cu, max(lengths)))
+ grad = torch.randn_like(out)
+ got = torch.autograd.grad(out, (q, k, v), grad)
+ ref_out, _ = sdpa_attention_forward(module, q, k, v, mask, scaling = 0.11)
+ ref = torch.autograd.grad(ref_out, (q, k, v), grad)
+ torch.testing.assert_close(out.float(), ref_out.float(), atol = 2e-2, rtol = 2e-2)
+ for g, r in zip(got, ref):
+ torch.testing.assert_close(g.float(), r.float(), atol = 3e-2, rtol = 3e-2)
+ assert sum(torch._dynamo.utils.counters["graph_break"].values()) == 0
+ # max_seqlen specializes once, then is dynamic: at most two graphs for four layouts.
+ assert torch._dynamo.utils.counters["stats"]["unique_graphs"] <= 2
diff --git a/unsloth/models/_block_compile.py b/unsloth/models/_block_compile.py
index a1828fe9747..5ed54149dd8 100644
--- a/unsloth/models/_block_compile.py
+++ b/unsloth/models/_block_compile.py
@@ -794,6 +794,13 @@ def _wrap(
original = cls.forward
# Host-read packed lengths / PrefixGrouper segments stay stock.
unsloth_forward = getattr(original, "__module__", "").startswith("unsloth.models.")
+ try:
+ takes_kwargs = any(
+ p.kind is inspect.Parameter.VAR_KEYWORD
+ for p in inspect.signature(original).parameters.values()
+ )
+ except (TypeError, ValueError):
+ takes_kwargs = False
isolate = {}
if _ISOLATE_RECOMPILES:
isolate = dict(isolate_recompiles = True, recompile_limit = _region_recompile_limit(kinds))
@@ -830,11 +837,19 @@ def _wrap(
previous = inline_flag[0]
inline_flag[0] = True
_IN_BLOCK[0] = mode
- # Packed rows run hf_packed_attention's varlen kernel outside the graph (see there).
- packed = getattr(sys.modules.get(_PACKED_MODULE), "IN_COMPILED_BLOCK", _NO_PACKED)
+ packed_module = sys.modules.get(_PACKED_MODULE)
+ packed = getattr(packed_module, "IN_COMPILED_BLOCK", _NO_PACKED)
packed_previous = packed[0]
packed[0] = True
try:
+ if (
+ takes_kwargs
+ and packed_module is not None
+ and kwargs.get("packed_seq_lengths") is not None
+ ):
+ varlen = packed_module.block_varlen_kwargs(self, hidden_states, kwargs)
+ if varlen is not None:
+ kwargs = {**kwargs, packed_module.BLOCK_VARLEN_KWARG: varlen}
# Capture hooks (router_logits) append to empty scratch lists: no guard on the layer index.
with capture_scratch():
if graphs and not graphs_off[0]:
diff --git a/unsloth/utils/hf_packed_attention.py b/unsloth/utils/hf_packed_attention.py
index af850f6ff38..5ee47ce6ad4 100644
--- a/unsloth/utils/hf_packed_attention.py
+++ b/unsloth/utils/hf_packed_attention.py
@@ -20,7 +20,14 @@ _ORIG_SDPA = [None]
# True inside _block_compile's own compiled blocks (not a user's outer compile); see _leaves_block.
IN_COMPILED_BLOCK = [False]
# efficient: the subset of fast calls that ran SDPA's memory-efficient kernel over cu_seqlens.
-HF_PACKED_ATTENTION_STATS = {"fast": 0, "fallback": 0, "mask_checks": 0, "efficient": 0}
+HF_PACKED_ATTENTION_STATS = {
+ "fast": 0,
+ "fallback": 0,
+ "mask_checks": 0,
+ "efficient": 0,
+ "compiled": 0,
+}
+BLOCK_VARLEN_KWARG = "_unsloth_block_varlen"
# Layers of one window share a mask object: window -> [weakref, (cu_seqlens, versions), verdict].
_MASK_CHECK = {}
_MASK_CHECK_ROWS = 1024
@@ -290,6 +297,13 @@ _SDPA_MATH = []
def _sdpa_requested(query, key) -> bool:
"""Deterministic mode, a disabled flash SDPA backend or a math-first sdpa_kernel priority asks for
SDPA itself, so no varlen kernel (torch's, xformers or flash-attn) may replace it."""
+ return _sdpa_policy_requested(
+ query.device, query.dtype, query.shape[-1], query.shape[1], key.shape[1]
+ )
+
+
+def _sdpa_policy_requested(device, dtype, head_dim, n_heads, n_kv_heads) -> bool:
+ """_sdpa_requested from shapes; reads process state, so never while tracing."""
if torch.are_deterministic_algorithms_enabled():
return True
if not _SDPA_MATH:
@@ -297,11 +311,10 @@ def _sdpa_requested(query, key) -> bool:
from .attention_dispatch import _sdpa_backend_state
_SDPA_MATH[:] = [int(SDPBackend.MATH), _sdpa_backend_state]
math, backend_state = _SDPA_MATH
- n_heads, n_kv_heads = query.shape[1], key.shape[1]
flash, choice = backend_state(
- str(query.device),
- query.dtype,
- query.shape[-1],
+ str(device),
+ dtype,
+ head_dim,
n_heads,
n_kv_heads,
True,
@@ -310,6 +323,86 @@ def _sdpa_requested(query, key) -> bool:
return not flash or choice == math
+def _static_window(module, query, key, value, dropout, is_causal, kwargs):
+ """The window for a call a varlen kernel can take (shapes, dtypes, masking), else _NO_WINDOW.
+ Only shapes, dtypes and attributes: also safe while tracing."""
+ bsz, n_heads, q_len, head_dim = query.shape
+ window = _sliding_window(module, kwargs)
+ if (
+ bsz == 1
+ and q_len > 0
+ and query.is_cuda
+ and query.device == key.device == value.device
+ and key.shape[0] == value.shape[0] == 1
+ and key.shape[1] == value.shape[1]
+ and key.shape[2] == value.shape[2] == q_len
+ # Not MLA (192 / 128).
+ and key.shape[-1] == value.shape[-1] == head_dim
+ and head_dim % 8 == 0
+ and query.dtype in (torch.float16, torch.bfloat16)
+ and query.dtype == key.dtype == value.dtype
+ and not _autocast_dtype_differs(query)
+ and not dropout
+ and is_causal is not False
+ and getattr(module, "is_causal", True)
+ and kwargs.get("position_bias") is None
+ and kwargs.get("cache") is None
+ and kwargs.get("past_key_values") is None
+ and n_heads % key.shape[1] == 0
+ and not _softcapped(module, kwargs)
+ ):
+ return window
+ return _NO_WINDOW
+
+
+def _call_torch_varlen(torch_varlen, query, key, value, cu_seqlens, max_seqlen, scale, window):
+ n_heads, n_kv_heads = query.shape[1], key.shape[1]
+ gqa, k_in, v_in = {}, key, value
+ if n_kv_heads != n_heads:
+ if not _TORCH_VARLEN_GQA or _TORCH_VARLEN_GQA[0]:
+ gqa = {"enable_gqa": True}
+ else:
+ # torch 2.11: no enable_gqa, so repeat the K/V heads as transformers' sdpa path does.
+ k_in = key.repeat_interleave(n_heads // n_kv_heads, dim = 1)
+ v_in = value.repeat_interleave(n_heads // n_kv_heads, dim = 1)
+ out = torch_varlen(
+ query[0].transpose(0, 1),
+ k_in[0].transpose(0, 1),
+ v_in[0].transpose(0, 1),
+ cu_seqlens,
+ cu_seqlens,
+ max_seqlen,
+ max_seqlen,
+ scale = scale,
+ window_size = (-1, 0) if window is None else (window - 1, 0),
+ **gqa,
+ )
+ return out.unsqueeze(0)
+
+
+def _flash_varlen(query, key, value, cu_seqlens, max_seqlen, scale, window):
+ """aten's flash varlen, what torch's varlen_attn runs for these rows, called directly: a native op
+ with a C++ backward (varlen_attn's Python custom op cost ~37 us of host time per call in a
+ compiled step) that takes grouped K / V heads as they are."""
+ out = torch.ops.aten._flash_attention_forward(
+ query[0].transpose(0, 1),
+ key[0].transpose(0, 1),
+ value[0].transpose(0, 1),
+ cu_seqlens,
+ cu_seqlens,
+ max_seqlen,
+ max_seqlen,
+ 0.0,
+ False,
+ False,
+ scale = scale,
+ # Causal through the window: right 0, left unbounded or window - 1 (transformers' overlay).
+ window_size_left = -1 if window is None else window - 1,
+ window_size_right = 0,
+ )[0]
+ return out.unsqueeze(0)
+
+
def _sdpa_packed_varlen(
module,
query,
@@ -331,7 +424,25 @@ def _sdpa_packed_varlen(
if kwargs.get("packed_seq_lengths") is not None and not torch.compiler.is_compiling():
HF_PACKED_ATTENTION_STATS["fallback"] += 1
return orig(module, query, key, value, attention_mask, *args, **named, **kwargs)
+ block_varlen = kwargs.pop(BLOCK_VARLEN_KWARG, None)
# Before any counter while tracing: Dynamo would guard on it and recompile every forward.
+ if block_varlen is not None and torch.compiler.is_compiling() and not _disabled():
+ window = _static_window(module, query, key, value, dropout, is_causal, kwargs)
+ if (
+ window is not _NO_WINDOW
+ and query.shape[-1] <= 256
+ and _varlen_in_graph(
+ query.device.index,
+ query.dtype,
+ int(query.shape[-1]),
+ int(query.shape[1]),
+ int(key.shape[1]),
+ window,
+ )
+ ):
+ # Host inputs were prepared eagerly (block_varlen_kwargs); the kernel call traces.
+ scale = query.shape[-1] ** -0.5 if scaling is None else scaling
+ return _flash_varlen(query, key, value, *block_varlen, scale, window), None
if (
IN_COMPILED_BLOCK[0]
and torch.compiler.is_compiling()
@@ -382,31 +493,8 @@ def _sdpa_packed_varlen(
bsz, n_heads, q_len, head_dim = query.shape
seq_info = torch_varlen = backend = None
efficient = False
- window = _sliding_window(module, kwargs)
- if (
- bsz == 1
- and q_len > 0
- and query.is_cuda
- and query.device == key.device == value.device
- and key.shape[0] == value.shape[0] == 1
- and key.shape[1] == value.shape[1]
- and key.shape[2] == value.shape[2] == q_len
- # Not MLA (192 / 128).
- and key.shape[-1] == value.shape[-1] == head_dim
- and head_dim % 8 == 0
- and query.dtype in (torch.float16, torch.bfloat16)
- and query.dtype == key.dtype == value.dtype
- and not _autocast_dtype_differs(query)
- and not dropout
- and is_causal is not False
- and getattr(module, "is_causal", True)
- and kwargs.get("position_bias") is None
- and kwargs.get("cache") is None
- and kwargs.get("past_key_values") is None
- and n_heads % key.shape[1] == 0
- and window is not _NO_WINDOW
- and not _softcapped(module, kwargs)
- ):
+ window = _static_window(module, query, key, value, dropout, is_causal, kwargs)
+ if window is not _NO_WINDOW:
if head_dim > 256:
# Past every flash kernel (Gemma-4 global layers are 512): the efficient kernel, per segment.
efficient = _efficient_varlen_takes(query, window)
@@ -483,26 +571,9 @@ def _sdpa_packed_varlen(
HF_PACKED_ATTENTION_STATS["efficient"] += 1
return out, None
if torch_varlen is not None:
- gqa, k_in, v_in = {}, key, value
- if n_kv_heads != n_heads:
- if not _TORCH_VARLEN_GQA or _TORCH_VARLEN_GQA[0]:
- gqa = {"enable_gqa": True}
- else:
- # torch 2.11: no enable_gqa, so repeat the K/V heads as transformers' sdpa path does.
- k_in = key.repeat_interleave(n_heads // n_kv_heads, dim = 1)
- v_in = value.repeat_interleave(n_heads // n_kv_heads, dim = 1)
try:
- out = torch_varlen(
- query[0].transpose(0, 1),
- k_in[0].transpose(0, 1),
- v_in[0].transpose(0, 1),
- cu_seqlens,
- cu_seqlens,
- max_seqlen,
- max_seqlen,
- scale = scale,
- window_size = (-1, 0) if window is None else (window - 1, 0),
- **gqa,
+ out = _call_torch_varlen(
+ torch_varlen, query, key, value, cu_seqlens, max_seqlen, scale, window
)
except torch.OutOfMemoryError:
raise
@@ -526,7 +597,7 @@ def _sdpa_packed_varlen(
is_causal = is_causal,
**kwargs,
)
- return out.unsqueeze(0), None
+ return out, None
from .attention_dispatch import AttentionConfig, AttentionContext, run_attention
config = AttentionConfig(
@@ -610,6 +681,129 @@ def _leaves_block_probe(device_type, device_index, dtype, head_dim, window):
# 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)
+_VARLEN_IN_GRAPH = {}
+
+
+def _varlen_in_graph_eager(device_index, dtype, head_dim, n_heads, n_kv_heads, window):
+ key = (device_index, dtype, head_dim, n_heads, n_kv_heads, window)
+ if key not in _VARLEN_IN_GRAPH:
+ _VARLEN_IN_GRAPH[key] = _varlen_in_graph_probe(*key)
+ return _VARLEN_IN_GRAPH[key]
+
+
+def _varlen_in_graph_probe(device_index, dtype, head_dim, n_heads, n_kv_heads, window):
+ """aten's flash varlen takes this shape on this device: one real forward and backward (a build
+ that refuses at run time would otherwise fail inside the compiled graph)."""
+ try:
+ from .flash_impl import flash_impl_allows
+
+ device = torch.device("cuda", device_index)
+ query = torch.zeros(1, n_heads, 16, head_dim, device = device, dtype = dtype)
+ key = torch.zeros(1, n_kv_heads, 16, head_dim, device = device, dtype = dtype)
+ torch_varlen = _torch_varlen(device)
+ # Hardware and build only: the sdpa policy can change, block_varlen_kwargs checks it each step.
+ if torch_varlen is None or not flash_impl_allows(head_dim, window, device):
+ return False
+ query.requires_grad_()
+ cu_seqlens = torch.tensor([0, 7, 16], dtype = torch.int32, device = device)
+ out = _flash_varlen(query, key, key, cu_seqlens, 9, 1.0, window)
+ out.float().sum().backward()
+ return True
+ except Exception:
+ return False
+
+
+_varlen_in_graph = torch._dynamo.assume_constant_result(_varlen_in_graph_eager)
+
+
+def block_varlen_kwargs(layer, hidden_states, kwargs):
+ """Eager, before _block_compile runs a compiled decoder block: (cu_seqlens, max_seqlen) for its
+ packed row, so attention runs torch's varlen op inside the graph. Building them there needs a host
+ read of the longest segment and the mask check a host sync, which is why the traced wrapper used to
+ fall back to SDPA over the dense mask. None keeps that path."""
+ seq_lengths, mask = kwargs.get("packed_seq_lengths"), kwargs.get("attention_mask")
+ attention = getattr(layer, "self_attn", None)
+ # Layers of one forward (and its checkpoint recompute) share the lengths and their window's mask.
+ window = _sliding_window(attention, kwargs) if attention is not None else None
+ entry = _BLOCK_PREP.get(window)
+ if (
+ entry is not None
+ # Live tensors only: a dead weakref is None, and so is a missing mask.
+ and isinstance(seq_lengths, torch.Tensor)
+ and isinstance(mask, torch.Tensor)
+ and entry[0]() is seq_lengths
+ and entry[1]() is mask
+ and entry[2] == (hidden_states.device, seq_lengths._version, mask._version)
+ ):
+ if entry[3] is not None:
+ HF_PACKED_ATTENTION_STATS["compiled"] += 1
+ return entry[3]
+ result = _block_varlen_prepare(layer, attention, hidden_states, kwargs)
+ if (
+ isinstance(seq_lengths, torch.Tensor)
+ and isinstance(mask, torch.Tensor)
+ # Versions catch in-place edits; inference tensors have none, so are always rechecked.
+ and not (torch.is_inference(seq_lengths) or torch.is_inference(mask))
+ and not _disabled()
+ ):
+ # Weak: the T x T mask must not outlive its step.
+ _BLOCK_PREP[window] = (
+ weakref.ref(seq_lengths),
+ weakref.ref(mask),
+ (hidden_states.device, seq_lengths._version, mask._version),
+ result,
+ )
+ return result
+
+
+_BLOCK_PREP = {}
+
+
+def _block_varlen_prepare(layer, attention, hidden_states, kwargs):
+ if (
+ _disabled()
+ or _ORIG_SDPA[0] is None
+ or kwargs.get("packed_seq_lengths") is None
+ or not isinstance(hidden_states, torch.Tensor)
+ or not hidden_states.is_cuda
+ or hidden_states.dim() != 3
+ or hidden_states.shape[0] != 1
+ ):
+ return None
+ config = getattr(attention, "config", None)
+ if getattr(config, "_attn_implementation", None) != "sdpa":
+ return None
+ window = _sliding_window(attention, kwargs)
+ if window is _NO_WINDOW or _torch_varlen(hidden_states.device) is None:
+ return None
+ from .attention_dispatch import _VARLEN_INT32_GUARD_DISABLED, _varlen_backward_overflows_int32
+ from .packing import get_packed_info_from_kwargs
+
+ total = hidden_states.shape[1]
+ head_dim = getattr(attention, "head_dim", None)
+ n_heads = getattr(config, "num_attention_heads", None)
+ n_kv_heads = getattr(config, "num_key_value_heads", None) or n_heads
+ if not all(isinstance(n, int) for n in (head_dim, n_heads, n_kv_heads)):
+ return None
+ if _sdpa_policy_requested(
+ hidden_states.device, hidden_states.dtype, head_dim, n_heads, n_kv_heads
+ ):
+ return None
+ if not _VARLEN_INT32_GUARD_DISABLED and _varlen_backward_overflows_int32(
+ kwargs["packed_seq_lengths"].numel(), total, n_heads, head_dim
+ ):
+ return None
+ seq_info = get_packed_info_from_kwargs(kwargs, hidden_states.device)
+ if seq_info is None or not _mask_is_block_causal(
+ kwargs.get("attention_mask"), seq_info[1], total, window
+ ):
+ return None
+ _, cu_seqlens, max_seqlen = seq_info
+ # The segment count changes every step: one graph for all of them.
+ torch._dynamo.maybe_mark_dynamic(cu_seqlens, 0)
+ HF_PACKED_ATTENTION_STATS["compiled"] += 1
+ return cu_seqlens, int(max_seqlen)
+
def enable_hf_packed_attention() -> bool:
"""Wrap transformers' "sdpa" attention entry once. True when the wrapper is installed."""