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 attention: no graph break on warm packed rows (#16416)

Daniel Han9db840f441e8
diff --git a/tests/test_flash_attention_mrope_packed.py b/tests/test_flash_attention_mrope_packed.py
index aa60fc3b359..04023435b4e 100644
--- a/tests/test_flash_attention_mrope_packed.py
+++ b/tests/test_flash_attention_mrope_packed.py
@@ -187,6 +187,8 @@ def _compiled_boundaries(packed_rows, cases, warm):
packing.get_packed_info_from_kwargs(
{"packed_seq_lengths": lengths}, torch.device("cpu")
)
+ # Dynamo guards the recording list's length.
+ calls.clear()
compiled(_query(length), lengths)
kw = calls[-1]
seen.append(
@@ -264,3 +266,57 @@ def test_packed_documents_do_not_see_each_other_under_flash_attention():
torch.testing.assert_close(
out, torch.cat([alone(0, first), alone(first, total)], dim = 1), atol = 2e-2, rtol = 2e-2
)
+
+
[email protected]("dynamic", [False, True])
+def test_warm_packed_rows_support_fullgraph_forward_backward(monkeypatch, dynamic):
+ from unsloth.utils import packing
+
+ def attention(q, k, v, mask, *args, **kwargs):
+ cu = kwargs.get("cu_seq_lens_q")
+ longest = kwargs.get("max_length_q")
+ offset = 0 if cu is None else cu.sum() + longest
+ return q.cos() + offset, cu, longest
+
+ monkeypatch.setattr(fa_integration, "_flash_attention_forward", attention)
+ fix_transformers_flash_attention_mrope_packed_rows()
+
+ def step(q, lengths):
+ q = q.sin()
+ return fa_integration._flash_attention_forward(
+ q, q, q, None, position_ids = _mrope(q.shape[1]), packed_seq_lengths = lengths
+ )
+
+ torch._dynamo.reset()
+ compiled = torch.compile(step, backend = "aot_eager", fullgraph = True, dynamic = dynamic)
+ try:
+ cases = [
+ (8, [3, 5], [0, 3, 8], 5),
+ (16, [3, 5], [0, 3, 8, 16], 8),
+ (7, [3, 5], None, None),
+ (16, [4, 12], [0, 4, 16], 12),
+ (16, [2, 14], [0, 2, 16], 14),
+ ]
+ for total, docs, expected_cu, expected_max in cases:
+ packing.clear_packed_caches()
+ lengths = torch.tensor(docs, dtype = torch.int32)
+ packing.get_packed_info_from_kwargs(
+ {"packed_seq_lengths": lengths}, torch.device("cpu")
+ )
+ q = torch.randn(1, total, 2, 8, requires_grad = True)
+ out, cu, longest = compiled(q, lengths)
+ assert (None if cu is None else cu.tolist()) == expected_cu
+ assert longest == expected_max
+ offset = 0 if expected_cu is None else sum(expected_cu) + expected_max
+ reference = q.sin().cos() + offset
+ torch.testing.assert_close(out, reference)
+ grad = torch.autograd.grad(out.sum(), q)[0]
+ expected_grad = torch.autograd.grad(reference.sum(), q)[0]
+ torch.testing.assert_close(grad, expected_grad)
+
+ report = torch._dynamo.explain(step)(q, lengths)
+ assert report.graph_count == 1
+ assert report.graph_break_count == 0
+ finally:
+ torch._dynamo.reset()
+ packing.clear_packed_caches()
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index e8149a1bb0b..c391ce2d34c 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -2182,6 +2182,28 @@ def _packed_row_boundaries(kwargs, device, total):
disabled = _PACKED_ROW_BOUNDARIES_DISABLED
if disabled is not None and torch.compiler.is_compiling():
+ from .utils.packing import _PACKED_INFO_CACHE, _cache_hit
+
+ entry = _PACKED_INFO_CACHE.get(device)
+ if (
+ entry is not None
+ and entry["seq_lengths"] is kwargs.get("packed_seq_lengths")
+ and _cache_hit(entry)
+ and "row_shape" in entry
+ ):
+ covered, max_seqlen = entry["row_shape"].shape
+ if covered > total:
+ return None
+ cu_seqlens = entry["result"][1]
+ if covered < total:
+ cu_seqlens = torch.cat([cu_seqlens, cu_seqlens.new_full((1,), total)])
+ max_seqlen = max(max_seqlen, total - covered)
+ return {
+ "cu_seq_lens_q": cu_seqlens,
+ "cu_seq_lens_k": cu_seqlens,
+ "max_length_q": max_seqlen,
+ "max_length_k": max_seqlen,
+ }
return disabled(kwargs, device, total)
return _packed_row_boundaries_eager(kwargs, device, total)
diff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.py
index feaf354a834..b9bd807a26d 100644
--- a/unsloth/utils/packing.py
+++ b/unsloth/utils/packing.py
@@ -1905,11 +1905,14 @@ def get_packed_info_from_kwargs(
max_seqlen = max(host)
result = (lengths, cu_seqlens, max_seqlen)
+ # Meta shapes carry symbolic host scalars without allocating device memory.
+ row_shape = torch.empty((sum(host), max_seqlen), device = "meta")
_refresh_derived_packed_caches(entry, seq_lengths, result, device)
_PACKED_INFO_CACHE[device] = {
"seq_lengths": seq_lengths,
"result": result,
"inference": _built_in_inference_mode(),
+ "row_shape": row_shape,
}
_PACKED_HOST_LENGTHS_CACHE[lengths.device] = (lengths, cu_seqlens, host)
return result