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
4-bit decode: no recompile from the eager setup, one output dtype under autocast, refresh the cached LoRA cast (#14754)
Daniel Han550324684988
diff --git a/tests/test_bnb_integration_compile.py b/tests/test_bnb_integration_compile.pyindex 542f02a067a..d503573b454 100644--- a/tests/test_bnb_integration_compile.py+++ b/tests/test_bnb_integration_compile.py@@ -494,6 +494,82 @@ def test_fast_linear_forward_cold_compile_fullgraph(nf4_kernels, monkeypatch, bs_assert_compiled_matches(compiled, eager, backend = "aot_eager")+def test_fast_linear_forward_eager_setup_does_not_recompile(nf4_kernels, monkeypatch):+ monkeypatch.setattr(U, "_BNB_GEMM_4BIT", None)+ monkeypatch.setattr(U, "_BNB_GEMM_4BIT_DEVICE", {})+ _, block = _lora_block(dtype = torch.float16)+ fn = lambda x: U.fast_linear_forward(block.o_proj, x)+ X = torch.randn(8, 1, 256, dtype = torch.float16, device = DEVICE)+ torch._dynamo.reset()+ from torch._dynamo.testing import CompileCounter++ counter = CompileCounter()+ compiled = torch.compile(fn, backend = counter)+ with torch.no_grad():+ first = compiled(X)+ fn(X)+ again = compiled(X)+ torch._dynamo.reset()+ assert U._BNB_GEMM_4BIT is not None+ assert counter.frame_count == 1, counter.frame_count+ torch.testing.assert_close(first, again, rtol = 0, atol = 0)+++def test_fast_linear_forward_sees_lora_updates(nf4_kernels):+ _, block = _lora_block(dtype = torch.float16)+ proj = block.o_proj+ X = torch.randn(8, 1, 256, dtype = torch.float16, device = DEVICE)+ lora_B = proj.lora_B["default"].weight+ assert lora_B.dtype == torch.float32+ with torch.no_grad():+ U.fast_linear_forward(proj, X)+ lora_B.add_(0.5)+ after = U.fast_linear_forward(proj, X)+ for name in ("lora_A", "lora_B"):+ getattr(proj, name)["default"].weight.__dict__.pop("_fast_lora", None)+ fresh = U.fast_linear_forward(proj, X)+ torch.testing.assert_close(after, fresh, rtol = 0, atol = 0)++[email protected]("bnb_gemm", [True, False])+def test_fast_linear_forward_lora_under_a_different_autocast_dtype(nf4_kernels, monkeypatch, bnb_gemm):+ # fp16 activations under bf16 autocast: every base path must hand the LoRA update X.dtype.+ if not torch.cuda.is_bf16_supported():+ pytest.skip("needs bf16")+ monkeypatch.setattr(U, "_TRITON_GEMV_EAGER", False)+ monkeypatch.setattr(U, "_BNB_GEMM_4BIT", bnb_gemm)+ calls = []+ if bnb_gemm:+ monkeypatch.setattr(U, "_BNB_GEMM_4BIT_DTYPES", (torch.float16, torch.bfloat16))+ monkeypatch.setattr(U, "_BNB_GEMM_4BIT_DEVICE", {})+ monkeypatch.setattr(U, "_BNB_GEMM_4BIT_ARCHS", {torch.cuda.get_device_capability()})+ matmul_4bit = U.bnb.matmul_4bit+ monkeypatch.setattr(U.bnb, "matmul_4bit", lambda *a, **k: calls.append(1) or matmul_4bit(*a, **k))+ _, block = _lora_block(dtype = torch.float16)+ proj = block.o_proj+ X = torch.randn(4, 1, 256, dtype = torch.float16, device = DEVICE)+ with torch.no_grad():+ expected = U.fast_linear_forward(proj, X)+ with torch.autocast("cuda", dtype = torch.bfloat16):+ got = U.fast_linear_forward(proj, X)+ assert len(calls) == (2 if bnb_gemm else 0)+ assert got.dtype == torch.float16+ torch.testing.assert_close(got, expected, rtol = 2e-2, atol = 2e-2)+++def test_fast_linear_forward_lora_cast_with_inference_tensors(nf4_kernels):+ # Inference tensors have no version counter; the cast cache must not read one.+ with torch.inference_mode():+ _, block = _lora_block(dtype = torch.float16)+ proj = block.o_proj+ assert proj.lora_A["default"].weight.is_inference()+ X = torch.randn(4, 1, 256, dtype = torch.float16, device = DEVICE)+ with torch.no_grad():+ first = U.fast_linear_forward(proj, X)+ again = U.fast_linear_forward(proj, X)+ torch.testing.assert_close(first, again, rtol = 0, atol = 0)++def test_eager_gemv_gate_off_takes_bitsandbytes(monkeypatch):"""Where the Triton GEMV is not the eager choice (HIP before Triton 3.6, orUNSLOTH_TRITON_GEMV_EAGER=0), eager decode takes bitsandbytes' GEMV, on the live stream.diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.pyindex 93d18c01258..ff6eaed1aff 100644--- a/unsloth/kernels/utils.py+++ b/unsloth/kernels/utils.py@@ -1657,6 +1657,22 @@ def _rows_plans(quant_state):return plans+def _fast_lora_weights(lora_A, lora_B, dtype):+ if lora_A.dtype == dtype and lora_B.dtype == dtype:+ return lora_A, lora_B+ # Keyed on _version: adapters keep training between decodes (GRPO). Inference tensors have no+ # version counter (and cannot change outside inference mode), so they key on storage alone.+ 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)+ 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))+ lora_A._fast_lora = cache+ return cache[1], cache[2]++def fast_linear_forward(proj,X,@@ -1707,7 +1723,9 @@ def fast_linear_forward():out = rowselif (- _BNB_GEMM_4BIT is not False+ # _is_compiling() first: reading the lazy global while tracing guards on it and recompiles later.+ not _is_compiling()+ and _BNB_GEMM_4BIT is not Falseand bsz <= _BNB_GEMM_4BIT_MAX_ROWSand _bnb_gemm_4bit_ok(X, W, W_quant)):@@ -1716,22 +1734,33 @@ def fast_linear_forward(W = fast_dequantize(W.t(), W_quant, use_global_buffer = True, dtype = X.dtype)out = torch_matmul(X, W, out = out)+ if out.dtype != X.dtype:+ # torch.matmul under a different autocast dtype returns that dtype; the LoRA update, decode+ # buffers and every other branch here work in X.dtype.+ out = out.to(X.dtype)+if lora_A is not None:out_dim = out.shape[2]dtype = X.dtype- if not hasattr(lora_A, "_fast_lora"):- lora_A._fast_lora = lora_A.to(dtype)- lora_B._fast_lora = lora_B.to(dtype)+ if _is_compiling():+ A, B = lora_A.to(dtype), lora_B.to(dtype)+ else:+ A, B = _fast_lora_weights(lora_A, lora_B, dtype)if bsz == 1:out = out.view(out_dim)- temp_lora = torch_mv(lora_A._fast_lora, X.ravel(), out = temp_lora)- out.addmv_(lora_B._fast_lora, temp_lora, alpha = lora_S)+ temp_lora = torch_mv(A, X.ravel(), out = temp_lora)+ # Without out=, mv / mm follow a different autocast dtype; the in-place update does not.+ if temp_lora.dtype != dtype:+ temp_lora = temp_lora.to(dtype)+ out.addmv_(B, temp_lora, alpha = lora_S)else:out = out.view(bsz, out_dim)- temp_lora = torch_mm(X.view(bsz, in_dim), lora_A._fast_lora.t(), out = temp_lora)- out.addmm_(temp_lora, lora_B._fast_lora.t(), alpha = lora_S)+ temp_lora = torch_mm(X.view(bsz, in_dim), A.t(), out = temp_lora)+ if temp_lora.dtype != dtype:+ temp_lora = temp_lora.to(dtype)+ out.addmm_(temp_lora, B.t(), alpha = lora_S)out = out.view(bsz, 1, out_dim)if bias is not None: