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
Grouped KQ MoE kernel takes R rows (users/sessions): no host-synced per-expert loop above batch 1
YanissAmz1588e361be8d
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cuindex 24d7374..851c944 100644--- a/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu@@ -31,7 +31,7 @@ __global__ void fq_moe_kq_upgate_kernel(const uint8_t* __restrict__ aqb,int64_t up_stride,int64_t qb_stride,__half* __restrict__ act,- int S, int I, int K, int E, int ntiles_u)+ int S, int I, int K, int E, int ntiles_u, int topk){int b = blockIdx.x;int s = b / ntiles_u;@@ -41,6 +41,7 @@ __global__ void fq_moe_kq_upgate_kernel(const uint8_t* __restrict__ aqb,int64_t e = sel[s];e = (e < 0 || e >= E) ? 0 : e;int n = t * FQ_GEMV_OUT_PER_BLOCK + grp;+ const uint8_t* aq = aqb + (int64_t)(s / topk) * qb_stride; // assignment s = row * topk + j reads h row s / topkextern __shared__ float red[];@@ -51,23 +52,23 @@ __global__ void fq_moe_kq_upgate_kernel(const uint8_t* __restrict__ aqb,const uint8_t* ur = up_bases[e] + (int64_t)n * up_stride;if constexpr (FMT == 0){- g = fq_dot_q4_k_q8(gr, aqb, K, lane, FQ_GEMV_LANES);- u = fq_dot_q4_k_q8(ur, aqb, K, lane, FQ_GEMV_LANES);+ g = fq_dot_q4_k_q8(gr, aq, K, lane, FQ_GEMV_LANES);+ u = fq_dot_q4_k_q8(ur, aq, K, lane, FQ_GEMV_LANES);}else if constexpr (FMT == 1){- g = fq_dot_q5_k_q8(gr, aqb, K, lane, FQ_GEMV_LANES);- u = fq_dot_q5_k_q8(ur, aqb, K, lane, FQ_GEMV_LANES);+ g = fq_dot_q5_k_q8(gr, aq, K, lane, FQ_GEMV_LANES);+ u = fq_dot_q5_k_q8(ur, aq, K, lane, FQ_GEMV_LANES);}else if constexpr (FMT == 2){- g = fq_dot_q6_k_q8(gr, aqb, K, lane, FQ_GEMV_LANES);- u = fq_dot_q6_k_q8(ur, aqb, K, lane, FQ_GEMV_LANES);+ g = fq_dot_q6_k_q8(gr, aq, K, lane, FQ_GEMV_LANES);+ u = fq_dot_q6_k_q8(ur, aq, K, lane, FQ_GEMV_LANES);}else{- g = fq_dot_iq4_xs_q8(gr, aqb, K, lane, FQ_GEMV_LANES);- u = fq_dot_iq4_xs_q8(ur, aqb, K, lane, FQ_GEMV_LANES);+ g = fq_dot_iq4_xs_q8(gr, aq, K, lane, FQ_GEMV_LANES);+ u = fq_dot_iq4_xs_q8(ur, aq, K, lane, FQ_GEMV_LANES);}}// Two reductions in one shared row: red[2*tid] = g, red[2*tid+1] = u.@@ -147,6 +148,10 @@ __global__ void fq_moe_kq_combine_kernel(const float* __restrict__ partial,const __half* __restrict__ wts,float* __restrict__ out, int S, int K){+ // blockIdx.y = row r: its S = topk assignments are partial[r*S .. r*S+S), weights wts[r*S ..)+ partial += (int64_t)blockIdx.y * S * K;+ wts += (int64_t)blockIdx.y * S;+ out += (int64_t)blockIdx.y * K;for (int k = blockIdx.x * blockDim.x + threadIdx.x; k < K; k += gridDim.x * blockDim.x){float acc = 0.0f;@@ -170,7 +175,10 @@ static void fq_moe_kq_grouped_launch(torch::Tensor h, torch::Tensor sel, torch::torch::Tensor partial, torch::Tensor out){int K = (int)h.size(1);- int S = (int)sel.numel();+ int R = (int)h.size(0);+ int S = (int)sel.numel(); // R rows x topk picks, assignment s = row * topk + j+ int topk = S / R;+ TORCH_CHECK(S % R == 0 && R >= 1 && topk <= 32, "fq_moe_kq: sel must be R x topk with topk <= 32");TORCH_CHECK_DTYPE(h, kHalf);int E = (int)up_ptrs.numel();// I from the down row stride (down rows are I-wide, like Bolt's@@ -180,7 +188,7 @@ static void fq_moe_kq_grouped_launch(torch::Tensor h, torch::Tensor sel, torch::auto stream = at::cuda::getCurrentCUDAStream().stream();int ntiles_u = (I + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;int ntiles_d = (K + FQ_GEMV_OUT_PER_BLOCK - 1) / FQ_GEMV_OUT_PER_BLOCK;- torch::Tensor qb_h = fq_q8_scratch(h.get_device(), 1, K);+ torch::Tensor qb_h = fq_q8_scratch(h.get_device(), R, K);fq_quant_q8_1_rows(h, qb_h);int64_t qb_stride_h = (int64_t)(K / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;static thread_local std::map<std::tuple<int, int, int>, torch::Tensor> act_cache;@@ -202,7 +210,7 @@ static void fq_moe_kq_grouped_launch(torch::Tensor h, torch::Tensor sel, torch::reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr<int64_t>()),gate_stride, up_stride, qb_stride_h,reinterpret_cast<__half*>(act.data_ptr<at::Half>()),- S, I, K, E, ntiles_u);+ S, I, K, E, ntiles_u, topk);torch::Tensor qb_act = fq_q8_scratch(h.get_device(), S, I);fq_quant_q8_1_rows(act, qb_act);int64_t qb_stride_a = (int64_t)(I / FQ_Q8_1_GROUP) * FQ_Q8_1_BYTES;@@ -212,10 +220,10 @@ static void fq_moe_kq_grouped_launch(torch::Tensor h, torch::Tensor sel, torch::reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr<int64_t>()),down_stride, partial.data_ptr<float>(), S, I, K, E, ntiles_d);int nblocks = (K + 255) / 256;- fq_moe_kq_combine_kernel<<<nblocks, 256, 0, stream>>>(+ fq_moe_kq_combine_kernel<<<dim3(nblocks, R), 256, 0, stream>>>(partial.data_ptr<float>(),reinterpret_cast<const __half*>(wts.data_ptr<at::Half>()),- out.data_ptr<float>(), S, K);+ out.data_ptr<float>(), topk, K);}void fq_moe_q4k_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex a945970..9f4f5f8 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -61,6 +61,9 @@ MAX_BSZN = 8 # must match MAX_BSZN in exllamav3_ext/libtorch/blocksparse_mlp.h# rows runs as job-aligned slices of at most MAX_BSZN rows (each slice is the exact 2..8 row call, rows are independent in an MoE block).# ROCm only (the CUDA fused kernels have their own COOP_ROWS); EXL3_ROW_INV_MAX_ROWS=8 restores the single-call cap.UNION_ROWS = max(MAX_BSZN, ROW_INV_MAX_ROWS) if torch.version.hip else MAX_BSZN+# 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"))# 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@@ -1778,16 +1781,16 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):def _forward_foreign_grouped_kq(self, x, y, selected_experts, routing_weights,params, out_dtype, eshape):- """Grouped KQ MoE for batch-1 SwiGLU decode. One fq_moe kernel runs- all selected experts (gate+up dots, torch-half SwiGLU, down dots,- weighted fold), replacing the per-expert torch loop (top-k launches- + python dispatch per layer). Returns routed+shared sum or None."""+ """Grouped KQ MoE for SwiGLU decode, R = 1..FQ_GROUPED_MAX_ROWS rows (one per user / session). One fq_moe kernel+ runs all R x top-k assignments (gate+up dots, torch-half SwiGLU, down dots, per-row weighted fold), replacing the+ per-expert torch loop (host-synced expert counts, ~10x slower from the second row). Returns routed+shared sum or None."""fmts = self._fq_grouped_kq_ok(y)if fmts is None:return Nonefmt, fmt_d = fmtsS = self.num_experts_per_tok- if tuple(selected_experts.shape) != (1, S):+ R = y.shape[0]+ if R > FQ_GROUPED_MAX_ROWS or tuple(selected_experts.shape) != (R, S):return Nonesel = selected_experts.reshape(-1)wts = routing_weights.reshape(-1)@@ -1797,7 +1800,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):sel = sel.contiguous()if not wts.is_contiguous():wts = wts.contiguous()- h = y.reshape(1, -1)+ h = y.reshape(R, -1)dev = h.deviceK = h.shape[1]_BB = {"q4_k": 144, "q5_k": 176, "q6_k": 210, "iq4_xs": 136}@@ -1818,22 +1821,25 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):gate_stride = (K // 256) * bbup_stride = gate_stridedown_stride = (I // 256) * bb_d+ # buffers sized once for the largest row count (stable pointers for CUDA graphs); the kernel gets row-prefix viewsif getattr(self, "_fq_kq_partial", None) is None or \- self._fq_kq_partial.shape != (S, K) or self._fq_kq_partial.device != dev:- self._fq_kq_partial = torch.empty((S, K), dtype=torch.float, device=dev)- self._fq_kq_routed = torch.empty((1, K), dtype=torch.float, device=dev)+ 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)+ 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]_FN = {"q4_k": "fq_moe_q4k_grouped_q8", "q5_k": "fq_moe_q5k_grouped_q8","q6_k": "fq_moe_q6k_grouped_q8", "iq4_xs": "fq_moe_iq4xs_grouped_q8"}if fmt == fmt_d:getattr(ext, _FN[fmt])(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,gate_stride, up_stride, down_stride,- self._fq_kq_partial, self._fq_kq_routed)+ partial_v, routed_v)else:_FID = {"q4_k": 0, "q5_k": 1, "q6_k": 2, "iq4_xs": 3}ext.fq_moe_kq_grouped_mixed_q8(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,gate_stride, up_stride, down_stride, _FID[fmt], _FID[fmt_d],- self._fq_kq_partial, self._fq_kq_routed)- final_hidden_states = self._fq_kq_routed+ partial_v, routed_v)+ final_hidden_states = routed_vif self.shared_experts is not None:se_params = {**params, "moe_valu": True} if _MOE_VALU else paramsse = self.shared_experts.forward(x, se_params)@@ -2123,14 +2129,14 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# KQ grouped decode (MiniCPM SwiGLU MoE): same idea via the KQ dots# (see _forward_foreign_grouped_kq). Tried first (Bolt returns None# without latent projs anyway).- if bsz == 1 and not params.get("activate_all_experts") and \+ if bsz <= FQ_GROUPED_MAX_ROWS and not params.get("activate_all_experts") and \not params.get("reconstruct") and not params.get("autosplit_measure"):grouped = self._forward_foreign_grouped_kq(x, y, selected_experts, routing_weights, params, out_dtype, eshape)if grouped is not None:return groupedgrouped = self._forward_foreign_grouped(- x, y, selected_experts, routing_weights, params, out_dtype, eshape)+ x, y, selected_experts, routing_weights, params, out_dtype, eshape) if bsz == 1 else Noneif grouped is not None:return groupeddiff --git a/tests/bench_moe_foreign_rows.py b/tests/bench_moe_foreign_rows.pynew file mode 100644index 0000000..8a9bf3f--- /dev/null+++ b/tests/bench_moe_foreign_rows.py@@ -0,0 +1,90 @@+"""Multi-row (N users) MoE decode timing on real unsloth UD experts: N = 1,2,4,8,16,32 rows, top-8 of 256 each.++Runs BlockSparseMLP.forward with pre-routed picks (batch 1, top-8 of 256) through the grouped fq_moe kernel and checks it+against a numpy dequant + torch SwiGLU reference and against the ungrouped per-expert path.++ FMOE_GGUF=<file.gguf> python tests/test_moe_foreign_mixed.py [layer]+"""+from __future__ import annotations+import os, sys+import numpy as np+import torch++ENGINE = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+sys.path.insert(0, ENGINE)+from exllamav3.loader.gguf_collection import GGUFCollection # noqa: E402+from exllamav3.modules.foreign_linear import ForeignLinear # noqa: E402+from exllamav3.modules.block_sparse_mlp import BlockSparseMLP # noqa: E402+from exllamav3.foreign_quant import k_quants # noqa: E402++LAYER = int(sys.argv[1]) if len(sys.argv) > 1 else 0+FMT = {12: ("q4_k", 144, k_quants.dequant_q4_K_block), 13: ("q5_k", 176, k_quants.dequant_q5_K_block)}+++def deq(packed: np.ndarray, rows: int, cols: int, bb: int, fn) -> np.ndarray:+ nb = cols // 256+ out = np.empty((rows, cols), np.float32)+ for r in range(rows):+ for b in range(nb):+ out[r, b * 256:(b + 1) * 256] = fn(packed[r, b * bb:(b + 1) * bb].tobytes())+ return out+++def main() -> int:+ dev = torch.device("cuda")+ g = GGUFCollection(os.environ["FMOE_GGUF"])+ pre = f"blk.{LAYER}"+ H, I = g.infos[f"{pre}.ffn_gate_exps.weight"][1][0], g.infos[f"{pre}.ffn_gate_exps.weight"][1][1]+ E = g.infos[f"{pre}.ffn_gate_exps.weight"][1][2]+ tg, tu, td = (g.infos[f"{pre}.ffn_{n}_exps.weight"][0] for n in ("gate", "up", "down"))+ print(f"layer {LAYER}: H={H} I={I} E={E} gate/up type {tg}/{tu} down type {td}")+ fg, bbg, fng = FMT[tg]+ fd, bbd, fnd = FMT[td]+ assert FMT[tu][0] == fg++ def mk(name, fin, fout, fmt, out_dtype=None):+ m = ForeignLinear(None, name, fin, fout, fmt, out_dtype=out_dtype)+ m.packed = g.get_tensor(f"{pre}.ffn_{name.split('.')[0]}_exps.e{int(name.split('e')[-1])}.weight", device=dev)+ m.device = dev+ return m++ gates = [mk(f"gate.e{e}", H, I, fg) for e in range(E)]+ ups = [mk(f"up.e{e}", H, I, fg) for e in range(E)]+ downs = [mk(f"down.e{e}", I, H, fd, torch.float) for e in range(E)]+ print("packed shapes", tuple(gates[0].packed.shape), tuple(downs[0].packed.shape), "resident MiB",+ sum(m.packed.numel() for m in gates + ups + downs) >> 20)++ moe = BlockSparseMLP(None, "moe", hidden_size=H, intermediate_size=I, num_experts=E, num_experts_per_tok=8,+ activation_fn="silu", gates=gates, ups=ups, downs=downs)+ for m in gates + ups + downs:+ moe.register_submodule(m)+ moe.device = dev++ torch.manual_seed(3)+ byt1 = 8 * I * H * 2 * 144 / 256 + 8 * H * I * 176 / 256+ ref1 = None+ for N in (1, 2, 4, 8, 16, 32):+ x = (torch.randn(N, H, device=dev) * 0.5).half()+ sel = torch.stack([torch.randperm(E, device=dev)[:8] for _ in range(N)])+ wts = torch.softmax(torch.randn(N, 8, device=dev), -1).half()+ def run():+ return moe.forward(x, {"dec_routed": (sel, wts)})+ for _ in range(5):+ y = run().clone()+ torch.cuda.synchronize()+ a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)+ a.record()+ for _ in range(50):+ run()+ b.record()+ torch.cuda.synchronize()+ ms = a.elapsed_time(b) / 50+ # exactness: row-by-row bsz=1 forward (validated kernel) vs the N-row call+ rows = torch.cat([moe.forward(x[i:i + 1], {"dec_routed": (sel[i:i + 1], wts[i:i + 1])}).float().clone() for i in range(N)])+ rel = ((y.float() - rows).norm() / rows.norm()).item()+ print(f"N={N:2d}: {ms * 1000:7.0f} us/layer {ms * 1000 / N:6.0f} us/row rel_vs_rowwise={rel:.1e}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())