Skip to content

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.

Apply the DoRA magnitude in fast_linear_forward (#12642)

Vineeth Sai Varikuntla93434b1c4309
diff --git a/tests/test_multiple_active_lora_adapters.py b/tests/test_multiple_active_lora_adapters.py
index 04d3ad6b279..97f36e74c79 100644
--- a/tests/test_multiple_active_lora_adapters.py
+++ b/tests/test_multiple_active_lora_adapters.py
@@ -113,3 +113,22 @@ def test_fast_linear_forward_decode_matches_peft(adapters):
got = fast_linear_forward(block.q_proj, X, out = out)
torch.testing.assert_close(got, block.q_proj(X), rtol = 2e-2, atol = 2e-2)
assert got.data_ptr() == out.data_ptr()
+
+
[email protected]("q_len", [1, 5])
+def test_fast_linear_forward_applies_dora_magnitude(q_len):
+ from peft import LoraConfig, get_peft_model
+ from unsloth.kernels import fast_linear_forward
+
+ torch.manual_seed(3407)
+ cfg = LoraConfig(
+ r = 4, lora_alpha = 8, target_modules = ["q_proj"], init_lora_weights = False, use_dora = True
+ )
+ block = get_peft_model(_Block(), cfg).to("cuda", torch.bfloat16).base_model.model
+ X = torch.randn(1, q_len, H, device = "cuda", dtype = torch.bfloat16)
+ with torch.no_grad():
+ # A trained magnitude no longer equals the row norms DoRA starts from.
+ block.q_proj.lora_magnitude_vector["default"].weight.mul_(1.5)
+ torch.testing.assert_close(
+ fast_linear_forward(block.q_proj, X), block.q_proj(X), rtol = 2e-2, atol = 2e-2
+ )
diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.py
index f98d6f1a07b..7dde169e53b 100644
--- a/unsloth/kernels/utils.py
+++ b/unsloth/kernels/utils.py
@@ -350,6 +350,19 @@ def _has_multiple_active_adapters(proj):
return not isinstance(adapters, str) and len(adapters) > 1
+def _has_active_dora_adapter(proj):
+ # DoRA rescales the output by lora_magnitude_vector, which the fast LoRA path never applies.
+ magnitude = getattr(proj, "lora_magnitude_vector", None)
+ if not magnitude or getattr(proj, "disable_adapters", True) or getattr(proj, "merged", False):
+ return False
+ adapters = getattr(proj, "active_adapters", None)
+ if adapters is None:
+ adapters = getattr(proj, "active_adapter", ())
+ if isinstance(adapters, str):
+ adapters = (adapters,)
+ return any(adapter in magnitude for adapter in adapters)
+
+
def has_mxfp4_base(*projs):
"""A packed MXFP4 base that cannot hand its bytes to the fused LoRA kernels (they would then hold a 16-bit
weight until backward): use PEFT. Bases with ``mxfp4_quant_state`` pass ``weight_packed`` + that state instead."""
@@ -1378,7 +1391,7 @@ def fast_linear_forward(
temp_lora = None,
out = None,
):
- if _has_multiple_active_adapters(proj):
+ if _has_multiple_active_adapters(proj) or _has_active_dora_adapter(proj):
result = proj(X)
return result if out is None else out.copy_(result)
W, W_quant, lora_A, lora_B, lora_S, bias = get_lora_parameters_bias(proj)