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: skip the compiled wrapper for rowwise FP8 inference linears (#15584)
Daniel Han772bff93e2e4
diff --git a/tests/test_fp8_rowwise_direct_route.py b/tests/test_fp8_rowwise_direct_route.pynew file mode 100644index 00000000000..98775b5031c--- /dev/null+++ b/tests/test_fp8_rowwise_direct_route.py@@ -0,0 +1,142 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Rowwise FP8 direct-route routing (fake CUDA tensors) and parity (sm89+ GPU)."""++import pytest+import torch+from torch._subclasses.fake_tensor import FakeTensorMode++from unsloth.kernels import fp8 as F8+++def spies(monkeypatch):+ calls = []+ monkeypatch.setattr(F8, "_fp8_rowwise_backend", lambda device: "scaled_mm")+ monkeypatch.setattr(F8, "_FP8_ROWWISE_DIRECT", True)+ monkeypatch.setattr(+ F8, "_fp8_rowwise_direct", lambda X, w, s, b, route: calls.append(route) or "direct"+ )+ monkeypatch.setattr(+ F8,+ "_fbgemm_fp8_linear_compiled",+ lambda X, w, s, b = None: calls.append("compiled") or "compiled",+ )+ return calls+++def _args(+ rows,+ N = 256,+ K = 512,+ requires_grad = False,+):+ X = torch.empty(1, rows, K, device = "cuda", dtype = torch.bfloat16, requires_grad = requires_grad)+ w = torch.nn.Parameter(+ torch.empty(N, K, device = "cuda", dtype = torch.float8_e4m3fn), requires_grad = False+ )+ s = torch.nn.Parameter(+ torch.empty(N, 1, device = "cuda", dtype = torch.float32), requires_grad = False+ )+ return X, w, s+++ "rows, route", [(17, "dequant"), (64, "dequant"), (65, "scaled_mm"), (4096, "scaled_mm")]+)+def test_inference_calls_take_the_direct_path(spies, rows, route):+ with FakeTensorMode(), torch.no_grad():+ assert F8.fbgemm_fp8_linear(*_args(rows)) == "direct"+ assert spies == [route]+++def test_autograd_fbgemm_and_kill_switch_keep_the_compiled_path(spies, monkeypatch):+ with FakeTensorMode():+ assert F8.fbgemm_fp8_linear(*_args(128, requires_grad = True)) == "compiled"+ with torch.no_grad():+ X, w, s = _args(128)+ # Transposed weight (LoRA backward's W.t()) and odd scaled_mm dims stay compiled / dequant. Built with+ # empty_strided: view ops on fake CUDA tensors raise on CPU-only torch builds.+ Xt = torch.empty(1, 128, 256, device = "cuda", dtype = torch.bfloat16)+ wt = torch.empty_strided((512, 256), (1, 512), device = "cuda", dtype = torch.float8_e4m3fn)+ st = torch.empty(512, 1, device = "cuda", dtype = torch.float32)+ assert F8.fbgemm_fp8_linear(Xt, wt, st) == "compiled"+ X2, w2, s2 = _args(128, N = 200)+ assert F8.fbgemm_fp8_linear(X2, w2, s2) == "direct"+ assert F8.fbgemm_fp8_linear(*_args(F8._FP8_ROWWISE_DIRECT_MAX_ROWS + 1)) == "compiled"+ monkeypatch.setattr(F8, "_fp8_rowwise_backend", lambda device: "fbgemm")+ assert F8.fbgemm_fp8_linear(X, w, s) == "compiled"+ monkeypatch.setattr(F8, "_fp8_rowwise_backend", lambda device: "scaled_mm")+ monkeypatch.setattr(F8, "_FP8_ROWWISE_DIRECT", False)+ assert F8.fbgemm_fp8_linear(X, w, s) == "compiled"+ assert spies == ["compiled", "compiled", "dequant", "compiled", "compiled", "compiled"]+++def test_cpu_and_traced_calls_keep_the_compiled_path(spies, monkeypatch):+ with torch.no_grad():+ X = torch.zeros(1, 128, 512, dtype = torch.bfloat16)+ w = torch.zeros(256, 512, dtype = torch.float8_e4m3fn)+ s = torch.ones(256, 1)+ assert F8.fbgemm_fp8_linear(X, w, s) == "compiled"+ with FakeTensorMode():+ args = _args(128)+ monkeypatch.setattr(torch.compiler, "is_compiling", lambda: True)+ assert F8.fbgemm_fp8_linear(*args) == "compiled"+ assert spies == ["compiled", "compiled"]+++_sm89 = torch.cuda.is_available() and torch.cuda.get_device_capability() >= (8, 9)++[email protected](not _sm89, reason = "rowwise FP8 GEMM parity needs an sm89+ GPU")[email protected]("dtype", [torch.bfloat16, torch.float16])+def test_direct_path_is_bitwise_equal_to_the_compiled_path(dtype):+ if F8._fp8_rowwise_backend(torch.device("cuda", 0)) != "scaled_mm":+ pytest.skip("this GPU does not use the scaled_mm rowwise backend")+ torch.manual_seed(0)+ with torch.no_grad():+ for N, K in ((256, 512), (768, 2048), (512, 5120), (208, 4112), (256, 16400)):+ w = (torch.randn(N, K, device = "cuda") * 0.5).to(torch.float8_e4m3fn)+ for s in (+ torch.rand(N, 1, device = "cuda") * 0.01 + 1e-3,+ (torch.rand(N, 1, device = "cuda") + 0.5).to(torch.bfloat16),+ ):+ for rows in (17, 64, 65, 300):+ X = (torch.randn(2, rows, K, device = "cuda") * 3).to(dtype)+ X[0, 0] = 0+ X[0, 1, ::7] = 1e4+ X[1, 2, 5] = float("nan")+ X[1, 3, 9] = float("inf")+ bias = torch.randn(N, device = "cuda", dtype = torch.float32)+ for b in (None, bias):+ for ub in (None, torch.tensor([20.0], device = "cuda")):+ if ub is not None:+ w.input_scale_ub = ub+ elif hasattr(w, "input_scale_ub"):+ del w.input_scale_ub+ route = F8._fp8_rowwise_direct_route(X, w, s)+ assert route == (+ "scaled_mm"+ if 2 * rows > 64 and N % 16 == 0 and K % 16 == 0+ else "dequant"+ )+ ref = F8._fbgemm_fp8_linear_compiled(X, w, s, b)+ out = F8.fbgemm_fp8_linear(X, w, s, b)+ assert out.shape == ref.shape and out.dtype == ref.dtype+ assert torch.equal(out.view(torch.int16), ref.view(torch.int16)), (+ N,+ K,+ rows,+ s.dtype,+ b is None,+ ub,+ )+++def test_compile_disabled_keeps_the_eager_wrapper():+ # UNSLOTH_COMPILE_DISABLE runs the wrapper eagerly, whose dequant rounds the scale first: keep it.+ assert F8._fp8_rowwise_direct_enabled("1", compile_disabled = True) is False+ assert F8._fp8_rowwise_direct_enabled("1", compile_disabled = False) is True+ for off in ("0", "false", "No", " off "):+ assert F8._fp8_rowwise_direct_enabled(off, compile_disabled = False) is Falsediff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.pyindex fd13c7efc3c..b75bfd60dd3 100644--- a/unsloth/kernels/fp8.py+++ b/unsloth/kernels/fp8.py@@ -2079,7 +2079,7 @@ class FbgemmFp8Linear_matmul(torch.autograd.Function):@torch_compile-def fbgemm_fp8_linear(+def _fbgemm_fp8_linear_compiled(X,weight,weight_scale,@@ -2090,6 +2090,213 @@ def fbgemm_fp8_linear()+# Rowwise FP8 inference: the compiled wrapper costs 75-95 us host time vs 10-80 us GPU at decode, so launch+# Inductor's kernels directly (bitwise equal). UNSLOTH_FP8_ROWWISE_DIRECT=0 disables it.+try:+ from unsloth_zoo.temporary_patches.common import UNSLOTH_COMPILE_DISABLE as _COMPILE_DISABLED+except ImportError:+ _COMPILE_DISABLED = os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") in ("1", "partial")+++def _fp8_rowwise_direct_enabled(setting, compile_disabled):+ # With UNSLOTH_COMPILE_DISABLE the wrapper runs eagerly (scale rounded to the activation dtype before the+ # multiply), so the direct path, which matches the compiled numerics, would change outputs there.+ if compile_disabled:+ return False+ return setting.strip().lower() not in ("0", "false", "no", "off")+++_FP8_ROWWISE_DIRECT = _fp8_rowwise_direct_enabled(+ os.environ.get("UNSLOTH_FP8_ROWWISE_DIRECT", "1"), _COMPILE_DISABLED+)+# Past this many rows the call is GPU bound and the compiled wrapper costs nothing extra; keep it there.+_FP8_ROWWISE_DIRECT_MAX_ROWS = 4096+++def _fp8_act_quant_per_row_kernel(+ x_ptr,+ y_ptr,+ s_ptr,+ ub_ptr,+ K,+ stride_xm,+ HAS_UB: tl.constexpr,+ BLOCK_K: tl.constexpr,+ ONE_BLOCK: tl.constexpr,+):+ # Same fp32 math Inductor emits for _quantize_fp8_per_row; [1, BLOCK_K] tile is faster than 1D on sm120.+ row = tl.program_id(0).to(tl.int64)+ x_row = x_ptr + row * stride_xm+ y_row = y_ptr + row * K+ offs = tl.arange(0, BLOCK_K)[None, :]+ if ONE_BLOCK:+ x = tl.load(x_row + offs, mask = offs < K, other = 0.0).to(tl.float32)+ row_max = tl.max(tl.abs(x), axis = 1)+ nans = tl.sum((x != x).to(tl.int32), axis = 1)+ else:+ amax = tl.zeros((1, BLOCK_K), dtype = tl.float32)+ nan_count = tl.zeros((1, BLOCK_K), dtype = tl.int32)+ for k in range(0, K, BLOCK_K):+ xk = tl.load(x_row + k + offs, mask = k + offs < K, other = 0.0).to(tl.float32)+ amax = tl.maximum(amax, tl.abs(xk))+ nan_count += (xk != xk).to(tl.int32)+ row_max = tl.max(amax, axis = 1)+ nans = tl.sum(nan_count, axis = 1)+ # torch.amax / clamp propagate NaN; tl.max and tl.maximum drop it by default.+ row_max = tl.where(nans > 0, float("nan"), row_max)+ if HAS_UB:+ row_max = tl.minimum(+ row_max, tl.load(ub_ptr).to(tl.float32), propagate_nan = tl.PropagateNan.ALL+ )+ scale = tl.maximum(row_max / 448.0, 1.0 / (448.0 * 512.0), propagate_nan = tl.PropagateNan.ALL)+ if ONE_BLOCK:+ y = tl.maximum(x / scale[:, None], -448.0, propagate_nan = tl.PropagateNan.ALL)+ y = tl.minimum(y, 448.0, propagate_nan = tl.PropagateNan.ALL)+ tl.store(y_row + offs, y.to(tl.float8e4nv), mask = offs < K)+ else:+ for k in range(0, K, BLOCK_K):+ mask = k + offs < K+ xk = tl.load(x_row + k + offs, mask = mask, other = 0.0).to(tl.float32)+ y = tl.maximum(xk / scale[:, None], -448.0, propagate_nan = tl.PropagateNan.ALL)+ y = tl.minimum(y, 448.0, propagate_nan = tl.PropagateNan.ALL)+ tl.store(y_row + k + offs, y.to(tl.float8e4nv), mask = mask)+ tl.store(s_ptr + row + tl.arange(0, 1), scale)+++def _fp8_rowwise_dequant_kernel(w_ptr, s_ptr, y_ptr, numel, K, BLOCK: tl.constexpr):+ # One fp32 multiply, one rounding, as Inductor fuses it (eager x.to(dtype) * s.to(dtype) rounds twice).+ offs = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)+ mask = offs < numel+ w = tl.load(w_ptr + offs, mask = mask, other = 0.0).to(tl.float32)+ s = tl.load(s_ptr + offs // K, mask = mask, other = 0.0).to(tl.float32)+ tl.store(y_ptr + offs, (w * s).to(y_ptr.dtype.element_ty), mask = mask)+++def _fp8_rowwise_direct_route(X, weight, weight_scale):+ """The compiled branch an eager call would take, when the direct path reproduces it; else None."""+ # Training first: it never takes the direct path, so it pays only these checks.+ if torch.is_grad_enabled() and (+ X.requires_grad or weight.requires_grad or weight_scale.requires_grad+ ):+ return None+ if not (+ _FP8_ROWWISE_DIRECT+ and X.is_cuda+ and X.dtype in (torch.bfloat16, torch.float16)+ and weight.dtype == torch.float8_e4m3fn+ and weight.dim() == 2+ and weight_scale.dim() == 2+ and torch.version.hip is None+ ):+ return None+ N, K = weight.shape+ if (+ weight_scale.shape[0] != N+ or weight_scale.shape[1] != 1+ or X.shape[-1] != K+ or N <= 1+ or X.numel() == 0+ or X.numel() > _FP8_ROWWISE_DIRECT_MAX_ROWS * K+ or weight_scale.dtype not in (torch.float32, torch.bfloat16, torch.float16)+ ):+ return None+ if (+ not weight.is_contiguous()+ or not weight_scale.is_contiguous()+ or X.device != weight.device+ or weight_scale.device != weight.device+ or _fp8_e4m3fn_unsupported_in_trace(weight)+ ):+ return None+ backend = _fp8_rowwise_backend(X.device)+ if backend == "fbgemm" and N % 8 == 0 and K % 8 == 0:+ return None+ if backend == "scaled_mm" and N % 16 == 0 and K % 16 == 0 and X.numel() > 64 * K:+ scale_ub = getattr(weight, "input_scale_ub", None)+ if scale_ub is not None and (+ not isinstance(scale_ub, torch.Tensor)+ or scale_ub.numel() != 1+ or scale_ub.device != X.device+ ):+ return None+ return "scaled_mm"+ return "dequant"+++def _fp8_rowwise_direct(X, weight, weight_scale, bias, route):+ K = X.shape[-1]+ output_shape = (*X.shape[:-1], -1)+ if route == "scaled_mm":+ x2 = X.reshape(-1, K)+ if x2.stride(-1) != 1:+ x2 = x2.contiguous()+ M = x2.shape[0]+ x_quantized = torch.empty((M, K), device = X.device, dtype = torch.float8_e4m3fn)+ x_scale = torch.empty((M, 1), device = X.device, dtype = torch.float32)+ scale_ub = getattr(weight, "input_scale_ub", None)+ block_k = min(triton.next_power_of_2(K), 16384)+ with _fp8_triton_device_context(X, static_device_count = True):+ _fp8_act_quant_per_row_kernel[(M,)](+ x2,+ x_quantized,+ x_scale,+ x_scale if scale_ub is None else scale_ub,+ K,+ x2.stride(0),+ HAS_UB = scale_ub is not None,+ BLOCK_K = block_k,+ ONE_BLOCK = block_k >= K,+ num_warps = 4 if block_k <= 4096 else 16,+ enable_fp_fusion = True,+ )+ output = torch._scaled_mm(+ x_quantized,+ weight.t(),+ scale_a = x_scale,+ scale_b = (+ weight_scale if weight_scale.dtype == torch.float32 else weight_scale.float()+ ).view(1, -1),+ out_dtype = X.dtype,+ use_fast_accum = True,+ )+ else:+ W_deq = torch.empty(weight.shape, device = weight.device, dtype = X.dtype)+ numel = W_deq.numel()+ with _fp8_triton_device_context(weight, static_device_count = True):+ _fp8_rowwise_dequant_kernel[(triton.cdiv(numel, 1024),)](+ weight,+ weight_scale,+ W_deq,+ numel,+ K,+ BLOCK = 1024,+ num_warps = 4,+ enable_fp_fusion = True,+ )+ output = torch_matmul(X, W_deq.t())+ if bias is not None:+ output = output + bias+ # FbgemmFp8Linear keeps its bias in float32; only cast when it promoted (a no-op .to() aliases).+ if output.dtype != X.dtype:+ output = output.to(X.dtype)+ return output.reshape(output_shape) if route == "scaled_mm" else output+++def fbgemm_fp8_linear(+ X,+ weight,+ weight_scale,+ bias = None,+):+ if not torch.compiler.is_compiling():+ route = _fp8_rowwise_direct_route(X, weight, weight_scale)+ if route is not None:+ return _fp8_rowwise_direct(X, weight, weight_scale, bias, route)+ return _fbgemm_fp8_linear_compiled(X, weight, weight_scale, bias)++class FP8_fbgemm_block_linear(torch.autograd.Function):@staticmethoddef forward(