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 block decode: weight-only GEMV where it beats the block GEMM, fused small-M called directly (#14813)

Daniel Han9bc4713a7780
diff --git a/tests/test_fp8_block_gemv.py b/tests/test_fp8_block_gemv.py
new file mode 100644
index 00000000000..ad85e860e2d
--- /dev/null
+++ b/tests/test_fp8_block_gemv.py
@@ -0,0 +1,239 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
+
+import pytest
+import torch
+
+if not torch.cuda.is_available():
+ pytest.skip("needs CUDA", allow_module_level = True)
+pytest.importorskip("triton")
+
+import triton # noqa: E402
+import unsloth # noqa: E402,F401
+from unsloth.kernels import fp8 as F8 # noqa: E402
+
+if F8._fp8_device_lacks_kernel(torch.device("cuda")):
+ pytest.skip("e4m3 Triton kernels need sm89+", allow_module_level = True)
+
+
[email protected](autouse = True)
+def _gemv_only(monkeypatch):
+ monkeypatch.setattr(F8, "_FP8_BLOCK_SMALL_M", False)
+
+
+def _quantize(N, K, seed = 0):
+ g = torch.Generator(device = "cuda").manual_seed(seed)
+ W = torch.randn(N, K, device = "cuda", generator = g)
+ nb, kb = triton.cdiv(N, 128), triton.cdiv(K, 128)
+ Wp = torch.zeros(nb * 128, kb * 128, device = "cuda")
+ Wp[:N, :K] = W
+ blocks = Wp.view(nb, 128, kb, 128)
+ s = blocks.abs().amax(dim = (1, 3)).clamp_min(1e-12) / 448.0
+ q = (blocks / s[:, None, :, None]).view(nb * 128, kb * 128)[:N, :K].to(torch.float8_e4m3fn)
+ return q.contiguous(), s.float().contiguous()
+
+
+def _uncached(q):
+ # Drop cached eligibility: gate tests flip device gates on the same weight.
+ q.__dict__.pop("_unsloth_fp8_block_gemv", None)
+ return q
+
+
+def _oracle(X, q, s):
+ S = s.double().repeat_interleave(128, 0).repeat_interleave(128, 1)[: q.shape[0], : q.shape[1]]
+ return X.double().reshape(-1, q.shape[1]) @ (q.double() * S).T
+
+
+def _rel_err(y, ref):
+ return ((y.double().reshape(ref.shape) - ref).abs().mean() / ref.pow(2).mean().sqrt()).item()
+
+
[email protected]("dtype", [torch.bfloat16, torch.float16])
[email protected]("M", [1, 3, 16])
[email protected]("NK", [(2048, 4096), (1024, 4096), (500, 1152), (320, 1000)])
+def test_block_gemv_matches_oracle_and_beats_act_quant(dtype, M, NK):
+ N, K = NK
+ q, s = _quantize(N, K, seed = M)
+ X = torch.randn(M, 1, K, device = "cuda", dtype = torch.float32).to(dtype)
+ assert M > 2 or F8.can_use_fp8_block_gemv(X, q, s)
+ with torch.no_grad():
+ y = F8.fp8_block_gemv(X, q, s)
+ y_main = F8.fp8_torch_block_quant_forward(X, q, s)
+ assert y.shape == (M, 1, N) and y.dtype == dtype
+ ref = _oracle(X, q, s)
+ err, err_main = _rel_err(y, ref), _rel_err(y_main, ref)
+ # Only the output rounding is left: about half an ulp of the activation dtype.
+ assert err <= torch.finfo(dtype).eps
+ assert err <= err_main
+
+
+def test_split_k_matches_single_pass():
+ q, s = _quantize(256, 8192)
+ X = torch.randn(4, 1, 8192, device = "cuda").to(torch.bfloat16)
+ with torch.no_grad():
+ split = F8.fp8_block_gemv(X, q, s)
+ sm = F8._sm_count
+ try:
+ F8._sm_count = lambda device: 1 # 2 tiles >= 2 * SMs: no split
+ single = F8.fp8_block_gemv(X, q, s)
+ finally:
+ F8._sm_count = sm
+ ref = _oracle(X, q, s)
+ assert _rel_err(split, ref) <= torch.finfo(torch.bfloat16).eps
+ assert _rel_err(single, ref) <= torch.finfo(torch.bfloat16).eps
+ torch.testing.assert_close(split, single, atol = 0, rtol = 2 * torch.finfo(torch.bfloat16).eps)
+
+
+def test_routing_decode_only(monkeypatch):
+ q, s = _quantize(512, 1024)
+ calls = []
+ real = F8.fp8_block_gemv
+ monkeypatch.setattr(F8, "fp8_block_gemv", lambda *a: calls.append(1) or real(*a))
+ with torch.no_grad():
+ F8.fp8_block_quant_linear(torch.randn(8, 1, 1024, device = "cuda", dtype = torch.bfloat16), q, s)
+ assert len(calls) == 1
+ F8.fp8_block_quant_linear(torch.randn(2, 4, 1024, device = "cuda", dtype = torch.bfloat16), q, s)
+ F8.fp8_block_quant_linear(torch.randn(17, 1, 1024, device = "cuda", dtype = torch.bfloat16), q, s)
+ X =torch.randn(2, 1, 1024, device = "cuda", dtype = torch.bfloat16, requires_grad = True)
+ F8.fp8_block_quant_linear(X, q, s).sum().backward() # training keeps the autograd path
+ assert len(calls) == 1 and X.grad is not None
+ assert not F8.can_use_fp8_block_gemv(X.detach(), q, s.t().contiguous())
+ assert not F8.can_use_fp8_block_gemv(X.detach().float(), q, s)
+ assert not F8.can_use_fp8_block_gemv(X.detach(), q, s.to(torch.float64))
+
+
+def test_kill_switch_and_device_gates(monkeypatch):
+ q, s = _quantize(256, 512)
+ X = torch.randn(1, 1, 512, device = "cuda", dtype = torch.bfloat16)
+ assert F8.can_use_fp8_block_gemv(X, q, s)
+ monkeypatch.setattr(F8, "_FP8_BLOCK_GEMV", False)
+ assert not F8.can_use_fp8_block_gemv(X, q, s)
+ monkeypatch.setattr(F8, "_FP8_BLOCK_GEMV", True)
+ # pre-sm89 (no e4m3 Triton) and Blackwell with Triton < 3.4 keep main's routing
+ monkeypatch.setattr(F8, "_fp8_device_lacks_kernel", lambda device: True)
+ assert not F8.can_use_fp8_block_gemv(X, _uncached(q), s)
+ monkeypatch.undo()
+ monkeypatch.setattr(F8, "_fp8_gemv_miscompiles", lambda device: True)
+ assert not F8.can_use_fp8_block_gemv(X, _uncached(q), s)
+ monkeypatch.undo()
+ monkeypatch.setattr(torch.version, "hip", "6.4")
+ assert not F8.can_use_fp8_block_gemv(X, _uncached(q), s)
+
+
+def test_weight_decision_cached_per_scale():
+ q, s = _quantize(256, 512)
+ X = torch.randn(1, 1, 512, device = "cuda", dtype = torch.bfloat16)
+ assert F8.can_use_fp8_block_gemv(X, q, s)
+ assert q._unsloth_fp8_block_gemv[0] is s and q._unsloth_fp8_block_gemv[1]
+ assert not F8.can_use_fp8_block_gemv(X, q, s.t().contiguous())
+ assert F8.can_use_fp8_block_gemv(X, q, s)
+
+
+def test_compiled_call_is_one_opaque_op():
+ q, s = _quantize(512, 1024)
+ X = torch.randn(4, 1, 1024, device = "cuda", dtype = torch.bfloat16)
+
+ def f(x):
+ return F8.fp8_block_quant_linear(x, q, s) * 2
+
+ torch._dynamo.reset()
+ with torch.no_grad():
+ eager = f(X)
+ compiled = torch.compile(f, fullgraph = True)(X)
+ torch.testing.assert_close(compiled, eager, atol = 0, rtol = 0)
+
+
[email protected]("block", [(64, 64), (128, 64), (64, 256)])
+def test_non_128_blocks(block):
+ bn, bk = block
+ N, K = 384, 1024
+ g = torch.Generator(device = "cuda").manual_seed(1)
+ W = torch.randn(N, K, device = "cuda", generator = g)
+ blocks = W.view(N // bn, bn, K // bk, bk)
+ s = (blocks.abs().amax(dim = (1, 3)) / 448.0).float().contiguous()
+ q = (blocks / s[:, None, :, None]).view(N, K).to(torch.float8_e4m3fn).contiguous()
+ q.block_size = [bn, bk]
+ X = torch.randn(4, 1, K, device = "cuda", generator = g).to(torch.bfloat16)
+ assert F8.can_use_fp8_block_gemv(X, q, s)
+ with torch.no_grad():
+ y = F8.fp8_block_gemv(X, q, s)
+ S = s.double().repeat_interleave(bn, 0).repeat_interleave(bk, 1)
+ ref = X.double().reshape(4, K) @ (q.double() * S).T
+ assert _rel_err(y, ref) <= torch.finfo(torch.bfloat16).eps
+
+
+def test_routes_only_where_never_slower(monkeypatch):
+ # Wide outputs (q, gate / up) keep the block GEMM everywhere; on < 100-SM parts big weights do too.
+ X = torch.randn(2, 1, 4096, device = "cuda", dtype = torch.bfloat16)
+ q, s = _quantize(4096, 4096)
+ assert not F8.can_use_fp8_block_gemv(X, q, s)
+ q, s = _quantize(2048, 4096)
+ assert F8.can_use_fp8_block_gemv(X, q, s)
+ Xd = torch.randn(2, 1, 12288, device = "cuda", dtype = torch.bfloat16)
+ qd, sd = _quantize(4096, 12288)
+ monkeypatch.setattr(F8, "_sm_count", lambda device: 188)
+ assert F8.can_use_fp8_block_gemv(Xd, _uncached(qd), sd)
+ monkeypatch.setattr(F8, "_sm_count", lambda device: 58)
+ assert not F8.can_use_fp8_block_gemv(Xd, _uncached(qd), sd)
+ assert F8.can_use_fp8_block_gemv(X, *_quantize(1024, 4096))
+
+
[email protected]("route, expect", [("small_m_first", "small_m"), ("gemv_first", "gemv")])
+def test_router_order(monkeypatch, route, expect):
+ # 100+ SM parts take the fused kernel here, smaller ones the GEMV.
+ if F8.fp8_block_matmul is not F8.w8a8_block_fp8_matmul_triton:
+ pytest.skip("the fused small-M kernel replaces the Triton block matmul route only")
+ monkeypatch.setattr(F8, "_FP8_BLOCK_SMALL_M", True)
+ fn = F8._fp8_block_small_m_first if route == "small_m_first" else F8._with_fp8_block_gemv(F8.fp8_torch_block_quant_forward)
+ q, s = _quantize(1024, 4096)
+ X = torch.randn(4, 1, 4096, device = "cuda", dtype = torch.bfloat16)
+ calls = []
+ real_gemv, real_small = F8.fp8_block_gemv, F8.fp8_block_small_m_linear
+ monkeypatch.setattr(F8, "fp8_block_gemv", lambda *a: calls.append("gemv") or real_gemv(*a))
+ monkeypatch.setattr(F8, "fp8_block_small_m_linear", lambda *a: calls.append("small_m") or real_small(*a))
+ with torch.no_grad():
+ y = fn(X, q, s)
+ assert calls == [expect]
+ # act_quant rounds X to e4m3 on the fused path: a few percent, against the GEMV's bf16 eps.
+ assert _rel_err(y, _oracle(X, q, s)) <= (5e-2 if expect == "small_m" else torch.finfo(torch.bfloat16).eps)
+ Xg = X.clone().requires_grad_()
+ calls.clear()
+ fn(Xg, q, s).sum().backward()
+ assert "gemv" not in calls and Xg.grad is not None
+
+
+def test_router_small_m_first_falls_back(monkeypatch):
+ # Compiled regions (the fused kernel is eager only) and pre-sm89 parts do not take the fused kernel.
+ monkeypatch.setattr(F8, "_FP8_BLOCK_SMALL_M", True)
+ q, s = _quantize(1024, 4096)
+ X = torch.randn(2, 1, 4096, device = "cuda", dtype = torch.bfloat16)
+ torch._dynamo.reset()
+ with torch.no_grad():
+ compiled = torch.compile(lambda x: F8._fp8_block_small_m_first(x, q, s), fullgraph = True)(X)
+ gemv = F8.fp8_block_gemv(X, q, s)
+ torch.testing.assert_close(compiled, gemv, atol = 0, rtol = 0)
+ monkeypatch.setattr(F8, "_fp8_device_lacks_kernel", lambda device: True)
+ monkeypatch.setattr(F8, "fp8_block_small_m_linear", lambda *a: pytest.fail("fused kernel used below sm89"))
+ with torch.no_grad():
+ F8._fp8_block_small_m_first(X, _uncached(q), s)
+
+
+def test_router_binding_follows_sm_count():
+ bound = F8.fp8_block_quant_linear
+ if F8.fp8_block_matmul is not F8.w8a8_block_fp8_matmul_triton or bound.__wrapped__ is not F8.fp8_torch_block_quant_forward:
+ pytest.skip("FBGEMM / torchao block route: the GEMV wraps it")
+ big = torch.version.hip is None and min(F8._SM_COUNTS) >= 100
+ assert (bound is F8._fp8_block_small_m_first) == big
+
+
+def test_small_gpu_row_cap(monkeypatch):
+ # Below 100 SMs: up to 8 rows, 2 over 8M elements; 100+ SM parts take all 16.
+ def rows_ok(sms, N, K, rows):
+ monkeypatch.setattr(F8, "_sm_count", lambda device: sms)
+ q, s = _quantize(N, K)
+ X = torch.randn(rows, 1, K, device = "cuda", dtype = torch.bfloat16)
+ return F8.can_use_fp8_block_gemv(X, _uncached(q), s)
+
+ assert rows_ok(58, 1024, 4096, 8) and not rows_ok(58, 1024, 4096, 9)
+ assert rows_ok(58, 2048, 6144, 2) and not rows_ok(58, 2048, 6144, 3)
+ assert rows_ok(188, 2048, 6144, 16) and rows_ok(188, 1024, 4096, 16)
diff --git a/tests/test_fp8_block_small_m.py b/tests/test_fp8_block_small_m.py
index ba4ce2da119..94061b79a7a 100644
--- a/tests/test_fp8_block_small_m.py
+++ b/tests/test_fp8_block_small_m.py
@@ -20,6 +20,12 @@ pytestmark = pytest.mark.skipif(
)
[email protected](autouse = True)
+def _no_block_gemv(monkeypatch):
+ # The GEMV, which takes some decode shapes first, is tested in test_fp8_block_gemv.py.
+ monkeypatch.setattr(f, "_FP8_BLOCK_GEMV", False, raising = False)
+
+
def _block_weight(N, K, scale_dtype = torch.float32):
W = torch.randn(N, K, device = "cuda") * 0.02
s = W.abs().view(N // 128, 128, K // 128, 128).amax((1, 3)) / 448.0
diff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.py
index 9282233d61c..26460879eb9 100644
--- a/unsloth/kernels/fp8.py
+++ b/unsloth/kernels/fp8.py
@@ -532,11 +532,6 @@ def _small_m_config(M, N, K, device):
return block_n, split_k, 4, _SMALL_M_STAGES[block_n]
[email protected]_cache(maxsize = None)
-def _sm_count(device):
- return torch.cuda.get_device_properties(device).multi_processor_count
-
-
def can_use_fp8_block_small_m(X, weight, weight_scale, block_size):
# Eager only: under torch.compile the M bound below would guard on the symbolic M and recompile.
if not _FP8_BLOCK_SMALL_M or fp8_block_matmul is not w8a8_block_fp8_matmul_triton or torch.compiler.is_compiling():
@@ -926,6 +921,236 @@ def fp8_rowwise_gemv(X, weight, weight_scale):
return out
+# Block-FP8 decode GEMV (1-16 tokens): reads the fp8 weight once, unquantized activations.
+# UNSLOTH_FP8_BLOCK_GEMV=0 disables it.
+_FP8_BLOCK_GEMV = os.environ.get("UNSLOTH_FP8_BLOCK_GEMV", "1").strip().lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+)
+_FP8_BLOCK_GEMV_MAX_ROWS = 16
+
+
+# M stays unspecialized: one compiled variant for batch 1-16.
[email protected](do_not_specialize = ["M", "stride_ys"])
+def _fp8_block_gemv_kernel(
+ x_ptr,
+ w_ptr,
+ s_ptr,
+ y_ptr,
+ M,
+ N,
+ K,
+ K_PER_SPLIT,
+ stride_xm,
+ stride_wn,
+ stride_sn,
+ stride_sk,
+ stride_ys,
+ stride_ym,
+ GROUP_N: tl.constexpr,
+ GROUP_K: tl.constexpr,
+ BLOCK_M: tl.constexpr,
+ BLOCK_N: tl.constexpr,
+ BLOCK_K: tl.constexpr,
+ LONG_INDEXING: tl.constexpr = False,
+):
+ pid_n = tl.program_id(0)
+ pid_k = tl.program_id(1)
+ if LONG_INDEXING:
+ pid_n = pid_n.to(tl.int64)
+ offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
+ offs_m = tl.arange(0, BLOCK_M)
+ mask_n = offs_n < N
+ mask_m = offs_m < M
+ s_rows = s_ptr + (offs_n // GROUP_N) * stride_sn
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype = tl.float32)
+ k_begin = pid_k * K_PER_SPLIT
+ k_end = tl.minimum(k_begin + K_PER_SPLIT, K)
+ for k0 in range(k_begin, k_end, BLOCK_K):
+ offs_k = k0 + tl.arange(0, BLOCK_K)
+ mask_k = offs_k < k_end
+ x = tl.load(
+ x_ptr + offs_m[:, None] * stride_xm + offs_k[None, :],
+ mask = mask_m[:, None] & mask_k[None, :],
+ other = 0.0,
+ )
+ # e4m3 values are exact in bf16 and fp16, so the dot sees the stored weight.
+ w = tl.load(
+ w_ptr + offs_n[:, None] * stride_wn + offs_k[None, :],
+ mask = mask_n[:, None] & mask_k[None, :],
+ other = 0.0,
+ ).to(x.dtype)
+ s = tl.load(s_rows + (k0 // GROUP_K) * stride_sk, mask = mask_n, other = 0.0).to(tl.float32)
+ acc += tl.dot(x, tl.trans(w), out_dtype = tl.float32) * s[None, :]
+ y = y_ptr + pid_k * stride_ys + offs_m[:, None] * stride_ym + offs_n[None, :]
+ tl.store(y, acc.to(y_ptr.dtype.element_ty), mask = mask_m[:, None] & mask_n[None, :])
+
+
+def _fp8_block_size(weight, weight_scale):
+ return list(
+ getattr(weight, "block_size", None)
+ or getattr(weight_scale, "block_size", None)
+ or [128, 128]
+ )
+
+
+def _fp8_block_gemv_weight_ok(weight, weight_scale):
+ # Cached per (weight, scale): 0 = never, else max decode rows.
+ if not weight.is_cuda or weight.dtype != torch.float8_e4m3fn or weight.dim() != 2 or not weight.is_contiguous():
+ return 0
+ N, K = weight.shape
+ # Only where never slower than the block GEMM (L4, RTX PRO 6000; L2 flushed and hot). Small parts cap
+ # rows at 8, and 2 over 8M elements (L4 2048 x 6144: 16 rows 1.98x the GEMM's time).
+ small_gpu = _sm_count(weight.device) < 100
+ if 2 * N > K or (small_gpu and N * K > _FP8_BLOCK_GEMV_SMALL_GPU_MAX_ELEMS):
+ return 0
+ max_rows = _FP8_BLOCK_GEMV_MAX_ROWS
+ if small_gpu:
+ max_rows = 2 if N * K > _FP8_BLOCK_GEMV_SMALL_GPU_MAX_ELEMS // 2 else 8
+ if (
+ weight_scale.ndim != 2
+ or weight_scale.dtype not in (torch.float32, torch.bfloat16, torch.float16)
+ or weight_scale.device != weight.device
+ ):
+ return 0
+ block_size = _fp8_block_size(weight, weight_scale)
+ if len(block_size) != 2:
+ return 0
+ group_n, group_k = int(block_size[0]), int(block_size[1])
+ if tuple(weight_scale.shape) != (triton.cdiv(N, group_n), triton.cdiv(K, group_k)):
+ return 0
+ if group_n < 1 or group_k < 16 or group_k & (group_k - 1):
+ return 0
+ if _fp8_kernel_unsupported(weight):
+ return 0
+ # Triton 3.3 miscompiles fp8 GEMVs on Blackwell; keep the GEMM there.
+ return 0 if _fp8_gemv_miscompiles(weight.device) else max_rows
+
+
+def can_use_fp8_block_gemv(X, weight, weight_scale):
+ # Not validated on ROCm yet.
+ if not _FP8_BLOCK_GEMV or torch.version.hip is not None:
+ return False
+ cached = getattr(weight, "_unsloth_fp8_block_gemv", None)
+ if cached is not None and cached[0] is weight_scale:
+ weight_ok = cached[1] # max decode rows, 0 = never
+ else:
+ weight_ok = _fp8_block_gemv_weight_ok(weight, weight_scale)
+ if not torch.compiler.is_compiling():
+ weight._unsloth_fp8_block_gemv = (weight_scale, weight_ok)
+ if not weight_ok:
+ return False
+ if not (X.is_cuda and X.dtype in (torch.bfloat16, torch.float16)) or X.device != weight.device:
+ return False
+ K = weight.shape[1]
+ if X.shape[-1] != K:
+ return False
+ rows = X.numel() // K
+ if not 1 <= rows <= weight_ok or (X.dim() >= 3 and X.shape[-2] != 1):
+ return False
+ return not (torch.is_grad_enabled() and (X.requires_grad or weight.requires_grad))
+
+
+_FP8_BLOCK_GEMV_SMALL_GPU_MAX_ELEMS = 16 * 1024 * 1024
+# Read once: a device-properties query inside a compiled region graph-breaks.
+_SM_COUNTS = tuple(
+ torch.cuda.get_device_properties(i).multi_processor_count
+ for i in range(torch.cuda.device_count() if torch.cuda.is_available() else 0)
+)
+
+
+def _sm_count(device):
+ index = device.index if device.index is not None else torch.cuda.current_device()
+ return _SM_COUNTS[index] if index < len(_SM_COUNTS) else 0
+
+
+@_opaque_under_compile(
+ "fp8_block_gemv",
+ lambda X, weight, weight_scale, group_n, group_k: X.new_empty(X.shape[:-1] + (weight.shape[0],)),
+)
+def _fp8_block_gemv(
+ X: torch.Tensor, weight: torch.Tensor, weight_scale: torch.Tensor, group_n: int, group_k: int
+) -> torch.Tensor:
+ N, K = weight.shape
+ x2 = X.reshape(-1, K)
+ if not x2.is_contiguous():
+ x2 = x2.contiguous()
+ M = x2.shape[0]
+ sms = _sm_count(weight.device)
+ block_n, num_warps, num_stages, programs_per_sm = (16, 2, 4, 1) if sms < 100 else (32, 4, 3, 4)
+ block_k = min(128, group_k)
+ n_tiles = triton.cdiv(N, block_n)
+ k_blocks = triton.cdiv(K, group_k)
+ split = max(1, min(k_blocks, (programs_per_sm * sms + n_tiles - 1) // n_tiles, 16))
+ k_per_split = triton.cdiv(k_blocks, split) * group_k
+ split = triton.cdiv(K, k_per_split)
+ if split == 1:
+ y = torch.empty((1, M, N), device = X.device, dtype = X.dtype)
+ else:
+ y = torch.empty((split, M, N), device = X.device, dtype = torch.float32)
+ scale = weight_scale if weight_scale.stride(-1) == 1 else weight_scale.contiguous()
+ with _fp8_triton_device_context(X, static_device_count = True):
+ _fp8_block_gemv_kernel[(n_tiles, split)](
+ x2,
+ weight,
+ scale,
+ y,
+ M,
+ N,
+ K,
+ k_per_split,
+ x2.stride(0),
+ weight.stride(0),
+ scale.stride(0),
+ scale.stride(1),
+ y.stride(0),
+ y.stride(1),
+ GROUP_N = group_n,
+ GROUP_K = group_k,
+ BLOCK_M = 16,
+ BLOCK_N = block_n,
+ BLOCK_K = block_k,
+ LONG_INDEXING = long_indexing(weight),
+ num_warps = num_warps,
+ num_stages = num_stages,
+ enable_fp_fusion = True,
+ )
+ out = y[0] if split == 1 else y.sum(0).to(X.dtype)
+ return out.reshape(*X.shape[:-1], N)
+
+
+def fp8_block_gemv(X, weight, weight_scale):
+ """X @ dequant(weight, weight_scale).T for 1-16 decode tokens, activations unquantized."""
+ group_n, group_k = (int(b) for b in _fp8_block_size(weight, weight_scale))
+ return _fp8_block_gemv(X, weight, weight_scale, group_n, group_k)
+
+
+def _with_fp8_block_gemv(block_forward):
+ @functools.wraps(block_forward)
+ def forward(X, weight, weight_scale):
+ if can_use_fp8_block_gemv(X, weight, weight_scale):
+ return fp8_block_gemv(X, weight, weight_scale)
+ return block_forward(X, weight, weight_scale)
+
+ return forward
+
+
+def _fp8_block_small_m_first(X, weight, weight_scale):
+ # 100+ SM parts: the fused small-M kernel is faster, so try it first (eager only; compiled uses the GEMV).
+ if not (torch.is_grad_enabled() and X.requires_grad):
+ if (
+ can_use_fp8_block_small_m(X, weight, weight_scale, _fp8_block_size(weight, weight_scale))
+ and weight.is_contiguous()
+ and not _fp8_kernel_unsupported(weight, torch.float8_e4m3fn)
+ ):
+ return fp8_block_small_m_linear(X, weight, weight_scale)
+ if can_use_fp8_block_gemv(X, weight, weight_scale):
+ return fp8_block_gemv(X, weight, weight_scale)
+ return fp8_torch_block_quant_forward(X, weight, weight_scale)
+
+
# Expanding the scale over the whole weight needs two m*n float32 temporaries, ~6x the triton
# kernel's peak; chunk by block-rows so the scratch stays bounded. Values are identical.
_DEQUANT_CHUNK_ELEMS = 8 * 1024 * 1024
@@ -1500,6 +1725,17 @@ try:
os.environ["UNSLOTH_HAS_FBGEMM"] = "0"
except:
pass
+# Decode-sized calls take the GEMV whichever block GEMM was selected above.
+if (
+ fp8_block_quant_linear is fp8_torch_block_quant_forward
+ and torch.version.hip is None
+ and _SM_COUNTS
+ and min(_SM_COUNTS) >= 100
+):
+ _fp8_block_small_m_first.__wrapped__ = fp8_torch_block_quant_forward
+ fp8_block_quant_linear = _fp8_block_small_m_first
+else:
+ fp8_block_quant_linear = _with_fp8_block_gemv(fp8_block_quant_linear)
# Not torch.compiled, for the same reason as fp8_torch_block_quant_forward.