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
Router: multi-row Triton top-k instead of a stable sort over all experts
YanissAmze52465afb23a
diff --git a/exllamav3/modules/block_sparse_mlp_routing.py b/exllamav3/modules/block_sparse_mlp_routing.pyindex ea97e27..bbbe335 100644--- a/exllamav3/modules/block_sparse_mlp_routing.py+++ b/exllamav3/modules/block_sparse_mlp_routing.py@@ -209,6 +209,18 @@ def _hip_router_buffers(cfg, rows):def _routing_std_torch(cfg, y, params, include_bias = False):router_logits = torch.matmul(_pad_rows(y), cfg.gate_tensor)+ # EXL3_ROUTER_TOPK (default 1, read per call): prefill rows select top-k with one Triton pass (router_topk.py)+ # instead of the stable sort below over all experts; same ids, same values into the same softmax+ if (router_logits.dim() == 2 and router_logits.shape[0] > 16 and router_logits.is_cuda and router_logits.stride(1) == 1+ and not (include_bias and cfg.router_bias is not None) and not params.get("activate_all_experts")+ and cfg.num_experts_per_tok <= 32 and os.environ.get("EXL3_ROUTER_TOPK", "1") != "0"+ and not torch.cuda.is_current_stream_capturing()):+ from .router_topk import router_topk+ top_v, selected_experts = router_topk(router_logits, cfg.num_experts_per_tok)+ routing_weights = torch.softmax(top_v, dim = -1)+ if cfg.per_expert_scale is not None:+ routing_weights = routing_weights * cfg.per_expert_scale.float()[selected_experts]+ return selected_experts, routing_weights.half()router_logits_f = router_logits.float()if include_bias and cfg.router_bias is not None:router_logits_f = router_logits_f + cfg.router_bias.float()@@ -243,8 +255,15 @@ def _routing_nogroup_torch(cfg, y, params, scores):# at the k-th place, which expert is chosen). Router scores tie often, so identical inputs gave# different expert sets from run to run. A stable descending sort keeps the lowest expert index first# among equals: same values, reproducible routing.- selected_experts = torch.sort(selection_scores, dim = -1, descending = True, stable = True).indices[- :, :cfg.num_experts_per_tok].contiguous()+ if (selection_scores.dim() == 2 and selection_scores.shape[0] > 16 and selection_scores.is_cuda+ and selection_scores.stride(1) == 1 and cfg.num_experts_per_tok <= 32+ and os.environ.get("EXL3_ROUTER_TOPK", "1") != "0" and not torch.cuda.is_current_stream_capturing()):+ # EXL3_ROUTER_TOPK: same ids as the stable sort (router_topk.py)+ from .router_topk import router_topk+ selected_experts = router_topk(selection_scores, cfg.num_experts_per_tok)[1]+ else:+ selected_experts = torch.sort(selection_scores, dim = -1, descending = True, stable = True).indices[+ :, :cfg.num_experts_per_tok].contiguous()routing_weights = scores.gather(1, selected_experts)routing_weights = routing_weights / (routing_weights.sum(dim = -1, keepdim = True) + 1e-20)routing_weights = routing_weights * cfg.routed_scaling_factordiff --git a/exllamav3/modules/router_topk.py b/exllamav3/modules/router_topk.pynew file mode 100644index 0000000..221e3b0--- /dev/null+++ b/exllamav3/modules/router_topk.py@@ -0,0 +1,41 @@+"""+Multi-row router top-k (EXL3_ROUTER_TOPK, default 1, read per call). On ROCm the ext has no multi-row+routing_std, so prefill routing ran torch.sort(stable = True) over all experts per row plus ~5 staging copies+(~2.6 ms per 16384-row layer). This selects the same top-k directly: per row, k rounds of+(max, lowest index among the maxima), i.e. the order of a stable descending sort, NaN first as in torch.sort.+Values are copied, not computed, so the softmax that follows sees the same inputs: bit-identical routing.+"""+import torch+import triton+import triton.language as tl+++def _topk_kernel(x_ptr, v_ptr, i_ptr, E, XS, K: tl.constexpr, BE: tl.constexpr):+ r = tl.program_id(0).to(tl.int64)+ o = tl.arange(0, BE)+ m = o < E+ x = tl.load(x_ptr + r * XS + o, mask = m, other = 0.0).to(tl.float32)+ avail = m+ for j in tl.static_range(K):+ nan = avail & (x != x)+ hv = tl.max(tl.where(avail, tl.where(nan, float("inf"), x), float("-inf")), axis = 0)+ any_nan = tl.max(nan.to(tl.int32), axis = 0) > 0+ cand = tl.where(any_nan, nan, avail & (x == hv))+ idx = tl.min(tl.where(cand, o, BE), axis = 0)+ # x[idx] == hv (a signed zero may come back as the other zero: same softmax)+ tl.store(v_ptr + r * K + j, tl.where(any_nan, float("nan"), hv))+ tl.store(i_ptr + r * K + j, idx.to(tl.int64))+ avail = avail & (o != idx)+++def router_topk(logits: torch.Tensor, k: int):+ """logits (R, E) fp16/bf16/fp32, unit column stride -> (values (R, k) fp32, indices (R, k) int64),+ equal to torch.sort(logits.float(), -1, descending = True, stable = True)[:, :k]."""+ R, E = logits.shape+ assert logits.stride(1) == 1 and 1 <= k <= E+ v = torch.empty((R, k), dtype = torch.float, device = logits.device)+ i = torch.empty((R, k), dtype = torch.long, device = logits.device)+ if R:+ _topk_kernel[(R,)](logits, v, i, E, logits.stride(0), k, triton.next_power_of_2(E), num_warps = 4)+ return v, i