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.

Decode LoRA cast cache: refresh after fused optimizer steps (#15052)

Daniel Han5c38c961230d
diff --git a/tests/test_fast_lora_cast_cache.py b/tests/test_fast_lora_cast_cache.py
new file mode 100644
index 00000000000..af5e4a1adc0
--- /dev/null
+++ b/tests/test_fast_lora_cast_cache.py
@@ -0,0 +1,54 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+"""The decode LoRA cast cache must follow every optimizer, including fused ones that skip _version."""
+
+import pytest
+import torch
+
+from unsloth.kernels import utils as U
+
+
+def _adapters():
+ torch.manual_seed(0)
+ A = torch.nn.Parameter(torch.randn(8, 16))
+ B = torch.nn.Parameter(torch.randn(32, 8))
+ return A, B
+
+
+def _step(optimizer, params):
+ for p in params:
+ p.grad = torch.randn_like(p)
+ optimizer.step()
+
+
+ "make_optimizer",
+ [
+ pytest.param(lambda p: torch.optim.AdamW(p, lr = 0.1, fused = True), id = "adamw_fused"),
+ pytest.param(lambda p: torch.optim.AdamW(p, lr = 0.1, foreach = True), id = "adamw_foreach"),
+ pytest.param(lambda p: torch.optim.AdamW(p, lr = 0.1, foreach = False), id = "adamw_loop"),
+ pytest.param(lambda p: torch.optim.SGD(p, lr = 0.1), id = "sgd"),
+ ],
+)
+def test_cast_cache_follows_optimizer_steps(make_optimizer):
+ A, B = _adapters()
+ optimizer = make_optimizer([A, B])
+ A16, B16 = U._fast_lora_weights(A, B, torch.bfloat16)
+ assert torch.equal(A16, A.detach().to(torch.bfloat16))
+ _step(optimizer, [A, B])
+ A16, B16 = U._fast_lora_weights(A, B, torch.bfloat16)
+ assert torch.equal(A16, A.detach().to(torch.bfloat16))
+ assert torch.equal(B16, B.detach().to(torch.bfloat16))
+
+
+def test_cast_cache_hits_without_updates():
+ A, B = _adapters()
+ first = U._fast_lora_weights(A, B, torch.bfloat16)
+ second = U._fast_lora_weights(A, B, torch.bfloat16)
+ assert first[0] is second[0] and first[1] is second[1]
+
+
+def test_matching_dtype_skips_the_cache():
+ A, B = _adapters()
+ assert U._fast_lora_weights(A, B, torch.float32) == (A, B)
+ assert "_fast_lora" not in A.__dict__
diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.py
index 2badee81b67..94c812ac32b 100644
--- a/unsloth/kernels/utils.py
+++ b/unsloth/kernels/utils.py
@@ -1676,6 +1676,23 @@ def _rows_plans(quant_state):
return plans
+_OPTIMIZER_STEPS = 0
+
+
+def _count_optimizer_step(optimizer, args, kwargs):
+ global _OPTIMIZER_STEPS
+ _OPTIMIZER_STEPS += 1
+
+
+try:
+ # Fused optimizers (AdamW(fused = True), the transformers default on torch >= 2.8) update
+ # parameters without bumping _version, so the LoRA cast cache also keys on optimizer steps.
+ from torch.optim.optimizer import register_optimizer_step_post_hook
+ register_optimizer_step_post_hook(_count_optimizer_step)
+except Exception:
+ pass
+
+
def _fast_lora_weights(lora_A, lora_B, dtype):
if lora_A.dtype == dtype and lora_B.dtype == dtype:
return lora_A, lora_B
@@ -1684,7 +1701,14 @@ def _fast_lora_weights(lora_A, lora_B, dtype):
if lora_A.is_inference() or lora_B.is_inference():
key = (None, None, lora_A.data_ptr(), lora_B.data_ptr(), dtype)
else:
- key = (lora_A._version, lora_B._version, lora_A.data_ptr(), lora_B.data_ptr(), dtype)
+ key = (
+ _OPTIMIZER_STEPS,
+ lora_A._version,
+ lora_B._version,
+ lora_A.data_ptr(),
+ lora_B.data_ptr(),
+ dtype,
+ )
cache = getattr(lora_A, "_fast_lora", None)
if cache is None or cache[0] != key:
cache = (key, lora_A.to(dtype), lora_B.to(dtype))