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
MXFP4 MoE decode: tuned grid and fused gate/up launch (EXL3_MXFP4_MOE_TUNED)
YanissAmz39b6c1ddb2b5
diff --git a/exllamav3/foreign_quant/triton_moe_mxfp4.py b/exllamav3/foreign_quant/triton_moe_mxfp4.pyindex dfed095..c3ec62e 100644--- a/exllamav3/foreign_quant/triton_moe_mxfp4.py+++ b/exllamav3/foreign_quant/triton_moe_mxfp4.py@@ -58,6 +58,59 @@ def moe_gemv(x: torch.Tensor, wtab: torch.Tensor, btab: torch.Tensor | None, sel"""x (rows, K) fp16 contiguous; sel (slots,) int32 expert ids; returns (slots, N) fp32."""slots = sel.numel()y = torch.empty((slots, N), dtype=torch.float32, device=x.device)- _mxfp4_moe[(triton.cdiv(N, BN), slots)](x, wtab, btab if btab is not None else wtab, sel, y, K, N, xdiv,- HAS_B=btab is not None, BN=BN, num_warps=NW)+ bn, nw = (TUNED_BN, TUNED_NW) if tuned() else (BN, NW)+ _mxfp4_moe[(triton.cdiv(N, bn), slots)](x, wtab, btab if btab is not None else wtab, sel, y, K, N, xdiv,+ HAS_B=btab is not None, BN=bn, num_warps=nw)return y+++def tuned() -> bool:+ """EXL3_MXFP4_MOE_TUNED=1 on CUDA (not HIP): fused gate+up launch + BN16/NW4 grids. Read at call time."""+ return os.environ.get("EXL3_MXFP4_MOE_TUNED", "0") == "1" and not torch.version.hip+++TUNED_BN = 16+TUNED_NW = 4+++def _gu_fused(x_ptr, gtab, gbtab, utab, ubtab, sel_ptr, a_ptr, K, N, LIM, BN: tl.constexpr):+ pid = tl.program_id(0)+ slot = tl.program_id(1)+ e = tl.load(sel_ptr + slot).to(tl.int64)+ gp = tl.load(gtab + e).to(tl.pointer_type(tl.uint8))+ up = tl.load(utab + e).to(tl.pointer_type(tl.uint8))+ Kb = K // 32+ rn = pid * BN + tl.arange(0, BN)+ mn = rn < N+ j = tl.arange(0, 16)+ row = rn.to(tl.int64) * (Kb * 17)+ ag = tl.zeros((BN,), dtype=tl.float32)+ au = tl.zeros((BN,), dtype=tl.float32)+ for kb in range(0, Kb):+ base = row + kb * 17+ xl = tl.load(x_ptr + kb * 32 + j).to(tl.float32)+ xh = tl.load(x_ptr + kb * 32 + 16 + j).to(tl.float32)+ dg = tl.exp2(tl.load(gp + base, mask=mn, other=0).to(tl.float32) - 128.0)+ du = tl.exp2(tl.load(up + base, mask=mn, other=0).to(tl.float32) - 128.0)+ qg = tl.load(gp + base[:, None] + 1 + j[None, :], mask=mn[:, None], other=0).to(tl.int32)+ qu = tl.load(up + base[:, None] + 1 + j[None, :], mask=mn[:, None], other=0).to(tl.int32)+ ag += tl.sum(_fp4half(qg & 15) * xl[None, :] + _fp4half(qg >> 4) * xh[None, :], axis=1) * dg+ au += tl.sum(_fp4half(qu & 15) * xl[None, :] + _fp4half(qu >> 4) * xh[None, :], axis=1) * du+ bg = tl.load(gbtab + e).to(tl.pointer_type(tl.float16))+ bu = tl.load(ubtab + e).to(tl.pointer_type(tl.float16))+ ag += tl.load(bg + rn, mask=mn, other=0.0).to(tl.float32)+ au += tl.load(bu + rn, mask=mn, other=0.0).to(tl.float32)+ g = ag.to(tl.float16).to(tl.float32) # the 3-launch path rounds g,u to fp16 before the activation+ u = au.to(tl.float16).to(tl.float32)+ g = tl.minimum(g, LIM)+ u = tl.minimum(tl.maximum(u, -LIM), LIM)+ a = (u + 1.0) * g * (1.0 / (1.0 + tl.exp(-1.702 * g))) # swiglu_oai+ tl.store(a_ptr + slot.to(tl.int64) * N + rn, a.to(tl.float16), mask=mn)+++def gu_fused(h, gw, gb, uw, ub, sel, I: int, K: int, lim: float) -> torch.Tensor:+ """Fused gate+up+bias+swiglu_oai: h (rows=1.., K) fp16, returns (slots, I) fp16. Single-row input only (x row 0 for all slots)."""+ a = torch.empty((sel.numel(), I), dtype=torch.float16, device=h.device)+ _gu_fused[(triton.cdiv(I, TUNED_BN), sel.numel())](h, gw, gb, uw, ub, sel, a, K, I, lim, BN=TUNED_BN, num_warps=TUNED_NW)+ return adiff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex b57ba97..bc0e4dd 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -1957,10 +1957,15 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):gb is not None and ub is not None):# EXL3_FQ_MMVQ_MXFP4=1 (CUDA): llama.cpp-style mmvq decode, q8_1 activations (see _mxfp4_mmvq_forward)return self._mxfp4_mmvq_forward(x, h, sel, (gw, gb, uw, ub, dw, db), I, K, H, routing_weights, params, out_dtype)- g = MX.moe_gemv(h, gw, gb, sel, I, K, S).half()- u = MX.moe_gemv(h, uw, ub, sel, I, K, S).half()- a = torch.empty_like(g)- self.activation_fn_call(g, u, a, self.act_limit)+ if (MX.tuned() and R == 1 and self.activation_fn == "swiglu_oai" and self.act_limit > 0 and+ gb is not None and ub is not None):+ # EXL3_MXFP4_MOE_TUNED=1 (CUDA): fused gate+up+bias+swiglu_oai launch, then down (BN16/NW4 both)+ a = MX.gu_fused(h, gw, gb, uw, ub, sel, I, K, float(self.act_limit))+ else:+ g = MX.moe_gemv(h, gw, gb, sel, I, K, S).half()+ u = MX.moe_gemv(h, uw, ub, sel, I, K, S).half()+ a = torch.empty_like(g)+ self.activation_fn_call(g, u, a, self.act_limit)d = MX.moe_gemv(a, dw, db, sel, self.downs[0].inner.fl.out_features, I, 1)routed = (d.view(R, S, -1)[..., :H] * routing_weights.reshape(R, S, 1).float()).sum(1)final_hidden_states = routed.view(x.shape)diff --git a/tests/test_mxfp4_moe_tuned_cpu.py b/tests/test_mxfp4_moe_tuned_cpu.pynew file mode 100644index 0000000..88177d2--- /dev/null+++ b/tests/test_mxfp4_moe_tuned_cpu.py@@ -0,0 +1,69 @@+"""CPU checks for EXL3_MXFP4_MOE_TUNED (no GPU, no kernel launch)."""+import importlib.util+import os+import re+import sys++import pytest+import torch++triton = pytest.importorskip("triton")++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+# Load the foreign_quant package by path: importing exllamav3 would build/load the CUDA extension.+_dir = os.path.join(ROOT, "exllamav3", "foreign_quant")+_spec = importlib.util.spec_from_file_location("fq_mx", os.path.join(_dir, "__init__.py"), submodule_search_locations=[_dir])+_pkg = importlib.util.module_from_spec(_spec)+sys.modules["fq_mx"] = _pkg+_spec.loader.exec_module(_pkg)+import fq_mx.triton_moe_mxfp4 as MX # noqa: E402+++def test_fused_branch_is_gated_and_else_is_unchanged():+ s = open(os.path.join(ROOT, "exllamav3", "modules", "block_sparse_mlp.py")).read()+ i = s.index("def _forward_mxfp4_grouped")+ body = s[i:s.index("def _forward_fp8_grouped", i)]+ m = re.search(r" if \(MX\.tuned\(\) and R == 1 and self\.activation_fn == \"swiglu_oai\" and self\.act_limit > 0 and\n"+ r" gb is not None and ub is not None\):\n.*?\n else:\n((?: [^\n]*\n)+)", body, re.S)+ assert m, "tuned branch not found"+ assert "MX.gu_fused(" in m.group(0).split(" else:")[0]+ else_lines = [l.strip() for l in m.group(1).splitlines()]+ assert else_lines == [+ "g = MX.moe_gemv(h, gw, gb, sel, I, K, S).half()",+ "u = MX.moe_gemv(h, uw, ub, sel, I, K, S).half()",+ "a = torch.empty_like(g)",+ "self.activation_fn_call(g, u, a, self.act_limit)",+ ]+++def launches(monkeypatch):+ rec = []++ class L:+ def __getitem__(self, grid):+ def call(*a, **k):+ rec.append((grid, k["BN"], k["num_warps"]))+ return call++ monkeypatch.setattr(MX, "_mxfp4_moe", L())+ return rec+++def _run(rec, monkeypatch, env, hip):+ monkeypatch.delenv("EXL3_MXFP4_MOE_TUNED", raising=False)+ if env is not None:+ monkeypatch.setenv("EXL3_MXFP4_MOE_TUNED", env)+ monkeypatch.setattr(torch.version, "hip", hip, raising=False)+ rec.clear()+ sel = torch.zeros(4, dtype=torch.int32)+ MX.moe_gemv(torch.zeros(1, 8), sel, None, sel, 2880, 2944, 4)+ return rec[0]+++def test_flag_semantics(launches, monkeypatch):+ assert _run(launches, monkeypatch, None, None)[1:] == (MX.BN, MX.NW) # default off, read at call time+ assert _run(launches, monkeypatch, "0", None)[1:] == (MX.BN, MX.NW)+ assert _run(launches, monkeypatch, "1", "6.1")[1:] == (MX.BN, MX.NW) # HIP ignores the flag+ grid, bn, nw = _run(launches, monkeypatch, "1", None)+ assert (bn, nw) == (16, 4) and grid == (180, 4)diff --git a/tests/test_mxfp4_moe_tuned_gpu.py b/tests/test_mxfp4_moe_tuned_gpu.pynew file mode 100644index 0000000..ae5b7fb--- /dev/null+++ b/tests/test_mxfp4_moe_tuned_gpu.py@@ -0,0 +1,65 @@+"""GPU check: EXL3_MXFP4_MOE_TUNED=1 (fused gate+up+bias+swiglu_oai, BN16/NW4) == flag off, bit for bit, R == 1."""+import importlib.util+import os+import sys++import pytest+import torch++pytestmark = pytest.mark.skipif(not torch.cuda.is_available() or bool(torch.version.hip), reason="needs CUDA")++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+H, K, I, ND, NE, S, LIM = 2880, 2944, 2880, 2880, 32, 4, 7.0 # gpt-oss-20b shapes (K = H padded to 128)+++def _load():+ d = os.path.join(ROOT, "exllamav3", "foreign_quant")+ spec = importlib.util.spec_from_file_location("fq_mxg", os.path.join(d, "__init__.py"), submodule_search_locations=[d])+ pkg = importlib.util.module_from_spec(spec)+ sys.modules["fq_mxg"] = pkg+ spec.loader.exec_module(pkg)+ import fq_mxg.triton_moe_mxfp4 as MX+ return MX+++def _experts(seed, N, Kk, dev):+ g = torch.Generator(device="cpu").manual_seed(seed)+ Kb = Kk // 32+ w = torch.randint(0, 256, (NE, N, Kb, 17), dtype=torch.uint8, generator=g) # GGUF block_mxfp4: [e8m0][16 bytes]+ w[..., 0] = torch.randint(118, 127, (NE, N, Kb), dtype=torch.uint8, generator=g)+ w = w.reshape(NE, N, Kb * 17).to(dev)+ b = (torch.randn(NE, N, generator=g) * 0.1).half().to(dev)+ wt = torch.tensor([w.data_ptr() + e * w[0].numel() for e in range(NE)], dtype=torch.int64, device=dev)+ bt = torch.tensor([b.data_ptr() + e * b[0].numel() * 2 for e in range(NE)], dtype=torch.int64, device=dev)+ return w, b, wt, bt+++def test_tuned_equals_untuned(monkeypatch):+ MX = _load()+ try:+ from exllamav3.ext import exllamav3_ext as ext+ oai = ext.silu_oai_mul+ except Exception:+ pytest.skip("needs the built extension (silu_oai_mul)")+ dev = torch.device("cuda")+ g_, u_, d_ = _experts(1, I, K, dev), _experts(2, I, K, dev), _experts(3, ND, I, dev)+ h = torch.nn.functional.pad(torch.randn(1, H, device=dev).half(), (0, K - H)).contiguous()+ sel = torch.tensor([3, 17, 5, 28], dtype=torch.int32, device=dev)++ def layer():+ if MX.tuned():+ a = MX.gu_fused(h, g_[2], g_[3], u_[2], u_[3], sel, I, K, LIM)+ else:+ g = MX.moe_gemv(h, g_[2], g_[3], sel, I, K, S).half()+ u = MX.moe_gemv(h, u_[2], u_[3], sel, I, K, S).half()+ a = torch.empty_like(g)+ oai(g, u, a, LIM)+ return MX.moe_gemv(a, d_[2], d_[3], sel, ND, I, 1)++ monkeypatch.setenv("EXL3_MXFP4_MOE_TUNED", "0")+ off = layer()+ monkeypatch.setenv("EXL3_MXFP4_MOE_TUNED", "1")+ on = layer()+ torch.cuda.synchronize()+ assert torch.isfinite(on).all()+ assert (on - off).abs().max().item() == 0.0