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
Keep flash attention from reading Qwen3.5 mRoPE position ids as packed sequences (#12856)
Daniel Hanc6cfbb71cc72
diff --git a/tests/test_flash_attention_mrope_packed.py b/tests/test_flash_attention_mrope_packed.pynew file mode 100644index 00000000000..04aff428a65--- /dev/null+++ b/tests/test_flash_attention_mrope_packed.py@@ -0,0 +1,84 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""One unpadded Qwen3.5 row must not reach flash attention as three packed rows (transformers#44910)."""++import pytest++torch = pytest.importorskip("torch")+fa_utils = pytest.importorskip("transformers.modeling_flash_attention_utils")++from real_accelerator import has_real_cuda # tests/_shared, on sys.path via tests/conftest.py++from unsloth.import_fixes import ( # noqa: E402+ _mrope_position_ids_read_as_packed,+ fix_transformers_flash_attention_mrope_packed_sequence,+)+++def _mrope(length, batch = 1):+ return torch.arange(length).view(1, 1, length).expand(3, batch, length)+++def patched():+ before = fa_utils._is_packed_sequence+ fix_transformers_flash_attention_mrope_packed_sequence()+ yield fa_utils._is_packed_sequence+ fa_utils._is_packed_sequence = before+++def test_mrope_ids_are_never_packed(patched):+ for length in (1, 4, 304):+ assert not patched(_mrope(length), batch_size = 1)+++def test_two_dim_packing_is_unchanged(patched):+ original = getattr(patched, "__wrapped__", patched)+ packed = torch.tensor([[0, 1, 2, 0, 1, 2, 3]])+ plain = torch.arange(7).view(1, 7)+ for ids, batch in ((packed, 1), (plain, 1), (packed.expand(2, 7), 2), (None, 1)):+ assert bool(patched(ids, batch_size = batch)) == bool(original(ids, batch_size = batch))+ assert patched(packed, batch_size = 1)+++def test_probe_reads_the_original(patched):+ original = getattr(patched, "__wrapped__", patched)+ assert _mrope_position_ids_read_as_packed(original) == bool(original(_mrope(4), batch_size = 1))+ assert not _mrope_position_ids_read_as_packed(patched)+++def test_idempotent(patched):+ fix_transformers_flash_attention_mrope_packed_sequence()+ assert fa_utils._is_packed_sequence is patched++[email protected](not has_real_cuda(), reason = "flash-attn needs CUDA")+def test_flash_attention_forward_keeps_one_row_unpacked(patched, monkeypatch):+ pytest.importorskip("flash_attn")+ calls = []+ real = fa_utils._prepare_from_posids+ monkeypatch.setattr(+ fa_utils,+ "_prepare_from_posids",+ lambda *a, **k: calls.append(1) or real(*a, **k),+ )+ length, heads, dim = 304, 4, 256+ q = torch.randn(1, length, heads, dim, device = "cuda", dtype = torch.bfloat16)+ k, v = torch.randn_like(q), torch.randn_like(q)+ out = fa_utils._flash_attention_forward(+ q,+ k,+ v,+ attention_mask = None,+ query_length = length,+ is_causal = True,+ position_ids = _mrope(length).cuda(),+ attn_implementation = "flash_attention_2",+ )+ ref = torch.nn.functional.scaled_dot_product_attention(+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal = True+ ).transpose(1, 2)+ assert calls == []+ assert torch.isfinite(out).all()+ torch.testing.assert_close(out, ref, atol = 2e-2, rtol = 2e-2)diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.pyindex 195507ab15e..b3f1705298d 100644--- a/unsloth/_gpu_init.py+++ b/unsloth/_gpu_init.py@@ -309,6 +309,7 @@ from .import_fixes import (fix_transformers5_image_processing_reexports,fix_transformers_composite_prefix_renaming,fix_transformers_fully_masked_rows,+ fix_transformers_flash_attention_mrope_packed_sequence,fix_transformers_untrusted_config_fields,fix_transformers_chat_template_path_traversal,fix_transformers_chunked_mask_block_sequence_ids,@@ -371,6 +372,7 @@ fix_transformers5_bare_annotation_configs()# nothing. Ordered here, before anything imports a model, so a plain transformers.generate in the# same process is covered too (#9708).fix_transformers_fully_masked_rows()+fix_transformers_flash_attention_mrope_packed_sequence()fix_transformers_chunked_mask_block_sequence_ids()fix_transformers_flex_mask_graph_breaks()# CVE-2026-4372 / 5241 / 9856, no-ops once transformers carries the fix; before any config loads.diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.pyindex 317f4f7eb38..9b8acdf4168 100644--- a/unsloth/import_fixes.py+++ b/unsloth/import_fixes.py@@ -2048,6 +2048,49 @@ def fix_transformers_fully_masked_rows():logger.info(f"Unsloth: Failed patching sdpa_mask ({e})")+_PACKED_SEQUENCE_PATCH_FLAG = "_unsloth_patched_is_packed_sequence"+++def _mrope_position_ids_read_as_packed(is_packed_sequence):+ """Does `_is_packed_sequence` call Qwen3.5's `(3, 1, L)` mRoPE ids packed (transformers#44910)?"""+ try:+ import torch+ positions = torch.arange(4, device = "cpu").view(1, 1, 4).expand(3, 1, 4)+ return bool(is_packed_sequence(positions, batch_size = 1))+ except Exception:+ return False+++def fix_transformers_flash_attention_mrope_packed_sequence():+ """Stop transformers 5.3 turning Qwen3.5's `(3, 1, L)` mRoPE ids into out-of-bounds+ `cu_seqlens = [0, L, 2L, 3L]`: packed ids are flattened 2D `(1, total)`, never more dims.+ """+ try:+ from transformers import modeling_flash_attention_utils as fa_utils+ except Exception:+ return+ current = getattr(fa_utils, "_is_packed_sequence", None)+ if current is None or getattr(current, _PACKED_SEQUENCE_PATCH_FLAG, False):+ return+ original = getattr(current, "__wrapped__", current)+ if not _mrope_position_ids_read_as_packed(original):+ return++ @functools.wraps(original)+ def _is_packed_sequence(position_ids, batch_size):+ if position_ids is not None and position_ids.dim() > 2:+ return False+ return original(position_ids, batch_size)++ _is_packed_sequence.__wrapped__ = original+ setattr(_is_packed_sequence, _PACKED_SEQUENCE_PATCH_FLAG, True)+ fa_utils._is_packed_sequence = _is_packed_sequence+ logger.info(+ "Unsloth: Patching transformers `_is_packed_sequence` so flash attention never "+ "reads mRoPE position ids as packed sequences (transformers#44910)"+ )++_CHUNKED_MASK_PATCH_FLAG = "_unsloth_patched_chunked_block_sequence_ids"_BLOCK_SEQUENCE_IDS = "block_sequence_ids"