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
FP8 dequant: multiply per-tensor and rowwise scales in fp32 for fp16 output (#14677)
Daniel Han22f5633a2db0
diff --git a/tests/test_fp8_fp16_scale_rounding.py b/tests/test_fp8_fp16_scale_rounding.pynew file mode 100644index 00000000000..9636fc2e02a--- /dev/null+++ b/tests/test_fp8_fp16_scale_rounding.py@@ -0,0 +1,92 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""Per-tensor / rowwise FP8 dequant to fp16 rounds once: an fp16 scale underflows or overflows."""++import os++import pytest++torch = pytest.importorskip("torch")+pytest.importorskip("triton")++[email protected](scope = "module")+def F():+ os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")+ from unsloth.kernels import fp8+ return fp8+++def _q(value, shape = (2, 4)):+ return torch.full(shape, value).to(torch.float8_e4m3fn)+++def _oracle(q, s, dtype):+ return (q.double() * s.double()).to(dtype)++[email protected]("layout", ["tensor", "row", "row_t"])[email protected]("value, scale", [(448.0, 1e-8), (0.001953125, 1e5), (448.0, 1.234567e-4)])+def test_fp16_scalar_and_row_scales_round_once(F, layout, value, scale):+ q = _q(value)+ if layout == "tensor":+ s = torch.tensor(scale, dtype = torch.float32)+ x, ref_s = q, s+ elif layout == "row":+ s = torch.full((2, 1), scale, dtype = torch.float32)+ x, ref_s = q, s+ else:+ s = torch.full((2, 1), scale, dtype = torch.float32)+ x, ref_s = q.t(), s.view(1, 2)+ out = F.weight_dequant(x, s, torch.float16)+ ref = _oracle(x, ref_s, torch.float16)+ assert out.dtype == torch.float16+ assert torch.isfinite(ref).all() and (ref != 0).all()+ assert torch.equal(out, ref)+++def test_fp16_transposed_view_keeps_layout(F):+ torch.manual_seed(2)+ w = torch.randn(48, 32) * torch.linspace(1e-4, 1.0, 48)[:, None]+ s = (w.abs().amax(1, keepdim = True) / 448).float()+ q = (w / s).to(torch.float8_e4m3fn)+ out = F.weight_dequant(q.t(), s, torch.float16)+ assert out.shape == (32, 48) and out.stride() == q.t().stride()+ assert torch.equal(out, (q.double() * s.double()).half().t())+++def test_fp16_rowwise_small_amax_error(F):+ torch.manual_seed(0)+ w = torch.randn(64, 256) * 0.001 / 4+ w[:, 0] = 0.001+ s = (w.abs().amax(1, keepdim = True) / 448).float()+ q = (w / s).to(torch.float8_e4m3fn)+ ref = q.double() * s.double()+ out = F.weight_dequant(q, s, torch.float16)+ assert torch.equal(out, ref.half())++[email protected]("dtype", [torch.bfloat16, torch.float32, torch.float64])[email protected]("layout", ["tensor", "row", "row_t"])+def test_other_dtypes_keep_native_expression(F, dtype, layout):+ torch.manual_seed(1)+ w = torch.randn(32, 48) * torch.linspace(1e-4, 1.0, 32)[:, None]+ # fp64 must not pass through an fp32 scale: give it bits fp32 cannot hold.+ s = (w.abs().amax(1, keepdim = True) / 448).to(+ torch.float64 if dtype == torch.float64 else torch.float32+ )+ if dtype == torch.float64:+ s = s * (1 + 2**-40)+ q = (w / s).to(torch.float8_e4m3fn)+ if layout == "tensor":+ s = s.amax().reshape(())+ expected = q.to(dtype) * s.view(1, 1).to(dtype)+ out = F.weight_dequant(q, s, dtype)+ elif layout == "row":+ expected = q.to(dtype) * s.to(dtype)+ out = F.weight_dequant(q, s, dtype)+ else:+ expected = (q.to(dtype) * s.to(dtype)).t()+ out = F.weight_dequant(q.t().contiguous(), s, dtype)+ assert out.dtype == dtype+ assert torch.equal(out, expected)diff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.pyindex 55912b3c194..6254c6fbbc0 100644--- a/unsloth/kernels/fp8.py+++ b/unsloth/kernels/fp8.py@@ -184,6 +184,20 @@ def _has_fbgemm_rowwise():return False+def _scale_mul(x, s, dtype):+ # fp16: an fp16 scale goes subnormal below 6.1e-5 and overflows above 65504, zeroing or inf-ing+ # the weight, so multiply by the fp32 scale and round once. fp8 values are exact in fp16, and an+ # fp16 out= makes TensorIterator compute in fp32 per element without fp32 temporaries. Dynamo+ # refuses a strided out=; under compile Inductor fuses the fp32 expression instead (same bits).+ # Other dtypes keep their dtype-native expression.+ if dtype != torch.float16:+ return x.to(dtype) * s.to(dtype)+ if torch.compiler.is_compiling():+ return (x.to(torch.float32) * s.to(torch.float32)).to(dtype)+ x16 = x.to(dtype)+ return torch.mul(x16, s.to(torch.float32), out = torch.empty_like(x16))++def weight_dequant(x: torch.Tensor,s: torch.Tensor,@@ -194,14 +208,14 @@ def weight_dequant(return weight_dequant(x.t(), s, dtype).t()# Per-tensor scale: single value for entire weight matrixif s.numel() == 1:- return x.to(dtype) * s.view(1, 1).to(dtype)+ return _scale_mul(x, s.view(1, 1), dtype)# Row quantized weight: scale shape is (m, 1) or (n, 1)elif s.ndim == 2 and s.shape[1] == 1:if x.shape[0] == s.shape[0]:- y = x.to(dtype) * s.to(dtype)+ y = _scale_mul(x, s, dtype)elif x.shape[1] == s.shape[0]:# Sometimes called with the transpose of the weight.- y = x.t().to(dtype) * s.to(dtype)+ y = _scale_mul(x.t(), s, dtype)y = y.t()else:raise ValueError(f"Incompatible shapes {x.shape = }, {s.shape = }")