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
Run non-LoRA PEFT adapters through their own forward in fast inference (#13578)
Daniel Han51d8ca30ba32
diff --git a/tests/test_non_lora_peft_inference.py b/tests/test_non_lora_peft_inference.pynew file mode 100644index 00000000000..147c99c7205--- /dev/null+++ b/tests/test_non_lora_peft_inference.py@@ -0,0 +1,84 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++from __future__ import annotations++import pytest+import torch+import unsloth # noqa: F401++from real_accelerator import has_real_cuda++pytestmark = [+ pytest.mark.gpu,+ pytest.mark.skipif(not has_real_cuda(), reason = "needs a real CUDA device"),+]++H = 64+++class _Block(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.q_proj = torch.nn.Linear(H, H, bias = False)+++def _config(method):+ import peft++ if method == "lora":+ return peft.LoraConfig(+ r = 4, lora_alpha = 8, target_modules = ["q_proj"], init_lora_weights = False+ )+ if method == "vera":+ return peft.VeraConfig(r = 8, target_modules = ["q_proj"], init_weights = False)+ if method == "loha":+ return peft.LoHaConfig(r = 4, alpha = 8, target_modules = ["q_proj"], init_weights = False)+ if method == "lokr":+ return peft.LoKrConfig(r = 4, alpha = 8, target_modules = ["q_proj"], init_weights = False)+ if method == "ia3":+ return peft.IA3Config(+ target_modules = ["q_proj"], feedforward_modules = [], init_ia3_weights = False+ )+ if method == "adalora":+ return peft.AdaLoraConfig(init_r = 4, target_r = 2, total_step = 10, target_modules = ["q_proj"])+ raise ValueError(method)+++def _q_proj(method):+ from peft import get_peft_model++ torch.manual_seed(3407)+ model = get_peft_model(_Block(), _config(method)).to("cuda", torch.bfloat16)+ proj = model.base_model.model.q_proj+ if method == "adalora":+ with torch.no_grad():+ # lora_E starts at zero, so the adapter would be a no-op+ proj.lora_E["default"].normal_(std = 10.0)+ return proj++[email protected]("method", ["vera", "loha", "lokr", "ia3", "adalora"])[email protected]("q_len", [1, 5])+def test_fast_linear_forward_runs_non_lora_adapter(method, q_len):+ from unsloth.kernels import fast_linear_forward++ proj = _q_proj(method)+ X = torch.randn(1, q_len, H, device = "cuda", dtype = torch.bfloat16)+ with torch.no_grad():+ expected = proj(X)+ # a no-op adapter would make this test vacuous+ assert not torch.allclose(expected, proj.base_layer(X), rtol = 2e-2, atol = 2e-2)+ out = torch.empty(1, q_len, H, device = "cuda", dtype = torch.bfloat16)+ got = fast_linear_forward(proj, X, out = out)+ torch.testing.assert_close(got, expected, rtol = 2e-2, atol = 2e-2)+ assert got.data_ptr() == out.data_ptr()+++def test_only_non_lora_adapters_leave_the_fast_path():+ from unsloth.kernels.utils import _has_non_lora_adapter++ for method in ("vera", "loha", "lokr", "ia3", "adalora"):+ assert _has_non_lora_adapter(_q_proj(method))+ assert not _has_non_lora_adapter(_q_proj("lora"))+ assert not _has_non_lora_adapter(torch.nn.Linear(H, H))diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.pyindex 7e7e40152a5..49ea13c182b 100644--- a/unsloth/kernels/utils.py+++ b/unsloth/kernels/utils.py@@ -362,6 +362,12 @@ def _has_active_dora_adapter(proj):return any(adapter in magnitude for adapter in adapters)+def _has_non_lora_adapter(proj):+ # VeRA, LoHa, LoKr, IA3, OFT and AdaLoRA layers from peft.get_peft_model hold no lora_A Linears (#1385).+ modules = proj._modules+ return "base_layer" in modules and not isinstance(modules.get("lora_A"), torch.nn.ModuleDict)++def _has_active_lora_bias(proj):# PEFT lora_bias=True gives lora_B a bias, which the fast LoRA paths never add.lora_B = getattr(proj, "lora_B", None)@@ -1421,7 +1427,8 @@ def fast_linear_forward(out = None,):if (- _has_multiple_active_adapters(proj)+ _has_non_lora_adapter(proj)+ or _has_multiple_active_adapters(proj)or _has_active_dora_adapter(proj)or _has_active_lora_bias(proj)or _has_packed_qweight(proj)diff --git a/unsloth/save.py b/unsloth/save.pyindex 4eca801fa53..4c837b9cf8a 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -3891,7 +3891,9 @@ def _assert_export_target_is_not_base_with_lora_layers(self):"Unsloth: This model has LoRA layers, but the save method was called on the ""base model. This happens when the adapter is attached with ""`peft.PeftModel.from_pretrained`. Load the adapter folder with "- "`FastModel.from_pretrained(<adapter folder>)` instead."+ "`FastModel.from_pretrained(<adapter folder>)` instead. If the adapter was added with "+ "`peft.get_peft_model` (VeRA, LoHa, AdaLoRA, ...), run `model = model.merge_and_unload()` "+ "first, then save.")