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 mRoPE flash attention: cover a padded tail, same decision when compiled (#16058)

Daniel Han85176e598e42
diff --git a/tests/test_flash_attention_mrope_packed.py b/tests/test_flash_attention_mrope_packed.py
index bd9708b368a..aa60fc3b359 100644
--- a/tests/test_flash_attention_mrope_packed.py
+++ b/tests/test_flash_attention_mrope_packed.py
@@ -137,10 +137,10 @@ def test_every_other_call_is_passed_through_unchanged(packed_rows):
{"position_ids": _mrope(8, 2), "packed_seq_lengths": lengths},
),
(
- _query(9),
+ _query(7),
None,
- {"position_ids": _mrope(9), "packed_seq_lengths": lengths},
- ), # rows not covered
+ {"position_ids": _mrope(7), "packed_seq_lengths": lengths},
+ ), # lengths run past the row
(
q,
None,
@@ -152,6 +152,67 @@ def test_every_other_call_is_passed_through_unchanged(packed_rows):
assert calls[-1] == kwargs
+def test_padded_tail_gets_its_own_segment(packed_rows):
+ # TRL's padding-free collator pads the flattened row to pad_to_multiple_of after the lengths
+ # are taken: the tail must not fall back to causal attention over every document.
+ forward, calls = packed_rows
+ lengths = torch.tensor([3, 5], dtype = torch.int32)
+ q = _query(16)
+ forward(q, q, q, None, position_ids = _mrope(16), packed_seq_lengths = lengths)
+ assert calls[-1]["cu_seq_lens_q"].tolist() == [0, 3, 8, 16]
+ assert calls[-1]["cu_seq_lens_k"].tolist() == [0, 3, 8, 16]
+ assert calls[-1]["max_length_q"] == calls[-1]["max_length_k"] == 8
+
+
+def _compiled_boundaries(packed_rows, cases, warm):
+ from torch._dynamo.testing import CompileCounter
+ from unsloth.utils import packing
+
+ _, calls = packed_rows
+
+ def step(q, lengths):
+ # Read the module attribute at call time, as transformers' flash_attention_forward does.
+ return fa_integration._flash_attention_forward(
+ q, q, q, None, position_ids = _mrope(q.shape[1]), packed_seq_lengths = lengths
+ )
+
+ torch._dynamo.reset()
+ counter = CompileCounter()
+ compiled = torch.compile(step, backend = counter, dynamic = True)
+ seen = []
+ for length, docs in cases:
+ lengths = torch.tensor(docs, dtype = torch.int32)
+ packing._PACKED_INFO_CACHE.clear()
+ if warm: # the hybrid varlen outer forward fills the cache before the layers run
+ packing.get_packed_info_from_kwargs(
+ {"packed_seq_lengths": lengths}, torch.device("cpu")
+ )
+ compiled(_query(length), lengths)
+ kw = calls[-1]
+ seen.append(
+ None
+ if "cu_seq_lens_q" not in kw
+ else (kw["cu_seq_lens_q"].tolist(), int(kw["max_length_q"]))
+ )
+ torch._dynamo.reset()
+ return seen, counter.frame_count
+
+
[email protected]("warm", [False, True])
+def test_compiled_calls_match_eager_boundaries(packed_rows, warm):
+ cases = [(8, [3, 5]), (16, [3, 5]), (7, [3, 5])]
+ seen, _ = _compiled_boundaries(packed_rows, cases, warm)
+ assert seen == [([0, 3, 8], 5), ([0, 3, 8, 16], 8), None]
+
+
[email protected]("warm", [False, True])
+def test_compiled_calls_do_not_recompile_per_document_length(packed_rows, warm):
+ cases = [(16, [16 - longest, longest]) for longest in range(8, 16)]
+ seen, frames = _compiled_boundaries(packed_rows, cases, warm)
+ assert [m for _, m in seen] == list(range(8, 16))
+ assert frames <= 4, frames
+
+
def test_packed_rows_patch_is_idempotent(packed_rows):
forward, _ = packed_rows
fix_transformers_flash_attention_mrope_packed_rows()
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index 1c2dcb3d57c..92c9b07260e 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -2145,19 +2145,26 @@ def _packed_row_varlen_kwargs(query, attention_mask, kwargs):
or query.shape[0] != 1
):
return None
- from .utils.packing import get_packed_info_from_kwargs
+ return _packed_row_boundaries(kwargs, query.device, query.shape[1])
- info = get_packed_info_from_kwargs(kwargs, query.device)
+
+def _packed_row_boundaries_eager(kwargs, device, total):
+ """Host-side packed-row boundaries, outside any compiled graph: max_seqlen as a guarded
+ constant recompiled once per distinct length."""
+ from .utils.packing import cover_padded_cu_seqlens, get_packed_info_from_kwargs
+
+ info = get_packed_info_from_kwargs(kwargs, device)
if info is None:
return None
- _, cu_seqlens, max_seqlen = info
- # One host read per batch, not per layer: rows that do not cover the query keep the original path.
- if not torch.compiler.is_compiling():
- checked = _PACKED_ROWS_CHECKED
- if checked[0] is not cu_seqlens or checked[1] != query.shape[1]:
- checked[:] = [cu_seqlens, query.shape[1], int(cu_seqlens[-1]) == query.shape[1]]
- if not checked[2]:
- return None
+ cu_seqlens = info[1]
+ # One host read per batch, not per layer: lengths past the row cannot be honoured.
+ checked = _PACKED_ROWS_CHECKED
+ if checked[0] is not cu_seqlens or checked[1] != total:
+ checked[:] = [cu_seqlens, total, int(cu_seqlens[-1]) <= total]
+ if not checked[2]:
+ return None
+ # A pad_to_multiple_of tail gets its own segment so no document attends to it.
+ cu_seqlens, max_seqlen = cover_padded_cu_seqlens(info, total)
return {
"cu_seq_lens_q": cu_seqlens,
"cu_seq_lens_k": cu_seqlens,
@@ -2166,6 +2173,19 @@ def _packed_row_varlen_kwargs(query, attention_mask, kwargs):
}
+# _packed_row_boundaries_eager under torch.compiler.disable, built when the patch is installed.
+_PACKED_ROW_BOUNDARIES_DISABLED = None
+
+
+def _packed_row_boundaries(kwargs, device, total):
+ import torch
+
+ disabled = _PACKED_ROW_BOUNDARIES_DISABLED
+ if disabled is not None and torch.compiler.is_compiling():
+ return disabled(kwargs, device, total)
+ return _packed_row_boundaries_eager(kwargs, device, total)
+
+
def fix_transformers_flash_attention_mrope_packed_rows():
"""Qwen3.5 / Qwen3.5-MoE on transformers 5.3 give decoder layers 3-row mRoPE ids, which cannot mark
document starts: take a packed row's boundaries from `packed_seq_lengths` instead."""
@@ -2176,6 +2196,10 @@ def fix_transformers_flash_attention_mrope_packed_rows():
current = getattr(fa_integration, "_flash_attention_forward", None)
if current is None or getattr(current, _PACKED_ROWS_PATCH_FLAG, False):
return
+ global _PACKED_ROW_BOUNDARIES_DISABLED
+ if _PACKED_ROW_BOUNDARIES_DISABLED is None:
+ import torch
+ _PACKED_ROW_BOUNDARIES_DISABLED = torch.compiler.disable(_packed_row_boundaries_eager)
@functools.wraps(current)
def _flash_attention_forward(