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: attend packed rows per segment instead of under a dense mask (2.9x less memory, 2.5x faster without flash-attn / xformers) (#12740)

Daniel Han5babb22c6922
diff --git a/tests/utils/test_attention_masks.py b/tests/utils/test_attention_masks.py
index 7f8288b075d..49744ea13fa 100644
--- a/tests/utils/test_attention_masks.py
+++ b/tests/utils/test_attention_masks.py
@@ -378,6 +378,8 @@ def test_real_xformers_packed_mask_validates_on_each_device():
def test_run_attention_sdpa_passes_sliding_window(monkeypatch):
seq_info = _make_seq_info([3, 2])
sliding_window = 2
+ # Dense-mask path (UNSLOTH_SDPA_PACKED_SEGMENTS=0).
+ monkeypatch.setattr(attention_dispatch, "_SDPA_PACKED_SEGMENTS", False)
original_builder = attention_dispatch.build_sdpa_packed_attention_mask
captured = {}
diff --git a/tests/utils/test_packing.py b/tests/utils/test_packing.py
index 70b5a36d784..a67731107b8 100644
--- a/tests/utils/test_packing.py
+++ b/tests/utils/test_packing.py
@@ -1216,26 +1216,14 @@ def test_packing_sdpa(tmp_path):
)
assert seq_info is not None
- original_mask = attention_dispatch_utils.build_sdpa_packed_attention_mask
- mask_calls = []
+ original_lengths = attention_dispatch_utils.packed_segment_lengths
+ segment_calls = []
captured_loss_labels = {}
- def _capture_mask(
- seq_info,
- dtype,
- device,
- *,
- sliding_window = None,
- total_tokens = None,
- ):
- mask_calls.append(tuple(seq_info[0].tolist()))
- return original_mask(
- seq_info,
- dtype = dtype,
- device = device,
- sliding_window = sliding_window,
- total_tokens = total_tokens,
- )
+ def _capture_lengths(seq_info, total_tokens = None):
+ lengths = original_lengths(seq_info, total_tokens)
+ segment_calls.append(lengths)
+ return lengths
def _capture_loss(*, logits, labels, **loss_kwargs):
captured_loss_labels["labels"] = labels.detach().to("cpu")
@@ -1247,8 +1235,8 @@ def test_packing_sdpa(tmp_path):
stack.enter_context(
patch.object(
attention_dispatch_utils,
- "build_sdpa_packed_attention_mask",
- side_effect = _capture_mask,
+ "packed_segment_lengths",
+ side_effect = _capture_lengths,
)
)
stack.enter_context(
@@ -1261,7 +1249,9 @@ def test_packing_sdpa(tmp_path):
with torch.no_grad():
outputs = model(**inputs)
- assert mask_calls, "SDPA packed mask was not constructed"
+ assert segment_calls, "SDPA packed path did not split the row into its segments"
+ packed = tuple(batch["packed_seq_lengths"].tolist())
+ assert all(lengths[: len(packed)] == packed for lengths in segment_calls)
assert outputs.loss is not None
assert "labels" in captured_loss_labels
flat_loss_labels = captured_loss_labels["labels"].reshape(-1)
diff --git a/tests/utils/test_sdpa_packed_segments.py b/tests/utils/test_sdpa_packed_segments.py
new file mode 100644
index 00000000000..cc852ee09b7
--- /dev/null
+++ b/tests/utils/test_sdpa_packed_segments.py
@@ -0,0 +1,115 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""Packed rows on SDPA run per segment: same result as the dense block-diagonal mask, without the (T, T) scores."""
+
+import pytest
+import torch
+
+import unsloth # noqa: F401
+from unsloth.utils import attention_dispatch as ad
+from unsloth.utils import packing
+
+
+def _seq_info(lengths):
+ lengths = torch.tensor(lengths, dtype = torch.int32)
+ cu = torch.cat((torch.zeros(1, dtype = torch.int32), lengths.cumsum(0).int()))
+ return lengths, cu, int(lengths.max())
+
+
+def _run(
+ monkeypatch,
+ segments,
+ lengths,
+ total,
+ n_heads,
+ n_kv,
+ qkv,
+ is_causal = True,
+ window = None,
+):
+ monkeypatch.setattr(ad, "_SDPA_PACKED_SEGMENTS", segments)
+ packing.clear_packed_caches()
+ config = ad.AttentionConfig(backend = ad.SDPA, n_kv_heads = n_kv, n_groups = n_heads // n_kv)
+ context = ad.AttentionContext(
+ bsz = 1,
+ q_len = total,
+ kv_seq_len = total,
+ n_heads = n_heads,
+ head_dim = qkv[0].shape[-1],
+ requires_grad = True,
+ seq_info = _seq_info(lengths),
+ attention_mask = None,
+ causal_mask = None,
+ is_causal = is_causal,
+ sliding_window = window,
+ )
+ Q, K, V = (x.detach().clone().requires_grad_() for x in qkv)
+ out = ad.run_attention(config = config, context = context, Q = Q, K = K, V = V)
+ out = out.reshape(1, total, n_heads, -1)
+ (
+ out.float() * torch.linspace(-1, 1, out.numel(), device = out.device).view_as(out)
+ ).sum().backward()
+ return out.detach(), Q.grad, K.grad, V.grad
+
+
+CASES = [
+ # lengths, total tokens (> sum = pad tail segment), heads, kv heads, causal, window
+ ((5, 3, 4), 12, 4, 4, True, None),
+ ((5, 3, 4), 12, 4, 2, True, None),
+ ((4, 4, 4), 12, 4, 1, True, None),
+ ((7,), 10, 4, 2, True, None),
+ ((6, 2, 5), 13, 4, 2, True, 3),
+ ((6, 2, 5), 13, 4, 2, False, None),
+ ((6, 2, 5), 13, 4, 4, False, 3),
+ ((1, 1, 9), 11, 2, 1, True, 4),
+]
+
+
+ "device, dtype", [("cpu", torch.float32), ("cuda", torch.bfloat16), ("cuda", torch.float16)]
+)
[email protected]("lengths, total, n_heads, n_kv, is_causal, window", CASES)
+def test_segments_match_dense_mask(
+ monkeypatch, device, dtype, lengths, total, n_heads, n_kv, is_causal, window
+):
+ if device == "cuda" and not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ g = torch.Generator().manual_seed(3407)
+ shapes = ((1, n_heads, total, 64), (1, n_kv, total, 64), (1, n_kv, total, 64))
+ qkv = [torch.randn(s, generator = g).to(device, dtype) for s in shapes]
+ args = (lengths, total, n_heads, n_kv, qkv, is_causal, window)
+ dense = _run(monkeypatch, False, *args)
+ segs = _run(monkeypatch, True, *args)
+ tol = dict(atol = 1e-5, rtol = 1e-5) if dtype == torch.float32 else dict(atol = 2e-2, rtol = 2e-2)
+ for name, a, b in zip(("out", "dQ", "dK", "dV"), dense, segs):
+ assert torch.isfinite(b).all(), name
+ torch.testing.assert_close(b.float(), a.float(), **tol, msg = name)
+
+
+def test_segments_never_build_the_dense_mask(monkeypatch):
+ def refuse(*args, **kwargs):
+ raise AssertionError("dense packed mask built")
+
+ monkeypatch.setattr(ad, "build_sdpa_packed_attention_mask", refuse)
+ qkv = [torch.randn(1, 2, 9, 8) for _ in range(3)]
+ out = _run(monkeypatch, True, (4, 5), 9, 2, 2, qkv)[0]
+ assert out.shape == (1, 9, 2, 8)
+
+
[email protected](not torch.cuda.is_available(), reason = "needs CUDA")
+def test_peak_memory_is_linear_in_tokens(monkeypatch):
+ # 2 x 2048-token segments, 16 heads over 8 KV heads, as Qwen3-0.6B under padding-free SFT.
+ total, n_heads, n_kv = 4096, 16, 8
+ g = torch.Generator().manual_seed(0)
+ shapes = ((1, n_heads, total, 128), (1, n_kv, total, 128), (1, n_kv, total, 128))
+ qkv = [torch.randn(s, generator = g).cuda().bfloat16() for s in shapes]
+ peaks = {}
+ for segments in (False, True):
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats()
+ base = torch.cuda.memory_allocated()
+ _run(monkeypatch, segments, (2048, 2048), total, n_heads, n_kv, qkv)
+ torch.cuda.synchronize()
+ peaks[segments] = (torch.cuda.max_memory_allocated() - base) / 2**20
+ # The dense path holds (16, 4096, 4096) fp32 scores (1 GiB); per segment no (T, T) tensor exists.
+ assert peaks[True] < 256, peaks
+ assert peaks[False] > 4 * peaks[True], peaks
diff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.py
index 7f0a60888cf..3b87034cddf 100644
--- a/unsloth/utils/attention_dispatch.py
+++ b/unsloth/utils/attention_dispatch.py
@@ -28,6 +28,8 @@ from ..utils.packing import (
build_xformers_block_causal_mask,
cover_padded_cu_seqlens,
move_xformers_attention_bias,
+ packed_block_mask,
+ packed_segment_lengths,
)
flash_attn_func = None
@@ -76,6 +78,79 @@ _XFORMERS_FP32_UNSUPPORTED = (
)
SDPA_HAS_GQA = "enable_gqa" in (scaled_dot_product_attention.__doc__ or "")
+# Packed SDPA runs per segment: a dense (T, T) mask + enable_gqa leaves only the math kernel.
+_SDPA_PACKED_SEGMENTS = os.environ.get("UNSLOTH_SDPA_PACKED_SEGMENTS", "1").lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+)
+
+
+def _sdpa_flash_takes_gqa(Q: Tensor) -> bool:
+ # Only flash / math take enable_gqa: expand K/V elsewhere (pre-sm80, fp32, wide heads, ROCm).
+ return (
+ SDPA_HAS_GQA
+ and Q.is_cuda
+ and torch.version.hip is None
+ and Q.dtype in (torch.float16, torch.bfloat16)
+ and Q.shape[-1] <= 256
+ and Q.shape[-1] % 8 == 0
+ and torch.cuda.get_device_capability(Q.device)[0] >= 8
+ )
+
+
+def _sdpa_packed_segments(
+ Q: Tensor,
+ K: Tensor,
+ V: Tensor,
+ lengths: Tuple[int, ...],
+ *,
+ n_groups: int,
+ is_causal: bool,
+ sliding_window: Optional[int],
+ sdpa_kwargs: dict,
+) -> Optional[Tensor]:
+ """Q (1, H, T, D), K / V (1, H_kv, T, D) -> (1, T, H, D), the block-diagonal mask's result;
+ None when the lengths do not tile the row."""
+ if sum(length for length in lengths if length > 0) != Q.shape[-2]:
+ return None
+ gqa = n_groups != 1 and _sdpa_flash_takes_gqa(Q)
+ if n_groups != 1 and not gqa:
+ K = K.repeat_interleave(n_groups, dim = 1)
+ V = V.repeat_interleave(n_groups, dim = 1)
+ outs, start, i = [], 0, 0
+ lengths = [length for length in lengths if length > 0]
+ while i < len(lengths):
+ length = lengths[i]
+ j = i
+ while j < len(lengths) and lengths[j] == length:
+ j += 1
+ n = j - i
+ end = start + n * length
+
+ def split(x):
+ return x[0, :, start:end].unflatten(1, (n, length)).transpose(0, 1)
+
+ kwargs = dict(sdpa_kwargs)
+ windowed = sliding_window is not None and length > sliding_window
+ if windowed:
+ kwargs["attn_mask"] = packed_block_mask(
+ length,
+ dtype = Q.dtype,
+ device = Q.device,
+ sliding_window = sliding_window,
+ is_causal = is_causal,
+ )
+ kwargs["is_causal"] = is_causal and not windowed
+ if gqa:
+ kwargs["enable_gqa"] = True
+ out = scaled_dot_product_attention(split(Q), split(K), split(V), **kwargs)
+ outs.append(out.transpose(1, 2).flatten(0, 1))
+ start, i = end, j
+ return torch.cat(outs, dim = 0).unsqueeze(0)
+
+
# PrefixGrouper kernel, resolved once when the env gate is on so PG-off users never load torch flex_attention.
_flex_shared_prefix_attention = None
if os.environ.get("UNSLOTH_GRPO_PREFIX_GROUPER", "1").lower() not in ("0", "false", "no", "off"):
@@ -505,6 +580,25 @@ def run_attention(
else:
local_mask = context.attention_mask
is_causal_local = False
+ if (
+ _SDPA_PACKED_SEGMENTS
+ and context.seq_info is not None
+ and local_mask is None
+ and Q.shape[0] == 1
+ and Q.shape[-2] == K.shape[-2]
+ ):
+ out = _sdpa_packed_segments(
+ Q,
+ K,
+ V,
+ packed_segment_lengths(context.seq_info, K.shape[-2]),
+ n_groups = config.n_groups,
+ is_causal = context.is_causal,
+ sliding_window = sliding_window,
+ sdpa_kwargs = sdpa_kwargs,
+ )
+ if out is not None:
+ return out
if context.seq_info is not None and local_mask is None:
local_mask = build_sdpa_packed_attention_mask(
context.seq_info,
diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.py
index 7e23b4b57b5..f1ae71ef84f 100644
--- a/unsloth/utils/packing.py
+++ b/unsloth/utils/packing.py
@@ -53,6 +53,8 @@ _PACKED_INFO_CACHE: dict = {}
# Cache per device for build_sdpa_packed_attention_mask to avoid repeated D2H sync across layers
_SDPA_MASK_CACHE: dict = {}
+_SEGMENT_LENGTHS_CACHE: dict = {}
+
# Cache per device for build_xformers_block_causal_mask to avoid repeated D2H sync across layers
_XFORMERS_BLOCK_MASK_CACHE: dict = {}
@@ -689,6 +691,41 @@ def build_xformers_block_causal_mask(
return mask
+def packed_block_mask(
+ length: int,
+ *,
+ dtype: torch.dtype,
+ device: torch.device,
+ sliding_window: Optional[int] = None,
+ is_causal: bool = True,
+) -> torch.Tensor:
+ """Additive (length, length) mask of one packed segment: causal and / or sliding window."""
+ block = torch.zeros((length, length), dtype = dtype, device = device)
+ if is_causal:
+ upper = torch.triu(torch.ones((length, length), device = device), diagonal = 1).bool()
+ block = block.masked_fill(upper, float("-inf"))
+ if sliding_window is not None and sliding_window > 0 and length > sliding_window:
+ idx = torch.arange(length, device = device)
+ dist = idx.unsqueeze(1) - idx.unsqueeze(0)
+ block = block.masked_fill(dist >= sliding_window, float("-inf"))
+ return block
+
+
+def packed_segment_lengths(
+ seq_info: Tuple[torch.Tensor, torch.Tensor, int], total_tokens: Optional[int] = None
+) -> Tuple[int, ...]:
+ """Segment lengths of a packed row, the pad tail as its own segment; one D2H sync per batch."""
+ seq_lengths = seq_info[0]
+ entry = _SEGMENT_LENGTHS_CACHE.get(seq_lengths.device)
+ if entry is not None and entry[0] is seq_lengths and entry[1] == total_tokens:
+ return entry[2]
+ lengths = _with_padding_segment(
+ tuple(int(length) for length in seq_lengths.tolist()), total_tokens
+ )
+ _SEGMENT_LENGTHS_CACHE[seq_lengths.device] = (seq_lengths, total_tokens, lengths)
+ return lengths
+
+
def build_sdpa_packed_attention_mask(
seq_info: Tuple[torch.Tensor, torch.Tensor, int],
*,
@@ -720,16 +757,13 @@ def build_sdpa_packed_attention_mask(
for length in lengths:
if length <= 0:
continue
- block = torch.zeros((length, length), dtype = dtype, device = device)
- if is_causal:
- upper = torch.triu(torch.ones((length, length), device = device), diagonal = 1).bool()
- block = block.masked_fill(upper, float("-inf"))
- if sliding_window is not None and sliding_window > 0 and length > sliding_window:
- idx = torch.arange(length, device = device)
- dist = idx.unsqueeze(1) - idx.unsqueeze(0)
- window_mask = dist >= sliding_window
- block = block.masked_fill(window_mask, float("-inf"))
- mask[offset : offset + length, offset : offset + length] = block
+ mask[offset : offset + length, offset : offset + length] = packed_block_mask(
+ length,
+ dtype = dtype,
+ device = device,
+ sliding_window = sliding_window,
+ is_causal = is_causal,
+ )
offset += length
result = mask.unsqueeze(0).unsqueeze(0)
@@ -825,6 +859,7 @@ def clear_packed_caches():
_XFORMERS_MASK_CACHE.clear()
_PACKED_INFO_CACHE.clear()
_SDPA_MASK_CACHE.clear()
+ _SEGMENT_LENGTHS_CACHE.clear()
_XFORMERS_BLOCK_MASK_CACHE.clear()
_PADDED_CU_SEQLENS_CACHE.clear()