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 prefill: opt-in native grouped dequant kernel, fused in-tile decode switch, profiling script
YanissAmz7cf52f252b1f
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cppindex 91ca080..ecbf80c 100644--- a/exllamav3/exllamav3_ext/bindings.cpp+++ b/exllamav3/exllamav3_ext/bindings.cpp@@ -571,6 +571,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)py::arg("packed"), py::arg("out"));m.def("fq_dequant_nvfp4", &fq_dequant_nvfp4, "fq_dequant_nvfp4",py::arg("packed"), py::arg("scales"), py::arg("global_scale"), py::arg("out"));+ m.def("fq_dequant_kq_grouped", &fq_dequant_kq_grouped, "fq_dequant_kq_grouped",+ py::arg("ptrs"), py::arg("out"), py::arg("e0"), py::arg("ec"), py::arg("n"), py::arg("k"), py::arg("fmt"));m.def("fq_dequant_q4_k", &fq_dequant_q4_k, "fq_dequant_q4_k",py::arg("packed"), py::arg("out"));m.def("fq_dequant_q5_k", &fq_dequant_q5_k, "fq_dequant_q5_k",diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_api.h b/exllamav3/exllamav3_ext/foreign_quant/fq_api.hindex f30e256..3367061 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_api.h+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_api.h@@ -38,6 +38,7 @@ void fq_moe_iq2xxs_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor// 256-block), out = fp16 [N, K] with K = Kb*256. Bitwise-identical to// dequant_row(blocks, fmt).astype(np.float16) in foreign_quant/k_quants.py.void fq_dequant_q4_k(torch::Tensor packed, torch::Tensor out);+void fq_dequant_kq_grouped(torch::Tensor ptrs, torch::Tensor out, int64_t e0, int64_t ec, int64_t n, int64_t k, int64_t fmt);void fq_dequant_q5_k(torch::Tensor packed, torch::Tensor out);void fq_dequant_q6_k(torch::Tensor packed, torch::Tensor out);void fq_dequant_iq4_xs(torch::Tensor packed, torch::Tensor out);diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cuindex 3375c01..7ddb7b6 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cu+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_dequant_kq.cu@@ -43,9 +43,12 @@ namespace {// decoded by fq_q4k_scales(..., s >> 1) at index s & 1. First 32 elements of// a 64-group take the low nibble (d1, m1), next 32 the high nibble (d2, m2):// y = (d*sc) * nib - (dmin*m) (left-assoc, two roundings).-__global__ void fq_dq_q4_k_kernel(const uint8_t* __restrict__ packed, __half* __restrict__ out,- int64_t kb)+__global__ void fq_dq_q4_k_kernel(const uint8_t* __restrict__ packed_, __half* __restrict__ out_,+ int64_t kb, const int64_t* __restrict__ ptrs, int64_t out_stride){+ // ptrs != null: grouped launch, blockIdx.z picks the expert (its packed pointer and out slice)+ const uint8_t* packed = ptrs ? reinterpret_cast<const uint8_t*>(ptrs[blockIdx.z]) : packed_;+ __half* out = out_ + (int64_t)blockIdx.z * out_stride;int b = blockIdx.x; // 256-block index within the rowint n = blockIdx.y; // rowint e = threadIdx.x; // 0..255, element index inside the block@@ -75,9 +78,12 @@ __global__ void fq_dq_q4_k_kernel(const uint8_t* __restrict__ packed, __half* __// u2 = 2<<(2*c)) while the qh byte index restarts at 0 in every group, so the// mask is 1 << (2*c + hi) == 1 << s and the qh byte is l, NOT l + 32*c.// y = (d*sc) * (nib + 16*(qh[l] >> s & 1)) - (dmin*m)-__global__ void fq_dq_q5_k_kernel(const uint8_t* __restrict__ packed, __half* __restrict__ out,- int64_t kb)+__global__ void fq_dq_q5_k_kernel(const uint8_t* __restrict__ packed_, __half* __restrict__ out_,+ int64_t kb, const int64_t* __restrict__ ptrs, int64_t out_stride){+ // ptrs != null: grouped launch, blockIdx.z picks the expert (its packed pointer and out slice)+ const uint8_t* packed = ptrs ? reinterpret_cast<const uint8_t*>(ptrs[blockIdx.z]) : packed_;+ __half* out = out_ + (int64_t)blockIdx.z * out_stride;int b = blockIdx.x;int n = blockIdx.y;int e = threadIdx.x;@@ -114,9 +120,12 @@ __global__ void fq_dq_q5_k_kernel(const uint8_t* __restrict__ packed, __half* __// planes, so the global byte offsets are 64*half, 128 + 32*half and 192 +// 8*half -- dropping the 128 would silently read the wrong qh plane.// y = (d * sc) * q (left-assoc: d*sc first, then *q, q already -32)-__global__ void fq_dq_q6_k_kernel(const uint8_t* __restrict__ packed, __half* __restrict__ out,- int64_t kb)+__global__ void fq_dq_q6_k_kernel(const uint8_t* __restrict__ packed_, __half* __restrict__ out_,+ int64_t kb, const int64_t* __restrict__ ptrs, int64_t out_stride){+ // ptrs != null: grouped launch, blockIdx.z picks the expert (its packed pointer and out slice)+ const uint8_t* packed = ptrs ? reinterpret_cast<const uint8_t*>(ptrs[blockIdx.z]) : packed_;+ __half* out = out_ + (int64_t)blockIdx.z * out_stride;int b = blockIdx.x;int n = blockIdx.y;int e = threadIdx.x;@@ -147,9 +156,12 @@ __global__ void fq_dq_q6_k_kernel(const uint8_t* __restrict__ packed, __half* __// and dl = d * (ls - 32); the first 16 lanes take the low nibble of 16 qs// bytes, the next 16 the high nibble of the same bytes.// y = (d * (ls-32)) * kvalues[nib]-__global__ void fq_dq_iq4_xs_kernel(const uint8_t* __restrict__ packed, __half* __restrict__ out,- int64_t kb)+__global__ void fq_dq_iq4_xs_kernel(const uint8_t* __restrict__ packed_, __half* __restrict__ out_,+ int64_t kb, const int64_t* __restrict__ ptrs, int64_t out_stride){+ // ptrs != null: grouped launch, blockIdx.z picks the expert (its packed pointer and out slice)+ const uint8_t* packed = ptrs ? reinterpret_cast<const uint8_t*>(ptrs[blockIdx.z]) : packed_;+ __half* out = out_ + (int64_t)blockIdx.z * out_stride;int b = blockIdx.x;int n = blockIdx.y;int e = threadIdx.x;@@ -216,7 +228,7 @@ void fq_dequant_q4_k(torch::Tensor packed, torch::Tensor out)int64_t nc = (n - n0 < FQ_DQ_KQ_MAX_ROWS) ? n - n0 : FQ_DQ_KQ_MAX_ROWS;dim3 grid((unsigned)kb, (unsigned)nc);fq_dq_q4_k_kernel<<<grid, 256, 0, stream>>>(- p + n0 * kb * FQ_Q4_K_BYTES, o + n0 * kb * FQ_Q4_K_GROUP, kb);+ p + n0 * kb * FQ_Q4_K_BYTES, o + n0 * kb * FQ_Q4_K_GROUP, kb, nullptr, 0);}}@@ -233,7 +245,7 @@ void fq_dequant_q5_k(torch::Tensor packed, torch::Tensor out)int64_t nc = (n - n0 < FQ_DQ_KQ_MAX_ROWS) ? n - n0 : FQ_DQ_KQ_MAX_ROWS;dim3 grid((unsigned)kb, (unsigned)nc);fq_dq_q5_k_kernel<<<grid, 256, 0, stream>>>(- p + n0 * kb * FQ_Q5_K_BYTES, o + n0 * kb * FQ_Q5_K_GROUP, kb);+ p + n0 * kb * FQ_Q5_K_BYTES, o + n0 * kb * FQ_Q5_K_GROUP, kb, nullptr, 0);}}@@ -250,7 +262,7 @@ void fq_dequant_q6_k(torch::Tensor packed, torch::Tensor out)int64_t nc = (n - n0 < FQ_DQ_KQ_MAX_ROWS) ? n - n0 : FQ_DQ_KQ_MAX_ROWS;dim3 grid((unsigned)kb, (unsigned)nc);fq_dq_q6_k_kernel<<<grid, 256, 0, stream>>>(- p + n0 * kb * FQ_Q6_K_BYTES, o + n0 * kb * FQ_Q6_K_GROUP, kb);+ p + n0 * kb * FQ_Q6_K_BYTES, o + n0 * kb * FQ_Q6_K_GROUP, kb, nullptr, 0);}}@@ -267,6 +279,26 @@ void fq_dequant_iq4_xs(torch::Tensor packed, torch::Tensor out)int64_t nc = (n - n0 < FQ_DQ_KQ_MAX_ROWS) ? n - n0 : FQ_DQ_KQ_MAX_ROWS;dim3 grid((unsigned)kb, (unsigned)nc);fq_dq_iq4_xs_kernel<<<grid, 256, 0, stream>>>(- p + n0 * kb * FQ_IQ4_XS_BYTES, o + n0 * kb * FQ_IQ4_XS_GROUP, kb);+ p + n0 * kb * FQ_IQ4_XS_BYTES, o + n0 * kb * FQ_IQ4_XS_GROUP, kb, nullptr, 0);}-}\ No newline at end of file+}+// Grouped dequant: experts e0 .. e0+ec-1 of a pointer table (int64 device pointers to [n, kb*bytes] packed rows) into+// out[ec, n, k] fp16 in ONE launch (the per-expert path launches once per expert and matrix).+void fq_dequant_kq_grouped(torch::Tensor ptrs, torch::Tensor out, int64_t e0, int64_t ec, int64_t n, int64_t k, int64_t fmt)+{+ TORCH_CHECK(ptrs.is_cuda() && ptrs.dtype() == torch::kInt64 && out.is_cuda() && out.dtype() == torch::kHalf, "bad args");+ TORCH_CHECK(k % 256 == 0 && n <= FQ_DQ_KQ_MAX_ROWS && ec <= 65535 && out.numel() >= ec * n * k, "bad shape");+ at::cuda::CUDAGuard guard(ptrs.device());+ auto 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;+ switch (fmt)+ {+ case 0: fq_dq_q4_k_kernel<<<grid, 256, 0, stream>>>(nullptr, o, kb, pp, n * k); break;+ case 1: fq_dq_q5_k_kernel<<<grid, 256, 0, stream>>>(nullptr, o, kb, pp, n * k); break;+ case 2: fq_dq_q6_k_kernel<<<grid, 256, 0, stream>>>(nullptr, o, kb, pp, n * k); break;+ default: fq_dq_iq4_xs_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 7e72441..934f91e 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -1927,7 +1927,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, PF_BM+ from .fq_moe_prefill_kq import moe_kq_prefill, gmm_kq, PF_BME = self.num_expertsdev = y.deviceK = y.shape[1]@@ -1954,8 +1954,12 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):dn = torch.empty((M, K), dtype=torch.half, device=dev)if use_kq:xs = y.index_select(0, token_sorted)- moe_kq_prefill(xs, gu_ptrs, dn_ptrs, a, dn, tile_e, tile_r0, offs, weight_sorted, E, I, K,- _KQ[fmts[0]], _KQ[fmts[1]], bm)+ if os.environ.get("MCPM_FQ_PF_FUSED", "0") == "1": # weights decoded inside the GEMM tile (no fp16 scratch)+ gmm_kq(xs, gu_ptrs, a, tile_e, tile_r0, offs, I, K, E, _KQ[fmts[0]], swiglu=True, BM=bm)+ gmm_kq(a, dn_ptrs, dn, tile_e, tile_r0, offs, K, I, E, _KQ[fmts[1]], wrow=weight_sorted, BM=bm)+ else:+ moe_kq_prefill(xs, gu_ptrs, dn_ptrs, a, dn, tile_e, tile_r0, offs, weight_sorted, E, I, K,+ _KQ[fmts[0]], _KQ[fmts[1]], bm)else:xs = perm_cols(y.index_select(0, token_sorted))gmm_iq4(xs, gu_ptrs, a, tile_e, tile_r0, offs, I, K, E, swiglu=True)diff --git a/exllamav3/modules/fq_moe_prefill_kq.py b/exllamav3/modules/fq_moe_prefill_kq.pyindex 36ec5c7..c1b80a4 100644--- a/exllamav3/modules/fq_moe_prefill_kq.py+++ b/exllamav3/modules/fq_moe_prefill_kq.py@@ -5,9 +5,11 @@ import osimport torchimport tritonimport triton.language as tl+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"BLOCK_BYTES = {FMT_Q4K: 144, FMT_Q5K: 176, FMT_Q6K: 210}@@ -233,9 +235,14 @@ def moe_kq_prefill(y_sorted, gu_ptrs, dn_ptrs, a, dn, tile_e, tile_r0, offs, wrowg = _buf(dev, "g", ec * I * K)wu = _buf(dev, "u", ec * I * K)wd = _buf(dev, "d", ec * K * I)- _dq_kq[(triton.cdiv(I, BNd), K // 256, ec)](gu_ptrs, wg, e0, I, K, FMT=fmt_gu, BN=BNd, num_warps=4)- _dq_kq[(triton.cdiv(I, BNd), K // 256, ec)](gu_ptrs, wu, E + e0, I, K, FMT=fmt_gu, BN=BNd, num_warps=4)- _dq_kq[(triton.cdiv(K, BNd), I // 256, ec)](dn_ptrs, wd, e0, K, I, FMT=fmt_dn, BN=BNd, num_warps=4)+ 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+ 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)+ else:+ _dq_kq[(triton.cdiv(I, BNd), K // 256, ec)](gu_ptrs, wg, e0, I, K, FMT=fmt_gu, BN=BNd, num_warps=4)+ _dq_kq[(triton.cdiv(I, BNd), K // 256, ec)](gu_ptrs, wu, E + e0, I, K, FMT=fmt_gu, BN=BNd, num_warps=4)+ _dq_kq[(triton.cdiv(K, BNd), I // 256, ec)](dn_ptrs, wd, e0, K, I, FMT=fmt_dn, BN=BNd, num_warps=4)T = tile_e.shape[0]BN, BK, nw, ns = 128, 64, 8, (2 if torch.version.hip else 3) # 64 KiB LDS on gfx11_gmm_f16[(triton.cdiv(I, BN), T)](y_sorted, wg, wu, a, tile_e, tile_r0, offs, offs, I, K, y_sorted.stride(0),diff --git a/tests/bench_moe_prefill_kq.py b/tests/bench_moe_prefill_kq.pyindex 0a57d77..d9946d7 100644--- a/tests/bench_moe_prefill_kq.py+++ b/tests/bench_moe_prefill_kq.py@@ -78,6 +78,13 @@ def main() -> int:b.record()torch.cuda.synchronize()res[mode] = (a.elapsed_time(b) / 5, y)+ if os.environ.get("PROF") and N == 4096:+ from torch.profiler import profile, ProfilerActivity+ os.environ["MCPM_FQ_PF_GROUPED_KQ"] = "1"+ with profile(activities=[ProfilerActivity.CUDA]) as p:+ run(); torch.cuda.synchronize()+ for e in sorted(p.key_averages(), key=lambda e: -e.device_time_total)[:6]:+ print(f" {e.device_time_total / 1e3:8.1f} ms n={e.count:4d} {e.key[:70]}")rel = ((res["1"][1] - res["0"][1]).norm() / res["0"][1].norm()).item()print(f"N={N:5d}: per-expert {res['0'][0]:8.1f} ms grouped {res['1'][0]:8.1f} ms ({res['0'][0] / res['1'][0]:.1f}x) rel_diff={rel:.1e}")return 0diff --git a/tests/prof_prefill.py b/tests/prof_prefill.pynew file mode 100644index 0000000..ff46e76--- /dev/null+++ b/tests/prof_prefill.py@@ -0,0 +1,24 @@+"""torch-profiler op-class split of one prefill. MODEL_DIR | FMOE_GGUF, PREFILL_L (default 8192)."""+import os, sys+import torch+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))+from exllamav3 import Model, Config, Cache, Generator, Job, GreedySampler, Tokenizer+from exllamav3.loader.gguf_config import write_config_dir+from torch.profiler import profile, ProfilerActivity+L = int(os.environ.get("PREFILL_L", "8192"))+d = os.environ.get("MODEL_DIR") or write_config_dir(os.environ["FMOE_GGUF"], os.path.join(os.environ.get("FMOE_CFG", "/tmp"), "qwen35moe_cfg"))+config = Config.from_directory(d); model = Model.from_config(config)+cache = Cache(model, max_num_tokens=(L + 1024) // 256 * 256 + 256); model.load()+tok = Tokenizer.from_config(config); gen = Generator(model=model, cache=cache, tokenizer=tok)+g = torch.Generator().manual_seed(2)+def run(seed):+ ids = torch.randint(1000, 100000, (1, L), generator=g)+ gen.enqueue(Job(input_ids=ids, max_new_tokens=1, sampler=GreedySampler(), stop_conditions=[]))+ while gen.num_remaining_jobs(): gen.iterate()+run(0); torch.cuda.synchronize()+with profile(activities=[ProfilerActivity.CUDA]) as p:+ run(1); torch.cuda.synchronize()+rows = sorted(p.key_averages(), key=lambda e: -e.device_time_total)[:14]+tot = sum(e.device_time_total for e in p.key_averages())+print(f"total device time {tot / 1e3:.0f} ms")+for e in rows: print(f"{100 * e.device_time_total / tot:5.1f}% {e.device_time_total / 1e3:8.1f} ms n={e.count:5d} {e.key[:90]}")