Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

FP8 decode GEMV in C++ for ROCm (#202)

Yaniss Amazouzc3df002fccee
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index 6402a1a..75b0743 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -613,6 +613,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
py::arg("x"), py::arg("qb"));
m.def("fq_gemv_iq2_xxs_q8", &fq_gemv_iq2_xxs_q8, "fq_gemv_iq2_xxs_q8",
py::arg("qb"), py::arg("packed"), py::arg("out"));
+ m.def("fq_gemv_fp8", &fq_gemv_fp8, "fq_gemv_fp8",
+ py::arg("x"), py::arg("q"), py::arg("s"), py::arg("out"), py::arg("s_cols"), py::arg("bo"), py::arg("bi"), py::arg("grid"));
m.def("fq_gemv_nvfp4_q8", &fq_gemv_nvfp4_q8, "fq_gemv_nvfp4_q8",
py::arg("qb"), py::arg("packed"), py::arg("scales"), py::arg("global_scale"), py::arg("out"));
m.def("fq_gemv_q8_0_q8", &fq_gemv_q8_0_q8, "fq_gemv_q8_0_q8",
diff --git a/exllamav3/exllamav3_ext/build_config.py b/exllamav3/exllamav3_ext/build_config.py
index 0a76a92..7a86e10 100644
--- a/exllamav3/exllamav3_ext/build_config.py
+++ b/exllamav3/exllamav3_ext/build_config.py
@@ -12,7 +12,7 @@ ROCM_EXCLUDE_DIRS = {'parallel', 'comp_units', 'foreign_quant'}
# Other comp_units remain excluded because they implement unported MoE/GEMM paths.
ROCM_ALLOW_PREFIXES = (
'foreign_quant/fq_dequant.cu', 'foreign_quant/fq_dequant_kq.cu', 'foreign_quant/fq_gemv.cu',
- 'foreign_quant/fq_gemv_kq.cu', 'foreign_quant/fq_gemv_q8.cu', 'foreign_quant/fq_mmvq.cu', 'foreign_quant/fq_moe_kq.cu', 'foreign_quant/fq_gemm.cu',
+ 'foreign_quant/fq_gemv_kq.cu', 'foreign_quant/fq_gemv_q8.cu', 'foreign_quant/fq_gemv_fp8.cu', 'foreign_quant/fq_mmvq.cu', 'foreign_quant/fq_moe_kq.cu', 'foreign_quant/fq_gemm.cu',
'quant/comp_units/exl3_gemv_int8_inst_',
'quant/comp_units/quantize_tiles_inst_',
)
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_api.h b/exllamav3/exllamav3_ext/foreign_quant/fq_api.h
index 2792550..492c6d4 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_api.h
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_api.h
@@ -27,6 +27,8 @@ void fq_gemv_iq2_xxs_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor ou
void fq_gemv_nvfp4_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor scales,
double global_scale, torch::Tensor out);
void fq_gemv_q8_0_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);
+// FP8 E4M3 decode GEMV (fq_gemv_fp8.cu): x half [M, K], q uint8 [N, K], s float32 [N] (per row) or [ceil(N/bo), s_cols] (grid), out float32 [M, N].
+void fq_gemv_fp8(torch::Tensor x, torch::Tensor q, torch::Tensor s, torch::Tensor out, int64_t s_cols, int64_t bo, int64_t bi, bool grid);
// q8_1-activation grouped MoE (fq_moe_q8.cu), same args/contract as above.
bool fq_use_q8moe();
void fq_moe_iq2xxs_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_fp8.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_fp8.cu
new file mode 100644
index 0000000..4a62b97
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_fp8.cu
@@ -0,0 +1,147 @@
+// FP8 (E4M3, stored as is) decode GEMV in C++ (CUDA and HIP, wave32 on RDNA). Replaces the Triton _gemv_fp8 for 1..16 activation rows:
+// the Triton tile read 64 rows x 128 B per iteration and streamed DRAM at 42-55 GB/s on gfx1151 once the weights fall out of the 32 MB
+// MALL (every served step). Here one warp owns one output column and walks its K bytes in 16-byte lanes (512 contiguous bytes per
+// warp step = long DRAM bursts), each lane keeping U loads in flight (BOLT_FP8_U1 for 1 x-row, BOLT_FP8_UM for 2..16 x-rows in groups
+// of 4); each weight chunk is decoded once for all the rows of its group.
+// E4M3 -> fp16 by the same bit move as quant/fp8.py (sign | exponent-mantissa << 7, x 256), fp32 accumulation; scales per output row
+// (s[N], applied at the end) or per [bo x bi] block (s[ceil(N/bo), s_cols], bi % 16 == 0, applied per 16-byte chunk) as the Triton kernel.
+#include <cuda_fp16.h>
+#include <cstdint>
+#include <cstdlib>
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <ATen/cuda/CUDAContext.h>
+#include "../util.h"
+#include "fq_api.h"
+
+#if defined(USE_ROCM)
+#define __shfl_xor_sync(mask, var, ...) __shfl_xor(var, __VA_ARGS__)
+#endif
+
+#define FQ_FP8_WARP 32
+#define FQ_FP8_WARPS 4
+
+__device__ __forceinline__ float fq_e4m3_f(uint32_t b)
+{
+ uint16_t h = (uint16_t)(((b & 0x80u) << 8) | ((b & 0x7Fu) << 7));
+ return __half2float(__ushort_as_half(h)) * 256.0f;
+}
+
+template <int MR, int U>
+__global__ void fq_gemv_fp8_kernel(const __half* __restrict__ x, const uint8_t* __restrict__ q, const float* __restrict__ s,
+ float* __restrict__ out, int M, int N, int K, int s_cols, int bo, int bi, bool grid)
+{
+ // One warp per output column; each lane issues U 16-byte weight loads (chunks k, k + 512, ...) before it consumes them, so a lane
+ // keeps U requests in flight instead of one; each weight chunk is decoded once and dotted against up to MR x-rows.
+ int lane = threadIdx.x % FQ_FP8_WARP;
+ int n = blockIdx.x * FQ_FP8_WARPS + threadIdx.x / FQ_FP8_WARP;
+ int m0 = blockIdx.y * MR;
+ int mc = min(MR, M - m0);
+ if (n >= N) return; // whole warp leaves together (no block-wide sync below)
+
+ const uint8_t* wr = q + (int64_t)n * K;
+ const float* srow = grid ? s + (int64_t)(n / bo) * s_cols : nullptr;
+ constexpr int STEP = FQ_FP8_WARP * 16;
+ float acc[MR];
+ #pragma unroll
+ for (int r = 0; r < MR; r++) acc[r] = 0.0f;
+
+ for (int k0 = lane * 16; k0 < K; k0 += STEP * U)
+ {
+ uint4 wv4[U];
+ #pragma unroll
+ for (int u = 0; u < U; u++)
+ if (k0 + u * STEP < K) wv4[u] = *reinterpret_cast<const uint4*>(wr + k0 + u * STEP);
+ #pragma unroll
+ for (int u = 0; u < U; u++)
+ {
+ int k = k0 + u * STEP;
+ if (k >= K) break;
+ float wf[16];
+ uint32_t wv[4] = {wv4[u].x, wv4[u].y, wv4[u].z, wv4[u].w};
+ #pragma unroll
+ for (int j = 0; j < 4; j++)
+ {
+ #pragma unroll
+ for (int b = 0; b < 4; b++) wf[j * 4 + b] = fq_e4m3_f((wv[j] >> (8 * b)) & 0xFFu);
+ }
+ float sc = grid ? srow[k / bi] : 1.0f;
+ #pragma unroll
+ for (int r = 0; r < MR; r++)
+ {
+ if (r < mc)
+ {
+ const uint4* xr = reinterpret_cast<const uint4*>(x + (int64_t)(m0 + r) * K + k);
+ uint4 xa = xr[0], xb = xr[1];
+ const __half2* h2a = reinterpret_cast<const __half2*>(&xa);
+ const __half2* h2b = reinterpret_cast<const __half2*>(&xb);
+ float sum = 0.0f;
+ #pragma unroll
+ for (int j = 0; j < 4; j++)
+ {
+ float2 fa = __half22float2(h2a[j]);
+ float2 fb = __half22float2(h2b[j]);
+ sum = fmaf(wf[2 * j], fa.x, sum);
+ sum = fmaf(wf[2 * j + 1], fa.y, sum);
+ sum = fmaf(wf[8 + 2 * j], fb.x, sum);
+ sum = fmaf(wf[8 + 2 * j + 1], fb.y, sum);
+ }
+ acc[r] = fmaf(sum, sc, acc[r]);
+ }
+ }
+ }
+ }
+ #pragma unroll
+ for (int r = 0; r < MR; r++)
+ {
+ float v = acc[r];
+ #pragma unroll
+ for (int o = FQ_FP8_WARP / 2; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o, FQ_FP8_WARP);
+ if (lane == 0 && r < mc) out[(int64_t)(m0 + r) * N + n] = grid ? v : v * s[n];
+ }
+}
+
+template <int MR, int U>
+static void fq_gemv_fp8_launch(const __half* xp, torch::Tensor q, torch::Tensor s, torch::Tensor out, int M, int N, int K,
+ int s_cols, int bo, int bi, bool grid, cudaStream_t stream)
+{
+ dim3 g((N + FQ_FP8_WARPS - 1) / FQ_FP8_WARPS, (M + MR - 1) / MR);
+ fq_gemv_fp8_kernel<MR, U><<<g, dim3(FQ_FP8_WARP * FQ_FP8_WARPS), 0, stream>>>(xp, q.data_ptr<uint8_t>(), s.data_ptr<float>(),
+ out.data_ptr<float>(), M, N, K, s_cols, bo, bi, grid);
+}
+
+static int fq_fp8_env(const char* name, int dflt)
+{
+ const char* e = getenv(name);
+ return e ? atoi(e) : dflt;
+}
+
+void fq_gemv_fp8(torch::Tensor x, torch::Tensor q, torch::Tensor s, torch::Tensor out, int64_t s_cols, int64_t bo, int64_t bi, bool grid)
+{
+ const at::cuda::OptionalCUDAGuard device_guard(x.device());
+ TORCH_CHECK(x.dtype() == torch::kHalf && x.dim() == 2 && x.is_contiguous(), "fq_gemv_fp8: x must be contiguous half [M, K]");
+ TORCH_CHECK(q.dtype() == torch::kUInt8 && q.dim() == 2 && q.is_contiguous(), "fq_gemv_fp8: q must be contiguous uint8 [N, K]");
+ TORCH_CHECK(s.dtype() == torch::kFloat && s.is_contiguous(), "fq_gemv_fp8: s must be contiguous float32");
+ TORCH_CHECK(out.dtype() == torch::kFloat && out.is_contiguous(), "fq_gemv_fp8: out must be contiguous float32 [M, N]");
+ int M = x.size(0), K = x.size(1), N = q.size(0);
+ TORCH_CHECK(q.size(1) == K && out.size(0) == M && out.size(1) == N, "fq_gemv_fp8: shape mismatch");
+ TORCH_CHECK(K % 16 == 0 && (!grid || bi % 16 == 0), "fq_gemv_fp8: K and the scale block width must be multiples of 16");
+ TORCH_CHECK(((uintptr_t)x.data_ptr() % 16) == 0 && ((uintptr_t)q.data_ptr() % 16) == 0, "fq_gemv_fp8: x and q must be 16-byte aligned");
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ const __half* xp = reinterpret_cast<const __half*>(x.data_ptr());
+ static const int u1 = fq_fp8_env("BOLT_FP8_U1", 4); // weight loads in flight per lane, 1 x-row
+ static const int um = fq_fp8_env("BOLT_FP8_UM", 4); // same, 2..16 x-rows (groups of 4)
+ int sc = (int)s_cols, ibo = (int)bo, ibi = (int)bi;
+ if (M == 1)
+ {
+ if (u1 >= 4) fq_gemv_fp8_launch<1, 4>(xp, q, s, out, M, N, K, sc, ibo, ibi, grid, stream);
+ else if (u1 >= 2) fq_gemv_fp8_launch<1, 2>(xp, q, s, out, M, N, K, sc, ibo, ibi, grid, stream);
+ else fq_gemv_fp8_launch<1, 1>(xp, q, s, out, M, N, K, sc, ibo, ibi, grid, stream);
+ }
+ else
+ {
+ if (um >= 4) fq_gemv_fp8_launch<4, 4>(xp, q, s, out, M, N, K, sc, ibo, ibi, grid, stream);
+ else if (um >= 2) fq_gemv_fp8_launch<4, 2>(xp, q, s, out, M, N, K, sc, ibo, ibi, grid, stream);
+ else fq_gemv_fp8_launch<4, 1>(xp, q, s, out, M, N, K, sc, ibo, ibi, grid, stream);
+ }
+}
diff --git a/exllamav3/modules/quant/fp8.py b/exllamav3/modules/quant/fp8.py
index f55376d..50a4599 100644
--- a/exllamav3/modules/quant/fp8.py
+++ b/exllamav3/modules/quant/fp8.py
@@ -1,13 +1,15 @@
"""FP8 (E4M3) linears served as stored: per-row / per-tensor scale (`weight_scale`) or the 2D block grid (`weight_scale_inv`,
DeepSeek / Qwen-FP8 / GLM / MiniMax layout). One byte per weight is read instead of the two of the fp16 dequant.
-Decode GEMV (<= MAX_ROWS rows): one Triton kernel for ROCm and CUDA (no extension build). E4M3 -> fp16 is exact by bit placement:
+Decode GEMV (<= MAX_ROWS rows): the C++ fq_gemv_fp8 on ROCm when the extension has it, else (and on CUDA) one Triton kernel. E4M3 -> fp16 is exact by bit placement:
half(bits = sign << 8 | (b & 0x7F) << 7) * 256 (normals and subnormals; the 0x7F NaN code is never stored by real checkpoints).
With the block grid, BN rows of a tile share one block row and each BK chunk one block column, so the block scale is one
scalar per (tile, chunk) applied to the chunk's partial sum. Wider batches: fp16 dequant of the matrix + matmul.
"""
from __future__ import annotations
+import os
+
import torch
import triton
import triton.language as tl
@@ -158,11 +160,33 @@ def moe_fused(h, tabs, sel, wts, I, K, grid, block, S, sc_gu, sc_d):
return y
+def _ext_gemv():
+ """The C++ FP8 GEMV (fq_gemv_fp8.cu: one warp per output column, 16-byte lanes = long DRAM bursts), or None (old build /
+ the Triton kernel below). Default on ROCm only: there Triton streamed cold weights at 42-55 GB/s (gfx1151) vs 75-136 for the
+ C++ kernel; on CUDA Triton already reads at 640-740 GB/s (RTX 3090) and beats it at 4-8 rows. BOLT_FP8_GEMV_EXT=1 / 0 forces."""
+ if os.environ.get("BOLT_FP8_GEMV_EXT", "1" if torch.version.hip else "0") == "0":
+ return None
+ try:
+ from ...ext import exllamav3_ext as ext
+ return getattr(ext, "fq_gemv_fp8", None)
+ except Exception:
+ return None
+
+
+_EXT = []
+
+
def gemv(x: torch.Tensor, q: torch.Tensor, s: torch.Tensor, grid: bool, block: tuple[int, int]) -> torch.Tensor:
"""x half [R, K] (R <= MAX_ROWS), q uint8 [N, K], s float32 [N] (per row) or [ceil(N/bo), ceil(K/bi)] (grid) -> float32 [R, N]."""
R, K = x.shape
N = q.shape[0]
y = torch.empty((R, N), dtype=torch.float32, device=x.device)
+ if not _EXT:
+ _EXT.append(_ext_gemv())
+ f = _EXT[0]
+ if f is not None and K % 16 == 0 and (not grid or block[1] % 16 == 0) and x.data_ptr() % 16 == 0 and q.data_ptr() % 16 == 0:
+ f(x, q, s, y, s.shape[1] if grid else 1, block[0], block[1], grid)
+ return y
_gemv_fp8[(triton.cdiv(N, BN),)](x, q, s, y, R, K, N, s.shape[1] if grid else 1, GRID=grid, BO=block[0], BI=block[1],
BN=BN, BK=BK, RP=16, num_warps=4)
return y
diff --git a/tests/test_fp8_gemv_ext.py b/tests/test_fp8_gemv_ext.py
new file mode 100644
index 0000000..ce4e43e
--- /dev/null
+++ b/tests/test_fp8_gemv_ext.py
@@ -0,0 +1,39 @@
+"""C++ FP8 decode GEMV (fq_gemv_fp8.cu) vs the fp16 dequant reference and the Triton kernel it replaces: 1, 3 and 16 activation rows,
+per-row and 128x128 block-grid scales, ragged N. Needs a GPU and an extension built with fq_gemv_fp8."""
+import pytest
+import torch
+
+pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
+
+
+def _ext():
+ from exllamav3.ext import exllamav3_ext as ext
+ if not hasattr(ext, "fq_gemv_fp8"):
+ pytest.skip("extension built without fq_gemv_fp8")
+ return ext
+
+
[email protected]("rows", [1, 3, 16])
[email protected]("grid", [False, True])
+def test_fq_gemv_fp8_matches_dequant_and_triton(rows, grid, monkeypatch):
+ ext = _ext()
+ from exllamav3.modules.quant import fp8 as F
+ torch.manual_seed(0)
+ N, K = 1000, 4096 # ragged N (not a multiple of the 4 columns per block)
+ q = torch.randint(0, 0x7E, (N, K), dtype=torch.uint8, device="cuda")
+ q[:, ::7] |= 0x80 # negative codes too
+ block = (128, 128) if grid else (1, 1)
+ s = (torch.rand((-(-N // 128), K // 128) if grid else (N,), device="cuda") * 0.01 + 1e-3).float()
+ x = torch.randn((rows, K), dtype=torch.half, device="cuda")
+ ref = x.float() @ F.dequant(q, s, grid, block).float().t()
+ y = torch.empty((rows, N), dtype=torch.float32, device="cuda")
+ ext.fq_gemv_fp8(x, q, s, y, s.shape[1] if grid else 1, block[0], block[1], grid)
+ rel = float((y - ref).abs().max() / ref.abs().max())
+ assert rel < 2e-3, rel
+ monkeypatch.setenv("BOLT_FP8_GEMV_EXT", "0")
+ monkeypatch.setattr(F, "_EXT", [])
+ tri = F.gemv(x, q, s, grid, block)
+ assert float((y - tri).abs().max() / tri.abs().max()) < 2e-3
+ monkeypatch.setenv("BOLT_FP8_GEMV_EXT", "1")
+ monkeypatch.setattr(F, "_EXT", [])
+ assert torch.equal(F.gemv(x, q, s, grid, block), y) # the module entry takes the C++ kernel