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.

Run the skinny fp16 hgemm for 9-32 rows on ROCm

YanissAmz60808654c8fc
diff --git a/exllamav3/exllamav3_ext/hgemm.cu b/exllamav3/exllamav3_ext/hgemm.cu
index 7830756..c55355b 100644
--- a/exllamav3/exllamav3_ext/hgemm.cu
+++ b/exllamav3/exllamav3_ext/hgemm.cu
@@ -363,7 +363,8 @@ namespace skinny
constexpr int COLS = 32; // output columns per block (one lane each)
constexpr int WARPS = 8; // warps per block, each a k-sub-slice of the block's k-chunk
constexpr int THREADS = WARPS * 32;
-constexpr int MAX_M = 8;
+constexpr int EXACT_M = 8; // rows served by one exact-M instantiation (and by skinny_cat)
+constexpr int MAX_M = 32; // 9..32 rows run padded instantiations (12/16/24/32), same per-row reduction
constexpr int MAX_N = 128; // above this, let hipblaslt have it
constexpr int K_CHUNK = 128; // k rows per block -> 16 k's per warp, 20 blocks on k=2560
constexpr int MAX_KSPLIT = 64; // k <= 8192
@@ -419,9 +420,14 @@ void skinny_partials_kernel
const int lda,
int* __restrict__ cnt, // ONEPASS: [MAX_N / COLS] tickets
C_T* __restrict__ c, // ONEPASS: output [M, ldc]
- const int ldc
+ const int ldc,
+ const int m_rt // rows really used: M for the exact instantiations (<= 8), <= M for the padded ones
)
{
+ // M > EXACT_M: padded instantiation, rows >= m_rt are skipped. A row's accumulation and reduction order do not
+ // depend on M or m_rt, so rows 9..32 are bit-identical to the same rows in an exact <= 8-row launch.
+ constexpr bool PAD = M > EXACT_M;
+ const int mr = PAD ? m_rt : M;
const int lane = threadIdx.x & 31;
const int warp = threadIdx.x >> 5;
const int col = blockIdx.x * COLS + lane;
@@ -450,7 +456,8 @@ void skinny_partials_kernel
{
#pragma unroll
for (int i = 0; i < M; ++i)
- acc[i] = fmaf(__half2float(a[(size_t) i * lda + kk]), bv[j], acc[i]);
+ if (!PAD || i < mr)
+ acc[i] = fmaf(__half2float(a[(size_t) i * lda + kk]), bv[j], acc[i]);
}
}
}
@@ -462,10 +469,11 @@ void skinny_partials_kernel
if (warp == 0 && active)
{
- float* out = part + ((size_t) blockIdx.y * M) * MAX_N;
+ float* out = part + ((size_t) blockIdx.y * mr) * MAX_N;
#pragma unroll
for (int i = 0; i < M; ++i)
{
+ if (PAD && i >= mr) continue;
float s = 0.0f;
#pragma unroll
for (int w = 0; w < WARPS; ++w) s += red[w][i][lane];
@@ -487,14 +495,14 @@ void skinny_partials_kernel
if (!last_s) return;
__threadfence();
const int ksplit = gridDim.y;
- for (int idx = threadIdx.x; idx < M * COLS; idx += THREADS)
+ for (int idx = threadIdx.x; idx < mr * COLS; idx += THREADS)
{
const int i = idx / COLS;
const int cc = blockIdx.x * COLS + idx % COLS;
if (cc >= n) continue;
float s = 0.0f;
for (int y = 0; y < ksplit; ++y)
- s += __builtin_nontemporal_load(&part[((size_t) y * M + i) * MAX_N + cc]);
+ s += __builtin_nontemporal_load(&part[((size_t) y * mr + i) * MAX_N + cc]);
if constexpr (std::is_same_v<C_T, float>)
c[(size_t) i * ldc + cc] = s;
else
@@ -532,12 +540,16 @@ template <bool ONEPASS, typename C_T>
static void launch_partials(int m, const half* a, const half* b, float* part, int k, int n, int lda,
dim3 grid, cudaStream_t stream, int* cnt = nullptr, C_T* c = nullptr, int ldc = 0)
{
- #define SK_CASE(MM) case MM: skinny_partials_kernel<MM, ONEPASS, C_T><<<grid, THREADS, 0, stream>>>(a, b, part, k, n, lda, cnt, c, ldc); break;
+ #define SK_CASE(MM) case MM: skinny_partials_kernel<MM, ONEPASS, C_T><<<grid, THREADS, 0, stream>>>(a, b, part, k, n, lda, cnt, c, ldc, m); break;
+ #define SK_PAD(MM, LO, HI) if (m >= LO && m <= HI) { skinny_partials_kernel<MM, ONEPASS, C_T><<<grid, THREADS, 0, stream>>>(a, b, part, k, n, lda, cnt, c, ldc, m); return; }
switch (m)
{
SK_CASE(1) SK_CASE(2) SK_CASE(3) SK_CASE(4) SK_CASE(5) SK_CASE(6) SK_CASE(7) SK_CASE(8)
- default: break;
+ default:
+ SK_PAD(12, 9, 12) SK_PAD(16, 13, 16) SK_PAD(24, 17, 24) SK_PAD(32, 25, 32)
+ break;
}
+ #undef SK_PAD
#undef SK_CASE
}
@@ -565,6 +577,19 @@ static bool enabled()
return cached == 1;
}
+// Rows above this are left to the caller's GEMM (EXL3_HIP_SKINNY_MAX_M, default MAX_M; 8 = the old behaviour).
+static int max_rows()
+{
+ static int cached = -1;
+ if (cached < 0)
+ {
+ const char* e = getenv("EXL3_HIP_SKINNY_MAX_M");
+ int v = e && *e ? atoi(e) : MAX_M;
+ cached = v < 1 ? 1 : (v > MAX_M ? MAX_M : v);
+ }
+ return cached;
+}
+
// true if handled
static bool try_launch(const at::Tensor& a, const at::Tensor& b, at::Tensor& c, cudaStream_t stream)
{
@@ -575,7 +600,7 @@ static bool try_launch(const at::Tensor& a, const at::Tensor& b, at::Tensor& c,
const int k = a.size(-1);
const int m = a.numel() / k;
const int n = b.size(-1);
- if (m < 1 || m > MAX_M || n < 1 || n > MAX_N || k < 1) return false;
+ if (m < 1 || m > max_rows() || n < 1 || n > MAX_N || k < 1) return false;
const int ksplit = (k + K_CHUNK - 1) / K_CHUNK;
if (ksplit > MAX_KSPLIT) return false;
if (a.stride(-1) != 1 || c.stride(-1) != 1) return false;
@@ -790,14 +815,14 @@ static void skinny_cat_impl(at::Tensor a, const at::Tensor* b, const std::vector
seg.ldw[s] = n;
}
}
- TORCH_CHECK(m >= 1 && m <= MAX_M && n >= 1 && n <= CAT_MAX_N, "skinny_cat: shape out of range");
+ TORCH_CHECK(m >= 1 && m <= EXACT_M && n >= 1 && n <= CAT_MAX_N, "skinny_cat: shape out of range");
const int ksplit = (k + K_CHUNK - 1) / K_CHUNK;
TORCH_CHECK(ksplit <= MAX_KSPLIT, "skinny_cat: k too large");
const int dev = a.device().index();
TORCH_CHECK(dev >= 0 && dev < NUM_DEV, "skinny_cat: device");
if (!g_cat_partials[dev])
- cuda_check(cudaMalloc((void**) &g_cat_partials[dev], (size_t) MAX_KSPLIT * MAX_M * CAT_MAX_N * sizeof(float)));
+ cuda_check(cudaMalloc((void**) &g_cat_partials[dev], (size_t) MAX_KSPLIT * EXACT_M * CAT_MAX_N * sizeof(float)));
if (!g_cat_counters[dev])
{
cuda_check(cudaMalloc((void**) &g_cat_counters[dev], (CAT_MAX_N / COLS) * sizeof(int)));
diff --git a/exllamav3/modules/quant/fp16.py b/exllamav3/modules/quant/fp16.py
index c31c0ec..2418859 100644
--- a/exllamav3/modules/quant/fp16.py
+++ b/exllamav3/modules/quant/fp16.py
@@ -10,6 +10,15 @@ _f32_via_f16_min_rows = int(_os.environ.get("EXL3_HIP_F32OUT_VIA_F16_MIN_ROWS",
# split-K GEMV first (M <= 8, N <= 128) and falls back to the same GEMM otherwise
_hip = bool(torch.version.hip)
_f16_small_m_hgemm = _os.environ.get("EXL3_HIP_F16_SMALL_M_HGEMM", "1") != "0" and bool(torch.version.hip)
+# Multi-user verify (rows = users x (depth + 1)) reaches 9..32 rows: the skinny kernel runs padded 12/16/24/32-row
+# instantiations whose per-row reduction is identical to the <= 8-row ones, so these rows stay bit-identical to a
+# solo decode instead of falling to hipBLASLt. N > 128 keeps the GEMM (skinny does not cover it).
+_f16_small_m_rows = max(8, int(_os.environ.get("EXL3_HIP_F16_SMALL_M_ROWS", "32"))) if _f16_small_m_hgemm else 8
+_f16_small_m_max_n = 128
+
+
+def _skinny_rows_ok(rows: int, n: int) -> bool:
+ return rows <= 8 or (rows <= _f16_small_m_rows and n <= _f16_small_m_max_n)
from ...util.tensor import to2
from ...util import first_not_none
@@ -107,10 +116,11 @@ class LinearFP16:
# multiple of 4 KiB (hidden 4096 = 8192 B); one padded copy of x runs the same product bit-exactly 3-4x faster
from .exl3 import pad_copy_in
ext.hgemm(pad_copy_in(x, x.shape[1]), weight, y)
- elif dtype == x.dtype and not (_f16_small_m_hgemm and x.dtype == torch.half and x.shape[0] <= 8):
+ elif dtype == x.dtype and not (_f16_small_m_hgemm and x.dtype == torch.half and _skinny_rows_ok(x.shape[0], self.out_features)):
torch.matmul(x, weight, out = y)
elif (_f32_via_f16 and dtype == torch.float and x.dtype == torch.half
- and x.shape[0] >= _f32_via_f16_min_rows):
+ and x.shape[0] >= _f32_via_f16_min_rows
+ and not (_f16_small_m_hgemm and _skinny_rows_ok(x.shape[0], self.out_features))):
# gfx1151: hipblaslt's fp16-in/fp32-out kernels run at ~6 TFLOP/s vs ~34 for
# fp16-out. Compute narrow, widen after. See exl3.py for the measurement.
yh = torch.empty(y.shape, dtype = torch.half, device = y.device)
diff --git a/tools/decode/skinny_rows_bench.py b/tools/decode/skinny_rows_bench.py
new file mode 100644
index 0000000..1ae8ffa
--- /dev/null
+++ b/tools/decode/skinny_rows_bench.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+"""ROCm skinny fp16 hgemm at 1..32 rows (ext.hgemm, N <= 128).
+check: row j of the R-row product == the same row alone (R = 1), bitwise, for fp16 and fp32 outputs.
+time: us per call for ext.hgemm vs torch.matmul (hipBLASLt) at the same shape. Needs EXL3_ROOT=<worktree>."""
+import os, sys, argparse
+ap = argparse.ArgumentParser()
+ap.add_argument("--rows", default="1,2,4,8,9,10,12,13,16,17,20,24,25,28,32")
+ap.add_argument("--shapes", default="4096x128,4096x64,2048x128,2560x32,6144x128,4096x16")
+ap.add_argument("--reps", type=int, default=100)
+a = ap.parse_args()
+sys.path.insert(0, os.environ["EXL3_ROOT"])
+import torch
+from exllamav3.ext import exllamav3_ext as ext
+dev = torch.device("cuda:0")
+g = torch.Generator(device=dev).manual_seed(7)
+rows = [int(r) for r in a.rows.split(",")]
+bad = 0
+for sh in a.shapes.split(","):
+ K, N = (int(v) for v in sh.split("x"))
+ w = (torch.randn(K, N, device=dev, generator=g) * 0.05).half()
+ x = torch.randn(32, K, device=dev, generator=g).half()
+ for odt in (torch.half, torch.float):
+ solo = []
+ for j in range(32):
+ y = torch.empty(1, N, dtype=odt, device=dev); ext.hgemm(x[j:j + 1].contiguous(), w, y); solo.append(y)
+ solo = torch.cat(solo)
+ for R in rows:
+ y = torch.empty(R, N, dtype=odt, device=dev); ext.hgemm(x[:R].contiguous(), w, y)
+ torch.cuda.synchronize()
+ ok = torch.equal(y, solo[:R])
+ if not ok:
+ bad += 1
+ print(f"MISMATCH K={K} N={N} out={odt} R={R} rows_bad={(y != solo[:R]).any(1).nonzero().flatten().tolist()}", flush=True)
+ for R in rows:
+ xr = x[:R].contiguous(); y = torch.empty(R, N, dtype=torch.half, device=dev)
+ def t(fn):
+ for _ in range(10): fn()
+ torch.cuda.synchronize(); s = torch.cuda.Event(enable_timing=True); e = torch.cuda.Event(enable_timing=True)
+ s.record()
+ for _ in range(a.reps): fn()
+ e.record(); torch.cuda.synchronize(); return s.elapsed_time(e) * 1000 / a.reps
+ us_s = t(lambda: ext.hgemm(xr, w, y)); us_m = t(lambda: torch.matmul(xr, w, out=y))
+ print(f"K={K} N={N} R={R:2d} skinny {us_s:7.1f} us matmul {us_m:7.1f} us", flush=True)
+print("MISMATCHES", bad, "OK" if bad == 0 else "FAIL", flush=True)