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.

MXFP4 MoE decode: llama.cpp-shape mmvq in fq_mmvq (EXL3_FQ_MMVQ_MXFP4)

YanissAmz7f75d3b58f61
diff --git a/exllamav3/exllamav3_ext/bindings.cpp b/exllamav3/exllamav3_ext/bindings.cpp
index 430e91e..6209855 100644
--- a/exllamav3/exllamav3_ext/bindings.cpp
+++ b/exllamav3/exllamav3_ext/bindings.cpp
@@ -664,6 +664,11 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
py::arg("h"), py::arg("sel"), py::arg("wts"), py::arg("gate_ptrs"), py::arg("up_ptrs"), py::arg("down_ptrs"),
py::arg("gate_stride"), py::arg("up_stride"), py::arg("down_stride"), py::arg("type_ug"), py::arg("type_down"),
py::arg("partial"), py::arg("out"));
+ m.def("fq_mxfp4_moe_gu", &fq_mxfp4_moe_gu, "fq_mxfp4_moe_gu",
+ py::arg("qb"), py::arg("sel"), py::arg("gate_ptrs"), py::arg("gate_bias"), py::arg("up_ptrs"), py::arg("up_bias"), py::arg("act"),
+ py::arg("I"), py::arg("K"), py::arg("lim"));
+ m.def("fq_mxfp4_moe_down", &fq_mxfp4_moe_down, "fq_mxfp4_moe_down",
+ py::arg("qb"), py::arg("sel"), py::arg("down_ptrs"), py::arg("down_bias"), py::arg("out"), py::arg("N"), py::arg("K"));
m.def("fq_mmvq_q5_k", &fq_mmvq_q5_k, "fq_mmvq_q5_k",
py::arg("qb"), py::arg("packed"), py::arg("out"));
m.def("fq_mmvq_q4_k", &fq_mmvq_q4_k, "fq_mmvq_q4_k",
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu
index 12eb741..bc98a6e 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq.cu
@@ -23,6 +23,7 @@
#include "ggml_mmvq/ggml_vecdotq_iq.cuh"
#include "ggml_mmvq/ggml_vecdotq_k46.cuh"
#include "ggml_mmvq/ggml_vecdotq_legacy.cuh"
+#include "ggml_mmvq/ggml_vecdotq_mxfp4.cuh"
#if defined(USE_ROCM)
// HIP: maskless shuffles (RDNA runs these kernels as wave32, MQ_WARP = 32)
@@ -33,7 +34,7 @@ namespace {
using namespace ggml_iq;
-enum { MQ_IQ2_XXS = 0, MQ_IQ2_XS = 1, MQ_IQ2_S = 2, MQ_IQ3_XXS = 3, MQ_IQ3_S = 4, MQ_IQ4_NL = 5, MQ_IQ4_XS = 6, MQ_Q5_K = 7, MQ_Q4_K = 8, MQ_Q6_K = 9, MQ_Q3_K = 10, MQ_Q4_0 = 11, MQ_Q4_1 = 12, MQ_Q5_0 = 13, MQ_Q5_1 = 14, MQ_NTYPES = 15 };
+enum { MQ_IQ2_XXS = 0, MQ_IQ2_XS = 1, MQ_IQ2_S = 2, MQ_IQ3_XXS = 3, MQ_IQ3_S = 4, MQ_IQ4_NL = 5, MQ_IQ4_XS = 6, MQ_Q5_K = 7, MQ_Q4_K = 8, MQ_Q6_K = 9, MQ_Q3_K = 10, MQ_Q4_0 = 11, MQ_Q4_1 = 12, MQ_Q5_0 = 13, MQ_Q5_1 = 14, MQ_MXFP4 = 15, MQ_NTYPES = 16 };
// qk = weight elements per block, qi = ints per block (ggml QI*), vdr = ints per lane per call, bb = block bytes
template <int T> struct MqTraits;
@@ -59,6 +60,7 @@ MQ_TRAITS(MQ_Q4_0, 32, 4, VDR_Q4_0_Q8_1_MMVQ, 18, vec_dot_q4_0_q8_1);
MQ_TRAITS(MQ_Q4_1, 32, 4, VDR_Q4_1_Q8_1_MMVQ, 20, vec_dot_q4_1_q8_1);
MQ_TRAITS(MQ_Q5_0, 32, 4, VDR_Q5_0_Q8_1_MMVQ, 22, vec_dot_q5_0_q8_1);
MQ_TRAITS(MQ_Q5_1, 32, 4, VDR_Q5_1_Q8_1_MMVQ, 24, vec_dot_q5_1_q8_1);
+MQ_TRAITS(MQ_MXFP4, 32, 4, VDR_MXFP4_Q8_1_MMVQ, 17, vec_dot_mxfp4_q8_1);
#undef MQ_TRAITS
constexpr int MQ_WARP = 32;
@@ -369,6 +371,77 @@ __global__ void fq_mmvq_moe_combine_kernel(const float* __restrict__ partial, co
}
+// ---------------------------------------------------------------------------------------------------------------------------------
+// MXFP4 decode MoE, llama.cpp launch shape (EXL3_FQ_MMVQ_MXFP4): one output row per block, MXM_WARPS = 4 warps (128 threads) per row
+// (mmvq.cu:452-460 nwarps = 4 for ncols_dst = 1, :579-583 rows_per_block = 1), blocks_per_iter = vdr * 4 * 32 / qi = 64, per-warp partials
+// through shared memory (mmvq.cu:763-840), grid (rows, slots). Existing grouped IQ kernels above use 1 warp per row (LPR 32), 8 rows per block.
+// x is one q8_1 row shared by every slot (R == 1); expert weights / biases through the same int64 pointer tables the Triton path uses.
+// gate and up of the same row are computed in one launch (mmvq.cu:661-760), + bias, fp16 rounding, swiglu_oai with clamp, fp16 out [S, I].
+// ---------------------------------------------------------------------------------------------------------------------------------
+constexpr int MXM_WARPS = 4;
+
+template <bool GU>
+__global__ void __launch_bounds__(MQ_WARP * MXM_WARPS, 1)
+fq_mxfp4_moe_kernel(const uint8_t* __restrict__ qb, int64_t qb_slot_stride, const int* __restrict__ sel, const int64_t* __restrict__ wtab,
+ const int64_t* __restrict__ btab, const int64_t* __restrict__ wtab2, const int64_t* __restrict__ btab2,
+ void* __restrict__ outp, int N, int K, int E, float lim)
+{
+ using Tr = MqTraits<MQ_MXFP4>;
+ constexpr int blocks_per_iter = Tr::vdr * MXM_WARPS * MQ_WARP / Tr::qi;
+ const int row = blockIdx.x, slot = blockIdx.y;
+ int e = sel[slot];
+ e = (e < 0 || e >= E) ? 0 : e;
+ const int tid = MQ_WARP * threadIdx.y + threadIdx.x;
+ const int nb = K / Tr::qk;
+ const block_q8_1* y = reinterpret_cast<const block_q8_1*>(qb + (int64_t)slot * qb_slot_stride);
+ const uint8_t* w0 = reinterpret_cast<const uint8_t*>(wtab[e]) + (int64_t)row * nb * Tr::bb;
+ const uint8_t* w1 = GU ? reinterpret_cast<const uint8_t*>(wtab2[e]) + (int64_t)row * nb * Tr::bb : nullptr;
+ float a0 = 0.0f, a1 = 0.0f;
+ for (int kbx = tid / (Tr::qi / Tr::vdr); kbx < nb; kbx += blocks_per_iter)
+ {
+ const int kqs = Tr::vdr * (tid % (Tr::qi / Tr::vdr));
+ a0 += Tr::dot(w0, y + kbx, kbx, kqs);
+ if constexpr (GU)
+ a1 += Tr::dot(w1, y + kbx, kbx, kqs);
+ }
+ __shared__ float sh[MXM_WARPS - 1][2][MQ_WARP];
+ if (threadIdx.y > 0)
+ {
+ sh[threadIdx.y - 1][0][threadIdx.x] = a0;
+ sh[threadIdx.y - 1][1][threadIdx.x] = a1;
+ }
+ __syncthreads();
+ if (threadIdx.y > 0)
+ return;
+#pragma unroll
+ for (int l = 0; l < MXM_WARPS - 1; ++l)
+ {
+ a0 += sh[l][0][threadIdx.x];
+ a1 += sh[l][1][threadIdx.x];
+ }
+ a0 = mq_warp_sum(a0);
+ if constexpr (GU) a1 = mq_warp_sum(a1);
+ if (threadIdx.x != 0)
+ return;
+ if constexpr (GU)
+ {
+ // same rounding as triton_moe_mxfp4._gu_fused: acc + bias, rounded to fp16, clamp, (u + 1) * g * sigmoid(1.702 g)
+ float g = a0 + (btab ? __half2float(reinterpret_cast<const __half*>(btab[e])[row]) : 0.0f);
+ float u = a1 + (btab2 ? __half2float(reinterpret_cast<const __half*>(btab2[e])[row]) : 0.0f);
+ g = __half2float(__float2half_rn(g));
+ u = __half2float(__float2half_rn(u));
+ g = fminf(g, lim);
+ u = fminf(fmaxf(u, -lim), lim);
+ const float a = (u + 1.0f) * g * (1.0f / (1.0f + expf(-1.702f * g)));
+ reinterpret_cast<__half*>(outp)[(int64_t)slot * N + row] = __float2half_rn(a);
+ }
+ else
+ {
+ if (btab) a0 += __half2float(reinterpret_cast<const __half*>(btab[e])[row]);
+ reinterpret_cast<float*>(outp)[(int64_t)slot * N + row] = a0;
+ }
+}
+
// ---------------------------------------------------------------------------------------------------------------------------------
// Dequantize to fp16 [N, K] (prefill / large-batch path: dequant + GEMM). Port of ggml/src/ggml-cuda/convert.cu dequantize_block_iq*
// (MIT, The ggml authors): one 32-thread block per 256-element super block, 8 outputs per thread (4 + 4 for the 4-bit formats).
@@ -530,9 +603,11 @@ void fq_moe_mmvq_grouped(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
torch::Tensor down_ptrs, int64_t gate_stride, int64_t up_stride, int64_t down_stride, int64_t type_ug, int64_t type_down,
torch::Tensor partial, torch::Tensor out)
{
- static const int kQk[8] = {256, 256, 256, 256, 256, 32, 256, 256};
- static const int kBb[8] = {66, 74, 82, 98, 110, 18, 136, 176};
- TORCH_CHECK(type_ug >= 0 && type_ug < 8 && type_down >= 0 && type_down < 8, "fq_moe_mmvq_grouped: bad format id");
+ static const int kQk[16] = {256, 256, 256, 256, 256, 32, 256, 256, 0, 0, 0, 0, 0, 0, 0, 32};
+ static const int kBb[16] = {66, 74, 82, 98, 110, 18, 136, 176, 0, 0, 0, 0, 0, 0, 0, 17};
+ // 15 = MQ_MXFP4 (plain silu(gate) * up, no bias: the gpt-oss swiglu_oai + bias path is fq_mxfp4_moe_gu / fq_mxfp4_moe_down below)
+ auto ok_t = [](int64_t t) { return (t >= 0 && t < 8) || t == MQ_MXFP4; };
+ TORCH_CHECK(ok_t(type_ug) && ok_t(type_down), "fq_moe_mmvq_grouped: bad format id");
const int K = (int)h.size(1), R = (int)h.size(0), S = (int)sel.numel();
TORCH_CHECK(S % R == 0 && R >= 1, "sel must be R x topk");
TORCH_CHECK(h.dtype() == torch::kHalf && h.is_cuda() && h.is_contiguous(), "h must be contiguous half CUDA");
@@ -563,7 +638,7 @@ void fq_moe_mmvq_grouped(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
switch (type_ug)
{
#define MQ_UG(T) case T: mq_moe_upgate_t<T>(qb_h.data_ptr<uint8_t>(), sel.data_ptr<int64_t>(), gb, ub, gate_stride, up_stride, qb_stride_h, actp, S, I, K, E, topk, stream); break;
- MQ_UG(MQ_IQ2_XXS) MQ_UG(MQ_IQ2_XS) MQ_UG(MQ_IQ2_S) MQ_UG(MQ_IQ3_XXS) MQ_UG(MQ_IQ3_S) MQ_UG(MQ_IQ4_NL) MQ_UG(MQ_IQ4_XS) MQ_UG(MQ_Q5_K)
+ MQ_UG(MQ_IQ2_XXS) MQ_UG(MQ_IQ2_XS) MQ_UG(MQ_IQ2_S) MQ_UG(MQ_IQ3_XXS) MQ_UG(MQ_IQ3_S) MQ_UG(MQ_IQ4_NL) MQ_UG(MQ_IQ4_XS) MQ_UG(MQ_Q5_K) MQ_UG(MQ_MXFP4)
#undef MQ_UG
}
torch::Tensor qb_act = fq_q8_scratch(h.get_device(), S, I);
@@ -572,13 +647,46 @@ void fq_moe_mmvq_grouped(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
switch (type_down)
{
#define MQ_DN(T) case T: mq_moe_down_t<T>(qb_act.data_ptr<uint8_t>(), qb_stride_a, sel.data_ptr<int64_t>(), db, down_stride, partial.data_ptr<float>(), S, I, K, E, stream); break;
- MQ_DN(MQ_IQ2_XXS) MQ_DN(MQ_IQ2_XS) MQ_DN(MQ_IQ2_S) MQ_DN(MQ_IQ3_XXS) MQ_DN(MQ_IQ3_S) MQ_DN(MQ_IQ4_NL) MQ_DN(MQ_IQ4_XS) MQ_DN(MQ_Q5_K)
+ MQ_DN(MQ_IQ2_XXS) MQ_DN(MQ_IQ2_XS) MQ_DN(MQ_IQ2_S) MQ_DN(MQ_IQ3_XXS) MQ_DN(MQ_IQ3_S) MQ_DN(MQ_IQ4_NL) MQ_DN(MQ_IQ4_XS) MQ_DN(MQ_Q5_K) MQ_DN(MQ_MXFP4)
#undef MQ_DN
}
fq_mmvq_moe_combine_kernel<<<dim3((K + 255) / 256, R), 256, 0, stream>>>(partial.data_ptr<float>(), reinterpret_cast<const __half*>(wts.data_ptr<at::Half>()),
out.data_ptr<float>(), topk, K);
}
+// EXL3_FQ_MMVQ_MXFP4 decode MoE (R == 1). qb: fq_quant_q8_1_rows of the input. Pointer tables = int64 data_ptr of each expert's packed rows
+// [rows, K/32*17] / fp16 bias [rows] (as triton_moe_mxfp4); sel int32 [S]; bias tables may be empty (numel 0) = no bias.
+// gu: act [S, I] fp16 = swiglu_oai(gate(x) + bg, up(x) + bu, lim) with fp16 rounding of both before the activation; qb is ONE row (all slots).
+void fq_mxfp4_moe_gu(torch::Tensor qb, torch::Tensor sel, torch::Tensor gate_ptrs, torch::Tensor gate_bias, torch::Tensor up_ptrs,
+ torch::Tensor up_bias, torch::Tensor act, int64_t I, int64_t K, double lim)
+{
+ TORCH_CHECK(sel.dtype() == torch::kInt && qb.dtype() == torch::kUInt8 && act.dtype() == torch::kHalf && act.is_contiguous() && K % 32 == 0,
+ "fq_mxfp4_moe_gu: bad arguments");
+ TORCH_CHECK(qb.numel() >= (K / 32) * 36 && act.numel() >= sel.numel() * I, "fq_mxfp4_moe_gu: sizes");
+ at::cuda::CUDAGuard guard(qb.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ dim3 grid((unsigned)I, (unsigned)sel.numel(), 1), block(MQ_WARP, MXM_WARPS, 1);
+ fq_mxfp4_moe_kernel<true><<<grid, block, 0, stream>>>(
+ qb.data_ptr<uint8_t>(), 0, sel.data_ptr<int>(), gate_ptrs.data_ptr<int64_t>(), gate_bias.numel() ? gate_bias.data_ptr<int64_t>() : nullptr,
+ up_ptrs.data_ptr<int64_t>(), up_bias.numel() ? up_bias.data_ptr<int64_t>() : nullptr, act.data_ptr(), (int)I, (int)K,
+ (int)gate_ptrs.numel(), (float)lim);
+}
+
+// down: out [S, N] fp32 = act_q8[slot] . W_down[sel[slot]]^T + bias; qb = S rows (one per slot) of K/32*36 bytes.
+void fq_mxfp4_moe_down(torch::Tensor qb, torch::Tensor sel, torch::Tensor down_ptrs, torch::Tensor down_bias, torch::Tensor out, int64_t N,
+ int64_t K)
+{
+ TORCH_CHECK(sel.dtype() == torch::kInt && qb.dtype() == torch::kUInt8 && out.dtype() == torch::kFloat && out.is_contiguous() && K % 32 == 0,
+ "fq_mxfp4_moe_down: bad arguments");
+ TORCH_CHECK(qb.numel() >= sel.numel() * (K / 32) * 36 && out.numel() >= sel.numel() * N, "fq_mxfp4_moe_down: sizes");
+ at::cuda::CUDAGuard guard(qb.device());
+ auto stream = at::cuda::getCurrentCUDAStream().stream();
+ dim3 grid((unsigned)N, (unsigned)sel.numel(), 1), block(MQ_WARP, MXM_WARPS, 1);
+ fq_mxfp4_moe_kernel<false><<<grid, block, 0, stream>>>(
+ qb.data_ptr<uint8_t>(), (K / 32) * 36, sel.data_ptr<int>(), down_ptrs.data_ptr<int64_t>(),
+ down_bias.numel() ? down_bias.data_ptr<int64_t>() : nullptr, nullptr, nullptr, out.data_ptr(), (int)N, (int)K, (int)down_ptrs.numel(), 0.0f);
+}
+
// out [N, K] half from raw GGUF bytes; fmt = MQ type id (0 iq2_xxs, 1 iq2_xs, 2 iq2_s, 3 iq3_xxs, 4 iq3_s, 5 iq4_nl, 6 iq4_xs), K % 256 == 0
void fq_dequant_iq(torch::Tensor packed, torch::Tensor out, int64_t fmt)
{
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h
index 43d2583..884f10e 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_mmvq_api.h
@@ -23,6 +23,12 @@ void fq_mmvq_q5_1(torch::Tensor qb, torch::Tensor packed, torch::Tensor out);
void fq_moe_mmvq_grouped(torch::Tensor h, torch::Tensor sel, torch::Tensor wts, torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
torch::Tensor down_ptrs, int64_t gate_stride, int64_t up_stride, int64_t down_stride, int64_t type_ug, int64_t type_down,
torch::Tensor partial, torch::Tensor out);
+// EXL3_FQ_MMVQ_MXFP4 (CUDA, R == 1): llama.cpp-shaped MXFP4 MoE decode on the stacked experts through int64 pointer tables (fq_mmvq.cu).
+// gu: act [S, I] half = swiglu_oai(gate + bias, up + bias, lim); qb = ONE q8_1 row of the input. down: out [S, N] float = q8_1(act)[slot] . W^T + bias.
+void fq_mxfp4_moe_gu(torch::Tensor qb, torch::Tensor sel, torch::Tensor gate_ptrs, torch::Tensor gate_bias, torch::Tensor up_ptrs,
+ torch::Tensor up_bias, torch::Tensor act, int64_t I, int64_t K, double lim);
+void fq_mxfp4_moe_down(torch::Tensor qb, torch::Tensor sel, torch::Tensor down_ptrs, torch::Tensor down_bias, torch::Tensor out, int64_t N,
+ int64_t K);
// Dequantize IQ blocks to fp16 [N, K] (K % 256 == 0); fmt = MQ type id as above (0..6, 10 q3_k). Port of ggml convert.cu dequantize_block_iq*.
void fq_dequant_iq(torch::Tensor packed, torch::Tensor out, int64_t fmt);
#if !defined(USE_ROCM)
diff --git a/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_mxfp4.cuh b/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_mxfp4.cuh
new file mode 100644
index 0000000..7e95d4b
--- /dev/null
+++ b/exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ggml_vecdotq_mxfp4.cuh
@@ -0,0 +1,57 @@
+// MXFP4 x q8_1 dot product for the fq_mmvq family: port of llama.cpp ggml/src/ggml-cuda/vecdotq.cuh (get_int_b1 :7-15,
+// get_int_from_table_16 :34 (shared, see ggml_vecdotq_iq.cuh), vec_dot_mxfp4_q8_1 :310-329, VDR_MXFP4_Q8_1_MMVQ :307),
+// block_mxfp4 ggml-common.h:214-219, kvalues_mxfp4 (= kvalues_fp4, e2m1 values doubled) ggml-common.h:1124-1129.
+// MIT License, Copyright (c) 2023-2026 The ggml authors (llama.cpp commit 7182ef7). See THIRD_PARTY_NOTICES.md.
+// Change: ggml_cuda_dp4a -> ggml_dp4a; ggml_cuda_e8m0_to_fp32 written with integer bits (exact same value for every e8m0 byte
+// incl. 0 -> 2^-127 denormal), so the file also compiles on HIP.
+#pragma once
+
+#include "ggml_vecdotq_iq.cuh"
+
+namespace ggml_iq {
+
+#define QK_MXFP4 32
+#define QI_MXFP4 4
+#define VDR_MXFP4_Q8_1_MMVQ 2
+
+struct block_mxfp4 { uint8_t e; uint8_t qs[QK_MXFP4 / 2]; }; // 17 bytes: [E8M0 scale][elements j (low nibble) and j + 16 (high nibble)]
+static_assert(sizeof(block_mxfp4) == 17, "ggml block layout");
+
+alignas(16) static __device__ const int8_t kvalues_mxfp4[16] = {0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12};
+
+static __device__ __forceinline__ int get_int_b1(const void * x, const int & i32) {
+ const uint8_t * x8 = (const uint8_t *) x;
+ int x32 = x8[4*i32 + 0] << 0;
+ x32 |= x8[4*i32 + 1] << 8;
+ x32 |= x8[4*i32 + 2] << 16;
+ x32 |= x8[4*i32 + 3] << 24;
+ return x32;
+}
+
+static __device__ __forceinline__ float mxfp4_e8m0_to_fp32(uint8_t x) { // 2^(x-127); x == 0 -> 2^-127
+ const uint32_t bits = x == 0 ? 0x00400000u : (uint32_t) x << 23;
+ return __uint_as_float(bits);
+}
+
+static __device__ __forceinline__ float vec_dot_mxfp4_q8_1(
+ const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & kbx, const int & iqs) {
+
+ const block_mxfp4 * bq4 = (const block_mxfp4 *) vbq + kbx;
+
+ const int * q8 = (const int *) bq8_1->qs + iqs;
+
+ int sumi = 0;
+#pragma unroll
+ for (int l = 0; l < VDR_MXFP4_Q8_1_MMVQ; ++l) {
+ const int aux_q4 = get_int_b1(bq4->qs, iqs + l);
+ const int2 v = get_int_from_table_16(aux_q4, kvalues_mxfp4);
+
+ sumi = ggml_dp4a(v.x, q8[l + 0], sumi);
+ sumi = ggml_dp4a(v.y, q8[l + 4], sumi);
+ }
+
+ const float d = mxfp4_e8m0_to_fp32(bq4->e) * 0.5f * __low2float(bq8_1->ds);
+ return d * sumi;
+}
+
+} // namespace ggml_iq
diff --git a/exllamav3/foreign_quant/triton_moe_mxfp4.py b/exllamav3/foreign_quant/triton_moe_mxfp4.py
index e0d5f9f..dfed095 100644
--- a/exllamav3/foreign_quant/triton_moe_mxfp4.py
+++ b/exllamav3/foreign_quant/triton_moe_mxfp4.py
@@ -46,6 +46,14 @@ def _mxfp4_moe(x_ptr, wtab, btab, sel_ptr, y_ptr, K, N, XDIV, HAS_B: tl.constexp
tl.store(y_ptr + slot.to(tl.int64) * N + rn, acc, mask=mn)
+MMVQ_FIRES = 0 # python-level count of EXL3_FQ_MMVQ_MXFP4 branch calls (eager / capture; a graph replay does not run python)
+
+
+def mmvq_mxfp4() -> bool:
+ """EXL3_FQ_MMVQ_MXFP4=1 on CUDA (not HIP): llama.cpp-style MXFP4 mmvq decode MoE (fq_mxfp4_moe_gu / fq_mxfp4_moe_down). Read at call time."""
+ return os.environ.get("EXL3_FQ_MMVQ_MXFP4", "0") == "1" and bool(torch.version.cuda) and not torch.version.hip
+
+
def moe_gemv(x: torch.Tensor, wtab: torch.Tensor, btab: torch.Tensor | None, sel: torch.Tensor, N: int, K: int, xdiv: int) -> torch.Tensor:
"""x (rows, K) fp16 contiguous; sel (slots,) int32 expert ids; returns (slots, N) fp32."""
slots = sel.numel()
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index 7c6094a..b57ba97 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -1900,6 +1900,32 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
return False
return True
+ def _mxfp4_mmvq_forward(self, x, h, sel, tbl, I, K, H, routing_weights, params, out_dtype):
+ """EXL3_FQ_MMVQ_MXFP4=1, one decode row: q8_1(x) once, gate+up+bias+swiglu_oai in one mmvq launch (fp16 [S, I]), q8_1(act), down + bias in one
+ mmvq launch (fp32 [S, N]), then the same torch fold as the Triton path. Weights = the stacked expert bytes via the Triton path's pointer tables."""
+ from ..foreign_quant import triton_moe_mxfp4 as MX
+ gw, gb, uw, ub, dw, db = tbl
+ S = self.num_experts_per_tok
+ ndev = h.device.index if h.device.index is not None else torch.cuda.current_device()
+ N = self.downs[0].inner.fl.out_features
+ qx = ext.fq_q8_scratch(ndev, 1, K)
+ ext.fq_quant_q8_1_rows(h, qx)
+ a = torch.empty((S, I), dtype=torch.float16, device=h.device)
+ ext.fq_mxfp4_moe_gu(qx, sel, gw, gb, uw, ub, a, I, K, float(self.act_limit))
+ qa = ext.fq_q8_scratch(ndev, S, I)
+ ext.fq_quant_q8_1_rows(a, qa)
+ 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
+ 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:
+ 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_mxfp4_grouped(self, x, y, selected_experts, routing_weights, params, out_dtype, eshape):
"""Grouped MXFP4 MoE decode: gate, up, down of every (row, expert) slot in one launch each (biases in-kernel),
the layer's own activation (swiglu_oai clamp for gpt-oss), weighted fold per row."""
@@ -1927,6 +1953,10 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
self._mx_ptrs = tbl
_, _, gw, gb, uw, ub, dw, db = tbl
sel = selected_experts.reshape(-1).to(torch.int32).contiguous()
+ if (MX.mmvq_mxfp4() 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_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)
diff --git a/tests/test_fq_mmvq_mxfp4_gpu.py b/tests/test_fq_mmvq_mxfp4_gpu.py
new file mode 100644
index 0000000..4e38b68
--- /dev/null
+++ b/tests/test_fq_mmvq_mxfp4_gpu.py
@@ -0,0 +1,92 @@
+"""GPU check for EXL3_FQ_MMVQ_MXFP4: random packed MXFP4 experts at small shapes, flag-on output of
+BlockSparseMLP._forward_mxfp4_grouped (R == 1) and of the raw kernels vs an fp32 dequant reference, rel L2 < 2e-2.
+Skipped without CUDA, the built extension or the fq_mxfp4_moe_* kernels."""
+import os
+import types
+
+import pytest
+import torch
+
+pytestmark = [pytest.mark.gpu, pytest.mark.ext,
+ pytest.mark.skipif(not torch.cuda.is_available() or bool(torch.version.hip), reason="needs CUDA")]
+
+E, S, H, K, I, LIM = 6, 4, 192, 256, 128, 7.0 # hidden 192 padded to K = 256 (as gpt-oss 2880 -> 2944); down: N = 256 rows, K = I = 128
+
+
+def _packed(rows, k, gen):
+ nb = k // 32
+ t = torch.randint(0, 256, (E, rows, nb, 17), dtype=torch.uint8, generator=gen)
+ t[..., 0] = torch.randint(118, 127, (E, rows, nb), dtype=torch.uint8, generator=gen) # scales around 2^-9 .. 2^-1
+ return t.reshape(E, rows * nb * 17).cuda()
+
+
+def _rel(a, b):
+ return ((a.float() - b.float()).norm() / b.float().norm()).item()
+
+
+def test_mmvq_mxfp4_moe_vs_dequant_reference(monkeypatch):
+ from exllamav3.ext import exllamav3_ext as ext
+ if not (hasattr(ext, "fq_mxfp4_moe_gu") and hasattr(ext, "fq_mxfp4_moe_down")):
+ pytest.skip("extension built without fq_mxfp4_moe_*")
+ from exllamav3.foreign_quant import gap_formats as GF
+ from exllamav3.foreign_quant import triton_moe_mxfp4 as MX
+ from exllamav3.modules import block_sparse_mlp as B
+
+ gen = torch.Generator().manual_seed(0)
+ gp, up, dp = _packed(I, K, gen), _packed(I, K, gen), _packed(K, I, gen)
+ gb, ub, db = [(torch.randn(E, n, generator=gen) * 0.1).half().cuda() for n in (I, I, K)]
+ x = (torch.randn(1, H, generator=gen) * 0.5).half().cuda()
+ sel = torch.tensor([[3, 0, 5, 1]], dtype=torch.int64).cuda()
+ rw = torch.tensor([[0.4, 0.3, 0.2, 0.1]]).cuda()
+
+ def tbl(t):
+ return torch.tensor([t[e].data_ptr() for e in range(E)], dtype=torch.int64).cuda()
+
+ def mod(t, b, n, k):
+ return types.SimpleNamespace(inner=types.SimpleNamespace(
+ fl=types.SimpleNamespace(packed=t, in_features=k, out_features=n, format="mxfp4"), bias=b))
+
+ gates = [mod(gp[e], gb[e], I, K) for e in range(E)]
+ ups = [mod(up[e], ub[e], I, K) for e in range(E)]
+ downs = [mod(dp[e], db[e], K, I) for e in range(E)]
+ me = types.SimpleNamespace(num_experts_per_tok=S, activation_fn="swiglu_oai", act_limit=LIM, shared_experts=None,
+ gates=gates, ups=ups, downs=downs)
+ me._mxfp4_grouped_ok = lambda y: True
+ me._mxfp4_mmvq_forward = types.MethodType(B.BlockSparseMLP._mxfp4_mmvq_forward, me)
+
+ # fp32 reference from the engine's own dequant of the same bytes
+ def deq(t, n, k):
+ return torch.stack([GF.dequant("mxfp4", t[e].reshape(n, -1)).float() for e in range(E)])
+ Wg, Wu, Wd = deq(gp, I, K), deq(up, I, K), deq(dp, K, I)
+ xp = torch.nn.functional.pad(x, (0, K - H)).float()[0]
+ ref_d = torch.empty(S, K, device="cuda")
+ ref_a = torch.empty(S, I, device="cuda")
+ for s in range(S):
+ e = sel[0, s].item()
+ g = (Wg[e] @ xp + gb[e].float()).half().float().clamp(max=LIM)
+ u = (Wu[e] @ xp + ub[e].float()).half().float().clamp(-LIM, LIM)
+ a = ((u + 1.0) * g * torch.sigmoid(1.702 * g)).half()
+ ref_a[s] = a.float()
+ ref_d[s] = Wd[e] @ a.float() + db[e].float()
+ ref_out = (ref_d[:, :H] * rw.reshape(S, 1)).sum(0, keepdim=True)
+
+ # raw kernels
+ ssel = sel.reshape(-1).to(torch.int32).contiguous()
+ qx = ext.fq_q8_scratch(0, 1, K)
+ ext.fq_quant_q8_1_rows(torch.nn.functional.pad(x, (0, K - H)).contiguous(), qx)
+ a = torch.empty(S, I, dtype=torch.float16, device="cuda")
+ ext.fq_mxfp4_moe_gu(qx, ssel, tbl(gp), tbl(gb), tbl(up), tbl(ub), a, I, K, LIM)
+ assert _rel(a, ref_a) < 2e-2, _rel(a, ref_a)
+ qa = ext.fq_q8_scratch(0, S, I)
+ ext.fq_quant_q8_1_rows(a, qa)
+ d = torch.empty(S, K, dtype=torch.float32, device="cuda")
+ ext.fq_mxfp4_moe_down(qa, ssel, tbl(dp), tbl(db), d, K, I)
+ assert _rel(d, ref_d) < 2e-2, _rel(d, ref_d)
+
+ # flag on: whole decode branch of _forward_mxfp4_grouped
+ monkeypatch.setenv("EXL3_FQ_MMVQ_MXFP4", "1")
+ fires = MX.MMVQ_FIRES
+ out = B.BlockSparseMLP._forward_mxfp4_grouped(me, x, x, sel, rw, {}, None, None)
+ assert MX.MMVQ_FIRES == fires + 1, "mmvq branch did not fire"
+ assert out.shape == (1, H)
+ assert _rel(out, ref_out) < 2e-2, _rel(out, ref_out)
diff --git a/tests/test_mmvq_mxfp4_cpu.py b/tests/test_mmvq_mxfp4_cpu.py
new file mode 100644
index 0000000..5d56854
--- /dev/null
+++ b/tests/test_mmvq_mxfp4_cpu.py
@@ -0,0 +1,270 @@
+"""CPU checks for EXL3_FQ_MMVQ_MXFP4 (no GPU, no kernel launch, no extension build).
+
+1. e8m0 convention: ggml (kvalues x ggml_e8m0_to_fp32(e) * 0.5) == engine dequant (exp2(e - 128) x fp4) on the same bytes
+2. numpy emulation of vec_dot_mxfp4_q8_1 (+ the 4-warp lane partition of the kernel) vs dequant(W) @ x, rel < 1e-2
+3. numpy emulation of the gate/up epilogue (bias, fp16 rounding, clamp, swiglu_oai)
+4. dispatch with stubs: flag 0 -> Triton calls only (identical to today), flag 1 -> quant, gu, quant, down, fold;
+ R > 1 / other activation / no bias -> old path
+
+Modules are loaded by path (gap_formats, triton_moe_mxfp4) or cut out of the source by ast (the two BlockSparseMLP methods), so that
+nothing imports exllamav3.ext (which would start the extension build).
+"""
+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")
+
+KV = np.array([0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12], dtype=np.int64) # kvalues_mxfp4 (= doubled e2m1)
+
+
+class _Dummy:
+ """Stands in for triton / triton.language when only the module-level code of triton_moe_mxfp4 has to run."""
+ def __call__(self, *a, **k):
+ return a[0] if len(a) == 1 and callable(a[0]) and not k else _Dummy()
+ def __getattr__(self, n):
+ return _Dummy()
+ def __getitem__(self, k):
+ return _Dummy()
+
+
+def _load(name, rel, extra_modules=None):
+ """Load exllamav3/<rel> by path as exllamav3.<name> under empty parent packages (their __init__ is never run)."""
+ saved = {}
+ mods = {"exllamav3": types.ModuleType("exllamav3"), "exllamav3.foreign_quant": types.ModuleType("exllamav3.foreign_quant")}
+ mods["exllamav3"].__path__ = [PKG]
+ mods["exllamav3.foreign_quant"].__path__ = [os.path.join(PKG, "foreign_quant")]
+ mods.update(extra_modules or {})
+ for k, v in mods.items():
+ saved[k] = sys.modules.get(k)
+ sys.modules[k] = v
+ try:
+ 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)
+ return m
+ finally:
+ sys.modules.pop(name, None)
+ for k, v in saved.items():
+ if v is None:
+ sys.modules.pop(k, None)
+ else:
+ sys.modules[k] = v
+
+
+def _gap_formats():
+ return _load("exllamav3.foreign_quant.gap_formats", "foreign_quant/gap_formats.py")
+
+
+def _mx():
+ return _load("exllamav3.foreign_quant.triton_moe_mxfp4", "foreign_quant/triton_moe_mxfp4.py",
+ {"triton": _Dummy(), "triton.language": _Dummy()})
+
+
+def _mlp_methods():
+ """The two BlockSparseMLP methods under test, compiled from the source file without importing the module."""
+ src = open(os.path.join(PKG, "modules/block_sparse_mlp.py")).read()
+ tree = ast.parse(src)
+ cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "BlockSparseMLP")
+ want = ("_mxfp4_mmvq_forward", "_forward_mxfp4_grouped")
+ 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"}
+ exec(compile(ast.fix_missing_locations(mod), "block_sparse_mlp.py", "exec"), ns)
+ return ns
+
+
+def e8m0_ggml(e):
+ """ggml_cuda_e8m0_to_fp32 (common.cuh:830): bf16 raw e8m0 = 2^(e-127); e == 0 -> 2^-127 (bits 0x00400000)."""
+ bits = np.where(e == 0, np.uint32(0x00400000), (e.astype(np.uint32) << 23)).astype(np.uint32)
+ return bits.view(np.float32)
+
+
+def dequant_np(raw, nb):
+ """raw uint8 [N, nb*17] -> float32 [N, nb*32] with the ggml convention: kvalues * (e8m0 * 0.5)."""
+ b = raw.reshape(raw.shape[0], nb, 17)
+ d = (e8m0_ggml(b[..., 0]) * np.float32(0.5))[..., None]
+ qs = b[..., 1:]
+ v = np.concatenate([KV[qs & 15], KV[qs >> 4]], axis=-1).astype(np.float32)
+ return (d * v).reshape(raw.shape[0], nb * 32)
+
+
+def quant_q8_1(x):
+ """per-32 q8_1: d = amax / 127 (fp16), q = round(x / d); returns (d fp32 [nb], q int8 [nb, 32])."""
+ xb = x.reshape(-1, 32).astype(np.float32)
+ amax = np.abs(xb).max(1)
+ d = (amax / 127.0).astype(np.float16).astype(np.float32)
+ dd = np.where(d == 0, 1.0, d)
+ q = np.clip(np.rint(xb / dd[:, None]), -127, 127).astype(np.int8)
+ return d, q
+
+
+def vec_dot_np(row_bytes, nb, d8, q8):
+ """The kernel's work split: 4 warps x 32 lanes = 128 threads, blocks_per_iter = vdr(2) * 128 / qi(4) = 64, kbx = tid / 2 (+ 64 per iter),
+ iqs = vdr * (tid % 2); each call = vec_dot_mxfp4_q8_1 (2 ints x 2 dp4a). Returns per-thread partial sums (128,) -> sum = row result."""
+ b = row_bytes.reshape(nb, 17)
+ part = np.zeros(128, dtype=np.float64)
+ for tid in range(128):
+ for kbx in range(tid // 2, nb, 64):
+ iqs = 2 * (tid % 2)
+ e, qs = b[kbx, 0], b[kbx, 1:]
+ sumi = 0
+ for l in range(2):
+ four = qs[4 * (iqs + l): 4 * (iqs + l) + 4]
+ vx, vy = KV[four & 15], KV[four >> 4] # get_int_from_table_16: v.x = low nibbles, v.y = high nibbles
+ sumi += int((vx * q8[kbx, 4 * (iqs + l): 4 * (iqs + l) + 4]).sum())
+ sumi += int((vy * q8[kbx, 16 + 4 * (iqs + l): 16 + 4 * (iqs + l) + 4]).sum())
+ part[tid] += float(e8m0_ggml(np.array([e]))[0] * np.float32(0.5) * np.float32(d8[kbx])) * sumi
+ return part
+
+
+def rnd16(v):
+ return np.float32(np.float16(v))
+
+
+def swiglu_oai(g, u, lim):
+ g = np.minimum(g, lim)
+ u = np.minimum(np.maximum(u, -lim), lim)
+ return (u + 1.0) * g * (1.0 / (1.0 + np.exp(-1.702 * g)))
+
+
+def test_e8m0_convention_matches_engine_dequant():
+ GF = _gap_formats()
+ rng = np.random.default_rng(0)
+ nb, N = 8, 6
+ raw = rng.integers(0, 256, (N, nb, 17), dtype=np.uint8)
+ raw[..., 0] = rng.integers(112, 136, (N, nb), dtype=np.uint8)
+ raw[0, 0, 0] = 0
+ raw[0, 1, 0] = 1 # denormal corner (fp16 flushes these to 0 on both sides)
+ eng = GF.dequant("mxfp4", torch.from_numpy(raw.reshape(N, -1))).float().numpy()
+ ref = dequant_np(raw.reshape(N, -1), nb)
+ assert np.array_equal(eng, ref.astype(np.float16).astype(np.float32))
+ allb = np.arange(0, 255, dtype=np.uint8) # full e8m0 range: ggml value == 2^(e-128) (what Triton / engine use), in fp32
+ assert np.array_equal(e8m0_ggml(allb) * np.float32(0.5), np.exp2(allb.astype(np.float64) - 128.0).astype(np.float32))
+
+
[email protected]("K", [2944, 2880]) # 92 blocks (gate/up shape), 90 blocks (down shape)
+def test_vec_dot_emulation(K):
+ rng = np.random.default_rng(K)
+ nb = K // 32
+ W = rng.integers(0, 256, (3, nb * 17), dtype=np.uint8).reshape(3, nb, 17)
+ W[..., 0] = rng.integers(118, 127, (3, nb), dtype=np.uint8)
+ W = W.reshape(3, -1)
+ x = (rng.standard_normal(K) * 0.5).astype(np.float16).astype(np.float32)
+ d8, q8 = quant_q8_1(x)
+ wd = dequant_np(W, nb)
+ exact = wd.astype(np.float64) @ x.astype(np.float64)
+ for r in range(3):
+ got = vec_dot_np(W[r], nb, d8, q8).sum()
+ rel = abs(got - exact[r]) / (np.linalg.norm(wd[r]) * np.linalg.norm(x) + 1e-30)
+ assert rel < 1e-2, (K, r, got, exact[r], rel)
+ cover = np.zeros(nb)
+ for tid in range(128):
+ for kbx in range(tid // 2, nb, 64):
+ cover[kbx] += 1
+ assert (cover == 2).all(), "every block must be taken by exactly 2 lanes (iqs 0 and 2)"
+
+
+def test_epilogue_swiglu_oai():
+ rng = np.random.default_rng(1)
+ lim = 7.0
+ ag, au = rng.standard_normal(4096) * 6, rng.standard_normal(4096) * 6
+ bg, bu = (rng.standard_normal(4096) * 0.1).astype(np.float16), (rng.standard_normal(4096) * 0.1).astype(np.float16)
+ g = rnd16(ag + bg.astype(np.float32))
+ u = rnd16(au + bu.astype(np.float32))
+ a_kernel = np.float16(swiglu_oai(g, u, lim))
+ gg, uu = np.minimum(g, lim), np.clip(u, -lim, lim)
+ a_ref = np.float16((uu + 1.0) * (gg * (1.0 / (1.0 + np.exp(-1.702 * gg)))))
+ assert np.abs(a_kernel.astype(np.float32) - a_ref.astype(np.float32)).max() <= 2 ** -9 * np.abs(a_ref.astype(np.float32)).max()
+
+
+def test_flag_read_at_call_time(monkeypatch):
+ MX = _mx()
+ monkeypatch.setattr(torch.version, "cuda", "13.0")
+ monkeypatch.setattr(torch.version, "hip", None)
+ for v, want in (("1", True), ("0", False), (None, False)):
+ monkeypatch.delenv("EXL3_FQ_MMVQ_MXFP4", raising=False)
+ if v is not None:
+ monkeypatch.setenv("EXL3_FQ_MMVQ_MXFP4", v)
+ assert MX.mmvq_mxfp4() is want
+ monkeypatch.setenv("EXL3_FQ_MMVQ_MXFP4", "1")
+ monkeypatch.setattr(torch.version, "hip", "6.1")
+ assert MX.mmvq_mxfp4() is False # off on HIP
+
+
+def test_dispatch_with_stubs(monkeypatch):
+ MX = _mx()
+ ns = _mlp_methods()
+ monkeypatch.setattr(torch.version, "cuda", "13.0")
+ monkeypatch.setattr(torch.version, "hip", None)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ rec = []
+
+ class Ext:
+ def fq_q8_scratch(self, dev, M, K):
+ rec.append(("scratch", M, K))
+ return torch.empty(M, K // 32 * 36, dtype=torch.uint8)
+ def fq_quant_q8_1_rows(self, x, qb): rec.append(("quant", tuple(x.shape)))
+ def fq_mxfp4_moe_gu(self, qb, sel, gw, gb, uw, ub, a, I, K, lim): rec.append(("gu", I, K, lim, tuple(a.shape), sel.dtype))
+ def fq_mxfp4_moe_down(self, qa, sel, dw, db, d, N, K): rec.append(("down", N, K, tuple(d.shape), db.numel()))
+
+ ns["ext"] = Ext()
+
+ def stub_gemv(*a, **k):
+ rec.append(("tri_gemv", a[4], a[5]))
+ return torch.zeros(a[3].numel(), a[4])
+ MX.moe_gemv = stub_gemv
+ # the method does `from ..foreign_quant import triton_moe_mxfp4 as MX`: resolve it to this module
+ pkg = types.ModuleType("exllamav3.modules"); pkg.__path__ = []
+ fq = types.ModuleType("exllamav3.foreign_quant"); fq.triton_moe_mxfp4 = MX; fq.__path__ = []
+ root = types.ModuleType("exllamav3"); root.__path__ = []
+ for k, v in (("exllamav3", root), ("exllamav3.modules", pkg), ("exllamav3.foreign_quant", fq),
+ ("exllamav3.foreign_quant.triton_moe_mxfp4", MX)):
+ monkeypatch.setitem(sys.modules, k, v)
+ ns["__package__"] = "exllamav3.modules"
+
+ def mk(H=2880, K=2944, I=2880, bias=True, act="swiglu_oai", R=1):
+ def mod(n, k):
+ t = torch.zeros(8, n * (k // 32) * 17, dtype=torch.uint8)
+ return types.SimpleNamespace(inner=types.SimpleNamespace(
+ fl=types.SimpleNamespace(packed=t[0], in_features=k, out_features=n, format="mxfp4"),
+ bias=torch.zeros(n, dtype=torch.float16) if bias else None))
+ s = types.SimpleNamespace(num_experts_per_tok=4, activation_fn=act, act_limit=7.0, shared_experts=None,
+ gates=[mod(I, K)] * 4, ups=[mod(I, K)] * 4, downs=[mod(2880, I)] * 4)
+ s._mxfp4_grouped_ok = lambda y: True
+ s._mxfp4_mmvq_forward = types.MethodType(ns["_mxfp4_mmvq_forward"], s)
+ s.activation_fn_call = lambda g, u, a, lim: rec.append(("act_call",))
+ y = torch.zeros(R, H, dtype=torch.float16)
+ return s, y, torch.zeros(R, 4, dtype=torch.int64), torch.full((R, 4), 0.25)
+
+ def run(**kw):
+ rec.clear()
+ s, y, sel, rw = mk(**kw)
+ out = ns["_forward_mxfp4_grouped"](s, y, y, sel, rw, {}, None, None)
+ return [r[0] for r in rec], out
+
+ monkeypatch.setenv("EXL3_FQ_MMVQ_MXFP4", "0")
+ names, _ = run()
+ assert names == ["tri_gemv", "tri_gemv", "act_call", "tri_gemv"], names
+ monkeypatch.setenv("EXL3_FQ_MMVQ_MXFP4", "1")
+ fires = MX.MMVQ_FIRES
+ names, out = run()
+ assert names == ["scratch", "quant", "gu", "scratch", "quant", "down"], names
+ assert MX.MMVQ_FIRES == fires + 1
+ assert out.shape[-1] == 2880, out.shape
+ g = [r for r in rec if r[0] == "gu"][0]
+ d = [r for r in rec if r[0] == "down"][0]
+ assert g[1:6] == (2880, 2944, 7.0, (4, 2880), torch.int32) and d[1:4] == (2880, 2880, (4, 2880)) and d[4] == 4
+ assert [r for r in rec if r[0] == "quant"] == [("quant", (1, 2944)), ("quant", (4, 2880))]
+ for kw in (dict(R=2), dict(act="silu"), dict(bias=False)): # outside the branch conditions -> today's code
+ names, _ = run(**kw)
+ assert not any(n in ("gu", "down") for n in names) and any(n.startswith("tri") for n in names), (kw, names)