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.

Dequantize FP8 weights in the activation dtype for fp16 LoRA (#14495)

Daniel Hanb2b9852c02a6
diff --git a/tests/test_fp8_fp16_lora_dtype.py b/tests/test_fp8_fp16_lora_dtype.py
new file mode 100644
index 00000000000..bdf3f220611
--- /dev/null
+++ b/tests/test_fp8_fp16_lora_dtype.py
@@ -0,0 +1,162 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team.
+"""fp16 LoRA on block-FP8: dequant follows the activation dtype (was bf16 -> `Half != BFloat16`)."""
+
+import pytest
+import torch
+
+pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason = "needs CUDA")
+
+BLOCK = 128
+HIDDEN, INTER, RANK, TOKENS = 256, 384, 8, 16
+
+
+def _fp8_weight(out_f, in_f, seed):
+ g = torch.Generator(device = "cuda").manual_seed(seed)
+ W = torch.randn(out_f, in_f, generator = g, device = "cuda") * 0.05
+ Wb = W.view(out_f // BLOCK, BLOCK, in_f // BLOCK, BLOCK)
+ s = Wb.abs().amax(dim = (1, 3)) / 448.0
+ q = (Wb / s[:, None, :, None]).view(out_f, in_f).to(torch.float8_e4m3fn)
+ return q.contiguous(), s.float().contiguous()
+
+
+def _exact(W, s):
+ return (W.float().view(W.shape[0] // BLOCK, BLOCK, -1, BLOCK) * s[:, None, :, None]).view(
+ W.shape
+ )
+
+
+def _lora(out_f, in_f, seed, dtype):
+ g = torch.Generator(device = "cuda").manual_seed(seed)
+ A = (torch.randn(RANK, in_f, generator = g, device = "cuda") * 0.05).to(dtype)
+ B = (torch.randn(out_f, RANK, generator = g, device = "cuda") * 0.05).to(dtype)
+ return A.requires_grad_(), B.requires_grad_()
+
+
[email protected]("dtype", [torch.float16, torch.bfloat16, torch.float32])
+def test_fast_dequantize_fp8_follows_dtype(dtype):
+ from unsloth.kernels.utils import fast_dequantize
+
+ W, s = _fp8_weight(INTER, HIDDEN, 0)
+ out = fast_dequantize(W, s, dtype = dtype)
+ assert out.dtype == dtype
+ assert torch.equal(out, _exact(W, s).to(dtype))
+ out_t = fast_dequantize(W.t(), s, dtype = dtype)
+ assert out_t.dtype == dtype and torch.equal(out_t, out.t())
+
+
+def test_fast_dequantize_fp8_default_stays_bf16():
+ from unsloth.kernels.utils import fast_dequantize
+
+ W, s = _fp8_weight(INTER, HIDDEN, 0)
+ a = fast_dequantize(W, s)
+ assert a.dtype == torch.bfloat16
+ assert torch.equal(a, fast_dequantize(W, s, dtype = torch.bfloat16))
+
+
+def _x(dtype):
+ g = torch.Generator(device = "cuda").manual_seed(99)
+ return (
+ (torch.randn(1, TOKENS, HIDDEN, generator = g, device = "cuda") * 0.5)
+ .to(dtype)
+ .requires_grad_()
+ )
+
+
+def _run_lora_w(dtype):
+ from unsloth.kernels import fast_lora
+
+ W, s = _fp8_weight(INTER, HIDDEN, 1)
+ A, B = _lora(INTER, HIDDEN, 2, dtype)
+ X = _x(dtype)
+ Y = fast_lora.LoRA_W.apply(X, W, s, A, B, 2.0)
+ Y.float().square().sum().backward()
+ return Y, X.grad, A.grad, B.grad, W, s, A, B, X
+
+
+def _run_mlp(dtype):
+ from unsloth.kernels import fast_lora
+ from unsloth.kernels.swiglu import swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel
+
+ gW, gs = _fp8_weight(INTER, HIDDEN, 3)
+ uW, us = _fp8_weight(INTER, HIDDEN, 4)
+ dW, ds = _fp8_weight(HIDDEN, INTER, 5)
+ gA, gB = _lora(INTER, HIDDEN, 6, dtype)
+ uA, uB = _lora(INTER, HIDDEN, 7, dtype)
+ dA, dB = _lora(HIDDEN, INTER, 8, dtype)
+ X = _x(dtype)
+ Y = fast_lora.LoRA_MLP.apply(
+ X, gW, gs, gA, gB, 2.0, uW, us, uA, uB, 2.0, dW, ds, dA, dB, 2.0,
+ swiglu_fg_kernel, swiglu_DWf_DW_dfg_kernel, False,
+ ) # fmt: skip
+ Y.float().square().sum().backward()
+ return Y, X.grad, gA.grad, uB.grad, dA.grad
+
+
+def _run_qkv(dtype):
+ from unsloth.kernels import fast_lora
+
+ Ws = [_fp8_weight(n, HIDDEN, 10 + i) for i, n in enumerate((HIDDEN, BLOCK, BLOCK))]
+ AB = [_lora(n, HIDDEN, 20 + i, dtype) for i, n in enumerate((HIDDEN, BLOCK, BLOCK))]
+ X = _x(dtype)
+ args = []
+ for (W, s), (A, B) in zip(Ws, AB):
+ args += [W, s, A, B, 2.0]
+ Q, K, V = fast_lora.LoRA_QKV.apply(X, *args, False)
+ (Q.float().square().sum() + K.float().square().sum() + V.float().square().sum()).backward()
+ return Q, K, V, X.grad, AB[0][0].grad, AB[2][1].grad
+
+
+def test_lora_w_fp16_fp8_backward():
+ Y, dX, dA, dB, W, s, A, B, _ = _run_lora_w(torch.float16)
+ assert Y.dtype == dX.dtype == torch.float16
+ Weff = _exact(W, s) + 2.0 * B.detach().float() @ A.detach().float()
+ # Forward quantizes X to FP8, so dY = 2 * Y from the real output.
+ torch.testing.assert_close(dX.float(), (2 * Y.detach().float()) @ Weff, rtol = 2e-2, atol = 2e-2)
+ assert torch.isfinite(dA).all() and torch.isfinite(dB).all()
+
+
+def test_lora_mlp_fp16_fp8_backward():
+ outs = _run_mlp(torch.float16)
+ assert outs[1].dtype == torch.float16
+ assert all(torch.isfinite(t).all() for t in outs)
+
+
+def test_lora_qkv_fp16_fp8_backward():
+ outs = _run_qkv(torch.float16)
+ assert outs[3].dtype == torch.float16
+ assert all(torch.isfinite(t).all() for t in outs)
+
+
[email protected]("runner", [_run_lora_w, _run_mlp, _run_qkv])
+def test_bf16_fp8_backward_matches_bf16_dequant(runner, monkeypatch):
+ # bf16 must stay bit-identical to the old no-dtype (bf16 default) path.
+ from unsloth.kernels import fast_lora, fp8
+
+ new = [
+ t.detach().clone()
+ for t in runner(torch.bfloat16)
+ if t.dtype in (torch.bfloat16, torch.float32)
+ ]
+ real = fast_lora.fast_dequantize
+
+ def old_fast_dequantize(
+ W,
+ q = None,
+ *a,
+ dtype = None,
+ **k,
+ ):
+ if W.dtype == torch.float8_e4m3fn:
+ return fp8.weight_dequant(W, q)
+ return real(W, q, *a, **k)
+
+ monkeypatch.setattr(fast_lora, "fast_dequantize", old_fast_dequantize)
+ old = [
+ t.detach().clone()
+ for t in runner(torch.bfloat16)
+ if t.dtype in (torch.bfloat16, torch.float32)
+ ]
+ assert len(new) == len(old)
+ for a, b in zip(new, old):
+ assert a.dtype == b.dtype and torch.equal(a, b)
diff --git a/unsloth/kernels/bnb_override.py b/unsloth/kernels/bnb_override.py
index 4c7c6e3e760..80f0d0a05ce 100644
--- a/unsloth/kernels/bnb_override.py
+++ b/unsloth/kernels/bnb_override.py
@@ -54,12 +54,12 @@ class _NF4Linear(torch.autograd.Function):
@staticmethod
def forward(ctx, x, weight, quant_state, bias):
ctx.unsloth_nf4 = (weight, quant_state)
- return F.linear(x, _U.fast_dequantize(weight, quant_state), bias)
+ return F.linear(x, _U.fast_dequantize(weight, quant_state, dtype = x.dtype), bias)
@staticmethod
def backward(ctx, dY):
weight, quant_state = ctx.unsloth_nf4
- W = _U.fast_dequantize(weight, quant_state)
+ W = _U.fast_dequantize(weight, quant_state, dtype = dY.dtype)
# bitsandbytes MatMul4Bit.backward: matmul(dY, dequantize_4bit(B).to(dY.dtype)).
return torch.matmul(dY, W.to(dY.dtype)), None, None, None
@@ -74,7 +74,7 @@ def _linear(x, weight, quant_state, bias):
if bias is not None:
out = out + bias
return out.reshape(*x.shape[:-1], N)
- return F.linear(x, _U.fast_dequantize(weight, quant_state), bias)
+ return F.linear(x, _U.fast_dequantize(weight, quant_state, dtype = x.dtype), bias)
def _bnb_ops_traceable():
diff --git a/unsloth/kernels/fast_lora.py b/unsloth/kernels/fast_lora.py
index daa2fb5839e..6fe2185b457 100644
--- a/unsloth/kernels/fast_lora.py
+++ b/unsloth/kernels/fast_lora.py
@@ -421,7 +421,7 @@ class LoRA_MLP(torch.autograd.Function):
if downW.dtype == torch.float8_e4m3fn:
# Dequantize like gate / up: matmul_lora would send the FP8 weight to fp8_linear, quantizing dY to FP8.
- downW, downW_quant = fast_dequantize(downW.t(), downW_quant), None
+ downW, downW_quant = fast_dequantize(downW.t(), downW_quant, dtype = dY.dtype), None
else:
downW = downW.t()
if down_mask is None:
@@ -481,13 +481,13 @@ class LoRA_MLP(torch.autograd.Function):
d_downBias = _lora_bias_grad(dY, downS) if down_has_bias else None
# dX = matmul_lora(df, upW.t(), ...) + matmul_lora(de, gateW.t(), ...), expanded below.
- upW = fast_dequantize(upW.t(), upW_quant)
+ upW = fast_dequantize(upW.t(), upW_quant, dtype = df.dtype)
# Eager only: AOT autograd rejects a backward mutating a forward input that requires grad.
dX = torch.matmul(df, upW.t(), out = X if ctx.inplace and not _is_compiling() else None)
del upW
_add_lora_dX(dX, up_dB, upA, upS, up_mask, up_p)
- gateW = fast_dequantize(gateW.t(), gateW_quant)
+ gateW = fast_dequantize(gateW.t(), gateW_quant, dtype = de.dtype)
addmm_(dX, de, gateW.t())
del gateW
_add_lora_dX(dX, gate_dB, gateA, gateS, gate_mask, gate_p)
@@ -852,17 +852,17 @@ class LoRA_QKV(torch.autograd.Function):
d_VBias = _lora_bias_grad(dV, VS) if V_has_bias else None
# Combine the per-projection derivatives into dX.
- QW = fast_dequantize(QW.t(), QW_quant)
+ QW = fast_dequantize(QW.t(), QW_quant, dtype = dQ.dtype)
dX = torch.matmul(dQ, QW.t(), out = X if ctx.inplace and not _is_compiling() else None)
del QW
_add_lora_dX(dX, q_dB, QA, QS, Q_mask, Q_p)
- KW = fast_dequantize(KW.t(), KW_quant)
+ KW = fast_dequantize(KW.t(), KW_quant, dtype = dK.dtype)
addmm_(dX, dK, KW.t())
del KW
_add_lora_dX(dX, k_dB, KA, KS, K_mask, K_p)
- VW = fast_dequantize(VW.t(), VW_quant)
+ VW = fast_dequantize(VW.t(), VW_quant, dtype = dV.dtype)
addmm_(dX, dV, VW.t())
del VW
_add_lora_dX(dX, v_dB, VA, VS, V_mask, V_p)
@@ -1025,7 +1025,7 @@ class LoRA_W(torch.autograd.Function):
del Xd
d_bias = _lora_bias_grad(dY, S) if ctx.has_bias else None
- W = fast_dequantize(W.t(), W_quant)
+ W = fast_dequantize(W.t(), W_quant, dtype = dY.dtype)
dX = dY @ W.t()
del W
_add_lora_dX(dX, y_dB, A, S, mask, ctx.dropout_p)
diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.py
index d9fa8a8f086..bebeb09eec1 100644
--- a/unsloth/kernels/utils.py
+++ b/unsloth/kernels/utils.py
@@ -695,6 +695,7 @@ if DEVICE_TYPE == "xpu" and HAS_XPU_STREAM:
quant_state = None,
out = None,
use_global_buffer = False,
+ dtype = None,
):
# TODO: After adding XPU BNB support, check this function
if isinstance(W, Float8Tensor):
@@ -702,7 +703,7 @@ if DEVICE_TYPE == "xpu" and HAS_XPU_STREAM:
if quant_state is None:
return W
if W.dtype == torch.float8_e4m3fn:
- return weight_dequant(W, quant_state)
+ return weight_dequant(W, quant_state, dtype or torch.bfloat16)
if type(quant_state) is NVFP4QuantState:
return nvfp4_dequantize(
W, quant_state.scale, quant_state.global_scale, quant_state.dtype
@@ -872,13 +873,14 @@ elif DEVICE_TYPE in ("cuda", "hip") and HAS_CUDA_STREAM:
quant_state = None,
out = None,
use_global_buffer = False,
+ dtype = None,
):
if isinstance(W, Float8Tensor):
return W.dequantize()
if quant_state is None:
return W
if W.dtype == torch.float8_e4m3fn:
- return weight_dequant(W, quant_state)
+ return weight_dequant(W, quant_state, dtype or torch.bfloat16)
if type(quant_state) is NVFP4QuantState:
return nvfp4_dequantize(
W, quant_state.scale, quant_state.global_scale, quant_state.dtype
@@ -979,13 +981,14 @@ else:
quant_state = None,
out = None,
use_global_buffer = False,
+ dtype = None,
):
if isinstance(W, Float8Tensor):
return W.dequantize()
if quant_state is None:
return W
if W.dtype == torch.float8_e4m3fn:
- return weight_dequant(W, quant_state)
+ return weight_dequant(W, quant_state, dtype or torch.bfloat16)
if type(quant_state) is NVFP4QuantState:
return nvfp4_dequantize(
W, quant_state.scale, quant_state.global_scale, quant_state.dtype
@@ -1171,7 +1174,7 @@ elif DEVICE_TYPE in ("cuda", "hip") and HAS_CUDA_STREAM:
)
if shape[1] % blocksize != 0:
# The gemv kernels assume each weight row starts a new quantization block.
- return torch_matmul(X, fast_dequantize(W, quant_state).t(), out = out)
+ return torch_matmul(X, fast_dequantize(W, quant_state, dtype = X.dtype).t(), out = out)
device = W.device
CUDA_STREAM = c_void_p(_gpu_getCurrentRawStream(device.index))
@@ -1283,7 +1286,7 @@ elif DEVICE_TYPE in ("cuda", "hip") and HAS_CUDA_STREAM:
)
if shape[1] % blocksize != 0:
# The gemv kernels assume each weight row starts a new quantization block.
- return torch_matmul(X, fast_dequantize(W, quant_state).t(), out = out)
+ return torch_matmul(X, fast_dequantize(W, quant_state, dtype = X.dtype).t(), out = out)
try:
if (
eager
@@ -1432,14 +1435,18 @@ def fast_dequantize(
quant_state = None,
out = None,
use_global_buffer = False,
+ dtype = None,
):
+ # dtype only steers the FP8 dequant (default bf16); every other format keeps its own dtype.
quant_type = type(quant_state)
if quant_type is Int4QuantState:
return _int4_dequantize_weight(W, quant_state)
# A packed MXFP4 base hands in weight_packed (or its .t()) with a decoder as the quant state.
if getattr(quant_type, "_unsloth_packed_weight_state", False):
return quant_state.dequantize(W)
- return _fast_dequantize_bnb(W, quant_state, out = out, use_global_buffer = use_global_buffer)
+ return _fast_dequantize_bnb(
+ W, quant_state, out = out, use_global_buffer = use_global_buffer, dtype = dtype
+ )
def fast_gemv(
@@ -1702,7 +1709,7 @@ def fast_linear_forward(
):
out = bnb.matmul_4bit(X, W.t(), quant_state = W_quant, out = out)
else:
- W = fast_dequantize(W.t(), W_quant, use_global_buffer = True)
+ W = fast_dequantize(W.t(), W_quant, use_global_buffer = True, dtype = X.dtype)
out = torch_matmul(X, W, out = out)
if lora_A is not None:
@@ -1793,7 +1800,7 @@ def matmul_lora(
elif _is_packed_state(W_quant):
out = W_quant.matmul(X, W, out = out)
else:
- W = fast_dequantize(W, W_quant, use_global_buffer = use_global_buffer)
+ W = fast_dequantize(W, W_quant, use_global_buffer = use_global_buffer, dtype = dtype)
out = torch_matmul(X, W.t(), out = out)
if W_quant is not None:
del W
diff --git a/unsloth/save.py b/unsloth/save.py
index 6145797cb31..9f6f23a503e 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -674,11 +674,19 @@ def _free_cached_model(model):
delete_strategy.execute()
-def _merge_lora(layer, name):
+def _merge_lora(
+ layer,
+ name,
+ dtype = None,
+):
bias = getattr(layer, "bias", None)
if isinstance(layer, (Bnb_Linear4bit, Peft_Linear4bit, Peft_Linear)):
W, quant_state, A, B, s, bias = get_lora_parameters_bias(layer)
- if quant_state is not None:
+ if quant_state is not None and W.dtype == torch.float8_e4m3fn:
+ # FP8 quant_state is the fp32 scale, not the model dtype: dequant in fp32, save in model dtype.
+ W = fast_dequantize(W, quant_state, dtype = torch.float32)
+ dtype = dtype if isinstance(dtype, torch.dtype) else torch.bfloat16
+ elif quant_state is not None:
dtype = quant_state.dtype if type(quant_state) is not list else quant_state[2]
W = fast_dequantize(W, quant_state)
else:
@@ -1516,7 +1524,7 @@ def unsloth_save_model(
for item in LLAMA_WEIGHTS:
proj = eval(f"layer.{item}")
name = f"model.layers.{j}.{item}.weight"
- W, bias = _merge_lora(proj, name)
+ W, bias = _merge_lora(proj, name, torch_dtype)
if bias is not None:
state_dict[f"model.layers.{j}.{item}.bias"] = bias