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.

Keep packed INT4 layers off the fused inference kernel in train mode (#12349)

Daniel Han9f2f65fa5a73
diff --git a/tests/test_compressed_tensors_int4.py b/tests/test_compressed_tensors_int4.py
index 2d94fa4ddb8..1bbf3d74cbb 100644
--- a/tests/test_compressed_tensors_int4.py
+++ b/tests/test_compressed_tensors_int4.py
@@ -643,3 +643,33 @@ def test_training_single_row_forward_uses_the_backward_weights():
x = torch.randn(1, 512, device = "cuda", dtype = torch.bfloat16)
want = x @ int4_dequantize(W, qs, torch.bfloat16).t()
assert torch.equal(int4_matmul(x, W, qs, fast = False), want)
+
+
+@needs_gpu
+@needs_ct
+@needs_sm80
+def test_train_mode_no_grad_forward_skips_the_fused_kernel_cache():
+ # Gradient checkpointing runs its first forward under no_grad in train mode: it must use the same exact
+ # dequantize + matmul as the recompute, and must not build the fused kernel's per-layer scale cache.
+ from unsloth.kernels.int4_packed import int4_dequantize
+
+ lin, _, _ = _repacked_linear()
+ qs = lin.quant_state
+ x = torch.randn(2, 1024, device = "cuda", dtype = torch.bfloat16)
+ want = x @ int4_dequantize(lin._parameters["weight_packed"], qs, torch.bfloat16).t()
+
+ lin.train()
+ with torch.no_grad():
+ y = lin(x)
+ # The fast LoRA kernels call int4_matmul directly (default fast = True) inside their autograd forward.
+ from unsloth.kernels.utils import matmul_lora
+ z = matmul_lora(x, lin.weight, lin.quant_state, None, None, None)
+ assert qs._fast is None and torch.equal(y, want) and torch.equal(z, want)
+
+ # Eval keeps the fused kernel (and its cache); going back to training frees it.
+ lin.eval()
+ with torch.no_grad():
+ matmul_lora(x, lin.weight, lin.quant_state, None, None, None)
+ assert qs._fast is not None
+ lin.train()
+ assert qs._fast is None
diff --git a/unsloth/kernels/int4_packed.py b/unsloth/kernels/int4_packed.py
index 8363080164d..308b876da87 100644
--- a/unsloth/kernels/int4_packed.py
+++ b/unsloth/kernels/int4_packed.py
@@ -55,6 +55,7 @@ class Int4QuantState:
"_launchers",
"layout",
"_fast",
+ "training",
)
def __init__(self, scale, zero_point, g_idx, shape, bits, group_size, dtype):
@@ -69,6 +70,8 @@ class Int4QuantState:
self._launchers = None
self.layout = None
self._fast = None
+ # Owning module in train mode: every caller (incl. the fast LoRA kernels) skips the fused kernel.
+ self.training = False
@triton.jit
@@ -724,6 +727,7 @@ def int4_matmul(
fast = True,
):
"""``x @ W.T`` for packed ``W``; ``x`` is ``[..., K]``. ``fast = False`` (training) keeps the exact dequantize + matmul."""
+ fast = fast and not qs.training
shape = x.shape
x2 = x.reshape(-1, shape[-1])
M = x2.shape[0]
diff --git a/unsloth/models/compressed_tensors_int4.py b/unsloth/models/compressed_tensors_int4.py
index d0924625a12..9100785da03 100644
--- a/unsloth/models/compressed_tensors_int4.py
+++ b/unsloth/models/compressed_tensors_int4.py
@@ -128,6 +128,7 @@ class Int4PackedLinear(nn.Linear):
self.__dict__.get("_int4_dtype") or torch.bfloat16,
)
qs.layout = self.__dict__.get("_int4_layout")
+ qs.training = self.training
self.__dict__["_int4_quant_state"] = qs
packed.quant_state = qs
elif getattr(packed, "quant_state", None) is not qs:
@@ -152,9 +153,21 @@ class Int4PackedLinear(nn.Linear):
from ..kernels.int4_packed import int4_matmul
qs = self.quant_state
- out = int4_matmul(x.to(qs.dtype), self._parameters["weight_packed"], qs)
+ # Train mode (incl. GC's no-grad first pass): exact dequant + matmul, same math as the recompute.
+ out = int4_matmul(
+ x.to(qs.dtype), self._parameters["weight_packed"], qs, fast = not self.training
+ )
return out if bias is None else out + bias.to(out.dtype)
+ def train(self, mode = True):
+ qs = self.__dict__.get("_int4_quant_state")
+ if qs is not None:
+ qs.training = bool(mode)
+ if mode:
+ # Free the fused kernel's per-layer scale cache (1/8 of the packed weight); training never uses it.
+ qs._fast = None
+ return super().train(mode)
+
def dequantize_weight(self, dtype = None):
from ..kernels.int4_packed import int4_dequantize
qs = self.quant_state