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
Add opt-in K6 and K8 fused MoE support (#104)
razeth6b87266cb7de
diff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuindex a896327..2d98a3b 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cu@@ -102,7 +102,7 @@ template <class S> void mf_launch}} // namespace-#define MF_SHAPES(X) X(mf::QwenShape) X(mf::SmallTestShape) X(mf::SmallK3Shape) X(mf::QwenK3S4) X(mf::QwenK3S5) X(mf::QwenK4S4) X(mf::QwenK4S5) X(mf::SmallK3S4) X(mf::SmallK3S5) X(mf::SmallK4S4) X(mf::SmallK4S5) X(mf::QwenK6S6) X(mf::SmallK6S6) X(mf::QwenK4S6) X(mf::QwenK5S6) X(mf::SmallK4S6) X(mf::SmallK5S6)+#define MF_SHAPES(X) X(mf::QwenShape) X(mf::SmallTestShape) X(mf::SmallK3Shape) X(mf::QwenK3S4) X(mf::QwenK3S5) X(mf::QwenK4S4) X(mf::QwenK4S5) X(mf::SmallK3S4) X(mf::SmallK3S5) X(mf::SmallK4S4) X(mf::SmallK4S5) X(mf::QwenK6S6) X(mf::SmallK6S6) X(mf::QwenK6S8) X(mf::SmallK6S8) X(mf::QwenK4S6) X(mf::QwenK5S6) X(mf::SmallK4S6) X(mf::SmallK5S6)bool exl3_moe_fused_supported(int64_t D, int64_t H, int64_t LR, int64_t NEXP, int64_t TOPK, int64_t INTER, int64_t RB, int64_t SB){@@ -194,6 +194,7 @@ void exl3_moe_fused_tile_test(const at::Tensor& A, const at::Tensor& B, at::Tenselse if (bits == 4) ok = mf_tt_dispatch<4>(ks, cf, A, B, C, R, nt, (int) native, stream);else if (bits == 5) ok = mf_tt_dispatch<5>(ks, cf, A, B, C, R, nt, (int) native, stream);else if (bits == 6) ok = mf_tt_dispatch<6>(ks, cf, A, B, C, R, nt, (int) native, stream);+ else if (bits == 8) ok = mf_tt_dispatch<8>(ks, cf, A, B, C, R, nt, (int) native, stream);TORCH_CHECK(ok, "tile test: (bits, K, output dtype) not instantiated");}#endifdiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuhindex bbb75fb..04862b3 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuh+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused.cuh@@ -213,6 +213,14 @@ __device__ __forceinline__ void mf_dq8_k6(const uint32_t (&w)[7], const int t, Fexl3_gemv_ns::decode8<2>(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], f0, f1);}+// K8 shared expert: one wrap word plus eight own words, same mul1 codebook.+__device__ __forceinline__ void mf_dq8_k8(const uint32_t (&w)[9], const int t, FragB& f0, FragB& f1)+{+ unsigned v[8];+ kn_words(8, w, t, v);+ exl3_gemv_ns::decode8<2>(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], f0, f1);+}+// ---------------------------------------------------------------- VALU tile on a trellis tile (native or repacked layout)// One wave = one 16-column tile, all k. Same decode body as core3's mv_tile; Bt = base of the tile's first k-slice, ss = u32 between k-slices.// Lane (cq, g8): g8 = column pair (g8, g8 + 8), cq = chunk lane. Words: wrap word + `BITS` own words; K3 own words are three scalar loads (3 g8 is not@@ -222,7 +230,7 @@ template <int BITS, bool CF32, int RW, int KS>__device__ __forceinline__ void mf_tile(const uint32_t* __restrict__ A32, const uint32_t* __restrict__ Bt, long ss, void* __restrict__ C,int size_n, int tile, float* red, int wave, int lane){- static_assert(BITS >= 2 && BITS <= 6, "K1, K7.. need their own per-lane word set and decode body: not implemented");+ static_assert((BITS >= 2 && BITS <= 6) || BITS == 8, "K1 and K7 are not implemented in this fused tile");constexpr int NWD = BITS + 1, CH = (KS + 15) / 16, NRND = 4, K = KS * 16;constexpr int VU = CH > 5 ? 5 : CH;const int g8 = lane & 7, cq = lane >> 3;@@ -238,6 +246,7 @@ __device__ __forceinline__ void mf_tile(const uint32_t* __restrict__ A32, constelse if constexpr (BITS == 3) { w[1] = q[0]; w[2] = q[1]; w[3] = q[2]; }else if constexpr (BITS == 5) { w[1] = q[0]; w[2] = q[1]; w[3] = q[2]; w[4] = q[3]; w[5] = q[4]; }else if constexpr (BITS == 6) { const uint2 v0 = *(const uint2*) q, v1 = *(const uint2*) (q + 2), v2 = *(const uint2*) (q + 4); w[1] = v0.x; w[2] = v0.y; w[3] = v1.x; w[4] = v1.y; w[5] = v2.x; w[6] = v2.y; }+ else if constexpr (BITS == 8) { const uint4 v0 = *(const uint4*) q, v1 = *(const uint4*) (q + 4); w[1] = v0.x; w[2] = v0.y; w[3] = v0.z; w[4] = v0.w; w[5] = v1.x; w[6] = v1.y; w[7] = v1.z; w[8] = v1.w; }else { const uint4 v = *(const uint4*) q; w[1] = v.x; w[2] = v.y; w[3] = v.z; w[4] = v.w; }};auto ldst = [&](uint32_t (&w)[VU][NWD], int rnd, int sg0)@@ -275,6 +284,7 @@ __device__ __forceinline__ void mf_tile(const uint32_t* __restrict__ A32, constelse if constexpr (BITS == 3) exl3_gemv_ns::dq8_regs_3bits<2>(wa[u][t == 0 ? 0 : (t == 1 ? 1 : 2)], wa[u][t == 0 ? 1 : (t == 1 ? 2 : 3)], t == 0 ? 8 : (t == 1 ? 16 : (t == 2 ? 24 : 0)), f0[t], f1[t]);else if constexpr (BITS == 5) mf_dq8_k5(wa[u], t, f0[t], f1[t]);else if constexpr (BITS == 6) mf_dq8_k6(wa[u], t, f0[t], f1[t]);+ else if constexpr (BITS == 8) mf_dq8_k8(wa[u], t, f0[t], f1[t]);else exl3_gemv_ns::dq8_regs_4bits<2>(wa[u][t], wa[u][t + 1], f0[t], f1[t]);}#pragma unrolldiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_mv.cuh b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_mv.cuhindex 6a4dc8d..2424b6e 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_mv.cuh+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused7_mv.cuh@@ -55,7 +55,7 @@ template <int BITS, bool CF32, int RW, int KS, int ABL>__device__ __forceinline__ void mf7_tile(const uint32_t* __restrict__ A32, const uint32_t* __restrict__ Bt, long ss, void* __restrict__ C,int size_n, int tile, float* red, int wave, int lane){- static_assert(BITS >= 2 && BITS <= 6, "K1, K7.. need their own per-lane word set and decode body: not implemented");+ static_assert((BITS >= 2 && BITS <= 6) || BITS == 8, "K1 and K7 are not implemented in this fused tile");constexpr int NWD = BITS + 1, CH = (KS + 15) / 16, NRND = 4, K = KS * 16;constexpr int VU = CH > 5 ? 5 : CH;const int g8 = lane & 7, cq = lane >> 3;@@ -72,6 +72,7 @@ __device__ __forceinline__ void mf7_tile(const uint32_t* __restrict__ A32, constelse if constexpr (BITS == 3) { w[1] = q[0]; w[2] = q[1]; w[3] = q[2]; }else if constexpr (BITS == 5) { w[1] = q[0]; w[2] = q[1]; w[3] = q[2]; w[4] = q[3]; w[5] = q[4]; }else if constexpr (BITS == 6) { const uint2 v0 = *(const uint2*) q, v1 = *(const uint2*) (q + 2), v2 = *(const uint2*) (q + 4); w[1] = v0.x; w[2] = v0.y; w[3] = v1.x; w[4] = v1.y; w[5] = v2.x; w[6] = v2.y; }+ else if constexpr (BITS == 8) { const uint4 v0 = *(const uint4*) q, v1 = *(const uint4*) (q + 4); w[1] = v0.x; w[2] = v0.y; w[3] = v0.z; w[4] = v0.w; w[5] = v1.x; w[6] = v1.y; w[7] = v1.z; w[8] = v1.w; }else { const uint4 v = *(const uint4*) q; w[1] = v.x; w[2] = v.y; w[3] = v.z; w[4] = v.w; }};auto ldst = [&](uint32_t (&w)[VU][NWD], int rnd, int sg0)@@ -116,6 +117,7 @@ __device__ __forceinline__ void mf7_tile(const uint32_t* __restrict__ A32, constelse if constexpr (BITS == 3) exl3_gemv_ns::dq8_regs_3bits<2>(wa[u][t == 0 ? 0 : (t == 1 ? 1 : 2)], wa[u][t == 0 ? 1 : (t == 1 ? 2 : 3)], t == 0 ? 8 : (t == 1 ? 16 : (t == 2 ? 24 : 0)), f0[t], f1[t]);else if constexpr (BITS == 5) mf_dq8_k5(wa[u], t, f0[t], f1[t]);else if constexpr (BITS == 6) mf_dq8_k6(wa[u], t, f0[t], f1[t]);+ else if constexpr (BITS == 8) mf_dq8_k8(wa[u], t, f0[t], f1[t]);else exl3_gemv_ns::dq8_regs_4bits<2>(wa[u][t], wa[u][t + 1], f0[t], f1[t]);}#pragma unrolldiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cuindex f0e2997..c6da5e1 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused9.cu@@ -130,6 +130,12 @@ void mf9_half(at::Tensor& x, const at::Tensor& fn, const at::Tensor& fn_scale, cswitch ((variant >> 8) & 3) { case 1: L7A(mf::QwenK4S5, true, 2, 1, 1); break; case 2: L7A(mf::QwenK4S5, true, 2, 1, 2); break; default: L7A(mf::QwenK4S5, true, 2, 1, 3); } return; }X9D(mf::QwenK3S4) X9D(mf::QwenK3S5) X9D(mf::QwenK4S4) X9D(mf::QwenK4S5)X9D(mf::QwenK6S6) X9D(mf::SmallK6S6)+ if (Match7<mf::QwenK6S8>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB) || Match7<mf::SmallK6S8>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) {+ TORCH_CHECK((variant & ~0x1000LL) == 0x160000 && !timing, "mf9: experimental K6S8 supports only six-stage launches without timing or ablations");+ if (Match7<mf::QwenK6S8>::eq(D, H, LR, NEXP, TOPK, INTER, RB, SB)) L7(mf::QwenK6S8, false, 4, 1);+ else L7(mf::SmallK6S8, false, 4, 1);+ return;+ }X9D(mf::QwenK4S6) X9D(mf::QwenK5S6) X9D(mf::SmallK4S6) X9D(mf::SmallK5S6)X9D(mf::SmallK3S4) X9D(mf::SmallK3S5) X9D(mf::SmallK4S4) X9D(mf::SmallK4S5)#undef X9Ddiff --git a/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.h b/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.hindex 9d7f558..2be703e 100644--- a/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.h+++ b/exllamav3/exllamav3_ext/quant/exl3_moe_fused_idx.h@@ -48,6 +48,9 @@ struct SmallK3S5 { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPKstruct SmallK4S4 { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPK = 4, INTER = 128, RB = 4, SB = 4; };struct QwenK6S6 { static constexpr int D = 2560, H = 4, LR = 320, NEXP = 512, TOPK = 10, INTER = 640, RB = 6, SB = 6; }; // the MTP drafter layer of the public pack (routed K6, shared K6)struct SmallK6S6 { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPK = 4, INTER = 128, RB = 6, SB = 6; };+// Experimental six-bit routed / eight-bit shared experts; Python serving requires EXL3_MOE_FUSED_K6S8=1.+struct QwenK6S8 : QwenK6S6 { static constexpr int SB = 8; };+struct SmallK6S8 : SmallK6S6 { static constexpr int SB = 8; };struct SmallK4S5 { static constexpr int D = 256, H = 4, LR = 32, NEXP = 64, TOPK = 4, INTER = 128, RB = 4, SB = 5; };// 4 bpw and 5 bpw routed experts with a K6 shared expert (the layout of the public 4.05 bpw pack; K5S6 is its 5 bpw sibling), and small twinsstruct QwenK4S6 { static constexpr int D = 2560, H = 4, LR = 320, NEXP = 512, TOPK = 10, INTER = 640, RB = 4, SB = 6; };@@ -86,7 +89,7 @@ struct Dmstatic_assert(TOPK >= 1 && TOPK <= 15, "combine uses wave <= TOPK, 16 waves");static_assert(MAXR * TOPK <= THREADS && MAXR * TOPK <= 40, "sort/group arrays");static_assert(TRows<S>::v >= MAXR && TRows<S>::v <= MAXRT && TRows<S>::v * TOPK <= THREADS, "wide instantiation: sort/group arrays (one thread per slot)");- static_assert((RB >= 2 && RB <= 6) && (SB >= 2 && SB <= 6), "K2, K3, K4, K5, K6");+ static_assert((RB >= 2 && RB <= 6) && ((SB >= 2 && SB <= 6) || SB == 8), "routed K2..K6; shared K2..K6 or K8");static_assert(H >= 1 && H <= 4, "dred/rmr scratch");static_assert(LR % 1 == 0 && LR <= 1024, "t scratch");// dynamic-free LDS: A + A2 for MAXR rows of the larger of D / INTER@@ -126,8 +129,9 @@ MF_FN int kn_i0(int bits, int t, int g) { return kn_MF_FN int kn_i2(int bits, int t, int g) { return (kn_rel(bits, t, g) + 3 * bits + 15) / 32; }MF_FN int kn_s2(int bits, int t, int g) { return (kn_i2(bits, t, g) + 1) * 32 - (kn_rel(bits, t, g) + 3 * bits + 16); }// the 8 trellis words (16 bit each, low half) of lane (g8, t) from its lane set w[0 .. bits] (wrap, own0 ..), in the order the decoder takes them-template <class W> MF_FN void kn_words(int bits, const W (&w)[7], int t, unsigned (&v)[8])+template <class W, int N> MF_FN void kn_words(int bits, const W (&w)[N], int t, unsigned (&v)[8]){+ static_assert(N == 7 || N == 9, "K6 needs seven words; K8 needs nine");for (int g = 0; g < 2; ++g){const unsigned long long m = ((unsigned long long) w[kn_i0(bits, t, g)] << 32) | (unsigned long long) w[kn_i2(bits, t, g)];diff --git a/exllamav3/modules/moe_fused.py b/exllamav3/modules/moe_fused.pyindex 54270c3..8a2104f 100644--- a/exllamav3/modules/moe_fused.py+++ b/exllamav3/modules/moe_fused.py@@ -37,6 +37,35 @@ def enabled_by_env() -> bool:return bool(torch.version.hip) and os.environ.get("EXL3_MOE_FUSED", "0") not in ("", "0")+def _first_k(module):+ """K of the first expert projection, or None when the module has no EXL3 projection with a K (such a block falls back)."""+ gates = getattr(module, "gates", None)+ return getattr(getattr(gates[0], "inner", None), "K", None) if gates else None+++def _k6s8_support_reason(mlp) -> str | None:+ """Enable experimental K6/K8 only with an explicit setting.++ EXL3_MOE_FUSED_K6S8=1 enables native-layout, six-stage launches only.+ Validate every projection: the fused shape has one bit width per expert class.+ """+ if _first_k(mlp) != 6 or _first_k(getattr(mlp, "shared_experts", None)) != 8:+ return None+ if os.environ.get("EXL3_MOE_FUSED_K6S8", "0") != "1":+ return "experimental K6/K8 fusion requires EXL3_MOE_FUSED_K6S8=1"+ if os.environ.get("EXL3_MOE_FUSED_LAYOUT", "native") != "native":+ return "experimental K6/K8 fusion requires native layout"+ if MF9["variant"] & ~0x1000 != 0x160000 or MF9["timing"]:+ return "experimental K6/K8 fusion requires the default six-stage variant without timing"+ for module, bits in ((mlp, 6), (mlp.shared_experts, 8)):+ for projections in (module.gates, module.ups, module.downs):+ for projection in projections:+ inner = getattr(projection, "inner", None)+ if getattr(inner, "K", None) != bits or not getattr(inner, "mul1", False) or getattr(inner, "mcg", True):+ return "experimental K6/K8 fusion needs uniform K6 routed / K8 shared mul1 projections"+ return None++def _rep(tr: torch.Tensor) -> torch.Tensor:"""(kt, nt, nw) int16 trellis -> (nt/2, kt, 2*nw) int16: one 32-column group per leading index, k-slice major."""kt, nt, nw = tr.shape@@ -77,7 +106,7 @@ class FusedMoEHalf:return "router bias / shared post norm"if len(mlp.gates) != mlp.num_experts or len(mlp.ups) != mlp.num_experts or len(mlp.downs) != mlp.num_experts:return "experts are not one linear each"- return None+ return _k6s8_support_reason(mlp)def __init__(self, block):t0 = time.time()diff --git a/tests/moe_fused/k8_check.cpp b/tests/moe_fused/k8_check.cppnew file mode 100644index 0000000..ab8861a--- /dev/null+++ b/tests/moe_fused/k8_check.cpp@@ -0,0 +1,100 @@+// CPU-only check of the actual fused word-extraction helper. No HIP runtime.+// Oracle 1 follows exl3_dq.cuh::dq4<8>; oracle 2 extracts each 16-bit word+// independently from the cyclic tile, without the fused lane-local helpers.+#include "exl3_moe_fused_idx.h"+#include <array>+#include <cstdint>+#include <cstdio>+#include <random>+#include <cstdlib>++static long checks = 0;+static void check(bool ok, const char* what) {+ ++checks;+ if (!ok) { std::fprintf(stderr, "K8 CHECK FAILED: %s\n", what); std::exit(1); }+}++static void decode_tile(const std::array<uint32_t, 64>& tile) {+ constexpr int bits = 8;+ for (int g8 = 0; g8 < 8; ++g8) {+ uint32_t w[9];+ const long own = mf::own_i(bits, g8, 0, 0);+ const long wrap = mf::wrp_i(bits, g8, 0, 0);+ check(own >= 0 && own + 8 <= 64 && wrap >= 0 && wrap < 64, "lane load bounds");+ check(own % 4 == 0 && (own + 4) % 4 == 0, "two uint4 loads aligned");+ w[0] = tile[wrap];+ for (int j = 0; j < 8; ++j) w[j + 1] = tile[own + j];+ for (int t = 0; t < 4; ++t) {+ unsigned values[8];+ mf::kn_words(bits, w, t, values);+ for (int group = 0; group < 2; ++group) {+ const int offset = 8 * (4 * g8 + t) + 4 * group;+ const int b0 = (offset + 257) * bits - 16;+ const int b2 = b0 + 3 * bits + 16;+ const int i0 = b0 / 32, i2 = (b2 - 1) / 32;+ const int shift = (i2 + 1) * 32 - b2;+ const uint64_t pair = (uint64_t(tile[i0 % 64]) << 32) | tile[i2 % 64];+ const int l0 = mf::kn_i0(bits, t, group), l2 = mf::kn_i2(bits, t, group);+ check(l0 >= 0 && l0 < 9 && l2 >= 0 && l2 < 9, "local word bounds");+ check(l2 == l0 + 1, "K8 group spans exactly two words");+ check(shift == mf::kn_s2(bits, t, group), "engine shift matches");+ for (int j = 0; j < 4; ++j) {+ const int sh = shift + bits * (3 - j);+ check(sh >= 0 && sh < 64, "valid shift");+ const unsigned engine_word = unsigned(pair >> sh) & 0xffffu;+ check(values[4 * group + j] == engine_word, "dq4 oracle mismatch");+ // Tiles are a cyclic stream of MSB-first uint32 words.+ const int pos = (b0 + bits * j) % 2048;+ unsigned bit_word = 0;+ for (int bit = 0; bit < 16; ++bit) {+ const int p = (pos + bit) % 2048;+ bit_word = (bit_word << 1) | ((tile[p / 32] >> (31 - p % 32)) & 1u);+ }+ check(values[4 * group + j] == bit_word, "independent bit oracle mismatch");+ }+ }+ }+ }+}++template<class S> static void matrices() {+ using DM = mf::Dm<S>;+ check(DM::SHARED_U32 == 3L * S::D * S::INTER * S::SB / 32, "shared matrix size");+ check(DM::EXPERT_U32 == 3L * S::D * S::INTER * S::RB / 32, "routed matrix size");+ for (int bits : {S::RB, S::SB}) {+ for (auto dims : {std::array<int, 2>{S::D / 16, S::INTER / 16},+ std::array<int, 2>{S::INTER / 16, S::D / 16}}) {+ const int ks = dims[0], nt = dims[1];+ const long size = mf::mat_words(bits, ks, nt);+ for (bool native : {false, true})+ for (int tile = 0; tile < nt; ++tile)+ for (int slice = 0; slice < ks; ++slice)+ for (int lane = 0; lane < 8; ++lane) {+ const long base = mf::tile_off(native, bits, ks, nt, tile);+ const long stride = mf::tile_ss(native, bits, nt);+ const long own = base + mf::own_i(bits, lane, slice, stride);+ const long wrap = base + mf::wrp_i(bits, lane, slice, stride);+ check(own >= 0 && own + bits <= size && wrap >= 0 && wrap < size, "matrix load bounds");+ check(own % (bits == 8 ? 4 : 2) == 0, "matrix vector-load alignment");+ }+ }+ }+}++int main() {+ std::array<uint32_t, 64> tile{};+ decode_tile(tile);+ tile.fill(0xffffffffu); decode_tile(tile);+ // Every input bit individually exercises both the wrapped first lane and last word.+ for (int bit = 0; bit < 2048; ++bit) {+ tile.fill(0); tile[bit / 32] = uint32_t(1) << (bit % 32); decode_tile(tile);+ }+ std::mt19937 random(8060);+ for (int n = 0; n < 200; ++n) {+ for (auto& word : tile) word = random();+ decode_tile(tile);+ }+ matrices<mf::SmallK6S8>();+ matrices<mf::QwenK6S8>();+ std::printf("K8 CHECK OK (%ld checks)\n", checks);+}diff --git a/tests/test_moe_fused_k8_cpu.py b/tests/test_moe_fused_k8_cpu.pynew file mode 100644index 0000000..d8e08a1--- /dev/null+++ b/tests/test_moe_fused_k8_cpu.py@@ -0,0 +1,150 @@+"""CPU checks for the experimental K6/K8 extension; these are not GPU validation."""+import ast+import os+from pathlib import Path+import subprocess+from types import SimpleNamespace++import pytest++ROOT = Path(__file__).resolve().parents[1]+QUANT = ROOT / "exllamav3/exllamav3_ext/quant"+CPP = ROOT / "tests/moe_fused/k8_check.cpp"+++def build_and_run(headers, output):+ subprocess.run([+ "g++", "-std=c++17", "-O1", "-g", "-fsanitize=address,undefined",+ "-fno-sanitize-recover=all", "-I", str(headers), str(CPP), "-o", str(output),+ ], check=True, capture_output=True, text=True)+ # LeakSanitizer cannot inspect this container's /proc; address/UB checks remain enabled.+ return subprocess.run([str(output)], capture_output=True, text=True,+ env={**os.environ, "ASAN_OPTIONS": "detect_leaks=0"})+++def test_k8_word_values_and_bounds(tmp_path):+ result = build_and_run(QUANT, tmp_path / "check")+ assert result.returncode == 0, result.stdout + result.stderr+ assert "K8 CHECK OK" in result.stdout++[email protected]("old,new", [+ ("bits + 16; }", "bits + 17; }"),+ ("bits * g8 - 1 : tw(bits) - 1", "bits * g8 - 2 : tw(bits) - 1"),+ ("t + 4 * bits * g + bits", "t + 3 * bits * g + bits"),+])+def test_k8_oracle_rejects_broken_indexing(tmp_path, old, new):+ source = (QUANT / "exl3_moe_fused_idx.h").read_text()+ assert source.count(old) == 1+ (tmp_path / "exl3_moe_fused_idx.h").write_text(source.replace(old, new))+ result = build_and_run(tmp_path, tmp_path / "mutant")+ assert result.returncode != 0, "corrupted extraction escaped the check"+++def eligibility():+ # Isolate this pure policy helper without importing torch or compiling the HIP extension.+ tree = ast.parse((ROOT / "exllamav3/modules/moe_fused.py").read_text())+ functions = [n for n in tree.body if isinstance(n, ast.FunctionDef)+ and n.name in ("_first_k", "_k6s8_support_reason")]+ assert len(functions) == 2+ state = {"variant": 0x160000, "timing": 0}+ namespace = {"os": os, "MF9": state}+ exec(compile(ast.Module(body=functions, type_ignores=[]), "eligibility", "exec"), namespace)+ def experts(bits, count):+ return SimpleNamespace(**{+ key: [SimpleNamespace(inner=SimpleNamespace(K=bits, mul1=True, mcg=False))+ for _ in range(count)] for key in ("gates", "ups", "downs")+ })+ model = experts(6, 3)+ model.shared_experts = experts(8, 1)+ return namespace["_k6s8_support_reason"], state, model+++def test_disabled_without_explicit_opt_in(eligibility, monkeypatch):+ fn, _, model = eligibility+ monkeypatch.delenv("EXL3_MOE_FUSED_K6S8", raising=False)+ assert "requires EXL3_MOE_FUSED_K6S8=1" in fn(model)+++def test_opt_in_and_unchanged_existing_pack(eligibility, monkeypatch):+ fn, _, model = eligibility+ monkeypatch.setenv("EXL3_MOE_FUSED_K6S8", "1")+ monkeypatch.delenv("EXL3_MOE_FUSED_LAYOUT", raising=False)+ assert fn(model) is None+ model.shared_experts.gates[0].inner.K = 6+ monkeypatch.delenv("EXL3_MOE_FUSED_K6S8")+ assert fn(model) is None++[email protected]("part,projection,index,attribute,value", [+ ("routed", "ups", 2, "K", 5),+ ("routed", "downs", 1, "mul1", False),+ ("shared", "downs", 0, "K", 6),+ ("shared", "ups", 0, "mcg", True),+])+def test_rejects_mixed_projection_formats(eligibility, monkeypatch, part, projection, index, attribute, value):+ fn, _, model = eligibility+ monkeypatch.setenv("EXL3_MOE_FUSED_K6S8", "1")+ monkeypatch.delenv("EXL3_MOE_FUSED_LAYOUT", raising=False)+ module = model if part == "routed" else model.shared_experts+ setattr(getattr(module, projection)[index].inner, attribute, value)+ assert "uniform K6" in fn(model)++[email protected]("break_part", ["routed_inner", "routed_k", "shared_inner", "shared_k", "shared_gates", "shared_missing"])+def test_block_without_k_falls_back(eligibility, monkeypatch, break_part):+ # A block whose projections have no `.inner.K` (for example a non-EXL3 linear) must fall back, not raise.+ fn, _, model = eligibility+ monkeypatch.setenv("EXL3_MOE_FUSED_K6S8", "1")+ monkeypatch.delenv("EXL3_MOE_FUSED_LAYOUT", raising=False)+ assert fn(model) is None+ if break_part == "routed_inner":+ model.gates[0] = SimpleNamespace()+ elif break_part == "routed_k":+ del model.gates[0].inner.K+ elif break_part == "shared_inner":+ model.shared_experts.gates[0] = SimpleNamespace()+ elif break_part == "shared_k":+ del model.shared_experts.gates[0].inner.K+ elif break_part == "shared_gates":+ model.shared_experts = SimpleNamespace()+ else:+ model.shared_experts = None+ assert fn(model) is None+++def test_missing_attribute_in_a_later_projection_is_a_mismatch_not_an_error(eligibility, monkeypatch):+ fn, _, model = eligibility+ monkeypatch.setenv("EXL3_MOE_FUSED_K6S8", "1")+ monkeypatch.delenv("EXL3_MOE_FUSED_LAYOUT", raising=False)+ del model.downs[1].inner.mul1+ assert "uniform K6" in fn(model)+ model.downs[1].inner.mul1 = True+ model.shared_experts.ups[0] = SimpleNamespace()+ assert "uniform K6" in fn(model)+++def test_rejects_repack_and_nondefault_launches(eligibility, monkeypatch):+ fn, state, model = eligibility+ monkeypatch.setenv("EXL3_MOE_FUSED_K6S8", "1")+ monkeypatch.setenv("EXL3_MOE_FUSED_LAYOUT", "repack")+ assert "native layout" in fn(model)+ monkeypatch.delenv("EXL3_MOE_FUSED_LAYOUT")+ for variant in (0, 0x60000, 0xe0000, 0x160100):+ state["variant"] = variant+ assert "six-stage" in fn(model)+ state.update(variant=0x160000, timing=1)+ assert "without timing" in fn(model)+++def test_k8_decoder_is_wired_into_both_tile_paths():+ source = (QUANT / "exl3_moe_fused.cuh").read_text()+ body = source.split("void mf_dq8_k8(", 1)[1].split("\n}", 1)[0]+ assert "const uint32_t (&w)[9]" in body+ assert "kn_words(8, w, t, v);" in body+ assert "decode8<2>(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], f0, f1);" in body+ for name in ("exl3_moe_fused.cuh", "exl3_moe_fused7_mv.cuh"):+ text = (QUANT / name).read_text()+ assert "BITS == 8) mf_dq8_k8(wa[u], t, f0[t], f1[t]);" in text+ assert "w[5] = v1.x; w[6] = v1.y; w[7] = v1.z; w[8] = v1.w;" in textdiff --git a/tools/qwen/K6K8.md b/tools/qwen/K6K8.mdnew file mode 100644index 0000000..878408f--- /dev/null+++ b/tools/qwen/K6K8.md@@ -0,0 +1,163 @@+# Experimental K6/K8 fused MoE++This path supports Qwen routed experts with K6 weights and shared experts+with K8 weights. All projections must use the mul1 codebook.+The default remains disabled. Rebuild the extension before use.++Set these variables before you start the server:++```sh+export EXL3_MOE_FUSED=1+export EXL3_MOE_FUSED_LAYOUT=native+export EXL3_MOE_FUSED9=1441792+export EXL3_MOE_FUSED_K6S8=1+```++Only the native six-stage variant is supported. Timing and other variants+are excluded. Without this setting, the existing fallback remains in use.+No model conversion is required.++## Checks++Run the CPU checks from the repository root:++```sh+python -m pytest --noconftest -q tests/test_moe_fused_k8_cpu.py tests/test_moe_fused_k6_cpu.py tests/test_moe_k56_cpu.py+```++On an idle ROCm GPU, run the real-weight check with the model directory:++```sh+python tools/qwen/check_k6k8_layers.py --model "$MODEL_DIR"+```++The GPU check loads one block at a time. It does not stop services.+It checks buffer bounds, finite outputs, repeatability, batch shape,+and error against the unfused path. Exit code 2 reports a relative update RMS+error above `--max-rel-error` (default 1e-3; `0` requires bit-exact outputs).+Differences below the limit are counted and reported, not hidden.+It does not establish full-model quality or long-context correctness.++## Earlier hardware results++The prototype was tested on an EVO-X2 with 128 GB RAM and gfx1151.+The local Qwen3.8 Flash-Next EXL3 pack was labelled 6.05 bpw.+These results used base commit 7844feb. They are not a GPU test of the+rebased PR. Each comparison used the same experimental binary and changed+EXL3_MOE_FUSED_K6S8 from 0 to 1. Context was 262144, cache was 16-bit,+sessions was 2, and ndt was 3. The ngram table used disk streaming.++| Prompt | Before (tokens/s) | After (tokens/s) |+| --- | ---: | ---: |+| Explanation | 16.08 | 18.45 |+| Code | 21.71 | 25.67 |+| Story | 13.95 | 16.29 |++These are medians from two repetitions. Paired-request wall time changed+from 16.80 s to 15.79 s. These are small-sample observations.++All 64 real-weight half-layer comparisons had numerical differences.+Relative update RMS error ranged from 0.0149% to 0.0347%.+Bounds, finite-output, repeatability, and batch-shape checks passed.+The 128-token output checks matched. A 256-token code response differed+at token 204 in both repetitions. Its AST matched, but its text did not.+The largest shared top-10 probability change was 6.411 percentage points.++## Numerical acceptance++Where the half-layer difference comes from. Blocks: main layers 0, 24, 47 and+the MTP layer of the 6.05 bpw pack (K6 routed, K8 shared), rows 1 to 4, two+seeds. The mixed inputs and the expert selection were identical in every case.+Only the shared expert or only the routed experts were left active:++| Active experts | Fused vs unfused, relative update RMS (min / median / max) |+| --- | --- |+| Routed only (K6) | 1.4e-4 / 2.0e-4 / 2.9e-4 |+| Shared only (K8) | 2.1e-4 / 3.0e-4 / 4.1e-4 |+| Both | 1.9e-4 / 2.3e-4 / 2.9e-4 |++The same comparison on a K4 routed / K4 shared pack is bit-exact in 24 of 24+cases. The K6 routed / K6 shared MTP layer of that pack, which already ships+on the existing fused path, differs by 1.6e-4 to 2.4e-4, and the difference+comes from its routed experts. So a K6 routed difference of this size is+already present in the merged code. K8 adds a somewhat larger one.++Neither path is closer to exact arithmetic. Against an fp64 evaluation of+the same quantized weights, both the fused and the unfused path sit at about+7e-4 of the output RMS (the two are within 3% of each other). The distance+between them (2.4e-4 of the output RMS) is about three times smaller than the+distance of either one to the exact result.++Why the K8 shared expert differs. The unfused K8 shared expert reconstructs an+fp16 weight and runs a half-precision GEMM. K4 and K6 shared experts run through+a direct decode GEMV, and the fused tile matches that GEMV bit for bit. The fused+tile decodes and accumulates in fp32. Measured against fp64, the K8 gate and up tile output+is correctly rounded to fp16 (error equal to the rounding floor, ratio 1.00,+for K4, K6 and K8). The unfused K8 reconstruct route is 2.1 to 2.3 times the+floor. The down projection (fp32 output) is about 7 times the+rounding floor for every K, K4 included, so it is not specific to K8. We found no indexing or decode error in the K6 or K8 tile.++## Served comparison on this revision++Full model, 6.05 bpw K6 routed / K8 shared pack, gfx1151, context 65536,+greedy, thinking off. Unfused is the default; fused sets+`EXL3_MOE_FUSED=1 EXL3_MOE_FUSED_LAYOUT=native EXL3_MOE_FUSED9=1441792 EXL3_MOE_FUSED_K6S8=1`.+32 prompts of 256 tokens, top-10 log-probabilities compared at every position+whose context is identical in both runs (5407 positions):++| Quantity | Fused vs unfused |+| --- | ---: |+| Prompts whose greedy text diverges | 19 of 32 |+| Largest change of a top-10 probability | 6.96 points |+| Mean top-10 total variation | 0.0031 |+| RMS change of the log-probability of the chosen token | 0.012 |+| Mean change of that log-probability (bias) | -0.0004 |++The unfused server is deterministic: two unfused runs that differ only in the+draft policy are bit-identical (1849 positions, largest change 0.000 points),+so every difference above comes from the fused kernels. The size of the+effect is what a rounding-level change does to this model, not a sign of a+wrong kernel: a separate change that only touches the dense attention+projections (direct K8 decode instead of reconstruct plus half-precision GEMM,+relative error 5e-4 per projection) gives 17 of 32 diverging prompts, 9.58 points,+RMS 0.013 and bias -0.0004 on the same prompts. Divergence of the greedy text+is expected whenever two top tokens are close, so a diverging text is not a+quality measure by itself.++Speed, same prompts and runs, medians of nine runs (three arms of three runs, ranges in brackets):++| Context | Unfused (tokens/s) | Fused (tokens/s) | Prefill, fused / unfused |+| --- | ---: | ---: | ---: |+| 4K | 14.6 [12.9 to 15.4] | 16.4 [14.9 to 17.5] (+12%) | 0.98 |+| 32K | 15.1 [10.4 to 17.6] | 16.6 [0.6 to 17.8] (+10%) | 0.99 |++The host had under 6 GiB of free memory during these runs, which explains+the wide ranges (one 32K fused run stalled at 0.6 tokens/s).++## Build size and registers++Measured on gfx1151 with the build script of `tools/strix_halo/rebuild.sh`+(three parallel jobs): the extension grows from 134.66 MB to 136.20 MB+(+1.54 MB, +1.1%) with this change. A full build took 469 s here against 490 s+for the base; the machine was not idle, so treat build times as equal within noise.+Compiled alone with the same flags, `exl3_moe_fused` takes 46 s instead of 41 s+and its object grows from 3.30 MB to 3.76 MB.++Registers and spills (hipcc `-Rpass-analysis=kernel-resource-usage`) of the new+K6S8 kernels. The six stage kernels are the ones that run in the native layout:++| Kernel | VGPRs | Spilled VGPRs | Waves/SIMD |+| --- | ---: | ---: | ---: |+| `moe_fused_kernel<QwenK6S8>` | 220 | 0 | 6 |+| `moe_fused9s_kernel<QwenK6S8>`, stages 0 to 5 | 179, 180, 139, 190, 178, 29 | 0 | 8 |+| `moe_fused9_kernel<QwenK6S8>` | 234 | 0 | 6 |+| `moe_fused9o_kernel<QwenK6S8>` | 192 | 32 | 8 |+| `moe_fused_kernel<SmallK6S8>` | 160 | 0 | 9 |+| `moe_fused9s_kernel<SmallK6S8>`, stages 0 to 5 | 94, 150, 34, 132, 123, 29 | 0 | 9 to 16 |++Only the `o` variant spills (32 registers, 84 bytes per lane). Kernels that+existed before did not change their register or spill counts.++The check script now accepts the numbers above and keeps exit code 2 for larger errors.+The numerical differences of the fused path are at rounding level (see above).+Use tools/bench.sh with the same machine and command for each comparison.diff --git a/tools/qwen/check_k6k8_layers.py b/tools/qwen/check_k6k8_layers.pynew file mode 100644index 0000000..c98fc15--- /dev/null+++ b/tools/qwen/check_k6k8_layers.py@@ -0,0 +1,167 @@+#!/usr/bin/env python3+"""Compare experimental K6/K8 MoE half-layers with the unfused implementation.++Run from the patched checkout, with production stopped. Loads only one block+at a time. No model files, service configuration, or repository files are edited.+Synthetic residual inputs exercise real weights, not full-model activations.+Any numerical difference is reported for review, not silently accepted.+"""+import argparse+import gc+import importlib.util+import json+import os+from pathlib import Path+import sys+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--model", required=True)+ parser.add_argument("--max-rel-error", type=float, default=1e-3,+ help="largest accepted relative update RMS error against the unfused path (default 1e-3; "+ "0 requires bit-exact outputs)")+ args = parser.parse_args()+ root = Path.cwd().resolve()+ assert (root / "tools/qwen/serve.py").is_file(), "Run from the experimental checkout"+ sys.path.insert(0, str(root))+ spec = importlib.util.find_spec("exllamav3_ext")+ assert spec and Path(spec.origin).resolve().parent == root, "Wrong extension path"+ print("Extension:", spec.origin, flush=True)++ # Apply the same defaults and sidecar selection as production before engine imports.+ from tools.qwen.serve import SERVE_ENV, configure_hc_sidecar+ for key, value in SERVE_ENV:+ os.environ.setdefault(key, value)+ os.environ["EXL3_MOE_FUSED_K6S8"] = "1"+ os.environ["EXL3_MOE_FUSED"] = "1"+ os.environ["EXL3_MOE_FUSED_LAYOUT"] = "native"+ os.environ["EXL3_MOE_FUSED9"] = "1441792"+ os.environ["EXL3_VERIFY_ROW_SPLIT"] = "2"+ print(configure_hc_sidecar(args.model), flush=True)++ import torch+ import exllamav3+ from exllamav3 import Config, Model+ from exllamav3.modules.moe_fused import FusedMoEHalf+ assert Path(exllamav3.__file__).resolve().parent == root / "exllamav3"+ assert torch.version.hip and hasattr(torch.ops.mf9, "half")+ torch.set_num_threads(4)+ torch.set_grad_enabled(False)+ dev = torch.device("cuda:0")+ print("GPU:", torch.cuda.get_device_name(dev), flush=True)+ cfg = Config.from_directory(args.model)+ models = [Model.from_config(cfg), Model.from_config(cfg, component="mtp")]+ selected = []+ for model in models:+ blocks = [m for m in model.modules if getattr(m, "mlp_hc", None) is not None]+ assert blocks, f"No MoE blocks in {model.component}"+ indices = sorted({0, len(blocks) // 2, len(blocks) - 1})+ selected.extend(blocks[i] for i in indices)++ calls = [0]+ original_call = FusedMoEHalf.__call__++ def counted_call(self, x):+ calls[0] += 1+ return original_call(self, x)++ FusedMoEHalf.__call__ = counted_call+ comparisons = differences = 0+ worst = 0.0+ try:+ for block in selected:+ print("Loading block:", block.key, flush=True)+ block.load(dev)+ try:+ assert block.ablit is None, "Runtime projection needs a separate compatibility check"+ assert block.mlp_resid_scalar is None+ reason = FusedMoEHalf.why_not(block)+ assert reason is None, reason+ plan = FusedMoEHalf(block)+ assert plan.supported and plan.native and (plan.RB, plan.SB) == (6, 8)+ block._moe_fused = plan+ block._moe_fused_tried = True+ # Guard the workspace without changing its contents or alignment.+ size = plan.ws.numel()+ workspace = torch.full((size + 4096,), 171, dtype=torch.uint8, device=dev)+ workspace[:size].copy_(plan.ws)+ plan.ws = workspace[:size]+ print("Shape:", plan.shape, "extra_bytes:", plan.extra_bytes, flush=True)++ def run(x, fused):+ block._moe_fused_on = fused+ storage = torch.full((x.numel() + 128,), 12345.0, dtype=torch.float32, device=dev)+ view = storage[64:-64].view_as(x)+ view.copy_(x)+ before = calls[0]+ if fused:+ assert plan.applicable(view, {})+ out = block._forward_mlp(view, None, {"attn_mode": "flash_attn", "dflash_verify": True})+ torch.cuda.synchronize()+ assert (calls[0] > before) == fused, "Unexpected fused/fallback dispatch"+ assert bool(torch.isfinite(out).all()), "Nonfinite output"+ assert bool((storage[:64] == 12345).all()) and bool((storage[-64:] == 12345).all()), "Residual guard overwritten"+ assert bool((workspace[size:] == 171).all()), "Workspace guard overwritten"+ assert plan.ctl().tolist() == [0, 0, 0], "Kernel control error"+ return out.clone()++ for seed in (1234, 5678):+ generator = torch.Generator(device=dev).manual_seed(seed)+ base = torch.randn((1, 8, plan.H, plan.D), generator=generator, device=dev)+ # Include correlated streams, larger activations, and identical rows.+ base = base + base[:, :, :1, :]+ if seed == 5678:+ base *= 8+ base[:, 1::2] = base[:, ::2].clone()+ for rows in range(1, 9):+ x = base[:, :rows].contiguous()+ ref = run(x, False)+ got = run(x, True)+ repeat = run(x, True)+ assert torch.equal(got, repeat), "Repeated fused calls differ"+ # Two-session shape must preserve the same per-row computation.+ if rows % 2 == 0:+ batched = run(x.view(2, rows // 2, plan.H, plan.D), True).view_as(x)+ assert torch.equal(got, batched), "Batch reshape changes fused result"+ error = (got.double() - ref.double())+ update = ref.double() - x.double()+ rms = lambda t: t.square().mean().sqrt().item()+ exact = torch.equal(got, ref)+ comparisons += 1+ differences += not exact+ relative = rms(error) / max(rms(update), 1e-30)+ worst = max(worst, relative)+ print(json.dumps({+ "block": block.key, "seed": seed, "rows": rows,+ "exact": exact, "max_abs_error": error.abs().max().item(),+ "error_rms": rms(error), "reference_update_rms": rms(update),+ "relative_update_rms_error": relative,+ }), flush=True)+ print("Block checks complete:", block.key, flush=True)+ del run, plan, workspace, x, ref, got, repeat, base+ finally:+ block._moe_fused = None+ block._moe_fused_tried = False+ block.unload()+ gc.collect()+ torch.cuda.empty_cache()+ finally:+ FusedMoEHalf.__call__ = original_call+ print(f"Comparisons: {comparisons}; non-exact: {differences}; worst relative update RMS error: {worst:.3e}", flush=True)+ print("PASS: guards, finite outputs, repeatability, and batch reshape checks.", flush=True)+ if worst > args.max_rel_error or (args.max_rel_error == 0 and differences):+ print(f"REVIEW REQUIRED: worst relative error {worst:.3e} exceeds --max-rel-error {args.max_rel_error:g}; "+ "do not enable in production yet.", flush=True)+ return 2+ if differences:+ print(f"PASS: {differences} of {comparisons} outputs differ from the unfused path at rounding level "+ f"(worst {worst:.3e} <= {args.max_rel_error:g}); see tools/qwen/K6K8.md, Numerical acceptance.", flush=True)+ else:+ print("PASS: all tested half-layer outputs exactly match the unfused path.", flush=True)+ print("Full-model and performance checks are still required.", flush=True)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())