Skip to content

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.

MoE fold fused kernel (EXL3_MOE_FOLD_FUSED, off: 3.6 % < 4 %)

YanissAmzfa1db77d1c27
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index b32cf55..60ac6f0 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -619,6 +619,7 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
m.def("fq_mlp_shared_iq2xxs", &fq_mlp_shared_iq2xxs, "fq_mlp_shared_iq2xxs",
py::arg("x"), py::arg("up_packed"), py::arg("h"));
#endif
+ m.def("fq_moe_fold", &fq_moe_fold, "fq_moe_fold", py::arg("d"), py::arg("rw"), py::arg("out"));
m.def("fq_mmvq_epi_abi", &fq_mmvq_epi_abi, "fq_mmvq_epi_abi");
m.def("fq_q8_scratch", &fq_q8_scratch, "fq_q8_scratch",
py::arg("dev"), py::arg("M"), py::arg("K"));
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu
index a46990c..4535024 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu
@@ -725,3 +725,52 @@ void fq_dequant_iq(torch::Tensor packed, torch::Tensor out, int64_t fmt)
default: TORCH_CHECK(false, "fq_dequant_iq: bad format id ", fmt);
}
}
+
+// ---------------------------------------------------------------------------------------------------------------------------------
+// EXL3_MOE_FOLD_FUSED: out[n] = sum_s (d[s, n] * float(rw[s])) in ONE launch, replacing routing_weights.float(), the broadcast multiply,
+// .sum(1) and the final .to(out_dtype). Order = torch's CUDA reduce for a size-S non-fastest dim (Reduce.cuh thread_reduce_impl, no warp split:
+// ((0+v0)+v1)+v2)+v3, one rounded fp32 multiply then one rounded add, no FMA), so the fp32 result is bit-identical to the torch chain.
+// ---------------------------------------------------------------------------------------------------------------------------------
+template <typename RW> __device__ __forceinline__ float fold_to_f(RW v);
+template <> __device__ __forceinline__ float fold_to_f<float>(float v) { return v; }
+template <> __device__ __forceinline__ float fold_to_f<__half>(__half v) { return __half2float(v); }
+
+template <typename RW, typename OUT>
+__global__ void fq_moe_fold_kernel(const float* __restrict__ d, const RW* __restrict__ rw, OUT* __restrict__ out, int S, int64_t N, int H)
+{
+ const int n = blockIdx.x * blockDim.x + threadIdx.x;
+ if (n >= H) return;
+ float acc = 0.0f;
+ for (int s = 0; s < S; ++s)
+ acc = __fadd_rn(acc, __fmul_rn(d[(int64_t)s * N + n], fold_to_f<RW>(rw[s])));
+ mq_store<OUT>(&out[n], acc);
+}
+
+void fq_moe_fold(torch::Tensor d, torch::Tensor rw, torch::Tensor out)
+{
+ TORCH_CHECK(d.is_cuda() && rw.is_cuda() && out.is_cuda(), "tensors must be CUDA");
+ TORCH_CHECK(d.is_contiguous() && rw.is_contiguous() && out.is_contiguous(), "tensors must be contiguous");
+ TORCH_CHECK(d.dtype() == torch::kFloat && d.dim() == 2, "d must be float [S, N]");
+ TORCH_CHECK(rw.dtype() == torch::kHalf || rw.dtype() == torch::kFloat, "rw must be half or float");
+ TORCH_CHECK(out.dtype() == torch::kHalf || out.dtype() == torch::kFloat, "out must be half or float");
+ const int S = (int)d.size(0);
+ const int64_t N = d.size(1);
+ const int H = (int)out.numel();
+ TORCH_CHECK(rw.numel() == S && H <= N, "shape mismatch");
+ at::cuda::CUDAGuard guard(d.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ const int blocks = (H + 127) / 128;
+ const float* dp = d.data_ptr<float>();
+ if (rw.dtype() == torch::kHalf)
+ {
+ const __half* r = reinterpret_cast<const __half*>(rw.data_ptr<at::Half>());
+ if (out.dtype() == torch::kHalf) fq_moe_fold_kernel<__half, __half><<<blocks, 128, 0, stream>>>(dp, r, reinterpret_cast<__half*>(out.data_ptr<at::Half>()), S, N, H);
+ else fq_moe_fold_kernel<__half, float><<<blocks, 128, 0, stream>>>(dp, r, out.data_ptr<float>(), S, N, H);
+ }
+ else
+ {
+ const float* r = rw.data_ptr<float>();
+ if (out.dtype() == torch::kHalf) fq_moe_fold_kernel<float, __half><<<blocks, 128, 0, stream>>>(dp, r, reinterpret_cast<__half*>(out.data_ptr<at::Half>()), S, N, H);
+ else fq_moe_fold_kernel<float, float><<<blocks, 128, 0, stream>>>(dp, r, out.data_ptr<float>(), S, N, H);
+ }
+}
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h
index 272c545..8a670a6 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h
@@ -39,3 +39,6 @@ bool fq_mmq_few(torch::Tensor x, torch::Tensor scratch, torch::Tensor packed, to
// ABI marker: the fq_mmvq_* functions above take an optional half bias applied in the store (EXL3_FQ_MMVQ_EPI).
inline int fq_mmvq_epi_abi() { return 1; }
+
+// EXL3_MOE_FOLD_FUSED: out[H] (half or float) = sum over the S slots of d[s, :H] * float(rw[s]), torch's reduce order (fq_mmvq.cu).
+void fq_moe_fold(torch::Tensor d, torch::Tensor rw, torch::Tensor out);
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index a8b5359..21ca7f2 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -1917,6 +1917,23 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
d = torch.empty((S, N), dtype=torch.float32, device=h.device)
ext.fq_mxfp4_moe_down(qa, sel, dw, db if db is not None else dw[:0], d, N, I)
MX.MMVQ_FIRES += 1
+ # EXL3_MOE_FOLD_FUSED=1 (CUDA, read at call time): routing_weights.float(), the multiply, .sum(1) and the final .to(out_dtype) in ONE kernel
+ # (fq_moe_fold: sequential fp32 sum over the S slots = torch's reduce order for a size-S non-fastest dim, bit-identical). With a shared expert
+ # the kernel writes fp32 and the rest is unchanged; out_dtype other than half / float falls back to the torch chain.
+ _rw = routing_weights.reshape(-1)
+ if (os.environ.get("EXL3_MOE_FOLD_FUSED", "0") == "1" and torch.version.cuda and not torch.version.hip and hasattr(ext, "fq_moe_fold")
+ and _rw.numel() == S and _rw.dtype in (torch.half, torch.float) and d.is_contiguous() and d.dtype == torch.float32 and H <= d.shape[1]
+ and out_dtype in (None, torch.half, torch.float) and x.numel() == H):
+ direct = self.shared_experts is None
+ routed = torch.empty((1, H), dtype=(out_dtype or torch.float32) if direct else torch.float32, device=d.device)
+ ext.fq_moe_fold(d, _rw.contiguous(), routed)
+ final_hidden_states = routed.view(x.shape)
+ if not direct:
+ 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
routed = (d.view(1, S, -1)[..., :H] * routing_weights.reshape(1, S, 1).float()).sum(1)
final_hidden_states = routed.view(x.shape)
if self.shared_experts is not None:
diff --git a/tests/test_mmvq_mxfp4_cpu.py b/tests/test_mmvq_mxfp4_cpu.py
index 5d56854..dd777ff 100644
--- a/tests/test_mmvq_mxfp4_cpu.py
+++ b/tests/test_mmvq_mxfp4_cpu.py
@@ -78,7 +78,7 @@ def _mlp_methods():
fns = [n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name in want]
assert len(fns) == 2
mod = ast.Module(body=fns, type_ignores=[])
- ns = {"torch": torch, "FQ_GROUPED_MAX_ROWS": 8, "ext": None, "__name__": "exllamav3.modules.block_sparse_mlp"}
+ ns = {"os": os, "torch": torch, "FQ_GROUPED_MAX_ROWS": 8, "ext": None, "__name__": "exllamav3.modules.block_sparse_mlp"}
exec(compile(ast.fix_missing_locations(mod), "block_sparse_mlp.py", "exec"), ns)
return ns
diff --git a/tests/test_moe_fold_fused_cpu.py b/tests/test_moe_fold_fused_cpu.py
new file mode 100644
index 0000000..0165747
--- /dev/null
+++ b/tests/test_moe_fold_fused_cpu.py
@@ -0,0 +1,89 @@
+"""CPU checks for EXL3_MOE_FOLD_FUSED (fq_moe_fold): reduce-order emulation + dispatch with stubbed kernels.
+No GPU, no kernel launch: the extension is replaced by stubs. Needs the repo importable (exllamav3 package, built extension present so the
+import does not start a build); skipped otherwise. Run: CUDA_VISIBLE_DEVICES= python -m pytest tests/test_moe_fold_fused_cpu.py -q"""
+import glob
+import os
+import sys
+import types
+
+import numpy as np
+import pytest
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+if not glob.glob(os.path.join(ROOT, "exllamav3_ext*.so")):
+ pytest.skip("extension not built in " + ROOT + " (importing exllamav3 would start the build)", allow_module_level=True)
+sys.path.insert(0, ROOT)
+import torch
+
+
+
+def fold_seq(d, rw, H): # kernel / torch reduce order for a size-S non-fastest dim: ((0+v0)+v1)+v2)+v3, products rounded to fp32 first
+ acc = np.zeros(H, dtype=np.float32)
+ for s in range(d.shape[0]):
+ acc = acc + (d[s, :H] * np.float32(rw[s])).astype(np.float32)
+ return acc
+
+
+def test_fold_order():
+ import torch
+ rng = np.random.default_rng(3)
+ bad = 0
+ for S, H, N in ((4, 2880, 2880), (4, 2880, 2944), (4, 4096, 4096)):
+ d = (rng.standard_normal((S, N)) * 5).astype(np.float32)
+ rw = rng.random(S).astype(np.float16)
+ ref = (torch.from_numpy(d).view(1, S, -1)[..., :H] * torch.from_numpy(rw).reshape(1, S, 1).float()).sum(1).numpy().reshape(-1)
+ mine = fold_seq(d, rw.astype(np.float32), H)
+ bad += int((ref != mine).sum())
+ # the other plausible order, pairwise (v0+v2)+(v1+v3), for contrast
+ p = (d[:, :H] * rw.astype(np.float32)[:, None]).astype(np.float32)
+ pw = (p[0] + p[2]) + (p[1] + p[3])
+ print(f"fold S={S} H={H} N={N}: sequential vs torch-CPU {int((ref != mine).sum())} diffs; pairwise vs torch-CPU {int((ref != pw).sum())} diffs")
+ # not asserted: torch CPU is not torch CUDA. The CUDA order is sequential (Reduce.cuh thread_reduce_impl, block_height does not split a 4-long dim: values_per_thread 4 < 16 * block_height).
+ print("fold order emulation done (CPU torch diffs total", bad, ")")
+
+
+class _FakeCudaBias:
+ """Stand-in for a CUDA half bias on a CPU box."""
+ is_cuda = True
+ dtype = torch.half
+ def __init__(self, n): self.n = n
+ def is_contiguous(self): return True
+ def numel(self): return self.n
+
+
[email protected](params=["0", "1"])
+def flag(request, monkeypatch):
+ monkeypatch.setattr(torch.version, "cuda", "13.0", raising=False)
+ monkeypatch.setattr(torch.version, "hip", None, raising=False)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ return request.param == "1"
+
+def test_dispatch(flag, monkeypatch):
+ from exllamav3.modules import block_sparse_mlp as bs
+ monkeypatch.setenv("EXL3_MOE_FOLD_FUSED", "1" if flag else "0")
+ S, H, N = 4, 16, 16
+ rng = np.random.default_rng(5)
+ dd = torch.from_numpy((rng.standard_normal((S, N)) * 4).astype(np.float32))
+ fold_calls = []
+ def moe_down(qa, sel, dw, db, d, N_, I_): d.copy_(dd)
+ def fold(d, rw, out):
+ fold_calls.append(1)
+ out.copy_(torch.from_numpy(fold_seq(d.numpy(), rw.float().numpy(), out.numel())).reshape(out.shape).to(out.dtype))
+ bext = types.SimpleNamespace(fq_q8_scratch=lambda dev, R, K: torch.zeros(R, K // 32 * 36, dtype=torch.uint8),
+ fq_quant_q8_1_rows=lambda x, qb: None,
+ fq_mxfp4_moe_gu=lambda *a: None, fq_mxfp4_moe_down=moe_down, fq_moe_fold=fold)
+ monkeypatch.setattr(bs, "ext", bext)
+ mod = object.__new__(bs.BlockSparseMLP)
+ mod.num_experts_per_tok = S; mod.act_limit = 7.0; mod.shared_experts = None
+ mod.downs = [types.SimpleNamespace(inner=types.SimpleNamespace(fl=types.SimpleNamespace(out_features=N)))]
+ xin = torch.zeros(1, 1, H, dtype=torch.half); h = torch.zeros(1, H, dtype=torch.half)
+ rw = torch.from_numpy(rng.random(S).astype(np.float16))
+ tbl = (None, None, None, None, torch.zeros(1), None)
+ outs = {}
+ for od in (None, torch.half, torch.float):
+ fold_calls.clear()
+ outs[od] = mod._mxfp4_mmvq_forward(xin, h, torch.zeros(S, dtype=torch.long), tbl, 8, H, H, rw.reshape(1, S), {}, od)
+ assert len(fold_calls) == (1 if flag else 0), (od, fold_calls)
+ ref = (dd.view(1, S, -1)[..., :H] * rw.reshape(1, S, 1).float()).sum(1).view(xin.shape)
+ assert torch.equal(outs[None].float(), ref) and torch.equal(outs[torch.half], ref.half()) and outs[torch.half].dtype == torch.half
+ assert outs[torch.float].dtype == torch.float32