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.

Multi-user GGUF MoE decode on CUDA, version 1.8.18 (#196)

Yaniss Amazouz84514fc6eb91
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_q8.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_q8.cu
index 2078e87..834a841 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_q8.cu
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv_q8.cu
@@ -8,6 +8,7 @@
// shared-memory reduction, __fmul_rn/__fadd_rn + fq_dp4a only).
#include <cuda_fp16.h>
#include <map>
+#include <cstdlib>
#include <torch/extension.h>
#include <c10/cuda/CUDAGuard.h>
#include <ATen/cuda/CUDAContext.h>
@@ -241,6 +242,82 @@ __global__ void fq_gemv_q8_q8_kernel(const uint8_t* __restrict__ aqb,
}
}
+// Multi-row Q8_0 q8 dot (BOLT_FQ_Q8_MROWS, default on for 2..16 x-rows): one block per column n, rows
+// m0 .. m0 + mc - 1 (mc <= 8, grid.y = row groups). Each weight 32-block is loaded once and dotted against
+// every row. Per row: same chunk loop per thread and same sequential reduction as fq_gemv_q8_q8_kernel,
+// so each output is bit-identical to the 1-row kernel.
+template <typename OUT>
+__global__ void fq_gemv_q8_q8_mrows_kernel(const uint8_t* __restrict__ aqb,
+ const uint8_t* __restrict__ packed,
+ OUT* __restrict__ out,
+ int M, int N, int K, int64_t packed_stride,
+ int64_t qb_stride)
+{
+ constexpr int MR = 8;
+ int n = blockIdx.x;
+ int m0 = blockIdx.y * MR;
+ int mc = min(MR, M - m0);
+ int tid = threadIdx.x;
+ int nt = blockDim.x;
+
+ extern __shared__ float red[]; // [MR][nt]
+
+ float acc[MR];
+ #pragma unroll
+ for (int r = 0; r < MR; r++) acc[r] = 0.0f;
+
+ const uint8_t* wr = packed + (int64_t)n * packed_stride;
+ int nchunks = K / 32;
+ for (int c = tid; c < nchunks; c += nt)
+ {
+ const uint8_t* blk = wr + (size_t)c * FQ_Q8_0_BYTES;
+ __half dwh;
+ memcpy(&dwh, blk, 2);
+ float dw = __half2float(dwh);
+ const uint16_t* w16 = reinterpret_cast<const uint16_t*>(blk + 2);
+ int32_t w4[8];
+ #pragma unroll
+ for (int j2 = 0; j2 < 8; j2++)
+ w4[j2] = (int32_t)(w16[j2 * 2] | ((uint32_t)w16[j2 * 2 + 1] << 16));
+ #pragma unroll
+ for (int r = 0; r < MR; r++)
+ {
+ if (r < mc)
+ {
+ const uint8_t* ab = aqb + (int64_t)(m0 + r) * qb_stride + (size_t)c * FQ_Q8_1_BYTES;
+ __half dah;
+ memcpy(&dah, ab, 2);
+ float da = __half2float(dah);
+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(ab + 4);
+ int sumi = 0;
+ #pragma unroll
+ for (int j2 = 0; j2 < 8; j2++)
+ sumi = fq_dp4a(w4[j2], aq32[j2], sumi);
+ acc[r] = __fadd_rn(acc[r], __fmul_rn(__fmul_rn(dw, da), (float)sumi));
+ }
+ }
+ }
+ #pragma unroll
+ for (int r = 0; r < MR; r++) red[r * nt + tid] = acc[r];
+ __syncthreads();
+ if (tid < mc)
+ {
+ float s = 0.0f;
+ for (int l = 0; l < nt; l++)
+ s = __fadd_rn(s, red[tid * nt + l]);
+ if constexpr (std::is_same<OUT, __half>::value)
+ out[(int64_t)(m0 + tid) * N + n] = __float2half_rn(s);
+ else
+ out[(int64_t)(m0 + tid) * N + n] = s;
+ }
+}
+
+static bool fq_q8_mrows_on()
+{
+ static const int on = [] { const char* e = getenv("BOLT_FQ_Q8_MROWS"); return e ? atoi(e) : 1; }();
+ return on != 0;
+}
+
// Cached global q8_1 scratch: [M][nb32(K)] 36B blocks. One buffer serves
// all layers of a decode step (single stream: no two dots live at once;
// allocated on first use = outside CUDA-graph capture, like act_cache).
@@ -364,11 +441,17 @@ void fq_gemv_q8_0_q8(torch::Tensor qb, torch::Tensor packed, torch::Tensor out)
size_t shmem = (size_t)nt * sizeof(float);
at::cuda::CUDAGuard guard(qb.device());
auto stream = at::cuda::getCurrentCUDAStream().stream();
+ bool mrows = M >= 2 && M <= 16 && fq_q8_mrows_on();
auto launch = [&](auto* op)
{
- fq_gemv_q8_q8_kernel<std::decay_t<decltype(*op)>> <<<M * N, nt, shmem, stream>>>(
- qb.data_ptr<uint8_t>(), packed.data_ptr<uint8_t>(),
- op, M, N, K, pstride, qb_stride);
+ if (mrows)
+ fq_gemv_q8_q8_mrows_kernel<std::decay_t<decltype(*op)>> <<<dim3(N, (M + 7) / 8), nt, 8 * shmem, stream>>>(
+ qb.data_ptr<uint8_t>(), packed.data_ptr<uint8_t>(),
+ op, M, N, K, pstride, qb_stride);
+ else
+ fq_gemv_q8_q8_kernel<std::decay_t<decltype(*op)>> <<<M * N, nt, shmem, stream>>>(
+ qb.data_ptr<uint8_t>(), packed.data_ptr<uint8_t>(),
+ op, M, N, K, pstride, qb_stride);
};
if (out.dtype() == torch::kHalf)
launch(reinterpret_cast<__half*>(out.data_ptr<at::Half>()));
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index 99a7229..9dcc932 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -65,9 +65,12 @@ UNION_ROWS = max(MAX_BSZN, ROW_INV_MAX_ROWS) if torch.version.hip else MAX_BSZN
# EXL3_MOE_UNION_BATCH=1: the R-row union decode also serves plain multi-user decode steps (2..8 rows), not only DFlash verify. Without it a
# HIP build with no exl3_mgemm / exl3_moe (Strix) runs every multi-row decode step through the per-expert torch loop.
_UNION_BATCH = os.environ.get("EXL3_MOE_UNION_BATCH", "0") != "0"
-# Rows (users / session slots) the grouped KQ MoE kernel takes in one call: top-8 x 32 rows = 256 assignments; above it the
-# per-expert / prefill paths amortize each expert over its rows. MCPM_FQ_GROUPED_MAX_ROWS=1 is the old batch-1-only gate.
-FQ_GROUPED_MAX_ROWS = int(os.environ.get("MCPM_FQ_GROUPED_MAX_ROWS", "32"))
+# Rows (users / session slots) the grouped KQ MoE kernel takes in one call; above it the per-expert / prefill paths amortize
+# each expert over its rows. MCPM_FQ_GROUPED_MAX_ROWS=1 is the old batch-1-only gate. CUDA default 128: a short new prompt
+# (<= 128 tokens, as when users join a multi-user batch) goes through the grouped kernel instead of dequantising every expert for
+# a GEMM (RTX 3090, 35B-A3B UD-Q4_K_XL at 8 users: N4 +16 %, N8 +18 %). HIP keeps 32 (not measured there).
+FQ_GROUPED_MAX_ROWS = int(os.environ.get("MCPM_FQ_GROUPED_MAX_ROWS", "32" if torch.version.hip else "128"))
+_FQ_KQ_PARTIAL: dict = {} # (device, rows * top-k, hidden) -> shared grouped-MoE partial-sum scratch
# Row capacity of the fused decode kernels (exl3_moe_coop): up to this many token rows (bounded by 256 slots = rows * top_k) take
# them instead of the prefill-shaped exl3_moe kernel or row chunks; rows <= MAX_BSZN run exactly as before. The kernels group the
# slots by expert, so each picked expert is decoded once for all of its rows. CUDA only; EXL3_MOE_COOP_ROWS=8 restores the old cap
@@ -1982,7 +1985,11 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
# buffers sized once for the largest row count (stable pointers for CUDA graphs); the kernel gets row-prefix views
if getattr(self, "_fq_kq_partial", None) is None or \
self._fq_kq_partial.shape != (FQ_GROUPED_MAX_ROWS * S, K) or self._fq_kq_partial.device != dev:
- self._fq_kq_partial = torch.empty((FQ_GROUPED_MAX_ROWS * S, K), dtype=torch.float, device=dev)
+ # partial sums: scratch consumed inside this call -> one buffer per (device, shape) for every MoE layer
+ key = (str(dev), FQ_GROUPED_MAX_ROWS * S, K)
+ if key not in _FQ_KQ_PARTIAL:
+ _FQ_KQ_PARTIAL[key] = torch.empty((FQ_GROUPED_MAX_ROWS * S, K), dtype=torch.float, device=dev)
+ self._fq_kq_partial = _FQ_KQ_PARTIAL[key]
self._fq_kq_routed = torch.empty((FQ_GROUPED_MAX_ROWS, K), dtype=torch.float, device=dev)
partial_v = self._fq_kq_partial[:R * S]
routed_v = self._fq_kq_routed[:R]
diff --git a/exllamav3/version.py b/exllamav3/version.py
index bae6b8a..91c1a02 100644
--- a/exllamav3/version.py
+++ b/exllamav3/version.py
@@ -1 +1 @@
-__version__ = "1.8.17"
+__version__ = "1.8.18"
diff --git a/tests/test_q8_gemv_mrows.py b/tests/test_q8_gemv_mrows.py
new file mode 100644
index 0000000..34c5f29
--- /dev/null
+++ b/tests/test_q8_gemv_mrows.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+"""Q8_0 multi-row decode GEMV (x-rows 2..16, BOLT_FQ_Q8_MROWS): output row m must equal the one-row kernel's output for x-row m BIT FOR BIT,
+for R = 1..16 (row groups of 8: R = 9..16 runs two groups), half and float output, several (N, K) shapes. Also checks that
+BOLT_FQ_Q8_MROWS=0 (the old per-(row, column) launch) gives the same bytes, so batch composition never changes an output.
+usage: python tests/test_q8_gemv_mrows.py (needs a CUDA / HIP GPU and the built extension)"""
+import os, subprocess, sys
+
+CASES = [(1, 32), (37, 1024), (512, 2048), (1000, 2048), (2048, 4096), (4096, 512), (5, 12288)] # (N, K)
+
+
+def child(tag):
+ import torch
+ from exllamav3.ext import exllamav3_ext as ext
+ torch.manual_seed(0)
+ bad = n = 0
+ outs = []
+ for N, K in CASES:
+ nb = K // 32
+ d = (torch.rand(N, nb, device="cuda") * 0.02 + 1e-3).half()
+ q = torch.randint(-127, 128, (N, nb, 32), device="cuda", dtype=torch.int8)
+ w = torch.cat([d.view(torch.uint8).reshape(N, nb, 2), q.view(torch.uint8)], dim=2).contiguous()
+ for R in range(1, 17):
+ x = torch.randn(R, K, device="cuda", dtype=torch.half)
+ for dt in (torch.half, torch.float):
+ out = torch.empty(R, N, device="cuda", dtype=dt)
+ ext.fq_gemv_q8_0(x, w, out)
+ for m in range(R):
+ o1 = torch.empty(1, N, device="cuda", dtype=dt)
+ ext.fq_gemv_q8_0(x[m:m + 1].contiguous(), w, o1)
+ n += 1
+ if not torch.equal(out[m], o1[0]):
+ bad += 1
+ print(f"{tag}: MISMATCH N {N} K {K} R {R} row {m} {dt}", flush=True)
+ outs.append(out.view(torch.uint8).flatten().cpu())
+ torch.save(torch.cat(outs), sys.argv[3])
+ print(f"{tag}: {n} row checks, {bad} mismatches", flush=True)
+ sys.exit(1 if bad else 0)
+
+
+if __name__ == "__main__":
+ if len(sys.argv) > 1 and sys.argv[1] == "--child":
+ child(sys.argv[2])
+ import tempfile
+ import torch
+ with tempfile.TemporaryDirectory() as td:
+ rc = 0
+ for tag, val in (("mrows", "1"), ("per_row", "0")):
+ env = dict(os.environ, BOLT_FQ_Q8_MROWS=val)
+ rc |= subprocess.run([sys.executable, __file__, "--child", tag, f"{td}/{tag}.pt"], env=env).returncode
+ same = torch.equal(torch.load(f"{td}/mrows.pt"), torch.load(f"{td}/per_row.pt"))
+ print("BOLT_FQ_Q8_MROWS=1 vs 0: " + ("identical bytes" if same else "DIFFERENT"))
+ print("PASS" if rc == 0 and same else "FAIL")
+ sys.exit(0 if rc == 0 and same else 1)