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
Flex attention decode steps for Gemma 4 and Qwen3.5 / Qwen3.6 under decode CUDA graphs (#17329)
Daniel Handb12e18b0999
diff --git a/tests/test_flex_decode_gemma4.py b/tests/test_flex_decode_gemma4.pynew file mode 100644index 00000000000..d0697539381--- /dev/null+++ b/tests/test_flex_decode_gemma4.py@@ -0,0 +1,245 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Gemma 4 greedy generate() with one-token steps on unsloth_flex_decode equals SDPA decode: real head dims+(sliding 256, full 512), GQA, sliding windows (512 E2B-like, 1024 26B-like), KV-shared consumer layers (E2B) and+k_eq_v full layers (26B), batch 1 and a left-padded ragged batch, decoding past the window. zoo's flex decode is+stood in by eager flex_attention over the same mask semantics (CPU has no flex_decoding kernel). float64: SDPA and+flex then agree bit for bit, so any difference is a routing / mask error, not rounding (Gemma 4's attention scale+is 1.0, which turns fp32 summation-order noise into visible logit differences)."""++import pytest+import torch++transformers = pytest.importorskip("transformers")+gemma4 = pytest.importorskip("transformers.models.gemma4.modeling_gemma4")++import unsloth.models._flex_decode as FD+import unsloth.models.vision as vision+from unsloth.models.vision import _NonFlexGenerate++if not (+ "q_length"+ in __import__("inspect")+ .signature(__import__("transformers.masking_utils", fromlist = ["x"]).sdpa_mask)+ .parameters+):+ pytest.skip("transformers 5.x mask interface needed", allow_module_level = True)+++def _ref_block_mask(+ batch_size,+ kv_length,+ q_offset,+ kv_offset = 0,+ *,+ mask_function = None,+ attention_mask = None,+ window = None,+ device = None,+ graph_contract = True,+):+ # zoo's decode_block_mask contract: slot j holds position kv_offset + j, the query sits at q_offset,+ # mask_function is transformers' (causal / causal + sliding overlay), the 2D mask adds per-slot padding.+ from torch.nn.attention.flex_attention import create_block_mask++ # Copies: a hybrid StaticLayer's cumulative_length is bumped in place before attention reads the mask.+ q_o = q_offset.clone() if isinstance(q_offset, torch.Tensor) else torch.tensor(q_offset)+ kv_o = kv_offset.clone() if isinstance(kv_offset, torch.Tensor) else torch.tensor(kv_offset)+ pad = None+ if attention_mask is not None:+ full = attention_mask.to(torch.bool)+ pos = torch.arange(kv_length) + kv_o+ pad = full[:, pos.clamp(max = full.shape[-1] - 1)] & (pos < full.shape[-1])++ def mask_mod(b, h, q, kv):+ m = mask_function(b, h, q + q_o, kv + kv_o)+ if pad is not None:+ m = m & pad[b, kv]+ return m++ return create_block_mask(mask_mod, batch_size, None, 1, kv_length, device = device)+++def _ref_attention(+ q,+ k,+ v,+ block_mask,+ scale,+ *,+ sinks = None,+ softcap = None,+):+ from torch.nn.attention.flex_attention import flex_attention+ return flex_attention(+ q, k, v, block_mask = block_mask, scale = scale, enable_gqa = q.shape[1] != k.shape[1]+ )+++def flex(monkeypatch):+ # The routing is under test, not zoo's kernels: always the reference mask / attention (CPU float64).+ monkeypatch.setattr(FD, "decode_block_mask", _ref_block_mask)+ monkeypatch.setattr(FD, "flex_decode_attention", _ref_attention)+ monkeypatch.setattr(+ FD, "flex_decode_supported", lambda head_dim, n_q, n_kv, dtype, device: True+ )+ FD._REGISTERED = False+ FD._SUPPORT_CACHE.clear()+ assert FD.register()+ monkeypatch.setattr(FD, "wanted", lambda device: True)+ # No CUDA graphs on CPU: force flex decode for eager calls too.+ monkeypatch.setenv(FD.ENV, "1")+ monkeypatch.setattr(vision, "_model_device", lambda model: torch.device("cpu"))+ return FD+++def _gemma4(kind, window = None):+ from transformers import Gemma4ForCausalLM, Gemma4TextConfig++ torch.manual_seed(0)+ if kind == "e2b":+ kw = dict(+ num_hidden_layers = 10,+ layer_types = (["sliding_attention"] * 4 + ["full_attention"]) * 2,+ num_attention_heads = 8,+ num_key_value_heads = 1,+ head_dim = 256,+ global_head_dim = 512,+ sliding_window = 512,+ num_kv_shared_layers = 5,+ hidden_size_per_layer_input = 8,+ )+ else:+ kw = dict(+ num_hidden_layers = 6,+ layer_types = ["sliding_attention"] * 5 + ["full_attention"],+ num_attention_heads = 16,+ num_key_value_heads = 8,+ head_dim = 256,+ global_head_dim = 512,+ num_global_key_value_heads = 2,+ attention_k_eq_v = True,+ sliding_window = 1024,+ hidden_size_per_layer_input = 0,+ )+ if window is not None:+ kw["sliding_window"] = window+ config = Gemma4TextConfig(+ vocab_size = 128,+ vocab_size_per_layer_input = 128,+ hidden_size = 64,+ intermediate_size = 64,+ max_position_embeddings = 4096,+ final_logit_softcapping = 30.0,+ pad_token_id = 0,+ eos_token_id = 1,+ bos_token_id = 2,+ attn_implementation = "sdpa",+ **kw,+ )+ model = Gemma4ForCausalLM(config).eval().double()+ with torch.no_grad():+ for p in model.parameters():+ p.mul_(4.0)+ return model+++def _inputs(prompt, batch):+ torch.manual_seed(1)+ lengths = [prompt] if batch == 1 else [prompt, prompt - 37, prompt // 2, 7]+ ids = torch.zeros(batch, prompt, dtype = torch.long)+ mask = torch.zeros(batch, prompt, dtype = torch.long)+ for i, n in enumerate(lengths):+ ids[i, prompt - n :] = torch.randint(3, 128, (n,))+ mask[i, prompt - n :] = 1+ return ids, mask+++def _generate(model, ids, mask, new):+ out = model.generate(+ input_ids = ids,+ attention_mask = mask,+ max_new_tokens = new,+ min_new_tokens = new,+ do_sample = False,+ cache_implementation = "static",+ output_logits = True,+ return_dict_in_generate = True,+ pad_token_id = 0,+ )+ return out.sequences, torch.stack(out.logits, 1)+++# The checkpoints' windows on CPU take minutes: over the default per-test timeout on a CI runner.+_SLOW = [pytest.mark.slow, pytest.mark.timeout(900)]+++ "kind,window,prompt,batch,new",+ [+ ("e2b", 32, 40, 4, 40),+ ("26b", 32, 40, 4, 40),+ # The checkpoints' windows (512 / 1024); a batch past the 1024 window is covered by the window-32 rows.+ pytest.param("e2b", None, 400, 1, 160, marks = _SLOW),+ pytest.param("e2b", None, 400, 4, 160, marks = _SLOW),+ pytest.param("26b", None, 900, 1, 140, marks = _SLOW),+ ],+)+def test_gemma4_flex_decode_matches_sdpa_past_the_window(flex, kind, window, prompt, batch, new):+ model = _gemma4(kind, window)+ ids, mask = _inputs(prompt, batch)+ with torch.no_grad():+ ref_seq, ref_logits = _generate(model, ids, mask, new)+ FD.reset_stats(model)+ with _NonFlexGenerate(model):+ seq, logits = _generate(model, ids, mask, new)+ assert model.config._attn_implementation == "sdpa"+ stats = FD.stats(model)+ window = model.config.sliding_window+ assert prompt + new > window, "the test must decode past the sliding window"+ # Every attention layer ran every decode step on flex (KV-shared consumers included), none fell back.+ assert len(stats) == model.config.num_hidden_layers+ assert all(s["flex"] == new - 1 and not s["fallback"] for s in stats.values()), stats+ assert torch.equal(seq, ref_seq)+ assert (logits - ref_logits).abs().max().item() < 1e-9+++def test_gemma4_unsupported_full_layers_stay_on_sdpa(flex, monkeypatch):+ # head_dim 512 without flex decode support (sm75): full layers keep SDPA, sliding layers decode on flex.+ monkeypatch.setattr(+ FD, "flex_decode_supported", lambda head_dim, n_q, n_kv, dtype, device: head_dim != 512+ )+ FD._SUPPORT_CACHE.clear()+ model = _gemma4("e2b", 32)+ ids, mask = _inputs(40, 4)+ with torch.no_grad():+ ref_seq, ref_logits = _generate(model, ids, mask, 24)+ FD.reset_stats(model)+ with _NonFlexGenerate(model):+ seq, logits = _generate(model, ids, mask, 24)+ stats = FD.stats(model)+ full = [s for s in stats.values() if s["kind"] == "full"]+ sliding = [s for s in stats.values() if s["kind"] == "sliding"]+ assert full and sliding+ assert all(s["flex"] == 0 and sum(s["fallback"].values()) == 23 for s in full), full+ assert all("head_dim 512" in next(iter(s["fallback"])) for s in full)+ assert all(s["flex"] == 23 and not s["fallback"] for s in sliding), sliding+ assert torch.equal(seq, ref_seq)+ assert (logits - ref_logits).abs().max().item() < 1e-9+++def test_gemma4_with_zoo_decode_block_mask(flex, monkeypatch):+ zoo = pytest.importorskip("unsloth_zoo.flex_attention.decode")+ monkeypatch.setattr(FD, "decode_block_mask", zoo.decode_block_mask)+ model = _gemma4("e2b", 32)+ ids, mask = _inputs(40, 4)+ with torch.no_grad():+ ref_seq, ref_logits = _generate(model, ids, mask, 40)+ FD.reset_stats(model)+ with _NonFlexGenerate(model):+ seq, logits = _generate(model, ids, mask, 40)+ assert all(s["flex"] == 39 and not s["fallback"] for s in FD.stats(model).values())+ assert torch.equal(seq, ref_seq)+ assert (logits - ref_logits).abs().max().item() < 1e-9diff --git a/tests/test_flex_decode_qwen35.py b/tests/test_flex_decode_qwen35.pynew file mode 100644index 00000000000..c27d62661e4--- /dev/null+++ b/tests/test_flex_decode_qwen35.py@@ -0,0 +1,127 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Qwen3.5 / Qwen3.6 (qwen3_5, qwen3_5_moe) greedy generate() with one-token steps on Unsloth's flex decode equals+SDPA decode: gated full-attention layers (output gate, partial rotary, q / k norm) between Gated DeltaNet layers,+GQA, the MoE block, batch 1 and a left-padded ragged batch. Same float64 stand-in as test_flex_decode_gemma4 (zoo's+flex decode replaced by eager flex_attention over the same mask semantics), so any difference is a routing or mask+error, not rounding."""++import pytest+import torch++transformers = pytest.importorskip("transformers")+pytest.importorskip("transformers.models.qwen3_5_moe.modeling_qwen3_5_moe")+if "linear_attention" not in getattr(+ pytest.importorskip("transformers.masking_utils"),+ "LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING",+ {"linear_attention": 1},+):+ # Early 5.x: generate() builds no mask for linear-attention layers, so a Qwen3.5 static-cache call cannot run.+ pytest.skip(+ "transformers without linear_attention masks for generate()", allow_module_level = True+ )++import unsloth.models._flex_decode as FD+from unsloth.models.vision import _NonFlexGenerate++from tests.test_flex_decode_gemma4 import _generate, _inputs, flex # noqa: F401 (fixture)+++def _torch_linear_attention(monkeypatch):+ # The CPU float64 stand-in must not reach FLA / causal-conv1d Triton kernels where those packages are installed+ # (GPU hosts): transformers picks them by import, not by device, and they reject CPU tensors.+ import importlib+ for name in ("qwen3_5", "qwen3_5_moe"):+ module = importlib.import_module(f"transformers.models.{name}.modeling_{name}")+ for fn in (+ "torch_chunk_gated_delta_rule",+ "torch_recurrent_gated_delta_rule",+ "causal_conv1d_fn",+ "causal_conv1d_update",+ ):+ original = getattr(getattr(module, fn, None), "__wrapped__", None)+ if original is not None:+ monkeypatch.setattr(module, fn, original)+++def _native_torch_moe(monkeypatch):+ # The float64 stand-in needs the per-expert loop: a CUDA host selects grouped_mm (half / fp32 only) process-wide.+ import sys+ monkeypatch.setenv("UNSLOTH_MOE_BACKEND", "native_torch")+ for module in list(sys.modules.values()):+ if "_SELECTED_MOE_BACKEND" in getattr(module, "__dict__", {}):+ monkeypatch.setattr(module, "_SELECTED_MOE_BACKEND", None)+++def _qwen(moe):+ from transformers import (+ Qwen3_5ForCausalLM,+ Qwen3_5MoeForCausalLM,+ Qwen3_5MoeTextConfig,+ Qwen3_5TextConfig,+ )++ torch.manual_seed(0)+ common = dict(+ vocab_size = 128,+ hidden_size = 64,+ num_hidden_layers = 4,+ layer_types = ["linear_attention", "linear_attention", "linear_attention", "full_attention"],+ num_attention_heads = 8,+ num_key_value_heads = 2,+ head_dim = 32,+ linear_key_head_dim = 16,+ linear_value_head_dim = 16,+ linear_num_key_heads = 2,+ linear_num_value_heads = 4,+ max_position_embeddings = 1024,+ pad_token_id = 0,+ eos_token_id = 1,+ bos_token_id = 2,+ attn_implementation = "sdpa",+ )+ if moe:+ config = Qwen3_5MoeTextConfig(+ moe_intermediate_size = 32,+ shared_expert_intermediate_size = 32,+ num_experts = 8,+ num_experts_per_tok = 2,+ **common,+ )+ model = Qwen3_5MoeForCausalLM(config)+ else:+ config = Qwen3_5TextConfig(intermediate_size = 64, **common)+ model = Qwen3_5ForCausalLM(config)+ model = model.eval().double()+ with torch.no_grad():+ for p in model.parameters():+ p.mul_(4.0)+ return model++[email protected]("zoo_mask", [False, True], ids = ["stand_in_mask", "zoo_mask"])[email protected]("moe", [False, True], ids = ["qwen3_5", "qwen3_5_moe"])[email protected]("batch", [1, 4])+def test_qwen35_flex_decode_matches_sdpa(flex, monkeypatch, moe, batch, zoo_mask):+ # Regression: a mask keeping a reference to the live counter saw one slot too many.+ if zoo_mask:+ zoo = pytest.importorskip("unsloth_zoo.flex_attention.decode")+ monkeypatch.setattr(FD, "decode_block_mask", zoo.decode_block_mask)+ _torch_linear_attention(monkeypatch)+ _native_torch_moe(monkeypatch)+ model = _qwen(moe)+ assert FD._model_type(model.config) in FD.MODEL_TYPES+ ids, mask = _inputs(48, batch)+ with torch.no_grad():+ ref_seq, ref_logits = _generate(model, ids, mask, 24)+ FD.reset_stats(model)+ with _NonFlexGenerate(model):+ seq, logits = _generate(model, ids, mask, 24)+ assert model.config._attn_implementation == "sdpa"+ stats = FD.stats(model)+ assert len(stats) == 1 and all(+ s["flex"] == 23 and not s["fallback"] for s in stats.values()+ ), stats+ assert torch.equal(seq, ref_seq)+ assert (logits - ref_logits).abs().max().item() < 1e-9diff --git a/tests/test_flex_decode_routing.py b/tests/test_flex_decode_routing.pynew file mode 100644index 00000000000..d855a68d13d--- /dev/null+++ b/tests/test_flex_decode_routing.py@@ -0,0 +1,358 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""generate() decode-step routing to Unsloth's flex decode (unsloth_flex_decode): StaticCache one-token steps+switch to it, prefill and dynamic caches keep their attention, UNSLOTH_FLEX_DECODE=0 restores the old routing."""++import types++import pytest+import torch++import unsloth.models._flex_decode as FD+import unsloth.models.vision as vision+from unsloth.models.vision import _NonFlexGenerate, _generate_routes++[email protected](autouse = True)+def _env(monkeypatch):+ monkeypatch.delenv("UNSLOTH_FLEX_ATTENTION_GENERATE", raising = False)+ monkeypatch.delenv(FD.ENV, raising = False)+++class _Static:+ is_compileable = True+++class _Dynamic:+ is_compileable = False+++def _model(model_type, attn):+ from transformers import LlamaConfig++ config = LlamaConfig(+ num_hidden_layers = 1,+ hidden_size = 32,+ intermediate_size = 64,+ num_attention_heads = 2,+ num_key_value_heads = 1,+ head_dim = 16,+ vocab_size = 64,+ )+ config.model_type = model_type+ config._attn_implementation = attn+ model = types.SimpleNamespace(config = config, seen = [])++ def prepare_inputs_for_generation(+ input_ids,+ cache_position = None,+ past_key_values = None,+ **kwargs,+ ):+ model.seen.append(config._attn_implementation)+ if cache_position is not None:+ input_ids = input_ids[:, -cache_position.shape[0] :]+ return {"input_ids": input_ids, "cache_position": cache_position}++ model.prepare_inputs_for_generation = prepare_inputs_for_generation+ model.modules = lambda: iter(())+ return model+++def _steps(+ model,+ cache,+ n_new = 3,+ prompt = 5,+ batch = 1,+):+ for step in range(n_new):+ n = prompt + step+ ids = torch.zeros(batch, n, dtype = torch.long)+ cp = torch.arange(n) if step == 0 else torch.tensor([n - 1])+ model.prepare_inputs_for_generation(ids, cache_position = cp, past_key_values = cache)+++def flex_on(monkeypatch):+ import unsloth.models._decode_graphs as G++ monkeypatch.setattr(FD, "wanted", lambda device: True)+ monkeypatch.setattr(G, "call_plan", lambda: "graph")+ monkeypatch.setattr(+ FD, "routable", lambda model, config: FD._model_type(config) in FD.MODEL_TYPES+ )+ monkeypatch.setattr(vision, "_model_device", lambda model: torch.device("cpu"))+++def test_static_decode_steps_use_flex_decode_and_prefill_keeps_sdpa(flex_on):+ model = _model("gemma4_text", "sdpa")+ assert [d for _, _, d in _generate_routes(model)] == [FD.ATTN_KEY]+ with _NonFlexGenerate(model):+ _steps(model, _Static())+ assert model.seen == ["sdpa", FD.ATTN_KEY, FD.ATTN_KEY]+ assert model.config._attn_implementation == "sdpa"+++def test_requested_attention_weights_keep_the_model_attention(flex_on, monkeypatch):+ # Flex decode returns no attention weights: output_attentions keeps every step on the model's attention.+ monkeypatch.setenv(FD.ENV, "1")+ for kwargs in (+ {"output_attentions": True},+ {"generation_config": types.SimpleNamespace(output_attentions = True)},+ ):+ model = _model("gemma4_text", "eager")+ assert vision._wants_attentions(model, kwargs)+ with _NonFlexGenerate(model, flex_decode = not vision._wants_attentions(model, kwargs)):+ _steps(model, _Static())+ assert model.seen == ["eager", "eager", "eager"], kwargs+ assert not vision._wants_attentions(+ _model("gemma4_text", "eager"), {"output_attentions": False}+ )+++def test_auto_routes_only_graph_planned_calls(flex_on, monkeypatch):+ # Eager flex decode is slower than SDPA: auto switches only calls that decode through CUDA graphs, =1 forces.+ import unsloth.models._decode_graphs as G++ monkeypatch.setattr(G, "call_plan", lambda: "eager")+ model = _model("gemma4_text", "sdpa")+ with _NonFlexGenerate(model):+ _steps(model, _Static())+ assert model.seen == ["sdpa", "sdpa", "sdpa"]+ monkeypatch.setenv(FD.ENV, "1")+ model = _model("gemma4_text", "sdpa")+ with _NonFlexGenerate(model):+ _steps(model, _Static())+ assert model.seen == ["sdpa", FD.ATTN_KEY, FD.ATTN_KEY]+++def test_auto_caps_the_batch(flex_on, monkeypatch):+ # auto: batches over UNSLOTH_FLEX_DECODE_MAX_BATCH (default 4) keep SDPA; the env var moves the cap, =1 lifts it.+ for batch, env, expected in (+ (4, None, FD.ATTN_KEY),+ (8, None, "sdpa"),+ (8, "8", FD.ATTN_KEY),+ (8, "0", FD.ATTN_KEY),+ ):+ if env is None:+ monkeypatch.delenv(FD.MAX_BATCH_ENV, raising = False)+ else:+ monkeypatch.setenv(FD.MAX_BATCH_ENV, env)+ model = _model("gemma4_text", "sdpa")+ with _NonFlexGenerate(model):+ _steps(model, _Static(), batch = batch)+ assert model.seen == ["sdpa", expected, expected], (batch, env)+ monkeypatch.delenv(FD.MAX_BATCH_ENV, raising = False)+ monkeypatch.setenv(FD.ENV, "1")+ model = _model("gemma4_text", "sdpa")+ with _NonFlexGenerate(model):+ _steps(model, _Static(), batch = 8)+ assert model.seen == ["sdpa", FD.ATTN_KEY, FD.ATTN_KEY]+++def test_dynamic_cache_keeps_the_model_attention(flex_on):+ model = _model("gemma4_text", "sdpa")+ with _NonFlexGenerate(model):+ _steps(model, _Dynamic())+ assert model.seen == ["sdpa", "sdpa", "sdpa"]+++def test_off_switch_and_unlisted_models_are_unchanged(flex_on, monkeypatch):+ model = _model("llama", "sdpa")+ assert _generate_routes(model) == []+ monkeypatch.setattr(FD, "wanted", lambda device: False)+ gemma = _model("gemma4_text", "sdpa")+ assert _generate_routes(gemma) == []+ with _NonFlexGenerate(gemma):+ _steps(gemma, _Static())+ assert gemma.seen == ["sdpa", "sdpa", "sdpa"]+++def test_flex_preferred_config_decodes_on_flex_decode_when_routable(flex_on, monkeypatch):+ # A flex-preferred config (prefill on flex) keeps the eager decode unless its type is routable.+ model = _model("gemma3_text", "flex_attention")+ routes = _generate_routes(model)+ assert [(p, d) for _, p, d in routes] == [("flex_attention", "eager")]+ monkeypatch.setattr(FD, "routable", lambda model, config: True)+ routes = _generate_routes(model)+ assert [(p, d) for _, p, d in routes] == [("flex_attention", FD.ATTN_KEY)]+ with _NonFlexGenerate(model):+ _steps(model, _Static())+ _steps(model, _Dynamic())+ assert model.seen == [+ "flex_attention",+ FD.ATTN_KEY,+ FD.ATTN_KEY,+ "flex_attention",+ "eager",+ "eager",+ ]+++def test_policy_auto_needs_sm80_and_env_overrides(monkeypatch):+ monkeypatch.setattr(FD, "register", lambda: True)+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.version, "hip", None)+ for major, expected in ((7, False), (8, True), (9, True), (12, True)):+ monkeypatch.setattr(+ torch.cuda, "get_device_capability", lambda device = None, m = major: (m, 0)+ )+ assert FD.wanted("cuda:0") is expected+ monkeypatch.setenv(FD.ENV, "0")+ assert FD.wanted("cuda:0") is False+ monkeypatch.setenv(FD.ENV, "1")+ assert FD.wanted("cuda:0") is True+ monkeypatch.delenv(FD.ENV)+ assert FD.wanted("cpu") is False+ # ROCm reports gfx11 as (11, x): auto stays off there, =1 still forces it.+ monkeypatch.setattr(torch.version, "hip", "7.2")+ assert FD.wanted("cuda:0") is False+ monkeypatch.setenv(FD.ENV, "1")+ assert FD.wanted("cuda:0") is True+ monkeypatch.delenv(FD.ENV)+ monkeypatch.setattr(FD, "register", lambda: False)+ monkeypatch.setenv(FD.ENV, "1")+ assert FD.wanted("cuda:0") is False+++def test_routable_excludes_gpt_oss_and_chunked_layers(monkeypatch):+ monkeypatch.setattr(FD, "_describe", lambda model, config: {"full": {(64, 8, 1)}})+ for model_type, layer_types, expected in (+ ("gemma4_text", ["sliding_attention", "full_attention"], True),+ ("qwen3_5_text", ["linear_attention", "full_attention"], True),+ ("gpt_oss", ["sliding_attention", "full_attention"], False),+ ("gemma4_text", ["chunked_attention", "full_attention"], False),+ ("llama", ["full_attention"], False),+ ):+ config = types.SimpleNamespace(+ model_type = model_type, layer_types = layer_types, _attn_implementation = "sdpa"+ )+ assert FD.routable(None, config) is expected, model_type+ monkeypatch.setenv(FD.ENV, "1")+ config = types.SimpleNamespace(+ model_type = "llama", layer_types = ["full_attention"], _attn_implementation = "sdpa"+ )+ assert FD.routable(None, config) is True+ config.model_type = "gpt_oss"+ assert FD.routable(None, config) is False+++def test_unavailable_flex_decode_shape_falls_back_to_sdpa(monkeypatch):+ decode = pytest.importorskip("unsloth_zoo.flex_attention.decode")+ if FD.FlexDecodeUnavailable is None:+ pytest.skip("unsloth_zoo without FlexDecodeUnavailable")++ def unavailable(*args, **kwargs):+ raise decode.FlexDecodeUnavailable("no tile fits")++ monkeypatch.setattr(FD, "flex_decode_attention", unavailable)+ torch.manual_seed(0)+ batch, heads, kv_heads, dim, kv_length, position = 2, 4, 2, 16, 32, 9+ pad = torch.ones(batch, kv_length, dtype = torch.long)+ pad[1, :3] = 0+ mask = decode.decode_block_mask(batch, kv_length, torch.tensor(position), attention_mask = pad)+ q = torch.randn(batch, heads, 1, dim, dtype = torch.float64)+ k = torch.randn(batch, kv_heads, kv_length, dim, dtype = torch.float64)+ v = torch.randn(batch, kv_heads, kv_length, dim, dtype = torch.float64)+ module = torch.nn.Module()+ module.num_key_value_groups = heads // kv_heads+ module.is_causal = True+ out, _ = FD._attention(module, q, k, v, mask, scaling = 0.25)++ visible = (torch.arange(kv_length) <= position).view(1, kv_length) & pad.bool()+ rep = lambda x: x.repeat_interleave(heads // kv_heads, dim = 1)+ ref = torch.nn.functional.scaled_dot_product_attention(+ q, rep(k), rep(v), attn_mask = visible[:, None, None, :], scale = 0.25+ )+ torch.testing.assert_close(out, ref.transpose(1, 2), rtol = 0, atol = 1e-12)+ assert module._unsloth_flex_decode_stats == {+ "flex": 0,+ "fallback": {"flex_decoding unavailable for this shape": 1},+ }+++def test_other_flex_decode_errors_propagate(monkeypatch):+ decode = pytest.importorskip("unsloth_zoo.flex_attention.decode")++ def broken(*args, **kwargs):+ raise ValueError("bad shapes")++ monkeypatch.setattr(FD, "flex_decode_attention", broken)+ mask = decode.decode_block_mask(1, 16, torch.tensor(3))+ q = torch.randn(1, 2, 1, 8)+ k = v = torch.randn(1, 2, 16, 8)+ with pytest.raises(ValueError, match = "bad shapes"):+ FD._attention(torch.nn.Module(), q, k, v, mask)++[email protected]("path", ["dense_mask", "unavailable", "elided_causal"])+def test_softcapped_fallback_keeps_the_softcap(monkeypatch, path):+ # Fallback must keep the logit softcap (SDPA drops it silently).+ torch.manual_seed(0)+ heads, kv_heads, dim, kv_len = 4, 2, 16, 12+ q_len = 3 if path == "elided_causal" else 1+ q = torch.randn(2, heads, q_len, dim, dtype = torch.float64) * 4+ k = torch.randn(2, kv_heads, kv_len, dim, dtype = torch.float64) * 4+ v = torch.randn(2, kv_heads, kv_len, dim, dtype = torch.float64)+ visible = torch.ones(2, kv_len, dtype = torch.bool)+ visible[1, :4] = False+ module = torch.nn.Module()+ module.is_causal = True+ if path == "unavailable":+ decode = pytest.importorskip("unsloth_zoo.flex_attention.decode")+ if FD.FlexDecodeUnavailable is None:+ pytest.skip("unsloth_zoo without FlexDecodeUnavailable")++ def unavailable(*args, **kwargs):+ raise decode.FlexDecodeUnavailable("no tile fits")++ monkeypatch.setattr(FD, "flex_decode_attention", unavailable)+ pad = visible.long()+ mask = decode.decode_block_mask(2, kv_len, torch.tensor(kv_len - 1), attention_mask = pad)+ dense = visible[:, None, None, :]+ elif path == "dense_mask":+ mask = dense = visible[:, None, None, :]+ else:+ mask, dense = None, torch.ones(q_len, kv_len, dtype = torch.bool).tril()+ out, _ = FD._attention(module, q, k, v, mask, scaling = 0.25, softcap = 5.0)+ rep = lambda x: x.repeat_interleave(heads // kv_heads, dim = 1)+ scores = torch.tanh((q @ rep(k).transpose(2, 3)) * 0.25 / 5.0) * 5.0+ scores = scores.masked_fill(~dense, float("-inf"))+ ref = (torch.softmax(scores, -1) @ rep(v)).transpose(1, 2)+ torch.testing.assert_close(out, ref, rtol = 0, atol = 1e-12)+++def test_register_installs_the_block_mask_device_transfer(monkeypatch):+ # accelerate moves a split model's layer arguments with BlockMask.to(): the routed registration must install+ # zoo's transfer (rebuilds mask_mod's offsets / padding on the target card) even if gpt-oss never registered.+ decode = pytest.importorskip("unsloth_zoo.flex_attention.decode")+ if not hasattr(decode, "install_block_mask_transfer") or not FD.available():+ pytest.skip("unsloth_zoo without the shared BlockMask transfer")+ from torch.nn.attention.flex_attention import BlockMask++ plain = getattr(BlockMask.to, "__wrapped__", BlockMask.to)+ monkeypatch.setattr(BlockMask, "to", plain)+ monkeypatch.setattr(FD, "_REGISTERED", False)+ assert FD.register()+ assert getattr(BlockMask.to, "_unsloth_gpt_oss", False)+++def test_stats_counter_does_not_recompile_a_compiled_caller():+ from torch._dynamo.utils import counters++ module = torch.nn.Module()+ FD._count(module, None)++ @torch.compile(backend = "eager", fullgraph = True)+ def step(x):+ FD._count(module, None)+ return x + 1++ torch._dynamo.reset()+ before = sum(counters["recompiles"].values())+ for _ in range(12):+ step(torch.ones(2))+ assert sum(counters["recompiles"].values()) == before+ assert module.__dict__["_unsloth_flex_decode_stats"]["flex"] == 1diff --git a/unsloth/models/_flex_decode.py b/unsloth/models/_flex_decode.pynew file mode 100644index 00000000000..940d4c05bc6--- /dev/null+++ b/unsloth/models/_flex_decode.py@@ -0,0 +1,500 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""One-token flex decode (zoo flex_decoding) for FastModel generate() over a StaticCache.++Per layer type, builds zoo's graph-refillable decode BlockMask when every layer's shape is supported, else+transformers' SDPA mask, so a model can mix both. Prefill, dynamic caches and custom masks are untouched.+UNSLOTH_FLEX_DECODE: auto (sm80+, MODEL_TYPES, CUDA-graphed decode only: eager flex decode is slower than SDPA),+1 (always), 0 (off)."""++import inspect+import os+import threading+import weakref++import torch++__all__ = [+ "ATTN_KEY",+ "ENV",+ "MODEL_TYPES",+ "available",+ "register",+ "wanted",+ "routable",+ "stats",+ "reset_stats",+]++ATTN_KEY = "unsloth_flex_decode_routed"+ENV = "UNSLOTH_FLEX_DECODE"+# Model types whose flex decode was checked against eager attention.+MODEL_TYPES = frozenset(+ (+ "gemma4",+ "gemma4_text",+ "qwen3_5",+ "qwen3_5_text",+ "qwen3_5_moe",+ "qwen3_5_moe_text",+ )+)+# zoo owns these models' decode attention (gpt-oss: sinks and its own graph modes).+EXCLUDED_MODEL_TYPES = frozenset(("gpt_oss",))+_KINDS = {"full_attention": "full", "sliding_attention": "sliding"}++try:+ from unsloth_zoo.flex_attention.decode import (+ decode_block_mask,+ flex_decode_attention,+ flex_decode_supported,+ )+except Exception:+ decode_block_mask = flex_decode_attention = flex_decode_supported = None+try:+ from unsloth_zoo.flex_attention.decode import FlexDecodeUnavailable, dense_decode_mask+except Exception:+ FlexDecodeUnavailable = dense_decode_mask = None++try:+ from torch.nn.attention.flex_attention import BlockMask+except Exception:+ BlockMask = None+++def _unwrap(config):+ """The config behind a forwarding proxy (zoo's Gemma 4 _Gemma4KVSharedSafeProxy keeps it in `_real`)."""+ for _ in range(4):+ try:+ real = object.__getattribute__(config, "_real")+ except Exception:+ return config+ if real is None or real is config:+ return config+ config = real+ return config+++class _ConfigMap:+ """Keyed by id + weakref: configs are unhashable in 5.x and their __dict__ is saved by save_pretrained."""++ def __init__(self):+ self.items = {}++ def get(+ self,+ config,+ default = None,+ ):+ config = _unwrap(config)+ entry = self.items.get(id(config))+ if entry is None or entry[0]() is not config:+ return default+ return entry[1]++ def set(self, config, value):+ config = _unwrap(config)+ key = id(config)+ try:+ ref = weakref.ref(config, lambda _, key = key, items = self.items: items.pop(key, None))+ except TypeError:+ return value+ self.items[key] = (ref, value)+ return value++ def setdefault(self, config, value):+ current = self.get(config, None)+ return current if current is not None else self.set(config, value)+++_LOCK = threading.Lock()+_REGISTERED = False+_LAYERS = _ConfigMap()+_MASK_REASONS = _ConfigMap()+_SUPPORT_CACHE = {}+++def available():+ """zoo's flex decode API and a transformers mask interface taking q_length / q_offset (5.x)."""+ if decode_block_mask is None or BlockMask is None:+ return False+ try:+ from transformers.masking_utils import sdpa_mask+ except Exception:+ return False+ params = inspect.signature(sdpa_mask).parameters+ return "q_length" in params and "q_offset" in params+++def register():+ """Registers the attention + mask interface pair under ATTN_KEY (idempotent). False when unavailable."""+ global _REGISTERED+ if _REGISTERED:+ return True+ if not available():+ return False+ with _LOCK:+ if _REGISTERED:+ return True+ try:+ from transformers.masking_utils import AttentionMaskInterface+ from transformers.modeling_utils import AttentionInterface+ except Exception:+ return False+ # generate() calls .contiguous() on masks; class-level so it is not a BlockMask field in the graph key.+ if not hasattr(BlockMask, "contiguous"):+ BlockMask.contiguous = lambda self, *args, **kwargs: self+ try:+ # Accelerate moves a split model's layer arguments with BlockMask.to(), which leaves mask_mod's+ # offsets / padding on the first card; zoo's transfer rebuilds the mask on the target card.+ from unsloth_zoo.flex_attention.decode import install_block_mask_transfer+ install_block_mask_transfer()+ except Exception:+ pass+ AttentionInterface.register(ATTN_KEY, _attention)+ AttentionMaskInterface.register(ATTN_KEY, _mask)+ _REGISTERED = True+ return True+++def _mode():+ return os.environ.get(ENV, "auto").strip().lower()+++def forced():+ """UNSLOTH_FLEX_DECODE=1: flex decode whether or not the call decodes through CUDA graphs, any batch."""+ return _mode() in ("1", "true", "on", "yes", "force")+++MAX_BATCH_ENV = "UNSLOTH_FLEX_DECODE_MAX_BATCH"+++def batch_ok(batch):+ """auto: batch <= UNSLOTH_FLEX_DECODE_MAX_BATCH (default 4); A100 graphed flex is slower at batch 8."""+ if forced() or batch is None:+ return True+ try:+ limit = int(os.environ.get(MAX_BATCH_ENV, "4"))+ except ValueError:+ limit = 4+ return limit <= 0 or int(batch) <= limit+++def wanted(device):+ """Whether one-token steps on `device` should decode on flex (policy only; shapes are checked per layer)."""+ mode = _mode()+ if mode in ("0", "false", "off", "no"):+ return False+ if not register():+ return False+ if mode in ("1", "true", "on", "yes", "force"):+ return True+ try:+ device = torch.device(device)+ except Exception:+ return False+ # auto is calibrated on NVIDIA; ROCm reports gfx numbers as the capability, so it needs =1.+ if device.type != "cuda" or not torch.cuda.is_available() or torch.version.hip is not None:+ return False+ try:+ major = torch.cuda.get_device_capability(device)[0]+ except Exception:+ return False+ return major >= 8+++def _model_type(config):+ try:+ return str(getattr(config, "model_type", "") or "").lower()+ except Exception:+ return ""+++def _layer_types(config):+ try:+ return list(getattr(config, "layer_types", None) or ())+ except Exception:+ return []+++def routable(model, config):+ """Allowed model type, SDPA / eager / flex attention, no chunked layers. Records its layer shapes."""+ model_type = _model_type(config)+ if model_type in EXCLUDED_MODEL_TYPES or any(+ model_type.startswith(t) for t in EXCLUDED_MODEL_TYPES+ ):+ return False+ if _mode() not in ("1", "true", "on", "yes", "force") and model_type not in MODEL_TYPES:+ return False+ try:+ impl = getattr(config, "_attn_implementation", None)+ except Exception:+ impl = None+ if impl not in ("sdpa", "eager", "flex_attention", ATTN_KEY):+ return False+ if any(t not in _KINDS and t not in ("linear_attention",) for t in _layer_types(config)):+ return False+ layers = _describe(model, config)+ return bool(layers)+++def _describe(model, config):+ """{kind: {(head_dim, n_q, n_kv)}} over the attention modules that read `config`."""+ cached = _LAYERS.get(config)+ if cached is not None:+ return cached+ layers = {}+ types = _layer_types(config)+ real = _unwrap(config)+ for module in model.modules():+ owner = getattr(module, "config", None)+ if owner is None or _unwrap(owner) is not real:+ continue+ head_dim = getattr(module, "head_dim", None)+ groups = getattr(module, "num_key_value_groups", None)+ layer_idx = getattr(module, "layer_idx", None)+ if not isinstance(head_dim, int) or not isinstance(groups, int) or groups <= 0:+ continue+ layer_type = getattr(module, "layer_type", None)+ if layer_type is None and isinstance(layer_idx, int) and layer_idx < len(types):+ layer_type = types[layer_idx]+ kind = _KINDS.get(layer_type or "full_attention")+ if kind is None:+ continue+ try:+ n_q = int(config.num_attention_heads)+ except Exception:+ continue+ layers.setdefault(kind, set()).add((head_dim, n_q, n_q // groups))+ module.__dict__["_unsloth_flex_decode_kind"] = kind+ _LAYERS.set(config, layers)+ return layers+++def _supported(config, kind, dtype, device):+ layers = _LAYERS.get(config, {}).get(kind)+ if not layers:+ return False, f"no {kind} attention layers recorded"+ try:+ device = torch.device(device)+ except Exception:+ return False, "unknown device"+ for head_dim, n_q, n_kv in layers:+ key = (head_dim, n_q, n_kv, dtype, str(device))+ ok = _SUPPORT_CACHE.get(key)+ if ok is None:+ try:+ ok = bool(flex_decode_supported(head_dim, n_q, n_kv, dtype, device))+ except Exception:+ ok = False+ _SUPPORT_CACHE[key] = ok+ if not ok:+ return (+ False,+ f"flex decode unsupported for head_dim {head_dim}, {n_q} / {n_kv} heads, {dtype}",+ )+ return True, None+++def _note(config, kind, reason):+ if config is None:+ return+ reasons = _MASK_REASONS.setdefault(config, {})+ reasons[kind] = reason+++def _mask(+ batch_size,+ q_length = None,+ kv_length = None,+ q_offset = 0,+ kv_offset = 0,+ mask_function = None,+ attention_mask = None,+ local_size = None,+ config = None,+ use_vmap = False,+ device = "cpu",+ dtype = None,+ **kwargs,+):+ from transformers.masking_utils import ALL_MASK_ATTENTION_FUNCTIONS, causal_mask_function++ args = dict(+ batch_size = batch_size,+ q_length = q_length,+ kv_length = kv_length,+ q_offset = q_offset,+ kv_offset = kv_offset,+ mask_function = mask_function,+ attention_mask = attention_mask,+ config = config,+ use_vmap = use_vmap,+ device = device,+ dtype = dtype,+ **kwargs,+ )+ if local_size is not None:+ args["local_size"] = local_size+ kind = "sliding" if local_size else "full"+ reason = None+ if q_length != 1:+ reason = "not a one-token step"+ elif use_vmap:+ reason = "custom mask function"+ elif kind == "full" and mask_function is not causal_mask_function:+ reason = "not a causal mask"+ elif kwargs.get("allow_is_bidirectional_skip") is not None:+ reason = "bidirectional mask"+ else:+ ok, reason = _supported(config, kind, dtype, device)+ _note(config, kind, reason)+ if reason is not None:+ return ALL_MASK_ATTENTION_FUNCTIONS["sdpa"](**args)+ return decode_block_mask(+ batch_size,+ kv_length,+ q_offset,+ kv_offset,+ mask_function = mask_function,+ attention_mask = attention_mask,+ device = device,+ )+++def _count(module, reason):+ if torch.compiler.is_compiling():+ # Python counters under trace become guards: every increment would recompile.+ return+ stats = module.__dict__.get("_unsloth_flex_decode_stats")+ if stats is None:+ stats = module.__dict__["_unsloth_flex_decode_stats"] = {"flex": 0, "fallback": {}}+ if reason is None:+ stats["flex"] += 1+ else:+ stats["fallback"][reason] = stats["fallback"].get(reason, 0) + 1+++def _default_stance():+ """Compiles new flex decode shapes even under eager_on_recompile (eager flex_attention runs dense)."""+ try:+ from torch._dynamo.eval_frame import _stance+ if getattr(_stance, "stance", "default") == "eager_on_recompile" and hasattr(+ torch.compiler, "set_stance"+ ):+ return torch.compiler.set_stance("default")+ except Exception:+ pass+ return None+++def _dense_attention(module, query, key, value, attention_mask, dropout, scaling, softcap, kwargs):+ """Dense fallback: SDPA, or eager attention when a logit softcap is set (SDPA silently drops it)."""+ if softcap is None:+ from transformers.integrations.sdpa_attention import sdpa_attention_forward+ return sdpa_attention_forward(+ module, query, key, value, attention_mask, dropout = dropout, scaling = scaling, **kwargs+ )+ groups = query.shape[1] // key.shape[1]+ key = key.repeat_interleave(groups, dim = 1)+ value = value.repeat_interleave(groups, dim = 1)+ scores = torch.matmul(query, key.transpose(2, 3)) * scaling+ scores = torch.tanh(scores / softcap) * softcap+ L, S = query.shape[-2], key.shape[-2]+ if (+ attention_mask is None+ and L > 1+ and kwargs.get("is_causal", getattr(module, "is_causal", True))+ ):+ # An elided causal mask: the upper-left causal mask SDPA's is_causal would apply (query i sees keys 0..i).+ attention_mask = torch.ones(L, S, dtype = torch.bool, device = query.device).tril()+ if attention_mask is not None:+ mask = attention_mask[..., : key.shape[-2]]+ if mask.dtype == torch.bool:+ scores = scores.masked_fill(~mask, float("-inf"))+ else:+ scores = scores + mask+ upcast = torch.float32 if scores.dtype in (torch.float16, torch.bfloat16) else scores.dtype+ probs = torch.softmax(scores, dim = -1, dtype = upcast).to(query.dtype)+ probs = torch.nn.functional.dropout(+ probs, p = dropout, training = getattr(module, "training", False)+ )+ return torch.matmul(probs, value).transpose(1, 2).contiguous(), None+++def _attention(+ module,+ query,+ key,+ value,+ attention_mask,+ dropout = 0.0,+ scaling = None,+ sliding_window = None,+ softcap = None,+ **kwargs,+):+ reason = None+ if not isinstance(attention_mask, BlockMask):+ config = getattr(module, "config", None)+ kind = module.__dict__.get("_unsloth_flex_decode_kind", "full")+ reason = _MASK_REASONS.get(config, {}).get(kind) if config is not None else None+ reason = reason or "dense mask"+ elif query.shape[-2] != 1:+ reason = "not a one-token step"+ elif dropout:+ reason = "dropout"+ elif kwargs.get("s_aux") is not None:+ reason = "attention sinks"+ if reason is not None:+ _count(module, reason)+ if isinstance(attention_mask, BlockMask):+ raise RuntimeError(f"Unsloth: flex decode got a BlockMask it cannot run ({reason}).")+ return _dense_attention(+ module, query, key, value, attention_mask, dropout, scaling, softcap, kwargs+ )+ if scaling is None:+ scaling = getattr(module, "scaling", None)+ if scaling is None:+ scaling = query.shape[-1] ** -0.5+ stance = None if torch.compiler.is_compiling() else _default_stance()+ try:+ if stance is None:+ out = flex_decode_attention(query, key, value, attention_mask, scaling, softcap = softcap)+ else:+ with stance:+ out = flex_decode_attention(+ query, key, value, attention_mask, scaling, softcap = softcap+ )+ except Exception as error:+ if FlexDecodeUnavailable is None or not isinstance(error, FlexDecodeUnavailable):+ raise+ _count(module, "flex_decoding unavailable for this shape")+ dense = dense_decode_mask(attention_mask, key.shape[-2], query.device)+ return _dense_attention(module, query, key, value, dense, dropout, scaling, softcap, kwargs)+ _count(module, None)+ if out.dim() == 4 and out.shape[1] == query.shape[1] and out.shape[2] == query.shape[2]:+ out = out.transpose(1, 2)+ return out.contiguous(), None+++def stats(model):+ """{layer_idx: {"kind", "flex", "fallback"}}; counts Python executions (graph replays run none)."""+ out = {}+ for name, module in model.named_modules():+ s = module.__dict__.get("_unsloth_flex_decode_stats")+ if s is None:+ continue+ idx = getattr(module, "layer_idx", name)+ out[idx] = {+ "kind": module.__dict__.get("_unsloth_flex_decode_kind"),+ "flex": s["flex"],+ "fallback": dict(s["fallback"]),+ }+ return out+++def reset_stats(model):+ for module in model.modules():+ module.__dict__.pop("_unsloth_flex_decode_stats", None)diff --git a/unsloth/models/vision.py b/unsloth/models/vision.pyindex 098f3822808..f98adb3636f 100644--- a/unsloth/models/vision.py+++ b/unsloth/models/vision.py@@ -292,7 +292,7 @@ from ._custom_dtype import cast_mixed_linear_inputs, resolve_dtype, trusted_custfrom ._mamba_lora import patch_mamba_fused_lorafrom .remote_code_shims import apply_remote_code_shimsfrom .grouped_linear_lora import register_grouped_linear_lora-from . import _decode_graphs, _generic_decode_graphs+from . import _decode_graphs, _generic_decode_graphs, _flex_decodefrom .loader_utils import (_bnb_bits_requested,vlm_gradient_checkpointing_reentrant,@@ -1628,8 +1628,8 @@ class _GraphDecodeSteps(_EagerDecodeSteps):_generic_decode_graphs.end(self.model, keep = self.keep and exc[0] is None)-# One-token decode is slower on flex than SDPA, but prefill must stay on flex (its block mask skips tiles a-# dense mask computes). The path is picked in prepare_inputs_for_generation, where the step's mask is built.+# One-token decode on stock flex is slower than SDPA, but prefill must stay on flex (its block mask skips tiles a+# dense mask computes). StaticCache decode steps use _flex_decode where supported, else the non-flex path._FLEX_GENERATE_ENV_VAR = "UNSLOTH_FLEX_ATTENTION_GENERATE"_FLEX_GENERATE_LOCK = threading.Lock()@@ -1684,6 +1684,54 @@ def _flex_generate_configs(model):]+def _model_device(model):+ device = getattr(model, "device", None)+ if isinstance(device, torch.device):+ return device+ try:+ return next(model.parameters()).device+ except Exception:+ return None+++def _wants_attentions(model, kwargs):+ if kwargs.get("output_attentions") is not None:+ return bool(kwargs["output_attentions"])+ config = kwargs.get("generation_config") or getattr(model, "generation_config", None)+ return bool(getattr(config, "output_attentions", False))+++def _generate_routes(model, flex_decode = True):+ """(config, prefill attention, decode attention) per text attention config the generate call switches.+ Flex-preferred configs prefill on flex and decode on flex decode or the non-flex path; other configs of a+ flex-decode model keep their attention for prefill and decode on flex decode. flex_decode=False (attention+ weights requested: flex decode returns none) keeps every decode on its non-flex attention."""+ routes = [(c, "flex_attention", _NON_FLEX_DECODE) for c in _flex_generate_configs(model)]+ config = getattr(model, "config", None)+ if config is None or not flex_decode or not _flex_decode.wanted(_model_device(model)):+ return routes+ base = model.get_base_model() if hasattr(model, "get_base_model") else model+ if getattr(base, _EXPLICIT_FLEX_ATTR, False) or getattr(model, _EXPLICIT_FLEX_ATTR, False):+ return routes+ seen = {id(c) for c, _, _ in routes}+ out = []+ for c, prefill, decode in routes:+ if _flex_decode.routable(base, c):+ decode = _flex_decode.ATTN_KEY+ out.append((c, prefill, decode))+ for c in _text_attention_configs(config):+ if id(c) in seen:+ continue+ impl = _config_get(c, "_attn_implementation", None)+ if impl in ("sdpa", "eager") and _flex_decode.routable(base, c):+ out.append((c, impl, _flex_decode.ATTN_KEY))+ return out+++def _static_cache(cache):+ return cache is not None and bool(getattr(cache, "is_compileable", False))++def _step_query_length(model_inputs):if not isinstance(model_inputs, dict):return None@@ -1697,18 +1745,35 @@ def _step_query_length(model_inputs):class _NonFlexGenerate:"""Threads are serialised per model: they share one config, switched between mask build and forward."""- def __init__(self, model):+ def __init__(+ self,+ model,+ flex_decode = True,+ ):self.model = model+ self.flex_decode = flex_decodeself.active = Falseself.serial = Noneself.base = model.get_base_model() if hasattr(model, "get_base_model") else model- def _set(self, decode):+ def _set(+ self,+ decode,+ static = False,+ batch = None,+ ):state = self.model.__dict__if state.get("_unsloth_non_flex_generate_pinned", False):decode = True- value = _NON_FLEX_DECODE if decode else "flex_attention"- for c in state.get("_unsloth_non_flex_generate_configs", ()):+ for c, prefill, decode_impl in state.get("_unsloth_non_flex_generate_configs", ()):+ value = decode_impl if decode else prefill+ # Needs fixed shapes (StaticCache); pays off only under CUDA graphs.+ if value == _flex_decode.ATTN_KEY and not (+ static+ and _flex_decode.batch_ok(batch)+ and (_flex_decode.forced() or _decode_graphs.call_plan() == "graph")+ ):+ value = _NON_FLEX_DECODE if prefill == "flex_attention" else prefillif _config_get(c, "_attn_implementation", None) != value:_config_set(c, "_attn_implementation", value)@@ -1723,11 +1788,14 @@ class _NonFlexGenerate:else:decode = scope.steps > 0scope.steps += 1- scope._set(decode)+ static = _static_cache(kwargs.get("past_key_values"))+ ids = args[0] if args else kwargs.get("input_ids")+ batch = ids.shape[0] if isinstance(ids, torch.Tensor) and ids.dim() >= 1 else None+ scope._set(decode, static, batch)model_inputs = prepare(*args, **kwargs)q_len = _step_query_length(model_inputs)if q_len is not None and (q_len == 1) != decode:- scope._set(q_len == 1)+ scope._set(q_len == 1, static, batch)model_inputs = prepare(*args, **kwargs)return model_inputs@@ -1737,7 +1805,7 @@ class _NonFlexGenerate:state = self.model.__dict__with _FLEX_GENERATE_LOCK:routed = _FLEX_GENERATE_ROUTING.get(self.base, 0) > 0 or bool(- _flex_generate_configs(self.model)+ _generate_routes(self.model, self.flex_decode))serial = Noneif routed:@@ -1751,7 +1819,7 @@ class _NonFlexGenerate:with _FLEX_GENERATE_LOCK:depth = state.get("_unsloth_non_flex_generate", 0)if depth == 0:- configs = _flex_generate_configs(self.model)+ configs = _generate_routes(self.model, self.flex_decode)if not configs:self._release()return self@@ -2487,7 +2555,7 @@ def unsloth_base_fast_generate(self, *args, **kwargs):def _run(scope, plan):with (- _NonFlexGenerate(self),+ _NonFlexGenerate(self, flex_decode = not _wants_attentions(self, kwargs)),decode_scope,scope,_decode_graphs.plan_scope(plan),