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
Hy4 decode: HY4_GM_FFN decode FFN on the shared gm_ext ops (gm_route, one Q8_0 launch for rdown + shared gate/up, gm_moe_kq_decode, rup + shared swiglu-down in one buffer), gm_ext v4 sources
YanissAmza2c3fc5d4f8b
diff --git a/exllamav3/gm_ext/gm_bindings.cpp b/exllamav3/gm_ext/gm_bindings.cppindex 7459231..4abd50e 100644--- a/exllamav3/gm_ext/gm_bindings.cpp+++ b/exllamav3/gm_ext/gm_bindings.cpp@@ -6,7 +6,11 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m){m.def("gm_routing_std_bsz1", &gm_routing_std_bsz1, "gm_routing_std_bsz1");m.def("gm_qkv_decode", &gm_qkv_decode, "gm_qkv_decode");- m.def("gm_moe_kq_decode", &gm_moe_kq_decode, "gm_moe_kq_decode");+ m.def("gm_moe_kq_decode", &gm_moe_kq_decode, "gm_moe_kq_decode", 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("fmt_d"), py::arg("act"), py::arg("qb"),+ py::arg("partial"), py::arg("out"), py::arg("resid"), py::arg("fmt_gu") = 0, py::arg("lim") = 0.0, py::arg("meta") = at::Tensor());+ m.def("gm_q8_swiglu_down", &gm_q8_swiglu_down, "gm_q8_swiglu_down");+ m.def("gm_route", &gm_route, "gm_route");m.def("gm_pf_gate_up", &gm_pf_gate_up, "gm_pf_gate_up");m.def("gm_pf_down", &gm_pf_down, "gm_pf_down");}diff --git a/exllamav3/gm_ext/gm_kq_item.cuh b/exllamav3/gm_ext/gm_kq_item.cuhindex 689817f..3725597 100644--- a/exllamav3/gm_ext/gm_kq_item.cuh+++ b/exllamav3/gm_ext/gm_kq_item.cuh@@ -106,4 +106,83 @@ __device__ __forceinline__ void fq_kq_item_q6_k(const uint8_t* __restrict__ wr,}}+// ---- Q3_K and Q8_0 lane dots (verbatim fq_dot_q3_k_q8 / fq_dot_q8_0_q8 of fq_gemv_hip.cuh: lane tid of nthreads sums sub-chunks c = tid, tid + nthreads, ...) ----+#ifndef FQ_Q3_K_BYTES+#define FQ_Q3_K_BYTES 110+#endif+#ifndef FQ_Q8_0_BYTES+#define FQ_Q8_0_BYTES 34+#endif++__device__ __forceinline__ float gm_dot_q3_k(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aqb, int K, int tid, int nthreads)+{+ const int nsub = K / 16;+ float acc = 0.0f;+ for (int c = tid; c < nsub; c += nthreads)+ {+ const int b = c >> 4;+ const int iqs = c & 15;+ const uint8_t* blk = wr + (size_t)b * FQ_Q3_K_BYTES;+ const int bq8_offset = 4 * (iqs / 8);+ const int scale_offset = iqs - iqs % 8 + (iqs % 8) / 4;+ int32_t vl, vm;+ memcpy(&vl, blk + 32 + 4 * iqs, 4);+ memcpy(&vm, blk + 4 * (iqs % 8), 4);+ const int32_t vh = ~vm >> bq8_offset;+ const uint8_t* scales = blk + 96;+ __half dh;+ memcpy(&dh, blk + 108, 2);+ const float d = __half2float(dh);+ float sumf = 0.0f;+ #pragma unroll+ for (int i = 0; i < 4; i++)+ {+ const int isc = scale_offset + 2 * i;+ const int sc_low = (scales[isc % 8] >> (4 * (isc / 8))) & 0xF;+ const int sc_high = ((scales[8 + isc % 4] >> (2 * (isc / 4))) & 3) << 4;+ const int sc = (sc_low | sc_high) - 32;+ const uint32_t vil = ((uint32_t)vl >> (2 * i)) & 0x03030303u;+ const uint32_t vih = (uint32_t)((vh >> i) << 2) & 0x04040404u;+ const uint32_t vi = fq_vsub4(vil, vih);+ const uint8_t* aqb_blk = aqb + (size_t)(b * 8 + bq8_offset + i) * FQ_Q8_1_BYTES;+ __half dah;+ memcpy(&dah, aqb_blk, 2);+ const float d8 = __half2float(dah);+ int32_t u;+ memcpy(&u, aqb_blk + 4 + 4 * (iqs % 8), 4);+ sumf = __fadd_rn(sumf, __fmul_rn(d8, (float)(fq_dp4a((int32_t)vi, u, 0) * sc)));+ }+ acc = __fadd_rn(acc, __fmul_rn(d, sumf));+ }+ return acc;+}++__device__ __forceinline__ float gm_dot_q8_0(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aqb, int K, int tid, int nthreads)+{+ const int nchunks = K / 32;+ float acc = 0.0f;+ for (int c = tid; c < nchunks; c += nthreads)+ {+ const uint8_t* blk = wr + (size_t)c * FQ_Q8_0_BYTES;+ __half dwh;+ memcpy(&dwh, blk, 2);+ const float dw = __half2float(dwh);+ __half dah;+ memcpy(&dah, aqb + (size_t)c * FQ_Q8_1_BYTES, 2);+ const float da = __half2float(dah);+ const int8_t* aq = reinterpret_cast<const int8_t*>(aqb + (size_t)c * FQ_Q8_1_BYTES + 4);+ const uint16_t* w16 = reinterpret_cast<const uint16_t*>(blk + 2);+ const int32_t* aq32 = reinterpret_cast<const int32_t*>(aq);+ int sumi = 0;+ #pragma unroll+ for (int j2 = 0; j2 < 8; j2++)+ {+ const int32_t w4 = (int32_t)(w16[j2 * 2] | ((uint32_t)w16[j2 * 2 + 1] << 16));+ sumi = fq_dp4a(w4, aq32[j2], sumi);+ }+ acc = __fadd_rn(acc, __fmul_rn(__fmul_rn(dw, da), (float)sumi));+ }+ return acc;+}+} // namespacediff --git a/exllamav3/gm_ext/gm_moe.cu b/exllamav3/gm_ext/gm_moe.cuindex c501fea..bfed6e7 100644--- a/exllamav3/gm_ext/gm_moe.cu+++ b/exllamav3/gm_ext/gm_moe.cu@@ -19,6 +19,8 @@#define FQ_Q8_1_BYTES 36#define FQ_Q4_K_BYTES 144#define FQ_Q6_K_BYTES 210+#define FQ_Q3_K_BYTES 110+#define FQ_Q8_0_BYTES 34__device__ __forceinline__ int fq_dp4a(int a, int b, int c){@@ -81,108 +83,241 @@ __global__ void gm_quant_rows_kernel(const __half* __restrict__ x, uint8_t* __reif (b < nb32) gm_quant_block(x + (int64_t)b * 32, qb + (int64_t)b * FQ_Q8_1_BYTES);}-// Gate + up (Q4_K), one slot per (blockIdx / ntiles) and 32 rows per block: fq_moe_kq_upgate_v2_kernel without the shared-expert slot and+// fp32 activations (the Hy4 latent / shared paths): the arithmetic of fq_quant_q8_1_kernel<float> (same d, round-half-away, sum in index order).+__device__ __forceinline__ void gm_quant_block_f(const float* __restrict__ x, uint8_t* __restrict__ dst)+{+ float v[32];+ float amax = 0.0f;+ #pragma unroll+ for (int i = 0; i < 32; i++) { v[i] = x[i]; amax = fmaxf(amax, fabsf(v[i])); }+ const float d = amax / 127.0f;+ float sum = 0.0f;+ #pragma unroll+ for (int i = 0; i < 32; i++)+ {+ int q = (amax == 0.0f) ? 0 : (int)roundf(v[i] / d);+ q = q < -127 ? -127 : (q > 127 ? 127 : q);+ dst[4 + i] = (uint8_t)(int8_t)q;+ sum += v[i];+ }+ const __half dh = __float2half_rn(d);+ const __half sh = __float2half_rn(sum);+ uint16_t dhb, shb;+ memcpy(&dhb, &dh, 2);+ memcpy(&shb, &sh, 2);+ reinterpret_cast<uint16_t*>(dst)[0] = dhb;+ reinterpret_cast<uint16_t*>(dst)[1] = shb;+}++__global__ void gm_quant_rows_f_kernel(const float* __restrict__ x, uint8_t* __restrict__ qb, int nb32)+{+ const int b = blockIdx.x * blockDim.x + threadIdx.x;+ if (b < nb32) gm_quant_block_f(x + (int64_t)b * 32, qb + (int64_t)b * FQ_Q8_1_BYTES);+}++// SwiGLU epilogue shared by the gate/up kernels: g / u rounded to half (Linear out_dtype), optional routed clamp (lim > 0: g <= lim, u in [-lim, lim]),+// silu in float, product back to half.+__device__ __forceinline__ __half gm_swiglu_act(float sg, float su, float lim)+{+ float gh = __half2float(__float2half_rn(sg));+ float uh = __half2float(__float2half_rn(su));+ if (lim > 0.0f) { gh = fminf(gh, lim); uh = fminf(fmaxf(uh, -lim), lim); }+ const float sig = 1.0f / (1.0f + expf(-gh));+ return __float2half_rn(sig * gh * uh);+}++// Expert-major groups (R >= 2): meta[u * GM_GRP] = number of slots of the u-th distinct expert, then those slot ids. Block group u loads the weight rows of its expert+// once per tile and runs every slot of the group on them (the weights stay in L1 / L2 for the repeated slots); without meta each slot is its own group.+constexpr int GM_GRP = 9;++__global__ void gm_meta_kernel(const int64_t* __restrict__ sel, int* __restrict__ meta, int SR, int E)+{+ __shared__ int ex[128];+ __shared__ int lead[128];+ const int s = threadIdx.x;+ if (s < SR)+ {+ int64_t e = sel[s];+ ex[s] = (int)((e < 0 || e >= E) ? 0 : e);+ meta[s * GM_GRP] = 0;+ }+ __syncthreads();+ int first = 0;+ if (s < SR)+ {+ first = 1;+ for (int p = 0; p < s; p++) if (ex[p] == ex[s]) first = 0;+ lead[s] = first;+ }+ __syncthreads();+ if (s < SR && first)+ {+ int rank = 0;+ for (int p = 0; p < s; p++) rank += lead[p];+ int cnt = 0;+ for (int p = s; p < SR; p++)+ if (ex[p] == ex[s] && cnt < GM_GRP - 1) meta[rank * GM_GRP + 1 + cnt++] = p;+ meta[rank * GM_GRP] = cnt;+ }+}++// Gate + up (Q4_K), one slot group per (blockIdx / ntiles) and 32 rows per block: fq_moe_kq_upgate_v2_kernel without the shared-expert slot and// without the unaligned fallback (the host checks the alignment of every expert).-__global__ void __launch_bounds__(256) gm_upgate_q4k_kernel(const uint8_t* __restrict__ aqb, const int64_t* __restrict__ sel,+__global__ void __launch_bounds__(256) gm_upgate_q4k_kernel(const uint8_t* __restrict__ aqb, const int64_t* __restrict__ sel, const int* __restrict__ meta,const uint8_t* const* __restrict__ gate_bases,const uint8_t* const* __restrict__ up_bases,int64_t gate_stride, int64_t up_stride,- __half* __restrict__ act, int I, int K, int E, int ntiles, int S_row, int qrow_bytes)+ __half* __restrict__ act, int I, int K, int E, int ntiles, int S_row, int qrow_bytes, float lim){__shared__ float pg[GM_ROWS * GM_PS];__shared__ float pu[GM_ROWS * GM_PS];- const int s = blockIdx.x / ntiles;+ const int u = blockIdx.x / ntiles;const int t = blockIdx.x % ntiles;+ const int ns = meta ? meta[u * GM_GRP] : 1;+ if (ns == 0) return;const int r = threadIdx.x >> 3, j = threadIdx.x & 7;- int64_t e = sel[s];- e = (e < 0 || e >= E) ? 0 : e;- const uint8_t* aq = aqb + (int64_t)(s / S_row) * qrow_bytes; // the q8_1 row of this slot's token (R rows, S_row slots each)const int n = t * GM_ROWS + r;- float ag[4] = {0.0f, 0.0f, 0.0f, 0.0f}, au[4] = {0.0f, 0.0f, 0.0f, 0.0f};- if (n < I)+ int64_t e = sel[meta ? meta[u * GM_GRP + 1] : u];+ e = (e < 0 || e >= E) ? 0 : e;+ for (int m = 0; m < ns; m++){- const uint8_t* gr = gate_bases[e] + (int64_t)n * gate_stride;- const uint8_t* ur = up_bases[e] + (int64_t)n * up_stride;- const int nitems = (K / 256) * 4;- for (int it = j; it < nitems; it += 8)+ const int s = meta ? meta[u * GM_GRP + 1 + m] : u;+ const uint8_t* aq = aqb + (int64_t)(s / S_row) * qrow_bytes; // the q8_1 row of this slot's token (R rows, S_row slots each)+ float ag[4] = {0.0f, 0.0f, 0.0f, 0.0f}, au[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ if (n < I){- float tg[4], tu[4];- fq_kq_item_q4_k(gr, aq, it, tg);- fq_kq_item_q4_k(ur, aq, it, tu);+ const uint8_t* gr = gate_bases[e] + (int64_t)n * gate_stride;+ const uint8_t* ur = up_bases[e] + (int64_t)n * up_stride;+ const int nitems = (K / 256) * 4;+ for (int it = j; it < nitems; it += 8)+ {+ float tg[4], tu[4];+ fq_kq_item_q4_k(gr, aq, it, tg);+ fq_kq_item_q4_k(ur, aq, it, tu);+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ ag[q] = __fadd_rn(ag[q], tg[q]);+ au[q] = __fadd_rn(au[q], tu[q]);+ }+ }+ }+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ pg[r * GM_PS + 4 * j + q] = ag[q];+ pu[r * GM_PS + 4 * j + q] = au[q];+ }+ __syncthreads();+ if (n < I && j == 0)+ {+ float sg = 0.0f, su = 0.0f;#pragma unroll- for (int q = 0; q < 4; q++)+ for (int l = 0; l < 32; l++){- ag[q] = __fadd_rn(ag[q], tg[q]);- au[q] = __fadd_rn(au[q], tu[q]);+ sg = __fadd_rn(sg, pg[r * GM_PS + l]);+ su = __fadd_rn(su, pu[r * GM_PS + l]);}+ act[(int64_t)s * I + n] = gm_swiglu_act(sg, su, lim);}+ __syncthreads();}- #pragma unroll- for (int q = 0; q < 4; q++)- {- pg[r * GM_PS + 4 * j + q] = ag[q];- pu[r * GM_PS + 4 * j + q] = au[q];- }- __syncthreads();- if (n < I && j == 0)+}++// Gate + up (Q3_K): the v1 lane layout of fq_moe_kq_upgate_kernel<8> (32 lane partials per row, summed in lane order), 8 rows per 256-thread block.+__global__ void __launch_bounds__(256) gm_upgate_q3k_kernel(const uint8_t* __restrict__ aqb, const int64_t* __restrict__ sel, const int* __restrict__ meta,+ const uint8_t* const* __restrict__ gate_bases,+ const uint8_t* const* __restrict__ up_bases,+ int64_t gate_stride, int64_t up_stride,+ __half* __restrict__ act, int I, int K, int E, int ntiles, int S_row, int qrow_bytes, float lim)+{+ __shared__ float red[256 * 2];+ const int u = blockIdx.x / ntiles;+ const int t = blockIdx.x % ntiles;+ const int ns = meta ? meta[u * GM_GRP] : 1;+ if (ns == 0) return;+ const int r = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int n = t * 8 + r;+ int64_t e = sel[meta ? meta[u * GM_GRP + 1] : u];+ e = (e < 0 || e >= E) ? 0 : e;+ for (int m = 0; m < ns; m++){- float sg = 0.0f, su = 0.0f;- #pragma unroll- for (int l = 0; l < 32; l++)+ const int s = meta ? meta[u * GM_GRP + 1 + m] : u;+ const uint8_t* aq = aqb + (int64_t)(s / S_row) * qrow_bytes;+ float g = 0.0f, uu = 0.0f;+ if (n < I)+ {+ g = gm_dot_q3_k(gate_bases[e] + (int64_t)n * gate_stride, aq, K, lane, 32);+ uu = gm_dot_q3_k(up_bases[e] + (int64_t)n * up_stride, aq, K, lane, 32);+ }+ red[2 * threadIdx.x] = g;+ red[2 * threadIdx.x + 1] = uu;+ __syncthreads();+ if (n < I && lane == 0){- sg = __fadd_rn(sg, pg[r * GM_PS + l]);- su = __fadd_rn(su, pu[r * GM_PS + l]);+ float sg = 0.0f, su = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++)+ {+ sg = __fadd_rn(sg, red[(r * 32 + l) * 2]);+ su = __fadd_rn(su, red[(r * 32 + l) * 2 + 1]);+ }+ act[(int64_t)s * I + n] = gm_swiglu_act(sg, su, lim);}- const float gh = __half2float(__float2half_rn(sg));- const float uh = __half2float(__float2half_rn(su));- const float sig = 1.0f / (1.0f + expf(-gh));- act[(int64_t)s * I + n] = __float2half_rn(sig * gh * uh);+ __syncthreads();}}// Down (Q4_K = FMT 0, Q6_K = FMT 2): fq_moe_kq_down_v2_kernel with the q8_1 quantization of act[s] done in shared memory first.template <int FMT>-__global__ void __launch_bounds__(256) gm_down_kernel(const __half* __restrict__ act, const int64_t* __restrict__ sel,+__global__ void __launch_bounds__(256) gm_down_kernel(const __half* __restrict__ act, const int64_t* __restrict__ sel, const int* __restrict__ meta,const uint8_t* const* __restrict__ down_bases, int64_t down_stride,float* __restrict__ partial, int I, int K, int E, int ntiles){__shared__ float pp[GM_ROWS * GM_PS];__shared__ __align__(16) uint8_t qa[GM_MAX_NB * FQ_Q8_1_BYTES];- const int s = blockIdx.x / ntiles;+ const int u = blockIdx.x / ntiles;const int t = blockIdx.x % ntiles;+ const int ns = meta ? meta[u * GM_GRP] : 1;+ if (ns == 0) return;const int r = threadIdx.x >> 3, j = threadIdx.x & 7;const int nb = I / 32;- if ((int)threadIdx.x < nb) gm_quant_block(act + (int64_t)s * I + threadIdx.x * 32, qa + threadIdx.x * FQ_Q8_1_BYTES);- int64_t e = sel[s];+ int64_t e = sel[meta ? meta[u * GM_GRP + 1] : u];e = (e < 0 || e >= E) ? 0 : e;const int n = t * GM_ROWS + r;- float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};- __syncthreads();- if (n < K)+ for (int m = 0; m < ns; m++){- const uint8_t* dr = down_bases[e] + (int64_t)n * down_stride;- const int nitems = (I / 256) * ((FMT == 2) ? 8 : 4);- for (int it = j; it < nitems; it += 8)+ const int s = meta ? meta[u * GM_GRP + 1 + m] : u;+ if ((int)threadIdx.x < nb) gm_quant_block(act + (int64_t)s * I + threadIdx.x * 32, qa + threadIdx.x * FQ_Q8_1_BYTES);+ float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ __syncthreads();+ if (n < K){- float tv[4];- if constexpr (FMT == 0) fq_kq_item_q4_k(dr, qa, it, tv);- else fq_kq_item_q6_k(dr, qa, it, tv);- #pragma unroll- for (int q = 0; q < 4; q++)- acc[q] = __fadd_rn(acc[q], tv[q]);+ const uint8_t* dr = down_bases[e] + (int64_t)n * down_stride;+ const int nitems = (I / 256) * ((FMT == 2) ? 8 : 4);+ for (int it = j; it < nitems; it += 8)+ {+ float tv[4];+ if constexpr (FMT == 0) fq_kq_item_q4_k(dr, qa, it, tv);+ else fq_kq_item_q6_k(dr, qa, it, tv);+ #pragma unroll+ for (int q = 0; q < 4; q++)+ acc[q] = __fadd_rn(acc[q], tv[q]);+ }}- }- #pragma unroll- for (int q = 0; q < 4; q++)- pp[r * GM_PS + ((FMT == 2) ? (j + 8 * q) : (4 * j + q))] = acc[q];- __syncthreads();- if (n < K && j == 0)- {- float sp = 0.0f;#pragma unroll- for (int l = 0; l < 32; l++)- sp = __fadd_rn(sp, pp[r * GM_PS + l]);- partial[(int64_t)s * K + n] = sp;+ for (int q = 0; q < 4; q++)+ pp[r * GM_PS + ((FMT == 2) ? (j + 8 * q) : (4 * j + q))] = acc[q];+ __syncthreads();+ if (n < K && j == 0)+ {+ float sp = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++)+ sp = __fadd_rn(sp, pp[r * GM_PS + l]);+ partial[(int64_t)s * K + n] = sp;+ }+ __syncthreads();}}@@ -209,16 +344,18 @@ __global__ void gm_combine_kernel(const float* __restrict__ partial, const __hal} // namespace-// h [1, K] half, sel [S] int64, wts [S] half, expert pointer tables (int64 device addresses), strides in bytes,-// fmt_d 0 = Q4_K / 2 = Q6_K down, act [S, I] half scratch, qb [K/32*36] uint8 scratch, partial [S, K] float scratch,-// out [1, K] float (routed sum), resid [K] float / half or an empty tensor (no residual add).+// h [R, K] half, sel [R*S] int64, wts [R*S] half, expert pointer tables (int64 device addresses), strides in bytes,+// fmt_d 0 = Q4_K / 2 = Q6_K down, fmt_gu 0 = Q4_K / 8 = Q3_K gate/up, act [R*S, I] half scratch, qb [R*K/32*36] uint8 scratch, partial [R*S, K] float scratch,+// out [R, K] float (routed sum), resid [K] float / half or an empty tensor (no residual add), lim = routed swiglu clamp (0 = none: g <= lim, u in [-lim, lim]),+// meta = int32 scratch [>= R*S*9] switches on the expert-major order (R >= 2: every distinct expert's weights are read once per tile for all rows that picked it).void gm_moe_kq_decode(const at::Tensor& h, const at::Tensor& sel, const at::Tensor& wts, const at::Tensor& gate_ptrs,const at::Tensor& up_ptrs, const at::Tensor& down_ptrs, int64_t gate_stride, int64_t up_stride,int64_t down_stride, int64_t fmt_d, at::Tensor& act, at::Tensor& qb, at::Tensor& partial,- at::Tensor& out, const at::Tensor& resid)+ at::Tensor& out, const at::Tensor& resid, int64_t fmt_gu, double lim, const at::Tensor& meta){TORCH_CHECK(h.is_cuda() && h.dtype() == at::kHalf && h.dim() == 2 && h.size(0) >= 1 && h.size(0) <= 8, "gm_moe_kq_decode: h must be [R, K] half on the device, R <= 8");TORCH_CHECK(fmt_d == 0 || fmt_d == 2, "gm_moe_kq_decode: down format must be Q4_K (0) or Q6_K (2)");+ TORCH_CHECK(fmt_gu == 0 || fmt_gu == 8, "gm_moe_kq_decode: gate/up format must be Q4_K (0) or Q3_K (8)");const at::cuda::OptionalCUDAGuard guard(h.device());const int K = (int)h.size(1);const int R = (int)h.size(0);@@ -228,27 +365,43 @@ void gm_moe_kq_decode(const at::Tensor& h, const at::Tensor& sel, const at::Tensconst int E = (int)up_ptrs.numel();const int bb = fmt_d == 2 ? FQ_Q6_K_BYTES : FQ_Q4_K_BYTES;const int I = (int)(down_stride / bb) * 256;- TORCH_CHECK(K % 256 == 0 && I % 256 == 0 && I / 32 <= GM_MAX_NB && S <= 32, "gm_moe_kq_decode: unsupported shape K=", K, " I=", I);- TORCH_CHECK(gate_stride == (int64_t)(K / 256) * FQ_Q4_K_BYTES && up_stride == gate_stride, "gm_moe_kq_decode: gate/up must be Q4_K");+ TORCH_CHECK(K % 256 == 0 && I % 256 == 0 && I / 32 <= GM_MAX_NB && S <= 32 && SR <= 128, "gm_moe_kq_decode: unsupported shape K=", K, " I=", I);+ const int64_t ug_bytes = fmt_gu == 8 ? FQ_Q3_K_BYTES : FQ_Q4_K_BYTES;+ TORCH_CHECK(gate_stride == (int64_t)(K / 256) * ug_bytes && up_stride == gate_stride, "gm_moe_kq_decode: gate/up stride does not match the gate/up format");TORCH_CHECK(act.numel() >= (int64_t)SR * I && qb.numel() >= (int64_t)R * (K / 32) * FQ_Q8_1_BYTES && partial.numel() >= (int64_t)SR * K && out.numel() >= (int64_t)R * K,"gm_moe_kq_decode: scratch too small");+ const bool grouped = R >= 2 && meta.numel() >= (int64_t)SR * GM_GRP;+ TORCH_CHECK(!grouped || meta.dtype() == at::kInt, "gm_moe_kq_decode: meta must be int32");hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();uint8_t* qbp = reinterpret_cast<uint8_t*>(qb.data_ptr());const int nb32 = K / 32;gm_quant_rows_kernel<<<(R * nb32 + 63) / 64, 64, 0, stream>>>(reinterpret_cast<const __half*>(h.data_ptr()), qbp, R * nb32);- const int ntu = (I + GM_ROWS - 1) / GM_ROWS, ntd = (K + GM_ROWS - 1) / GM_ROWS;+ const int64_t* selp = reinterpret_cast<const int64_t*>(sel.data_ptr());+ const int* metap = nullptr;+ if (grouped)+ {+ gm_meta_kernel<<<1, 128, 0, stream>>>(selp, reinterpret_cast<int*>(meta.data_ptr()), SR, E);+ metap = reinterpret_cast<const int*>(meta.data_ptr());+ }+ const int ntd = (K + GM_ROWS - 1) / GM_ROWS;__half* actp = reinterpret_cast<__half*>(act.data_ptr());- gm_upgate_q4k_kernel<<<SR * ntu, 256, 0, stream>>>(- qbp, reinterpret_cast<const int64_t*>(sel.data_ptr()),- reinterpret_cast<const uint8_t* const*>(gate_ptrs.data_ptr()), reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr()),- gate_stride, up_stride, actp, I, K, E, ntu, S, nb32 * FQ_Q8_1_BYTES);+ const uint8_t* const* gp = reinterpret_cast<const uint8_t* const*>(gate_ptrs.data_ptr());+ const uint8_t* const* upp = reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr());+ if (fmt_gu == 0)+ {+ const int ntu = (I + GM_ROWS - 1) / GM_ROWS;+ gm_upgate_q4k_kernel<<<SR * ntu, 256, 0, stream>>>(qbp, selp, metap, gp, upp, gate_stride, up_stride, actp, I, K, E, ntu, S, nb32 * FQ_Q8_1_BYTES, (float)lim);+ }+ else+ {+ const int ntu = (I + 7) / 8;+ gm_upgate_q3k_kernel<<<SR * ntu, 256, 0, stream>>>(qbp, selp, metap, gp, upp, gate_stride, up_stride, actp, I, K, E, ntu, S, nb32 * FQ_Q8_1_BYTES, (float)lim);+ }float* partp = reinterpret_cast<float*>(partial.data_ptr());if (fmt_d == 0)- gm_down_kernel<0><<<SR * ntd, 256, 0, stream>>>(actp, reinterpret_cast<const int64_t*>(sel.data_ptr()),- reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()), down_stride, partp, I, K, E, ntd);+ gm_down_kernel<0><<<SR * ntd, 256, 0, stream>>>(actp, selp, metap, reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()), down_stride, partp, I, K, E, ntd);else- gm_down_kernel<2><<<SR * ntd, 256, 0, stream>>>(actp, reinterpret_cast<const int64_t*>(sel.data_ptr()),- reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()), down_stride, partp, I, K, E, ntd);+ gm_down_kernel<2><<<SR * ntd, 256, 0, stream>>>(actp, selp, metap, reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()), down_stride, partp, I, K, E, ntd);const __half* wp = reinterpret_cast<const __half*>(wts.data_ptr());float* outp = reinterpret_cast<float*>(out.data_ptr());const int cb = (K + 255) / 256;@@ -337,22 +490,127 @@ __global__ void __launch_bounds__(64) gm_gemv3_kernel(Gm3 a, const uint8_t* __re}}+// Q8_0 projections, 1..3 matrices of one launch: the arithmetic of fq_gemv_q8_q8_kernel (one block per output row, nt = fq_q8_nt(K) lane partials of+// fq_dot_q8_0_q8, summed in lane order). OUT = __half or float.+struct Gm3q+{+ const uint8_t* w[3];+ void* out[3];+ int N[3];+};++template <typename OUT>+__global__ void gm_gemv_q8_kernel(Gm3q a, const uint8_t* __restrict__ aqb, int K, int nt, int64_t row_bytes)+{+ extern __shared__ float red[];+ const int row = blockIdx.y;+ aqb += (int64_t)row * (K / 32) * FQ_Q8_1_BYTES;+ int blk = blockIdx.x, mi = 0;+ if (blk >= a.N[0]) { blk -= a.N[0]; mi = 1; if (blk >= a.N[1]) { blk -= a.N[1]; mi = 2; } }+ const int tid = threadIdx.x;+ red[tid] = gm_dot_q8_0(a.w[mi] + (int64_t)blk * row_bytes, aqb, K, tid, nt);+ __syncthreads();+ if (tid == 0)+ {+ float sum = 0.0f;+ for (int l = 0; l < nt; l++) sum = __fadd_rn(sum, red[l]);+ OUT* o = reinterpret_cast<OUT*>(a.out[mi]);+ if constexpr (std::is_same<OUT, __half>::value) o[(int64_t)row * a.N[mi] + blk] = __float2half_rn(sum);+ else o[(int64_t)row * a.N[mi] + blk] = sum;+ }+}++__device__ __forceinline__ float gm_to_f(float v) { return v; }+__device__ __forceinline__ float gm_to_f(__half v) { return __half2float(v); }++// SwiGLU of the shared expert fused into its Q8_0 down projection: act = half(silu(g) * u) (g, u half or float [R, I]), quantized to q8_1 in shared memory,+// then the Q8_0 dot of fq_gemv_q8_q8_kernel. accumulate: out += result (fp32 add), else out = result.+template <typename GT>+__global__ void gm_swiglu_down_q8_kernel(const GT* __restrict__ g, const GT* __restrict__ u, const uint8_t* __restrict__ wd, float* __restrict__ out,+ int I, int N, int nt, int64_t row_bytes, int accumulate)+{+ extern __shared__ float red[];+ __shared__ __align__(16) uint8_t qa[GM_MAX_NB * FQ_Q8_1_BYTES];+ const int row = blockIdx.y, n = blockIdx.x, tid = threadIdx.x;+ const int nb = I / 32;+ if (tid < nb)+ {+ __half a32[32];+ #pragma unroll+ for (int i = 0; i < 32; i++)+ {+ const float gv = gm_to_f(g[(int64_t)row * I + tid * 32 + i]);+ const float uv = gm_to_f(u[(int64_t)row * I + tid * 32 + i]);+ const float sig = 1.0f / (1.0f + expf(-gv));+ a32[i] = __float2half_rn(sig * gv * uv);+ }+ gm_quant_block(a32, qa + tid * FQ_Q8_1_BYTES);+ }+ __syncthreads();+ red[tid] = gm_dot_q8_0(wd + (int64_t)n * row_bytes, qa, I, tid, nt);+ __syncthreads();+ if (tid == 0)+ {+ float sum = 0.0f;+ for (int l = 0; l < nt; l++) sum = __fadd_rn(sum, red[l]);+ float* o = out + (int64_t)row * N + n;+ *o = accumulate ? __fadd_rn(*o, sum) : sum;+ }+}+// ws: 2 or 3 packed matrices [N_i, row bytes] uint8 (Q4_K = fmt 0 / Q6_K = fmt 2), out [1, sum N] half, x [1, K] half, qb scratch.void gm_qkv_decode(const at::Tensor& x, const std::vector<at::Tensor>& ws, const std::vector<int64_t>& fmts, at::Tensor& out, at::Tensor& qb){- TORCH_CHECK(x.is_cuda() && x.dtype() == at::kHalf && x.dim() == 2 && x.size(0) >= 1 && x.size(0) <= 8, "gm_qkv_decode: x must be [R, K] half on the device, R <= 8");+ TORCH_CHECK(x.is_cuda() && (x.dtype() == at::kHalf || x.dtype() == at::kFloat) && x.dim() == 2 && x.size(0) >= 1 && x.size(0) <= 8, "gm_qkv_decode: x must be [R, K] half or float on the device, R <= 8");const int R = (int)x.size(0);TORCH_CHECK(ws.size() >= 1 && ws.size() <= 3 && ws.size() == fmts.size(), "gm_qkv_decode: 1..3 matrices");const at::cuda::OptionalCUDAGuard guard(x.device());const int K = (int)x.size(1);- TORCH_CHECK(K % 256 == 0 && qb.numel() >= (int64_t)R * (K / 32) * FQ_Q8_1_BYTES, "gm_qkv_decode: K / scratch");+ const bool q8 = fmts[0] == 3;+ for (auto f : fmts) TORCH_CHECK((f == 3) == q8, "gm_qkv_decode: Q8_0 (3) matrices cannot mix with Q4_K / Q6_K in one launch");+ TORCH_CHECK(K % (q8 ? 32 : 256) == 0 && qb.numel() >= (int64_t)R * (K / 32) * FQ_Q8_1_BYTES, "gm_qkv_decode: K / scratch");+ TORCH_CHECK(!(x.dtype() == at::kFloat) || q8, "gm_qkv_decode: float x only with Q8_0");+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ uint8_t* qbp = reinterpret_cast<uint8_t*>(qb.data_ptr());+ const int nb32 = K / 32;+ auto quant = [&]()+ {+ if (x.dtype() == at::kFloat) { gm_quant_rows_f_kernel<<<(R * nb32 + 63) / 64, 64, 0, stream>>>(x.data_ptr<float>(), qbp, R * nb32); }+ else { gm_quant_rows_kernel<<<(R * nb32 + 63) / 64, 64, 0, stream>>>(reinterpret_cast<const __half*>(x.data_ptr()), qbp, R * nb32); }+ };+ if (q8)+ {+ TORCH_CHECK(out.dtype() == at::kHalf || out.dtype() == at::kFloat, "gm_qkv_decode: out half or float for Q8_0");+ const int64_t rb = (int64_t)nb32 * FQ_Q8_0_BYTES;+ Gm3q a;+ memset(&a, 0, sizeof(a));+ int total = 0;+ const size_t esz = out.dtype() == at::kHalf ? 2 : 4;+ char* o = reinterpret_cast<char*>(out.data_ptr());+ for (size_t i = 0; i < ws.size(); i++)+ {+ TORCH_CHECK(ws[i].dim() == 2 && ws[i].size(1) == rb && ws[i].stride(1) == 1 && ws[i].stride(0) == rb, "gm_qkv_decode: packed Q8_0 matrix shape");+ TORCH_CHECK((reinterpret_cast<uintptr_t>(ws[i].data_ptr()) & 1) == 0, "gm_qkv_decode: unaligned weights");+ a.w[i] = reinterpret_cast<const uint8_t*>(ws[i].data_ptr());+ a.N[i] = (int)ws[i].size(0);+ a.out[i] = o + esz * (int64_t)R * total;+ total += a.N[i];+ }+ TORCH_CHECK(out.numel() >= (int64_t)R * total, "gm_qkv_decode: out too small");+ const int nt = nb32 >= 256 ? 256 : ((nb32 + 31) / 32) * 32;+ quant();+ if (out.dtype() == at::kHalf) { gm_gemv_q8_kernel<__half><<<dim3(total, R), nt, nt * sizeof(float), stream>>>(a, qbp, K, nt, rb); }+ else { gm_gemv_q8_kernel<float><<<dim3(total, R), nt, nt * sizeof(float), stream>>>(a, qbp, K, nt, rb); }+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_qkv_decode: launch failed");+ return;+ }Gm3 a;memset(&a, 0, sizeof(a));int total = 0;__half* o = reinterpret_cast<__half*>(out.data_ptr());for (size_t i = 0; i < ws.size(); i++){- TORCH_CHECK(fmts[i] == 0 || fmts[i] == 2, "gm_qkv_decode: Q4_K (0) or Q6_K (2) only");+ TORCH_CHECK(fmts[i] == 0 || fmts[i] == 2, "gm_qkv_decode: Q4_K (0), Q6_K (2) or Q8_0 (3) only");const int64_t rb = (int64_t)(K / 256) * (fmts[i] == 0 ? FQ_Q4_K_BYTES : FQ_Q6_K_BYTES);TORCH_CHECK(ws[i].dim() == 2 && ws[i].size(1) == rb && ws[i].stride(1) == 1 && ws[i].stride(0) == rb, "gm_qkv_decode: packed matrix shape");const uintptr_t am = fmts[i] == 0 ? 15 : 1;@@ -368,12 +626,37 @@ void gm_qkv_decode(const at::Tensor& x, const std::vector<at::Tensor>& ws, constTORCH_CHECK(out.numel() >= (int64_t)R * total, "gm_qkv_decode: out too small");auto ntf = [](int nsub) { return nsub >= 256 ? 256 : ((nsub + 31) / 32) * 32; };const int nt4 = ntf(K / 16), nt6 = ntf(K / 8);- hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();- uint8_t* qbp = reinterpret_cast<uint8_t*>(qb.data_ptr());- const int nb32 = K / 32;- gm_quant_rows_kernel<<<(R * nb32 + 63) / 64, 64, 0, stream>>>(reinterpret_cast<const __half*>(x.data_ptr()), qbp, R * nb32);+ quant();gm_gemv3_kernel<<<dim3(total, R), 64, 0, stream>>>(a, qbp, K, nt4, nt6);TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_qkv_decode: launch failed");}+// Shared expert down projection with the SwiGLU fused in: g, u [R, I] (half or float, e.g. the two outputs of a Q8_0 gm_qkv_decode), wd packed Q8_0 [N, I/32*34],+// out float [R, N]; accumulate = out += result (add the shared expert onto the routed up-projection output of a previous gm_qkv_decode call).+void gm_q8_swiglu_down(const at::Tensor& g, const at::Tensor& u, const at::Tensor& wd, at::Tensor& out, bool accumulate)+{+ TORCH_CHECK(g.is_cuda() && g.dim() == 2 && g.sizes() == u.sizes() && g.dtype() == u.dtype() && (g.dtype() == at::kHalf || g.dtype() == at::kFloat) && g.is_contiguous() && u.is_contiguous(),+ "gm_q8_swiglu_down: g, u [R, I] contiguous half or float");+ const at::cuda::OptionalCUDAGuard guard(g.device());+ const int R = (int)g.size(0), I = (int)g.size(1), N = (int)wd.size(0);+ const int nb = I / 32;+ const int64_t rb = (int64_t)nb * FQ_Q8_0_BYTES;+ TORCH_CHECK(R <= 8 && I % 32 == 0 && nb <= GM_MAX_NB && wd.dim() == 2 && wd.size(1) == rb && wd.is_contiguous() && (reinterpret_cast<uintptr_t>(wd.data_ptr()) & 1) == 0,+ "gm_q8_swiglu_down: shape / alignment");+ TORCH_CHECK(out.dtype() == at::kFloat && out.numel() >= (int64_t)R * N, "gm_q8_swiglu_down: out float [R, N]");+ const int nt = nb >= 256 ? 256 : ((nb + 31) / 32) * 32;+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ if (g.dtype() == at::kHalf)+ {+ gm_swiglu_down_q8_kernel<__half><<<dim3(N, R), nt, nt * sizeof(float), stream>>>(reinterpret_cast<const __half*>(g.data_ptr()), reinterpret_cast<const __half*>(u.data_ptr()),+ reinterpret_cast<const uint8_t*>(wd.data_ptr()), out.data_ptr<float>(), I, N, nt, rb, accumulate ? 1 : 0);+ }+ else+ {+ gm_swiglu_down_q8_kernel<float><<<dim3(N, R), nt, nt * sizeof(float), stream>>>(g.data_ptr<float>(), u.data_ptr<float>(),+ reinterpret_cast<const uint8_t*>(wd.data_ptr()), out.data_ptr<float>(), I, N, nt, rb, accumulate ? 1 : 0);+ }+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_q8_swiglu_down: launch failed");+}+#endif // USE_ROCMdiff --git a/exllamav3/gm_ext/gm_moe.cuh b/exllamav3/gm_ext/gm_moe.cuhindex df7b277..7a7e496 100644--- a/exllamav3/gm_ext/gm_moe.cuh+++ b/exllamav3/gm_ext/gm_moe.cuh@@ -5,7 +5,8 @@void gm_moe_kq_decode(const at::Tensor& h, const at::Tensor& sel, const at::Tensor& wts, const at::Tensor& gate_ptrs,const at::Tensor& up_ptrs, const at::Tensor& down_ptrs, int64_t gate_stride, int64_t up_stride,int64_t down_stride, int64_t fmt_d, at::Tensor& act, at::Tensor& qb, at::Tensor& partial,- at::Tensor& out, const at::Tensor& resid);+ at::Tensor& out, const at::Tensor& resid, int64_t fmt_gu, double lim, const at::Tensor& meta);+void gm_q8_swiglu_down(const at::Tensor& g, const at::Tensor& u, const at::Tensor& wd, at::Tensor& out, bool accumulate);void gm_qkv_decode(const at::Tensor& x, const std::vector<at::Tensor>& ws, const std::vector<int64_t>& fmts, at::Tensor& out, at::Tensor& qb);void gm_pf_gate_up(const at::Tensor& x, const at::Tensor& gate_ptrs, const at::Tensor& up_ptrs, at::Tensor& H, const at::Tensor& sp, const at::Tensor& be,int64_t P, int64_t topk, int64_t E, double lim, int64_t K, int64_t N, int64_t rowb, int64_t maxb, int64_t fmt);diff --git a/exllamav3/gm_ext/gm_moe.hip b/exllamav3/gm_ext/gm_moe.hipindex 9554d28..66aae6a 100644--- a/exllamav3/gm_ext/gm_moe.hip+++ b/exllamav3/gm_ext/gm_moe.hip@@ -20,6 +20,8 @@#define FQ_Q8_1_BYTES 36#define FQ_Q4_K_BYTES 144#define FQ_Q6_K_BYTES 210+#define FQ_Q3_K_BYTES 110+#define FQ_Q8_0_BYTES 34__device__ __forceinline__ int fq_dp4a(int a, int b, int c){@@ -82,108 +84,241 @@ __global__ void gm_quant_rows_kernel(const __half* __restrict__ x, uint8_t* __reif (b < nb32) gm_quant_block(x + (int64_t)b * 32, qb + (int64_t)b * FQ_Q8_1_BYTES);}-// Gate + up (Q4_K), one slot per (blockIdx / ntiles) and 32 rows per block: fq_moe_kq_upgate_v2_kernel without the shared-expert slot and+// fp32 activations (the Hy4 latent / shared paths): the arithmetic of fq_quant_q8_1_kernel<float> (same d, round-half-away, sum in index order).+__device__ __forceinline__ void gm_quant_block_f(const float* __restrict__ x, uint8_t* __restrict__ dst)+{+ float v[32];+ float amax = 0.0f;+ #pragma unroll+ for (int i = 0; i < 32; i++) { v[i] = x[i]; amax = fmaxf(amax, fabsf(v[i])); }+ const float d = amax / 127.0f;+ float sum = 0.0f;+ #pragma unroll+ for (int i = 0; i < 32; i++)+ {+ int q = (amax == 0.0f) ? 0 : (int)roundf(v[i] / d);+ q = q < -127 ? -127 : (q > 127 ? 127 : q);+ dst[4 + i] = (uint8_t)(int8_t)q;+ sum += v[i];+ }+ const __half dh = __float2half_rn(d);+ const __half sh = __float2half_rn(sum);+ uint16_t dhb, shb;+ memcpy(&dhb, &dh, 2);+ memcpy(&shb, &sh, 2);+ reinterpret_cast<uint16_t*>(dst)[0] = dhb;+ reinterpret_cast<uint16_t*>(dst)[1] = shb;+}++__global__ void gm_quant_rows_f_kernel(const float* __restrict__ x, uint8_t* __restrict__ qb, int nb32)+{+ const int b = blockIdx.x * blockDim.x + threadIdx.x;+ if (b < nb32) gm_quant_block_f(x + (int64_t)b * 32, qb + (int64_t)b * FQ_Q8_1_BYTES);+}++// SwiGLU epilogue shared by the gate/up kernels: g / u rounded to half (Linear out_dtype), optional routed clamp (lim > 0: g <= lim, u in [-lim, lim]),+// silu in float, product back to half.+__device__ __forceinline__ __half gm_swiglu_act(float sg, float su, float lim)+{+ float gh = __half2float(__float2half_rn(sg));+ float uh = __half2float(__float2half_rn(su));+ if (lim > 0.0f) { gh = fminf(gh, lim); uh = fminf(fmaxf(uh, -lim), lim); }+ const float sig = 1.0f / (1.0f + expf(-gh));+ return __float2half_rn(sig * gh * uh);+}++// Expert-major groups (R >= 2): meta[u * GM_GRP] = number of slots of the u-th distinct expert, then those slot ids. Block group u loads the weight rows of its expert+// once per tile and runs every slot of the group on them (the weights stay in L1 / L2 for the repeated slots); without meta each slot is its own group.+constexpr int GM_GRP = 9;++__global__ void gm_meta_kernel(const int64_t* __restrict__ sel, int* __restrict__ meta, int SR, int E)+{+ __shared__ int ex[128];+ __shared__ int lead[128];+ const int s = threadIdx.x;+ if (s < SR)+ {+ int64_t e = sel[s];+ ex[s] = (int)((e < 0 || e >= E) ? 0 : e);+ meta[s * GM_GRP] = 0;+ }+ __syncthreads();+ int first = 0;+ if (s < SR)+ {+ first = 1;+ for (int p = 0; p < s; p++) if (ex[p] == ex[s]) first = 0;+ lead[s] = first;+ }+ __syncthreads();+ if (s < SR && first)+ {+ int rank = 0;+ for (int p = 0; p < s; p++) rank += lead[p];+ int cnt = 0;+ for (int p = s; p < SR; p++)+ if (ex[p] == ex[s] && cnt < GM_GRP - 1) meta[rank * GM_GRP + 1 + cnt++] = p;+ meta[rank * GM_GRP] = cnt;+ }+}++// Gate + up (Q4_K), one slot group per (blockIdx / ntiles) and 32 rows per block: fq_moe_kq_upgate_v2_kernel without the shared-expert slot and// without the unaligned fallback (the host checks the alignment of every expert).-__global__ void __launch_bounds__(256) gm_upgate_q4k_kernel(const uint8_t* __restrict__ aqb, const int64_t* __restrict__ sel,+__global__ void __launch_bounds__(256) gm_upgate_q4k_kernel(const uint8_t* __restrict__ aqb, const int64_t* __restrict__ sel, const int* __restrict__ meta,const uint8_t* const* __restrict__ gate_bases,const uint8_t* const* __restrict__ up_bases,int64_t gate_stride, int64_t up_stride,- __half* __restrict__ act, int I, int K, int E, int ntiles, int S_row, int qrow_bytes)+ __half* __restrict__ act, int I, int K, int E, int ntiles, int S_row, int qrow_bytes, float lim){__shared__ float pg[GM_ROWS * GM_PS];__shared__ float pu[GM_ROWS * GM_PS];- const int s = blockIdx.x / ntiles;+ const int u = blockIdx.x / ntiles;const int t = blockIdx.x % ntiles;+ const int ns = meta ? meta[u * GM_GRP] : 1;+ if (ns == 0) return;const int r = threadIdx.x >> 3, j = threadIdx.x & 7;- int64_t e = sel[s];- e = (e < 0 || e >= E) ? 0 : e;- const uint8_t* aq = aqb + (int64_t)(s / S_row) * qrow_bytes; // the q8_1 row of this slot's token (R rows, S_row slots each)const int n = t * GM_ROWS + r;- float ag[4] = {0.0f, 0.0f, 0.0f, 0.0f}, au[4] = {0.0f, 0.0f, 0.0f, 0.0f};- if (n < I)+ int64_t e = sel[meta ? meta[u * GM_GRP + 1] : u];+ e = (e < 0 || e >= E) ? 0 : e;+ for (int m = 0; m < ns; m++){- const uint8_t* gr = gate_bases[e] + (int64_t)n * gate_stride;- const uint8_t* ur = up_bases[e] + (int64_t)n * up_stride;- const int nitems = (K / 256) * 4;- for (int it = j; it < nitems; it += 8)+ const int s = meta ? meta[u * GM_GRP + 1 + m] : u;+ const uint8_t* aq = aqb + (int64_t)(s / S_row) * qrow_bytes; // the q8_1 row of this slot's token (R rows, S_row slots each)+ float ag[4] = {0.0f, 0.0f, 0.0f, 0.0f}, au[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ if (n < I){- float tg[4], tu[4];- fq_kq_item_q4_k(gr, aq, it, tg);- fq_kq_item_q4_k(ur, aq, it, tu);+ const uint8_t* gr = gate_bases[e] + (int64_t)n * gate_stride;+ const uint8_t* ur = up_bases[e] + (int64_t)n * up_stride;+ const int nitems = (K / 256) * 4;+ for (int it = j; it < nitems; it += 8)+ {+ float tg[4], tu[4];+ fq_kq_item_q4_k(gr, aq, it, tg);+ fq_kq_item_q4_k(ur, aq, it, tu);+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ ag[q] = __fadd_rn(ag[q], tg[q]);+ au[q] = __fadd_rn(au[q], tu[q]);+ }+ }+ }+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ pg[r * GM_PS + 4 * j + q] = ag[q];+ pu[r * GM_PS + 4 * j + q] = au[q];+ }+ __syncthreads();+ if (n < I && j == 0)+ {+ float sg = 0.0f, su = 0.0f;#pragma unroll- for (int q = 0; q < 4; q++)+ for (int l = 0; l < 32; l++){- ag[q] = __fadd_rn(ag[q], tg[q]);- au[q] = __fadd_rn(au[q], tu[q]);+ sg = __fadd_rn(sg, pg[r * GM_PS + l]);+ su = __fadd_rn(su, pu[r * GM_PS + l]);}+ act[(int64_t)s * I + n] = gm_swiglu_act(sg, su, lim);}+ __syncthreads();}- #pragma unroll- for (int q = 0; q < 4; q++)- {- pg[r * GM_PS + 4 * j + q] = ag[q];- pu[r * GM_PS + 4 * j + q] = au[q];- }- __syncthreads();- if (n < I && j == 0)+}++// Gate + up (Q3_K): the v1 lane layout of fq_moe_kq_upgate_kernel<8> (32 lane partials per row, summed in lane order), 8 rows per 256-thread block.+__global__ void __launch_bounds__(256) gm_upgate_q3k_kernel(const uint8_t* __restrict__ aqb, const int64_t* __restrict__ sel, const int* __restrict__ meta,+ const uint8_t* const* __restrict__ gate_bases,+ const uint8_t* const* __restrict__ up_bases,+ int64_t gate_stride, int64_t up_stride,+ __half* __restrict__ act, int I, int K, int E, int ntiles, int S_row, int qrow_bytes, float lim)+{+ __shared__ float red[256 * 2];+ const int u = blockIdx.x / ntiles;+ const int t = blockIdx.x % ntiles;+ const int ns = meta ? meta[u * GM_GRP] : 1;+ if (ns == 0) return;+ const int r = threadIdx.x >> 5, lane = threadIdx.x & 31;+ const int n = t * 8 + r;+ int64_t e = sel[meta ? meta[u * GM_GRP + 1] : u];+ e = (e < 0 || e >= E) ? 0 : e;+ for (int m = 0; m < ns; m++){- float sg = 0.0f, su = 0.0f;- #pragma unroll- for (int l = 0; l < 32; l++)+ const int s = meta ? meta[u * GM_GRP + 1 + m] : u;+ const uint8_t* aq = aqb + (int64_t)(s / S_row) * qrow_bytes;+ float g = 0.0f, uu = 0.0f;+ if (n < I)+ {+ g = gm_dot_q3_k(gate_bases[e] + (int64_t)n * gate_stride, aq, K, lane, 32);+ uu = gm_dot_q3_k(up_bases[e] + (int64_t)n * up_stride, aq, K, lane, 32);+ }+ red[2 * threadIdx.x] = g;+ red[2 * threadIdx.x + 1] = uu;+ __syncthreads();+ if (n < I && lane == 0){- sg = __fadd_rn(sg, pg[r * GM_PS + l]);- su = __fadd_rn(su, pu[r * GM_PS + l]);+ float sg = 0.0f, su = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++)+ {+ sg = __fadd_rn(sg, red[(r * 32 + l) * 2]);+ su = __fadd_rn(su, red[(r * 32 + l) * 2 + 1]);+ }+ act[(int64_t)s * I + n] = gm_swiglu_act(sg, su, lim);}- const float gh = __half2float(__float2half_rn(sg));- const float uh = __half2float(__float2half_rn(su));- const float sig = 1.0f / (1.0f + expf(-gh));- act[(int64_t)s * I + n] = __float2half_rn(sig * gh * uh);+ __syncthreads();}}// Down (Q4_K = FMT 0, Q6_K = FMT 2): fq_moe_kq_down_v2_kernel with the q8_1 quantization of act[s] done in shared memory first.template <int FMT>-__global__ void __launch_bounds__(256) gm_down_kernel(const __half* __restrict__ act, const int64_t* __restrict__ sel,+__global__ void __launch_bounds__(256) gm_down_kernel(const __half* __restrict__ act, const int64_t* __restrict__ sel, const int* __restrict__ meta,const uint8_t* const* __restrict__ down_bases, int64_t down_stride,float* __restrict__ partial, int I, int K, int E, int ntiles){__shared__ float pp[GM_ROWS * GM_PS];__shared__ __align__(16) uint8_t qa[GM_MAX_NB * FQ_Q8_1_BYTES];- const int s = blockIdx.x / ntiles;+ const int u = blockIdx.x / ntiles;const int t = blockIdx.x % ntiles;+ const int ns = meta ? meta[u * GM_GRP] : 1;+ if (ns == 0) return;const int r = threadIdx.x >> 3, j = threadIdx.x & 7;const int nb = I / 32;- if ((int)threadIdx.x < nb) gm_quant_block(act + (int64_t)s * I + threadIdx.x * 32, qa + threadIdx.x * FQ_Q8_1_BYTES);- int64_t e = sel[s];+ int64_t e = sel[meta ? meta[u * GM_GRP + 1] : u];e = (e < 0 || e >= E) ? 0 : e;const int n = t * GM_ROWS + r;- float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};- __syncthreads();- if (n < K)+ for (int m = 0; m < ns; m++){- const uint8_t* dr = down_bases[e] + (int64_t)n * down_stride;- const int nitems = (I / 256) * ((FMT == 2) ? 8 : 4);- for (int it = j; it < nitems; it += 8)+ const int s = meta ? meta[u * GM_GRP + 1 + m] : u;+ if ((int)threadIdx.x < nb) gm_quant_block(act + (int64_t)s * I + threadIdx.x * 32, qa + threadIdx.x * FQ_Q8_1_BYTES);+ float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ __syncthreads();+ if (n < K){- float tv[4];- if constexpr (FMT == 0) fq_kq_item_q4_k(dr, qa, it, tv);- else fq_kq_item_q6_k(dr, qa, it, tv);- #pragma unroll- for (int q = 0; q < 4; q++)- acc[q] = __fadd_rn(acc[q], tv[q]);+ const uint8_t* dr = down_bases[e] + (int64_t)n * down_stride;+ const int nitems = (I / 256) * ((FMT == 2) ? 8 : 4);+ for (int it = j; it < nitems; it += 8)+ {+ float tv[4];+ if constexpr (FMT == 0) fq_kq_item_q4_k(dr, qa, it, tv);+ else fq_kq_item_q6_k(dr, qa, it, tv);+ #pragma unroll+ for (int q = 0; q < 4; q++)+ acc[q] = __fadd_rn(acc[q], tv[q]);+ }}- }- #pragma unroll- for (int q = 0; q < 4; q++)- pp[r * GM_PS + ((FMT == 2) ? (j + 8 * q) : (4 * j + q))] = acc[q];- __syncthreads();- if (n < K && j == 0)- {- float sp = 0.0f;#pragma unroll- for (int l = 0; l < 32; l++)- sp = __fadd_rn(sp, pp[r * GM_PS + l]);- partial[(int64_t)s * K + n] = sp;+ for (int q = 0; q < 4; q++)+ pp[r * GM_PS + ((FMT == 2) ? (j + 8 * q) : (4 * j + q))] = acc[q];+ __syncthreads();+ if (n < K && j == 0)+ {+ float sp = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++)+ sp = __fadd_rn(sp, pp[r * GM_PS + l]);+ partial[(int64_t)s * K + n] = sp;+ }+ __syncthreads();}}@@ -210,16 +345,18 @@ __global__ void gm_combine_kernel(const float* __restrict__ partial, const __hal} // namespace-// h [1, K] half, sel [S] int64, wts [S] half, expert pointer tables (int64 device addresses), strides in bytes,-// fmt_d 0 = Q4_K / 2 = Q6_K down, act [S, I] half scratch, qb [K/32*36] uint8 scratch, partial [S, K] float scratch,-// out [1, K] float (routed sum), resid [K] float / half or an empty tensor (no residual add).+// h [R, K] half, sel [R*S] int64, wts [R*S] half, expert pointer tables (int64 device addresses), strides in bytes,+// fmt_d 0 = Q4_K / 2 = Q6_K down, fmt_gu 0 = Q4_K / 8 = Q3_K gate/up, act [R*S, I] half scratch, qb [R*K/32*36] uint8 scratch, partial [R*S, K] float scratch,+// out [R, K] float (routed sum), resid [K] float / half or an empty tensor (no residual add), lim = routed swiglu clamp (0 = none: g <= lim, u in [-lim, lim]),+// meta = int32 scratch [>= R*S*9] switches on the expert-major order (R >= 2: every distinct expert's weights are read once per tile for all rows that picked it).void gm_moe_kq_decode(const at::Tensor& h, const at::Tensor& sel, const at::Tensor& wts, const at::Tensor& gate_ptrs,const at::Tensor& up_ptrs, const at::Tensor& down_ptrs, int64_t gate_stride, int64_t up_stride,int64_t down_stride, int64_t fmt_d, at::Tensor& act, at::Tensor& qb, at::Tensor& partial,- at::Tensor& out, const at::Tensor& resid)+ at::Tensor& out, const at::Tensor& resid, int64_t fmt_gu, double lim, const at::Tensor& meta){TORCH_CHECK(h.is_cuda() && h.dtype() == at::kHalf && h.dim() == 2 && h.size(0) >= 1 && h.size(0) <= 8, "gm_moe_kq_decode: h must be [R, K] half on the device, R <= 8");TORCH_CHECK(fmt_d == 0 || fmt_d == 2, "gm_moe_kq_decode: down format must be Q4_K (0) or Q6_K (2)");+ TORCH_CHECK(fmt_gu == 0 || fmt_gu == 8, "gm_moe_kq_decode: gate/up format must be Q4_K (0) or Q3_K (8)");const at::cuda::OptionalCUDAGuard guard(h.device());const int K = (int)h.size(1);const int R = (int)h.size(0);@@ -229,27 +366,43 @@ void gm_moe_kq_decode(const at::Tensor& h, const at::Tensor& sel, const at::Tensconst int E = (int)up_ptrs.numel();const int bb = fmt_d == 2 ? FQ_Q6_K_BYTES : FQ_Q4_K_BYTES;const int I = (int)(down_stride / bb) * 256;- TORCH_CHECK(K % 256 == 0 && I % 256 == 0 && I / 32 <= GM_MAX_NB && S <= 32, "gm_moe_kq_decode: unsupported shape K=", K, " I=", I);- TORCH_CHECK(gate_stride == (int64_t)(K / 256) * FQ_Q4_K_BYTES && up_stride == gate_stride, "gm_moe_kq_decode: gate/up must be Q4_K");+ TORCH_CHECK(K % 256 == 0 && I % 256 == 0 && I / 32 <= GM_MAX_NB && S <= 32 && SR <= 128, "gm_moe_kq_decode: unsupported shape K=", K, " I=", I);+ const int64_t ug_bytes = fmt_gu == 8 ? FQ_Q3_K_BYTES : FQ_Q4_K_BYTES;+ TORCH_CHECK(gate_stride == (int64_t)(K / 256) * ug_bytes && up_stride == gate_stride, "gm_moe_kq_decode: gate/up stride does not match the gate/up format");TORCH_CHECK(act.numel() >= (int64_t)SR * I && qb.numel() >= (int64_t)R * (K / 32) * FQ_Q8_1_BYTES && partial.numel() >= (int64_t)SR * K && out.numel() >= (int64_t)R * K,"gm_moe_kq_decode: scratch too small");+ const bool grouped = R >= 2 && meta.numel() >= (int64_t)SR * GM_GRP;+ TORCH_CHECK(!grouped || meta.dtype() == at::kInt, "gm_moe_kq_decode: meta must be int32");hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();uint8_t* qbp = reinterpret_cast<uint8_t*>(qb.data_ptr());const int nb32 = K / 32;hipLaunchKernelGGL(( gm_quant_rows_kernel), dim3((R * nb32 + 63) / 64), dim3(64), 0, stream, reinterpret_cast<const __half*>(h.data_ptr()), qbp, R * nb32);- const int ntu = (I + GM_ROWS - 1) / GM_ROWS, ntd = (K + GM_ROWS - 1) / GM_ROWS;+ const int64_t* selp = reinterpret_cast<const int64_t*>(sel.data_ptr());+ const int* metap = nullptr;+ if (grouped)+ {+ hipLaunchKernelGGL(( gm_meta_kernel), dim3(1), dim3(128), 0, stream, selp, reinterpret_cast<int*>(meta.data_ptr()), SR, E);+ metap = reinterpret_cast<const int*>(meta.data_ptr());+ }+ const int ntd = (K + GM_ROWS - 1) / GM_ROWS;__half* actp = reinterpret_cast<__half*>(act.data_ptr());- hipLaunchKernelGGL(( gm_upgate_q4k_kernel), dim3(SR * ntu), dim3(256), 0, stream,- qbp, reinterpret_cast<const int64_t*>(sel.data_ptr()),- reinterpret_cast<const uint8_t* const*>(gate_ptrs.data_ptr()), reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr()),- gate_stride, up_stride, actp, I, K, E, ntu, S, nb32 * FQ_Q8_1_BYTES);+ const uint8_t* const* gp = reinterpret_cast<const uint8_t* const*>(gate_ptrs.data_ptr());+ const uint8_t* const* upp = reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr());+ if (fmt_gu == 0)+ {+ const int ntu = (I + GM_ROWS - 1) / GM_ROWS;+ hipLaunchKernelGGL(( gm_upgate_q4k_kernel), dim3(SR * ntu), dim3(256), 0, stream, qbp, selp, metap, gp, upp, gate_stride, up_stride, actp, I, K, E, ntu, S, nb32 * FQ_Q8_1_BYTES, (float)lim);+ }+ else+ {+ const int ntu = (I + 7) / 8;+ hipLaunchKernelGGL(( gm_upgate_q3k_kernel), dim3(SR * ntu), dim3(256), 0, stream, qbp, selp, metap, gp, upp, gate_stride, up_stride, actp, I, K, E, ntu, S, nb32 * FQ_Q8_1_BYTES, (float)lim);+ }float* partp = reinterpret_cast<float*>(partial.data_ptr());if (fmt_d == 0)- hipLaunchKernelGGL(( gm_down_kernel<0>), dim3(SR * ntd), dim3(256), 0, stream, actp, reinterpret_cast<const int64_t*>(sel.data_ptr()),- reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()), down_stride, partp, I, K, E, ntd);+ hipLaunchKernelGGL(( gm_down_kernel<0>), dim3(SR * ntd), dim3(256), 0, stream, actp, selp, metap, reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()), down_stride, partp, I, K, E, ntd);else- hipLaunchKernelGGL(( gm_down_kernel<2>), dim3(SR * ntd), dim3(256), 0, stream, actp, reinterpret_cast<const int64_t*>(sel.data_ptr()),- reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()), down_stride, partp, I, K, E, ntd);+ hipLaunchKernelGGL(( gm_down_kernel<2>), dim3(SR * ntd), dim3(256), 0, stream, actp, selp, metap, reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()), down_stride, partp, I, K, E, ntd);const __half* wp = reinterpret_cast<const __half*>(wts.data_ptr());float* outp = reinterpret_cast<float*>(out.data_ptr());const int cb = (K + 255) / 256;@@ -338,22 +491,127 @@ __global__ void __launch_bounds__(64) gm_gemv3_kernel(Gm3 a, const uint8_t* __re}}+// Q8_0 projections, 1..3 matrices of one launch: the arithmetic of fq_gemv_q8_q8_kernel (one block per output row, nt = fq_q8_nt(K) lane partials of+// fq_dot_q8_0_q8, summed in lane order). OUT = __half or float.+struct Gm3q+{+ const uint8_t* w[3];+ void* out[3];+ int N[3];+};++template <typename OUT>+__global__ void gm_gemv_q8_kernel(Gm3q a, const uint8_t* __restrict__ aqb, int K, int nt, int64_t row_bytes)+{+ extern __shared__ float red[];+ const int row = blockIdx.y;+ aqb += (int64_t)row * (K / 32) * FQ_Q8_1_BYTES;+ int blk = blockIdx.x, mi = 0;+ if (blk >= a.N[0]) { blk -= a.N[0]; mi = 1; if (blk >= a.N[1]) { blk -= a.N[1]; mi = 2; } }+ const int tid = threadIdx.x;+ red[tid] = gm_dot_q8_0(a.w[mi] + (int64_t)blk * row_bytes, aqb, K, tid, nt);+ __syncthreads();+ if (tid == 0)+ {+ float sum = 0.0f;+ for (int l = 0; l < nt; l++) sum = __fadd_rn(sum, red[l]);+ OUT* o = reinterpret_cast<OUT*>(a.out[mi]);+ if constexpr (std::is_same<OUT, __half>::value) o[(int64_t)row * a.N[mi] + blk] = __float2half_rn(sum);+ else o[(int64_t)row * a.N[mi] + blk] = sum;+ }+}++__device__ __forceinline__ float gm_to_f(float v) { return v; }+__device__ __forceinline__ float gm_to_f(__half v) { return __half2float(v); }++// SwiGLU of the shared expert fused into its Q8_0 down projection: act = half(silu(g) * u) (g, u half or float [R, I]), quantized to q8_1 in shared memory,+// then the Q8_0 dot of fq_gemv_q8_q8_kernel. accumulate: out += result (fp32 add), else out = result.+template <typename GT>+__global__ void gm_swiglu_down_q8_kernel(const GT* __restrict__ g, const GT* __restrict__ u, const uint8_t* __restrict__ wd, float* __restrict__ out,+ int I, int N, int nt, int64_t row_bytes, int accumulate)+{+ extern __shared__ float red[];+ __shared__ __align__(16) uint8_t qa[GM_MAX_NB * FQ_Q8_1_BYTES];+ const int row = blockIdx.y, n = blockIdx.x, tid = threadIdx.x;+ const int nb = I / 32;+ if (tid < nb)+ {+ __half a32[32];+ #pragma unroll+ for (int i = 0; i < 32; i++)+ {+ const float gv = gm_to_f(g[(int64_t)row * I + tid * 32 + i]);+ const float uv = gm_to_f(u[(int64_t)row * I + tid * 32 + i]);+ const float sig = 1.0f / (1.0f + expf(-gv));+ a32[i] = __float2half_rn(sig * gv * uv);+ }+ gm_quant_block(a32, qa + tid * FQ_Q8_1_BYTES);+ }+ __syncthreads();+ red[tid] = gm_dot_q8_0(wd + (int64_t)n * row_bytes, qa, I, tid, nt);+ __syncthreads();+ if (tid == 0)+ {+ float sum = 0.0f;+ for (int l = 0; l < nt; l++) sum = __fadd_rn(sum, red[l]);+ float* o = out + (int64_t)row * N + n;+ *o = accumulate ? __fadd_rn(*o, sum) : sum;+ }+}+// ws: 2 or 3 packed matrices [N_i, row bytes] uint8 (Q4_K = fmt 0 / Q6_K = fmt 2), out [1, sum N] half, x [1, K] half, qb scratch.void gm_qkv_decode(const at::Tensor& x, const std::vector<at::Tensor>& ws, const std::vector<int64_t>& fmts, at::Tensor& out, at::Tensor& qb){- TORCH_CHECK(x.is_cuda() && x.dtype() == at::kHalf && x.dim() == 2 && x.size(0) >= 1 && x.size(0) <= 8, "gm_qkv_decode: x must be [R, K] half on the device, R <= 8");+ TORCH_CHECK(x.is_cuda() && (x.dtype() == at::kHalf || x.dtype() == at::kFloat) && x.dim() == 2 && x.size(0) >= 1 && x.size(0) <= 8, "gm_qkv_decode: x must be [R, K] half or float on the device, R <= 8");const int R = (int)x.size(0);TORCH_CHECK(ws.size() >= 1 && ws.size() <= 3 && ws.size() == fmts.size(), "gm_qkv_decode: 1..3 matrices");const at::cuda::OptionalCUDAGuard guard(x.device());const int K = (int)x.size(1);- TORCH_CHECK(K % 256 == 0 && qb.numel() >= (int64_t)R * (K / 32) * FQ_Q8_1_BYTES, "gm_qkv_decode: K / scratch");+ const bool q8 = fmts[0] == 3;+ for (auto f : fmts) TORCH_CHECK((f == 3) == q8, "gm_qkv_decode: Q8_0 (3) matrices cannot mix with Q4_K / Q6_K in one launch");+ TORCH_CHECK(K % (q8 ? 32 : 256) == 0 && qb.numel() >= (int64_t)R * (K / 32) * FQ_Q8_1_BYTES, "gm_qkv_decode: K / scratch");+ TORCH_CHECK(!(x.dtype() == at::kFloat) || q8, "gm_qkv_decode: float x only with Q8_0");+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ uint8_t* qbp = reinterpret_cast<uint8_t*>(qb.data_ptr());+ const int nb32 = K / 32;+ auto quant = [&]()+ {+ if (x.dtype() == at::kFloat) {hipLaunchKernelGGL(( gm_quant_rows_f_kernel), dim3((R * nb32 + 63) / 64), dim3(64), 0, stream, x.data_ptr<float>(), qbp, R * nb32); }+ else {hipLaunchKernelGGL(( gm_quant_rows_kernel), dim3((R * nb32 + 63) / 64), dim3(64), 0, stream, reinterpret_cast<const __half*>(x.data_ptr()), qbp, R * nb32); }+ };+ if (q8)+ {+ TORCH_CHECK(out.dtype() == at::kHalf || out.dtype() == at::kFloat, "gm_qkv_decode: out half or float for Q8_0");+ const int64_t rb = (int64_t)nb32 * FQ_Q8_0_BYTES;+ Gm3q a;+ memset(&a, 0, sizeof(a));+ int total = 0;+ const size_t esz = out.dtype() == at::kHalf ? 2 : 4;+ char* o = reinterpret_cast<char*>(out.data_ptr());+ for (size_t i = 0; i < ws.size(); i++)+ {+ TORCH_CHECK(ws[i].dim() == 2 && ws[i].size(1) == rb && ws[i].stride(1) == 1 && ws[i].stride(0) == rb, "gm_qkv_decode: packed Q8_0 matrix shape");+ TORCH_CHECK((reinterpret_cast<uintptr_t>(ws[i].data_ptr()) & 1) == 0, "gm_qkv_decode: unaligned weights");+ a.w[i] = reinterpret_cast<const uint8_t*>(ws[i].data_ptr());+ a.N[i] = (int)ws[i].size(0);+ a.out[i] = o + esz * (int64_t)R * total;+ total += a.N[i];+ }+ TORCH_CHECK(out.numel() >= (int64_t)R * total, "gm_qkv_decode: out too small");+ const int nt = nb32 >= 256 ? 256 : ((nb32 + 31) / 32) * 32;+ quant();+ if (out.dtype() == at::kHalf) {hipLaunchKernelGGL(( gm_gemv_q8_kernel<__half>), dim3(dim3(total, R)), dim3(nt), nt * sizeof(float), stream, a, qbp, K, nt, rb); }+ else {hipLaunchKernelGGL(( gm_gemv_q8_kernel<float>), dim3(dim3(total, R)), dim3(nt), nt * sizeof(float), stream, a, qbp, K, nt, rb); }+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_qkv_decode: launch failed");+ return;+ }Gm3 a;memset(&a, 0, sizeof(a));int total = 0;__half* o = reinterpret_cast<__half*>(out.data_ptr());for (size_t i = 0; i < ws.size(); i++){- TORCH_CHECK(fmts[i] == 0 || fmts[i] == 2, "gm_qkv_decode: Q4_K (0) or Q6_K (2) only");+ TORCH_CHECK(fmts[i] == 0 || fmts[i] == 2, "gm_qkv_decode: Q4_K (0), Q6_K (2) or Q8_0 (3) only");const int64_t rb = (int64_t)(K / 256) * (fmts[i] == 0 ? FQ_Q4_K_BYTES : FQ_Q6_K_BYTES);TORCH_CHECK(ws[i].dim() == 2 && ws[i].size(1) == rb && ws[i].stride(1) == 1 && ws[i].stride(0) == rb, "gm_qkv_decode: packed matrix shape");const uintptr_t am = fmts[i] == 0 ? 15 : 1;@@ -369,12 +627,37 @@ void gm_qkv_decode(const at::Tensor& x, const std::vector<at::Tensor>& ws, constTORCH_CHECK(out.numel() >= (int64_t)R * total, "gm_qkv_decode: out too small");auto ntf = [](int nsub) { return nsub >= 256 ? 256 : ((nsub + 31) / 32) * 32; };const int nt4 = ntf(K / 16), nt6 = ntf(K / 8);- hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();- uint8_t* qbp = reinterpret_cast<uint8_t*>(qb.data_ptr());- const int nb32 = K / 32;- hipLaunchKernelGGL(( gm_quant_rows_kernel), dim3((R * nb32 + 63) / 64), dim3(64), 0, stream, reinterpret_cast<const __half*>(x.data_ptr()), qbp, R * nb32);+ quant();hipLaunchKernelGGL(( gm_gemv3_kernel), dim3(dim3(total, R)), dim3(64), 0, stream, a, qbp, K, nt4, nt6);TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_qkv_decode: launch failed");}+// Shared expert down projection with the SwiGLU fused in: g, u [R, I] (half or float, e.g. the two outputs of a Q8_0 gm_qkv_decode), wd packed Q8_0 [N, I/32*34],+// out float [R, N]; accumulate = out += result (add the shared expert onto the routed up-projection output of a previous gm_qkv_decode call).+void gm_q8_swiglu_down(const at::Tensor& g, const at::Tensor& u, const at::Tensor& wd, at::Tensor& out, bool accumulate)+{+ TORCH_CHECK(g.is_cuda() && g.dim() == 2 && g.sizes() == u.sizes() && g.dtype() == u.dtype() && (g.dtype() == at::kHalf || g.dtype() == at::kFloat) && g.is_contiguous() && u.is_contiguous(),+ "gm_q8_swiglu_down: g, u [R, I] contiguous half or float");+ const at::cuda::OptionalCUDAGuard guard(g.device());+ const int R = (int)g.size(0), I = (int)g.size(1), N = (int)wd.size(0);+ const int nb = I / 32;+ const int64_t rb = (int64_t)nb * FQ_Q8_0_BYTES;+ TORCH_CHECK(R <= 8 && I % 32 == 0 && nb <= GM_MAX_NB && wd.dim() == 2 && wd.size(1) == rb && wd.is_contiguous() && (reinterpret_cast<uintptr_t>(wd.data_ptr()) & 1) == 0,+ "gm_q8_swiglu_down: shape / alignment");+ TORCH_CHECK(out.dtype() == at::kFloat && out.numel() >= (int64_t)R * N, "gm_q8_swiglu_down: out float [R, N]");+ const int nt = nb >= 256 ? 256 : ((nb + 31) / 32) * 32;+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ if (g.dtype() == at::kHalf)+ {+ hipLaunchKernelGGL(( gm_swiglu_down_q8_kernel<__half>), dim3(dim3(N, R)), dim3(nt), nt * sizeof(float), stream, reinterpret_cast<const __half*>(g.data_ptr()), reinterpret_cast<const __half*>(u.data_ptr()),+ reinterpret_cast<const uint8_t*>(wd.data_ptr()), out.data_ptr<float>(), I, N, nt, rb, accumulate ? 1 : 0);+ }+ else+ {+ hipLaunchKernelGGL(( gm_swiglu_down_q8_kernel<float>), dim3(dim3(N, R)), dim3(nt), nt * sizeof(float), stream, g.data_ptr<float>(), u.data_ptr<float>(),+ reinterpret_cast<const uint8_t*>(wd.data_ptr()), out.data_ptr<float>(), I, N, nt, rb, accumulate ? 1 : 0);+ }+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_q8_swiglu_down: launch failed");+}+#endif // USE_ROCMdiff --git a/exllamav3/gm_ext/gm_router.cu b/exllamav3/gm_ext/gm_router.cuindex 561dd8d..a7aa4c1 100644--- a/exllamav3/gm_ext/gm_router.cu+++ b/exllamav3/gm_ext/gm_router.cu@@ -255,4 +255,138 @@ void gm_routing_std_bsz1TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_routing_std_bsz1: launch failed");}+// ---------------------------------------------------------------------------------------------------------------------------------+// Generic router (any hidden size / expert count <= 1024 / top-k <= 32, fp32 or fp16 gate weights, fp32 or fp16 activations, 1..16 rows):+// logits = x . gate^T (fp32 accumulation, one wave per expert), then ONE block per row selects the top-k by rank counting (ties -> lowest expert id,+// i.e. a stable descending sort) and forms the weights.+// gating 0: softmax over all experts (selection on the logits), w = exp(l - max) / sum_all, or / (sum_selected + 1e-20) when norm (Qwen3 / Mixtral / gpt-oss)+// gating 2: sigmoid; selection on sigmoid + bias (bias optional, selection only), w = sigmoid[sel], / max(sum_sel, eps) when norm (GLM / DeepSeek / Hy4)+// w *= scale. Outputs: sel int64 [R, k], w half [R, k].+// ---------------------------------------------------------------------------------------------------------------------------------+namespace {++template <typename T> __device__ __forceinline__ float gm_ld_f(const T v);+template <> __device__ __forceinline__ float gm_ld_f<float>(const float v) { return v; }+template <> __device__ __forceinline__ float gm_ld_f<half>(const half v) { return __half2float(v); }++template <typename XT, typename WT>+__global__ __launch_bounds__(128) void gm_rt_logits_kernel(const XT* __restrict__ x, const WT* __restrict__ g, float* __restrict__ scores, int H, int E)+{+ const int row = blockIdx.y;+ const int wave = threadIdx.x / WAVE_SIZE;+ const int lane = threadIdx.x % WAVE_SIZE;+ const int expert = blockIdx.x * 4 + wave;+ if (expert >= E) return;+ const XT* xr = x + (size_t)row * H;+ const WT* gr = g + (size_t)expert * H;+ float sum = 0.0f;+ #pragma unroll 4+ for (int h = lane; h < H; h += WAVE_SIZE)+ sum = fmaf(gm_ld_f<XT>(xr[h]), gm_ld_f<WT>(gr[h]), sum);+ sum = wave_reduce_sum(sum);+ if (lane == 0) scores[(size_t)row * E + expert] = sum;+}++__global__ __launch_bounds__(1024) void gm_rt_topk_kernel(const float* __restrict__ scores, const float* __restrict__ bias, int64_t* __restrict__ sel,+ half* __restrict__ wout, int E, int topk, int gating, int norm, float scale, float eps)+{+ __shared__ float key[1024];+ __shared__ float prob[1024];+ __shared__ float wred[32];+ __shared__ float s_max, s_sum;+ __shared__ float selw[32];+ __shared__ int selidx[32];+ const int tid = threadIdx.x, lane = tid % WAVE_SIZE, wave = tid / WAVE_SIZE;+ const int nwaves = (blockDim.x + WAVE_SIZE - 1) / WAVE_SIZE;+ const float* sc = scores + (size_t)blockIdx.x * E;+ const bool valid = tid < E;+ const float logit = valid ? sc[tid] : NEG_INF;+ float p, k;+ if (gating == 2)+ {+ p = valid ? 1.0f / (1.0f + expf(-logit)) : 0.0f;+ k = valid ? (bias != nullptr ? p + bias[tid] : p) : NEG_INF;+ }+ else+ {+ float m = wave_reduce_max(logit);+ if (lane == 0) wred[wave] = m;+ __syncthreads();+ if (wave == 0)+ {+ float mm = lane < nwaves ? wred[lane] : NEG_INF;+ mm = wave_reduce_max(mm);+ if (lane == 0) s_max = mm;+ }+ __syncthreads();+ p = valid ? expf(logit - s_max) : 0.0f; // unnormalized exp+ k = logit;+ float t = wave_reduce_sum(p);+ __syncthreads();+ if (lane == 0) wred[wave] = t;+ __syncthreads();+ if (wave == 0)+ {+ float tt = lane < nwaves ? wred[lane] : 0.0f;+ tt = wave_reduce_sum(tt);+ if (lane == 0) s_sum = tt;+ }+ }+ key[tid] = k;+ prob[tid] = p;+ __syncthreads();+ int rank = 0;+ if (valid)+ {+ #pragma unroll 8+ for (int j = 0; j < E; ++j)+ {+ const float o = key[j];+ rank += (o > k || (o == k && j < tid)) ? 1 : 0;+ }+ if (rank < topk) { selw[rank] = p; selidx[rank] = tid; }+ }+ __syncthreads();+ if (wave == 0)+ {+ const float w = lane < topk ? selw[lane] : 0.0f;+ const float ssum = wave_reduce_sum(w);+ if (lane < topk)+ {+ float o;+ if (gating == 2) o = norm ? w / fmaxf(ssum, eps) : w;+ else o = norm ? w / (ssum + 1.0e-20f) : w / s_sum;+ sel[(size_t)blockIdx.x * topk + lane] = (int64_t)selidx[lane];+ wout[(size_t)blockIdx.x * topk + lane] = __float2half_rn(o * scale);+ }+ }+}++} // namespace++void gm_route(const at::Tensor& x, const at::Tensor& gate, const at::Tensor& bias, at::Tensor& scores, at::Tensor& sel, at::Tensor& w,+ int64_t gating, bool norm, double scale, double eps)+{+ TORCH_CHECK(x.is_cuda() && x.dim() == 2 && gate.is_cuda() && gate.dim() == 2 && x.is_contiguous() && gate.is_contiguous(), "gm_route: x [R, H] and gate [E, H] contiguous device tensors");+ const at::cuda::OptionalCUDAGuard guard(x.device());+ const int R = (int)x.size(0), H = (int)x.size(1), E = (int)gate.size(0), topk = (int)sel.size(1);+ TORCH_CHECK(R >= 1 && R <= MAX_ROUTER_ROWS && gate.size(1) == H && E <= 1024 && topk >= 1 && topk <= 32 && topk <= E, "gm_route: unsupported shape R=", R, " H=", H, " E=", E, " k=", topk);+ TORCH_CHECK(gating == 0 || gating == 2, "gm_route: gating 0 (softmax) or 2 (sigmoid)");+ TORCH_CHECK(sel.dtype() == at::kLong && w.dtype() == at::kHalf && scores.dtype() == at::kFloat && scores.numel() >= (int64_t)R * E && sel.size(0) == R && w.size(0) == R && w.size(1) == topk,+ "gm_route: sel int64 [R, k], w half [R, k], scores float scratch [R, E]");+ TORCH_CHECK(bias.numel() == 0 || (bias.dtype() == at::kFloat && bias.numel() == E && bias.is_contiguous()), "gm_route: bias float [E] or empty");+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ float* sp = scores.data_ptr<float>();+ const dim3 grid((E + 3) / 4, R);+ const bool xf = x.dtype() == at::kFloat, gf = gate.dtype() == at::kFloat;+ TORCH_CHECK((xf || x.dtype() == at::kHalf) && (gf || gate.dtype() == at::kHalf), "gm_route: x / gate float or half");+ #define GM_RT(XT, WT) gm_rt_logits_kernel<XT, WT><<<grid, 128, 0, stream>>>(reinterpret_cast<const XT*>(x.data_ptr()), reinterpret_cast<const WT*>(gate.data_ptr()), sp, H, E)+ if (xf && gf) GM_RT(float, float); else if (xf) GM_RT(float, half); else if (gf) GM_RT(half, float); else GM_RT(half, half);+ #undef GM_RT+ const int nt = ((E + 31) / 32) * 32;+ gm_rt_topk_kernel<<<R, nt, 0, stream>>>(sp, bias.numel() ? bias.data_ptr<float>() : nullptr, sel.data_ptr<int64_t>(), reinterpret_cast<half*>(w.data_ptr()),+ E, topk, (int)gating, norm ? 1 : 0, (float)scale, (float)eps);+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_route: launch failed");+}+#endif // USE_ROCMdiff --git a/exllamav3/gm_ext/gm_router.cuh b/exllamav3/gm_ext/gm_router.cuhindex c254b54..4eada32 100644--- a/exllamav3/gm_ext/gm_router.cuh+++ b/exllamav3/gm_ext/gm_router.cuh@@ -16,4 +16,7 @@ void gm_routing_std_bsz1at::Tensor& topk_weights);+void gm_route(const at::Tensor& x, const at::Tensor& gate, const at::Tensor& bias, at::Tensor& scores, at::Tensor& sel, at::Tensor& w,+ int64_t gating, bool norm, double scale, double eps);+#endifdiff --git a/exllamav3/gm_ext/gm_router.hip b/exllamav3/gm_ext/gm_router.hipindex 20a6393..2ede608 100644--- a/exllamav3/gm_ext/gm_router.hip+++ b/exllamav3/gm_ext/gm_router.hip@@ -256,4 +256,138 @@ void gm_routing_std_bsz1TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_routing_std_bsz1: launch failed");}+// ---------------------------------------------------------------------------------------------------------------------------------+// Generic router (any hidden size / expert count <= 1024 / top-k <= 32, fp32 or fp16 gate weights, fp32 or fp16 activations, 1..16 rows):+// logits = x . gate^T (fp32 accumulation, one wave per expert), then ONE block per row selects the top-k by rank counting (ties -> lowest expert id,+// i.e. a stable descending sort) and forms the weights.+// gating 0: softmax over all experts (selection on the logits), w = exp(l - max) / sum_all, or / (sum_selected + 1e-20) when norm (Qwen3 / Mixtral / gpt-oss)+// gating 2: sigmoid; selection on sigmoid + bias (bias optional, selection only), w = sigmoid[sel], / max(sum_sel, eps) when norm (GLM / DeepSeek / Hy4)+// w *= scale. Outputs: sel int64 [R, k], w half [R, k].+// ---------------------------------------------------------------------------------------------------------------------------------+namespace {++template <typename T> __device__ __forceinline__ float gm_ld_f(const T v);+template <> __device__ __forceinline__ float gm_ld_f<float>(const float v) { return v; }+template <> __device__ __forceinline__ float gm_ld_f<half>(const half v) { return __half2float(v); }++template <typename XT, typename WT>+__global__ __launch_bounds__(128) void gm_rt_logits_kernel(const XT* __restrict__ x, const WT* __restrict__ g, float* __restrict__ scores, int H, int E)+{+ const int row = blockIdx.y;+ const int wave = threadIdx.x / WAVE_SIZE;+ const int lane = threadIdx.x % WAVE_SIZE;+ const int expert = blockIdx.x * 4 + wave;+ if (expert >= E) return;+ const XT* xr = x + (size_t)row * H;+ const WT* gr = g + (size_t)expert * H;+ float sum = 0.0f;+ #pragma unroll 4+ for (int h = lane; h < H; h += WAVE_SIZE)+ sum = fmaf(gm_ld_f<XT>(xr[h]), gm_ld_f<WT>(gr[h]), sum);+ sum = wave_reduce_sum(sum);+ if (lane == 0) scores[(size_t)row * E + expert] = sum;+}++__global__ __launch_bounds__(1024) void gm_rt_topk_kernel(const float* __restrict__ scores, const float* __restrict__ bias, int64_t* __restrict__ sel,+ half* __restrict__ wout, int E, int topk, int gating, int norm, float scale, float eps)+{+ __shared__ float key[1024];+ __shared__ float prob[1024];+ __shared__ float wred[32];+ __shared__ float s_max, s_sum;+ __shared__ float selw[32];+ __shared__ int selidx[32];+ const int tid = threadIdx.x, lane = tid % WAVE_SIZE, wave = tid / WAVE_SIZE;+ const int nwaves = (blockDim.x + WAVE_SIZE - 1) / WAVE_SIZE;+ const float* sc = scores + (size_t)blockIdx.x * E;+ const bool valid = tid < E;+ const float logit = valid ? sc[tid] : NEG_INF;+ float p, k;+ if (gating == 2)+ {+ p = valid ? 1.0f / (1.0f + expf(-logit)) : 0.0f;+ k = valid ? (bias != nullptr ? p + bias[tid] : p) : NEG_INF;+ }+ else+ {+ float m = wave_reduce_max(logit);+ if (lane == 0) wred[wave] = m;+ __syncthreads();+ if (wave == 0)+ {+ float mm = lane < nwaves ? wred[lane] : NEG_INF;+ mm = wave_reduce_max(mm);+ if (lane == 0) s_max = mm;+ }+ __syncthreads();+ p = valid ? expf(logit - s_max) : 0.0f; // unnormalized exp+ k = logit;+ float t = wave_reduce_sum(p);+ __syncthreads();+ if (lane == 0) wred[wave] = t;+ __syncthreads();+ if (wave == 0)+ {+ float tt = lane < nwaves ? wred[lane] : 0.0f;+ tt = wave_reduce_sum(tt);+ if (lane == 0) s_sum = tt;+ }+ }+ key[tid] = k;+ prob[tid] = p;+ __syncthreads();+ int rank = 0;+ if (valid)+ {+ #pragma unroll 8+ for (int j = 0; j < E; ++j)+ {+ const float o = key[j];+ rank += (o > k || (o == k && j < tid)) ? 1 : 0;+ }+ if (rank < topk) { selw[rank] = p; selidx[rank] = tid; }+ }+ __syncthreads();+ if (wave == 0)+ {+ const float w = lane < topk ? selw[lane] : 0.0f;+ const float ssum = wave_reduce_sum(w);+ if (lane < topk)+ {+ float o;+ if (gating == 2) o = norm ? w / fmaxf(ssum, eps) : w;+ else o = norm ? w / (ssum + 1.0e-20f) : w / s_sum;+ sel[(size_t)blockIdx.x * topk + lane] = (int64_t)selidx[lane];+ wout[(size_t)blockIdx.x * topk + lane] = __float2half_rn(o * scale);+ }+ }+}++} // namespace++void gm_route(const at::Tensor& x, const at::Tensor& gate, const at::Tensor& bias, at::Tensor& scores, at::Tensor& sel, at::Tensor& w,+ int64_t gating, bool norm, double scale, double eps)+{+ TORCH_CHECK(x.is_cuda() && x.dim() == 2 && gate.is_cuda() && gate.dim() == 2 && x.is_contiguous() && gate.is_contiguous(), "gm_route: x [R, H] and gate [E, H] contiguous device tensors");+ const at::cuda::OptionalCUDAGuard guard(x.device());+ const int R = (int)x.size(0), H = (int)x.size(1), E = (int)gate.size(0), topk = (int)sel.size(1);+ TORCH_CHECK(R >= 1 && R <= MAX_ROUTER_ROWS && gate.size(1) == H && E <= 1024 && topk >= 1 && topk <= 32 && topk <= E, "gm_route: unsupported shape R=", R, " H=", H, " E=", E, " k=", topk);+ TORCH_CHECK(gating == 0 || gating == 2, "gm_route: gating 0 (softmax) or 2 (sigmoid)");+ TORCH_CHECK(sel.dtype() == at::kLong && w.dtype() == at::kHalf && scores.dtype() == at::kFloat && scores.numel() >= (int64_t)R * E && sel.size(0) == R && w.size(0) == R && w.size(1) == topk,+ "gm_route: sel int64 [R, k], w half [R, k], scores float scratch [R, E]");+ TORCH_CHECK(bias.numel() == 0 || (bias.dtype() == at::kFloat && bias.numel() == E && bias.is_contiguous()), "gm_route: bias float [E] or empty");+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ float* sp = scores.data_ptr<float>();+ const dim3 grid((E + 3) / 4, R);+ const bool xf = x.dtype() == at::kFloat, gf = gate.dtype() == at::kFloat;+ TORCH_CHECK((xf || x.dtype() == at::kHalf) && (gf || gate.dtype() == at::kHalf), "gm_route: x / gate float or half");+ #define GM_RT(XT, WT)hipLaunchKernelGGL(( gm_rt_logits_kernel<XT, WT>), dim3(grid), dim3(128), 0, stream, reinterpret_cast<const XT*>(x.data_ptr()), reinterpret_cast<const WT*>(gate.data_ptr()), sp, H, E)+ if (xf && gf) GM_RT(float, float); else if (xf) GM_RT(float, half); else if (gf) GM_RT(half, float); else GM_RT(half, half);+ #undef GM_RT+ const int nt = ((E + 31) / 32) * 32;+ hipLaunchKernelGGL(( gm_rt_topk_kernel), dim3(R), dim3(nt), 0, stream, sp, bias.numel() ? bias.data_ptr<float>() : nullptr, sel.data_ptr<int64_t>(), reinterpret_cast<half*>(w.data_ptr()),+ E, topk, (int)gating, norm ? 1 : 0, (float)scale, (float)eps);+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_route: launch failed");+}+#endif // USE_ROCMdiff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex cbbc761..23c914a 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -211,6 +211,21 @@ def _dq_q8_0_t(packed):# rows <= DENSE_MAXR run the extension GEMV (activation quantised to q8_1 inside, like llama.cpp), more rows dequantise per call (no resident fp32 copy).GG_DENSE = {8: (32, 34, "fq_gemv_q8_0", _dq_q8_0_t)}DENSE_MAXR = 16+GM_FFN = os.environ.get("HY4_GM_FFN", "0") == "1" # 1 = decode FFN (<= 8 rows) through the shared gm_ext ops: gm_route + one Q8_0 launch (rdown, shared gate, shared up) + gm_moe_kq_decode + rup / shared swiglu-down in one buffer+_GMX = []+++def _gm():+ if not _GMX:+ try:+ from .. import gm_ext+ _GMX.append(gm_ext.get())+ except Exception as ex: # noqa: BLE001+ print("hy4_forward: gm_ext unavailable:", repr(ex)[:160], flush=True)+ _GMX.append(None)+ return _GMX[0]++NO_ALIAS_LAT = os.environ.get("HY4_LAT_CLONE", "0") == "1" # 1 = copy the grouped MoE output before the rup matmul (old behaviour)DENSE_DQ = os.environ.get("HY4_DENSE_DQ", "0") == "1" # 1 = old path: dense matrices dequantised once to fp32 and kept resident@@ -539,6 +554,8 @@ class Hy4Forward:with tm.t("other"):return self._mm(torch.nn.functional.silu(self._mm(x, gt)) * self._mm(x, up), dn), NoneT, dev = x.shape[0], self.dev+ if self._gm_ok(i, L, x):+ return self._ffn_gm(i, L, x), Nonersp = self.res.get(i)pf = bool(PF_MOE and T > MMVQ_MAXR and dev.type == "cuda" and rsp is not None and rsp.fu in _pk().FROM_GROUPED and rsp.fd in _pk().FROM_GROUPED)with tm.t("router"):@@ -624,6 +641,48 @@ class Hy4Forward:sh = self._mm(torch.nn.functional.silu(self._mm(x, gt)) * self._mm(x, up), dn)return y + sh, lat+ def _gm_ok(self, i, L, x):+ """layer i FFN can run on the gm_ext ops: resident experts in a gm format, Q8_0 latent / shared matrices, 1..8 rows, no hooks"""+ if not GM_FFN or self.hook is not None or self.dev.type != "cuda" or i < self.n_dense or x.shape[0] > 8:+ return False+ rs = self.res.get(i)+ if rs is None or rs.fu not in (0, 8) or rs.fd not in (0, 2) or _gm() is None:+ return False+ return all(isinstance(q, QLinear) and q.ty == 8 for q in (L.rdown, L.rup, *L.shexp))++ def _ffn_gm(self, i, L, x):+ gm, rs, dev = _gm(), self.res[i], self.dev+ T, S = x.shape[0], self.topk+ w3 = getattr(L, "gm_w", None)+ if w3 is None:+ q8 = lambda q: q.packed.reshape(q.packed.shape[0], -1)+ w3 = L.gm_w = ([q8(L.rdown), q8(L.shexp[0]), q8(L.shexp[1])], [q8(L.rup)], q8(L.shexp[2]))+ N, D = L.rdown.shape[0], L.rup.shape[0]+ st = getattr(self, "_gms", None)+ if st is None:+ E = L.router.shape[0]+ st = self._gms = SimpleNamespace(+ sc=torch.empty(8, E, dtype=torch.float32, device=dev), sel=torch.empty(8, S, dtype=torch.int64, device=dev), w=torch.empty(8, S, dtype=torch.float16, device=dev),+ z3=torch.empty(8 * 3 * N, dtype=torch.float16, device=dev), qa=torch.empty(8 * max(x.shape[1], N) // 32 * 36, dtype=torch.uint8, device=dev),+ qm=torch.empty(8 * N // 32 * 36, dtype=torch.uint8, device=dev), act=torch.empty(8 * S, N, dtype=torch.float16, device=dev),+ part=torch.empty(8 * S, N, dtype=torch.float32, device=dev), lat=torch.empty(8, N, dtype=torch.float32, device=dev),+ meta=torch.zeros(8 * S * 9, dtype=torch.int32, device=dev), nometa=torch.empty(0, dtype=torch.int32, device=dev), nores=torch.empty(0, dtype=torch.float32, device=dev))+ sel, w = st.sel[:T], st.w[:T]+ xc = x.contiguous()+ gm.gm_route(xc, L.router, L.rbias, st.sc[:T], sel, w, 2, True, self.w_scale, 6.103515625e-5)+ z3 = st.z3[:3 * T * N]+ gm.gm_qkv_decode(xc, w3[0], [3, 3, 3], z3.view(1, -1), st.qa)+ z, g, u = z3[:T * N].view(T, N), z3[T * N:2 * T * N].view(T, N), z3[2 * T * N:].view(T, N)+ if T >= 2:+ st.meta.zero_()+ gm.gm_moe_kq_decode(z, sel.reshape(-1), w.reshape(-1), *rs.ptrs, *rs.strides[:3], rs.fd, st.act, st.qm, st.part, st.lat[:T], st.nores, rs.fu, float(self.clamp[i]),+ st.meta if T >= 2 else st.nometa)+ y = torch.empty(T, D, dtype=torch.float32, device=dev)+ gm.gm_qkv_decode(st.lat[:T], w3[1], [3], y.view(1, -1), st.qm)+ gm.gm_q8_swiglu_down(g, u, w3[2], y, True)+ self.stats["gm_ffn_calls"] = self.stats.get("gm_ffn_calls", 0) + 1+ return y+def _engram(self, i, x, ids, start):if os.environ.get("HY4_ENGRAM_GPU", "0") in ("1", "2") and self.dev.type == "cuda": # flag off: the old CPU path below, untouchedif i not in self.eng:diff --git a/tools/gguf_moe/hy4_ops_bench.py b/tools/gguf_moe/hy4_ops_bench.pynew file mode 100644index 0000000..0d17013--- /dev/null+++ b/tools/gguf_moe/hy4_ops_bench.py@@ -0,0 +1,51 @@+# hy4_ops_bench.py: gm_moe_kq_decode at Hy4 shapes (E=512 K=I=1536 S=16): stock vs gm plain vs gm expert-major, per layer ms (events, 50 reps); plus lim sensitivity check.+import os, sys, torch+sys.path.insert(0, os.environ.get("EXL3_ROOT", os.getcwd()))+torch.set_grad_enabled(False)+from exllamav3 import gm_ext+from exllamav3.ext import exllamav3_ext as ext+dev = "cuda:0"; gm = gm_ext.get(); g = torch.Generator(device=dev); g.manual_seed(3)+BB = {0: 144, 8: 110}+def rnd(lead, nblk, fmt):+ bb = BB[fmt]; t = torch.randint(0, 256, (*lead, nblk, bb), dtype=torch.uint8, device=dev, generator=g)+ t[..., (0 if fmt == 0 else 108):(2 if fmt == 0 else 110)] = (torch.rand(*lead, nblk, 1, device=dev, generator=g) * 0.02 + 0.001).half().view(torch.uint8)+ if fmt == 0: t[..., 2:4] = (torch.rand(*lead, nblk, 1, device=dev, generator=g) * 0.02).half().view(torch.uint8)+ return t.reshape(*lead, nblk * bb).contiguous()+E, K, I, S = 512, 1536, 1536, 16+def tm(f, n=40):+ for _ in range(5): f()+ torch.cuda.synchronize(); a = torch.cuda.Event(enable_timing=True); b = torch.cuda.Event(enable_timing=True); a.record()+ for _ in range(n): f()+ b.record(); torch.cuda.synchronize(); return a.elapsed_time(b) / n+for fu in (0, 8):+ gate, up, down = rnd((E, I), K // 256, fu), rnd((E, I), K // 256, fu), rnd((E, K), I // 256, 0)+ mk = lambda t: torch.tensor([t[e].data_ptr() for e in range(E)], dtype=torch.int64, device=dev)+ gp, upp, dpp = mk(gate), mk(up), mk(down); gs, ds = gate.shape[-1], down.shape[-1]+ for R in (1, 2, 4, 8):+ h = (torch.randn(R, K, device=dev) * 0.7).half()+ sel = torch.stack([torch.randperm(E, device=dev)[:S] for _ in range(R)]).long().contiguous()+ if R > 1: # Hy4 verify-like overlap: later rows share ~25 percent of the first row's experts+ for r in range(1, R): sel[r, :4] = sel[0, :4]+ wt = torch.softmax(torch.randn(R, S, device=dev), -1).half().contiguous()+ part = torch.empty(R * S, K, dtype=torch.float, device=dev); ref = torch.empty(R, K, dtype=torch.float, device=dev)+ act = torch.empty(8 * S, I, dtype=torch.half, device=dev); qb = torch.empty(8 * K // 32 * 36, dtype=torch.uint8, device=dev)+ pt = torch.empty(8 * S, K, dtype=torch.float, device=dev); out = torch.empty(R, K, dtype=torch.float, device=dev)+ meta = torch.zeros(8 * S * 9, dtype=torch.int32, device=dev); nometa = torch.empty(0, dtype=torch.int32, device=dev); nr = torch.empty(0, dtype=torch.float, device=dev)+ ext.fq_moe_kq_set_swiglu_limit(10.0)+ f_stock = lambda: ext.fq_moe_kq_grouped_mixed_q8(h, sel, wt, gp, upp, dpp, gs, gs, ds, fu, 0, part, ref)+ f_gm = lambda m: (lambda: gm.gm_moe_kq_decode(h, sel.reshape(-1), wt.reshape(-1), gp, upp, dpp, gs, gs, ds, 0, act, qb, pt, out, nr, fu, 10.0, m))+ wb = (len(set(sel.flatten().tolist())) * (2 * gs * I + ds * K))+ r = [f"gate/up fmt {fu} R={R}: distinct experts {len(set(sel.flatten().tolist()))}/{R * S}", f"stock {tm(f_stock):.3f} ms", f"gm plain {tm(f_gm(nometa)):.3f} ms"]+ if R > 1: r.append(f"gm expert-major {tm(f_gm(meta)):.3f} ms")+ r.append(f"(unique weight bytes {wb / 1e6:.0f} MB = {wb / 215e9 * 1e3:.3f} ms at 215 GB/s)")+ print(" " + " ".join(r), flush=True)+# clamp sensitivity: lim 0.3 must change the result vs 10, and equal the stock kernel+R = 2; h = (torch.randn(R, K, device=dev) * 0.7).half(); sel = torch.stack([torch.randperm(E, device=dev)[:S] for _ in range(R)]).long().contiguous(); wt = torch.softmax(torch.randn(R, S, device=dev), -1).half().contiguous()+part = torch.empty(R * S, K, dtype=torch.float, device=dev); res = {}+for lim in (0.0, 0.3, 10.0):+ ext.fq_moe_kq_set_swiglu_limit(lim); o = torch.empty(R, K, dtype=torch.float, device=dev)+ ext.fq_moe_kq_grouped_mixed_q8(h, sel, wt, gp, upp, dpp, gs, gs, ds, 8, 0, part, o); res[lim] = o+ act = torch.empty(8 * S, I, dtype=torch.half, device=dev); qb = torch.empty(8 * K // 32 * 36, dtype=torch.uint8, device=dev); pt = torch.empty(8 * S, K, dtype=torch.float, device=dev); o2 = torch.empty(R, K, dtype=torch.float, device=dev)+ gm.gm_moe_kq_decode(h, sel.reshape(-1), wt.reshape(-1), gp, upp, dpp, gs, gs, ds, 0, act, qb, pt, o2, torch.empty(0, device=dev), 8, lim, torch.empty(0, dtype=torch.int32, device=dev))+ print(f" lim {lim}: gm == stock {torch.equal(o, o2)}", flush=True)+print(" lim 0.3 differs from lim 0:", not torch.equal(res[0.0], res[0.3]))diff --git a/tools/gguf_moe/hy4_ops_test.py b/tools/gguf_moe/hy4_ops_test.pynew file mode 100644index 0000000..089b6db--- /dev/null+++ b/tools/gguf_moe/hy4_ops_test.py@@ -0,0 +1,118 @@+# hy4_ops_test.py: bit-exact checks of the Hy4 variants of the gm_ext decode ops against the stock fq kernels (Q3_K / Q4_K gate-up, routed clamp, expert-major+# order, Q8_0 projections, fused shared swiglu + down, generic router). Run under tools/gguf_moe/window.sh (GPU lock) with EXL3_GM_BUILD_DIR set.+import os, sys, torch+sys.path.insert(0, os.environ.get("EXL3_ROOT", os.getcwd()))+torch.set_grad_enabled(False)+from exllamav3 import gm_ext+from exllamav3.ext import exllamav3_ext as ext+dev = "cuda:0"; gm = gm_ext.get()+assert gm is not None+BB = {0: (144, 0), 8: (110, 108), 2: (210, 208), 3: (34, 0)} # fmt -> (block bytes, offset of the fp16 d)+def rnd(lead, nblk, fmt, g):+ bb, dp = BB[fmt]+ t = torch.randint(0, 256, (*lead, nblk, bb), dtype=torch.uint8, device=dev, generator=g)+ d = ((torch.rand(*lead, nblk, 1, device=dev, generator=g) * 0.02 + 0.001) * DS[0]).half().view(torch.uint8)+ t[..., dp:dp + 2] = d+ if fmt == 0: t[..., 2:4] = (torch.rand(*lead, nblk, 1, device=dev, generator=g) * 0.02 * DS[0]).half().view(torch.uint8)+ return t.reshape(*lead, nblk * bb).contiguous()+FID = {0: 0, 8: 8, 2: 2}+DS = [1.0]+ok_all = True+def report(name, a, b):+ global ok_all+ eq = torch.equal(a, b); ok_all &= eq+ print(f" {name}: {'BIT-EXACT' if eq else 'MISMATCH max diff %g, n diff %d' % ((a.float() - b.float()).abs().max().item(), (a != b).sum().item())}", flush=True)+g = torch.Generator(device=dev); g.manual_seed(1)++def moe_case(tag, E, K, I, S, fu, fd, lim, rows=(1, 2, 4, 8), pool=24):+ print(f"MoE {tag}: E={E} K={K} I={I} S={S} gate/up fmt {fu} down fmt {fd} lim {lim}", flush=True)+ gw = rnd((E, I), K // 256 * (1 if fu == 0 else 1), fu, g) if False else None+ nbu = K // 256; nbd = I // 256+ gate = rnd((E, I), nbu, fu, g); up = rnd((E, I), nbu, fu, g); down = rnd((E, K), nbd, fd, g)+ gs, ds = gate.shape[-1], down.shape[-1]+ mk = lambda t: torch.tensor([t[e].data_ptr() for e in range(E)], dtype=torch.int64, device=dev)+ gp, upp, dpp = mk(gate), mk(up), mk(down)+ for R in rows:+ torch.manual_seed(100 + R)+ h = (torch.randn(R, K, device=dev) * 0.7).half()+ sel = torch.stack([torch.randperm(E, device=dev)[:S] if pool is None else torch.randperm(pool, device=dev)[:S] for _ in range(R)]).long().contiguous()+ wt = torch.softmax(torch.randn(R, S, device=dev), -1).half().contiguous()+ part = torch.empty(R * S, K, dtype=torch.float, device=dev); ref = torch.empty(R, K, dtype=torch.float, device=dev)+ ext.fq_moe_kq_set_swiglu_limit(float(lim))+ ext.fq_moe_kq_grouped_mixed_q8(h, sel, wt.reshape(-1).contiguous() if False else wt, gp, upp, dpp, gs, gs, ds, FID[fu], FID[fd], part, ref)+ def run(meta):+ act = torch.empty(8 * S, I, dtype=torch.half, device=dev); qb = torch.empty(8 * K // 32 * 36, dtype=torch.uint8, device=dev)+ pt = torch.empty(8 * S, K, dtype=torch.float, device=dev); out = torch.empty(R, K, dtype=torch.float, device=dev)+ gm.gm_moe_kq_decode(h, sel.reshape(-1).contiguous(), wt.reshape(-1).contiguous(), gp, upp, dpp, gs, gs, ds, FID[fd], act, qb, pt, out,+ torch.empty(0, dtype=torch.float, device=dev), FID[fu], float(lim), meta)+ return out+ report(f"R={R} plain vs stock", run(torch.empty(0, dtype=torch.int32, device=dev)), ref)+ if R >= 2:+ meta = torch.zeros(8 * S * 9, dtype=torch.int32, device=dev)+ o = run(meta)+ nuniq = int((meta.view(-1, 9)[:, 0] > 0).sum())+ report(f"R={R} expert-major ({nuniq} distinct of {R * S}) vs stock", o, ref)+ del gate, up, down++moe_case("Hy4 Q4_K/Q4_K/Q4_K", 512, 1536, 1536, 16, 0, 0, 10.0)+moe_case("Hy4 Q3_K/Q3_K/Q4_K", 512, 1536, 1536, 16, 8, 0, 10.0)+moe_case("Q3_K no clamp", 512, 1536, 1536, 16, 8, 0, 0.0, rows=(1, 4))+DS[0] = 0.02+moe_case("Qwen3 Q4_K/Q4_K/Q6_K", 128, 2048, 768, 8, 0, 2, 0.0, pool=20)++print("Q8_0 projections", flush=True)+for K, Ns in ((3072, (1024, 576, 8192)), (1536, (3072,)), (3072, (1536, 1536))):+ for R in (1, 4):+ torch.manual_seed(7 + R)+ ws3 = [rnd((N,), K // 32, 3, g) for N in Ns]+ ws = [w.view(N, K // 32 * 34) for w, N in zip(ws3, Ns)]+ x = (torch.randn(R, K, device=dev) * 0.8).half()+ qb = torch.empty(R, K // 32 * 36, dtype=torch.uint8, device=dev); ext.fq_quant_q8_1_rows(x, qb)+ for od in (torch.half, torch.float):+ ref = torch.cat([(lambda o: (ext.fq_gemv_q8_0_q8(qb, w.view(N, K // 32, 34), o), o)[1])(torch.empty(R, N, dtype=od, device=dev)).reshape(-1) for w, N in zip(ws, Ns)])+ out = torch.empty(R * sum(Ns), dtype=od, device=dev); sc = torch.empty(8 * K // 32 * 36, dtype=torch.uint8, device=dev)+ gm.gm_qkv_decode(x, ws, [3] * len(ws), out.view(1, -1), sc)+ report(f"K={K} N={Ns} R={R} out {od} half-x", out, ref)+ xf = (torch.randn(R, K, device=dev) * 0.8)+ qbf = torch.empty(R, K // 32 * 36, dtype=torch.uint8, device=dev); ext.fq_quant_q8_1_rows(xf, qbf)+ ref = torch.cat([(lambda o: (ext.fq_gemv_q8_0_q8(qbf, w.view(N, K // 32, 34), o), o)[1])(torch.empty(R, N, dtype=torch.float, device=dev)).reshape(-1) for w, N in zip(ws, Ns)])+ out = torch.empty(R * sum(Ns), dtype=torch.float, device=dev)+ gm.gm_qkv_decode(xf, ws, [3] * len(ws), out.view(1, -1), sc)+ report(f"K={K} N={Ns} R={R} out float float-x", out, ref)++print("Q8_0 swiglu + down (+ accumulate)", flush=True)+I, N = 1536, 3072+for R in (1, 4):+ for gd in (torch.half, torch.float):+ wd = rnd((N,), I // 32, 3, g).view(N, I // 32 * 34)+ gg = (torch.randn(R, I, device=dev) * 2).to(gd); uu = (torch.randn(R, I, device=dev)).to(gd)+ act = ((1.0 / (1.0 + torch.exp(-gg.float()))) * gg.float() * uu.float()).half()+ qb = torch.empty(R, I // 32 * 36, dtype=torch.uint8, device=dev); ext.fq_quant_q8_1_rows(act, qb)+ ref = torch.empty(R, N, dtype=torch.float, device=dev); ext.fq_gemv_q8_0_q8(qb, wd.view(N, I // 32, 34), ref)+ out = torch.empty(R, N, dtype=torch.float, device=dev); gm.gm_q8_swiglu_down(gg, uu, wd, out, False)+ report(f"R={R} g/u {gd} overwrite", out, ref)+ base = torch.randn(R, N, device=dev); o2 = base.clone(); gm.gm_q8_swiglu_down(gg, uu, wd, o2, True)+ report(f"R={R} g/u {gd} accumulate", o2, base + ref)++print("Router", flush=True)+for (H, E, k, gating, norm, scale, xd, gd, bias) in ((3072, 512, 16, 2, True, 3.998, torch.float, torch.float, True), (3072, 512, 16, 2, True, 3.998, torch.half, torch.float, True),+ (2048, 128, 8, 0, True, 1.0, torch.half, torch.half, False), (2816, 128, 8, 0, False, 1.0, torch.half, torch.half, False),+ (2880, 32, 4, 0, True, 1.0, torch.half, torch.float, False), (2048, 64, 6, 2, True, 1.8, torch.half, torch.float, True)):+ for R in (1, 4, 8):+ x = (torch.randn(R, H, device=dev) * 1.0).to(xd); gate = (torch.randn(E, H, device=dev) * 0.05).to(gd)+ b = (torch.randn(E, device=dev) * 0.1) if bias else torch.empty(0, device=dev)+ sc = torch.empty(R, E, dtype=torch.float, device=dev); sel = torch.empty(R, k, dtype=torch.long, device=dev); w = torch.empty(R, k, dtype=torch.half, device=dev)+ gm.gm_route(x.contiguous(), gate.contiguous(), b, sc, sel, w, gating, norm, scale, 6.103515625e-5)+ lg = x.float() @ gate.float().T+ if gating == 2:+ p = torch.sigmoid(lg); key = p + (b if bias else 0)+ rs = torch.sort(key, dim=-1, descending=True, stable=True).indices[:, :k]; rw = torch.gather(p, 1, rs)+ if norm: rw = rw / rw.sum(-1, keepdim=True).clamp(min=6.103515625e-5)+ else:+ p = torch.softmax(lg, -1); rs = torch.sort(p, dim=-1, descending=True, stable=True).indices[:, :k]; rw = torch.gather(p, 1, rs)+ if norm: rw = rw / rw.sum(-1, keepdim=True)+ rw = rw * scale+ same = torch.equal(sel, rs); err = ((w.float() - rw).abs() / rw.abs().clamp(min=1e-6)).max().item()+ ok_all &= same and err < 2e-3+ print(f" H={H} E={E} k={k} gating={gating} norm={norm} R={R} x={xd} gate={gd}: sel {'same' if same else 'DIFFERENT'}, max rel w err {err:.2e}", flush=True)+print("ALL BIT-EXACT / OK" if ok_all else "SOME CHECKS FAILED")