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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Size the packed attention mask at the padded length, not the token count (#8278)
Vineeth Sai Varikuntla9cf231814b64
diff --git a/tests/utils/test_attention_masks.py b/tests/utils/test_attention_masks.pyindex 9a5991c5e13..7f8288b075d 100644--- a/tests/utils/test_attention_masks.py+++ b/tests/utils/test_attention_masks.py@@ -60,6 +60,66 @@ def test_sdpa_packed_attention_mask_sliding_window():assert mask[0, 0, 0, 6].item() == float("-inf")+def test_sdpa_packed_attention_mask_covers_a_padded_flattened_row():+ seq_info = _make_seq_info([3, 4])+ mask = packing_utils.build_sdpa_packed_attention_mask(+ seq_info,+ dtype = torch.float32,+ device = torch.device("cpu"),+ total_tokens = 8,+ )++ assert mask.shape == (1, 1, 8, 8)++ assert torch.all(mask[0, 0, :7, 7] == float("-inf"))+ assert torch.all((mask[0, 0] > -math.inf).any(dim = -1))++ query = torch.randn(1, 1, 8, 4)+ out = torch.nn.functional.scaled_dot_product_attention(+ query,+ torch.randn(1, 1, 8, 4),+ torch.randn(1, 1, 8, 4),+ attn_mask = mask,+ )+ assert out.shape == (1, 1, 8, 4)+ assert not torch.isnan(out).any()+++def test_sdpa_packed_attention_mask_unpadded_is_unchanged():+ seq_info = _make_seq_info([3, 4])+ without = packing_utils.build_sdpa_packed_attention_mask(+ seq_info,+ dtype = torch.float32,+ device = torch.device("cpu"),+ )+ packing_utils._SDPA_MASK_CACHE.clear()+ exact = packing_utils.build_sdpa_packed_attention_mask(+ seq_info,+ dtype = torch.float32,+ device = torch.device("cpu"),+ total_tokens = 7,+ )++ assert without.shape == (1, 1, 7, 7)+ assert torch.equal(without, exact)+++def test_sdpa_packed_attention_mask_keeps_the_window_when_padded():+ seq_info = _make_seq_info([5, 3])+ mask = packing_utils.build_sdpa_packed_attention_mask(+ seq_info,+ dtype = torch.float32,+ device = torch.device("cpu"),+ sliding_window = 3,+ total_tokens = 10,+ )++ assert mask.shape == (1, 1, 10, 10)+ assert mask[0, 0, 3, 0].item() == float("-inf")+ assert mask[0, 0, 4, 2].item() > -math.inf+ assert torch.all((mask[0, 0] > -math.inf).any(dim = -1))++def test_xformers_block_mask_sliding_window(monkeypatch):class _FakeMask:def __init__(@@ -328,6 +388,7 @@ def test_run_attention_sdpa_passes_sliding_window(monkeypatch):dtype,device,sliding_window = None,+ total_tokens = None,):captured["window"] = sliding_windowreturn original_builder(@@ -335,6 +396,7 @@ def test_run_attention_sdpa_passes_sliding_window(monkeypatch):dtype = dtype,device = device,sliding_window = sliding_window,+ total_tokens = total_tokens,)monkeypatch.setattr(@@ -404,6 +466,7 @@ def test_run_attention_xformers_passes_sliding_window(monkeypatch):*,sliding_window = None,base_mask = None,+ total_tokens = None,):captured["window"] = sliding_windowcaptured["base"] = base_mask@@ -520,6 +583,61 @@ def test_run_attention_flash_varlen_receives_window_and_softcap(monkeypatch):assert captured["kwargs"]["window_size"] == window_tuple+def test_run_attention_flash_varlen_covers_a_padded_flattened_row(monkeypatch):+ packing_utils.clear_packed_caches()+ seq_info = _make_seq_info([3, 4])+ total = 8++ def _fake_flash_varlen(Q, K, V, cu_q, cu_k, max_q, max_k, **kwargs):+ # Like flash-attn: rows outside cu_seqlens are never written.+ out = torch.full_like(Q, float("nan"))+ bounds = cu_q.tolist()+ for start, end in zip(bounds[:-1], bounds[1:]):+ assert end - start <= max_q+ q = Q[start:end].transpose(0, 1)+ k = K[start:end].transpose(0, 1)+ v = V[start:end].transpose(0, 1)+ out[start:end] = torch.nn.functional.scaled_dot_product_attention(+ q, k, v, is_causal = True+ ).transpose(0, 1)+ return out++ monkeypatch.setattr(attention_dispatch, "flash_attn_varlen_func", _fake_flash_varlen)+ monkeypatch.setattr(attention_dispatch, "HAS_FLASH_ATTENTION", True)++ config = attention_dispatch.AttentionConfig(+ backend = attention_dispatch.FLASH_VARLEN,+ n_kv_heads = 1,+ n_groups = 1,+ flash_varlen_kwargs = {"causal": True},+ )+ context = attention_dispatch.AttentionContext(+ bsz = 1,+ q_len = total,+ kv_seq_len = total,+ n_heads = 1,+ head_dim = 4,+ requires_grad = False,+ seq_info = seq_info,+ attention_mask = None,+ causal_mask = None,+ )+ Q = torch.randn(1, 1, total, 4)+ K = torch.randn(1, 1, total, 4)+ V = torch.randn(1, 1, total, 4)++ out = attention_dispatch.run_attention(config = config, context = context, Q = Q, K = K, V = V)++ assert not torch.isnan(out).any()+ first = torch.nn.functional.scaled_dot_product_attention(+ Q[..., :3, :], K[..., :3, :], V[..., :3, :], is_causal = True+ )+ assert torch.allclose(out[0, :3, 0].float(), first[0, 0], atol = 2e-2)++ cu_seqlens, max_seqlen = packing_utils.cover_padded_cu_seqlens(seq_info, 7)+ assert cu_seqlens is seq_info[1] and max_seqlen == 4++"""Unit tests for packed-attention mask helpers with sliding-window logic."""diff --git a/tests/utils/test_packing.py b/tests/utils/test_packing.pyindex fb650fa4a37..35a9b55df5c 100644--- a/tests/utils/test_packing.py+++ b/tests/utils/test_packing.py@@ -1161,6 +1161,7 @@ def test_packing_sdpa(tmp_path):device,*,sliding_window = None,+ total_tokens = None,):mask_calls.append(tuple(seq_info[0].tolist()))return original_mask(@@ -1168,6 +1169,7 @@ def test_packing_sdpa(tmp_path):dtype = dtype,device = device,sliding_window = sliding_window,+ total_tokens = total_tokens,)def _capture_loss(*, logits, labels, **loss_kwargs):diff --git a/tests/utils/test_varlen_int32_overflow_guard.py b/tests/utils/test_varlen_int32_overflow_guard.pyindex df464970791..57c362c9bbb 100644--- a/tests/utils/test_varlen_int32_overflow_guard.py+++ b/tests/utils/test_varlen_int32_overflow_guard.py@@ -84,7 +84,7 @@ def _context(n_heads = n_heads,head_dim = head_dim,requires_grad = requires_grad,- seq_info = (lengths, None, 1),+ seq_info = (lengths, torch.zeros(n_docs + 1, dtype = torch.int32), 1),attention_mask = None,causal_mask = None,)@@ -167,6 +167,47 @@ def test_softcapped_model_under_the_bound_is_untouched(monkeypatch, backend):assert _run(monkeypatch, backend, n_docs = 64, requires_grad = True, softcap = 50.0) == backend[email protected]("backend", [ad.XFORMERS, ad.FLASH_VARLEN])+def test_padded_tail_segment_counts_toward_the_bound(monkeypatch, backend):+ # 8127 one-token documents padded to 8192 tokens: the tail is the 8128th segment, which puts+ # dq_accum at exactly 2**31 elements for 16 heads / head_dim 128.+ from unsloth.utils import packing as packing_utils++ n_docs, total = 8127, 8192+ assert not ad._varlen_backward_overflows_int32(n_docs, total, 16, 128)+ assert ad._varlen_backward_overflows_int32(n_docs + 1, total, 16, 128)++ packing_utils.clear_packed_caches()+ taken = []+ monkeypatch.setattr(+ ad, "xformers_attention", lambda *a, **k: taken.append(ad.XFORMERS), raising = False+ )+ monkeypatch.setattr(+ ad, "flash_attn_varlen_func", lambda *a, **k: taken.append(ad.FLASH_VARLEN), raising = False+ )+ monkeypatch.setattr(+ ad,+ "scaled_dot_product_attention",+ lambda Q, *a, **k: taken.append(ad.SDPA) or torch.zeros_like(Q),+ )+ monkeypatch.setattr(ad, "build_xformers_block_causal_mask", lambda *a, **k: object())+ monkeypatch.setattr(ad, "build_sdpa_packed_attention_mask", lambda *a, **k: None)+ monkeypatch.setattr(ad, "_VARLEN_INT32_GUARD_DISABLED", False)+ monkeypatch.setattr(ad, "HAS_FLASH_ATTENTION", True)+ ad._VARLEN_INT32_WARNED[0] = False++ context = _context(n_docs, total, True)+ context.seq_info = (+ torch.ones(n_docs, dtype = torch.int32),+ torch.arange(n_docs + 1, dtype = torch.int32),+ 1,+ )+ q = torch.zeros((1, 16, total, 128), requires_grad = True)+ config = ad.AttentionConfig(backend = backend, n_kv_heads = 16, n_groups = 1)+ ad.run_attention(config = config, context = context, Q = q, K = q, V = q)+ assert taken == [ad.SDPA]++@pytest.mark.parametrize("backend", [ad.XFORMERS, ad.FLASH_VARLEN])def test_normal_partition_keeps_the_fast_backend(monkeypatch, backend):assert _run(monkeypatch, backend, n_docs = 64, requires_grad = True) == backenddiff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.pyindex 82b4e7cb4ed..5d0edc6a3ec 100644--- a/unsloth/utils/attention_dispatch.py+++ b/unsloth/utils/attention_dispatch.py@@ -26,6 +26,7 @@ from ..models._utils import *from ..utils.packing import (build_sdpa_packed_attention_mask,build_xformers_block_causal_mask,+ cover_padded_cu_seqlens,move_xformers_attention_bias,)@@ -314,7 +315,7 @@ def run_attention(backend = SDPA# Both varlen-capable backends land in the same flash-attn 2 backward kernel, so guard both before- # the int32 overflow aborts the process. Integer arithmetic only, no device sync.+ # the int32 overflow aborts the process. Integer arithmetic plus one cached sync per step.if backend in (FLASH_VARLEN, XFORMERS) and not _VARLEN_INT32_GUARD_DISABLED:# Both terms are needed. Q/K/V: a frozen hidden state feeding trainable LoRA q/k/v still yields a# Q that requires grad. context.requires_grad: gradient checkpointing runs its FIRST forward under@@ -325,9 +326,13 @@ def run_attention()if will_backward:seq_info = context.seq_info- # seq_info[0] is the per-document length tensor; .numel() needs no D2H copy.- n_seqs = seq_info[0].numel() if seq_info is not None else context.bsztotal_q = context.bsz * context.q_len+ # Includes the collator's trailing pad segment.+ n_seqs = (+ cover_padded_cu_seqlens(seq_info, total_q)[0].numel() - 1+ if seq_info is not None+ else context.bsz+ )if _varlen_backward_overflows_int32(n_seqs, total_q, context.n_heads, context.head_dim):# SDPA cannot apply logit softcapping, so rerouting a softcapped model (Gemma 2) would keep it# training on wrong logits and gradients, worse than the fault this guard avoids.@@ -400,7 +405,7 @@ def run_attention(Q_f = Q.transpose(1, 2).reshape(bsz * q_len, n_heads, head_dim)K_f = K.transpose(1, 2).reshape(bsz * q_len, config.n_kv_heads, head_dim)V_f = V.transpose(1, 2).reshape(bsz * q_len, config.n_kv_heads, head_dim)- _, cu_seqlens, max_seqlen = context.seq_info+ cu_seqlens, max_seqlen = cover_padded_cu_seqlens(context.seq_info, bsz * q_len)return flash_attn_varlen_func(Q_f,K_f,@@ -432,6 +437,7 @@ def run_attention(context.seq_info,sliding_window = sliding_window,base_mask = base_mask,+ total_tokens = K.shape[-2],)attn_bias = move_xformers_attention_bias(attn_bias, Q.device)@@ -496,6 +502,7 @@ def run_attention(dtype = Q.dtype,device = Q.device,sliding_window = sliding_window,+ total_tokens = K.shape[-2],)else:q_len_local = Q.shape[-2]diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.pyindex f6a5ca41e92..f0a72b47969 100644--- a/unsloth/utils/packing.py+++ b/unsloth/utils/packing.py@@ -46,6 +46,9 @@ _SDPA_MASK_CACHE: dict = {}# Cache per device for build_xformers_block_causal_mask to avoid repeated D2H sync across layers_XFORMERS_BLOCK_MASK_CACHE: dict = {}+# Cache per device for cover_padded_cu_seqlens to avoid repeated D2H sync across layers+_PADDED_CU_SEQLENS_CACHE: dict = {}+def _window_cache_key(sliding_window: Optional[int]) -> int:if sliding_window is None or sliding_window <= 0:@@ -589,11 +592,46 @@ def get_packed_info_from_kwargs(return result+def _with_padding_segment(lengths: Tuple[int, ...], total_tokens: Optional[int]) -> Tuple[int, ...]:+ # TRL pads the flattened padding-free row to pad_to_multiple_of after the lengths are+ # taken; the tail gets its own block, since a row outside every block softmaxes to NaN.+ if total_tokens is None:+ return lengths+ padding = total_tokens - sum(lengths)+ if padding <= 0:+ return lengths+ return lengths + (padding,)+++def cover_padded_cu_seqlens(+ seq_info: Tuple[torch.Tensor, torch.Tensor, int], total_tokens: int+) -> Tuple[torch.Tensor, int]:+ """Flash varlen leaves rows past cu_seqlens[-1] unwritten, so the pad tail gets a segment."""+ _, cu_seqlens, max_seqlen = seq_info+ device = cu_seqlens.device+ entry = _PADDED_CU_SEQLENS_CACHE.get(device)+ if entry is not None and entry["cu_seqlens"] is cu_seqlens and entry["total"] == total_tokens:+ return entry["result"]++ padding = total_tokens - int(cu_seqlens[-1].item())+ result = (cu_seqlens, max_seqlen)+ if padding > 0:+ tail = torch.tensor([total_tokens], dtype = cu_seqlens.dtype, device = device)+ result = (torch.cat([cu_seqlens, tail]), max(max_seqlen, padding))+ _PADDED_CU_SEQLENS_CACHE[device] = {+ "cu_seqlens": cu_seqlens,+ "total": total_tokens,+ "result": result,+ }+ return result++def build_xformers_block_causal_mask(seq_info: Optional[Tuple[torch.Tensor, torch.Tensor, int]],*,sliding_window: Optional[int] = None,base_mask: Optional[Any] = None,+ total_tokens: Optional[int] = None,):if _XFormersBlockMask is None:return None@@ -601,7 +639,7 @@ def build_xformers_block_causal_mask(seq_lengths, _, _ = seq_info# Cache the mask to avoid repeated D2H sync across layersdevice = seq_lengths.device- params = (sliding_window,)+ params = (sliding_window, total_tokens)entry = _XFORMERS_BLOCK_MASK_CACHE.get(device)if entry is not None and entry["seq_lengths"] is seq_lengths and entry["params"] == params:return entry["mask"]@@ -610,6 +648,7 @@ def build_xformers_block_causal_mask(if lengths_tensor.numel() == 0:return Nonelengths = tuple(int(x) for x in lengths_tensor.tolist())+ lengths = _with_padding_segment(lengths, total_tokens)mask = _get_cached_block_mask(lengths, sliding_window, device)_XFORMERS_BLOCK_MASK_CACHE[device] = {@@ -636,15 +675,20 @@ def build_sdpa_packed_attention_mask(dtype: torch.dtype,device: torch.device,sliding_window: Optional[int] = None,+ total_tokens: Optional[int] = None,) -> torch.Tensor:seq_lengths, _, _ = seq_info- params = (dtype, sliding_window)+ params = (dtype, sliding_window, total_tokens)entry = _SDPA_MASK_CACHE.get(device)if entry is not None and entry["seq_lengths"] is seq_lengths and entry["params"] == params:return entry["mask"]- total_tokens = int(seq_lengths.sum().item())+ lengths = _with_padding_segment(+ tuple(int(length) for length in seq_lengths.tolist()),+ total_tokens,+ )+ total_tokens = sum(lengths)mask = torch.full((total_tokens, total_tokens),float("-inf"),@@ -652,8 +696,7 @@ def build_sdpa_packed_attention_mask(device = device,)offset = 0- for length in seq_lengths.tolist():- length = int(length)+ for length in lengths:if length <= 0:continueblock = torch.zeros((length, length), dtype = dtype, device = device)@@ -761,6 +804,7 @@ def clear_packed_caches():_PACKED_INFO_CACHE.clear()_SDPA_MASK_CACHE.clear()_XFORMERS_BLOCK_MASK_CACHE.clear()+ _PADDED_CU_SEQLENS_CACHE.clear()__all__ = [@@ -773,6 +817,7 @@ __all__ = ["get_packed_info_from_kwargs","build_xformers_block_causal_mask","build_sdpa_packed_attention_mask",+ "cover_padded_cu_seqlens","mask_packed_sequence_boundaries","mask_packed_boundary_labels","clear_packed_caches",