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
Resolve apply_qkv and apply_o defensively, and explain zero patch counts (#11038)
Daniel Hanac9f9b8b82ab
diff --git a/tests/test_apply_qkv_fallback.py b/tests/test_apply_qkv_fallback.pynew file mode 100644index 00000000000..cdddd0047f7--- /dev/null+++ b/tests/test_apply_qkv_fallback.py@@ -0,0 +1,295 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""apply_qkv / apply_o must resolve even when the instance attribute is absent.++unsloth#1713 and unsloth#2587. pre_patch() replaces LlamaAttention.forward (and the six+sibling architectures) CLASS-WIDE, but apply_qkv and apply_o are attached PER INSTANCE+afterwards, in unsloth/models/llama.py. Two consequences, both reported:++ * unsloth#1713: a plain transformers model of the same architecture, built in the same+ process after FastLanguageModel.from_pretrained, runs unsloth's forward on instances+ that never got the attributes, and dies with+ AttributeError: 'LlamaAttention' object has no attribute 'apply_qkv'.+ * unsloth#2587: the fast_inference path loads vLLM before the attributes are attached,+ so vLLM's Transformers backend fallback runs the patched forward during profile_run+ and dies the same way.++The module level original_apply_qkv / original_apply_o are exactly what the loader would+have attached, so the call sites resolve through them as a default. The instance attribute+still wins, which is what keeps the fused LoRA kernels (apply_lora_qkv / apply_lora_o)+selected after get_peft_model.++The forward itself needs a real accelerator (triton rope, attention dispatch), so the CPU+tests here pin the resolution and the source contract; test_apply_qkv_fallback_end_to_end+below carries the executed half and is marked gpu.+"""++from __future__ import annotations++import ast+import importlib+import os+import pathlib++import pytest+import torch+import unsloth # noqa: F401++from unsloth.models import llama as llama_module++# Every model file whose patched attention forward calls apply_qkv / apply_o. gemma.py,+# qwen2.py and the vision/MoE loaders reuse LlamaAttention_fast_forward itself, so they+# resolve the fallback out of llama.py's own globals and are covered by the llama row.+ATTENTION_FILES = (+ "llama.py",+ "cohere.py",+ "falcon_h1.py",+ "gemma2.py",+ "granite.py",+ "mistral.py",+ "qwen3.py",+)++# The six that get the fallback by import rather than by definition.+SIBLING_FILES = tuple(f for f in ATTENTION_FILES if f != "llama.py")++FALLBACKS = (("apply_qkv", "original_apply_qkv"), ("apply_o", "original_apply_o"))++MODELS_DIR = pathlib.Path(llama_module.__file__).resolve().parent+++def _tree(filename: str) -> ast.Module:+ return ast.parse((MODELS_DIR / filename).read_text(encoding = "utf-8"))+++def _bare_self_calls(tree: ast.Module, attr: str) -> list[int]:+ """Line numbers of every `self.<attr>(...)` call."""+ hits = []+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == attr+ and isinstance(node.func.value, ast.Name)+ and node.func.value.id == "self"+ ):+ hits.append(node.lineno)+ return hits+++def _fallback_calls(tree: ast.Module, attr: str, fallback: str) -> list[int]:+ """Line numbers of every `getattr(self, "<attr>", <fallback>)(...)` call."""+ hits = []+ for node in ast.walk(tree):+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Call)):+ continue+ inner = node.func+ if not (isinstance(inner.func, ast.Name) and inner.func.id == "getattr"):+ continue+ if len(inner.args) != 3:+ continue+ target, name, default = inner.args+ if not (isinstance(target, ast.Name) and target.id == "self"):+ continue+ if not (isinstance(name, ast.Constant) and name.value == attr):+ continue+ if isinstance(default, ast.Name) and default.id == fallback:+ hits.append(node.lineno)+ return hits++[email protected]("filename", ATTENTION_FILES)[email protected]("attr,fallback", FALLBACKS)+def test_no_bare_instance_attribute_call(filename, attr, fallback):+ """A bare self.apply_qkv(...) is the defect; there must be none left."""+ bare = _bare_self_calls(_tree(filename), attr)+ assert bare == [], (+ f"unsloth/models/{filename} calls self.{attr}(...) with no fallback at "+ f"line(s) {bare}; use getattr(self, {attr!r}, {fallback}) so an instance that "+ "never reached the loader's attach step still resolves (unsloth#1713, unsloth#2587)"+ )++[email protected]("filename", ATTENTION_FILES)[email protected]("attr,fallback", FALLBACKS)+def test_call_site_uses_the_module_level_fallback(filename, attr, fallback):+ """And the call site really is the getattr form, not something else that happens to parse."""+ calls = _fallback_calls(_tree(filename), attr, fallback)+ assert (+ calls+ ), f"unsloth/models/{filename} has no getattr(self, {attr!r}, {fallback})(...) call site"++[email protected]("filename", SIBLING_FILES)[email protected]("attr,fallback", FALLBACKS)+def test_sibling_files_import_the_fallback_explicitly(filename, attr, fallback):+ """`from .llama import *` would also deliver these names, but only for as long as+ llama.py has no __all__ and neither name is renamed. The call sites are load bearing,+ so the import is explicit."""+ tree = _tree(filename)+ imported = {+ alias.name+ for node in ast.walk(tree)+ if isinstance(node, ast.ImportFrom) and node.module == "llama" and node.level == 1+ for alias in node.names+ }+ assert fallback in imported, (+ f"unsloth/models/{filename} must carry an explicit `from .llama import {fallback}`; "+ f"found {sorted(imported)}"+ )++[email protected]("filename", ATTENTION_FILES)[email protected]("attr,fallback", FALLBACKS)+def test_fallback_resolves_to_the_same_function_in_every_module(filename, attr, fallback):+ """The import audit above is static; this one loads each module and checks the object."""+ module = importlib.import_module(f"unsloth.models.{filename[:-3]}")+ assert getattr(module, fallback) is getattr(llama_module, fallback)+++def _plain_llama_attention():+ """A transformers LlamaAttention built outside unsloth's loader, as in unsloth#1713."""+ from transformers import LlamaConfig+ from transformers.models.llama.modeling_llama import LlamaAttention++ config = LlamaConfig(+ hidden_size = 32,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ intermediate_size = 64,+ num_hidden_layers = 1,+ vocab_size = 64,+ )+ return LlamaAttention(config, layer_idx = 0)+++def test_plain_attention_has_neither_attribute():+ """The premise: nothing attaches apply_qkv / apply_o to an instance unsloth did not load."""+ attention = _plain_llama_attention()+ assert not hasattr(attention, "apply_qkv")+ assert not hasattr(attention, "apply_o")+++def test_fallback_runs_on_an_instance_that_never_reached_the_loader():+ """The fallback is not just resolvable, it produces the projections the forward wants."""+ attention = _plain_llama_attention()+ hidden_states = torch.randn(1, 3, attention.config.hidden_size)++ apply_qkv = getattr(attention, "apply_qkv", llama_module.original_apply_qkv)+ apply_o = getattr(attention, "apply_o", llama_module.original_apply_o)+ assert apply_qkv is llama_module.original_apply_qkv+ assert apply_o is llama_module.original_apply_o++ Q, K, V = apply_qkv(attention, hidden_states)+ head_dim = attention.head_dim+ config = attention.config+ assert Q.shape == (1, 3, config.num_attention_heads * head_dim)+ assert K.shape == (1, 3, config.num_key_value_heads * head_dim)+ assert V.shape == K.shape++ attn_output = apply_o(attention, torch.randn(1, 3, config.num_attention_heads * head_dim))+ assert attn_output.shape == (1, 3, config.hidden_size)+++def test_instance_attribute_still_wins_over_the_fallback():+ """This is the whole safety argument: the fused LoRA kernels are still selected, so+ the getattr default only ever fires where the old code raised."""+ from unsloth.kernels import apply_lora_o, apply_lora_qkv++ attention = _plain_llama_attention()+ attention.apply_qkv = apply_lora_qkv+ attention.apply_o = apply_lora_o++ assert getattr(attention, "apply_qkv", llama_module.original_apply_qkv) is apply_lora_qkv+ assert getattr(attention, "apply_o", llama_module.original_apply_o) is apply_lora_o++ # And the loader's own attach step keeps working.+ attention.apply_qkv = llama_module.original_apply_qkv+ attention.apply_o = llama_module.original_apply_o+ assert getattr(attention, "apply_qkv", None) is llama_module.original_apply_qkv+ assert getattr(attention, "apply_o", None) is llama_module.original_apply_o+++def _plain_model_dtype() -> "torch.dtype":+ """The dtype to build the plain transformers model at.++ sm_75 cards such as the T4 have no bfloat16, and triton rejects a bfloat16 kernel+ for them (`.bf16 requires .target sm_80`) before the code under test is reached.+ `UNSLOTH_TEST_PLAIN_DTYPE` forces one of the two branches so both can be covered on+ a card that supports both.+ """+ forced = os.environ.get("UNSLOTH_TEST_PLAIN_DTYPE", "auto")+ if forced == "float16":+ return torch.float16+ if forced == "bfloat16":+ return torch.bfloat16+ try:+ return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16+ except Exception:+ return torch.float16+++ not torch.cuda.is_available(),+ reason = "loads a real checkpoint through FastLanguageModel; needs an accelerator",+)+def test_apply_qkv_fallback_end_to_end():+ """unsloth#1713 as reported: load with unsloth, then build a plain transformers model of+ the same architecture in the same process and run it. Needs a real accelerator because+ the patched forward uses triton rope and the attention dispatch."""+ from transformers import AutoConfig, AutoModelForCausalLM++ from unsloth import FastLanguageModel++ model_name = "unsloth/Llama-3.2-1B-Instruct"+ model, _tokenizer = FastLanguageModel.from_pretrained(+ model_name,+ max_seq_length = 512,+ load_in_4bit = True,+ )++ config = AutoConfig.from_pretrained(model_name)+ config.num_hidden_layers = 1++ # The checkpoint is bfloat16, which pre-Ampere cards cannot assemble, so pick the+ # widest dtype the device really has. Set the config attributes as well as the+ # keyword: the patched forward casts activations to the config dtype+ # (`dtype_from_config(self.config)` in llama.py), and on transformers 4.57.6 the+ # keyword casts the weights but leaves `config.dtype` at the checkpoint value, so+ # the two would disagree and the kernel would be handed a bfloat16 activation with+ # float16 weights.+ dtype = _plain_model_dtype()+ for attribute in ("torch_dtype", "dtype"):+ try:+ setattr(config, attribute, str(dtype).replace("torch.", ""))+ except Exception:+ pass+ try:+ plain = AutoModelForCausalLM.from_config(config, dtype = dtype)+ except TypeError:+ # transformers 4.x spelling, before `dtype` became the keyword name.+ plain = AutoModelForCausalLM.from_config(config, torch_dtype = dtype)+ plain = plain.to("cuda").eval()+ assert next(plain.parameters()).dtype is dtype+ for layer in plain.model.layers:+ assert not hasattr(layer.self_attn, "apply_qkv")++ with torch.no_grad():+ out = plain(input_ids = torch.randint(0, 128, (1, 8), device = "cuda"))+ assert out.logits.shape == (1, 8, config.vocab_size)++ # The fused kernels must still win on the unsloth-loaded model.+ from unsloth.kernels import apply_lora_o, apply_lora_qkv++ model = FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"],+ random_state = 0,+ )+ first = model.model.model.layers[0].self_attn+ assert first.apply_qkv is apply_lora_qkv+ assert first.apply_o is apply_lora_odiff --git a/tests/test_lora_dropout_patch_summary.py b/tests/test_lora_dropout_patch_summary.pynew file mode 100644index 00000000000..7e8eec738b4--- /dev/null+++ b/tests/test_lora_dropout_patch_summary.py@@ -0,0 +1,150 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The patched layers summary says why the fused LoRA kernels were skipped.++unsloth#2076. patch_peft_model only installs the fused kernels when+`lora_dropout == 0 and bias == "none"`, so anyone who passes lora_dropout = 0.1 (or a bias+term) gets++ Unsloth 2026.x patched 32 layers with 0 QKV layers, 0 O layers and 0 MLP layers.++which reads as a failed patch even though training is fine. _fused_lora_skip_reason supplies+the missing clause. It is a separate function so the wording can be tested without loading+a checkpoint, and the gate parity test below is what stops the two from drifting apart.+"""++from __future__ import annotations++import ast+import inspect+import itertools+import textwrap++import pytest+import torch+import unsloth # noqa: F401++from unsloth.models import llama as llama_module+from unsloth.models.llama import _fused_lora_skip_reason+++def test_no_reason_when_the_fused_kernels_were_installed():+ assert _fused_lora_skip_reason(0, "none") == ""+ assert _fused_lora_skip_reason(0.0, "none") == ""+++def test_lora_dropout_is_named_with_its_value():+ reason = _fused_lora_skip_reason(0.1, "none")+ assert "lora_dropout = 0.1" in reason+ assert "bias" not in reason+ assert "Training is unaffected." in reason+++def test_bias_is_named_with_its_value():+ reason = _fused_lora_skip_reason(0, "all")+ assert "bias = 'all'" in reason+ assert "lora_dropout" not in reason+++def test_both_reasons_are_joined():+ reason = _fused_lora_skip_reason(0.05, "lora_only")+ assert "lora_dropout = 0.05" in reason+ assert "bias = 'lora_only'" in reason+ assert " and " in reason+++def test_reason_appends_cleanly_to_the_summary_sentence():+ """The summary line ends in a full stop and the reason is appended straight onto it,+ so the reason must start with a space and must not start a new sentence mid word."""+ reason = _fused_lora_skip_reason(0.1, "none")+ assert reason.startswith(" ")+ assert reason.endswith(".")+ assert " " not in ("...0 MLP layers." + reason)+++ "lora_dropout,bias",+ list(itertools.product([0, 0.0, 0.1, 0.5], ["none", "all", "lora_only"])),+)+def test_reason_is_non_empty_exactly_when_the_fused_gate_is_closed(lora_dropout, bias):+ """Parity with the `lora_dropout == 0 and bias == "none"` gate in patch_peft_model."""+ fused_installed = lora_dropout == 0 and bias == "none"+ assert bool(_fused_lora_skip_reason(lora_dropout, bias)) is not fused_installed+++def _gate_tests(source: str) -> list[str]:+ """Every `if` test in patch_peft_model that reads both lora_dropout and bias."""+ tree = ast.parse(textwrap.dedent(source))+ out = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.If):+ continue+ names = {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)}+ if {"lora_dropout", "bias"} <= names:+ out.append(ast.unparse(node.test))+ return out+++def test_patch_peft_model_still_gates_the_fused_kernels_on_the_same_two_values():+ """If the gate grows a third condition, _fused_lora_skip_reason has to grow with it or+ the summary starts reporting zero counts with no reason again."""+ source = inspect.getsource(llama_module.FastLlamaModel.patch_peft_model)+ assert _gate_tests(source) == ["lora_dropout == 0 and bias == 'none'"]+++def test_the_summary_call_carries_the_reason():+ source = inspect.getsource(llama_module.FastLlamaModel.patch_peft_model)+ assert "unfused_reason = _fused_lora_skip_reason(lora_dropout, bias)" in source+ assert "MLP layers.{unfused_reason}" in source+++ not torch.cuda.is_available(),+ reason = "loads a real checkpoint through FastLanguageModel; needs an accelerator",+)+def test_summary_reason_is_logged_for_a_real_model():+ """unsloth#2076 end to end: the reason has to reach the user's console."""+ import logging++ from unsloth import FastLanguageModel++ records = []++ class _Capture(logging.Handler):+ def emit(self, record):+ records.append(record.getMessage())++ model, _tokenizer = FastLanguageModel.from_pretrained(+ "unsloth/Llama-3.2-1B-Instruct",+ max_seq_length = 512,+ load_in_4bit = True,+ )+ # warning_once (patched onto logging.Logger by transformers) dedupes process wide.+ getattr(llama_module.logger.warning_once, "cache_clear", lambda: None)()++ # Attach to the logger llama.py actually writes to. Naming it here rather than the+ # root logger keeps the test correct whether or not transformers has switched off+ # propagation on its own library logger.+ handler = _Capture()+ target = llama_module.logger+ target.addHandler(handler)+ previous_level = target.level+ target.setLevel(logging.WARNING)+ try:+ model = FastLanguageModel.get_peft_model(+ model,+ r = 8,+ lora_alpha = 16,+ lora_dropout = 0.1,+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"],+ random_state = 0,+ )+ finally:+ target.removeHandler(handler)+ target.setLevel(previous_level)++ summary = [m for m in records if "MLP layers." in m]+ assert summary, records+ assert "lora_dropout = 0.1" in summary[-1], summary[-1]diff --git a/unsloth/models/cohere.py b/unsloth/models/cohere.pyindex e212a0f7749..4051a7a9d14 100644--- a/unsloth/models/cohere.py+++ b/unsloth/models/cohere.py@@ -10,6 +10,10 @@# limitations under the License.from .llama import *+from .llama import (+ original_apply_qkv,+ original_apply_o,+)from ._utils import __version__from unsloth_zoo.hf_utils import dtype_from_configfrom unsloth_zoo.utils import _get_dtype, Version@@ -106,7 +110,7 @@ def CohereAttention_fast_forward(head_dim = self.head_dimassert n_kv_heads * n_groups == n_heads- Q, K, V = self.apply_qkv(self, hidden_states)+ Q, K, V = getattr(self, "apply_qkv", original_apply_qkv)(self, hidden_states)Q = Q.view(bsz, q_len, n_heads, head_dim).transpose(1, 2)K = K.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)@@ -165,7 +169,7 @@ def CohereAttention_fast_forward(A = run_attention(config = attention_config, context = context, Q = Q, K = K, V = V)attn_output = A.reshape(bsz, q_len, n_heads * head_dim)- attn_output = self.apply_o(self, attn_output)+ attn_output = getattr(self, "apply_o", original_apply_o)(self, attn_output)attn_weights = Nonereturn attn_output, attn_weights, past_key_valuediff --git a/unsloth/models/falcon_h1.py b/unsloth/models/falcon_h1.pyindex 34c9d8cdd11..ed295061d92 100644--- a/unsloth/models/falcon_h1.py+++ b/unsloth/models/falcon_h1.py@@ -27,6 +27,8 @@ from .llama import (LlamaRotaryEmbedding,LlamaLinearScalingRotaryEmbedding,_LlamaModel_fast_forward_inference,+ original_apply_qkv,+ original_apply_o,)try:@@ -98,7 +100,7 @@ def FalconH1Attention_fast_forward(head_dim = self.head_dimassert n_kv_heads * n_groups == n_heads- Q, K, V = self.apply_qkv(self, hidden_states)+ Q, K, V = getattr(self, "apply_qkv", original_apply_qkv)(self, hidden_states)Q = Q.view(bsz, q_len, n_heads, head_dim)K = K.view(bsz, q_len, n_kv_heads, head_dim)V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)@@ -170,7 +172,7 @@ def FalconH1Attention_fast_forward(A = run_attention(config = attention_config, context = context, Q = Q, K = K, V = V)attn_output = A.reshape(bsz, q_len, n_heads * head_dim)- attn_output = self.apply_o(self, attn_output)+ attn_output = getattr(self, "apply_o", original_apply_o)(self, attn_output)attn_weights = Nonereturn attn_output, attn_weights, past_key_valuediff --git a/unsloth/models/gemma2.py b/unsloth/models/gemma2.pyindex 672feeff8a9..1b4af1ebbdc 100644--- a/unsloth/models/gemma2.py+++ b/unsloth/models/gemma2.py@@ -10,6 +10,10 @@# limitations under the License.from .llama import *+from .llama import (+ original_apply_qkv,+ original_apply_o,+)from ._utils import __version__from unsloth_zoo.utils import _get_dtype, Versionfrom unsloth_zoo.hf_utils import dtype_from_config@@ -97,7 +101,7 @@ def Gemma2Attention_fast_forward(head_dim = self.head_dimassert n_kv_heads * n_groups == n_heads- Q, K, V = self.apply_qkv(self, hidden_states)+ Q, K, V = getattr(self, "apply_qkv", original_apply_qkv)(self, hidden_states)Q = Q.view(bsz, q_len, n_heads, head_dim).transpose(1, 2)K = K.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)@@ -191,7 +195,7 @@ def Gemma2Attention_fast_forward(else slow_attention_softcapping)A = fx(Q, K, V, causal_mask, self, bsz, kv_seq_len)- A = self.apply_o(self, A)+ A = getattr(self, "apply_o", original_apply_o)(self, A)return A, None, past_key_valuediff --git a/unsloth/models/granite.py b/unsloth/models/granite.pyindex cc071fda2ca..5410a8bd41c 100644--- a/unsloth/models/granite.py+++ b/unsloth/models/granite.py@@ -26,6 +26,8 @@ from ..utils.attention_dispatch import (from .llama import (LlamaRotaryEmbedding,LlamaLinearScalingRotaryEmbedding,+ original_apply_qkv,+ original_apply_o,)from .mistral import *@@ -107,7 +109,7 @@ def GraniteAttention_fast_forward(dropout_p = self.config.attention_dropout if self.training else 0assert n_kv_heads * n_groups == n_heads- Q, K, V = self.apply_qkv(self, hidden_states)+ Q, K, V = getattr(self, "apply_qkv", original_apply_qkv)(self, hidden_states)Q = Q.view(bsz, q_len, n_heads, head_dim).transpose(1, 2)K = K.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)@@ -186,7 +188,7 @@ def GraniteAttention_fast_forward(A = run_attention(config = attention_config, context = context, Q = Q, K = K, V = V)attn_output = A.reshape(bsz, q_len, n_heads * head_dim)- attn_output = self.apply_o(self, attn_output)+ attn_output = getattr(self, "apply_o", original_apply_o)(self, attn_output)attn_weights = Nonereturn attn_output, attn_weights, past_key_valuediff --git a/unsloth/models/llama.py b/unsloth/models/llama.pyindex 6fe9aa5292a..69d0248930b 100644--- a/unsloth/models/llama.py+++ b/unsloth/models/llama.py@@ -696,7 +696,7 @@ def LlamaAttention_fast_forward(head_dim = self.head_dimassert n_kv_heads * n_groups == n_heads- Q, K, V = self.apply_qkv(self, hidden_states)+ Q, K, V = getattr(self, "apply_qkv", original_apply_qkv)(self, hidden_states)Q = Q.view(bsz, q_len, n_heads, head_dim).transpose(1, 2)K = K.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)@@ -756,7 +756,7 @@ def LlamaAttention_fast_forward(A = run_attention(config = config, context = context, Q = Q, K = K, V = V)attn_output = A.reshape(bsz, q_len, n_heads * head_dim)- attn_output = self.apply_o(self, attn_output)+ attn_output = getattr(self, "apply_o", original_apply_o)(self, attn_output)attn_weights = Nonereturn attn_output, attn_weights, past_key_value@@ -2196,6 +2196,25 @@ def _vllm_will_load_weights(fast_inference, num_labels = None):return True+def _fused_lora_skip_reason(lora_dropout, bias) -> str:+ """Why patch_peft_model skipped the fused LoRA kernels, for the patched layers summary.++ Returns "" when nothing disabled them, so the common summary line is unchanged. The+ conditions mirror the `lora_dropout == 0 and bias == "none"` gate in patch_peft_model.+ """+ reasons = []+ if lora_dropout != 0:+ reasons.append(f"lora_dropout = {lora_dropout}")+ if bias != "none":+ reasons.append(f"bias = '{bias}'")+ if not reasons:+ return ""+ return (+ f" The fused LoRA kernels were skipped because {' and '.join(reasons)}, "+ "which is why the counts are zero. Training is unaffected."+ )++class FastLlamaModel:@staticmethoddef _prepare_for_qat(model, qat_scheme):@@ -3768,9 +3787,11 @@ class FastLlamaModel:"are not enabled or a bias term (like in Qwen) is used.")+ # A zero count reads as a failure, so say why the fused kernels were skipped.+ unfused_reason = _fused_lora_skip_reason(lora_dropout, bias)logger.warning_once(f"Unsloth {__version__} patched {len(model.model.model.layers)} layers with "- f"{n_qkv} QKV layers, {n_o} O layers and {n_mlp} MLP layers.",+ f"{n_qkv} QKV layers, {n_o} O layers and {n_mlp} MLP layers.{unfused_reason}",)patch_saving_functions(model)diff --git a/unsloth/models/mistral.py b/unsloth/models/mistral.pyindex fc3345f3d18..3db12fe3043 100644--- a/unsloth/models/mistral.py+++ b/unsloth/models/mistral.py@@ -31,6 +31,8 @@ from ..utils.attention_dispatch import (from .llama import (LlamaRotaryEmbedding,LlamaLinearScalingRotaryEmbedding,+ original_apply_qkv,+ original_apply_o,)from transformers.models.mistral.modeling_mistral import (MistralAttention,@@ -82,7 +84,7 @@ def MistralAttention_fast_forward(head_dim = self.head_dimassert n_kv_heads * n_groups == n_heads- Q, K, V = self.apply_qkv(self, hidden_states)+ Q, K, V = getattr(self, "apply_qkv", original_apply_qkv)(self, hidden_states)Q = Q.view(bsz, q_len, n_heads, head_dim).transpose(1, 2)K = K.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)@@ -151,7 +153,7 @@ def MistralAttention_fast_forward(A = run_attention(config = attention_config, context = context, Q = Q, K = K, V = V)attn_output = A.reshape(bsz, q_len, n_heads * head_dim)- attn_output = self.apply_o(self, attn_output)+ attn_output = getattr(self, "apply_o", original_apply_o)(self, attn_output)attn_weights = Nonereturn attn_output, attn_weights, past_key_valuediff --git a/unsloth/models/qwen3.py b/unsloth/models/qwen3.pyindex d30a2984763..e064826e6d0 100644--- a/unsloth/models/qwen3.py+++ b/unsloth/models/qwen3.py@@ -27,6 +27,8 @@ from .llama import (LlamaRotaryEmbedding,LlamaLinearScalingRotaryEmbedding,_LlamaModel_fast_forward_inference,+ original_apply_qkv,+ original_apply_o,)try:@@ -91,7 +93,7 @@ def Qwen3Attention_fast_forward(head_dim = self.head_dimassert n_kv_heads * n_groups == n_heads- Q, K, V = self.apply_qkv(self, hidden_states)+ Q, K, V = getattr(self, "apply_qkv", original_apply_qkv)(self, hidden_states)Q = Q.view(bsz, q_len, n_heads, head_dim)K = K.view(bsz, q_len, n_kv_heads, head_dim)V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2)@@ -157,7 +159,7 @@ def Qwen3Attention_fast_forward(A = run_attention(config = attention_config, context = context, Q = Q, K = K, V = V)attn_output = A.reshape(bsz, q_len, n_heads * head_dim)- attn_output = self.apply_o(self, attn_output)+ attn_output = getattr(self, "apply_o", original_apply_o)(self, attn_output)attn_weights = Nonereturn attn_output, attn_weights, past_key_value