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 block dequant on ROCm: round fp32 to fp16 with integer ops (#14992)
Daniel Han3922fa9927e8
diff --git a/tests/test_fp8_exact_f16_round.py b/tests/test_fp8_exact_f16_round.pynew file mode 100644index 00000000000..f2c0b6dd465--- /dev/null+++ b/tests/test_fp8_exact_f16_round.py@@ -0,0 +1,180 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+"""FP8 block dequant to fp16: the integer-rounding path (ROCm default, UNSLOTH_FP8_EXACT_F16_ROUND=1+elsewhere) must match the torch loop bit for bit."""++import numpy as np+import pytest+import torch++from unsloth.kernels import fp8++CUDA = torch.cuda.is_available()+HIP = torch.version.hip is not None+needs_cuda = pytest.mark.skipif(not CUDA, reason = "needs a GPU")+BLOCK = 16+++def _data(device):+ # Every e4m3fn byte per 16x16 block; scales 1e-4..1e-2 (rounding ties) and 2^-40..2^10 (subnormal / overflow).+ g = torch.Generator(device = "cpu").manual_seed(0)+ rows, cols = 256, 128+ w = torch.arange(256, dtype = torch.uint8).view(16, 16).repeat(rows, cols)+ s = torch.rand(rows, cols, generator = g, dtype = torch.float32) * 1e-2 + 1e-4+ wide = torch.rand(rows // 4, cols, generator = g, dtype = torch.float64) + 1.0+ wide = wide * 2.0 ** torch.randint(-40, 11, (rows // 4, cols), generator = g).double()+ s[: rows // 4] = wide.float()+ return w.view(torch.float8_e4m3fn).to(device), s.to(device)+++def _same_bits(a, b):+ nan = torch.isnan(a)+ assert torch.equal(nan, torch.isnan(b))+ ai = a.masked_fill(nan, 0).view(torch.int16)+ bi = b.masked_fill(nan, 0).view(torch.int16)+ bad = int((ai != bi).sum())+ assert bad == 0, f"{bad} of {ai.numel()} differ"+++def test_data_has_double_rounding_ties():+ # Non-vacuity: some products round differently from exact -> fp16 than from fp32 -> fp16.+ w, s = _data("cpu")+ p = (w.double() * s.double().repeat_interleave(BLOCK, 0).repeat_interleave(BLOCK, 1)).numpy()+ once, twice = (+ p.astype(np.float16).view(np.int16),+ p.astype(np.float32).astype(np.float16).view(np.int16),+ )+ assert int((once != twice).sum()) > 50+++def _rounding_inputs():+ # Every fp32 exponent x mantissas at the fp16 rounding point (halves, +-1, odd / even), both signs.+ low = torch.tensor(+ [0, 1, 0xFFF, 0x1000, 0x1001, 0x1FFF, 0x2000, 0x3000, 0x7FFFFF, 0x7FE000, 0x7FF000],+ dtype = torch.int64,+ )+ exps = torch.arange(256, dtype = torch.int64)+ bits = (exps[:, None] << 23 | low[None, :]).flatten()+ g = torch.Generator(device = "cpu").manual_seed(0)+ bits = torch.cat([bits, torch.randint(0, 1 << 31, (1 << 16,), generator = g)])+ bits = torch.cat([bits, bits | (1 << 31)])+ return bits.to(torch.int32).view(torch.float32)+++@needs_cuda+def test_f32_to_f16_rne_matches_torch_cast():+ import triton+ import triton.language as tl++ @triton.jit+ def _round(x_ptr, y_ptr, n, BLOCK: tl.constexpr):+ offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)+ mask = offs < n+ tl.store(y_ptr + offs, fp8._f32_to_f16_rne(tl.load(x_ptr + offs, mask = mask)), mask = mask)++ x = _rounding_inputs().cuda()+ y = torch.empty_like(x, dtype = torch.float16)+ _round[(triton.cdiv(x.numel(), 1024),)](x, y, x.numel(), BLOCK = 1024, enable_fp_fusion = True)+ _same_bits(y, x.half())+++@needs_cuda[email protected]("exact", ["1", "0"])[email protected]("kernel", ["bytes", "fp8e4nv"])+def test_dequant_kernels_match_torch_loop_fp16(monkeypatch, kernel, exact):+ if exact == "0" and HIP:+ pytest.skip("the plain fp16 cast is the one ROCm Triton fuses into v_fma_mixlo_f16")+ monkeypatch.setenv("UNSLOTH_FP8_EXACT_F16_ROUND", exact)+ w, s = _data("cuda")+ ref = fp8._torch_blockwise_dequant(w, s, [BLOCK, BLOCK], torch.float16)+ if kernel == "bytes":+ out = fp8._e4m3fn_bytes_dequant(w, s, BLOCK, BLOCK, torch.float16)+ else:+ fp8._fp8_device_lacks_kernel.cache_clear()+ if fp8._fp8_kernel_unsupported(w):+ pytest.skip("no fp8e4nv on this device")+ out = fp8.weight_dequant_block(w, s, block_size = BLOCK, dtype = torch.float16)+ _same_bits(out, ref)+++@needs_cuda[email protected]("dtype", [torch.bfloat16, torch.float32])+def test_other_dtypes_untouched(monkeypatch, dtype):+ monkeypatch.setenv("UNSLOTH_FP8_EXACT_F16_ROUND", "1")+ assert fp8._fp8_exact_f16_round(dtype) is False+ w, s = _data("cuda")+ _same_bits(+ fp8._e4m3fn_bytes_dequant(w, s, BLOCK, BLOCK, dtype),+ fp8._torch_blockwise_dequant(w, s, [BLOCK, BLOCK], dtype),+ )+++def test_exact_round_is_the_rocm_fp16_default(monkeypatch):+ monkeypatch.delenv("UNSLOTH_FP8_EXACT_F16_ROUND", raising = False)+ monkeypatch.setattr(fp8, "_FP8_EXACT_F16_ROUND", True)+ assert fp8._fp8_exact_f16_round(torch.float16) is True+ assert fp8._fp8_exact_f16_round(torch.bfloat16) is False+ monkeypatch.setattr(fp8, "_FP8_EXACT_F16_ROUND", False)+ assert fp8._fp8_exact_f16_round(torch.float16) is False+ monkeypatch.setenv("UNSLOTH_FP8_EXACT_F16_ROUND", "1")+ assert fp8._fp8_exact_f16_round(torch.float16) is True+ monkeypatch.setattr(fp8, "_FP8_EXACT_F16_ROUND", True)+ monkeypatch.setenv("UNSLOTH_FP8_EXACT_F16_ROUND", "0")+ assert fp8._fp8_exact_f16_round(torch.float16) is False+++def test_hip_codegen_has_no_fma_mix():+ # Offline: compile both kernels for gfx1151; the exact path must not round through an f16-output+ # mix op (v_fma_mixlo/hi_f16 with a +0 addend). v_fma_mix_f32 (f16 operand, -0 addend) is a plain fmul.+ triton = pytest.importorskip("triton")+ try:+ import triton.backends.amd # noqa: F401+ from triton.backends.compiler import GPUTarget+ from triton.compiler import ASTSource+ except Exception:+ pytest.skip("Triton built without the AMD backend")+ target = GPUTarget("hip", "gfx1151", 32)+ cases = {+ "weight_dequant_kernel": (+ fp8.weight_dequant_kernel,+ {"x_ptr": "*fp8e4nv", "s_ptr": "*fp32", "y_ptr": "*fp16", "M": "i32", "N": "i32"},+ {"BLOCK_SIZE": 128},+ ),+ "_e4m3fn_bytes_dequant_kernel": (+ fp8._e4m3fn_bytes_dequant_kernel,+ {+ "x_ptr": "*u8",+ "s_ptr": "*fp32",+ "y_ptr": "*fp16",+ "M": "i32",+ "N": "i32",+ "stride_xm": "i32",+ "stride_xn": "i32",+ "stride_sm": "i32",+ "stride_sn": "i32",+ },+ {+ "BLOCK_M_Q": 128,+ "BLOCK_N_Q": 128,+ "BLOCK_R": 8,+ "BLOCK_C": 512,+ "LONG_INDEXING": False,+ },+ ),+ }+ for name, (fn, sig, consts) in cases.items():+ found = {}+ for exact in (False, True):+ c = {**consts, "EXACT_F16": exact}+ try:+ k = triton.compile(+ ASTSource(+ fn = fn, signature = {**sig, **{x: "constexpr" for x in c}}, constexprs = c+ ),+ target = target,+ )+ except Exception as e: # noqa: BLE001+ pytest.skip(f"offline HIP compile unavailable: {type(e).__name__}: {e}"[:200])+ asm = k.asm["amdgcn"]+ found[exact] = "v_fma_mixlo_f16" in asm or "v_fma_mixhi_f16" in asm+ assert found[True] is False, namediff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.pyindex 31f7b9fee6f..dca43f5d4e5 100644--- a/unsloth/kernels/fp8.py+++ b/unsloth/kernels/fp8.py@@ -125,8 +125,48 @@ except:)+# ROCm Triton fuses fp32 multiply + fp16 cast into v_fma_mixlo_f16, which drops -0.0 and rounds+# differently from the torch loop, so the dequant kernels round to fp16 with integer ops there.+_FP8_EXACT_F16_ROUND = torch.version.hip is not None+++def _fp8_exact_f16_round(dtype):+ flag = os.environ.get("UNSLOTH_FP8_EXACT_F16_ROUND", "")+ on = _FP8_EXACT_F16_ROUND if flag == "" else flag == "1"+ return on and dtype == torch.float16++@triton.jit-def weight_dequant_kernel(x_ptr, s_ptr, y_ptr, M, N, BLOCK_SIZE: tl.constexpr):+def _f32_to_f16_rne(x):+ # IEEE fp32 -> fp16, round to nearest even, subnormals kept, sign of zero kept, NaN quietened.+ u = x.to(tl.int32, bitcast = True)+ sign = (u >> 16) & 0x8000+ a = u & 0x7FFFFFFF+ c = tl.minimum(a, 0x477FF000)+ normal = (c + 0xFFF + ((c >> 13) & 1) - 0x38000000) >> 13+ # Below 2^-14, in units of 2^-24; clamped so normal lanes never shift by a negative count.+ shift = tl.minimum(tl.maximum(126 - (a >> 23), 1), 31)+ m = (a & 0x7FFFFF) | 0x800000+ q = m >> shift+ rem = m - (q << shift)+ half = 1 << (shift - 1)+ q = q + ((rem > half) | ((rem == half) & ((q & 1) == 1))).to(tl.int32)+ h = tl.where(a < 0x38800000, q, normal)+ h = tl.where(a >= 0x477FF000, 0x7C00, h)+ h = tl.where(a > 0x7F800000, 0x7E00 | ((a >> 13) & 0x3FF), h)+ return (h | sign).to(tl.uint16).to(tl.float16, bitcast = True)+++def weight_dequant_kernel(+ x_ptr,+ s_ptr,+ y_ptr,+ M,+ N,+ BLOCK_SIZE: tl.constexpr,+ EXACT_F16: tl.constexpr = False,+):pid_m = tl.program_id(axis = 0)pid_n = tl.program_id(axis = 1)n = tl.cdiv(N, BLOCK_SIZE)@@ -138,6 +178,8 @@ def weight_dequant_kernel(x_ptr, s_ptr, y_ptr, M, N, BLOCK_SIZE: tl.constexpr):x = tl.load(x_ptr + offs, mask = mask).to(tl.float32)s = tl.load(s_ptr + pid_m * n + pid_n)y = x * s+ if EXACT_F16:+ y = _f32_to_f16_rne(y)tl.store(y_ptr + offs, y, mask = mask)@@ -165,7 +207,16 @@ def weight_dequant_block(triton.cdiv(N, meta["BLOCK_SIZE"]),)with _fp8_triton_device_context(x):- weight_dequant_kernel[grid](x, s, y, M, N, BLOCK_SIZE = block_size, enable_fp_fusion = True)+ weight_dequant_kernel[grid](+ x,+ s,+ y,+ M,+ N,+ BLOCK_SIZE = block_size,+ EXACT_F16 = _fp8_exact_f16_round(dtype),+ enable_fp_fusion = True,+ )return y@@ -1328,6 +1379,7 @@ def _e4m3fn_bytes_dequant_kernel(BLOCK_R: tl.constexpr,BLOCK_C: tl.constexpr,LONG_INDEXING: tl.constexpr,+ EXACT_F16: tl.constexpr = False,):pid_r = tl.program_id(0)pid_c = tl.program_id(1)@@ -1346,6 +1398,8 @@ def _e4m3fn_bytes_dequant_kernel().to(tl.float32)# One fp32 multiply then one round to the output dtype, as the torch fallback does.y = _e4m3fn_byte_to_float(b.to(tl.int32)) * s+ if EXACT_F16:+ y = _f32_to_f16_rne(y)tl.store(y_ptr + r[:, None] * N + c[None, :], y.to(y_ptr.dtype.element_ty), mask = mask)@@ -1426,6 +1480,7 @@ def _e4m3fn_bytes_dequant(BLOCK_R = BLOCK_R,BLOCK_C = BLOCK_C,LONG_INDEXING = long_indexing(x, weight_scale, out),+ EXACT_F16 = _fp8_exact_f16_round(dtype),enable_fp_fusion = True,num_warps = num_warps,)