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.

FP8 scaled_mm backend: send 17-64 rows to torch._scaled_mm when the 16-bit weight spills L2 (sm89) (#15791)

Daniel Han01c94d34adbf
diff --git a/tests/test_fp8_dequant_max_rows.py b/tests/test_fp8_dequant_max_rows.py
new file mode 100644
index 00000000000..44ef0662f02
--- /dev/null
+++ b/tests/test_fp8_dequant_max_rows.py
@@ -0,0 +1,150 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+"""scaled_mm rowwise FP8 backend: 17-64 rows go to torch._scaled_mm only when the 16-bit weight spills L2 (CPU)."""
+
+import pytest
+import torch
+from torch._subclasses.fake_tensor import FakeTensorMode
+
+from unsloth.kernels import fp8 as F8
+
+L2 = 48 * 1024 * 1024 # L4
+SMALL = (6144, 2048) # Qwen3-1.7B MLP: 24 MiB in bf16, L2 resident
+LARGE = (14336, 4096) # Llama-3.1-8B MLP: 112 MiB in bf16
+
+
+def route(monkeypatch):
+ monkeypatch.setattr(F8, "_fp8_rowwise_backend", lambda device: "scaled_mm")
+ monkeypatch.setattr(F8, "_FP8_ROWWISE_DIRECT", True)
+
+ def run(
+ rows,
+ shape,
+ l2 = L2,
+ env = None,
+ ):
+ monkeypatch.setattr(F8, "_fp8_l2_cache_bytes", lambda device: l2)
+ parsed = F8._parse_fp8_dequant_max_rows(env)
+ monkeypatch.setattr(F8, "_FP8_DEQUANT_MAX_ROWS_ENV", parsed)
+ monkeypatch.setattr(F8, "_FP8_DEQUANT_MAX_ROWS", 64 if parsed is None else parsed)
+ N, K = shape
+ with FakeTensorMode(), torch.no_grad():
+ X = torch.empty(1, rows, K, device = "cuda", dtype = torch.bfloat16)
+ w = torch.empty(N, K, device = "cuda", dtype = torch.float8_e4m3fn)
+ s = torch.empty(N, 1, device = "cuda", dtype = torch.float32)
+ return F8._fp8_rowwise_direct_route(X, w, s)
+
+ return run
+
+
[email protected]("rows", [17, 32, 64])
+def test_small_weight_stays_on_dequant_and_large_weight_goes_to_scaled_mm(route, rows):
+ assert route(rows, SMALL) == "dequant"
+ assert route(rows, LARGE) == "scaled_mm"
+
+
+def test_row_bounds_are_unchanged(route):
+ # 16 rows and below are the rows GEMV's; above 64 every weight already used scaled_mm.
+ assert route(16, LARGE) == "dequant"
+ assert route(65, SMALL) == "scaled_mm"
+
+
+def test_unknown_l2_keeps_the_64_row_default(route):
+ assert route(32, LARGE, l2 = 0) == "dequant"
+ assert route(65, LARGE, l2 = 0) == "scaled_mm"
+
+
+def test_env_override_sets_one_threshold_for_every_weight(route):
+ assert route(32, LARGE, env = "64") == "dequant"
+ assert route(17, SMALL, env = "16") == "scaled_mm"
+ for bad in ("", "abc", "-1", "1.5", None):
+ assert F8._parse_fp8_dequant_max_rows(bad) is None
+
+
+def test_l2_probe_falls_back_to_zero(monkeypatch):
+ def boom(device = None):
+ raise RuntimeError("no CUDA")
+
+ monkeypatch.setattr(torch.cuda, "get_device_properties", boom)
+ F8._probe_fp8_l2_cache_bytes.cache_clear()
+ try:
+ assert F8._probe_fp8_l2_cache_bytes(torch.device("cuda", 0)) == 0
+ finally:
+ F8._probe_fp8_l2_cache_bytes.cache_clear()
+
+
+ "capability, l2, expected",
+ [((8, 9), L2, L2), ((9, 0), 50 * 1024 * 1024, 0), ((12, 0), 128 * 1024 * 1024, 0)],
+)
+def test_l2_probe_only_reports_measured_arches(monkeypatch, capability, l2, expected):
+ """Only sm89 was measured: H100 without FBGEMM (50 MiB L2) keeps the 64 row default."""
+
+ class Props:
+ major, minor = capability
+ L2_cache_size = l2
+
+ monkeypatch.setattr(torch.cuda, "get_device_properties", lambda device = None: Props())
+ F8._probe_fp8_l2_cache_bytes.cache_clear()
+ try:
+ assert F8._probe_fp8_l2_cache_bytes(torch.device("cuda", 0)) == expected
+ finally:
+ F8._probe_fp8_l2_cache_bytes.cache_clear()
+
+
[email protected]("shape, scaled", [(LARGE, True), (SMALL, False)])
+def test_autograd_function_uses_the_same_gate(monkeypatch, shape, scaled):
+ calls = []
+
+ def fake_scaled_mm(a, b, **kwargs):
+ calls.append("scaled_mm")
+ return torch.empty(a.shape[0], b.shape[1], device = a.device, dtype = kwargs["out_dtype"])
+
+ def fake_dequant(w, s, dtype):
+ calls.append("dequant")
+ return torch.empty(w.shape, device = w.device, dtype = dtype)
+
+ monkeypatch.setattr(torch, "_scaled_mm", fake_scaled_mm)
+ monkeypatch.setattr(F8, "weight_dequant", fake_dequant)
+ monkeypatch.setattr(F8, "_fp8_l2_cache_bytes", lambda device: L2)
+ N, K = shape
+ with FakeTensorMode(), torch.no_grad():
+ X = torch.empty(1, 32, K, device = "cuda", dtype = torch.bfloat16)
+ w = torch.empty(N, K, device = "cuda", dtype = torch.float8_e4m3fn)
+ s = torch.empty(N, 1, device = "cuda", dtype = torch.float32)
+ y = F8.FbgemmFp8Linear_matmul.apply(X, w, s, None, "scaled_mm")
+ assert y.shape == (1, 32, N)
+ assert calls == ["scaled_mm" if scaled else "dequant"]
+
+
+def test_scaled_mm_asks_for_bf16_when_activations_are_fp16():
+ """torch 2.10's rowwise CUTLASS kernel writes bf16 bits into an fp16 output when there is no
+ bias: fp16 calls request bf16 and cast back; bf16 / fp32 are unchanged."""
+ assert F8._scaled_mm_out_dtype(torch.float16) is torch.bfloat16
+ assert F8._scaled_mm_out_dtype(torch.bfloat16) is torch.bfloat16
+ assert F8._scaled_mm_out_dtype(torch.float32) is torch.float32
+
+
+def test_every_rowwise_scaled_mm_call_uses_the_out_dtype_helper():
+ import ast
+ import inspect
+
+ tree = ast.parse(inspect.getsource(F8))
+ calls = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "_scaled_mm"
+ ]
+ out = {}
+ for node in calls:
+ for kw in node.keywords:
+ if kw.arg == "out_dtype":
+ out[node.lineno] = ast.unparse(kw.value)
+ # The backend probe asks for bf16 directly; every activation-dtype call goes through the helper.
+ data_calls = {line: v for line, v in out.items() if v != "torch.bfloat16"}
+ assert len(data_calls) >= 2, out
+ assert all(v.startswith("_scaled_mm_out_dtype(") for v in data_calls.values()), out
diff --git a/tests/test_fp8_rowwise_direct_route.py b/tests/test_fp8_rowwise_direct_route.py
index 98775b5031c..891444b1ed9 100644
--- a/tests/test_fp8_rowwise_direct_route.py
+++ b/tests/test_fp8_rowwise_direct_route.py
@@ -118,7 +118,9 @@ def test_direct_path_is_bitwise_equal_to_the_compiled_path(dtype):
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
+ if 2 * rows > F8._fp8_dequant_max_rows(X.device, N * K)
+ and N % 16 == 0
+ and K % 16 == 0
else "dequant"
)
ref = F8._fbgemm_fp8_linear_compiled(X, w, s, b)
diff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.py
index b75bfd60dd3..6b8d63ca72d 100644
--- a/unsloth/kernels/fp8.py
+++ b/unsloth/kernels/fp8.py
@@ -1981,6 +1981,66 @@ if hasattr(torch._dynamo, "assume_constant_result"):
_fp8_rowwise_backend = torch._dynamo.assume_constant_result(_fp8_rowwise_backend)
+def _scaled_mm_out_dtype(dtype):
+ """Rowwise torch._scaled_mm output dtype for activations of `dtype`. torch 2.10's rowwise CUTLASS
+ kernel picks its output element type from the bias dtype, so without a bias an fp16 output buffer
+ receives bf16 bits (every value garbage); ask for bf16 and let the caller cast back."""
+ return torch.bfloat16 if dtype == torch.float16 else dtype
+
+
+def _parse_fp8_dequant_max_rows(value):
+ try:
+ rows = int(str(value).strip())
+ except (TypeError, ValueError):
+ return None
+ return rows if rows >= 0 else None
+
+
+# The scaled_mm backend dequantizes the weight and runs a 16-bit GEMM up to this many rows, and quantizes the
+# activation per row for torch._scaled_mm above it (FBGEMM quantizes at every row count).
+# UNSLOTH_FP8_DEQUANT_MAX_ROWS sets it for every weight.
+_FP8_DEQUANT_MAX_ROWS_ENV = _parse_fp8_dequant_max_rows(
+ os.environ.get("UNSLOTH_FP8_DEQUANT_MAX_ROWS")
+)
+_FP8_DEQUANT_MAX_ROWS = 64 if _FP8_DEQUANT_MAX_ROWS_ENV is None else _FP8_DEQUANT_MAX_ROWS_ENV
+# A 16-bit weight copy larger than L2 makes dequant memory bound (L4, Llama-8B MLP: 1180 us vs 255 us for
+# _scaled_mm at 17-64 rows), while L2-resident weights stay launch bound and dequant wins (Qwen3-1.7B decode).
+_FP8_LARGE_WEIGHT_DEQUANT_MAX_ROWS = 16
+
+
+# Measured on sm89 only (L4); elsewhere (H100 without FBGEMM: 50 MiB L2) the 64 row default stays.
+_FP8_LARGE_WEIGHT_CAPABILITIES = ((8, 9),)
+
+
[email protected]_cache(maxsize = None)
+def _probe_fp8_l2_cache_bytes(device):
+ """L2 bytes for the large-weight gate, 0 (gate off) when unknown or on an unmeasured arch."""
+ try:
+ props = torch.cuda.get_device_properties(device)
+ if (props.major, props.minor) not in _FP8_LARGE_WEIGHT_CAPABILITIES:
+ return 0
+ return int(getattr(props, "L2_cache_size", 0) or 0)
+ except Exception:
+ return 0
+
+
+def _fp8_l2_cache_bytes(device):
+ return _probe_fp8_l2_cache_bytes(device)
+
+
+if hasattr(torch._dynamo, "assume_constant_result"):
+ _fp8_l2_cache_bytes = torch._dynamo.assume_constant_result(_fp8_l2_cache_bytes)
+
+
+def _fp8_dequant_max_rows(device, weight_numel):
+ """Largest row count the scaled_mm backend still serves with dequant + 16-bit GEMM for this weight."""
+ if _FP8_DEQUANT_MAX_ROWS_ENV is None:
+ l2 = _fp8_l2_cache_bytes(device)
+ if l2 > 0 and weight_numel * 2 > l2:
+ return _FP8_LARGE_WEIGHT_DEQUANT_MAX_ROWS
+ return _FP8_DEQUANT_MAX_ROWS
+
+
class FbgemmFp8Linear_matmul(torch.autograd.Function):
@staticmethod
def forward(
@@ -2030,8 +2090,9 @@ class FbgemmFp8Linear_matmul(torch.autograd.Function):
and rowwise
and (weight.shape[0] % 16 == 0 and weight.shape[1] % 16 == 0)
and x.shape[-1] == weight.shape[1]
- # Decode-sized calls: compiled dequant + GEMV beats quantizing the activation.
- and x.numel() > 64 * x.shape[-1]
+ # Decode-sized calls: dequant + 16-bit GEMM beats quantizing the activation unless the weight
+ # spills L2.
+ and x.numel() > _fp8_dequant_max_rows(x.device, weight.numel()) * x.shape[-1]
):
output_shape = (*x.shape[:-1], -1)
x_quantized, x_scale = _quantize_fp8_per_row(
@@ -2044,11 +2105,12 @@ class FbgemmFp8Linear_matmul(torch.autograd.Function):
weight.t(),
scale_a = x_scale,
scale_b = weight_scale.to(torch.float32).view(1, -1),
- out_dtype = x.dtype,
+ out_dtype = _scaled_mm_out_dtype(x.dtype),
use_fast_accum = True,
)
output = output + bias if bias is not None else output
- # FbgemmFp8Linear keeps its bias in float32; only cast when it promoted (a no-op .to() aliases).
+ # fp16 comes back as bf16 (_scaled_mm_out_dtype) and FbgemmFp8Linear keeps its bias in float32:
+ # cast only when the dtype differs (a no-op .to() aliases).
if output.dtype != x.dtype:
output = output.to(x.dtype)
output = output.reshape(output_shape)
@@ -2213,7 +2275,12 @@ def _fp8_rowwise_direct_route(X, weight, weight_scale):
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:
+ if (
+ backend == "scaled_mm"
+ and N % 16 == 0
+ and K % 16 == 0
+ and X.numel() > _fp8_dequant_max_rows(X.device, N * K) * K
+ ):
scale_ub = getattr(weight, "input_scale_ub", None)
if scale_ub is not None and (
not isinstance(scale_ub, torch.Tensor)
@@ -2258,7 +2325,7 @@ def _fp8_rowwise_direct(X, weight, weight_scale, bias, route):
scale_b = (
weight_scale if weight_scale.dtype == torch.float32 else weight_scale.float()
).view(1, -1),
- out_dtype = X.dtype,
+ out_dtype = _scaled_mm_out_dtype(X.dtype),
use_fast_accum = True,
)
else:
@@ -2278,7 +2345,8 @@ def _fp8_rowwise_direct(X, weight, weight_scale, bias, route):
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).
+ # fp16 comes back as bf16 (_scaled_mm_out_dtype) and FbgemmFp8Linear keeps its bias in float32:
+ # cast only when the dtype differs (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