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 prefill: routed-expert Triton dequant + grouped GEMM (EXL3_MXFP4_PREFILL_GROUPED)
YanissAmz47e7a1bd4248
diff --git a/exllamav3/foreign_quant/moe_mxfp4_prefill.py b/exllamav3/foreign_quant/moe_mxfp4_prefill.pynew file mode 100644index 0000000..1ea4749--- /dev/null+++ b/exllamav3/foreign_quant/moe_mxfp4_prefill.py@@ -0,0 +1,225 @@+"""MXFP4 routed experts in the grouped MoE prefill (CUDA only), EXL3_MXFP4_PREFILL_GROUPED=1 (default off).++Per prefill chunk: the experts routed in this chunk (and only those) are dequantized to an fp16 scratch [n, N, K] with ONE Triton+launch per projection and expert group (the 17-byte GGUF block_mxfp4: [e8m0][16 bytes, elements j | j + 16 << 4], same decode as+triton_gap FMT 2), then one grouped fp16 GEMM per projection over the expert-sorted rows (bias in the epilogue, gate+up in one+launch), the layer's own activation kernel (swiglu_oai clamp), and a down GEMM that adds the bias and scales the rows by the+routing weight. The scratch is freed at the end of the call: nothing stays resident between chunks. When the routed experts need more+than EXL3_MXFP4_PREFILL_SCRATCH_MB (default 1536) of scratch, they are processed in groups.++Value contract (same as the per-expert path it replaces, ForeignLinear gap_dequant + fp16 matmul + fp16 bias add + fp16 weight mul):+weights = fp16(2^(e-128) * fp4x2 value), g/u = fp16(acc) + fp16 bias rounded to fp16, a = activation(g, u) (same kernel),+dn = fp16(fp16(acc) + bias) * routing weight rounded to fp16; only the fp32 summation order of the top-k picks and the GEMM accumulate+order differ.+Env: EXL3_MXFP4_PREFILL_GROUPED (0/1), EXL3_MXFP4_PREFILL_GROUPED_MIN (min rows; default FQ_GROUPED_MAX_ROWS + 1, the rows above the+decode grouped path; a lower value forces the new path for short prompts, used by the oracle cell only), EXL3_MXFP4_PREFILL_SCRATCH_MB,+EXL3_MXFP4_PREFILL_BM / _BN / _BK / _NW / _NS (GEMM tile).+"""+from __future__ import annotations++import os++import numpy as np+import torch++try:+ import triton+ import triton.language as tl+ from .triton_gap import _fp4half+ HAVE_TRITON = True+except Exception: # CPU-only checks without triton+ HAVE_TRITON = False++FP4_X2 = (0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12) # gap_formats._FP4_HALF (fp4 value x 2; the scale is 2^(e-128))+FIRES = 0 # python-level count of run() calls (profiling / tests)+++def flag_on() -> bool:+ """EXL3_MXFP4_PREFILL_GROUPED=1 on CUDA (not HIP). Read at call time."""+ return os.environ.get("EXL3_MXFP4_PREFILL_GROUPED", "0") == "1" and bool(torch.version.cuda) and not torch.version.hip+++def use_prefill(rows: int, decode_max_rows: int) -> bool:+ """Dispatch: flag on, and rows >= EXL3_MXFP4_PREFILL_GROUPED_MIN (default decode_max_rows + 1) and >= 2."""+ if not flag_on():+ return False+ lo = int(os.environ.get("EXL3_MXFP4_PREFILL_GROUPED_MIN", str(decode_max_rows + 1)))+ return rows >= max(2, lo)+++def budget_bytes() -> int:+ return int(float(os.environ.get("EXL3_MXFP4_PREFILL_SCRATCH_MB", "1536")) * (1 << 20))+++def split_groups(n: int, per_expert_bytes: int, budget: int) -> list:+ """[(a, b)) ranges over n routed experts, each group's scratch <= budget (at least one expert per group), sizes balanced."""+ if n <= 0:+ return []+ cap = max(1, int(budget) // max(1, int(per_expert_bytes)))+ ng = -(-n // cap)+ base, extra = divmod(n, ng)+ out, a = [], 0+ for i in range(ng):+ b = a + base + (1 if i < extra else 0)+ out.append((a, b))+ a = b+ return out+++def ref_dequant_np(raw: np.ndarray) -> np.ndarray:+ """Numpy reference of the kernel: raw uint8 [N, Kb * 17] -> fp16 [N, Kb * 32] (what _dq_mx writes for one expert)."""+ n = raw.shape[0]+ b = raw.reshape(n, -1, 17)+ d = np.exp2(b[:, :, 0].astype(np.float32) - 128.0)[:, :, None]+ qs = b[:, :, 1:17]+ v = np.asarray(FP4_X2, dtype=np.float32)[np.concatenate([qs & 15, qs >> 4], axis=2).astype(np.int64)]+ return (d * v).reshape(n, -1).astype(np.float16)+++if HAVE_TRITON:+ @triton.jit+ def _dq_mx(wtab, eids, out, NB, BLK: tl.constexpr):+ pid = tl.program_id(0)+ s = tl.program_id(1)+ e = tl.load(eids + s).to(tl.int64)+ w = tl.load(wtab + e).to(tl.pointer_type(tl.uint8))+ b = pid.to(tl.int64) * BLK + tl.arange(0, BLK) # block index inside the expert, row n = b // Kb+ m = b < NB+ j = tl.arange(0, 16)+ base = b * 17+ d = tl.exp2(tl.load(w + base, mask=m, other=0).to(tl.float32) - 128.0)+ qs = tl.load(w + base[:, None] + 1 + j[None, :], mask=m[:, None], other=0).to(tl.int32)+ lo = (_fp4half(qs & 15) * d[:, None]).to(tl.float16)+ hi = (_fp4half(qs >> 4) * d[:, None]).to(tl.float16)+ o = out + s.to(tl.int64) * NB * 32 + b[:, None] * 32 + j[None, :]+ tl.store(o, lo, mask=m[:, None])+ tl.store(o + 16, hi, mask=m[:, None])++ @triton.jit+ def _gmm_mx(a_ptr, w_ptr, w2_ptr, out_ptr, out2_ptr, btab, b2tab, slot_ptr, tile_e, tile_r0, offs_ptr, wrow_ptr,+ N, K, stride_am, stride_om,+ DUAL: tl.constexpr, HAS_B: tl.constexpr, SCALE_ROWS: tl.constexpr,+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):+ pid_n = tl.program_id(0)+ t = tl.program_id(1)+ e = tl.load(tile_e + t)+ slot = tl.load(slot_ptr + e) # scratch slot of expert e in this group, -1 = not in it (or unused tile)+ if slot < 0:+ return+ r0 = tl.load(tile_r0 + t)+ r_end = tl.load(offs_ptr + e)+ offs_m = r0 + tl.arange(0, BM)+ mmask = offs_m < r_end+ offs_n = pid_n * BN + tl.arange(0, BN)+ nmask = offs_n < N+ kk = tl.arange(0, BK)+ wbase = slot.to(tl.int64) * N * K+ a_row = a_ptr + offs_m.to(tl.int64)[:, None] * stride_am+ w_col = w_ptr + wbase + offs_n.to(tl.int64)[None, :] * K+ acc = tl.zeros((BM, BN), dtype=tl.float32)+ if DUAL:+ w2_col = w2_ptr + wbase + offs_n.to(tl.int64)[None, :] * K+ acc2 = tl.zeros((BM, BN), dtype=tl.float32)+ for k in range(0, K, BK):+ a = tl.load(a_row + (k + kk)[None, :], mask=mmask[:, None], other=0.0)+ w = tl.load(w_col + (k + kk)[:, None], mask=nmask[None, :], other=0.0)+ acc = tl.dot(a, w, acc)+ if DUAL:+ w2 = tl.load(w2_col + (k + kk)[:, None], mask=nmask[None, :], other=0.0)+ acc2 = tl.dot(a, w2, acc2)+ res = acc.to(tl.float16)+ if HAS_B:+ bp = tl.load(btab + e).to(tl.pointer_type(tl.float16))+ bv = tl.load(bp + offs_n, mask=nmask, other=0.0).to(tl.float32)+ res = (res.to(tl.float32) + bv[None, :]).to(tl.float16)+ if SCALE_ROWS:+ wr = tl.load(wrow_ptr + offs_m, mask=mmask, other=0.0).to(tl.float32)+ res = (res.to(tl.float32) * wr[:, None]).to(tl.float16)+ o = out_ptr + offs_m.to(tl.int64)[:, None] * stride_om + offs_n[None, :]+ tl.store(o, res, mask=mmask[:, None] & nmask[None, :])+ if DUAL:+ res2 = acc2.to(tl.float16)+ if HAS_B:+ bp2 = tl.load(b2tab + e).to(tl.pointer_type(tl.float16))+ bv2 = tl.load(bp2 + offs_n, mask=nmask, other=0.0).to(tl.float32)+ res2 = (res2.to(tl.float32) + bv2[None, :]).to(tl.float16)+ o2 = out2_ptr + offs_m.to(tl.int64)[:, None] * stride_om + offs_n[None, :]+ tl.store(o2, res2, mask=mmask[:, None] & nmask[None, :])+++def dequant_group(wtab: torch.Tensor, ids: torch.Tensor, out: torch.Tensor, N: int, K: int) -> None:+ """ONE launch: experts ids (int32 [n]) of the int64 pointer table wtab -> fp16 out[n, N, K]."""+ NB = N * (K // 32)+ BLK = 128+ _dq_mx[(triton.cdiv(NB, BLK), ids.numel())](wtab, ids, out, NB, BLK=BLK, num_warps=4)+++def _gemm(a, w, w2, out, out2, btab, b2tab, slot_of, tiles, wrow, N, K, bm):+ tile_e, tile_r0, offs = tiles+ dual = w2 is not None+ bn = int(os.environ.get("EXL3_MXFP4_PREFILL_BN", "64" if dual else "128"))+ bk = int(os.environ.get("EXL3_MXFP4_PREFILL_BK", "32"))+ nw = int(os.environ.get("EXL3_MXFP4_PREFILL_NW", "8"))+ ns = int(os.environ.get("EXL3_MXFP4_PREFILL_NS", "3"))+ assert K % bk == 0, (K, bk)+ has_b = btab is not None+ z = offs+ _gmm_mx[(triton.cdiv(N, bn), tile_e.shape[0])](+ a, w, w2 if dual else w, out, out2 if dual else out, btab if has_b else z, b2tab if (has_b and dual) else z,+ slot_of, tile_e, tile_r0, offs, wrow if wrow is not None else offs, N, K, a.stride(0), out.stride(0),+ DUAL=dual, HAS_B=has_b, SCALE_ROWS=wrow is not None, BM=bm, BN=bn, BK=bk, num_warps=nw, num_stages=ns)+++def run(h, sel, wts, tbl, E, I, K, N, act_fn, act_limit, budget=None):+ """h half [R, K] contiguous (zero-padded to the experts' K); sel long [R, top_k]; wts half [R, top_k];+ tbl = the decode path's pointer tables (_, dev, gw, gb, uw, ub, dw, db). Returns fp32 [R, N] (routing-weighted sum of the experts)."""+ global FIRES+ from ..modules.fq_moe_prefill import build_tiles+ FIRES += 1+ R, top_k = sel.shape+ dev = h.device+ M = R * top_k+ _, _, gw, gb, uw, ub, dw, db = tbl+ bm = int(os.environ.get("EXL3_MXFP4_PREFILL_BM", "128"))+ flat_e = sel.reshape(-1)+ order = flat_e.argsort(stable=True)+ token_sorted = order // top_k+ wrow = wts.reshape(-1)[order].contiguous()+ counts = torch.bincount(flat_e, minlength=E)+ routed = torch.nonzero(counts).flatten().to(torch.int32) # one host sync per layer (n routed experts)+ n = routed.numel()+ xs = h.index_select(0, token_sorted)+ tiles = build_tiles(counts, M, bm)+ groups = split_groups(n, max(2 * I * K, N * I) * 2, budget if budget is not None else budget_bytes())+ slot_of = torch.empty(E + 1, dtype=torch.int32, device=dev)+ ar = torch.arange(n, dtype=torch.int32, device=dev)++ def set_slots(a, b):+ slot_of.fill_(-1)+ slot_of[routed[a:b].long()] = ar[:b - a]+ return routed[a:b]++ g = torch.empty((M, I), dtype=torch.half, device=dev)+ u = torch.empty((M, I), dtype=torch.half, device=dev)+ for a, b in groups:+ ids = set_slots(a, b)+ wg = torch.empty((b - a, I, K), dtype=torch.half, device=dev)+ wu = torch.empty((b - a, I, K), dtype=torch.half, device=dev)+ dequant_group(gw, ids, wg, I, K)+ dequant_group(uw, ids, wu, I, K)+ _gemm(xs, wg, wu, g, u, gb, ub, slot_of, tiles, None, I, K, bm)+ del wg, wu+ act = torch.empty_like(g)+ act_fn(g, u, act, act_limit)+ del g, u, xs+ dn = torch.empty((M, N), dtype=torch.half, device=dev)+ for a, b in groups:+ ids = set_slots(a, b)+ wd = torch.empty((b - a, N, I), dtype=torch.half, device=dev)+ dequant_group(dw, ids, wd, N, I)+ _gemm(act, wd, None, dn, None, db, None, slot_of, tiles, wrow, N, I, bm)+ del wd+ del act+ inv = torch.empty_like(order)+ inv[order] = torch.arange(M, device=dev)+ return dn.index_select(0, inv).view(R, top_k, N).float().sum(1)diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex bc0e4dd..a8b5359 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -1976,6 +1976,50 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):final_hidden_states = final_hidden_states.to(out_dtype)return final_hidden_states+ def _forward_mxfp4_prefill_grouped(self, x, y, selected_experts, routing_weights, params, out_dtype, eshape):+ """EXL3_MXFP4_PREFILL_GROUPED=1 (CUDA): MXFP4 experts at prefill. The experts routed in this chunk are dequantized to a per-chunk fp16+ scratch with one launch per projection (moe_mxfp4_prefill.py), grouped fp16 GEMMs with bias, the layer's activation, down GEMM x routing+ weight; nothing stays resident. Returns the block output or None (the caller keeps today's paths)."""+ from ..foreign_quant import moe_mxfp4_prefill as MP+ R = y.shape[0]+ if not MP.use_prefill(R, FQ_GROUPED_MAX_ROWS):+ return None+ if not self._mxfp4_grouped_ok(y) or (self.num_local_experts or self.num_experts) != self.num_experts:+ return None+ S = self.num_experts_per_tok+ if tuple(selected_experts.shape) != (R, S) or selected_experts.dtype != torch.long:+ return None+ fg, fd = self.gates[0].inner.fl, self.downs[0].inner.fl+ K, I, N = fg.in_features, fg.out_features, fd.out_features+ H = y.shape[1]+ if fd.in_features != I or K < H or K % 32 or I % 32:+ return None+ if any(m.inner.bias is not None and (m.inner.bias.dtype != torch.half or not m.inner.bias.is_contiguous())+ for m in self.gates + self.ups + self.downs):+ return None+ h = y.contiguous()+ if K != H:+ h = torch.nn.functional.pad(h, (0, K - H)).contiguous()+ dev = h.device+ tbl = getattr(self, "_mx_ptrs", None)+ if tbl is None or tbl[0] != fg.packed.data_ptr() or tbl[1] != dev:+ mk = lambda ms: torch.tensor([m.inner.fl.packed.data_ptr() for m in ms], dtype=torch.int64, device=dev)+ mb = lambda ms: torch.tensor([m.inner.bias.data_ptr() for m in ms], dtype=torch.int64, device=dev) \+ if all(m.inner.bias is not None for m in ms) else None+ tbl = (fg.packed.data_ptr(), dev, mk(self.gates), mb(self.gates), mk(self.ups), mb(self.ups), mk(self.downs), mb(self.downs))+ self._mx_ptrs = tbl+ if (tbl[3] is None) != (tbl[5] is None):+ return None+ wts = routing_weights if routing_weights.dtype == torch.half else routing_weights.to(torch.half)+ routed = MP.run(h, selected_experts.contiguous(), wts.contiguous(), tbl, self.num_experts, I, K, N, self.activation_fn_call, self.act_limit)+ final_hidden_states = routed[:, :H].reshape(eshape)+ if self.shared_experts is not None:+ se = self.shared_experts.forward(x, params)+ final_hidden_states = final_hidden_states + se.to(torch.float).view(final_hidden_states.shape)+ if out_dtype is not None:+ final_hidden_states = final_hidden_states.to(out_dtype)+ return final_hidden_states+def _forward_fp8_grouped(self, x, y, selected_experts, routing_weights, params, out_dtype, eshape):"""Grouped FP8 MoE decode (R <= FQ_GROUPED_MAX_ROWS rows): gate and up of every (row, expert) slot in one launch each,SiLU * up in torch, down in one launch, weighted fold per row; then the shared expert as the KQ grouped path does."""@@ -2639,6 +2683,13 @@ 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).+ # 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 \+ 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 \not params.get("reconstruct") and not params.get("autosplit_measure"):grouped = self._forward_fp8_grouped(diff --git a/tests/test_mxfp4_prefill_grouped_cpu.py b/tests/test_mxfp4_prefill_grouped_cpu.pynew file mode 100644index 0000000..5a539ee--- /dev/null+++ b/tests/test_mxfp4_prefill_grouped_cpu.py@@ -0,0 +1,174 @@+"""CPU checks for the MXFP4 grouped prefill (foreign_quant/moe_mxfp4_prefill.py), EXL3_MXFP4_PREFILL_GROUPED. No GPU, no extension build.+1. numpy reference of the dequant kernel == gap_formats.dequant('mxfp4') on the same bytes (bitwise, all 256 scale bytes)+2. scratch budget grouping (split_groups)+3. dispatch: flag 0/1, min rows, forced low min, HIP / no CUDA; BlockSparseMLP._forward_mxfp4_prefill_grouped with a stub self (run() stubbed).+Modules are loaded by path and the method is cut out of the source by ast: nothing imports exllamav3.ext."""+import ast+import importlib.util+import os+import sys+import types++import numpy as np+import pytest+import torch++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+PKG = os.path.join(ROOT, "exllamav3")+++def _load_all():+ """Load gap_formats, triton_gap (if triton), fq_moe_prefill (if triton) and moe_mxfp4_prefill by path under empty parent packages,+ so that exllamav3/__init__ (which builds the C++ extension) never runs. Returns (modules dict, parent packages)."""+ pk = {n: types.ModuleType(n) for n in ("exllamav3", "exllamav3.foreign_quant", "exllamav3.modules")}+ pk["exllamav3"].__path__ = [PKG]+ pk["exllamav3.foreign_quant"].__path__ = [os.path.join(PKG, "foreign_quant")]+ pk["exllamav3.modules"].__path__ = [os.path.join(PKG, "modules")]+ for k, v in pk.items():+ sys.modules[k] = v+ try:+ import triton # noqa: F401+ have = True+ except Exception:+ have = False+ out = {}+ for name, rel, needs in (("exllamav3.foreign_quant.gap_formats", "foreign_quant/gap_formats.py", False),+ ("exllamav3.foreign_quant.triton_gap", "foreign_quant/triton_gap.py", True),+ ("exllamav3.modules.fq_moe_prefill", "modules/fq_moe_prefill.py", True),+ ("exllamav3.foreign_quant.moe_mxfp4_prefill", "foreign_quant/moe_mxfp4_prefill.py", False)):+ if needs and not have:+ continue+ spec = importlib.util.spec_from_file_location(name, os.path.join(PKG, rel))+ m = importlib.util.module_from_spec(spec)+ sys.modules[name] = m+ spec.loader.exec_module(m)+ parent, _, leaf = name.rpartition(".")+ setattr(pk[parent], leaf, m)+ out[leaf] = m+ return out+++def _mlp_method(name="_forward_mxfp4_prefill_grouped", fq_max_rows=128):+ """The BlockSparseMLP method under test, compiled from the source file without importing the module."""+ tree = ast.parse(open(os.path.join(PKG, "modules/block_sparse_mlp.py")).read())+ cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "BlockSparseMLP")+ fn = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == name)+ ns = {"torch": torch, "FQ_GROUPED_MAX_ROWS": fq_max_rows, "__name__": "exllamav3.modules.block_sparse_mlp",+ "__package__": "exllamav3.modules"}+ exec(compile(ast.fix_missing_locations(ast.Module(body=[fn], type_ignores=[])), "block_sparse_mlp.py", "exec"), ns)+ return ns[name]++[email protected](scope="module")+def mods():+ saved = {k: sys.modules.get(k) for k in list(sys.modules) if k == "exllamav3" or k.startswith("exllamav3.")}+ try:+ yield _load_all()+ finally:+ for k in [k for k in sys.modules if k == "exllamav3" or k.startswith("exllamav3.")]:+ sys.modules.pop(k)+ sys.modules.update({k: v for k, v in saved.items() if v is not None})+++def clean_env(monkeypatch):+ for k in ("EXL3_MXFP4_PREFILL_GROUPED", "EXL3_MXFP4_PREFILL_GROUPED_MIN"):+ monkeypatch.delenv(k, raising=False)+ return monkeypatch+++def test_dequant_reference_matches_engine(mods):+ MP, gf = mods["moe_mxfp4_prefill"], mods["gap_formats"]+ rng = np.random.default_rng(0)+ for N, Kb in ((8, 7), (3, 90), (16, 1)):+ raw = rng.integers(0, 256, size=(N, Kb * 17), dtype=np.uint8)+ raw.reshape(N, Kb, 17)[:, :, 0] = rng.integers(100, 150, size=(N, Kb))+ ref = MP.ref_dequant_np(raw)+ eng = gf.dequant("mxfp4", torch.from_numpy(raw)).numpy()+ assert ref.shape == eng.shape and ref.dtype == eng.dtype and np.array_equal(ref.view(np.uint16), eng.view(np.uint16))+ raw = np.zeros((256, 17), dtype=np.uint8)+ raw[:, 0] = np.arange(256)+ raw[:, 1:] = rng.integers(0, 256, size=(256, 16), dtype=np.uint8)+ eng = gf.dequant("mxfp4", torch.from_numpy(raw)).numpy()+ assert np.array_equal(MP.ref_dequant_np(raw).view(np.uint16), eng.view(np.uint16))+ assert tuple(MP.FP4_X2) == tuple(gf._FP4_HALF)++[email protected]("n,bud,exp", [(0, 1 << 30, 0), (1, 1, 1), (32, 1536 << 20, 1), (32, 600 << 20, 2), (32, 100 << 20, 11), (5, 1, 5)])+def test_split_groups(mods, n, bud, exp):+ MP = mods["moe_mxfp4_prefill"]+ pe = max(2 * 2880 * 2880, 2880 * 2880) * 2+ g = MP.split_groups(n, pe, bud)+ assert len(g) == exp+ if g:+ assert g[0][0] == 0 and g[-1][1] == n and all(g[i][1] == g[i + 1][0] for i in range(len(g) - 1))+ cap = max(1, bud // pe)+ assert all(b - a <= cap and b > a for a, b in g)+ assert max([b - a for a, b in g], default=0) - min([b - a for a, b in g], default=0) <= 1+++def test_budget_env(mods, clean_env):+ MP = mods["moe_mxfp4_prefill"]+ assert MP.budget_bytes() == 1536 << 20+ clean_env.setenv("EXL3_MXFP4_PREFILL_SCRATCH_MB", "64")+ assert MP.budget_bytes() == 64 << 20+++def test_use_prefill(mods, clean_env):+ MP = mods["moe_mxfp4_prefill"]+ clean_env.setattr(torch.version, "cuda", "12.8")+ clean_env.setattr(torch.version, "hip", None)+ assert not MP.use_prefill(8192, 128) # unset -> off+ clean_env.setenv("EXL3_MXFP4_PREFILL_GROUPED", "0")+ assert not MP.use_prefill(8192, 128)+ clean_env.setenv("EXL3_MXFP4_PREFILL_GROUPED", "1")+ assert MP.use_prefill(8192, 128) and MP.use_prefill(129, 128)+ assert not MP.use_prefill(128, 128) and not MP.use_prefill(1, 128)+ clean_env.setenv("EXL3_MXFP4_PREFILL_GROUPED_MIN", "2")+ assert MP.use_prefill(34, 128) and not MP.use_prefill(1, 128)+ clean_env.setattr(torch.version, "hip", "6.2")+ assert not MP.use_prefill(8192, 128)+ clean_env.setattr(torch.version, "hip", None)+ clean_env.setattr(torch.version, "cuda", None)+ assert not MP.use_prefill(8192, 128)+++def _stub(ok=True, bias=True, E=4, H=64, I=32):+ ns = types.SimpleNamespace++ def lin(i, o):+ return ns(inner=ns(fl=ns(in_features=i, out_features=o, packed=torch.zeros(4, dtype=torch.uint8)),+ bias=torch.zeros(o, dtype=torch.half) if bias else None))+ s = ns(_mxfp4_grouped_ok=lambda y: ok, num_local_experts=None, num_experts=E, num_experts_per_tok=2, shared_experts=None, act_limit=7.0,+ activation_fn_call=lambda g, u, a, l: None)+ s.gates, s.ups, s.downs = [lin(H, I) for _ in range(E)], [lin(H, I) for _ in range(E)], [lin(I, H) for _ in range(E)]+ return s+++def test_dispatch(mods, clean_env):+ MP = mods["moe_mxfp4_prefill"]+ clean_env.setattr(torch.version, "cuda", "12.8")+ clean_env.setattr(torch.version, "hip", None)+ meth = _mlp_method()+ calls = []++ def fake_run(h, sel, wts, tbl, E, I, K, N, act_fn, lim, budget=None):+ calls.append((tuple(h.shape), tuple(sel.shape), wts.dtype, E, I, K, N, lim))+ return torch.zeros(h.shape[0], N)+ clean_env.setattr(MP, "run", fake_run)++ def call(rows, **kw):+ y = torch.zeros(rows, 64, dtype=torch.half)+ sel = torch.zeros(rows, 2, dtype=torch.long)+ return meth(_stub(**kw), y, y, sel, torch.ones(rows, 2), {}, None, (rows, 64))++ assert call(300) is None and not calls # flag off+ clean_env.setenv("EXL3_MXFP4_PREFILL_GROUPED", "1")+ r = call(300)+ assert r is not None and len(calls) == 1+ assert calls[0] == ((300, 64), (300, 2), torch.half, 4, 32, 64, 64, 7.0)+ calls.clear()+ assert call(128) is None and not calls # rows == decode max+ assert call(300, ok=False) is None and not calls # layer not eligible+ clean_env.setenv("EXL3_MXFP4_PREFILL_GROUPED_MIN", "2")+ assert call(34) is not None and len(calls) == 1diff --git a/tests/test_mxfp4_prefill_grouped_gpu.py b/tests/test_mxfp4_prefill_grouped_gpu.pynew file mode 100644index 0000000..9a68655--- /dev/null+++ b/tests/test_mxfp4_prefill_grouped_gpu.py@@ -0,0 +1,147 @@+"""GPU checks for the MXFP4 grouped prefill (EXL3_MXFP4_PREFILL_GROUPED): small random packed MXFP4 experts.+1. _dq_mx (Triton) == gap_formats.dequant('mxfp4') exactly+2. BlockSparseMLP._forward_mxfp4_prefill_grouped output vs the per-expert dequant + fp16 matmul path, rel L2 < 1e-2.+Modules are loaded by path (no extension build); the activation is the pure-torch silu_oai_mul of ext_fallbacks."""+import ast+import importlib.util+import os+import sys+import types++import pytest+import torch++try:+ import triton # noqa: F401+ HAVE_TRITON = True+except Exception:+ HAVE_TRITON = False++pytestmark = pytest.mark.skipif(not torch.cuda.is_available() or not HAVE_TRITON, reason="needs CUDA and triton")++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+PKG = os.path.join(ROOT, "exllamav3")+++def _load_all():+ """Load gap_formats, triton_gap (if triton), fq_moe_prefill (if triton) and moe_mxfp4_prefill by path under empty parent packages,+ so that exllamav3/__init__ (which builds the C++ extension) never runs. Returns (modules dict, parent packages)."""+ pk = {n: types.ModuleType(n) for n in ("exllamav3", "exllamav3.foreign_quant", "exllamav3.modules")}+ pk["exllamav3"].__path__ = [PKG]+ pk["exllamav3.foreign_quant"].__path__ = [os.path.join(PKG, "foreign_quant")]+ pk["exllamav3.modules"].__path__ = [os.path.join(PKG, "modules")]+ for k, v in pk.items():+ sys.modules[k] = v+ try:+ import triton # noqa: F401+ have = True+ except Exception:+ have = False+ out = {}+ for name, rel, needs in (("exllamav3.foreign_quant.gap_formats", "foreign_quant/gap_formats.py", False),+ ("exllamav3.foreign_quant.triton_gap", "foreign_quant/triton_gap.py", True),+ ("exllamav3.modules.fq_moe_prefill", "modules/fq_moe_prefill.py", True),+ ("exllamav3.foreign_quant.moe_mxfp4_prefill", "foreign_quant/moe_mxfp4_prefill.py", False)):+ if needs and not have:+ continue+ spec = importlib.util.spec_from_file_location(name, os.path.join(PKG, rel))+ m = importlib.util.module_from_spec(spec)+ sys.modules[name] = m+ spec.loader.exec_module(m)+ parent, _, leaf = name.rpartition(".")+ setattr(pk[parent], leaf, m)+ out[leaf] = m+ return out+++def _mlp_method(name="_forward_mxfp4_prefill_grouped", fq_max_rows=128):+ """The BlockSparseMLP method under test, compiled from the source file without importing the module."""+ tree = ast.parse(open(os.path.join(PKG, "modules/block_sparse_mlp.py")).read())+ cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "BlockSparseMLP")+ fn = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == name)+ ns = {"torch": torch, "FQ_GROUPED_MAX_ROWS": fq_max_rows, "__name__": "exllamav3.modules.block_sparse_mlp",+ "__package__": "exllamav3.modules"}+ exec(compile(ast.fix_missing_locations(ast.Module(body=[fn], type_ignores=[])), "block_sparse_mlp.py", "exec"), ns)+ return ns[name]++[email protected](scope="module")+def mods():+ saved = {k: sys.modules.get(k) for k in list(sys.modules) if k == "exllamav3" or k.startswith("exllamav3.")}+ try:+ m = _load_all()+ spec = importlib.util.spec_from_file_location("_exl3_fallbacks", os.path.join(PKG, "ext_fallbacks.py"))+ fb = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(fb)+ m["fallbacks"] = fb+ yield m+ finally:+ for k in [k for k in sys.modules if k == "exllamav3" or k.startswith("exllamav3.")]:+ sys.modules.pop(k)+ sys.modules.update({k: v for k, v in saved.items() if v is not None})+++def _rand_packed(n, k, gen, dev):+ """[n, k/32 * 17] uint8: realistic e8m0 scale bytes + random nibbles."""+ nb = k // 32+ raw = torch.randint(0, 256, (n, nb, 17), dtype=torch.uint8, generator=gen)+ raw[:, :, 0] = torch.randint(118, 128, (n, nb), dtype=torch.uint8, generator=gen)+ return raw.reshape(n, nb * 17).to(dev)+++def test_dq_mx_equals_gap_dequant(mods):+ MP, gf = mods["moe_mxfp4_prefill"], mods["gap_formats"]+ dev, gen = "cuda", torch.Generator().manual_seed(1)+ E, N, K = 5, 48, 96+ w = [_rand_packed(N, K, gen, dev) for _ in range(E)]+ tab = torch.tensor([t.data_ptr() for t in w], dtype=torch.int64, device=dev)+ ids = torch.tensor([3, 0, 4], dtype=torch.int32, device=dev)+ out = torch.empty((3, N, K), dtype=torch.half, device=dev)+ MP.dequant_group(tab, ids, out, N, K)+ for i, e in enumerate(ids.tolist()):+ ref = gf.dequant("mxfp4", w[e])+ assert torch.equal(out[i].view(torch.int16), ref.view(torch.int16))++[email protected]("scratch_mb", [None, "0"]) # "0": every expert in its own group+def test_prefill_matches_reference(mods, monkeypatch, scratch_mb):+ MP, gf, fb = mods["moe_mxfp4_prefill"], mods["gap_formats"], mods["fallbacks"]+ dev, gen = "cuda", torch.Generator().manual_seed(2)+ E, S, H, I, R, LIM = 8, 2, 64, 64, 300, 7.0+ ns = types.SimpleNamespace++ def lin(i, o):+ return ns(inner=ns(fl=ns(in_features=i, out_features=o, packed=_rand_packed(o, i, gen, dev)),+ bias=(torch.randn(o, generator=gen) * 0.1).half().to(dev)))+ st = ns(_mxfp4_grouped_ok=lambda y: True, num_local_experts=None, num_experts=E, num_experts_per_tok=S, shared_experts=None,+ act_limit=LIM, activation_fn_call=fb.silu_oai_mul)+ st.gates, st.ups, st.downs = [[lin(i, o) for _ in range(E)] for i, o in ((H, I), (H, I), (I, H))]+ monkeypatch.setenv("EXL3_MXFP4_PREFILL_GROUPED", "1")+ monkeypatch.setattr(torch.version, "hip", None)+ if scratch_mb is not None:+ monkeypatch.setenv("EXL3_MXFP4_PREFILL_SCRATCH_MB", scratch_mb)+ y = (torch.randn(R, H, generator=gen) * 0.5).half().to(dev)+ sel = torch.stack([torch.randperm(E, generator=gen)[:S] for _ in range(R)]).to(dev)+ wts = torch.softmax(torch.randn(R, S, generator=gen), -1).half().to(dev)++ meth = _mlp_method()+ got = meth(st, y, y, sel, wts, {}, None, (R, H))+ assert got is not None and got.shape == (R, H)++ # reference: per-expert dequant + fp16 matmul + bias, same activation, routing weight, fp32 sum+ def lw(m):+ return gf.dequant("mxfp4", m.inner.fl.packed), m.inner.bias+ ref = torch.zeros(R, H, dtype=torch.float32, device=dev)+ for e in range(E):+ rr, ss = (sel == e).nonzero(as_tuple=True)+ if rr.numel() == 0:+ continue+ x = y[rr]+ (wg, bg), (wu, bu), (wd, bd) = lw(st.gates[e]), lw(st.ups[e]), lw(st.downs[e])+ g, u = x @ wg.T + bg, x @ wu.T + bu+ a = torch.empty_like(g)+ fb.silu_oai_mul(g, u, a, LIM)+ d = (a @ wd.T + bd) * wts[rr, ss, None]+ ref.index_add_(0, rr, d.float())+ rel = (got.float() - ref).norm() / ref.norm()+ assert rel < 1e-2, rel.item()