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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
K-quant grouped dequant: vectorised bandwidth-bound kernel (8 outputs/thread), enable grouped prefill on ROCm by measured rule (native dq and >=512 rows)
YanissAmz95490d233083
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cuindex 7ddb7b6..3ac73d2 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cu+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cu@@ -209,6 +209,84 @@ static bool fq_dq_kq_check(torch::Tensor& packed, torch::Tensor& out, int64_t blreturn n > 0 && kb > 0; // empty input: nothing to launch}++// ---- Vectorised grouped decode (bandwidth path) --------------------------------------------------------------+// One thread decodes 8 consecutive outputs of one 256-block (32 threads per block, flat over rows x blocks):+// the packed bytes of those 8 outputs are one 8-byte load (Q4_K/Q5_K, 8-aligned) and the 8 fp16 results leave as+// one 16-byte store, so a warp streams ~4.6 KB of packed bytes per instruction group instead of 256 single bytes.+// Same arithmetic, same rounding as the scalar kernels above.+__device__ __forceinline__ uint2 fq_ld8(const uint8_t* p) { return *reinterpret_cast<const uint2*>(p); }++__device__ __forceinline__ void fq_st8(__half* o, const float* v)+{+ __half2 h[4];+ #pragma unroll+ for (int i = 0; i < 4; ++i) h[i] = __halves2half2(__float2half_rn(v[2*i]), __float2half_rn(v[2*i+1]));+ *reinterpret_cast<uint4*>(o) = *reinterpret_cast<uint4*>(h);+}++template <int FMT>+__global__ void fq_dqv_kq_kernel(__half* __restrict__ out_, int64_t kb, int64_t rows,+ const int64_t* __restrict__ ptrs, int64_t out_stride)+{+ const int64_t gid = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;+ const int64_t bi = gid >> 5; // block index inside the expert (row * kb + b)+ if (bi >= rows * kb) return;+ const int t = gid & 31;+ const int e0 = t * 8; // first output inside the 256-block+ constexpr int BYTES = FMT == 0 ? FQ_Q4_K_BYTES : FMT == 1 ? FQ_Q5_K_BYTES : FQ_Q6_K_BYTES;+ const uint8_t* blk = reinterpret_cast<const uint8_t*>(ptrs[blockIdx.y]) + bi * BYTES;+ __half* o = out_ + (int64_t)blockIdx.y * out_stride + bi * 256 + e0;+ float v[8];+ if (FMT < 2)+ {+ __half dh, dmh;+ memcpy(&dh, blk, 2);+ memcpy(&dmh, blk + 2, 2);+ const float d = __half2float(dh), dmin = __half2float(dmh);+ const int c = e0 >> 6, s = e0 >> 5, l = e0 & 31, hi = s & 1;+ uint8_t sc[2], m[2];+ fq_q4k_scales(blk + 4, s >> 1, sc, m);+ const uint2 q = fq_ld8(blk + (FMT == 0 ? 16 : 48) + 32 * c + l);+ uint32_t hb0 = 0, hb1 = 0;+ if (FMT == 1) { uint2 h = fq_ld8(blk + 16 + l); hb0 = h.x; hb1 = h.y; }+ const float d1 = __fmul_rn(d, (float)sc[hi]);+ const float m1 = __fmul_rn(dmin, (float)m[hi]);+ #pragma unroll+ for (int i = 0; i < 8; ++i)+ {+ uint32_t w = i < 4 ? q.x : q.y;+ int qb = (w >> (8 * (i & 3))) & 0xFF;+ int nib = hi ? (qb >> 4) : (qb & 0xF);+ if (FMT == 1)+ {+ uint32_t hw = i < 4 ? hb0 : hb1;+ nib += (((hw >> (8 * (i & 3))) >> s) & 1) << 4;+ }+ v[i] = __fsub_rn(__fmul_rn(d1, (float)nib), m1);+ }+ }+ else+ {+ __half dh;+ memcpy(&dh, blk + 208, 2);+ const float d = __half2float(dh);+ const int half = e0 >> 7, tt = e0 & 127, grp = tt >> 5, l = tt & 31;+ const uint8_t* qlp = blk + 64 * half + l + 32 * (grp & 1);+ const uint8_t* qhp = blk + 128 + 32 * half + l;+ const float ds = __fmul_rn(d, (float)(int8_t)blk[192 + 8 * half + 2 * grp + (l >> 4)]);+ #pragma unroll+ for (int i = 0; i < 8; ++i)+ {+ uint8_t ql = qlp[i], qh = qhp[i];+ int q = (grp >> 1) ? (ql >> 4) : (ql & 0xF);+ q = (q | (((qh >> (2 * grp)) & 3) << 4)) - 32;+ v[i] = __fmul_rn(ds, (float)q);+ }+ }+ fq_st8(o, v);+}+} // namespace// gridDim.y caps at 65535: the lm_head dequant is N = 248144 rows, so every@@ -292,8 +370,18 @@ void fq_dequant_kq_grouped(torch::Tensor ptrs, torch::Tensor out, int64_t e0, inauto stream = at::cuda::getCurrentCUDAStream().stream();const int64_t* pp = ptrs.data_ptr<int64_t>() + e0;__half* o = reinterpret_cast<__half*>(out.data_ptr<at::Half>());- dim3 grid((unsigned)(k / 256), (unsigned)n, (unsigned)ec);int64_t kb = k / 256;+ if (fmt <= 2)+ {+ int64_t nthr = n * kb * 32;+ dim3 vg((unsigned)((nthr + 255) / 256), (unsigned)ec);+ // braces: hipify mangles `else <<<...>>>` into `elsehipLaunchKernelGGL`+ if (fmt == 0) { fq_dqv_kq_kernel<0><<<vg, 256, 0, stream>>>(o, kb, n, pp, n * k); }+ else if (fmt == 1) { fq_dqv_kq_kernel<1><<<vg, 256, 0, stream>>>(o, kb, n, pp, n * k); }+ else { fq_dqv_kq_kernel<2><<<vg, 256, 0, stream>>>(o, kb, n, pp, n * k); }+ return;+ }+ dim3 grid((unsigned)(k / 256), (unsigned)n, (unsigned)ec);switch (fmt){case 0: fq_dq_q4_k_kernel<<<grid, 256, 0, stream>>>(nullptr, o, kb, pp, n * k); break;diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex 934f91e..eb6f05a 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -1917,9 +1917,15 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):if fmts is None or not (use_kq or fmts == ("iq4_xs", "iq4_xs")) or self.act_limit or \self.activation_fn not in ("silu", None):return None- # CUDA: 2.4-4.2x on the MoE layer. ROCm (iGPU): 0.9-1.1x (scratch traffic is bound by LPDDR bandwidth), so off by default there- if use_kq and os.environ.get("MCPM_FQ_PF_GROUPED_KQ", "0" if torch.version.hip else "1") == "0":- return None+ # Scratch path (grouped dequant + fp16 grouped GEMM): CUDA 2.4-4.2x on the MoE layer. ROCm iGPU with the+ # native bandwidth-bound dequant (~220 GB/s): 1.7x at 1K rows, 1.4x at 4K, 1.1-1.2x at 8K; ~1.0x at 256 rows,+ # so there it needs the native kernel and >= 512 rows. MCPM_FQ_PF_GROUPED_KQ=0/1 overrides.+ if use_kq:+ force = os.environ.get("MCPM_FQ_PF_GROUPED_KQ")+ if force == "0":+ return None+ if force is None and torch.version.hip and (not kq_native_dq() or R < 512):+ return Noneif (self.num_local_experts or self.num_experts) != self.num_experts:return Nonetop_k = self.num_experts_per_tok@@ -1927,7 +1933,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):return Nonefrom .fq_moe_prefill import build_tiles, gmm_iq4, perm_colsif use_kq:- from .fq_moe_prefill_kq import moe_kq_prefill, gmm_kq, PF_BM+ from .fq_moe_prefill_kq import moe_kq_prefill, gmm_kq, kq_native_dq, PF_BME = self.num_expertsdev = y.deviceK = y.shape[1]diff --git a/exllamav3/modules/fq_moe_prefill_kq.py b/exllamav3/modules/fq_moe_prefill_kq.pyindex c1b80a4..e2f84c6 100644--- a/exllamav3/modules/fq_moe_prefill_kq.py+++ b/exllamav3/modules/fq_moe_prefill_kq.py@@ -9,7 +9,7 @@ from ..ext import exllamav3_ext as extFMT_Q4K, FMT_Q5K, FMT_Q6K = 0, 1, 2PF_BM = int(os.environ.get("MCPM_FQ_PF_BM", "64")) # rows per tile: weight decode is shared by BM rows-_NATIVE_DQ = hasattr(ext, "fq_dequant_kq_grouped") and os.environ.get("MCPM_FQ_PF_NATIVE_DQ", "0") == "1"+_NATIVE_DQ = hasattr(ext, "fq_dequant_kq_grouped") and os.environ.get("MCPM_FQ_PF_NATIVE_DQ", "1") != "0"BLOCK_BYTES = {FMT_Q4K: 144, FMT_Q5K: 176, FMT_Q6K: 210}@@ -223,19 +223,32 @@ def _buf(dev, name, numel):return b+_ALIGNED = {}+++def _ptrs_aligned(ptrs) -> bool:+ """The vectorised dequant does 8-byte loads: all expert pointers must be 8-aligned (checked once per table)."""+ key = (ptrs.data_ptr(), ptrs.numel())+ ok = _ALIGNED.get(key)+ if ok is None:+ ok = _ALIGNED[key] = bool(((ptrs.cpu() % 8) == 0).all())+ return ok++def moe_kq_prefill(y_sorted, gu_ptrs, dn_ptrs, a, dn, tile_e, tile_r0, offs, wrow, E, I, K, fmt_gu, fmt_dn, bm,chunk=None):"""Dequant a chunk of experts to fp16 scratch (one launch per matrix kind), then fused gate/up/SwiGLU and down GEMMsover the rows of those experts. Scratch = chunk x (2 I K + K I) halves."""dev = y_sorted.devicechunk = chunk or int(os.environ.get("MCPM_FQ_PF_CHUNK", "64"))+ native = _NATIVE_DQ and _ptrs_aligned(gu_ptrs) and _ptrs_aligned(dn_ptrs)BNd = 32for e0 in range(0, E, chunk):ec = min(chunk, E - e0)wg = _buf(dev, "g", ec * I * K)wu = _buf(dev, "u", ec * I * K)wd = _buf(dev, "d", ec * K * I)- if _NATIVE_DQ: # opt-in native grouped dequant (fq_dequant_kq.cu): slower than the Triton one on the 3090, ~1.3x on the iGPU+ if native: # native grouped dequant (fq_dequant_kq.cu, vectorised): 770-820 GB/s on the 3090 (= Triton), ~220 GB/s on the iGPU (Triton 47)ext.fq_dequant_kq_grouped(gu_ptrs, wg, e0, ec, I, K, fmt_gu)ext.fq_dequant_kq_grouped(gu_ptrs, wu, E + e0, ec, I, K, fmt_gu)ext.fq_dequant_kq_grouped(dn_ptrs, wd, e0, ec, K, I, fmt_dn)@@ -263,3 +276,7 @@ def gmm_kq(a, wptrs, out, tile_e, tile_r0, offs, N, K, E, fmt, swiglu=False, wroN, K, a.stride(0), out.stride(0), E,FMT=fmt, SWIGLU=swiglu, SCALE_ROWS=wrow is not None, BM=BM, BN=BN,num_warps=num_warps, num_stages=num_stages)+++def kq_native_dq() -> bool:+ return _NATIVE_DQdiff --git a/tests/bench_kq_dequant.py b/tests/bench_kq_dequant.pynew file mode 100644index 0000000..cdb5ae9--- /dev/null+++ b/tests/bench_kq_dequant.py@@ -0,0 +1,25 @@+# Bandwidth of the grouped K-quant dequant: packed bytes read + fp16 written per second.+import os, sys, time, torch+from exllamav3.ext import exllamav3_ext as ext+dev = "cuda"+for name, fmt, bpb in (("q4_k", 0, 144), ("q5_k", 1, 176), ("q6_k", 2, 210)):+ n, k, ec = 512, 2048, 64+ kb = k // 256+ packed = torch.randint(0, 256, (ec, n * kb * bpb), dtype=torch.uint8, device=dev)+ if fmt == 2: packed.view(ec, n * kb, bpb)[:, :, 208:210] = torch.tensor([0x00, 0x2C], dtype=torch.uint8, device=dev)+ if fmt == 0 or fmt == 1:+ packed.view(ec, n * kb, bpb)[:, :, :4] = torch.tensor([0x00, 0x2C, 0x00, 0x2C], dtype=torch.uint8, device=dev) # sane d/dmin+ ptrs = torch.tensor([packed[e].data_ptr() for e in range(ec)], dtype=torch.int64, device=dev)+ out = torch.empty(ec, n, k, dtype=torch.half, device=dev)+ def grouped(): ext.fq_dequant_kq_grouped(ptrs, out, 0, ec, n, k, fmt)+ fn = getattr(ext, "fq_dequant_" + name)+ out2 = torch.empty(ec, n, k, dtype=torch.half, device=dev)+ def perexp():+ for e in range(ec): fn(packed[e].view(n, kb * bpb), out2[e])+ for lab, f in (("grouped", grouped), ("scalar/exp", perexp)):+ f(); torch.cuda.synchronize(); t = time.time()+ for _ in range(5): f()+ torch.cuda.synchronize(); dt = (time.time() - t) / 5+ gb = ec * n * kb * (bpb + 512) / 1e9+ print(f"{name} {lab:10s} {dt*1e3:7.2f} ms {gb/dt:6.1f} GB/s (read+write)")+ print(" match:", bool((out == out2).all()))