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
Fused MoE decode kernels: take 9-32 rows (up to 256 slots), not only 8
YanissAmz47ece7b8b1d5
diff --git a/exllamav3/exllamav3_ext/libtorch/blocksparse_mlp.cpp b/exllamav3/exllamav3_ext/libtorch/blocksparse_mlp.cppindex 2b44bfa..c4b5f44 100644--- a/exllamav3/exllamav3_ext/libtorch/blocksparse_mlp.cpp+++ b/exllamav3/exllamav3_ext/libtorch/blocksparse_mlp.cpp@@ -76,9 +76,10 @@ void BC_BlockSparseMLP::run_bszN// the weighted per-token reduction, with expert biases, padded dims (x zero-padded to the// quantized input width in the kernel, output trimmed to H) and expert-range masking// (out-of-range picks contribute exact zeros to the partial sum) handled inside. Nothing is- // captured or patched: routing tensors are read directly, so no per-bsz statics or graphs+ // captured or patched: routing tensors are read directly, so no per-bsz statics or graphs.+ // The row capacity is out_bszn's (python: up to 32 rows / 256 slots)int num_tokens = (int) y.size(0);- TORCH_CHECK(num_tokens >= 1 && num_tokens <= MAX_BSZN, "run_bszN: bsz out of supported range");+ TORCH_CHECK(num_tokens >= 1 && num_tokens <= out_bszn.size(0), "run_bszN: bsz out of supported range");c10::cuda::CUDAGuard device_guard(y.device());@@ -87,9 +88,16 @@ void BC_BlockSparseMLP::run_bszNc10::optional<at::Tensor> sh_o;if (shared_experts){- at::Tensor x_dense = y.unsqueeze(0);+ // The shared-expert graphs cover MAX_BSZN rows each: larger batches run as consecutive slices+ // (rows are independent), the first one included so that <= MAX_BSZN rows are unchangedat::Tensor out_d_sh_n = out_d_sh.value().slice(1, 0, num_tokens);- shared_experts->run_bszN(x_dense, out_d_sh_n);+ for (int a = 0; a < num_tokens; a += MAX_BSZN)+ {+ int n = std::min(MAX_BSZN, num_tokens - a);+ at::Tensor x_dense = y.slice(0, a, a + n).unsqueeze(0);+ at::Tensor d_n = out_d_sh_n.slice(1, a, a + n);+ shared_experts->run_bszN(x_dense, d_n);+ }sh_o = out_d_sh_n;}exl3_moe_coop_run(coop_p, coop_K_gu, coop_K_d, coop_cb, y, selected_experts, routing_weights, sh_o);@@ -249,6 +257,7 @@ BC_BlockSparseMLP::BC_BlockSparseMLP);coop_p.min_expert = min_expert;coop_p.max_expert = max_expert;+ coop_p.rows_ref = MAX_BSZN;}for (int i = 0; i < max_tokens_per_expert; ++i)diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cuindex 574ff4e..109719d 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cu@@ -152,6 +152,9 @@ void exl3_moe_coop_launch(const MoeCoopParams& p_in, int K_gu, int K_d, int cb,const int slots = p.bsz * p.topk;const int nproj = p.gated ? 2 : 1;p.a_global = p.bsz > 1;+ // A scratch built for more rows must not change the launch geometry of the rows it always served+ if (p.rows_ref > 0 && slots <= p.rows_ref * p.topk)+ p.slots_max = std::min(p.slots_max, p.rows_ref * p.topk);const bool wide_a = moe_coop_pick_wide(p.Hi / 16, slots, device);const bool wide_b = moe_coop_pick_wide(p.I / 16, slots, device);diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cuhindex 1ef66ec..3fd4ce6 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cuh+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_coop.cuh@@ -65,6 +65,8 @@ struct MoeCoopParamsint dbg; // diagnostics (EXL3_MOE_COOP_DBG): 1 skip A epilogue, 2 skip B reductionint* runs; // run table (bsz > 1): [n_runs, -, run_start[slots_max + 1], order[slots_max]]int slots_max;+ int rows_ref; // > 0: batches of up to rows_ref rows size their split-k / stream-K / run-table layout as if the+ // scratch held rows_ref * topk slots (the layout of the 8-row scratch), larger ones use all of itint rows_max; // token rows the output scratch holdsint n_local; // entries in the pointer tablesint sh_gate_n; // shared gate weight length (checked against H per call)diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex e4a0f7a..589a766 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -56,6 +56,10 @@ MOEG_ROWS = int(os.environ.get("EXL3_MOE_GROUPED_ROWS", 1 << 20))# restores the atomic addsFUSED_DET = os.environ.get("EXL3_MOE_FUSED_DET", "1") != "0"MAX_BSZN = 8 # must match MAX_BSZN in exllamav3_ext/libtorch/blocksparse_mlp.h+# 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+COOP_ROWS = max(MAX_BSZN, int(os.environ.get("EXL3_MOE_COOP_ROWS", "32"))) if torch.version.hip is None else MAX_BSZN# Row chunking: 9..EXL3_MOE_ROW_CHUNK_MAX rows of a pack without a fused MoE kernel run as <= MAX_BSZN-row slices through# the bszN decode kernels instead of the per-expert tier (host readback of the expert counts + one launch group per expert,# per layer); rows are independent in an MoE block. 0 disables. Measured on an RTX 3090 (Qwen3-30B-A3B 3INST)@@ -632,6 +636,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):self.routing_cfg = Noneself.experts_cfg = None+ self.coop_rows = MAX_BSZN # raised to the fused kernels' row capacity when the buffers are built# Persistent broadcast targets for TP ranks without the router (see forward)self.bcast_sel_bsz1 = None@@ -1064,7 +1069,8 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# graph loop's TEMP_ROWS_GRAPH requirement is larger, sharing the one cache entry per name# (g_tensor_cache is exact-shape-keyed and never evicts -- growing a differently-shaped# second entry under the same name would silently double memory forever)- bszn_rows = MAX_BSZN * numex+ self.coop_rows = max(MAX_BSZN, min(COOP_ROWS, 256 // numex))+ bszn_rows = self.coop_rows * numextemp_hidden = g_tensor_cache.get(device, (max(TEMP_ROWS_GRAPH * 2, bszn_rows), Hi), torch.half, "moe1_temp_hidden")temp_interm = g_tensor_cache.get(device, (max(TEMP_ROWS_GRAPH * 2, 2 * bszn_rows), I), self.interm_dtype, "moe1_temp_interm")@@ -1084,7 +1090,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# Completion counters + expert-run table of the fused decode kernels# (BC_BlockSparseMLP.run_bszN): the kernels reset each other's counters for the next# call, so they only need zeroing once- coop_ctr = g_tensor_cache.get(device, (bszn_rows * (I // 128) + MAX_BSZN * (Ho // 128) + 2 * bszn_rows + 3,), torch.int, "moe1_coop_ctr")+ coop_ctr = g_tensor_cache.get(device, (bszn_rows * (I // 128) + self.coop_rows * (Ho // 128) + 2 * bszn_rows + 3,), torch.int, "moe1_coop_ctr")coop_ctr.zero_()# Rotated up-projection input per slot for the fused kernels at bsz > 1 (yh holds the gate's)had_u = g_tensor_cache.get(device, (bszn_rows, Hi), torch.half, "moe1_temp_hidden_u")@@ -1096,7 +1102,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# Routed sum of the fused decode path, one exact-width row per token (the kernel trims the# padded down width on the way out)- out_bszn = g_tensor_cache.get(device, (MAX_BSZN, H), torch.float, "moe1_out_bszn")+ out_bszn = g_tensor_cache.get(device, (self.coop_rows, H), torch.float, "moe1_out_bszn")cfg = ExpertsCFG(yh = yh,@@ -1160,7 +1166,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):):self.bc_sh_exp = Truesh_exp_bc = self.shared_experts.bc- sh_exp_t = torch.empty((1, MAX_BSZN, self.hidden_size), dtype = torch.float, device = self.device)+ sh_exp_t = torch.empty((1, self.coop_rows, self.hidden_size), dtype = torch.float, device = self.device)if self.shared_gate:assert self.shared_gate.quant_type == "fp16"sh_gate_bc = self.shared_gate.inner.bc@@ -2019,7 +2025,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):out_dtype: torch.dtype | None = None) -> torch.Tensor:- if _ROW_CHUNK_MAX and MAX_BSZN < x.numel() // x.shape[-1] <= \+ if _ROW_CHUNK_MAX and self.coop_rows < x.numel() // x.shape[-1] <= \(min(_ROW_CHUNK_MAX, _FUSED_3INST_MIN) if self.support_fused else _ROW_CHUNK_MAX) and self._row_chunk_ok() and \not params.get("autosplit_measure"):return self._forward_row_chunks(x, params, out_dtype)@@ -2052,7 +2058,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# f_threshold-1 instead of MAX_BSZN). Expert-range shards (CPU split, TP) are masked# inside the kernel (out-of-range picks contribute exact zeros). Shared experts run# through BC_GatedMLP's own multi-row graph ahead of the kernel (see mlp.py)- bszn_eligible = self.bc is not None and bsz <= MAX_BSZN+ bszn_eligible = self.bc is not None and bsz <= self.coop_rows# Routingif self.router_pre_norm:@@ -2962,11 +2968,11 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):y = x.reshape(-1, x.shape[-1])routed = params.pop("dec_routed", None)outs = []- for a in range(0, y.shape[0], MAX_BSZN):+ for a in range(0, y.shape[0], self.coop_rows):sub = {k: v for k, v in params.items() if k != "mlp_residual_out"}if routed is not None:- sub["dec_routed"] = (routed[0][a:a + MAX_BSZN], routed[1][a:a + MAX_BSZN])- o = self.forward(y[a:a + MAX_BSZN].unsqueeze(0), sub, out_dtype)+ sub["dec_routed"] = (routed[0][a:a + self.coop_rows], routed[1][a:a + self.coop_rows])+ o = self.forward(y[a:a + self.coop_rows].unsqueeze(0), sub, out_dtype)outs.append(o.reshape(-1, o.shape[-1]).clone()) # the bszN output buffer is reused by the next slicereturn torch.cat(outs).view(x.shape[:-1] + (outs[0].shape[-1],))diff --git a/tests/test_moe_coop.py b/tests/test_moe_coop.pyindex b78eabd..dfbd9f7 100644--- a/tests/test_moe_coop.py+++ b/tests/test_moe_coop.py@@ -134,8 +134,8 @@ def run_case(seed, Kg, Ku, Kd, cb, act = "silu", gated = True, bias = False, limgu_u = torch.empty((smax, 1, I), dtype = gu_dt, device = DEV)act_out = torch.empty((smax, 1, I), dtype = torch.half, device = DEV)d_out = torch.empty((smax, 1, Ho), dtype = torch.float, device = DEV)- out = torch.full((8, H_out), float("nan"), dtype = torch.float, device = DEV)- ctr = torch.zeros((smax * (I // 128) + 8 * (Ho // 128) + 2 * smax + 3,), dtype = torch.int, device = DEV)+ out = torch.full((max(8, bsz), H_out), float("nan"), dtype = torch.float, device = DEV)+ ctr = torch.zeros((smax * (I // 128) + max(8, bsz) * (Ho // 128) + 2 * smax + 3,), dtype = torch.int, device = DEV)had_g = torch.empty((slots, Hi), dtype = torch.half, device = DEV); had_u = torch.empty_like(had_g)gtabs = gate.tabs if gated else up.tabsgK = gate.K if gated else up.K@@ -238,6 +238,16 @@ def test_batch_extremes():run_case(15, 2, 2, 2, 2, bsz = 8, topk = 32, E = 40, H = 512, Hi = 512, I = 384, Ho = 512, H_out = 512)+def test_many_rows():+ # 9..32 rows (verify batches of several requests): duplicates grouped into runs of ROWS, runs spanning the run table,+ # shared expert, expert-range masking, K widths on both register-dequant and staged paths+ run_case(30, 3, 3, 3, 2, bsz = 9, topk = 6, E = 24, H = 512, Hi = 512, I = 256, Ho = 512, H_out = 512, shared = "gated")+ run_case(31, 4, 4, 4, 1, bsz = 16, topk = 6, E = 20, H = 512, Hi = 512, I = 256, Ho = 512, H_out = 512)+ run_case(32, 2, 2, 5, 2, bsz = 32, topk = 8, E = 64, H = 256, Hi = 256, I = 256, Ho = 256, H_out = 256, shared = "plain")+ run_case(33, 4, 4, 4, 1, bsz = 32, topk = 8, E = 10, H = 256, Hi = 256, I = 256, Ho = 256, H_out = 256, min_e = 2, max_e = 8)+ run_case(34, 6, 6, 6, 0, bsz = 24, topk = 4, E = 5, H = 256, Hi = 256, I = 256, Ho = 256, H_out = 256, bias = True)++def test_odd_shapes():# k-slices not divisible by the 16-warp split, several column groupsrun_case(16, 4, 4, 4, 1, H = 640, Hi = 640, I = 896, Ho = 640, H_out = 640)