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 rowwise GEMV: int64 row offsets past 2^31 elements, and skip it on Blackwell with Triton 3.3 (#13830)
Daniel Han06d98531226c
diff --git a/tests/test_compressed_tensors_fp8_kernel_route.py b/tests/test_compressed_tensors_fp8_kernel_route.pyindex 084e19bc224..179ac31af81 100644--- a/tests/test_compressed_tensors_fp8_kernel_route.py+++ b/tests/test_compressed_tensors_fp8_kernel_route.py@@ -249,7 +249,11 @@ def test_a_model_mixing_fp8_and_other_schemes_is_not_partly_routed():)@pytest.mark.parametrize("rows", [(1,), (1, 1), (1, 1, 1)])def test_decode_gemv_matches_the_dequantized_matmul(shape, rows):- from unsloth.kernels.fp8 import can_use_fp8_rowwise_gemv, fp8_rowwise_gemv+ from unsloth.kernels.fp8 import (+ _fp8_gemv_miscompiles,+ can_use_fp8_rowwise_gemv,+ fp8_rowwise_gemv,+ )if _fp8_kernel_unsupported_here():pytest.skip("triton cannot read float8_e4m3fn on this GPU")@@ -257,6 +261,11 @@ def test_decode_gemv_matches_the_dequantized_matmul(shape, rows):W, s = model.lin.weight, model.lin.weight_scaleX = torch.randn(*rows, shape[1], device = dev, dtype = torch.bfloat16)with torch.no_grad():+ if _fp8_gemv_miscompiles(W.device):+ assert not can_use_fp8_rowwise_gemv(X, W, s)+ pytest.skip(+ "Triton < 3.4 miscompiles this GEMV on Blackwell; decode takes the dequant path"+ )assert can_use_fp8_rowwise_gemv(X, W, s)y = fp8_rowwise_gemv(X, W, s)y_again = fp8_rowwise_gemv(X, W, s)diff --git a/tests/test_fp8_rowwise_gemv_blackwell_gate.py b/tests/test_fp8_rowwise_gemv_blackwell_gate.pynew file mode 100644index 00000000000..93e6618f4b2--- /dev/null+++ b/tests/test_fp8_rowwise_gemv_blackwell_gate.py@@ -0,0 +1,61 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Triton 3.3 builds a wrong FP8 rowwise GEMV on Blackwell, so those cards must not take it."""++import os+import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++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+++ "capability, version, hip, expected",+ [+ ((10, 0), "3.3.1", None, True),+ ((12, 0), "3.3.0", None, True),+ ((10, 0), "3.4.0", None, False),+ ((9, 0), "3.3.1", None, False),+ ((8, 9), "3.2.0", None, False),+ ((10, 0), "3.3.1", "6.3", False),+ ],+)+def test_gate(F, monkeypatch, capability, version, hip, expected):+ monkeypatch.setattr(F.torch.cuda, "get_device_capability", lambda device = None: capability)+ monkeypatch.setattr(F.triton, "__version__", version)+ monkeypatch.setattr(F.torch.version, "hip", hip)+ F._fp8_gemv_miscompiles.cache_clear()+ try:+ assert F._fp8_gemv_miscompiles(0) is expected+ finally:+ F._fp8_gemv_miscompiles.cache_clear()++[email protected](not torch.cuda.is_available(), reason = "needs a GPU")[email protected]("N, K", [(5000, 1536), (40000, 1024), (4096, 4096)])+def test_chosen_gemv_is_exact(F, N, K):+ if F._fp8_kernel_unsupported(torch.empty(1, device = "cuda", dtype = torch.float8_e4m3fn)):+ pytest.skip("no fp8e4nv Triton kernel on this device")+ g = torch.Generator(device = "cuda").manual_seed(0)+ X = torch.randn(1, K, device = "cuda", dtype = torch.bfloat16, generator = g)+ W = (torch.randn(N, K, device = "cuda", generator = g) * 0.5).to(torch.float8_e4m3fn)+ S = torch.rand(N, 1, device = "cuda", generator = g) + 0.5+ if not F.can_use_fp8_rowwise_gemv(X, W, S):+ assert F._fp8_gemv_miscompiles(W.device)+ return+ out = F.fp8_rowwise_gemv(X, W, S).float().reshape(-1)+ ref = (X.float() @ (W.float() * S).T).reshape(-1)+ assert (out - ref).abs().max() <= 1e-2 * ref.abs().max()diff --git a/tests/test_fp8_rowwise_gemv_long_indexing.py b/tests/test_fp8_rowwise_gemv_long_indexing.pynew file mode 100644index 00000000000..441a26f4d41--- /dev/null+++ b/tests/test_fp8_rowwise_gemv_long_indexing.py@@ -0,0 +1,181 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""The FP8 rowwise GEMV must address weights holding more than 2^31 elements."""++import os+import sys+from contextlib import nullcontext+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++torch = pytest.importorskip("torch")+pytest.importorskip("triton", reason = "the FP8 GEMV is a Triton kernel")++CUDA = torch.cuda.is_available()++[email protected](scope = "module")+def F():+ os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")+ from unsloth.kernels import fp8+ return fp8+++class _Recorder:+ def __init__(self):+ self.calls = []++ def __getitem__(self, grid):+ def launch(*args, **kwargs):+ self.calls.append((grid, args, kwargs))++ return launch+++def _launch_kwargs(F, monkeypatch, N, K):+ rec = _Recorder()+ monkeypatch.setattr(F, "_fp8_rowwise_gemv_kernel", rec)+ monkeypatch.setattr(F, "_fp8_triton_device_context", lambda *a, **k: nullcontext())+ X = torch.empty(1, K, device = "meta", dtype = torch.bfloat16)+ W = torch.empty(N, K, device = "meta", dtype = torch.float8_e4m3fn)+ S = torch.empty(N, 1, device = "meta", dtype = torch.float32)+ F.fp8_rowwise_gemv(X, W, S)+ assert len(rec.calls) == 1+ return rec.calls[0][2]+++ "N, K, expected",+ [+ (4096, 4096, False),+ (152064, 8192, False),+ (2**31 // 4096, 4096, False), # exactly 2^31 elements: last offset is 2^31 - 1+ (2**31 // 4096 + 1, 4096, True), # one row past: last row starts at 2^31+ (2**31 // 7168 + 64, 7168, True), # K not a power of two+ (262144, 16384, True), # 2^32 elements+ ],+)+def test_launch_widens_exactly_when_offsets_pass_int32(F, monkeypatch, N, K, expected):+ kwargs = _launch_kwargs(F, monkeypatch, N, K)+ assert kwargs.get("LONG_INDEXING", False) is expected, (N, K, kwargs)+++def _compile_ir(+ F,+ long_indexing,+ arch = 90,+):+ from triton.compiler import ASTSource++ fn = F._fp8_rowwise_gemv_kernel+ sig = dict(x_ptr = "*bf16", w_ptr = "*fp8e4nv", s_ptr = "*fp32", y_ptr = "*bf16")+ sig |= dict(N = "i32", K = "i32", stride_wn = "i32")+ sig |= dict(BLOCK_N = "constexpr", BLOCK_K = "constexpr", LONG_INDEXING = "constexpr")+ cx = dict(BLOCK_N = 8, BLOCK_K = 512, LONG_INDEXING = long_indexing)+ try:+ src = ASTSource(fn, sig, constexprs = cx)+ except TypeError: # pragma: no cover - Triton 3.2 uses `constants`+ sig = {k: v for k, v in sig.items() if v != "constexpr"}+ src = ASTSource(fn, sig, constants = cx)+ try:+ return triton_compile(src, arch)+ except Exception as exc: # pragma: no cover+ if "driver" in str(exc).lower():+ pytest.skip(f"no Triton CUDA driver to compile against: {exc}")+ raise+++def triton_compile(src, arch):+ import triton+ from triton.backends.compiler import GPUTarget+ return triton.compile(src, target = GPUTarget("cuda", arch, 32)).asm["ttir"]++[email protected]("long_indexing", [False, True])+def test_row_offset_multiply_width(F, long_indexing):+ """The weight-row multiply is i64 exactly on the LONG_INDEXING path (compile-only)."""+ ttir = _compile_ir(F, long_indexing)+ muls = [line for line in ttir.splitlines() if "arith.muli" in line]+ wide = [+ line+ for line in muls+ if "i64>" in line or ": i64 " in line or line.rstrip().endswith(": i64")+ ]+ assert muls, ttir+ if long_indexing:+ # Every multiply, including program_id * BLOCK_N (rows past 2^31 for an (N, 1) weight).+ assert wide == muls, "\n".join(muls)+ else:+ assert not wide, "\n".join(wide)+++def _operands(+ N,+ K,+ device = "cuda",+ seed = 0,+):+ g = torch.Generator(device = device).manual_seed(seed)+ X = torch.randn(1, K, device = device, dtype = torch.bfloat16, generator = g)+ W = (torch.randn(N, K, device = device, generator = g) * 0.05).to(torch.float8_e4m3fn)+ S = torch.rand(N, 1, device = device, generator = g) * 0.01 + 0.001+ return X, W, S+++def _launch(F, X, W, S, long_indexing):+ import triton++ N, K = W.shape+ out = torch.empty(1, N, device = X.device, dtype = X.dtype)+ block_n = 1 if N <= 4096 else (4 if N <= 32768 else 8)+ F._fp8_rowwise_gemv_kernel[(triton.cdiv(N, block_n),)](+ X, W, S, out, N, K, W.stride(0),+ BLOCK_N = block_n, BLOCK_K = 512, LONG_INDEXING = long_indexing, num_warps = 2,+ ) # fmt: skip+ return out+++def _skip_without_kernel(F):+ W = torch.empty(1, device = "cuda", dtype = torch.float8_e4m3fn)+ if F._fp8_kernel_unsupported(W):+ pytest.skip("no fp8e4nv Triton kernel on this device")+ if F._fp8_gemv_miscompiles(W.device):+ pytest.skip("Triton < 3.4 miscompiles this GEMV on Blackwell; production skips it")++[email protected](not CUDA, reason = "needs a CUDA device")[email protected]("N, K", [(4096, 4096), (5000, 3000), (40000, 1536)])+def test_long_path_matches_int32_path_on_ordinary_shapes(F, N, K):+ _skip_without_kernel(F)+ X, W, S = _operands(N, K)+ short = _launch(F, X, W, S, False)+ wide = _launch(F, X, W, S, True)+ torch.cuda.synchronize()+ assert torch.equal(short, wide)+ ref = (X.float() @ (W.float() * S).T).to(X.dtype)+ torch.testing.assert_close(short.float(), ref.float(), atol = 2e-2, rtol = 2e-2)++[email protected](not CUDA, reason = "needs a CUDA device")+def test_weight_past_2_31_elements(F):+ """A real (N, K) FP8 weight one block past 2^31 elements (2 GiB): the tail rows must match."""+ _skip_without_kernel(F)+ K = 4096+ N = 2**31 // K + 256+ if torch.cuda.mem_get_info()[0] < 4 * 1024**3:+ pytest.skip("needs 4 GB free GPU memory")+ X = torch.randn(1, K, device = "cuda", dtype = torch.bfloat16)+ W = torch.empty(N, K, device = "cuda", dtype = torch.float8_e4m3fn)+ tail = slice(N - 512, N)+ W[tail] = (torch.randn(512, K, device = "cuda") * 0.05).to(torch.float8_e4m3fn)+ S = torch.rand(N, 1, device = "cuda") * 0.01 + 0.001+ assert F.can_use_fp8_rowwise_gemv(X, W, S)+ out = F.fp8_rowwise_gemv(X, W, S)+ ref = F.fp8_rowwise_gemv(X, W[tail].contiguous(), S[tail].contiguous())+ torch.cuda.synchronize()+ assert torch.equal(out[..., tail], ref)diff --git a/unsloth/kernels/fp8.py b/unsloth/kernels/fp8.pyindex be3858e4eb4..1e2c5c63e96 100644--- a/unsloth/kernels/fp8.py+++ b/unsloth/kernels/fp8.py@@ -485,6 +485,19 @@ def _rocm_fp8e4nv_kernel_supported(device):return arch in ("gfx940", "gfx941", "gfx942", "gfx950")[email protected]_cache(maxsize = None)+def _fp8_gemv_miscompiles(device):+ # Triton 3.3 miscompiles this GEMV on Blackwell (garbage rows at BLOCK_N 4/8); 3.4 is exact.+ if torch.version.hip is not None:+ return False+ try:+ return torch.cuda.get_device_capability(device) >= (10, 0) and Version(+ triton.__version__+ ).release[:2] < (3, 4)+ except Exception:+ return True++@functools.lru_cache(maxsize = None)def _fp8_device_lacks_kernel(device):# A device's capability cannot change, so look it up once. Tests that simulate another@@ -514,9 +527,22 @@ def _fp8_kernel_unsupported(tensor, kernel_dtype = None):@triton.jitdef _fp8_rowwise_gemv_kernel(- x_ptr, w_ptr, s_ptr, y_ptr, N, K, stride_wn, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr+ x_ptr,+ w_ptr,+ s_ptr,+ y_ptr,+ N,+ K,+ stride_wn,+ BLOCK_N: tl.constexpr,+ BLOCK_K: tl.constexpr,+ LONG_INDEXING: tl.constexpr = False,):- offs_n = tl.program_id(0) * BLOCK_N + tl.arange(0, BLOCK_N)+ pid = tl.program_id(0)+ # Widen before the multiply: row * stride_wn overflows int32 past 2^31 weight elements.+ if LONG_INDEXING:+ pid = pid.to(tl.int64)+ offs_n = pid * BLOCK_N + tl.arange(0, BLOCK_N)acc = tl.zeros((BLOCK_N, BLOCK_K), dtype = tl.float32)for k0 in range(0, K, BLOCK_K):offs_k = k0 + tl.arange(0, BLOCK_K)@@ -547,7 +573,7 @@ def can_use_fp8_rowwise_gemv(X, weight, weight_scale):return Falseif torch.is_grad_enabled() and (X.requires_grad or weight.requires_grad):return False- return not _fp8_kernel_unsupported(weight)+ return not _fp8_kernel_unsupported(weight) and not _fp8_gemv_miscompiles(weight.device)def fp8_rowwise_gemv(X, weight, weight_scale):@@ -569,6 +595,7 @@ def fp8_rowwise_gemv(X, weight, weight_scale):weight.stride(0),BLOCK_N = block_n,BLOCK_K = 512,+ LONG_INDEXING = long_indexing(weight),num_warps = 2,enable_fp_fusion = True,)