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
Hy4 latent MoE: exact pre-activation SwiGLU clamp as split gate / up limits (torch path; single-limit kernels decline)
YanissAmz10c45661d49e
diff --git a/exllamav3/ext_fallbacks.py b/exllamav3/ext_fallbacks.pyindex 7b7f21c..943767f 100644--- a/exllamav3/ext_fallbacks.py+++ b/exllamav3/ext_fallbacks.py@@ -26,8 +26,11 @@ def _act_mul(y: torch.Tensor,z: torch.Tensor,act_limit: float,+ act_limit_gate: float | None = None,+ act_limit_up: float | None = None,) -> None:- """Match act_mul_kernel_{h,f}'s dtype and clamp contract."""+ """Match act_mul_kernel_{h,f}'s dtype and clamp contract. act_limit_gate / act_limit_up (torch path only, no kernel+ takes them): min(act(x), act_limit_gate) and clip(y, +-act_limit_up), the split form of a pre-activation gate clamp."""if x.dtype not in (torch.float16, torch.float32) or y.dtype != x.dtype:raise TypeError("activation multiply expects matching float16 or float32 inputs")if z.dtype != torch.float16:@@ -37,6 +40,10 @@ def _act_mul(if act_limit != 0.0:x_act = x_act.clamp(max = act_limit)y = y.clamp(min = -act_limit, max = act_limit)+ if act_limit_gate is not None:+ x_act = torch.minimum(x_act, torch.as_tensor(act_limit_gate, dtype = x_act.dtype, device = x_act.device))+ if act_limit_up is not None:+ y = y.clamp(min = -act_limit_up, max = act_limit_up)result = x_act * y# The float-input native kernels saturate before the float-to-half store.if x.dtype == torch.float32:@@ -52,6 +59,35 @@ def silu_mul() -> None:_act_mul(F.silu, x, y, z, act_limit)++def silu_limit_exact(lim: float, dtype: torch.dtype) -> torch.Tensor:+ """silu(c) in `dtype` for the c whose silu is `lim` (= c * sigmoid(c), c > 0), computed by torch's own silu on c cast to+ `dtype`, so min(silu(g), silu_limit_exact(lim)) is bit-equal to silu(min(g, c)) (silu is monotone above -1.278)."""+ import math+ c = float(lim)+ for _ in range(60): # Newton on c * sigmoid(c) = lim, in float64+ sg = 1.0 / (1.0 + math.exp(-c))+ f = c * sg - lim+ d = sg * (1.0 + c * (1.0 - sg))+ if d == 0.0: break+ n = c - f / d+ if n == c: break+ c = n+ return F.silu(torch.tensor(c, dtype = dtype))+++def silu_mul_split(+ x: torch.Tensor,+ y: torch.Tensor,+ z: torch.Tensor,+ act_limit_gate: float | None = None,+ act_limit_up: float | None = None,+) -> None:+ """Hy4 swiglu_clamp_exp: silu(min(g, c)) * clip(u, -c, c) == min(silu(g), silu(c)) * clip(u, -c, c). Pure torch, any device;+ act_limit_gate = silu(c), act_limit_up = c."""+ lg = None if act_limit_gate is None else silu_limit_exact(act_limit_gate, x.dtype).to(x.device)+ _act_mul(F.silu, x, y, z, 0.0, lg, act_limit_up)+def silu_oai_mul(x: torch.Tensor,y: torch.Tensor,diff --git a/exllamav3/loader/gguf_blocks/mlp.py b/exllamav3/loader/gguf_blocks/mlp.pyindex 6b1a799..cc209d9 100644--- a/exllamav3/loader/gguf_blocks/mlp.py+++ b/exllamav3/loader/gguf_blocks/mlp.py@@ -181,6 +181,7 @@ def _latent_names(cfg, i, L, G):def _latent_build(config, plan, idx, L):+ import mathimport torchfrom ...modules import GatedMLP, BlockSparseMLPfrom ...architecture.gguf_generic import _fl@@ -197,8 +198,11 @@ def _latent_build(config, plan, idx, L):shared.register_submodule(m)kw = {}if c["clamp"]:- # the tree's clamp is post-activation; Hy4's is pre-activation (min(gate, c) then silu): they differ only for gate > c (<= 4.6e-4 at c = 10)- kw["act_limit"] = float(c["clamp"])+ # Hy4 (llama.cpp swiglu_clamp_exp) is silu(min(g, c)) * clip(u, -c, c); the engine's single act_limit clamps after the+ # activation. Exact split form (silu is increasing above -1.278, c > 0): min(silu(g), silu(c)) * clip(u, -c, c)+ cl = float(c["clamp"])+ kw["act_limit_gate"] = cl / (1.0 + math.exp(-cl)) # silu(c) = c * sigmoid(c)+ kw["act_limit_up"] = clmlp = BlockSparseMLP(config=config, key=f"{L}.mlp", hidden_size=H, intermediate_size=I, num_experts=E, shared_experts=shared,num_experts_per_tok=c["top_k"], norm_topk=bool(c["weights_norm"]), key_up=None, key_gate=None, key_down=None,key_routing_gate="gate", qmap="block.mlp", interm_dtype=torch.half, out_dtype=torch.float,diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex 7748763..bb5f7ea 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -10,6 +10,7 @@ from .multilinear import MultiLinearfrom .moe_mixedk import MixedKStore, MixedKUnsupported, expert_ks, layer_is_mixed, check_expert_bits, \PrunedLinear, pruned_experts, parse_expert_bitsfrom ..ext import exllamav3_ext as ext+from ..ext_fallbacks import silu_mul_splitfrom dataclasses import dataclassfrom .mlp import MLP, GatedMLPfrom .rmsnorm import RMSNorm@@ -389,6 +390,8 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):out_dtype: torch.dtype = None,activation_fn: str = "silu",act_limit: float = 0.0,+ act_limit_gate: float | None = None,+ act_limit_up: float | None = None,interm_dtype: torch.dtype = None,fused_fp16_interm: bool = True,interm_div: float = 1.0,@@ -455,6 +458,13 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):self.expert_size = latent_size or hidden_sizeself.router_type = router_typeself.act_limit = act_limit+ # Split clamp (Hy4 latent MoE): min(act(g), act_limit_gate) * clip(u, +-act_limit_up); None = the single act_limit above+ self.act_limit_gate = act_limit_gate+ self.act_limit_up = act_limit_up+ self._split_lim = act_limit_gate is not None or act_limit_up is not None+ self.split_declined = []+ if self._split_lim and (act_limit or activation_fn != "silu"):+ raise ValueError("split clamp limits need activation_fn silu and act_limit 0")self.alt_residual_channel = alt_residual_channelself.routing_first = routing_first@@ -686,6 +696,9 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):self.activation_fn_idx = 2case _:raise ValueError(f"Unknown activation function {activation_fn}")+ if self._split_lim:+ # torch-only activation: no CUDA / HIP kernel takes two limits+ self.activation_fn_call = lambda g, u, a, _lim = 0.0: silu_mul_split(g, u, a, self.act_limit_gate, self.act_limit_up)else:# Gateless relu2 rides the gated fast paths via relu(u) * u = relu2(u): the act call# sites pass (u, u, a) and the fused MoE kernel's MOE_ACT_RELU2_NOGATE synthesizes@@ -1495,7 +1508,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):return Noneif self.batch_recon is None:ok = (- self.tier is None and # reads the per-expert scale tensors, which a tiered layer does not keep+ not self._split_lim and self.tier is None and # reads the per-expert scale tensors, which a tiered layer does not keepBATCH_RECON and self.bc is not None and self.support_quant_paths andhasattr(ext, "reconstruct_batch") andself.interm_dtype in (torch.half, None, torch.float) and self.multi_up is not None and@@ -1657,7 +1670,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):EXL3_DEC_SHARED_FOLD (default 1; 0 = separate shared launch)."""self.dec_shf = Nonese = self.shared_experts- if not (se is not None and isinstance(se, GatedMLP) and hasattr(ext, "exl3_dec_moe_shared")): return+ if self._split_lim or not (se is not None and isinstance(se, GatedMLP) and hasattr(ext, "exl3_dec_moe_shared")): returnif (self.shared_gate is not None or self.shared_experts_post_norm is not None orself.routed_post_norm is not None or self.latent_in is not None or self.latent_out is not None orself.alt_residual_channel or getattr(se, "tp_reduce", False) or se.num_slices != 1): return@@ -2621,6 +2634,16 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):final_hidden_states = final_hidden_states.to(out_dtype)return final_hidden_states+ SPLIT_MSG = "split clamp limits need the two-limit kernel (Hy4 engine path)"++ def _split_decline(self, route: str) -> bool:+ """True (and recorded) when a GPU kernel route must not run: the kernels take one act_limit, split limits are torch-only."""+ if not getattr(self, "_split_lim", False):+ return False+ if route not in self.split_declined:+ self.split_declined.append(route)+ return True+def forward(self,x: torch.Tensor,@@ -2628,6 +2651,11 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):out_dtype: torch.dtype | None = None) -> torch.Tensor:+ # No fallback for these: EXL3 kernels (is_quantized) and the CPU expert host take one act_limit+ if getattr(self, "_split_lim", False) and (self.is_quantized or self.cpu_offload or self.cpu_split_first is not None):+ self._split_decline("exl3_or_cpu_host")+ raise NotImplementedError(self.SPLIT_MSG)+if gguf_ri("moe") and not params.get("autosplit_measure") and \2 <= x.numel() // x.shape[-1] <= GGUF_ROW_INV_MAX_ROWS and self._gguf_experts():return self._forward_rows_single(x, params, out_dtype)@@ -2707,13 +2735,14 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# (see _forward_foreign_grouped_kq). Tried first (Bolt returns None# without latent projs anyway).# MXFP4 experts at prefill (EXL3_MXFP4_PREFILL_GROUPED=1, rows above FQ_GROUPED_MAX_ROWS): routed-expert Triton dequant + grouped GEMM.- if bsz >= 2 and not params.get("activate_all_experts") and not params.get("reconstruct") and \+ split_no_foreign = self._split_decline("foreign_grouped") # fp8 / mxfp4 / KQ / foreign kernels: single act_limit+ if bsz >= 2 and not split_no_foreign and not params.get("activate_all_experts") and not params.get("reconstruct") and \not params.get("autosplit_measure") and not params.get("dflash_verify"):pf = self._forward_mxfp4_prefill_grouped(x, y, selected_experts, routing_weights, params, out_dtype, eshape)if pf is not None:return pf- if bsz <= FQ_GROUPED_MAX_ROWS and not params.get("activate_all_experts") and \+ if bsz <= FQ_GROUPED_MAX_ROWS and not split_no_foreign and not params.get("activate_all_experts") and \not params.get("reconstruct") and not params.get("autosplit_measure"):grouped = self._forward_fp8_grouped(x, y, selected_experts, routing_weights, params, out_dtype, eshape)@@ -2732,7 +2761,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):if grouped is not None:return grouped- if _MQ_MOE and FQ_GROUPED_MAX_ROWS < bsz <= _MQ_MOE_MAXR and not params.get("activate_all_experts") and not params.get("reconstruct") and not params.get("autosplit_measure") and not params.get("dflash_verify"):+ if _MQ_MOE and not split_no_foreign and FQ_GROUPED_MAX_ROWS < bsz <= _MQ_MOE_MAXR and not params.get("activate_all_experts") and not params.get("reconstruct") and not params.get("autosplit_measure") and not params.get("dflash_verify"):grouped = self._forward_foreign_grouped_kq(x, y, selected_experts, routing_weights, params, out_dtype, eshape, big=True)if grouped is not None:@@ -2743,7 +2772,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# (see _forward_foreign_prefill). Strict eligibility inside; falls# through otherwise. Skipped for DFlash verify batches (bit-exact# union path owns those).- if bsz > 1 and not params.get("activate_all_experts") and \+ if bsz > 1 and not split_no_foreign and not params.get("activate_all_experts") and \not params.get("reconstruct") and not params.get("autosplit_measure") and \not params.get("dflash_verify"):pf = self._forward_foreign_prefill_grouped(@@ -2780,6 +2809,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# gfx11.5 batch-1 fused decode (exl3_dec_moe): two launches for the whole routed sumelif (+ not self._split_lim andbsz == 1 and self.support_dec_moe and self.tp_mode is None and not (_MOE_VALU and self.support_hip_grouped) andy.dtype == torch.half and y.is_contiguous() andselected_experts.dtype == torch.long and routing_weights.dtype == torch.half and@@ -2883,6 +2913,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# build dominates), only R=2..5; EXL3_DEC_MOE_UNION=1 to use it anyway (e.g. to get a# bit-exact verify path even before that's fixed).elif (+ not self._split_lim and1 < bsz <= UNION_ROWS and self.support_dec_moe and self.tp_mode is None andnot (_MOE_VALU and self.support_hip_grouped and bsz <= 8) andhasattr(ext, "exl3_dec_moe_union") and@@ -2933,6 +2964,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# group partial sums added (moe_mixedk.MixedKStore.decode). Rows above the grouped cap and below the# WMMA threshold run the dense per-expert path, which is K-agnostic.elif (+ not self._split_lim andself.mixed_k is not None and self.support_hip_grouped and self.tp_mode is None and_hip_grouped_rows_eligible(bsz, False) andtuple(y.shape) == (bsz, self.expert_size) and y.dtype == torch.half and@@ -2955,6 +2987,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# gfx12 grouped decode/verification path: selected IDs and weights stay on-device,# and every row-major assignment slot remains distinct.elif (+ not self._split_lim andself.mixed_k is None and_hip_grouped_rows_eligible(bsz, self.support_hip_prefill) and self.support_hip_grouped andself.tp_mode is None and@@ -3001,6 +3034,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# so the fused kernel's per-expert count readback and tier planning are skipped for# eligible shapes.elif (+ not self._split_lim andself.support_hip_prefill and self.tp_mode is None and(self.num_local_experts == self.num_experts or(self.cpu_split_first is not None and self.routing_first == 0 and@@ -3061,6 +3095,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# Per-expert K layer, prefill: picks grouped by K, one WMMA launch set per group (compacted picks,# the kernel has no masked picks), per-token sum in routing-slot order (moe_mixedk.MixedKStore.prefill)elif (+ not self._split_lim andself.mixed_k is not None and self.support_hip_wmma and bsz >= _HIP_WMMA_MIN_ROWS andy.dtype == torch.half and (y.is_contiguous() or(y.dim() == 2 and y.stride(1) == 1 and y.stride(0) >= y.size(1) and y.stride(0) % 4 == 0)) and@@ -3093,6 +3128,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):# Grouped WMMA prefill (gfx11.5): one launch per projection over all experts, trellis# decoded inside the GEMM; replaces the per-expert reconstruct + hgemm loop at prefillelif (+ not self._split_lim andself.mixed_k is None and self.support_hip_wmma and bsz >= _HIP_WMMA_MIN_ROWS andy.dtype == torch.half and (y.is_contiguous() or # or a row-padded producer view(y.dim() == 2 and y.stride(1) == 1 and y.stride(0) >= y.size(1) and y.stride(0) % 4 == 0)) and@@ -3848,6 +3884,8 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):"n_group": self.n_group,"topk_group": self.topk_group,"act_limit": self.act_limit,+ "act_limit_gate": self.act_limit_gate,+ "act_limit_up": self.act_limit_up,"alt_residual_channel": self.alt_residual_channel,"key_tid2eid": self.tid2eid_key,"key_e_score_bias_vl": self.e_score_bias_vl_key,diff --git a/tests/test_gguf_hy4_moe.py b/tests/test_gguf_hy4_moe.pyindex 4eac62e..973e3b8 100644--- a/tests/test_gguf_hy4_moe.py+++ b/tests/test_gguf_hy4_moe.py@@ -168,7 +168,9 @@ def test_build_kwargs():mod = M._latent_build(cfg, plan, 1, "L")k = mod.kassert k["latent_size"] == 1536 and k["router_type"] == "ds3" and k["n_group"] == k["topk_group"] == 1 and k["norm_topk"] is True- assert abs(k["routed_scaling_factor"] - 3.998) < 1e-6 and k["act_limit"] == 10.0 and k["num_experts_per_tok"] == 16+ assert abs(k["routed_scaling_factor"] - 3.998) < 1e-6 and k["num_experts_per_tok"] == 16+ import math+ assert "act_limit" not in k and k["act_limit_up"] == 10.0 and abs(k["act_limit_gate"] - 10.0 / (1.0 + math.exp(-10.0))) < 1e-12 # exact split clamp: silu(c), cassert k["latent_in"] == ("L.mlp.fc1_latent_proj", 3072, 1536) and k["latent_out"] == ("L.mlp.fc2_latent_proj", 1536, 3072)assert k["gates"][0] == ("L.mlp.experts.0.gate_proj", 1536, 1536)sh = seen["n"][0]@@ -194,3 +196,94 @@ if __name__ == "__main__":for p, c in CASES:for r in check(p, c):print(f"{r[0]} | {r[1]} | ffn_moe_out rel {r[2]:.2e} cos {r[3]:.6f} | ffn_out(l_out-derived) rel {r[4]:.2e} cos {r[5]:.6f} | {r[6]}", flush=True)+++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))++# ---- split clamp (Hy4 swiglu_clamp_exp): silu(min(g, c)) * clip(u, -c, c) == min(silu(g), silu(c)) * clip(u, -c, c) ------------------------+# These run in a clean interpreter: the module tests above replace exllamav3.modules with stubs in this process.+_SPLIT_SCRIPT = r'''+import json, math, torch, torch.nn.functional as F+from exllamav3.ext_fallbacks import silu_mul, silu_mul_split+from exllamav3.modules.block_sparse_mlp import BlockSparseMLP+out = {}+torch.manual_seed(0)+def data(dt, c):+ g = (torch.rand(2048, 64) * 40 - 20).to(dt); u = (torch.rand(2048, 64) * 40 - 20).to(dt)+ g[:16] = (torch.rand(16, 64) * 8 + 10).to(dt) # rows with g > 10+ return g, u+mx, nbig, mxdef, mxdef_dtype = {}, 0, 0.0, []+for dt in (torch.float32, torch.float16):+ for c in (10.0, 2.0, 6.0, 7.5, 15.0, 0.75):+ g, u = data(dt, c); nbig = int((g > 10).any(1).sum())+ z = torch.empty(g.shape, dtype = torch.half)+ silu_mul_split(g, u, z, c / (1.0 + math.exp(-c)), c)+ ref = F.silu(torch.minimum(g, torch.tensor(c, dtype = dt))) * u.clamp(-c, c)+ if dt == torch.float32: ref = ref.clamp(-65504.0, 65504.0)+ mx[f"{str(dt)[6:]}_{c}"] = float((z.float() - ref.to(torch.half).float()).abs().max())+ # (b) default path against the previous formula, bit for bit+ for lim in (0.0, c):+ z0 = torch.empty(g.shape, dtype = torch.half); silu_mul(g, u, z0, lim)+ xa = F.silu(g)+ if lim != 0.0: xa = xa.clamp(max = lim); uu = u.clamp(min = -lim, max = lim)+ else: uu = u+ r0 = xa * uu+ if dt == torch.float32: r0 = r0.clamp(-65504.0, 65504.0)+ mxdef = max(mxdef, float((z0.float() - r0.to(torch.half).float()).abs().max()))+out["mx"], out["nbig"], out["mxdef"] = mx, nbig, mxdef+# (c) decline, no GPU: stubbed device check+m = BlockSparseMLP.__new__(BlockSparseMLP)+m._split_lim, m.split_declined = True, []+m.is_quantized, m.cpu_offload, m.cpu_split_first = True, False, None+out["decline_true"] = m._split_decline("hip_grouped")+try:+ m.forward(torch.zeros(1, 4), {})+ out["raised"] = None+except NotImplementedError as e:+ out["raised"] = str(e)+out["declined"] = m.split_declined+n = BlockSparseMLP.__new__(BlockSparseMLP); n._split_lim = False; n.split_declined = []+out["decline_default"] = n._split_decline("hip_grouped")+print("RESULT" + json.dumps(out))+'''+++def _split_run():+ import subprocess+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="")+ p = subprocess.run([sys.executable, "-c", _SPLIT_SCRIPT], cwd=ROOT, env=env, capture_output=True, text=True, timeout=120)+ if p.returncode != 0 and "libcudart" in p.stderr:+ pytest.skip("exllamav3 extension not importable here")+ assert p.returncode == 0, p.stderr[-800:]+ return json.loads(p.stdout.split("RESULT", 1)[1])++[email protected](scope="module")+def split_res():+ return _split_run()+++def test_split_clamp_exact_vs_reference(split_res):+ """(a) torch split path == silu(min(g, c)) * clip(u, -c, c), fp32 and fp16 inputs, g and u in [-20, 20], rows with g > 10 present"""+ assert split_res["nbig"] >= 16+ assert max(split_res["mx"].values()) == 0.0, split_res["mx"]+++def test_split_clamp_default_path_bit_identical(split_res):+ """(b) no split limits: ext_fallbacks.silu_mul (single act_limit) is bit-identical to the previous formula"""+ assert split_res["mxdef"] == 0.0+++def test_split_clamp_declines_gpu_routes(split_res):+ """(c) split limits record the decline on a GPU route and raise the clear error where no torch fallback exists; default never declines"""+ assert split_res["decline_true"] is True and split_res["decline_default"] is False+ assert split_res["raised"] == "split clamp limits need the two-limit kernel (Hy4 engine path)"+ assert "exl3_or_cpu_host" in split_res["declined"]+++def test_split_clamp_every_kernel_route_guarded():+ """every kernel `elif (` of the routed dispatch chain and every foreign grouped / prefill route checks the split flag"""+ src = open(os.path.join(ROOT, "exllamav3/modules/block_sparse_mlp.py")).read()+ a, b = src.index("# gfx11.5 batch-1 fused decode (exl3_dec_moe)"), src.index("# Torch/C++/fused path")+ assert src[a:b].count("elif (\n not self._split_lim and\n") == 7+ assert src.count("not split_no_foreign") == 4