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
Packed rows on sliding-window layers take varlen on the transformers path, plus opt-in FA4 / FA3 for packed training (#13326)
Daniel Han839996806873
diff --git a/tests/test_hf_packed_attention.py b/tests/test_hf_packed_attention.pyindex 398acd779cf..5c0377bcd39 100644--- a/tests/test_hf_packed_attention.py+++ b/tests/test_hf_packed_attention.py@@ -17,6 +17,29 @@ def _block_causal(lengths, device = "cpu"):return ((segment[:, None] == segment[None, :]).tril())[None, None]+def _hf_window_mask(+ lengths,+ window,+ device = "cpu",+):+ """The mask transformers builds for a packed row on a sliding layer: its own mask functions."""+ from transformers.masking_utils import (+ and_masks,+ find_packed_sequence_indices,+ packed_sequence_mask_function,+ sliding_window_causal_mask_function,+ )++ position_ids = torch.cat([torch.arange(n) for n in lengths])[None].to(device)+ packed = find_packed_sequence_indices(position_ids)+ fn = and_masks(+ sliding_window_causal_mask_function(window), packed_sequence_mask_function(packed)+ )+ idx = torch.arange(sum(lengths), device = device)+ zero = torch.zeros((), dtype = torch.long, device = device)+ return fn(zero, zero, idx[:, None], idx[None, :])[None, None]++def _cu(lengths, device = "cpu"):return torch.tensor([0] + list(torch.tensor(lengths).cumsum(0)), dtype = torch.int32, device = device@@ -26,9 +49,9 @@ def _cu(lengths, device = "cpu"):@pytest.fixture(autouse = True)def _fresh_state():saved = hpa._ORIG_SDPA[0]- hpa._MASK_CHECK[:] = [None, None, None]+ hpa._MASK_CHECK.clear()yield- hpa._MASK_CHECK[:] = [None, None, None]+ hpa._MASK_CHECK.clear()hpa._ORIG_SDPA[0] = saved@@ -62,6 +85,40 @@ def test_any_other_mask_keeps_the_masked_path(edit):assert not hpa._mask_is_block_causal(mask, cu, total)[email protected]("window", [1, 3, 4, 128])+def test_windowed_mask_is_recognised_only_with_its_window(window):+ lengths = [2, 7, 130, 4]+ mask, cu, total = _hf_window_mask(lengths, window), _cu(lengths), sum(lengths)+ assert hpa._mask_is_block_causal(mask, cu, total, window)+ # One off either way, or no window at all, is a different band for the 130-token document.+ for wrong in (window - 1 or None, window + 1, None):+ hpa._MASK_CHECK.clear()+ assert not hpa._mask_is_block_causal(mask, cu, total, wrong)+++def test_documents_inside_the_window_are_plain_block_causal():+ lengths = [3, 4, 2]+ mask = _hf_window_mask(lengths, 4)+ assert torch.equal(mask, _block_causal(lengths))+ assert hpa._mask_is_block_causal(mask, _cu(lengths), 9, 4)+++def test_sliding_and_full_layers_keep_their_own_verdicts():+ lengths = [6, 9]+ cu = _cu(lengths)+ full, sliding = _block_causal(lengths), _hf_window_mask(lengths, 3)+ for _ in range(3):+ assert hpa._mask_is_block_causal(full, cu, 15)+ assert hpa._mask_is_block_causal(sliding, cu, 15, 3)+ assert hpa.HF_PACKED_ATTENTION_STATS["mask_checks"] >= 2+ checks = hpa.HF_PACKED_ATTENTION_STATS["mask_checks"]+ assert hpa._mask_is_block_causal(full, cu, 15)+ assert hpa._mask_is_block_causal(sliding, cu, 15, 3)+ assert hpa.HF_PACKED_ATTENTION_STATS["mask_checks"] == checks+ # The same mask object asked about another window is checked, not answered from the cache.+ assert not hpa._mask_is_block_causal(full, cu, 15, 3)++def test_mask_verdict_is_cached_per_mask_object():lengths = [4, 4]mask, cu = _block_causal(lengths), _cu(lengths)@@ -101,6 +158,10 @@ def test_unpacked_calls_go_straight_through(monkeypatch):_CUDA = pytest.mark.skipif(not has_real_cuda(), reason = "needs a CUDA device")+# torch varlen is never used on ROCm (_torch_varlen returns None there).+_TORCH_VARLEN_HOST = pytest.mark.skipif(+ torch.version.hip is not None, reason = "torch varlen is off on ROCm"+)@_CUDA@@ -108,7 +169,10 @@ _CUDA = pytest.mark.skipif(not has_real_cuda(), reason = "needs a CUDA device")"why",["none",- "sliding",+ "window_inside_documents",+ "sliding_wrong_window",+ "zero_window",+ "float_window","softcap","sinks","fp32",@@ -140,8 +204,16 @@ def test_packed_calls_that_varlen_cannot_express_fall_back(monkeypatch, why):device, dtype, B = "cuda", torch.bfloat16, 1kwargs = {"packed_seq_lengths": torch.tensor(lengths, dtype = torch.int32)}dropout, mask, v_width = 0.0, _block_causal(lengths, "cuda"), D- if why == "sliding":+ if why == "window_inside_documents":+ # Both documents fit the window, so the band is the plain block-causal mask.module.sliding_window = 4+ elif why == "sliding_wrong_window":+ # The layer says 2, the mask has no band.+ module.sliding_window = 2+ elif why == "zero_window":+ kwargs["sliding_window"] = 0+ elif why == "float_window":+ module.sliding_window = 4.0elif why == "softcap":module.config = types.SimpleNamespace(attn_logit_softcapping = 50.0)elif why == "module_softcap":@@ -179,7 +251,7 @@ def test_packed_calls_that_varlen_cannot_express_fall_back(monkeypatch, why):out = hpa._sdpa_packed_varlen(module, q, k, v, mask, 0.0, **kwargs)else:out = hpa._sdpa_packed_varlen(module, q, k, v, mask, dropout = dropout, **kwargs)- if why == "none":+ if why in ("none", "window_inside_documents"):assert out[0].shape == (1, 6, 4, D) and seen == []assert hpa.HF_PACKED_ATTENTION_STATS["fast"] == before["fast"] + 1else:@@ -301,9 +373,40 @@ def test_install_forwards_router_sentinels_and_runs_once(monkeypatch):@_CUDA[email protected]("window", [None, 4])+def test_rocm_keeps_windowed_rows_off_flash_attn(monkeypatch, window):+ """flash-attn's ROCm backend lists sliding windows as work in progress."""+ from unsloth.utils import attention_dispatch as ad++ seen, orig = _calls()+ hpa._ORIG_SDPA[0] = orig+ dispatched = []+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)+ monkeypatch.setattr(torch.version, "hip", "6.4")+ monkeypatch.setattr(ad, "select_attention_backend", lambda use_varlen = False: ad.FLASH_VARLEN)+ monkeypatch.setattr(ad, "run_attention", lambda **kwargs: dispatched.append(1) or kwargs["Q"])+ lengths = [3, 5]+ q = torch.randn(1, 4, 8, 64, device = "cuda", dtype = torch.bfloat16)+ mask = (+ _block_causal(lengths, "cuda")+ if window is None+ else _hf_window_mask(lengths, window, "cuda")+ )+ module = types.SimpleNamespace(is_causal = True, num_key_value_groups = 1, sliding_window = window)+ hpa._sdpa_packed_varlen(+ module, q, q, q, mask, packed_seq_lengths = torch.tensor(lengths, dtype = torch.int32)+ )+ if window is None:+ assert dispatched and not seen+ else:+ assert seen and not dispatched+++@_CUDA[email protected]("window", [None, 3, 4, 128])@pytest.mark.parametrize("route", ["torch", "torch_2_11", "dispatch"])@pytest.mark.parametrize("n_kv", [8, 2])-def test_varlen_matches_sdpa_over_the_dense_mask(monkeypatch, n_kv, route):+def test_varlen_matches_sdpa_over_the_dense_mask(monkeypatch, n_kv, route, window):from unsloth.utils.attention_dispatch import HAS_FLASH_ATTENTION, HAS_XFORMERSif route != "dispatch" and hpa._torch_varlen(torch.device("cuda", 0)) is None:@@ -327,13 +430,19 @@ def test_varlen_matches_sdpa_over_the_dense_mask(monkeypatch, n_kv, route):hpa._ORIG_SDPA[0] = sdpa_attention_forwardmonkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)torch.manual_seed(0)- lengths = [37, 100, 5, 114]+ lengths = [37, 100, 2, 5, 230]T, H, D = sum(lengths), 8, 64- module = types.SimpleNamespace(is_causal = True, num_key_value_groups = H // n_kv, training = True)+ module = types.SimpleNamespace(+ is_causal = True, num_key_value_groups = H // n_kv, training = True, sliding_window = window+ )q = torch.randn(1, H, T, D, device = "cuda", dtype = torch.bfloat16, requires_grad = True)k = torch.randn(1, n_kv, T, D, device = "cuda", dtype = torch.bfloat16, requires_grad = True)v = torch.randn(1, n_kv, T, D, device = "cuda", dtype = torch.bfloat16, requires_grad = True)- mask = _block_causal(lengths, "cuda")+ mask = (+ _block_causal(lengths, "cuda")+ if window is None+ else _hf_window_mask(lengths, window, "cuda")+ )psl = torch.tensor(lengths, dtype = torch.int32)before = hpa.HF_PACKED_ATTENTION_STATS["fast"]fast, _ = hpa._sdpa_packed_varlen(module, q, k, v, mask, scaling = 0.11, packed_seq_lengths = psl)@@ -417,6 +526,7 @@ def test_int32_guard_follows_training_or_grad_mode(monkeypatch, mode):@_CUDA+@_TORCH_VARLEN_HOSTdef test_a_refusing_torch_varlen_hands_the_call_back(monkeypatch):seen, orig = _calls()hpa._ORIG_SDPA[0] = orig@@ -451,6 +561,7 @@ def test_torch_varlen_kill_switch(monkeypatch):@_CUDA+@_TORCH_VARLEN_HOST@pytest.mark.parametrize("policy", ["math_only", "flash_disabled", "math_first", "deterministic"])def test_an_sdpa_policy_keeps_every_varlen_kernel_off(monkeypatch, policy):"""The wrapped sdpa runs, not torch varlen nor the xformers / flash-attn dispatch; outside, varlen runs."""@@ -506,3 +617,56 @@ def test_an_sdpa_policy_keeps_every_varlen_kernel_off(monkeypatch, policy):assert calls == [] and len(seen) == 1run()assert calls == [1]+++@_CUDA[email protected]("window", [None, 4])+def test_tiny_mistral_packed_row_matches_the_masked_path(monkeypatch, window):+ """A real sliding-window decoder: packed logits and grads with the wrapper equal the wrapped sdpa."""+ transformers = pytest.importorskip("transformers")+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS+ from unsloth.utils.attention_dispatch import HAS_FLASH_ATTENTION, HAS_XFORMERS++ if not (HAS_FLASH_ATTENTION or HAS_XFORMERS or hpa._torch_varlen(torch.device("cuda", 0))):+ pytest.skip("no varlen kernel on this build")+ hpa._ORIG_SDPA[0] = None+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)+ from transformers.integrations.sdpa_attention import sdpa_attention_forward++ # transformers' own entry: an earlier test can leave the installed wrapper in the mapping.+ monkeypatch.setitem(ALL_ATTENTION_FUNCTIONS, "sdpa", sdpa_attention_forward)+ assert hpa.enable_hf_packed_attention()+ torch.manual_seed(0)+ config = transformers.MistralConfig(+ vocab_size = 128,+ hidden_size = 256,+ intermediate_size = 256,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ head_dim = 64,+ sliding_window = window,+ attn_implementation = "sdpa",+ )+ model = transformers.MistralForCausalLM(config).cuda().to(torch.bfloat16)+ lengths = [3, 11, 7]+ ids = torch.randint(0, 128, (1, sum(lengths)), device = "cuda")+ position_ids = torch.cat([torch.arange(n) for n in lengths])[None].cuda()+ psl = torch.tensor(lengths, dtype = torch.int32)++ def run():+ model.zero_grad()+ out = model(+ input_ids = ids, position_ids = position_ids, packed_seq_lengths = psl, use_cache = False+ )+ out.logits.float().square().mean().backward()+ return out.logits.detach().float(), [p.grad.float() for p in model.parameters()]++ before = hpa.HF_PACKED_ATTENTION_STATS["fast"]+ fast_logits, fast_grads = run()+ assert hpa.HF_PACKED_ATTENTION_STATS["fast"] == before + 2+ monkeypatch.setenv("UNSLOTH_HF_PACKED_VARLEN", "0")+ ref_logits, ref_grads = run()+ torch.testing.assert_close(fast_logits, ref_logits, atol = 3e-2, rtol = 3e-2)+ for a, b in zip(fast_grads, ref_grads):+ torch.testing.assert_close(a, b, atol = 3e-2, rtol = 5e-2)diff --git a/tests/utils/test_flash_impl.py b/tests/utils/test_flash_impl.pynew file mode 100644index 00000000000..1b410925a68--- /dev/null+++ b/tests/utils/test_flash_impl.py@@ -0,0 +1,600 @@+# SPDX-License-Identifier: AGPL-3.0-only+"""FA4 / FA3 activation gates (CPU, faked registry) and FA4 parity on real sm90 / sm100 hardware."""++import importlib.util+import os+import types++import pytest+import torch+from real_accelerator import has_real_cuda # tests/_shared, on sys.path via tests/conftest.py++from unsloth.utils import flash_impl as fi+++class FakeRegistry:+ def __init__(+ self,+ impls = ("FA3", "FA4"),+ current = None,+ ):+ self.impls, self.current_impl, self.calls = list(impls), current, []++ def activate(self, impl):+ self.calls.append(("activate", impl))+ self.current_impl = impl++ def restore(self, _raise_warn = True):+ self.calls.append(("restore",))+ self.current_impl = None++ def tuple(self):+ return (self.activate, self.restore, lambda: sorted(self.impls), lambda: self.current_impl)+++def _config(**kwargs):+ base = dict(+ num_attention_heads = 32,+ num_key_value_heads = 8,+ hidden_size = 4096,+ head_dim = 128,+ attention_dropout = 0.0,+ )+ base.update(kwargs)+ return types.SimpleNamespace(**base)+++def _model(**kwargs):+ return types.SimpleNamespace(config = _config(**kwargs), dtype = torch.bfloat16)+++def fake(monkeypatch):+ registry = FakeRegistry()+ monkeypatch.setattr(fi, "_registry", registry.tuple)+ monkeypatch.setattr(fi, "_device_majors", lambda: {10})+ monkeypatch.setattr(fi, "_package_error", lambda impl: None)+ probes = []++ def probe(impl, cases, activate, restore):+ probes.append((impl, cases))+ activate(impl)+ return None++ monkeypatch.setattr(fi, "_probe_error", probe)+ monkeypatch.setitem(fi.FLASH_IMPL_STATE, "active", None)+ monkeypatch.setitem(fi.FLASH_IMPL_STATE, "verdicts", {})+ monkeypatch.setenv(fi._ENV, "auto")+ registry.probes = probes+ return registry++[email protected]("value", [None, ""])+def test_on_by_default(fake, monkeypatch, value):+ if value is None:+ monkeypatch.delenv(fi._ENV, raising = False)+ else:+ monkeypatch.setenv(fi._ENV, value)+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA4"+ fi.deactivate_flash_attention_impl()+++def test_auto_activates_fa4_on_sm100(fake):+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA4"+ assert fake.current_impl == "FA4" and len(fake.probes) == 1+ # Decided once: a second call with the same shapes does not re-probe.+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA4"+ assert len(fake.probes) == 1+ fi.deactivate_flash_attention_impl()+ assert fake.current_impl is None and fi.FLASH_IMPL_STATE["active"] is None++[email protected]("value", ["off", "0", "false", "OFF", "bogus"])+def test_kill_switch_and_unknown_value_stay_off(fake, monkeypatch, value):+ monkeypatch.setenv(fi._ENV, value)+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+ assert fake.calls == [] and fake.probes == []+++def test_no_registry_is_a_no_op(fake, monkeypatch):+ monkeypatch.setattr(fi, "_registry", lambda: None)+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+ assert fake.calls == []++[email protected]("majors", [None, {8}, {12}, {11}, {9, 10}, set()])+def test_unsupported_or_mixed_devices_stay_off(fake, monkeypatch, majors):+ monkeypatch.setattr(fi, "_device_majors", lambda: majors)+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+ assert fake.probes == [] and fake.current_impl is None+++def test_hopper_auto_prefers_fa3_then_fa4(fake, monkeypatch):+ monkeypatch.setattr(fi, "_device_majors", lambda: {9})+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA3"+ fi.deactivate_flash_attention_impl()+ monkeypatch.setattr(fi, "_package_error", lambda impl: "missing" if impl == "FA3" else None)+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA4"+ fi.deactivate_flash_attention_impl()+ monkeypatch.setattr(fi, "_package_error", lambda impl: "missing")+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+ assert fake.current_impl is None+ monkeypatch.setattr(fi, "_package_error", lambda impl: None)+ monkeypatch.setenv(fi._ENV, "fa3")+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA3"+ fi.deactivate_flash_attention_impl()+ monkeypatch.setenv(fi._ENV, "fa4")+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA4"+ fi.deactivate_flash_attention_impl()+ monkeypatch.setattr(fi, "_device_majors", lambda: {10})+ monkeypatch.setenv(fi._ENV, "fa3")+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+++def test_hopper_auto_tries_fa4_when_fa3_fails_its_probe(fake, monkeypatch):+ monkeypatch.setattr(fi, "_device_majors", lambda: {9})+ tried = []++ def probe(impl, cases, activate, restore):+ tried.append(impl)+ if impl == "FA3":+ return "FA3 output differs from bundled flash"+ activate(impl)+ return None++ monkeypatch.setattr(fi, "_probe_error", probe)+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA4"+ assert tried == ["FA3", "FA4"] and fake.current_impl == "FA4"+ fi.deactivate_flash_attention_impl()+++def test_impl_not_registered_or_package_missing_stays_off(fake, monkeypatch):+ fake.impls = ["FA3"]+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+ fake.impls = ["FA4"]+ monkeypatch.setattr(fi, "_package_error", lambda impl: "flash_attn.cute not importable")+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+ assert fake.probes == []+++ "model",+ [+ _model(attention_dropout = 0.1),+ types.SimpleNamespace(+ config = types.SimpleNamespace(+ text_config = _config(), vision_config = _config(attention_dropout = 0.05)+ )+ ),+ _model(attn_pdrop = 0.1),+ ],+)+def test_attention_dropout_stays_off(fake, model):+ assert fi.maybe_activate_flash_attention_impl(model) is None+ assert "dropout" in fi.FLASH_IMPL_STATE["reason"]+ assert fake.probes == []+++def test_attention_module_dropout_stays_off(fake):+ class FakeAttention(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.attention_dropout = 0.1++ model = torch.nn.Sequential(FakeAttention())+ model.config = _config()+ assert fi.maybe_activate_flash_attention_impl(model) is None++[email protected]("head_dim", [160, 192, 136])+def test_head_dim_fa4_lacks_on_sm100_stays_off(fake, head_dim):+ assert fi.maybe_activate_flash_attention_impl(_model(head_dim = head_dim)) is None+ assert "head_dim" in fi.FLASH_IMPL_STATE["reason"]+++def test_head_dims_that_never_reach_flash_do_not_block(fake):+ # MLA (192 / 128) and Gemma-4 global 512 never reach torch's flash op with unequal / >256 heads.+ mla = _model(qk_nope_head_dim = 128, qk_rope_head_dim = 64, v_head_dim = 128)+ assert fi.maybe_activate_flash_attention_impl(mla) == "FA4"+ fi.deactivate_flash_attention_impl()+ assert (+ fi.maybe_activate_flash_attention_impl(_model(head_dim = 256, global_head_dim = 512)) == "FA4"+ )+ fi.deactivate_flash_attention_impl()+++def test_probe_failure_restores_and_stays_off(fake, monkeypatch):+ def failing(impl, cases, activate, restore):+ activate(impl)+ restore(_raise_warn = False)+ return "probe failed (mismatch)"++ monkeypatch.setattr(fi, "_probe_error", failing)+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+ assert fake.current_impl is None and fi.FLASH_IMPL_STATE["active"] is None+ # The failed verdict is remembered: no second probe, still off.+ monkeypatch.setattr(fi, "_probe_error", lambda *a: pytest.fail("re-probed"))+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+++def test_user_activated_impl_left_alone(fake):+ fake.current_impl = "FA4"+ assert fi.maybe_activate_flash_attention_impl(_model()) is None+ assert fake.calls == [] and fake.current_impl == "FA4"+ fi.deactivate_flash_attention_impl()+ assert fake.current_impl == "FA4"+++def test_later_model_failing_gates_restores(fake):+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA4"+ assert fi.maybe_activate_flash_attention_impl(_model(attention_dropout = 0.1)) is None+ assert fake.current_impl is None+++def test_scope_to_train_activates_only_inside_train(fake):+ seen = []++ class Trainer:+ def train(self, *args, **kwargs):+ seen.append(fake.current_impl)+ return "done"++ trainer = Trainer()+ trainer.model = _model()+ fi.scope_flash_attention_impl_to_train(trainer, trainer.model)+ fi.scope_flash_attention_impl_to_train(trainer, trainer.model) # idempotent+ assert fake.current_impl is None+ assert trainer.train() == "done" and seen == ["FA4"]+ assert fake.current_impl is None+ assert trainer.train() == "done" and seen == ["FA4", "FA4"]+ assert len(fake.probes) == 1+++def test_scope_restores_when_train_raises(fake):+ class Trainer:+ def train(self):+ raise RuntimeError("boom")++ trainer = Trainer()+ trainer.model = _model()+ fi.scope_flash_attention_impl_to_train(trainer, trainer.model)+ with pytest.raises(RuntimeError):+ trainer.train()+ assert fake.current_impl is None+++def test_reused_padding_free_collator_still_scopes_the_new_trainer(fake):+ from unsloth.utils import packing++ class Trainer:+ def train(self):+ return fake.current_impl++ collator = types.SimpleNamespace(padding_free = True, _unsloth_padding_free_lengths_wrapped = True)+ trainer = Trainer()+ trainer.model, trainer.data_collator = _model(), collator+ packing.enable_padding_free_metadata(trainer.model, trainer)+ assert trainer.train() == "FA4" and fake.current_impl is None++[email protected]("native_gqa", [True, False])+def test_probe_repeats_kv_heads_without_enable_gqa(monkeypatch, native_gqa):+ varlen = pytest.importorskip("torch.nn.attention.varlen")++ seen = []++ def fake_with_gqa(+ q,+ k,+ v,+ cu_q,+ cu_k,+ max_q,+ max_k,+ window_size = (-1, -1),+ enable_gqa = False,+ ):+ seen.append((k.shape[1], enable_gqa))+ return q * (k.float().mean() + v.float().mean()).to(q.dtype)++ def fake_2_11(+ q,+ k,+ v,+ cu_q,+ cu_k,+ max_q,+ max_k,+ window_size = (-1, -1),+ ):+ seen.append((k.shape[1], None))+ return q * (k.float().mean() + v.float().mean()).to(q.dtype)++ monkeypatch.setattr(varlen, "varlen_attn", fake_with_gqa if native_gqa else fake_2_11)+ out, dq, dk, dv = fi._run_case(("varlen", 64, 4, None, torch.float32), "cpu")+ assert seen == [(2, True)] if native_gqa else seen == [(8, None)]+ assert dk.shape == dv.shape == (sum([200, 1, 333, 64, 130]), 2, 64)+++def test_scope_skipped_when_off(fake, monkeypatch):+ monkeypatch.setenv(fi._ENV, "off")++ class Trainer:+ def train(self):+ return 1++ trainer = Trainer()+ fi.scope_flash_attention_impl_to_train(trainer, None)+ assert "train" not in vars(trainer)+++ "impl,major,head_dim,window,ok",+ [+ ("FA4", 10, 64, None, True),+ ("FA4", 10, 128, 4096, True),+ ("FA4", 10, 136, None, False),+ ("FA4", 10, 160, None, False),+ ("FA4", 10, 192, None, False),+ ("FA4", 10, 256, None, True),+ ("FA4", 10, 256, 4096, False),+ ("FA4", 10, 72, None, True),+ ("FA4", 10, 100, None, False),+ ("FA4", 9, 160, None, True),+ ("FA4", 9, 256, 4096, True),+ ("FA3", 9, 192, None, True),+ ("FA3", 9, 264, None, False),+ ],+)+def test_head_dim_supported(impl, major, head_dim, window, ok):+ assert fi.head_dim_supported(impl, major, head_dim, window = window) is ok+++def test_flash_impl_allows_reads_torch_active_impl(monkeypatch):+ registry = types.SimpleNamespace(_FLASH_ATTENTION_ACTIVE = None)+ monkeypatch.setattr(fi, "_TORCH_FLASH_REGISTRY", registry)+ assert fi.flash_impl_allows(160, None, torch.device("cuda", 0))+ registry._FLASH_ATTENTION_ACTIVE = ("FA4", object())+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device = None: (10, 0))+ assert fi.flash_impl_allows(128, None, torch.device("cuda", 0))+ assert not fi.flash_impl_allows(160, None, torch.device("cuda", 0))+ assert not fi.flash_impl_allows(256, 4096, torch.device("cuda", 0))+ assert fi.flash_impl_allows(256, None, torch.device("cuda", 0))+++def _fa4_ready():+ if not has_real_cuda() or torch.version.hip is not None:+ return False+ if fi._registry() is None or "FA4" not in fi._registry()[2]():+ return False+ if torch.cuda.get_device_capability()[0] not in (9, 10):+ return False+ return importlib.util.find_spec("flash_attn") is not None and fi._package_error("FA4") is None+++needs_fa4 = pytest.mark.skipif(+ not _fa4_ready(),+ reason = "needs sm90 / sm100 CUDA, torch >= 2.11 flash impl registry and flash_attn.cute (FA4)",+)+++def real_fa4(monkeypatch):+ monkeypatch.setenv(fi._ENV, "fa4")+ monkeypatch.setitem(fi.FLASH_IMPL_STATE, "active", None)+ yield+ fi.deactivate_flash_attention_impl()+ assert fi._current_impl() is None+ # Restored for real: the dispatcher no longer reaches torch's FA4 runner.+ with fi._count_impl_calls("FA4") as calls:+ _varlen(64, torch.bfloat16, None, lengths = (64, 32))+ assert calls == {"fwd": 0, "bwd": 0}, calls+++def _varlen(+ head_dim,+ dtype,+ window,+ lengths = (300, 17, 1000, 1, 731),+ hq = 16,+ hk = 4,+ seed = 0,+):+ from torch.nn.attention.varlen import varlen_attn++ g = torch.Generator(device = "cuda").manual_seed(seed)+ total = sum(lengths)++ def randn(*shape):+ return torch.randn(*shape, device = "cuda", dtype = dtype, generator = g)++ q, k, v = (randn(total, h, head_dim).requires_grad_() for h in (hq, hk, hk))+ cu = torch.tensor(+ [0, *torch.tensor(lengths).cumsum(0).tolist()], device = "cuda", dtype = torch.int32+ )+ out = varlen_attn(+ q,+ k,+ v,+ cu,+ cu,+ max(lengths),+ max(lengths),+ window_size = (window - 1, 0) if window else (-1, 0),+ enable_gqa = True,+ )+ out.backward(randn(*out.shape))+ return out.detach(), q.grad, k.grad, v.grad+++@needs_fa4+def test_fa4_varlen_matches_bundled_flash(real_fa4):+ cases = [+ (64, torch.bfloat16, None),+ (64, torch.bfloat16, 128),+ (128, torch.bfloat16, None),+ (128, torch.bfloat16, 128),+ (256, torch.bfloat16, None),+ (128, torch.float16, None),+ (128, torch.float16, 128),+ ]+ if torch.cuda.get_device_capability()[0] == 9:+ cases.append((256, torch.bfloat16, 128))+ refs = [_varlen(*case) for case in cases]+ model = _model(num_attention_heads = 16, num_key_value_heads = 4)+ assert fi.maybe_activate_flash_attention_impl(model) == "FA4", fi.FLASH_IMPL_STATE["reason"]+ for case, ref in zip(cases, refs):+ got = _varlen(*case)+ for a, b in zip(got, ref):+ err = (a.float() - b.float()).abs().max().item() / b.float().abs().max().item()+ assert err < 2e-2, (case, err)+++@needs_fa4+def test_fa4_backward_deterministic_mode(real_fa4):+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA4"+ previous = torch.are_deterministic_algorithms_enabled()+ torch.use_deterministic_algorithms(True, warn_only = True)+ try:+ a = _varlen(128, torch.bfloat16, None, lengths = (3000, 17, 1000, 1, 731) * 2)+ b = _varlen(128, torch.bfloat16, None, lengths = (3000, 17, 1000, 1, 731) * 2)+ finally:+ torch.use_deterministic_algorithms(previous)+ assert all(torch.equal(x, y) for x, y in zip(a, b))+++@needs_fa4+def test_fa4_run_attention_compiles_without_breaks(real_fa4):+ import torch._dynamo+ from torch._dynamo.utils import counters++ from unsloth.utils import attention_dispatch as ad+ from unsloth.utils import packing++ if ad._TORCH_VARLEN_ATTN is None:+ pytest.skip("torch varlen_attn with window_size + enable_gqa unavailable")+ assert fi.maybe_activate_flash_attention_impl(_model()) == "FA4"+ lengths = [300, 700, 24, 500, 524]+ total = sum(lengths)+ lens = torch.tensor(lengths, dtype = torch.int32, device = "cuda")+ cu = torch.zeros(len(lengths) + 1, dtype = torch.int32, device = "cuda")+ cu[1:] = lens.cumsum(0)+ config = ad.AttentionConfig(backend = ad.SDPA, n_kv_heads = 8, n_groups = 4)+ ctx = ad.AttentionContext(+ bsz = 1,+ q_len = total,+ kv_seq_len = total,+ n_heads = 32,+ head_dim = 128,+ requires_grad = True,+ seq_info = (lens, cu, max(lengths)),+ attention_mask = None,+ causal_mask = None,+ )+ q = torch.randn(1, 32, total, 128, device = "cuda", dtype = torch.bfloat16, requires_grad = True)+ k = torch.randn(1, 8, total, 128, device = "cuda", dtype = torch.bfloat16, requires_grad = True)+ calls = []+ real = ad._TORCH_VARLEN_ATTN++ def counted(*args, **kwargs):+ calls.append(1)+ return real(*args, **kwargs)++ def f(q, k, v):+ return ad.run_attention(config = config, context = ctx, Q = q, K = k, V = v)++ try:+ ad._TORCH_VARLEN_ATTN = counted+ eager = f(q, k, k)+ assert calls, "packed row did not take the varlen route"+ torch._dynamo.reset()+ counters.clear()+ packing.clear_packed_caches()+ out = torch.compile(f)(q, k, k)+ out.float().sum().backward()+ finally:+ ad._TORCH_VARLEN_ATTN = real+ assert sum(counters["graph_break"].values()) == 0, dict(counters["graph_break"])+ assert (out.float() - eager.float()).abs().max().item() < 2e-2+++@needs_fa4+def test_fa4_hd256_window_keeps_segments_route(real_fa4):+ if torch.cuda.get_device_capability()[0] != 10:+ pytest.skip("sm100 hd256 backward has no local attention; sm90 does")+ from unsloth.utils import attention_dispatch as ad++ assert fi.maybe_activate_flash_attention_impl(_model(head_dim = 256)) == "FA4"+ q = torch.randn(1, 8, 512, 256, device = "cuda", dtype = torch.bfloat16)+ assert not ad._torch_varlen_takes(q, q[:, :2], q[:, :2], {}, True, 128)+ assert ad._torch_varlen_takes(q, q[:, :2], q[:, :2], {}, True, None) == (+ ad._TORCH_VARLEN_ATTN is not None+ )+++ not has_real_cuda(), reason = "needs CUDA tensors (the wrapper only takes CUDA rows)"+)[email protected](torch.version.hip is not None, reason = "torch varlen is off on ROCm")[email protected]("window", [None, 2])[email protected]("allowed", [True, False])+def test_hf_wrapper_skips_torch_varlen_for_shapes_the_impl_lacks(monkeypatch, allowed, window):+ from unsloth.utils import hf_packed_attention as hpa+ from unsloth.utils import attention_dispatch as ad++ seen, used, asked = [], [], []++ def orig(+ module,+ q,+ k,+ v,+ mask,+ dropout = 0.0,+ scaling = None,+ is_causal = None,+ **kwargs,+ ):+ seen.append(1)+ return "orig", None++ def fake_varlen(q, k, v, *args, **kwargs):+ used.append(1)+ return q++ saved = hpa._ORIG_SDPA[0]+ hpa._ORIG_SDPA[0] = orig+ hpa._MASK_CHECK.clear()+ monkeypatch.delenv("UNSLOTH_HF_PACKED_VARLEN", raising = False)+ monkeypatch.setattr(hpa, "_TORCH_VARLEN", [fake_varlen])+ monkeypatch.setattr(hpa, "_TORCH_VARLEN_DEVICES", {})+ monkeypatch.setattr(hpa, "_sdpa_requested", lambda q, k: False)+ # No FA2 / xformers either, so a refused torch varlen goes back to the wrapped sdpa.+ monkeypatch.setattr(ad, "select_attention_backend", lambda use_varlen = False: ad.SDPA)+ monkeypatch.setattr(+ fi, "flash_impl_allows", lambda head_dim, window, device: asked.append(window) or allowed+ )+ lengths = [3, 3]+ q = torch.randn(1, 4, 6, 64, device = "cuda", dtype = torch.bfloat16)+ segment = torch.repeat_interleave(torch.arange(2), torch.tensor(lengths)).cuda()+ mask = (segment[:, None] == segment[None, :]).tril()[None, None]+ if window is not None:+ position = torch.arange(6, device = "cuda")+ mask = mask & (position[None, :] > position[:, None] - window)+ try:+ out = hpa._sdpa_packed_varlen(+ types.SimpleNamespace(is_causal = True, sliding_window = window),+ q,+ q,+ q,+ mask,+ packed_seq_lengths = torch.tensor(lengths, dtype = torch.int32),+ )+ finally:+ hpa._ORIG_SDPA[0] = saved+ hpa._MASK_CHECK.clear()+ assert asked == [window]+ if allowed:+ assert used and not seen+ else:+ assert out == ("orig", None) and not useddiff --git a/unsloth/utils/attention_dispatch.py b/unsloth/utils/attention_dispatch.pyindex cc225bd001a..5e0c1048cb1 100644--- a/unsloth/utils/attention_dispatch.py+++ b/unsloth/utils/attention_dispatch.py@@ -108,6 +108,8 @@ def _load_torch_varlen_attn():_TORCH_VARLEN_ATTN = _load_torch_varlen_attn()+from .flash_impl import flash_impl_allows # noqa: E402+def _torch_varlen_takes(Q: Tensor,@@ -136,6 +138,9 @@ def _torch_varlen_takes(# torch 2.14 routes bidirectional MHA to cuDNN ragged on sm90/sm100: no head_dim 256 plan.if not is_causal and Q.shape[1] == K.shape[1]:return False+ # An FA4 / FA3 impl behind torch's flash op lacks some shapes (sm100: hd 136-248, hd256 + window).+ if not flash_impl_allows(Q.shape[-1], sliding_window, Q.device):+ return Falsereturn not torch.are_deterministic_algorithms_enabled()diff --git a/unsloth/utils/flash_impl.py b/unsloth/utils/flash_impl.pynew file mode 100644index 00000000000..e365b3c1562--- /dev/null+++ b/unsloth/utils/flash_impl.py@@ -0,0 +1,478 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+"""Run torch's flash kernels as FA4 / FA3 while a packed / padding-free trainer trains.++torch (2.11+) swaps the flash impl process-wide, and FA4 raises (not falls back) on dropout and missing+head dims and costs ~0.2 ms per launch, so it is on only inside ``trainer.train()``, with no dropout,+supported head dims, and a probe matching torch's bundled flash.+UNSLOTH_FLASH_ATTENTION_IMPL = auto (default: FA4 on sm100, FA3 then FA4 on sm90) | fa4 | fa3 | off.+"""++import contextlib+import functools+import inspect+import logging+import os++import torch++__all__ = [+ "maybe_activate_flash_attention_impl",+ "deactivate_flash_attention_impl",+ "scope_flash_attention_impl_to_train",+ "flash_impl_allows",+ "FLASH_IMPL_STATE",+]++_ENV = "UNSLOTH_FLASH_ATTENTION_IMPL"+_MODULES = {"FA4": "flash_attn.cute.interface", "FA3": "flash_attn_interface"}+_DROPOUT_KEYS = (+ "attention_dropout",+ "attn_dropout",+ "attn_pdrop",+ "attention_probs_dropout_prob",+ "attention_dropout_prob",+)+_SUBCONFIG_KEYS = ("text_config", "vision_config", "audio_config", "encoder", "decoder")+FLASH_IMPL_STATE = {"active": None, "reason": None, "verdicts": {}, "logged": set()}+_logger = logging.getLogger(__name__)+++def _requested():+ value = os.environ.get(_ENV, "auto").strip().lower()+ if value in ("", "auto", "1", "on", "true"):+ return "auto"+ if value in ("fa4", "fa3"):+ return value.upper()+ if value not in ("0", "off", "false", "no", "none"):+ _log_once(+ f"Unsloth: {_ENV}={value!r} is not auto / fa4 / fa3 / off; leaving torch's flash kernels as they are."+ )+ return None+++def _log_once(message, level = logging.INFO):+ if message not in FLASH_IMPL_STATE["logged"]:+ FLASH_IMPL_STATE["logged"].add(message)+ _logger.log(level, message)+++def _registry():+ try:+ from torch.nn.attention import (+ activate_flash_attention_impl,+ current_flash_attention_impl,+ list_flash_attention_impls,+ restore_flash_attention_impl,+ )+ except Exception:+ return None+ return (+ activate_flash_attention_impl,+ restore_flash_attention_impl,+ list_flash_attention_impls,+ current_flash_attention_impl,+ )+++def _current_impl():+ registry = _registry()+ if registry is None:+ return None+ try:+ return registry[3]()+ except Exception:+ return None+++def _device_majors():+ if torch.version.hip is not None or not torch.cuda.is_available():+ return None+ try:+ return {torch.cuda.get_device_capability(i)[0] for i in range(torch.cuda.device_count())}+ except Exception:+ return None+++def _candidates(requested, majors):+ """auto: FA4 on sm100; FA3 (the mature Hopper kernel) then FA4 on sm90."""+ if not majors or len(majors) != 1:+ return []+ major = next(iter(majors))+ if major == 10:+ return ["FA4"] if requested in ("auto", "FA4") else []+ if major == 9:+ return ["FA3", "FA4"] if requested == "auto" else [requested]+ return []+++def _package_error(impl):+ try:+ if impl == "FA4":+ import flash_attn.cute.interface # noqa: F401+ else:+ import flash_attn_interface # noqa: F401+ if impl == "FA3":+ ops = getattr(torch.ops, "flash_attn_3", None)+ if ops is None or not hasattr(ops, "fwd") or not hasattr(ops, "bwd"):+ return "flash_attn_interface has no torch.ops.flash_attn_3 fwd / bwd"+ except Exception as exc:+ return f"{_MODULES[impl]} not importable ({type(exc).__name__})"+ return None+++def head_dim_supported(+ impl,+ major,+ head_dim,+ head_dim_v = None,+ window = None,+) -> bool:+ """Mirrors flash_attn.cute _validate_head_dims; the sm100 hd256 backward has no sliding window."""+ head_dim_v = head_dim if head_dim_v is None else head_dim_v+ if head_dim % 8 or head_dim_v % 8 or min(head_dim, head_dim_v) < 8:+ return False+ if impl == "FA3" or major == 9:+ return head_dim <= 256 and head_dim_v <= 256+ if head_dim <= 128 and head_dim_v <= 128:+ return True+ if (head_dim, head_dim_v) == (192, 128):+ return True+ return (head_dim, head_dim_v) == (256, 256) and not window+++try:+ from torch.nn.attention import _registry as _TORCH_FLASH_REGISTRY+except Exception:+ _TORCH_FLASH_REGISTRY = None+++def flash_impl_allows(head_dim, window, device) -> bool:+ """False when the active impl lacks this shape. Plain attribute reads so compiled callers do not graph break."""+ active = getattr(_TORCH_FLASH_REGISTRY, "_FLASH_ATTENTION_ACTIVE", None)+ if active is None:+ return True+ major = torch.cuda.get_device_capability(device)[0]+ return head_dim_supported(active[0], major, head_dim, window = window)+++def _configs(model):+ config = getattr(model, "config", None)+ seen, out, stack = set(), [], [config] if config is not None else []+ while stack:+ cfg = stack.pop()+ if cfg is None or id(cfg) in seen:+ continue+ seen.add(id(cfg))+ out.append(cfg)+ for key in _SUBCONFIG_KEYS:+ stack.append(getattr(cfg, key, None))+ sub = getattr(cfg, "sub_configs", None)+ if isinstance(sub, dict):+ stack.extend(getattr(cfg, key, None) for key in sub)+ return out+++def _ceil8(value):+ return -(-int(value) // 8) * 8+++def model_facts(model):+ """(dropout > 0, [(head_dim, head_dim_v)], heads, kv heads, window, dtype); None when unknown."""+ dropout, dims, n_heads, n_kv, window = False, [], None, None, None+ for cfg in _configs(model):+ for key in _DROPOUT_KEYS:+ value = getattr(cfg, key, None)+ if isinstance(value, (int, float)) and value > 0:+ dropout = True+ heads = getattr(cfg, "num_attention_heads", None)+ hidden = getattr(cfg, "hidden_size", None)+ head_dim = getattr(cfg, "head_dim", None)+ if (+ not isinstance(head_dim, int)+ and isinstance(heads, int)+ and isinstance(hidden, int)+ and heads+ ):+ head_dim = hidden // heads+ qk = [getattr(cfg, k, None) for k in ("qk_nope_head_dim", "qk_rope_head_dim")]+ v_dim = getattr(cfg, "v_head_dim", None)+ if all(isinstance(x, int) for x in qk) and isinstance(v_dim, int):+ dims.append((qk[0] + qk[1], v_dim))+ elif isinstance(head_dim, int) and head_dim > 0:+ dims.append((head_dim, head_dim))+ for key in ("global_head_dim", "local_head_dim"):+ value = getattr(cfg, key, None)+ if isinstance(value, int) and value > 0:+ dims.append((value, value))+ if n_heads is None and isinstance(heads, int):+ n_heads = heads+ kv = getattr(cfg, "num_key_value_heads", None)+ n_kv = kv if isinstance(kv, int) and kv > 0 else heads+ sliding = getattr(cfg, "sliding_window", None)+ layer_types = getattr(cfg, "layer_types", None) or ()+ if (+ isinstance(sliding, int)+ and sliding > 0+ and (+ getattr(cfg, "use_sliding_window", True) is not False+ or any("sliding" in str(t) for t in layer_types)+ )+ ):+ window = sliding+ modules = getattr(model, "modules", None)+ if callable(modules):+ try:+ for module in modules():+ if "attention" not in type(module).__name__.lower():+ continue+ for key in ("attention_dropout", "dropout", "attn_dropout", "dropout_p"):+ value = getattr(module, key, None)+ p = getattr(value, "p", value)+ if isinstance(p, (int, float)) and not isinstance(p, bool) and p > 0:+ dropout = True+ except Exception:+ pass+ dtype = getattr(model, "dtype", None)+ return dropout, dims, n_heads, n_kv, window, dtype+++def _model_gate(impl, major, facts):+ dropout, dims, *_ = facts+ if dropout:+ return "the model has attention dropout > 0 (FA4 / FA3 raise on dropout instead of falling back)"+ for head_dim, head_dim_v in dims:+ # Heads > 256 or unequal q / v dims never reach flash.+ if max(head_dim, head_dim_v) > 256 or head_dim != head_dim_v:+ continue+ if not head_dim_supported(impl, major, _ceil8(head_dim)):+ return f"head_dim {head_dim} is not one {impl} has on sm{major}x"+ return None+++def _probe_cases(facts):+ _, dims, n_heads, n_kv, window, dtype = facts+ dtype = dtype if dtype in (torch.float16, torch.bfloat16) else torch.bfloat16+ ratio = n_heads // n_kv if n_heads and n_kv and n_heads % n_kv == 0 else 4+ head_dims = sorted({d for d, v in dims if d == v and 8 <= d <= 256 and d % 8 == 0}) or [128]+ cases = []+ for head_dim in head_dims[:2]:+ cases.append(("varlen", head_dim, ratio, None, dtype))+ if window:+ cases.append(("varlen", head_dim, ratio, min(int(window), 64), dtype))+ cases.append(("decode", head_dim, ratio, None, dtype))+ return cases+++def _run_case(case, device):+ kind, head_dim, ratio, window, dtype = case+ g = torch.Generator(device = device).manual_seed(1234)+ n_kv = 2+ n_heads = n_kv * ratio++ def randn(*shape):+ return torch.randn(*shape, device = device, dtype = dtype, generator = g)++ if kind == "decode":+ q, k = randn(1, n_heads, 1, head_dim), randn(1, n_kv, 77, head_dim)+ v = randn(1, n_kv, 77, head_dim)+ with torch.no_grad():+ return (torch.nn.functional.scaled_dot_product_attention(q, k, v, enable_gqa = True),)+ from torch.nn.attention.varlen import varlen_attn++ lengths = [200, 1, 333, 64, 130]+ total = sum(lengths)+ q = randn(total, n_heads, head_dim).requires_grad_()+ k = randn(total, n_kv, head_dim).requires_grad_()+ v = randn(total, n_kv, head_dim).requires_grad_()+ cu = torch.tensor(+ [0] + torch.tensor(lengths).cumsum(0).tolist(), device = device, dtype = torch.int32+ )+ # torch 2.11's varlen_attn has no enable_gqa: repeat the K/V heads as the packed path does there.+ if "enable_gqa" in inspect.signature(varlen_attn).parameters:+ gqa, k_in, v_in = {"enable_gqa": True}, k, v+ else:+ gqa, k_in, v_in = {}, k.repeat_interleave(ratio, dim = 1), v.repeat_interleave(ratio, dim = 1)+ with torch.enable_grad():+ out = varlen_attn(+ q,+ k_in,+ v_in,+ cu,+ cu,+ max(lengths),+ max(lengths),+ window_size = (window - 1, 0) if window else (-1, 0),+ **gqa,+ )+ out.backward(randn(*out.shape))+ return out.detach(), q.grad, k.grad, v.grad+++def _count_impl_calls(impl):+ name = impl.lower()+ try:+ if impl == "FA4":+ from torch.nn.attention import _fa4 as module+ else:+ from torch.nn.attention import _fa3 as module+ fwd, bwd = getattr(module, f"_{name}_run_forward"), getattr(module, f"_{name}_run_backward")+ except Exception:+ yield None+ return+ calls = {"fwd": 0, "bwd": 0}++ def counted(key, fn):+ def run(*args, **kwargs):+ calls[key] += 1+ return fn(*args, **kwargs)++ return run++ setattr(module, f"_{name}_run_forward", counted("fwd", fwd))+ setattr(module, f"_{name}_run_backward", counted("bwd", bwd))+ try:+ yield calls+ finally:+ setattr(module, f"_{name}_run_forward", fwd)+ setattr(module, f"_{name}_run_backward", bwd)+++def _probe_error(impl, cases, activate, restore):+ device = torch.device("cuda", torch.cuda.current_device())+ try:+ refs = [_run_case(case, device) for case in cases]+ except Exception as exc:+ return f"reference flash probe failed ({type(exc).__name__}: {exc})"+ try:+ activate(impl)+ except Exception as exc:+ return f"activate_flash_attention_impl({impl!r}) failed ({type(exc).__name__}: {exc})"+ try:+ for case, ref in zip(cases, refs):+ with _count_impl_calls(impl) as calls:+ got = _run_case(case, device)+ torch.cuda.synchronize(device)+ # varlen_attn on cuDNN never reaches the impl.+ if case[0] == "varlen" and calls is not None and not (calls["fwd"] and calls["bwd"]):+ raise RuntimeError(f"varlen_attn did not run on {impl} ({calls})")+ tol = 2e-2 if case[-1] == torch.bfloat16 else 1e-2+ for a, b in zip(got, ref):+ if not torch.isfinite(a).all():+ raise RuntimeError(f"non-finite output for {case[:4]}")+ err = (a.float() - b.float()).abs().max().item()+ if err > tol * max(1.0, b.float().abs().max().item()):+ raise RuntimeError(f"{case[:4]} differs from bundled flash by {err:.3g}")+ except Exception as exc:+ try:+ restore(_raise_warn = False)+ except Exception:+ pass+ return f"probe failed ({type(exc).__name__}: {exc})"+ return None+++def maybe_activate_flash_attention_impl(model = None):+ """Returns the active impl or None. Never call while a backward is pending."""+ requested = _requested()+ registry = _registry()+ if requested is None or registry is None:+ FLASH_IMPL_STATE["reason"] = (+ "off" if requested is None else "torch has no flash attention impl registry (< 2.11)"+ )+ return None+ if torch.compiler.is_compiling():+ return FLASH_IMPL_STATE["active"]+ activate, restore, list_impls, current = registry+ current_impl = current()+ if current_impl is not None and FLASH_IMPL_STATE["active"] is None:+ FLASH_IMPL_STATE["reason"] = f"{current_impl} was activated outside Unsloth; left as is"+ return None+ majors = _device_majors()+ candidates = [impl for impl in _candidates(requested, majors) if impl in list_impls()]+ if not candidates:+ FLASH_IMPL_STATE["reason"] = f"no supported impl for devices sm{sorted(majors or [])}"+ deactivate_flash_attention_impl()+ return None+ major = next(iter(majors))+ facts = model_facts(model) if model is not None else (False, [], None, None, None, None)+ cases = _probe_cases(facts)+ # auto falls through to the next impl when one is missing, refuses this model or fails its probe.+ for impl in candidates:+ error = _package_error(impl) or _model_gate(impl, major, facts)+ key = (impl, tuple(cases))+ if error is None:+ if key not in FLASH_IMPL_STATE["verdicts"]:+ # The reference must run on the bundled kernels.+ deactivate_flash_attention_impl()+ error = _probe_error(impl, cases, activate, restore)+ FLASH_IMPL_STATE["verdicts"][key] = error+ else:+ error = FLASH_IMPL_STATE["verdicts"][key]+ if error is None and current() != impl:+ try:+ activate(impl)+ except Exception as exc:+ error = f"activate_flash_attention_impl({impl!r}) failed ({type(exc).__name__}: {exc})"+ if error is None:+ break+ deactivate_flash_attention_impl()+ if error is not None:+ FLASH_IMPL_STATE["reason"] = error+ deactivate_flash_attention_impl()+ if requested != "auto":+ _log_once(f"Unsloth: {_ENV}={requested.lower()} not used: {error}", logging.WARNING)+ return None+ FLASH_IMPL_STATE["active"] = impl+ FLASH_IMPL_STATE["reason"] = f"{impl} active"+ message = f"Unsloth: packed attention trains on {impl} ({_MODULES[impl]}); {_ENV}=off keeps torch's bundled flash."+ if message not in FLASH_IMPL_STATE["logged"]:+ FLASH_IMPL_STATE["logged"].add(message)+ print(message)+ return impl+++def deactivate_flash_attention_impl():+ if FLASH_IMPL_STATE["active"] is None:+ return+ FLASH_IMPL_STATE["active"] = None+ registry = _registry()+ if registry is not None:+ try:+ registry[1](_raise_warn = False)+ except Exception:+ pass+++def scope_flash_attention_impl_to_train(trainer, model) -> None:+ """Active only during trainer.train: FA4's launch cost makes decode attention ~6x slower."""+ if trainer is None or getattr(trainer, "_unsloth_flash_impl_wrapped", False):+ return+ if _requested() is None or _registry() is None:+ return+ original = getattr(trainer, "train", None)+ if not callable(original):+ return++ @functools.wraps(original)+ def train(*args, **kwargs):+ activated = None+ try:+ activated = maybe_activate_flash_attention_impl(+ getattr(trainer, "model", None) or model+ )+ except Exception as exc:+ FLASH_IMPL_STATE["reason"] = f"activation error ({type(exc).__name__}: {exc})"+ deactivate_flash_attention_impl()+ try:+ return original(*args, **kwargs)+ finally:+ if activated is not None:+ deactivate_flash_attention_impl()++ try:+ trainer.train = train+ trainer._unsloth_flash_impl_wrapped = True+ except Exception:+ passdiff --git a/unsloth/utils/hf_packed_attention.py b/unsloth/utils/hf_packed_attention.pyindex 236ba5692b6..a1c0b796fa5 100644--- a/unsloth/utils/hf_packed_attention.py+++ b/unsloth/utils/hf_packed_attention.py@@ -16,8 +16,8 @@ _FLAG = "_unsloth_hf_packed_varlen"_ENV = "UNSLOTH_HF_PACKED_VARLEN"_ORIG_SDPA = [None]HF_PACKED_ATTENTION_STATS = {"fast": 0, "fallback": 0, "mask_checks": 0}-# All layers of a forward share one mask object: weakref, (cu_seqlens, versions), verdict.-_MASK_CHECK = [None, None, None]+# Layers of one window share a mask object: window -> [weakref, (cu_seqlens, versions), verdict].+_MASK_CHECK = {}_MASK_CHECK_ROWS = 1024@@ -25,9 +25,14 @@ def _disabled() -> bool:return os.environ.get(_ENV, "1").lower() in ("0", "false", "no", "off")-def _mask_is_block_causal(attention_mask, cu_seqlens, total) -> bool:- """Exactly causal inside each packed segment and closed across them; windows, bidirectional- spans, pad tails and None (one document, already is_causal) keep the wrapped path."""+def _mask_is_block_causal(+ attention_mask,+ cu_seqlens,+ total,+ window = None,+) -> bool:+ """Exactly causal (k > q - window when windowed) inside each packed segment and closed across+ them; other windows, bidirectional spans, pad tails and None keep the wrapped path."""if not (isinstance(attention_mask, torch.Tensor)and attention_mask.dtype == torch.bool@@ -40,7 +45,7 @@ def _mask_is_block_causal(attention_mask, cu_seqlens, total) -> bool:# Versions catch in-place edits; inference tensors have none, so are always rechecked.cacheable = not (torch.is_inference(attention_mask) or torch.is_inference(cu_seqlens))key = (attention_mask._version, cu_seqlens._version, total) if cacheable else None- ref, checked, verdict = _MASK_CHECK+ ref, checked, verdict = _MASK_CHECK.get(window, (None, None, None))if (cacheableand ref is not None@@ -53,23 +58,27 @@ def _mask_is_block_causal(attention_mask, cu_seqlens, total) -> bool:verdict = Falseif int(cu_seqlens[-1].item()) == total:lengths = (cu_seqlens[1:] - cu_seqlens[:-1]).to(torch.int64)+ # output_size: no host sync to size the result.segment = torch.repeat_interleave(torch.arange(lengths.numel(), device = attention_mask.device),lengths.to(attention_mask.device),+ output_size = total,)position = torch.arange(total, device = attention_mask.device)- # Row blocks keep the reference to _MASK_CHECK_ROWS x T, not a second T x T mask.- verdict = True+ # Row blocks avoid a second T x T mask; one host sync for the whole mask.+ mismatch = torch.zeros((), dtype = torch.bool, device = attention_mask.device)for start in range(0, total, _MASK_CHECK_ROWS):rows = slice(start, min(start + _MASK_CHECK_ROWS, total))expected = (segment[rows, None] == segment[None, :]) & (position[None, :] <= position[rows, None])- if not torch.equal(attention_mask[0, 0, rows], expected):- verdict = False- break+ if window is not None:+ # transformers' sliding_window_overlay: kv_idx > q_idx - sliding_window.+ expected &= position[None, :] > position[rows, None] - window+ mismatch |= (attention_mask[0, 0, rows] != expected).any()+ verdict = not bool(mismatch)if cacheable:- _MASK_CHECK[:] = [weakref.ref(attention_mask), (cu_seqlens, key), verdict]+ _MASK_CHECK[window] = [weakref.ref(attention_mask), (cu_seqlens, key), verdict]return verdict@@ -83,9 +92,22 @@ def _autocast_dtype_differs(query) -> bool:return enabled and dtype != query.dtype-def _sliding_or_softcapped(module, kwargs) -> bool:- if kwargs.get("sliding_window") or getattr(module, "sliding_window", None):- return True+_NO_WINDOW = object()+++def _sliding_window(module, kwargs):+ """None, a positive int window, or _NO_WINDOW when the window is not one varlen can take."""+ window = kwargs.get("sliding_window")+ if window is None:+ window = getattr(module, "sliding_window", None)+ if window is None:+ return None+ if isinstance(window, bool) or not isinstance(window, int) or window <= 0:+ return _NO_WINDOW+ return window+++def _softcapped(module, kwargs) -> bool:if kwargs.get("softcap") or getattr(module, "sinks", None) is not None:return Trueif getattr(module, "attn_logit_softcapping", None):@@ -187,6 +209,7 @@ def _sdpa_packed_varlen(is_causal = is_causal,**kwargs,)+ from .flash_impl import flash_impl_allowsfrom .attention_dispatch import (_VARLEN_INT32_GUARD_DISABLED,FLASH_VARLEN,@@ -198,6 +221,7 @@ def _sdpa_packed_varlen(bsz, n_heads, q_len, head_dim = query.shapeseq_info = torch_varlen = backend = None+ window = _sliding_window(module, kwargs)if (bsz == 1and q_len > 0@@ -220,11 +244,18 @@ def _sdpa_packed_varlen(and kwargs.get("cache") is Noneand kwargs.get("past_key_values") is Noneand n_heads % key.shape[1] == 0- and not _sliding_or_softcapped(module, kwargs)+ and window is not _NO_WINDOW+ and not _softcapped(module, kwargs)and not _sdpa_requested(query, key)):torch_varlen = _torch_varlen(query.device)+ # An FA4 / FA3 impl behind torch's flash op lacks some shapes (sm100: hd 136-248, hd256 + window).+ if torch_varlen is not None and not flash_impl_allows(head_dim, window, query.device):+ torch_varlen = Nonebackend = select_attention_backend(use_varlen = True)+ # flash-attn's ROCm backend lists sliding windows as work in progress: windowed rows keep sdpa there.+ if window is not None and torch.version.hip is not None:+ backend = None# Flash-2 varlen backward faults past int32 indexing. Keyed on training / grad mode, not# requires_grad, so a reentrant checkpoint's no_grad forward and its recompute agree.if (@@ -237,7 +268,7 @@ def _sdpa_packed_varlen(torch_varlen, backend = None, Noneif torch_varlen is not None or backend in (FLASH_VARLEN, XFORMERS):seq_info = get_packed_info_from_kwargs(kwargs, query.device)- if seq_info is None or not _mask_is_block_causal(attention_mask, seq_info[1], q_len):+ if seq_info is None or not _mask_is_block_causal(attention_mask, seq_info[1], q_len, window):HF_PACKED_ATTENTION_STATS["fallback"] += 1return orig(module,@@ -273,7 +304,7 @@ def _sdpa_packed_varlen(max_seqlen,max_seqlen,scale = scale,- window_size = (-1, 0),+ window_size = (-1, 0) if window is None else (window - 1, 0),**gqa,)except torch.OutOfMemoryError:@@ -303,7 +334,12 @@ def _sdpa_packed_varlen(backend = backend,n_kv_heads = n_kv_heads,n_groups = n_heads // n_kv_heads,- flash_varlen_kwargs = {"dropout_p": 0.0, "causal": True, "softmax_scale": scale},+ flash_varlen_kwargs = {+ "dropout_p": 0.0,+ "causal": True,+ "softmax_scale": scale,+ **({} if window is None else {"window_size": (window - 1, 0)}),+ },sdpa_kwargs = {"scale": scale},xformers_kwargs = {"scale": scale},)@@ -319,6 +355,7 @@ def _sdpa_packed_varlen(seq_info = seq_info,attention_mask = None,causal_mask = None,+ sliding_window = window,)out = run_attention(config = config, context = context, Q = query, K = key, V = value)return out.contiguous(), Nonediff --git a/unsloth/utils/packing.py b/unsloth/utils/packing.pyindex c8b4ecaabfe..e505f9afe45 100644--- a/unsloth/utils/packing.py+++ b/unsloth/utils/packing.py@@ -203,6 +203,14 @@ def _enable_hf_packed_attention() -> None:logging.getLogger(__name__).info(f"Unsloth: packed varlen attention not enabled ({exc})")+def _scope_flash_attention_impl(model, trainer) -> None:+ try:+ from .flash_impl import scope_flash_attention_impl_to_train+ scope_flash_attention_impl_to_train(trainer, model)+ except Exception as exc:+ logging.getLogger(__name__).info(f"Unsloth: flash attention impl not scoped ({exc})")++def _mask_padding_free_boundary_labels(batch) -> None:"""TRL < 0.23.1 targets document starts; the zoo count excludes them; single row only."""labels = batch.get("labels") if isinstance(batch, Mapping) else None@@ -229,6 +237,7 @@ def enable_sample_packing(if collator is None or not hasattr(collator, "torch_call"):return_enable_hf_packed_attention()+ _scope_flash_attention_impl(model, trainer)if getattr(collator, "_unsloth_packing_wrapped", False):return@@ -266,11 +275,11 @@ def enable_sample_packing(def enable_padding_free_metadata(model, trainer):"""supply sequence lengths for padding-free batches without packing."""collator = getattr(trainer, "data_collator", None)- if (- collator is None- or getattr(collator, "_unsloth_padding_free_lengths_wrapped", False)- or not getattr(collator, "padding_free", False)- ):+ if collator is None or not getattr(collator, "padding_free", False):+ return+ # Before the already-wrapped return: a reused collator's new trainer still needs scoping.+ _scope_flash_attention_impl(model, trainer)+ if getattr(collator, "_unsloth_padding_free_lengths_wrapped", False):returnmark_allow_overlength(model)