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: copy the shared gm_ext (box gguf-moe tree 72376c9) and the HY4_MOE_HIP=2 prefill hook (box c82c76c)
YanissAmz044d89f26d06
diff --git a/exllamav3/exllamav3_ext/hip_kq/build_moe.sh b/exllamav3/exllamav3_ext/hip_kq/build_moe.shnew file mode 100644index 0000000..a130ec6--- /dev/null+++ b/exllamav3/exllamav3_ext/hip_kq/build_moe.sh@@ -0,0 +1,10 @@+#!/bin/bash+# build_moe.sh SRC.cu OUT.co : device-only code object for gfx1151 with the SDK toolchain that matches torch (build-only env, separate process)+SRC=$1; OUT=$2+ENG=${KYOJIN_ENGINE_DIR:-$PWD}+SDK=$(PATH=$ENG/.venv/bin:$PATH rocm-sdk path --root)+GCCD=$(dirname "$(gcc -print-libgcc-file-name)")+BC=$SDK/lib/llvm/amdgcn/bitcode; [ -d $BC ] || BC=$SDK/amdgcn/bitcode+export ROCM_PATH=$SDK HIP_PATH=$SDK+$SDK/bin/hipcc -x hip --offload-arch=gfx1151 --offload-device-only -O3 -std=c++17 --gcc-install-dir=$GCCD --rocm-device-lib-path=$BC --rocm-path=$SDK -save-temps=obj -Rpass-analysis=kernel-resource-usage "$SRC" -o "$OUT" 2>&1 | grep -E "error|warning: |VGPRs|Spill|SGPRs|LDS|Occupancy|Function Name" | head -40+ls -la "$OUT"diff --git a/exllamav3/gm_ext/__init__.py b/exllamav3/gm_ext/__init__.pynew file mode 100644index 0000000..e40c3c3--- /dev/null+++ b/exllamav3/gm_ext/__init__.py@@ -0,0 +1,35 @@+"""Small JIT-built extension beside the big exllamav3_ext (generic GGUF MoE decode kernels). get() returns the module or None.+Build: EXL3_GM_BUILD=1 python -c "from exllamav3 import gm_ext; gm_ext.get()" under tools/strix_halo/env.sh build. Loading a built one needs no compiler."""+import os, glob+_mod = None+_tried = False+_DIR = os.path.dirname(os.path.abspath(__file__))+_NAME = "exl3_gm_ext"+++def get():+ global _mod, _tried+ if _tried:+ return _mod+ _tried = True+ if os.environ.get("EXL3_GM", "1") == "0":+ return None+ build = os.environ.get("EXL3_GM_BUILD_DIR", os.path.join(os.path.expanduser("~"), ".cache", "exl3_gm_ext"))+ so = glob.glob(os.path.join(build, _NAME + "*.so"))+ try:+ import torch+ if so and os.environ.get("EXL3_GM_BUILD", "0") != "1":+ import importlib.util+ spec = importlib.util.spec_from_file_location(_NAME, so[0])+ _mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(_mod)+ elif os.environ.get("EXL3_GM_BUILD", "0") == "1":+ from torch.utils.cpp_extension import load+ os.makedirs(build, exist_ok=True)+ srcs = sorted(glob.glob(os.path.join(_DIR, "*.cu")) + glob.glob(os.path.join(_DIR, "*.cpp")))+ _mod = load(name=_NAME, sources=srcs, extra_include_paths=[_DIR],+ extra_cflags=["-O3", "-DUSE_ROCM"], extra_cuda_cflags=["-O3", "-DUSE_ROCM"], build_directory=build, verbose=True)+ except Exception as e: # missing build or toolchain: callers fall back to the stock path+ print(f"[gm_ext] unavailable: {e}")+ _mod = None+ return _moddiff --git a/exllamav3/gm_ext/gm_bindings.cpp b/exllamav3/gm_ext/gm_bindings.cppnew file mode 100644index 0000000..7459231--- /dev/null+++ b/exllamav3/gm_ext/gm_bindings.cpp@@ -0,0 +1,12 @@+#include <torch/extension.h>+#include <pybind11/stl.h>+#include "gm_router.cuh"+#include "gm_moe.cuh"+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_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.cuhnew file mode 100644index 0000000..689817f--- /dev/null+++ b/exllamav3/gm_ext/gm_kq_item.cuh@@ -0,0 +1,109 @@+// (copy of foreign_quant/fq_kq_item.cuh without the Q5_K item) Q4_K / Q6_K v2 "items" (one thread, one aligned wide load pair = 4 consecutive v1 sub-chunk values), shared by the dense+// rows GEMV (fq_gemv_kq.cu) and the grouped MoE gate+up (fq_moe_kq.cu). Include after fq_gemv.cuh, inside no namespace.+#pragma once+#include <cstdint>+#include <cstring>+#include <hip/hip_fp16.h>++namespace {++__device__ __forceinline__ float fq_h2f_lo(uint32_t w)+{+ uint16_t lo = (uint16_t)(w & 0xFFFFu);+ __half h;+ memcpy(&h, &lo, 2);+ return __half2float(h);+}++__device__ __forceinline__ uint32_t fq_ld_u16x2(const uint8_t* __restrict__ p) // p is 2-byte aligned+{+ const uint16_t* q = reinterpret_cast<const uint16_t*>(p);+ return (uint32_t)q[0] | ((uint32_t)q[1] << 16);+}++// Q4_K item: 256-block b = it >> 2, group g = it & 3 (qs bytes 32g .. 32g+31: low nibbles = sub-block 2g,+// high nibbles = sub-block 2g+1). dst[qo] = v1 chunk value c = 16 b + 4 g + qo, qo = 0..3.+__device__ __forceinline__ void fq_kq_item_q4_k(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aq,+ int it, float* __restrict__ dst)+{+ const int b = it >> 2, g = it & 3;+ const uint8_t* blk = wr + (size_t)b * FQ_Q4_K_BYTES; // 144 B: 16-byte aligned rows+ const uint32_t hd = *reinterpret_cast<const uint32_t*>(blk); // d | dmin+ const uint32_t* sp = reinterpret_cast<const uint32_t*>(blk + 4);+ const uint32_t sw0 = sp[0], sw1 = sp[1], sw2 = sp[2];+ const uint4 va = *reinterpret_cast<const uint4*>(blk + 16 + 32 * g);+ const uint4 vb = *reinterpret_cast<const uint4*>(blk + 16 + 32 * g + 16);+ const int32_t* a0 = reinterpret_cast<const int32_t*>(aq + (size_t)(b * 8 + 2 * g) * FQ_Q8_1_BYTES);+ const int32_t* a1 = a0 + FQ_Q8_1_BYTES / 4;+ const float dm0 = fq_h2f_lo(hd);+ const float dm1 = fq_h2f_lo(hd >> 16);+ const float d8[2] = {fq_h2f_lo((uint32_t)a0[0]), fq_h2f_lo((uint32_t)a1[0])};+ // scales / mins of sub-blocks 2g, 2g+1 (verbatim fq_q4k_scales on the three u16 words it reads)+ const int sh = 16 * (g & 1);+ const uint32_t s0 = (sw0 >> sh) & 0xFFFFu, s2 = (sw1 >> sh) & 0xFFFFu, s4 = (sw2 >> sh) & 0xFFFFu;+ const uint32_t hi = (g >= 2) ? 0xFFFFFFFFu : 0u;+ const uint16_t aux0 = (uint16_t)(((s0 & 0x3F3Fu) & ~hi) | ((((s4 >> 0) & 0x0F0Fu) | ((s0 & 0xC0C0u) >> 2)) & hi));+ const uint16_t aux1 = (uint16_t)(((s2 & 0x3F3Fu) & ~hi) | ((((s4 >> 4) & 0x0F0Fu) | ((s2 & 0xC0C0u) >> 2)) & hi));+ const int sc[2] = {(int)(aux0 & 0xFFu), (int)((aux0 >> 8) & 0xFFu)};+ const int mn[2] = {(int)(aux1 & 0xFFu), (int)((aux1 >> 8) & 0xFFu)};+ const uint32_t w0[4] = {va.x, va.y, va.z, va.w};+ const uint32_t w1[4] = {vb.x, vb.y, vb.z, vb.w};+ #pragma unroll+ for (int qo = 0; qo < 4; qo++)+ {+ float sumf_d = 0.0f, sumf_m = 0.0f;+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ const int32_t* a = i ? a1 : a0;+ const uint32_t v0i = (w0[qo] >> (4 * i)) & 0x0F0F0F0Fu;+ const uint32_t v1i = (w1[qo] >> (4 * i)) & 0x0F0F0F0Fu;+ const int32_t u0 = a[1 + qo], u1 = a[5 + qo];+ int dot1 = fq_dp4a((int32_t)v0i, u0, 0);+ dot1 = fq_dp4a((int32_t)v1i, u1, dot1);+ int dot2 = fq_dp4a(0x01010101, u0, 0);+ dot2 = fq_dp4a(0x01010101, u1, dot2);+ sumf_d = __fadd_rn(sumf_d, __fmul_rn(d8[i], (float)(dot1 * sc[i])));+ sumf_m = __fadd_rn(sumf_m, __fmul_rn(d8[i], (float)(dot2 * mn[i])));+ }+ dst[qo] = __fadd_rn(__fmul_rn(dm0, sumf_d), -__fmul_rn(dm1, sumf_m));+ }+}++// Q6_K item: 256-block b = it >> 3, lane p = it & 7; the four v1 chunks iqs = p + 8 q (q = 0..3) of that block,+// c = 32 b + p + 8 q. dst[q] = value of chunk q.+__device__ __forceinline__ void fq_kq_item_q6_k(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aq,+ int it, float* __restrict__ dst)+{+ const int b = it >> 3, p = it & 7;+ const uint8_t* blk = wr + (size_t)b * FQ_Q6_K_BYTES; // 210 B: 2-byte aligned only+ uint32_t vl[4];+ #pragma unroll+ for (int q = 0; q < 4; q++)+ vl[q] = fq_ld_u16x2(blk + 4 * p + 32 * q);+ const uint32_t vhw[2] = {fq_ld_u16x2(blk + 128 + 4 * p), fq_ld_u16x2(blk + 128 + 32 + 4 * p)};+ const int8_t* scl = reinterpret_cast<const int8_t*>(blk + 192);+ const float d = fq_h2f_lo((uint32_t)*reinterpret_cast<const uint16_t*>(blk + 208));+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ const int sc_off = 8 * (q >> 1) + (p >> 2) + 2 * (q & 1);+ const int bq8_off = 4 * (q >> 1) + (q & 1);+ const uint32_t vh = vhw[q >> 1] >> (2 * (q & 1));+ float sumf = 0.0f;+ #pragma unroll+ for (int i = 0; i < 2; i++)+ {+ const int scc = (int)scl[sc_off + 4 * i];+ const uint32_t vil = (vl[q] >> (4 * i)) & 0x0F0F0F0Fu;+ const uint32_t vih = ((vh >> (4 * i)) << 4) & 0x30303030u;+ const uint32_t vi = fq_vsub4(vil | vih, 0x20202020u);+ const int32_t* a = reinterpret_cast<const int32_t*>(aq + (size_t)(b * 8 + bq8_off + 2 * i) * FQ_Q8_1_BYTES);+ const float d8 = fq_h2f_lo((uint32_t)a[0]);+ sumf = __fadd_rn(sumf, __fmul_rn(d8, (float)(fq_dp4a((int32_t)vi, a[1 + p], 0) * scc)));+ }+ dst[q] = __fmul_rn(d, sumf);+ }+}++} // namespacediff --git a/exllamav3/gm_ext/gm_moe.cu b/exllamav3/gm_ext/gm_moe.cunew file mode 100644index 0000000..c501fea--- /dev/null+++ b/exllamav3/gm_ext/gm_moe.cu@@ -0,0 +1,379 @@+// Generic GGUF MoE decode, one token (R = 1): Q4_K gate/up experts, Q4_K / Q6_K down experts, SwiGLU, no shared expert.+// Same arithmetic as exllamav3_ext/foreign_quant/fq_moe_kq.cu (fq_moe_kq_upgate_v2_kernel, fq_moe_kq_down_v2_kernel, fq_moe_kq_combine_kernel,+// fq_quant_q8_1_kernel): bit-identical results, fewer launches. What changes:+// - the q8_1 quantization of the SwiGLU activation moves into the down kernel (each block quantizes the I values of its slot into shared memory);+// - the weighted fold also adds the result into the residual stream (the `x += y` of the transformer block).+// 6 launches (quant, upgate, quant, down, combine, add) -> 4 (quant, upgate, down, combine + add).+#if defined(USE_ROCM)++#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>+#include <ATen/cuda/CUDAContext.h>+#include <c10/cuda/CUDAGuard.h>+#include <torch/extension.h>+#include <cstdint>+#include <cstring>+#include <vector>+#include <type_traits>++#define FQ_Q8_1_BYTES 36+#define FQ_Q4_K_BYTES 144+#define FQ_Q6_K_BYTES 210++__device__ __forceinline__ int fq_dp4a(int a, int b, int c)+{+#if defined(__HIP_DEVICE_COMPILE__) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \+ defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) || defined(__gfx1200__) || defined(__gfx1201__))+ return __builtin_amdgcn_sudot4(true, a, true, b, c, false);+#else+ const int8_t* a8 = reinterpret_cast<const int8_t*>(&a);+ const int8_t* b8 = reinterpret_cast<const int8_t*>(&b);+ return c + (int)a8[0] * (int)b8[0] + (int)a8[1] * (int)b8[1] + (int)a8[2] * (int)b8[2] + (int)a8[3] * (int)b8[3];+#endif+}++__device__ __forceinline__ uint32_t fq_vsub4(uint32_t a, uint32_t b)+{+ uint32_t v = 0;+ #pragma unroll+ for (int m = 0; m < 4; m++)+ v |= (((((a >> (8 * m)) & 0xFFu) - ((b >> (8 * m)) & 0xFFu)) & 0xFFu) << (8 * m));+ return v;+}++#include "gm_kq_item.cuh"++namespace {++constexpr int GM_ROWS = 32; // output rows per block (8 threads per row)+constexpr int GM_PS = 33;+constexpr int GM_MAX_NB = 128; // q8_1 blocks of the activation held in shared memory: I <= 4096++// One q8_1 block (32 values) by one thread, the arithmetic of fq_quant_q8_1_kernel: d = amax / 127, q = round-half-away(v / d), sum in index order.+__device__ __forceinline__ void gm_quant_block(const __half* __restrict__ x, uint8_t* __restrict__ dst)+{+ float v[32];+ float amax = 0.0f;+ #pragma unroll+ for (int i = 0; i < 32; i++) { v[i] = __half2float(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_kernel(const __half* __restrict__ x, uint8_t* __restrict__ qb, int nb32)+{+ const int b = blockIdx.x * blockDim.x + threadIdx.x;+ if (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+// 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,+ 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)+{+ __shared__ float pg[GM_ROWS * GM_PS];+ __shared__ float pu[GM_ROWS * GM_PS];+ const int s = blockIdx.x / ntiles;+ const int t = blockIdx.x % ntiles;+ 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)+ {+ 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 l = 0; l < 32; l++)+ {+ sg = __fadd_rn(sg, pg[r * GM_PS + l]);+ su = __fadd_rn(su, pu[r * GM_PS + l]);+ }+ 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);+ }+}++// 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,+ 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 t = blockIdx.x % ntiles;+ 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];+ 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)+ {+ 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;+ }+}++// Weighted fold of the S slots (fq_moe_kq_combine_kernel), plus resid += out when resid != nullptr (torch's `x += y`: float add, rounded to the residual dtype).+template <typename RES_T>+__global__ void gm_combine_kernel(const float* __restrict__ partial, const __half* __restrict__ wts, float* __restrict__ out,+ RES_T* __restrict__ resid, int S, int K)+{+ const int k = blockIdx.x * blockDim.x + threadIdx.x;+ if (k >= K) return;+ const int row = blockIdx.y; // token row: S slots of partial / wts, K outputs+ partial += (int64_t)row * S * K; wts += (int64_t)row * S; out += (int64_t)row * K;+ if (resid != nullptr) resid += (int64_t)row * K;+ float acc = 0.0f;+ for (int s = 0; s < S; s++)+ acc = __fadd_rn(acc, __fmul_rn(partial[(int64_t)s * K + k], __half2float(wts[s])));+ out[k] = acc;+ if (resid != nullptr)+ {+ if constexpr (std::is_same<RES_T, float>::value) resid[k] = resid[k] + acc;+ else resid[k] = __float2half_rn(__half2float(resid[k]) + acc);+ }+}++} // 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).+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)+{+ 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)");+ const at::cuda::OptionalCUDAGuard guard(h.device());+ const int K = (int)h.size(1);+ const int R = (int)h.size(0);+ TORCH_CHECK(sel.numel() % R == 0, "gm_moe_kq_decode: sel must hold R rows of top-k");+ const int S = (int)(sel.numel() / R); // slots per row+ const int SR = R * S; // all slots+ const 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(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");+ 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;+ __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);+ 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);+ 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);+ const __half* wp = reinterpret_cast<const __half*>(wts.data_ptr());+ float* outp = reinterpret_cast<float*>(out.data_ptr());+ const int cb = (K + 255) / 256;+ if (resid.numel() == 0)+ gm_combine_kernel<float><<<dim3(cb, R), 256, 0, stream>>>(partp, wp, outp, nullptr, S, K);+ else if (resid.dtype() == at::kFloat)+ gm_combine_kernel<float><<<dim3(cb, R), 256, 0, stream>>>(partp, wp, outp, reinterpret_cast<float*>(resid.data_ptr()), S, K);+ else+ {+ TORCH_CHECK(resid.dtype() == at::kHalf, "gm_moe_kq_decode: resid must be float or half");+ gm_combine_kernel<__half><<<dim3(cb, R), 256, 0, stream>>>(partp, wp, outp, reinterpret_cast<__half*>(resid.data_ptr()), S, K);+ }+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_moe_kq_decode: launch failed");+}++// ---------------------------------------------------------------------------------------------------------------------------------+// q, k and v projections of one decode row in ONE launch (plus one q8_1 quantization): Q4_K / Q6_K rows, one row per 64-thread block,+// the arithmetic of fq_gemv_kq_rows_kernel<half, FMT, 1> (nt = number of v1 lane partials, as fq_kq_nt(K, 16)).+// The three matrices share the grid (blocks 0..N0-1 = matrix 0, ...), so the small k / v matrices run beside the large q one.+// ---------------------------------------------------------------------------------------------------------------------------------+struct Gm3+{+ const uint8_t* w[3];+ __half* out[3];+ int64_t stride[3];+ int N[3];+ int fmt[3];+ int R;+};++__global__ void __launch_bounds__(64) gm_gemv3_kernel(Gm3 a, const uint8_t* __restrict__ aqb, int K, int nt4, int nt6)+{+ __shared__ __align__(16) float part[260];+ 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 j = threadIdx.x;+ const uint8_t* wr = a.w[mi] + (int64_t)blk * a.stride[mi];+ const int f = a.fmt[mi];+ const int nt = (f == 0) ? nt4 : nt6; // fq_kq_nt(K, 16) for Q4_K, fq_kq_nt(K, 8) for Q6_K+ float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ if (f == 0)+ {+ const int nitems = (K / 256) * 4;+ for (int it = j; it < nitems; it += 64)+ {+ float t[4];+ fq_kq_item_q4_k(wr, aqb, it, t);+ #pragma unroll+ for (int q = 0; q < 4; q++) acc[q] = __fadd_rn(acc[q], t[q]);+ }+ }+ else+ {+ const int nitems = (K / 256) * 8;+ for (int it = j; it < nitems; it += 64)+ {+ float t[4];+ fq_kq_item_q6_k(wr, aqb, it, t);+ #pragma unroll+ for (int q = 0; q < 4; q++) acc[q] = __fadd_rn(acc[q], t[q]);+ }+ }+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ const int lane = (f == 0) ? (4 * j + q) : (32 * (j >> 3) + (j & 7) + 8 * q);+ if (lane < nt) part[lane] = acc[q];+ }+ __syncthreads();+ if (j == 0)+ {+ const float4* pv = reinterpret_cast<const float4*>(part);+ float s = 0.0f;+ #pragma unroll 8+ for (int l = 0; l < nt / 4; l++)+ {+ const float4 v = pv[l];+ s = __fadd_rn(s, v.x);+ s = __fadd_rn(s, v.y);+ s = __fadd_rn(s, v.z);+ s = __fadd_rn(s, v.w);+ }+ a.out[mi][(int64_t)row * a.N[mi] + blk] = __float2half_rn(s);+ }+}++// 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");+ 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");+ 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");+ 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;+ TORCH_CHECK((reinterpret_cast<uintptr_t>(ws[i].data_ptr()) & am) == 0 && (rb & am) == 0, "gm_qkv_decode: unaligned weights");+ a.w[i] = reinterpret_cast<const uint8_t*>(ws[i].data_ptr());+ a.stride[i] = rb;+ a.N[i] = (int)ws[i].size(0);+ a.fmt[i] = (int)fmts[i];+ a.out[i] = o + (int64_t)R * total; // q, k, v blocks one after the other, each [R, N_i] contiguous (R = 1: the old layout)+ total += a.N[i];+ }+ a.R = R;+ TORCH_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);+ gm_gemv3_kernel<<<dim3(total, R), 64, 0, stream>>>(a, qbp, K, nt4, nt6);+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_qkv_decode: launch failed");+}++#endif // USE_ROCMdiff --git a/exllamav3/gm_ext/gm_moe.cuh b/exllamav3/gm_ext/gm_moe.cuhnew file mode 100644index 0000000..df7b277--- /dev/null+++ b/exllamav3/gm_ext/gm_moe.cuh@@ -0,0 +1,14 @@+#pragma once+#if defined(USE_ROCM)+#include <ATen/Tensor.h>+#include <vector>+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);+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);+void gm_pf_down(const at::Tensor& H, const at::Tensor& down_ptrs, const at::Tensor& wts, const at::Tensor& sp, const at::Tensor& be, at::Tensor& out,+ int64_t P, int64_t E, int64_t K, int64_t N, int64_t rowb, int64_t fmt, int64_t maxb);+#endifdiff --git a/exllamav3/gm_ext/gm_moe.hip b/exllamav3/gm_ext/gm_moe.hipnew file mode 100644index 0000000..9554d28--- /dev/null+++ b/exllamav3/gm_ext/gm_moe.hip@@ -0,0 +1,380 @@+// !!! This is a file automatically generated by hipify!!!+// Generic GGUF MoE decode, one token (R = 1): Q4_K gate/up experts, Q4_K / Q6_K down experts, SwiGLU, no shared expert.+// Same arithmetic as exllamav3_ext/foreign_quant/fq_moe_kq.cu (fq_moe_kq_upgate_v2_kernel, fq_moe_kq_down_v2_kernel, fq_moe_kq_combine_kernel,+// fq_quant_q8_1_kernel): bit-identical results, fewer launches. What changes:+// - the q8_1 quantization of the SwiGLU activation moves into the down kernel (each block quantizes the I values of its slot into shared memory);+// - the weighted fold also adds the result into the residual stream (the `x += y` of the transformer block).+// 6 launches (quant, upgate, quant, down, combine, add) -> 4 (quant, upgate, down, combine + add).+#if defined(USE_ROCM)++#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>+#include <ATen/hip/HIPContext.h>+#include <c10/hip/HIPGuard.h>+#include <torch/extension.h>+#include <cstdint>+#include <cstring>+#include <vector>+#include <type_traits>++#define FQ_Q8_1_BYTES 36+#define FQ_Q4_K_BYTES 144+#define FQ_Q6_K_BYTES 210++__device__ __forceinline__ int fq_dp4a(int a, int b, int c)+{+#if defined(__HIP_DEVICE_COMPILE__) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \+ defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) || defined(__gfx1200__) || defined(__gfx1201__))+ return __builtin_amdgcn_sudot4(true, a, true, b, c, false);+#else+ const int8_t* a8 = reinterpret_cast<const int8_t*>(&a);+ const int8_t* b8 = reinterpret_cast<const int8_t*>(&b);+ return c + (int)a8[0] * (int)b8[0] + (int)a8[1] * (int)b8[1] + (int)a8[2] * (int)b8[2] + (int)a8[3] * (int)b8[3];+#endif+}++__device__ __forceinline__ uint32_t fq_vsub4(uint32_t a, uint32_t b)+{+ uint32_t v = 0;+ #pragma unroll+ for (int m = 0; m < 4; m++)+ v |= (((((a >> (8 * m)) & 0xFFu) - ((b >> (8 * m)) & 0xFFu)) & 0xFFu) << (8 * m));+ return v;+}++#include "gm_kq_item.cuh"++namespace {++constexpr int GM_ROWS = 32; // output rows per block (8 threads per row)+constexpr int GM_PS = 33;+constexpr int GM_MAX_NB = 128; // q8_1 blocks of the activation held in shared memory: I <= 4096++// One q8_1 block (32 values) by one thread, the arithmetic of fq_quant_q8_1_kernel: d = amax / 127, q = round-half-away(v / d), sum in index order.+__device__ __forceinline__ void gm_quant_block(const __half* __restrict__ x, uint8_t* __restrict__ dst)+{+ float v[32];+ float amax = 0.0f;+ #pragma unroll+ for (int i = 0; i < 32; i++) { v[i] = __half2float(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_kernel(const __half* __restrict__ x, uint8_t* __restrict__ qb, int nb32)+{+ const int b = blockIdx.x * blockDim.x + threadIdx.x;+ if (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+// 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,+ 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)+{+ __shared__ float pg[GM_ROWS * GM_PS];+ __shared__ float pu[GM_ROWS * GM_PS];+ const int s = blockIdx.x / ntiles;+ const int t = blockIdx.x % ntiles;+ 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)+ {+ 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 l = 0; l < 32; l++)+ {+ sg = __fadd_rn(sg, pg[r * GM_PS + l]);+ su = __fadd_rn(su, pu[r * GM_PS + l]);+ }+ 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);+ }+}++// 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,+ 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 t = blockIdx.x % ntiles;+ 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];+ 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)+ {+ 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;+ }+}++// Weighted fold of the S slots (fq_moe_kq_combine_kernel), plus resid += out when resid != nullptr (torch's `x += y`: float add, rounded to the residual dtype).+template <typename RES_T>+__global__ void gm_combine_kernel(const float* __restrict__ partial, const __half* __restrict__ wts, float* __restrict__ out,+ RES_T* __restrict__ resid, int S, int K)+{+ const int k = blockIdx.x * blockDim.x + threadIdx.x;+ if (k >= K) return;+ const int row = blockIdx.y; // token row: S slots of partial / wts, K outputs+ partial += (int64_t)row * S * K; wts += (int64_t)row * S; out += (int64_t)row * K;+ if (resid != nullptr) resid += (int64_t)row * K;+ float acc = 0.0f;+ for (int s = 0; s < S; s++)+ acc = __fadd_rn(acc, __fmul_rn(partial[(int64_t)s * K + k], __half2float(wts[s])));+ out[k] = acc;+ if (resid != nullptr)+ {+ if constexpr (std::is_same<RES_T, float>::value) resid[k] = resid[k] + acc;+ else resid[k] = __float2half_rn(__half2float(resid[k]) + acc);+ }+}++} // 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).+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)+{+ 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)");+ const at::cuda::OptionalCUDAGuard guard(h.device());+ const int K = (int)h.size(1);+ const int R = (int)h.size(0);+ TORCH_CHECK(sel.numel() % R == 0, "gm_moe_kq_decode: sel must hold R rows of top-k");+ const int S = (int)(sel.numel() / R); // slots per row+ const int SR = R * S; // all slots+ const 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(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");+ 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;+ __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);+ 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);+ 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);+ const __half* wp = reinterpret_cast<const __half*>(wts.data_ptr());+ float* outp = reinterpret_cast<float*>(out.data_ptr());+ const int cb = (K + 255) / 256;+ if (resid.numel() == 0)+ hipLaunchKernelGGL(( gm_combine_kernel<float>), dim3(dim3(cb, R)), dim3(256), 0, stream, partp, wp, outp, nullptr, S, K);+ else if (resid.dtype() == at::kFloat)+ hipLaunchKernelGGL(( gm_combine_kernel<float>), dim3(dim3(cb, R)), dim3(256), 0, stream, partp, wp, outp, reinterpret_cast<float*>(resid.data_ptr()), S, K);+ else+ {+ TORCH_CHECK(resid.dtype() == at::kHalf, "gm_moe_kq_decode: resid must be float or half");+ hipLaunchKernelGGL(( gm_combine_kernel<__half>), dim3(dim3(cb, R)), dim3(256), 0, stream, partp, wp, outp, reinterpret_cast<__half*>(resid.data_ptr()), S, K);+ }+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_moe_kq_decode: launch failed");+}++// ---------------------------------------------------------------------------------------------------------------------------------+// q, k and v projections of one decode row in ONE launch (plus one q8_1 quantization): Q4_K / Q6_K rows, one row per 64-thread block,+// the arithmetic of fq_gemv_kq_rows_kernel<half, FMT, 1> (nt = number of v1 lane partials, as fq_kq_nt(K, 16)).+// The three matrices share the grid (blocks 0..N0-1 = matrix 0, ...), so the small k / v matrices run beside the large q one.+// ---------------------------------------------------------------------------------------------------------------------------------+struct Gm3+{+ const uint8_t* w[3];+ __half* out[3];+ int64_t stride[3];+ int N[3];+ int fmt[3];+ int R;+};++__global__ void __launch_bounds__(64) gm_gemv3_kernel(Gm3 a, const uint8_t* __restrict__ aqb, int K, int nt4, int nt6)+{+ __shared__ __align__(16) float part[260];+ 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 j = threadIdx.x;+ const uint8_t* wr = a.w[mi] + (int64_t)blk * a.stride[mi];+ const int f = a.fmt[mi];+ const int nt = (f == 0) ? nt4 : nt6; // fq_kq_nt(K, 16) for Q4_K, fq_kq_nt(K, 8) for Q6_K+ float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ if (f == 0)+ {+ const int nitems = (K / 256) * 4;+ for (int it = j; it < nitems; it += 64)+ {+ float t[4];+ fq_kq_item_q4_k(wr, aqb, it, t);+ #pragma unroll+ for (int q = 0; q < 4; q++) acc[q] = __fadd_rn(acc[q], t[q]);+ }+ }+ else+ {+ const int nitems = (K / 256) * 8;+ for (int it = j; it < nitems; it += 64)+ {+ float t[4];+ fq_kq_item_q6_k(wr, aqb, it, t);+ #pragma unroll+ for (int q = 0; q < 4; q++) acc[q] = __fadd_rn(acc[q], t[q]);+ }+ }+ #pragma unroll+ for (int q = 0; q < 4; q++)+ {+ const int lane = (f == 0) ? (4 * j + q) : (32 * (j >> 3) + (j & 7) + 8 * q);+ if (lane < nt) part[lane] = acc[q];+ }+ __syncthreads();+ if (j == 0)+ {+ const float4* pv = reinterpret_cast<const float4*>(part);+ float s = 0.0f;+ #pragma unroll 8+ for (int l = 0; l < nt / 4; l++)+ {+ const float4 v = pv[l];+ s = __fadd_rn(s, v.x);+ s = __fadd_rn(s, v.y);+ s = __fadd_rn(s, v.z);+ s = __fadd_rn(s, v.w);+ }+ a.out[mi][(int64_t)row * a.N[mi] + blk] = __float2half_rn(s);+ }+}++// 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");+ 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");+ 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");+ 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;+ TORCH_CHECK((reinterpret_cast<uintptr_t>(ws[i].data_ptr()) & am) == 0 && (rb & am) == 0, "gm_qkv_decode: unaligned weights");+ a.w[i] = reinterpret_cast<const uint8_t*>(ws[i].data_ptr());+ a.stride[i] = rb;+ a.N[i] = (int)ws[i].size(0);+ a.fmt[i] = (int)fmts[i];+ a.out[i] = o + (int64_t)R * total; // q, k, v blocks one after the other, each [R, N_i] contiguous (R = 1: the old layout)+ total += a.N[i];+ }+ a.R = R;+ TORCH_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);+ 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");+}++#endif // USE_ROCMdiff --git a/exllamav3/gm_ext/gm_pfmoe.cu b/exllamav3/gm_ext/gm_pfmoe.cunew file mode 100644index 0000000..f152a23--- /dev/null+++ b/exllamav3/gm_ext/gm_pfmoe.cu@@ -0,0 +1,322 @@+// Generic GGUF MoE prefill experts, HIP / gfx1151 WMMA: fused dequant of the stored k-quant bytes + grouped fp16 GEMM over expert row blocks.+// Q4_K gate/up (+ SwiGLU) and Q4_K / Q6_K down, per-expert pointer tables (ForeignLinear.packed), no row floor: a block of 128 rows skips the+// 16-row groups beyond the expert's valid rows, so 30 rows per expert cost 2 of 8 WMMA groups. Weights are dequantised once per row block.+// Kernel structure and the Q4_K decode come from the Hy4 prefill agent's moe_hip.cu: fp16 operands,+// fp32 accumulate, fp16 dequant rounding, grid = (N tiles, row blocks) with the N tiles of one row block back to back.+// block = 256 threads = 8 waves; tile 128 rows x 128 columns (each wave owns 16 columns of the tile for ALL 128 rows); K step 64.+// A (activation rows gathered by sorted_pairs): global -> registers (one step ahead) -> LDS (XOR swizzle, double buffered).+// B (weights): each lane loads the stored bytes of its column and dequantises its own 8 K values of every 16-wide k slice into registers;+// v_permlanex16 supplies the other 8 (lanes 16-31 hold k 8-15 first, k 0-7 second; A is loaded in the same order).+#if defined(USE_ROCM)++#include <hip/hip_runtime.h>+#include <ATen/cuda/CUDAContext.h>+#include <c10/cuda/CUDAGuard.h>+#include <torch/extension.h>+#include <cstdint>++typedef __attribute__((__vector_size__(16 * sizeof(__fp16)))) __fp16 pf_h16;+typedef __attribute__((__vector_size__(8 * sizeof(float)))) float pf_f8;++constexpr int PF_MT = 128, PF_KT = 64, PF_TH = 256;++__device__ __forceinline__ float pf_h2f(uint32_t b) { return (float)__builtin_bit_cast(_Float16, (uint16_t)b); }+__device__ __forceinline__ uint32_t pf_f2hb(float f) { return (uint32_t)__builtin_bit_cast(uint16_t, (_Float16)f); }+__device__ __forceinline__ uint32_t pf_pk2(float a, float b) { return pf_f2hb(a) | (pf_f2hb(b) << 16); }+__device__ __forceinline__ uint32_t pf_perm16(uint32_t x) { return __builtin_amdgcn_permlanex16(x, x, 0x76543210, 0xfedcba98, false, false); }+__device__ __forceinline__ uint32_t pf_funnel(uint32_t lo, uint32_t hi, uint32_t sh) { return __builtin_amdgcn_alignbit(hi, lo, sh); }++// 2-byte aligned loads of 4 / 8 bytes (Q6_K blocks are 210 bytes)+__device__ __forceinline__ uint32_t pf_ld4_a2(const uint8_t* p)+{+ uintptr_t a = (uintptr_t)p;+ const uint32_t* q = (const uint32_t*)(a & ~(uintptr_t)3);+ uint32_t x = q[0];+ if ((a & 2) == 0) return x;+ return pf_funnel(x, q[1], 16);+}+__device__ __forceinline__ uint2 pf_ld8_a2(const uint8_t* p)+{+ uintptr_t a = (uintptr_t)p;+ const uint32_t* q = (const uint32_t*)(a & ~(uintptr_t)3);+ uint2 r;+ if ((a & 2) == 0) { r = *(const uint2*)q; }+ else { uint32_t x = q[0], y = q[1], z = q[2]; r.x = pf_funnel(x, y, 16); r.y = pf_funnel(y, z, 16); }+ return r;+}++// stored-byte registers of one matrix for one K step (64 values). Q4_K: a (d, dmin, scales), q0 q1 (qs). Q6_K: q0..q3 (ql, one per k slice),+// m0 m1 (qh, slices 0/2 and 1/3), s0 (4 int8 scales), dd (d)+struct PfW { uint4 a; uint2 q0, q1, q2, q3, m0, m1; uint32_t s0, s1, dd; }; // FMT 3 (Q3_K): q0 q1 (2-bit qs), m0 m1 (hmask), s0 s1 (scale bytes), dd (d)+struct PfSc { float ds[4], dmn[4]; };++template <int FMT> __device__ __forceinline__ void pf_load(PfW& r, const uint8_t* wrow, int it, int h)+{+ const int kb = it >> 2, jq = it & 3;+ if (FMT == 0) {+ const uint8_t* blk = wrow + kb * 144;+ r.a = *(const uint4*)blk;+ r.q0 = *(const uint2*)(blk + 16 + 32 * jq + 8 * h);+ r.q1 = *(const uint2*)(blk + 16 + 32 * jq + 16 + 8 * h);+ } else if (FMT == 3) { // Q3_K, 110-byte blocks: 32 hmask, 64 qs, 12 scale bytes, fp16 d+ const uint8_t* blk = wrow + kb * 110;+ const int half = jq >> 1;+ r.q0 = pf_ld8_a2(blk + 32 + half * 32 + 8 * h);+ r.q1 = pf_ld8_a2(blk + 32 + half * 32 + 16 + 8 * h);+ r.m0 = pf_ld8_a2(blk + 8 * h);+ r.m1 = pf_ld8_a2(blk + 16 + 8 * h);+ r.s0 = pf_ld4_a2(blk + 96 + 4 * (jq & 1));+ r.s1 = pf_ld4_a2(blk + 104);+ r.dd = pf_ld4_a2(blk + 108) & 0xffffu;+ } else {+ const uint8_t* blk = wrow + kb * 210;+ const int hf = jq >> 1, c = jq & 1;+ const uint8_t* ql = blk + hf * 64 + 8 * h;+ const uint8_t* qh = blk + 128 + hf * 32 + 8 * h;+ r.q0 = pf_ld8_a2(ql);+ r.q1 = pf_ld8_a2(ql + 16);+ r.q2 = pf_ld8_a2(ql + 32);+ r.q3 = pf_ld8_a2(ql + 48);+ r.m0 = pf_ld8_a2(qh);+ r.m1 = pf_ld8_a2(qh + 16);+ r.s0 = pf_ld4_a2(blk + 192 + hf * 8 + 4 * c);+ r.dd = (uint32_t)*(const uint16_t*)(blk + 208);+ }+}++template <int FMT> __device__ __forceinline__ void pf_scales(PfSc& c, const PfW& r, int it)+{+ const int jq = it & 3;+ if (FMT == 0) {+ const float d = pf_h2f(r.a.x & 0xffff), dm = pf_h2f(r.a.x >> 16);+ #pragma unroll+ for (int sbi = 0; sbi < 2; sbi++) {+ const int s = 2 * jq + sbi, jj = s & 3, sh = 8 * jj;+ uint32_t x0 = (r.a.y >> sh) & 255, x4 = (r.a.z >> sh) & 255, x8 = (r.a.w >> sh) & 255;+ uint32_t sc, mn;+ if (s >= 4) { sc = (x8 & 15) | ((x0 >> 6) << 4); mn = (x8 >> 4) | ((x4 >> 6) << 4); }+ else { sc = x0 & 63; mn = x4 & 63; }+ c.ds[sbi] = d * (float)sc;+ c.dmn[sbi] = dm * (float)mn;+ }+ } else if (FMT == 3) { // slice ks -> scale idx 4 jq + ks: low nibble of byte 96 + (idx & 7), high 2 bits of byte 104 + (idx & 3); value = ((q * sc) * d)+ #pragma unroll+ for (int ks = 0; ks < 4; ks++) {+ const uint32_t lo = ((r.s0 >> (8 * ks)) >> (4 * (jq >> 1))) & 15;+ const uint32_t hi = ((r.s1 >> (8 * ks)) >> (2 * jq)) & 3;+ c.ds[ks] = (float)((int)(lo | (hi << 4)) - 32);+ c.dmn[ks] = pf_h2f(r.dd);+ }+ } else {+ const float d = pf_h2f(r.dd);+ #pragma unroll+ for (int ks = 0; ks < 4; ks++) c.ds[ks] = d * (float)(((int)(r.s0 << (24 - 8 * ks))) >> 24);+ }+}++// dequantised fp16 values of k slice ks (0..3 of the 64 step) for this lane's 8 k: 4 packed half2 dwords+template <int FMT> __device__ __forceinline__ void pf_dec(uint32_t o[4], const PfW& r, const PfSc& c, int ks, int jq)+{+ if (FMT == 0) {+ const int sbi = ks >> 1, t = ks & 1, sh0 = 4 * sbi;+ const uint2 q = t ? r.q1 : r.q0;+ const float ds = c.ds[sbi], dmn = c.dmn[sbi];+ #pragma unroll+ for (int p = 0; p < 4; p++) {+ const uint32_t word = (p < 2) ? q.x : q.y;+ const int sh = 16 * (p & 1) + sh0;+ const float q0 = (float)((word >> sh) & 15), q1 = (float)((word >> (sh + 8)) & 15);+ o[p] = pf_pk2(fmaf(q0, ds, -dmn), fmaf(q1, ds, -dmn));+ }+ } else if (FMT == 3) {+ const int sbi = ks >> 1, t = ks & 1;+ const uint2 q = t ? r.q1 : r.q0, m = t ? r.m1 : r.m0;+ const int shq = 4 * (jq & 1) + 2 * sbi, shm = (2 * jq + sbi) & 7;+ const float sc = c.ds[ks], d = c.dmn[ks];+ #pragma unroll+ for (int p = 0; p < 4; p++) {+ const uint32_t wq = (p < 2) ? q.x : q.y, wm = (p < 2) ? m.x : m.y;+ const int b0 = 16 * (p & 1), b1 = b0 + 8;+ const int v0 = (int)((wq >> (b0 + shq)) & 3) + 4 * (int)((wm >> (b0 + shm)) & 1) - 4;+ const int v1 = (int)((wq >> (b1 + shq)) & 3) + 4 * (int)((wm >> (b1 + shm)) & 1) - 4;+ o[p] = pf_pk2(((float)v0 * sc) * d, ((float)v1 * sc) * d);+ }+ } else {+ // value = d * sc * ((ql nibble c | 2 qh bits) - 32); chunk c = jq & 1 picks the ql nibble, qh bit pair 4 c (+2 for slices 2, 3)+ const int cc = jq & 1;+ const uint2 ql = ks == 0 ? r.q0 : ks == 1 ? r.q1 : ks == 2 ? r.q2 : r.q3;+ const uint2 qh = (ks & 1) ? r.m1 : r.m0;+ const int shl = 4 * cc, shh = 4 * cc + (ks >= 2 ? 2 : 0);+ const float ds = c.ds[ks];+ #pragma unroll+ for (int p = 0; p < 4; p++) {+ const uint32_t wl = (p < 2) ? ql.x : ql.y, wh = (p < 2) ? qh.x : qh.y;+ const int b0 = 16 * (p & 1), b1 = b0 + 8;+ const int v0 = (int)(((wl >> (b0 + shl)) & 15) | (((wh >> (b0 + shh)) & 3) << 4)) - 32;+ const int v1 = (int)(((wl >> (b1 + shl)) & 15) | (((wh >> (b1 + shh)) & 3) << 4)) - 32;+ o[p] = pf_pk2((float)v0 * ds, (float)v1 * ds);+ }+ }+}++__device__ __forceinline__ pf_h16 pf_mk_frag(uint4 lo, uint4 hi)+{+ pf_h16 f; ((uint4*)&f)[0] = lo; ((uint4*)&f)[1] = hi; return f;+}+__device__ __forceinline__ pf_h16 pf_mk_bfrag(const uint32_t o[4])+{+ uint4 own = make_uint4(o[0], o[1], o[2], o[3]);+ uint4 oth = make_uint4(pf_perm16(o[0]), pf_perm16(o[1]), pf_perm16(o[2]), pf_perm16(o[3]));+ return pf_mk_frag(own, oth);+}++// GU = true: gate+up (two weight matrices, gathered rows of X, SwiGLU epilogue -> H); false: down (two column tiles per wave, rows of Hin,+// weighted fp32 scatter to OUT[pair]). Row groups of 16 beyond the block's valid rows are skipped (a wave-uniform branch).+template <int FMT, bool GU>+__device__ __forceinline__ void pf_body(const uint16_t* __restrict__ X, const uint8_t* const* __restrict__ W0, const uint8_t* const* __restrict__ W1,+ void* __restrict__ OUT, const float* __restrict__ wts, const int* __restrict__ sp, const int* __restrict__ be,+ int P, int topk, int E, float lim, int K, int N, int ROWB)+{+ constexpr int NM = 2;+ constexpr int CPB = GU ? 128 : 256;+ __shared__ uint4 sm[2][PF_MT * 8];+ const int bx = blockIdx.x, by = blockIdx.y;+ const int e = be[by];+ if (e >= E) return;+ const int tid = threadIdx.x, w = tid >> 5, l = tid & 31, n = l & 15, h = l >> 4;+ const int ar = tid >> 1, ah = tid & 1;+ const int pair = sp[by * PF_MT + ar];+ const bool valid = pair < P;+ const int nv16 = (__syncthreads_count(valid) / 2 + 15) >> 4; // valid rows are a prefix of the block+ const uint4* arow = (const uint4*)(X + (long)(GU ? (pair / topk) : (by * PF_MT + ar)) * K);+ const uint8_t* wr[NM];+ #pragma unroll+ for (int j = 0; j < NM; j++) {+ const long col = GU ? ((long)bx * CPB + w * 16 + n) : ((long)bx * CPB + w * 32 + 16 * j + n);+ wr[j] = ((GU && j == 1) ? W1[e] : W0[e]) + col * ROWB;+ }+ const int nit = K / PF_KT;++ pf_f8 acc[NM][8];+ #pragma unroll+ for (int j = 0; j < NM; j++)+ #pragma unroll+ for (int g = 0; g < 8; g++) acc[j][g] = (pf_f8){0, 0, 0, 0, 0, 0, 0, 0};++ uint4 ap[4];+ PfW wc[NM], wn[NM];+ #pragma unroll+ for (int i = 0; i < 4; i++) ap[i] = valid ? arow[4 * ah + i] : make_uint4(0, 0, 0, 0);+ #pragma unroll+ for (int j = 0; j < NM; j++) pf_load<FMT>(wc[j], wr[j], 0, h);++ for (int it = 0; it < nit; it++) {+ const int buf = it & 1;+ #pragma unroll+ for (int i = 0; i < 4; i++) sm[buf][ar * 8 + ((4 * ah + i) ^ (ar & 7))] = ap[i];+ __syncthreads();+ if (it + 1 < nit) {+ const int k8 = (it + 1) * (PF_KT / 8);+ #pragma unroll+ for (int i = 0; i < 4; i++) ap[i] = valid ? arow[k8 + 4 * ah + i] : make_uint4(0, 0, 0, 0);+ #pragma unroll+ for (int j = 0; j < NM; j++) pf_load<FMT>(wn[j], wr[j], it + 1, h);+ }+ PfSc c[NM];+ #pragma unroll+ for (int j = 0; j < NM; j++) pf_scales<FMT>(c[j], wc[j], it);+ const int jq = it & 3;+ const uint4* sA = sm[buf];+ #pragma unroll+ for (int ks = 0; ks < 4; ks++) {+ pf_h16 b[NM];+ #pragma unroll+ for (int j = 0; j < NM; j++) { uint32_t o[4]; pf_dec<FMT>(o, wc[j], c[j], ks, jq); b[j] = pf_mk_bfrag(o); }+ #pragma unroll+ for (int g = 0; g < 8; g++) {+ if (g < nv16) {+ const int r = g * 16 + n;+ const uint4 lo = sA[r * 8 + ((2 * ks + h) ^ (r & 7))];+ const uint4 hi = sA[r * 8 + ((2 * ks + (1 - h)) ^ (r & 7))];+ const pf_h16 a = pf_mk_frag(lo, hi);+ #pragma unroll+ for (int j = 0; j < NM; j++) acc[j][g] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b[j], acc[j][g]);+ }+ }+ }+ #pragma unroll+ for (int j = 0; j < NM; j++) wc[j] = wn[j];+ }++ // epilogue: D lane l, reg i -> row 2 i + h, col n+ #pragma unroll+ for (int g = 0; g < 8; g++) {+ if (g < nv16) {+ #pragma unroll+ for (int i = 0; i < 8; i++) {+ const int rr = g * 16 + 2 * i + h;+ if (GU) {+ const long col = (long)bx * CPB + w * 16 + n;+ const float gg = fminf(acc[0][g][i], lim);+ const float uu = fminf(fmaxf(acc[1][g][i], -lim), lim);+ const float hv = gg / (1.0f + __expf(-gg)) * uu;+ ((uint16_t*)OUT)[(long)(by * PF_MT + rr) * N + col] = (uint16_t)pf_f2hb(hv);+ } else {+ const int pr = sp[by * PF_MT + rr];+ if (pr < P) {+ const float wv = wts[pr];+ #pragma unroll+ for (int j = 0; j < NM; j++) ((float*)OUT)[(long)pr * N + (long)bx * CPB + w * 32 + 16 * j + n] = acc[j][g][i] * wv;+ }+ }+ }+ }+ }+}++template <int FMT>+__global__ __launch_bounds__(PF_TH) void gm_pf_gu_k(const uint16_t* X, const uint8_t* const* Wg, const uint8_t* const* Wu, uint16_t* H, const int* sp,+ const int* be, int P, int topk, int E, float lim, int K, int N, int ROWB)+{ pf_body<FMT, true>(X, Wg, Wu, H, nullptr, sp, be, P, topk, E, lim, K, N, ROWB); }+template <int FMT>+__global__ __launch_bounds__(PF_TH) void gm_pf_down_k(const uint16_t* Hin, const uint8_t* const* Wd, float* Out, const float* wts, const int* sp,+ const int* be, int P, int E, int K, int N, int ROWB)+{ pf_body<FMT, false>(Hin, Wd, nullptr, Out, wts, sp, be, P, 1, E, 0.f, K, N, ROWB); }++// x [R, K] fp16 -> H [maxb * 128, N] fp16 (SwiGLU applied, rows in the sorted block layout). sp / be = route_blocks tables (BM = 128).+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)+{+ TORCH_CHECK(fmt == 0 || fmt == 3, "gm_pf_gate_up: Q4_K (0) or Q3_K (3)");+ TORCH_CHECK(x.is_cuda() && x.dtype() == at::kHalf && x.is_contiguous(), "gm_pf_gate_up: x must be contiguous half on the device");+ TORCH_CHECK(K % 256 == 0 && N % 128 == 0 && rowb == (K / 256) * (fmt == 0 ? 144 : 110), "gm_pf_gate_up: row bytes, K % 256, N % 128");+ TORCH_CHECK(H.numel() >= maxb * PF_MT * N && H.dtype() == at::kHalf, "gm_pf_gate_up: H too small");+ const at::cuda::OptionalCUDAGuard guard(x.device());+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ auto launch = fmt == 0 ? gm_pf_gu_k<0> : gm_pf_gu_k<3>;+ launch<<<dim3((unsigned)(N / 128), (unsigned)maxb), PF_TH, 0, stream>>>(+ reinterpret_cast<const uint16_t*>(x.data_ptr()), reinterpret_cast<const uint8_t* const*>(gate_ptrs.data_ptr()),+ reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr()), reinterpret_cast<uint16_t*>(H.data_ptr()),+ reinterpret_cast<const int*>(sp.data_ptr()), reinterpret_cast<const int*>(be.data_ptr()), (int)P, (int)topk, (int)E, (float)lim, (int)K, (int)N, (int)rowb);+}++// H [maxb * 128, K] fp16 -> out [P, N] fp32 = routing weight * (H @ Wd^T), one row per (token, k) pair. fmt: 0 = Q4_K, 2 = Q6_K.+void gm_pf_down(const at::Tensor& H, const at::Tensor& down_ptrs, const at::Tensor& wts, const at::Tensor& sp, const at::Tensor& be, at::Tensor& out,+ int64_t P, int64_t E, int64_t K, int64_t N, int64_t rowb, int64_t fmt, int64_t maxb)+{+ TORCH_CHECK(fmt == 0 || fmt == 2, "gm_pf_down: Q4_K (0) or Q6_K (2)");+ TORCH_CHECK(K % 256 == 0 && N % 256 == 0 && rowb == (K / 256) * (fmt == 0 ? 144 : 210), "gm_pf_down: row bytes, K % 256, N % 256");+ TORCH_CHECK(out.numel() >= P * N && out.dtype() == at::kFloat && wts.dtype() == at::kFloat, "gm_pf_down: out fp32 [P, N], wts fp32");+ const at::cuda::OptionalCUDAGuard guard(H.device());+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ dim3 grid((unsigned)(N / 256), (unsigned)maxb);+ auto a = std::make_tuple(reinterpret_cast<const uint16_t*>(H.data_ptr()), reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()),+ reinterpret_cast<float*>(out.data_ptr()), reinterpret_cast<const float*>(wts.data_ptr()),+ reinterpret_cast<const int*>(sp.data_ptr()), reinterpret_cast<const int*>(be.data_ptr()));+ if (fmt == 0)+ gm_pf_down_k<0><<<grid, PF_TH, 0, stream>>>(std::get<0>(a), std::get<1>(a), std::get<2>(a), std::get<3>(a), std::get<4>(a), std::get<5>(a), (int)P, (int)E, (int)K, (int)N, (int)rowb);+ else+ gm_pf_down_k<2><<<grid, PF_TH, 0, stream>>>(std::get<0>(a), std::get<1>(a), std::get<2>(a), std::get<3>(a), std::get<4>(a), std::get<5>(a), (int)P, (int)E, (int)K, (int)N, (int)rowb);+}++#endifdiff --git a/exllamav3/gm_ext/gm_pfmoe.hip b/exllamav3/gm_ext/gm_pfmoe.hipnew file mode 100644index 0000000..f48d45c--- /dev/null+++ b/exllamav3/gm_ext/gm_pfmoe.hip@@ -0,0 +1,323 @@+// !!! This is a file automatically generated by hipify!!!+// Generic GGUF MoE prefill experts, HIP / gfx1151 WMMA: fused dequant of the stored k-quant bytes + grouped fp16 GEMM over expert row blocks.+// Q4_K gate/up (+ SwiGLU) and Q4_K / Q6_K down, per-expert pointer tables (ForeignLinear.packed), no row floor: a block of 128 rows skips the+// 16-row groups beyond the expert's valid rows, so 30 rows per expert cost 2 of 8 WMMA groups. Weights are dequantised once per row block.+// Kernel structure and the Q4_K decode come from the Hy4 prefill agent's moe_hip.cu: fp16 operands,+// fp32 accumulate, fp16 dequant rounding, grid = (N tiles, row blocks) with the N tiles of one row block back to back.+// block = 256 threads = 8 waves; tile 128 rows x 128 columns (each wave owns 16 columns of the tile for ALL 128 rows); K step 64.+// A (activation rows gathered by sorted_pairs): global -> registers (one step ahead) -> LDS (XOR swizzle, double buffered).+// B (weights): each lane loads the stored bytes of its column and dequantises its own 8 K values of every 16-wide k slice into registers;+// v_permlanex16 supplies the other 8 (lanes 16-31 hold k 8-15 first, k 0-7 second; A is loaded in the same order).+#if defined(USE_ROCM)++#include <hip/hip_runtime.h>+#include <ATen/hip/HIPContext.h>+#include <c10/hip/HIPGuard.h>+#include <torch/extension.h>+#include <cstdint>++typedef __attribute__((__vector_size__(16 * sizeof(__fp16)))) __fp16 pf_h16;+typedef __attribute__((__vector_size__(8 * sizeof(float)))) float pf_f8;++constexpr int PF_MT = 128, PF_KT = 64, PF_TH = 256;++__device__ __forceinline__ float pf_h2f(uint32_t b) { return (float)__builtin_bit_cast(_Float16, (uint16_t)b); }+__device__ __forceinline__ uint32_t pf_f2hb(float f) { return (uint32_t)__builtin_bit_cast(uint16_t, (_Float16)f); }+__device__ __forceinline__ uint32_t pf_pk2(float a, float b) { return pf_f2hb(a) | (pf_f2hb(b) << 16); }+__device__ __forceinline__ uint32_t pf_perm16(uint32_t x) { return __builtin_amdgcn_permlanex16(x, x, 0x76543210, 0xfedcba98, false, false); }+__device__ __forceinline__ uint32_t pf_funnel(uint32_t lo, uint32_t hi, uint32_t sh) { return __builtin_amdgcn_alignbit(hi, lo, sh); }++// 2-byte aligned loads of 4 / 8 bytes (Q6_K blocks are 210 bytes)+__device__ __forceinline__ uint32_t pf_ld4_a2(const uint8_t* p)+{+ uintptr_t a = (uintptr_t)p;+ const uint32_t* q = (const uint32_t*)(a & ~(uintptr_t)3);+ uint32_t x = q[0];+ if ((a & 2) == 0) return x;+ return pf_funnel(x, q[1], 16);+}+__device__ __forceinline__ uint2 pf_ld8_a2(const uint8_t* p)+{+ uintptr_t a = (uintptr_t)p;+ const uint32_t* q = (const uint32_t*)(a & ~(uintptr_t)3);+ uint2 r;+ if ((a & 2) == 0) { r = *(const uint2*)q; }+ else { uint32_t x = q[0], y = q[1], z = q[2]; r.x = pf_funnel(x, y, 16); r.y = pf_funnel(y, z, 16); }+ return r;+}++// stored-byte registers of one matrix for one K step (64 values). Q4_K: a (d, dmin, scales), q0 q1 (qs). Q6_K: q0..q3 (ql, one per k slice),+// m0 m1 (qh, slices 0/2 and 1/3), s0 (4 int8 scales), dd (d)+struct PfW { uint4 a; uint2 q0, q1, q2, q3, m0, m1; uint32_t s0, s1, dd; }; // FMT 3 (Q3_K): q0 q1 (2-bit qs), m0 m1 (hmask), s0 s1 (scale bytes), dd (d)+struct PfSc { float ds[4], dmn[4]; };++template <int FMT> __device__ __forceinline__ void pf_load(PfW& r, const uint8_t* wrow, int it, int h)+{+ const int kb = it >> 2, jq = it & 3;+ if (FMT == 0) {+ const uint8_t* blk = wrow + kb * 144;+ r.a = *(const uint4*)blk;+ r.q0 = *(const uint2*)(blk + 16 + 32 * jq + 8 * h);+ r.q1 = *(const uint2*)(blk + 16 + 32 * jq + 16 + 8 * h);+ } else if (FMT == 3) { // Q3_K, 110-byte blocks: 32 hmask, 64 qs, 12 scale bytes, fp16 d+ const uint8_t* blk = wrow + kb * 110;+ const int half = jq >> 1;+ r.q0 = pf_ld8_a2(blk + 32 + half * 32 + 8 * h);+ r.q1 = pf_ld8_a2(blk + 32 + half * 32 + 16 + 8 * h);+ r.m0 = pf_ld8_a2(blk + 8 * h);+ r.m1 = pf_ld8_a2(blk + 16 + 8 * h);+ r.s0 = pf_ld4_a2(blk + 96 + 4 * (jq & 1));+ r.s1 = pf_ld4_a2(blk + 104);+ r.dd = pf_ld4_a2(blk + 108) & 0xffffu;+ } else {+ const uint8_t* blk = wrow + kb * 210;+ const int hf = jq >> 1, c = jq & 1;+ const uint8_t* ql = blk + hf * 64 + 8 * h;+ const uint8_t* qh = blk + 128 + hf * 32 + 8 * h;+ r.q0 = pf_ld8_a2(ql);+ r.q1 = pf_ld8_a2(ql + 16);+ r.q2 = pf_ld8_a2(ql + 32);+ r.q3 = pf_ld8_a2(ql + 48);+ r.m0 = pf_ld8_a2(qh);+ r.m1 = pf_ld8_a2(qh + 16);+ r.s0 = pf_ld4_a2(blk + 192 + hf * 8 + 4 * c);+ r.dd = (uint32_t)*(const uint16_t*)(blk + 208);+ }+}++template <int FMT> __device__ __forceinline__ void pf_scales(PfSc& c, const PfW& r, int it)+{+ const int jq = it & 3;+ if (FMT == 0) {+ const float d = pf_h2f(r.a.x & 0xffff), dm = pf_h2f(r.a.x >> 16);+ #pragma unroll+ for (int sbi = 0; sbi < 2; sbi++) {+ const int s = 2 * jq + sbi, jj = s & 3, sh = 8 * jj;+ uint32_t x0 = (r.a.y >> sh) & 255, x4 = (r.a.z >> sh) & 255, x8 = (r.a.w >> sh) & 255;+ uint32_t sc, mn;+ if (s >= 4) { sc = (x8 & 15) | ((x0 >> 6) << 4); mn = (x8 >> 4) | ((x4 >> 6) << 4); }+ else { sc = x0 & 63; mn = x4 & 63; }+ c.ds[sbi] = d * (float)sc;+ c.dmn[sbi] = dm * (float)mn;+ }+ } else if (FMT == 3) { // slice ks -> scale idx 4 jq + ks: low nibble of byte 96 + (idx & 7), high 2 bits of byte 104 + (idx & 3); value = ((q * sc) * d)+ #pragma unroll+ for (int ks = 0; ks < 4; ks++) {+ const uint32_t lo = ((r.s0 >> (8 * ks)) >> (4 * (jq >> 1))) & 15;+ const uint32_t hi = ((r.s1 >> (8 * ks)) >> (2 * jq)) & 3;+ c.ds[ks] = (float)((int)(lo | (hi << 4)) - 32);+ c.dmn[ks] = pf_h2f(r.dd);+ }+ } else {+ const float d = pf_h2f(r.dd);+ #pragma unroll+ for (int ks = 0; ks < 4; ks++) c.ds[ks] = d * (float)(((int)(r.s0 << (24 - 8 * ks))) >> 24);+ }+}++// dequantised fp16 values of k slice ks (0..3 of the 64 step) for this lane's 8 k: 4 packed half2 dwords+template <int FMT> __device__ __forceinline__ void pf_dec(uint32_t o[4], const PfW& r, const PfSc& c, int ks, int jq)+{+ if (FMT == 0) {+ const int sbi = ks >> 1, t = ks & 1, sh0 = 4 * sbi;+ const uint2 q = t ? r.q1 : r.q0;+ const float ds = c.ds[sbi], dmn = c.dmn[sbi];+ #pragma unroll+ for (int p = 0; p < 4; p++) {+ const uint32_t word = (p < 2) ? q.x : q.y;+ const int sh = 16 * (p & 1) + sh0;+ const float q0 = (float)((word >> sh) & 15), q1 = (float)((word >> (sh + 8)) & 15);+ o[p] = pf_pk2(fmaf(q0, ds, -dmn), fmaf(q1, ds, -dmn));+ }+ } else if (FMT == 3) {+ const int sbi = ks >> 1, t = ks & 1;+ const uint2 q = t ? r.q1 : r.q0, m = t ? r.m1 : r.m0;+ const int shq = 4 * (jq & 1) + 2 * sbi, shm = (2 * jq + sbi) & 7;+ const float sc = c.ds[ks], d = c.dmn[ks];+ #pragma unroll+ for (int p = 0; p < 4; p++) {+ const uint32_t wq = (p < 2) ? q.x : q.y, wm = (p < 2) ? m.x : m.y;+ const int b0 = 16 * (p & 1), b1 = b0 + 8;+ const int v0 = (int)((wq >> (b0 + shq)) & 3) + 4 * (int)((wm >> (b0 + shm)) & 1) - 4;+ const int v1 = (int)((wq >> (b1 + shq)) & 3) + 4 * (int)((wm >> (b1 + shm)) & 1) - 4;+ o[p] = pf_pk2(((float)v0 * sc) * d, ((float)v1 * sc) * d);+ }+ } else {+ // value = d * sc * ((ql nibble c | 2 qh bits) - 32); chunk c = jq & 1 picks the ql nibble, qh bit pair 4 c (+2 for slices 2, 3)+ const int cc = jq & 1;+ const uint2 ql = ks == 0 ? r.q0 : ks == 1 ? r.q1 : ks == 2 ? r.q2 : r.q3;+ const uint2 qh = (ks & 1) ? r.m1 : r.m0;+ const int shl = 4 * cc, shh = 4 * cc + (ks >= 2 ? 2 : 0);+ const float ds = c.ds[ks];+ #pragma unroll+ for (int p = 0; p < 4; p++) {+ const uint32_t wl = (p < 2) ? ql.x : ql.y, wh = (p < 2) ? qh.x : qh.y;+ const int b0 = 16 * (p & 1), b1 = b0 + 8;+ const int v0 = (int)(((wl >> (b0 + shl)) & 15) | (((wh >> (b0 + shh)) & 3) << 4)) - 32;+ const int v1 = (int)(((wl >> (b1 + shl)) & 15) | (((wh >> (b1 + shh)) & 3) << 4)) - 32;+ o[p] = pf_pk2((float)v0 * ds, (float)v1 * ds);+ }+ }+}++__device__ __forceinline__ pf_h16 pf_mk_frag(uint4 lo, uint4 hi)+{+ pf_h16 f; ((uint4*)&f)[0] = lo; ((uint4*)&f)[1] = hi; return f;+}+__device__ __forceinline__ pf_h16 pf_mk_bfrag(const uint32_t o[4])+{+ uint4 own = make_uint4(o[0], o[1], o[2], o[3]);+ uint4 oth = make_uint4(pf_perm16(o[0]), pf_perm16(o[1]), pf_perm16(o[2]), pf_perm16(o[3]));+ return pf_mk_frag(own, oth);+}++// GU = true: gate+up (two weight matrices, gathered rows of X, SwiGLU epilogue -> H); false: down (two column tiles per wave, rows of Hin,+// weighted fp32 scatter to OUT[pair]). Row groups of 16 beyond the block's valid rows are skipped (a wave-uniform branch).+template <int FMT, bool GU>+__device__ __forceinline__ void pf_body(const uint16_t* __restrict__ X, const uint8_t* const* __restrict__ W0, const uint8_t* const* __restrict__ W1,+ void* __restrict__ OUT, const float* __restrict__ wts, const int* __restrict__ sp, const int* __restrict__ be,+ int P, int topk, int E, float lim, int K, int N, int ROWB)+{+ constexpr int NM = 2;+ constexpr int CPB = GU ? 128 : 256;+ __shared__ uint4 sm[2][PF_MT * 8];+ const int bx = blockIdx.x, by = blockIdx.y;+ const int e = be[by];+ if (e >= E) return;+ const int tid = threadIdx.x, w = tid >> 5, l = tid & 31, n = l & 15, h = l >> 4;+ const int ar = tid >> 1, ah = tid & 1;+ const int pair = sp[by * PF_MT + ar];+ const bool valid = pair < P;+ const int nv16 = (__syncthreads_count(valid) / 2 + 15) >> 4; // valid rows are a prefix of the block+ const uint4* arow = (const uint4*)(X + (long)(GU ? (pair / topk) : (by * PF_MT + ar)) * K);+ const uint8_t* wr[NM];+ #pragma unroll+ for (int j = 0; j < NM; j++) {+ const long col = GU ? ((long)bx * CPB + w * 16 + n) : ((long)bx * CPB + w * 32 + 16 * j + n);+ wr[j] = ((GU && j == 1) ? W1[e] : W0[e]) + col * ROWB;+ }+ const int nit = K / PF_KT;++ pf_f8 acc[NM][8];+ #pragma unroll+ for (int j = 0; j < NM; j++)+ #pragma unroll+ for (int g = 0; g < 8; g++) acc[j][g] = (pf_f8){0, 0, 0, 0, 0, 0, 0, 0};++ uint4 ap[4];+ PfW wc[NM], wn[NM];+ #pragma unroll+ for (int i = 0; i < 4; i++) ap[i] = valid ? arow[4 * ah + i] : make_uint4(0, 0, 0, 0);+ #pragma unroll+ for (int j = 0; j < NM; j++) pf_load<FMT>(wc[j], wr[j], 0, h);++ for (int it = 0; it < nit; it++) {+ const int buf = it & 1;+ #pragma unroll+ for (int i = 0; i < 4; i++) sm[buf][ar * 8 + ((4 * ah + i) ^ (ar & 7))] = ap[i];+ __syncthreads();+ if (it + 1 < nit) {+ const int k8 = (it + 1) * (PF_KT / 8);+ #pragma unroll+ for (int i = 0; i < 4; i++) ap[i] = valid ? arow[k8 + 4 * ah + i] : make_uint4(0, 0, 0, 0);+ #pragma unroll+ for (int j = 0; j < NM; j++) pf_load<FMT>(wn[j], wr[j], it + 1, h);+ }+ PfSc c[NM];+ #pragma unroll+ for (int j = 0; j < NM; j++) pf_scales<FMT>(c[j], wc[j], it);+ const int jq = it & 3;+ const uint4* sA = sm[buf];+ #pragma unroll+ for (int ks = 0; ks < 4; ks++) {+ pf_h16 b[NM];+ #pragma unroll+ for (int j = 0; j < NM; j++) { uint32_t o[4]; pf_dec<FMT>(o, wc[j], c[j], ks, jq); b[j] = pf_mk_bfrag(o); }+ #pragma unroll+ for (int g = 0; g < 8; g++) {+ if (g < nv16) {+ const int r = g * 16 + n;+ const uint4 lo = sA[r * 8 + ((2 * ks + h) ^ (r & 7))];+ const uint4 hi = sA[r * 8 + ((2 * ks + (1 - h)) ^ (r & 7))];+ const pf_h16 a = pf_mk_frag(lo, hi);+ #pragma unroll+ for (int j = 0; j < NM; j++) acc[j][g] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b[j], acc[j][g]);+ }+ }+ }+ #pragma unroll+ for (int j = 0; j < NM; j++) wc[j] = wn[j];+ }++ // epilogue: D lane l, reg i -> row 2 i + h, col n+ #pragma unroll+ for (int g = 0; g < 8; g++) {+ if (g < nv16) {+ #pragma unroll+ for (int i = 0; i < 8; i++) {+ const int rr = g * 16 + 2 * i + h;+ if (GU) {+ const long col = (long)bx * CPB + w * 16 + n;+ const float gg = fminf(acc[0][g][i], lim);+ const float uu = fminf(fmaxf(acc[1][g][i], -lim), lim);+ const float hv = gg / (1.0f + __expf(-gg)) * uu;+ ((uint16_t*)OUT)[(long)(by * PF_MT + rr) * N + col] = (uint16_t)pf_f2hb(hv);+ } else {+ const int pr = sp[by * PF_MT + rr];+ if (pr < P) {+ const float wv = wts[pr];+ #pragma unroll+ for (int j = 0; j < NM; j++) ((float*)OUT)[(long)pr * N + (long)bx * CPB + w * 32 + 16 * j + n] = acc[j][g][i] * wv;+ }+ }+ }+ }+ }+}++template <int FMT>+__global__ __launch_bounds__(PF_TH) void gm_pf_gu_k(const uint16_t* X, const uint8_t* const* Wg, const uint8_t* const* Wu, uint16_t* H, const int* sp,+ const int* be, int P, int topk, int E, float lim, int K, int N, int ROWB)+{ pf_body<FMT, true>(X, Wg, Wu, H, nullptr, sp, be, P, topk, E, lim, K, N, ROWB); }+template <int FMT>+__global__ __launch_bounds__(PF_TH) void gm_pf_down_k(const uint16_t* Hin, const uint8_t* const* Wd, float* Out, const float* wts, const int* sp,+ const int* be, int P, int E, int K, int N, int ROWB)+{ pf_body<FMT, false>(Hin, Wd, nullptr, Out, wts, sp, be, P, 1, E, 0.f, K, N, ROWB); }++// x [R, K] fp16 -> H [maxb * 128, N] fp16 (SwiGLU applied, rows in the sorted block layout). sp / be = route_blocks tables (BM = 128).+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)+{+ TORCH_CHECK(fmt == 0 || fmt == 3, "gm_pf_gate_up: Q4_K (0) or Q3_K (3)");+ TORCH_CHECK(x.is_cuda() && x.dtype() == at::kHalf && x.is_contiguous(), "gm_pf_gate_up: x must be contiguous half on the device");+ TORCH_CHECK(K % 256 == 0 && N % 128 == 0 && rowb == (K / 256) * (fmt == 0 ? 144 : 110), "gm_pf_gate_up: row bytes, K % 256, N % 128");+ TORCH_CHECK(H.numel() >= maxb * PF_MT * N && H.dtype() == at::kHalf, "gm_pf_gate_up: H too small");+ const at::cuda::OptionalCUDAGuard guard(x.device());+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ auto launch = fmt == 0 ? gm_pf_gu_k<0> : gm_pf_gu_k<3>;+ hipLaunchKernelGGL(( launch), dim3(dim3((unsigned)(N / 128), (unsigned)maxb)), dim3(PF_TH), 0, stream,+ reinterpret_cast<const uint16_t*>(x.data_ptr()), reinterpret_cast<const uint8_t* const*>(gate_ptrs.data_ptr()),+ reinterpret_cast<const uint8_t* const*>(up_ptrs.data_ptr()), reinterpret_cast<uint16_t*>(H.data_ptr()),+ reinterpret_cast<const int*>(sp.data_ptr()), reinterpret_cast<const int*>(be.data_ptr()), (int)P, (int)topk, (int)E, (float)lim, (int)K, (int)N, (int)rowb);+}++// H [maxb * 128, K] fp16 -> out [P, N] fp32 = routing weight * (H @ Wd^T), one row per (token, k) pair. fmt: 0 = Q4_K, 2 = Q6_K.+void gm_pf_down(const at::Tensor& H, const at::Tensor& down_ptrs, const at::Tensor& wts, const at::Tensor& sp, const at::Tensor& be, at::Tensor& out,+ int64_t P, int64_t E, int64_t K, int64_t N, int64_t rowb, int64_t fmt, int64_t maxb)+{+ TORCH_CHECK(fmt == 0 || fmt == 2, "gm_pf_down: Q4_K (0) or Q6_K (2)");+ TORCH_CHECK(K % 256 == 0 && N % 256 == 0 && rowb == (K / 256) * (fmt == 0 ? 144 : 210), "gm_pf_down: row bytes, K % 256, N % 256");+ TORCH_CHECK(out.numel() >= P * N && out.dtype() == at::kFloat && wts.dtype() == at::kFloat, "gm_pf_down: out fp32 [P, N], wts fp32");+ const at::cuda::OptionalCUDAGuard guard(H.device());+ hipStream_t stream = at::cuda::getCurrentCUDAStream().stream();+ dim3 grid((unsigned)(N / 256), (unsigned)maxb);+ auto a = std::make_tuple(reinterpret_cast<const uint16_t*>(H.data_ptr()), reinterpret_cast<const uint8_t* const*>(down_ptrs.data_ptr()),+ reinterpret_cast<float*>(out.data_ptr()), reinterpret_cast<const float*>(wts.data_ptr()),+ reinterpret_cast<const int*>(sp.data_ptr()), reinterpret_cast<const int*>(be.data_ptr()));+ if (fmt == 0)+ hipLaunchKernelGGL(( gm_pf_down_k<0>), dim3(grid), dim3(PF_TH), 0, stream, std::get<0>(a), std::get<1>(a), std::get<2>(a), std::get<3>(a), std::get<4>(a), std::get<5>(a), (int)P, (int)E, (int)K, (int)N, (int)rowb);+ else+ hipLaunchKernelGGL(( gm_pf_down_k<2>), dim3(grid), dim3(PF_TH), 0, stream, std::get<0>(a), std::get<1>(a), std::get<2>(a), std::get<3>(a), std::get<4>(a), std::get<5>(a), (int)P, (int)E, (int)K, (int)N, (int)rowb);+}++#endifdiff --git a/exllamav3/gm_ext/gm_router.cu b/exllamav3/gm_ext/gm_router.cunew file mode 100644index 0000000..561dd8d--- /dev/null+++ b/exllamav3/gm_ext/gm_router.cu@@ -0,0 +1,258 @@+#if defined(USE_ROCM)++#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>++#include <ATen/cuda/CUDAContext.h>+#include <c10/cuda/CUDAGuard.h>+#include <torch/extension.h>++#include "gm_router.cuh"++#include <cstdint>+#include <cstring>+#include <limits>++namespace {++constexpr int WAVE_SIZE = 32;+constexpr int GEMV_WAVES = 2; // 2 expert rows per block: E / 2 blocks (8 per block left most CUs idle at E = 256)+// Supported (hidden, experts, top-k) decode shapes: see gm_routing_std_bsz1 below and _HIP_ROUTER_SHAPES in block_sparse_mlp_routing.py+constexpr int MAX_ROUTER_ROWS = 16;+constexpr float NEG_INF = -std::numeric_limits<float>::infinity();++__device__ __forceinline__+void wave_reduce_best(float& key, int& idx)+{+ bool valid = idx >= 0;+ #pragma unroll+ for (int offset = WAVE_SIZE / 2; offset > 0; offset >>= 1)+ {+ const float other_key = __shfl_down(key, offset, WAVE_SIZE);+ const int other_idx = __shfl_down(idx, offset, WAVE_SIZE);+ const bool other_valid = other_idx >= 0;+ if (other_valid && (!valid || other_key > key ||+ (other_key == key && other_idx < idx)))+ {+ key = other_key;+ idx = other_idx;+ valid = true;+ }+ }+ key = __shfl(key, 0, WAVE_SIZE);+ idx = __shfl(idx, 0, WAVE_SIZE);+}++__device__ __forceinline__+float wave_reduce_max(float value)+{+ #pragma unroll+ for (int offset = WAVE_SIZE / 2; offset > 0; offset >>= 1)+ value = fmaxf(value, __shfl_down(value, offset, WAVE_SIZE));+ return __shfl(value, 0, WAVE_SIZE);+}++__device__ __forceinline__+float wave_reduce_sum(float value)+{+ #pragma unroll+ for (int offset = WAVE_SIZE / 2; offset > 0; offset >>= 1)+ value += __shfl_down(value, offset, WAVE_SIZE);+ return __shfl(value, 0, WAVE_SIZE);+}++template <int ROUTER_HIDDEN, int ROUTER_EXPERTS>+__global__ __launch_bounds__(GEMV_WAVES * WAVE_SIZE)+void routing_gemv_gfx12_bsz1_kernel+(+ const half* __restrict__ hidden,+ const half* __restrict__ gate_t,+ half* __restrict__ scores+)+{+ const int row = blockIdx.y;+ const int wave = threadIdx.x / WAVE_SIZE;+ const int lane = threadIdx.x % WAVE_SIZE;+ const int expert = blockIdx.x * GEMV_WAVES + wave;+ hidden += static_cast<size_t>(row) * ROUTER_HIDDEN;+ scores += static_cast<size_t>(row) * ROUTER_EXPERTS;+ if (expert >= ROUTER_EXPERTS) return;++ const half2* hidden2 = reinterpret_cast<const half2*>(hidden);+ const half2* gate2 = reinterpret_cast<const half2*>(+ gate_t + static_cast<size_t>(expert) * ROUTER_HIDDEN);++ float sum = 0.0f;+ #pragma unroll 8+ for (int col = lane; col < ROUTER_HIDDEN / 2; col += WAVE_SIZE)+ {+ const half2 h = hidden2[col];+ const half2 g = gate2[col];+ sum = fmaf(__half2float(__low2half(h)), __half2float(__low2half(g)), sum);+ sum = fmaf(__half2float(__high2half(h)), __half2float(__high2half(g)), sum);+ }++ sum = wave_reduce_sum(sum);+ if (lane == 0) scores[expert] = __float2half_rn(sum);+}++// Top-k by rank (same result as the standard routing.cu reduction): every thread holds one expert score and counts, from shared+// memory, the scores that beat it (greater, or equal with a lower expert index); a rank below K is that expert's output slot.+// Then the softmax over the K selected exactly as before: exp(score - max over all experts), lane-order sum, divide.+template <int ROUTER_EXPERTS, int ROUTER_TOP_K>+__global__ __launch_bounds__(ROUTER_EXPERTS)+void routing_std_topk_gfx12_bsz1_kernel+(+ const half* __restrict__ scores,+ int64_t* __restrict__ topk_indices,+ half* __restrict__ topk_weights+)+{+ constexpr int NUM_WAVES = ROUTER_EXPERTS / WAVE_SIZE;+ static_assert(ROUTER_EXPERTS % WAVE_SIZE == 0 && NUM_WAVES <= WAVE_SIZE && ROUTER_TOP_K < WAVE_SIZE, "router shape");++ __shared__ float logits[ROUTER_EXPERTS];+ __shared__ float wave_max[NUM_WAVES];+ __shared__ float global_max;+ __shared__ float selected_exp[ROUTER_TOP_K];+ __shared__ int selected_idx[ROUTER_TOP_K];++ const int tid = threadIdx.x;+ const int lane = tid % WAVE_SIZE;+ const int wave = tid / WAVE_SIZE;+ scores += static_cast<size_t>(blockIdx.x) * ROUTER_EXPERTS;+ topk_indices += static_cast<size_t>(blockIdx.x) * ROUTER_TOP_K;+ topk_weights += static_cast<size_t>(blockIdx.x) * ROUTER_TOP_K;+ const float logit = __half2float(scores[tid]);+ logits[tid] = logit;++ float max_logit = wave_reduce_max(logit);+ if (lane == 0) wave_max[wave] = max_logit;+ __syncthreads();+ if (wave == 0)+ {+ max_logit = lane < NUM_WAVES ? wave_max[lane] : NEG_INF;+ max_logit = wave_reduce_max(max_logit);+ if (lane == 0) global_max = max_logit;+ }++ int rank = 0;+ #pragma unroll 8+ for (int j = 0; j < ROUTER_EXPERTS; ++j)+ {+ const float other = logits[j];+ rank += (other > logit || (other == logit && j < tid)) ? 1 : 0;+ }+ __syncthreads();+ if (rank < ROUTER_TOP_K)+ {+ selected_exp[rank] = logit == global_max ? 1.0f : expf(logit - global_max);+ selected_idx[rank] = tid;+ }+ __syncthreads();++ if (wave == 0)+ {+ const float e = lane < ROUTER_TOP_K ? selected_exp[lane] : 0.0f;+ const float sum = wave_reduce_sum(e) + 1.0e-20f;+ if (lane < ROUTER_TOP_K)+ {+ topk_indices[lane] = static_cast<int64_t>(selected_idx[lane]);+ topk_weights[lane] = __float2half_rn(e / sum);+ }+ }+}++bool is_gfx12_wave32(int device)+{+ hipDeviceProp_t prop;+ if (hipGetDeviceProperties(&prop, device) != hipSuccess) return false;+ const char* arch = prop.gcnArchName;+ // These kernels use only wave-width primitives (__shfl*, __syncwarp) and no+ // RDNA4-only instruction, so every wave32 gfx11.5 / gfx12 part is valid.+ // gfx1150/1151/1152 = RDNA3.5 (Strix Halo), gfx1200/1201 = RDNA4.+ auto is_arch = [arch](const char* name, size_t n) {+ return !std::strncmp(arch, name, n) && (arch[n] == '\0' || arch[n] == ':');+ };+ const bool wave32_arch =+ is_arch("gfx1200", 7) || is_arch("gfx1201", 7) ||+ is_arch("gfx1150", 7) || is_arch("gfx1151", 7) || is_arch("gfx1152", 7);+ return wave32_arch && prop.warpSize == WAVE_SIZE;+}++void check_tensor+(+ const at::Tensor& tensor,+ const at::Device& device,+ at::ScalarType dtype,+ at::IntArrayRef shape,+ const char* name,+ size_t alignment+)+{+ TORCH_CHECK(tensor.is_cuda(), "gm_routing_std_bsz1: ", name, " must be a device tensor");+ TORCH_CHECK(tensor.device() == device, "gm_routing_std_bsz1: ", name,+ " must be on the hidden-state device");+ TORCH_CHECK(tensor.dtype() == dtype, "gm_routing_std_bsz1: ", name,+ " has the wrong dtype");+ TORCH_CHECK(tensor.sizes() == shape, "gm_routing_std_bsz1: ", name,+ " has the wrong shape");+ TORCH_CHECK(tensor.is_contiguous(), "gm_routing_std_bsz1: ", name,+ " must be contiguous");+ TORCH_CHECK(reinterpret_cast<uintptr_t>(tensor.data_ptr()) % alignment == 0,+ "gm_routing_std_bsz1: ", name, " must be ", alignment, "-byte aligned");+}++} // namespace++void gm_routing_std_bsz1+(+ const at::Tensor& hidden,+ const at::Tensor& gate_t,+ at::Tensor& scores,+ at::Tensor& topk_indices,+ at::Tensor& topk_weights+)+{+ TORCH_CHECK(hidden.is_cuda(),+ "gm_routing_std_bsz1: hidden must be a device tensor");+ const at::cuda::OptionalCUDAGuard device_guard(hidden.device());+ const int device = hidden.get_device();+ TORCH_CHECK(is_gfx12_wave32(device),+ "gm_routing_std_bsz1 requires gfx1200/gfx1201 with wave32");++ TORCH_CHECK(hidden.dim() == 2,+ "gm_routing_std_bsz1: hidden must be a 2D tensor");+ const int64_t rows = hidden.size(0);+ TORCH_CHECK(rows > 0 && rows <= MAX_ROUTER_ROWS,+ "gm_routing_std_bsz1 supports 1 through ", MAX_ROUTER_ROWS, " rows");+ TORCH_CHECK(hidden.dim() == 2 && gate_t.dim() == 2 && topk_indices.dim() == 2,+ "gm_routing_std_bsz1: 2D tensors expected");+ const int64_t H = hidden.size(1), E = gate_t.size(0), K = topk_indices.size(1);+ check_tensor(hidden, hidden.device(), at::kHalf, {rows, H}, "hidden", 16);+ check_tensor(gate_t, hidden.device(), at::kHalf, {E, H}, "gate_t", 16);+ check_tensor(scores, hidden.device(), at::kHalf, {rows, E}, "scores", 16);+ check_tensor(topk_indices, hidden.device(), at::kLong, {rows, K}, "topk_indices", 16);+ check_tensor(topk_weights, hidden.device(), at::kHalf, {rows, K}, "topk_weights", 16);++ hipStream_t stream = at::cuda::getCurrentCUDAStream(device).stream();+ const half* h = reinterpret_cast<const half*>(hidden.data_ptr());+ const half* g = reinterpret_cast<const half*>(gate_t.data_ptr());+ half* sc = reinterpret_cast<half*>(scores.data_ptr());+ int64_t* ti = reinterpret_cast<int64_t*>(topk_indices.data_ptr());+ half* tw = reinterpret_cast<half*>(topk_weights.data_ptr());+ #define ROUTER_SHAPE(HH, EE, KK) \+ if (H == HH && E == EE && K == KK) \+ { \+ routing_gemv_gfx12_bsz1_kernel<HH, EE><<<dim3(EE / GEMV_WAVES, rows), GEMV_WAVES * WAVE_SIZE, 0, stream>>>(h, g, sc); \+ routing_std_topk_gfx12_bsz1_kernel<EE, KK><<<rows, EE, 0, stream>>>(sc, ti, tw); \+ } else+ ROUTER_SHAPE(2560, 512, 10) // Qwen3.8-Flash-Next+ ROUTER_SHAPE(2048, 256, 8) // Qwen3.6-35B-A3B (GGUF and EXL3 packs)+ ROUTER_SHAPE(2048, 128, 8) // Qwen3-30B-A3B (qwen3moe)+ TORCH_CHECK(false, "gm_routing_std_bsz1: unsupported router shape ", H, " x ", E, " top-", K);+ #undef ROUTER_SHAPE+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_routing_std_bsz1: launch failed");+}++#endif // USE_ROCMdiff --git a/exllamav3/gm_ext/gm_router.cuh b/exllamav3/gm_ext/gm_router.cuhnew file mode 100644index 0000000..c254b54--- /dev/null+++ b/exllamav3/gm_ext/gm_router.cuh@@ -0,0 +1,19 @@+#pragma once++#if defined(USE_ROCM)++#include <ATen/Tensor.h>++// Decode-only standard MoE router for up to eight gfx1200/gfx1201 rows. The gate is+// supplied as a persistent contiguous (experts, hidden) transpose so each GEMV is coalesced.+// The bsz1 name is retained as a compatibility binding.+void gm_routing_std_bsz1+(+ const at::Tensor& hidden,+ const at::Tensor& gate_t,+ at::Tensor& scores,+ at::Tensor& topk_indices,+ at::Tensor& topk_weights+);++#endifdiff --git a/exllamav3/gm_ext/gm_router.hip b/exllamav3/gm_ext/gm_router.hipnew file mode 100644index 0000000..20a6393--- /dev/null+++ b/exllamav3/gm_ext/gm_router.hip@@ -0,0 +1,259 @@+// !!! This is a file automatically generated by hipify!!!+#if defined(USE_ROCM)++#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>++#include <ATen/hip/HIPContext.h>+#include <c10/hip/HIPGuard.h>+#include <torch/extension.h>++#include "gm_router.cuh"++#include <cstdint>+#include <cstring>+#include <limits>++namespace {++constexpr int WAVE_SIZE = 32;+constexpr int GEMV_WAVES = 2; // 2 expert rows per block: E / 2 blocks (8 per block left most CUs idle at E = 256)+// Supported (hidden, experts, top-k) decode shapes: see gm_routing_std_bsz1 below and _HIP_ROUTER_SHAPES in block_sparse_mlp_routing.py+constexpr int MAX_ROUTER_ROWS = 16;+constexpr float NEG_INF = -std::numeric_limits<float>::infinity();++__device__ __forceinline__+void wave_reduce_best(float& key, int& idx)+{+ bool valid = idx >= 0;+ #pragma unroll+ for (int offset = WAVE_SIZE / 2; offset > 0; offset >>= 1)+ {+ const float other_key = __shfl_down(key, offset, WAVE_SIZE);+ const int other_idx = __shfl_down(idx, offset, WAVE_SIZE);+ const bool other_valid = other_idx >= 0;+ if (other_valid && (!valid || other_key > key ||+ (other_key == key && other_idx < idx)))+ {+ key = other_key;+ idx = other_idx;+ valid = true;+ }+ }+ key = __shfl(key, 0, WAVE_SIZE);+ idx = __shfl(idx, 0, WAVE_SIZE);+}++__device__ __forceinline__+float wave_reduce_max(float value)+{+ #pragma unroll+ for (int offset = WAVE_SIZE / 2; offset > 0; offset >>= 1)+ value = fmaxf(value, __shfl_down(value, offset, WAVE_SIZE));+ return __shfl(value, 0, WAVE_SIZE);+}++__device__ __forceinline__+float wave_reduce_sum(float value)+{+ #pragma unroll+ for (int offset = WAVE_SIZE / 2; offset > 0; offset >>= 1)+ value += __shfl_down(value, offset, WAVE_SIZE);+ return __shfl(value, 0, WAVE_SIZE);+}++template <int ROUTER_HIDDEN, int ROUTER_EXPERTS>+__global__ __launch_bounds__(GEMV_WAVES * WAVE_SIZE)+void routing_gemv_gfx12_bsz1_kernel+(+ const half* __restrict__ hidden,+ const half* __restrict__ gate_t,+ half* __restrict__ scores+)+{+ const int row = blockIdx.y;+ const int wave = threadIdx.x / WAVE_SIZE;+ const int lane = threadIdx.x % WAVE_SIZE;+ const int expert = blockIdx.x * GEMV_WAVES + wave;+ hidden += static_cast<size_t>(row) * ROUTER_HIDDEN;+ scores += static_cast<size_t>(row) * ROUTER_EXPERTS;+ if (expert >= ROUTER_EXPERTS) return;++ const half2* hidden2 = reinterpret_cast<const half2*>(hidden);+ const half2* gate2 = reinterpret_cast<const half2*>(+ gate_t + static_cast<size_t>(expert) * ROUTER_HIDDEN);++ float sum = 0.0f;+ #pragma unroll 8+ for (int col = lane; col < ROUTER_HIDDEN / 2; col += WAVE_SIZE)+ {+ const half2 h = hidden2[col];+ const half2 g = gate2[col];+ sum = fmaf(__half2float(__low2half(h)), __half2float(__low2half(g)), sum);+ sum = fmaf(__half2float(__high2half(h)), __half2float(__high2half(g)), sum);+ }++ sum = wave_reduce_sum(sum);+ if (lane == 0) scores[expert] = __float2half_rn(sum);+}++// Top-k by rank (same result as the standard routing.cu reduction): every thread holds one expert score and counts, from shared+// memory, the scores that beat it (greater, or equal with a lower expert index); a rank below K is that expert's output slot.+// Then the softmax over the K selected exactly as before: exp(score - max over all experts), lane-order sum, divide.+template <int ROUTER_EXPERTS, int ROUTER_TOP_K>+__global__ __launch_bounds__(ROUTER_EXPERTS)+void routing_std_topk_gfx12_bsz1_kernel+(+ const half* __restrict__ scores,+ int64_t* __restrict__ topk_indices,+ half* __restrict__ topk_weights+)+{+ constexpr int NUM_WAVES = ROUTER_EXPERTS / WAVE_SIZE;+ static_assert(ROUTER_EXPERTS % WAVE_SIZE == 0 && NUM_WAVES <= WAVE_SIZE && ROUTER_TOP_K < WAVE_SIZE, "router shape");++ __shared__ float logits[ROUTER_EXPERTS];+ __shared__ float wave_max[NUM_WAVES];+ __shared__ float global_max;+ __shared__ float selected_exp[ROUTER_TOP_K];+ __shared__ int selected_idx[ROUTER_TOP_K];++ const int tid = threadIdx.x;+ const int lane = tid % WAVE_SIZE;+ const int wave = tid / WAVE_SIZE;+ scores += static_cast<size_t>(blockIdx.x) * ROUTER_EXPERTS;+ topk_indices += static_cast<size_t>(blockIdx.x) * ROUTER_TOP_K;+ topk_weights += static_cast<size_t>(blockIdx.x) * ROUTER_TOP_K;+ const float logit = __half2float(scores[tid]);+ logits[tid] = logit;++ float max_logit = wave_reduce_max(logit);+ if (lane == 0) wave_max[wave] = max_logit;+ __syncthreads();+ if (wave == 0)+ {+ max_logit = lane < NUM_WAVES ? wave_max[lane] : NEG_INF;+ max_logit = wave_reduce_max(max_logit);+ if (lane == 0) global_max = max_logit;+ }++ int rank = 0;+ #pragma unroll 8+ for (int j = 0; j < ROUTER_EXPERTS; ++j)+ {+ const float other = logits[j];+ rank += (other > logit || (other == logit && j < tid)) ? 1 : 0;+ }+ __syncthreads();+ if (rank < ROUTER_TOP_K)+ {+ selected_exp[rank] = logit == global_max ? 1.0f : expf(logit - global_max);+ selected_idx[rank] = tid;+ }+ __syncthreads();++ if (wave == 0)+ {+ const float e = lane < ROUTER_TOP_K ? selected_exp[lane] : 0.0f;+ const float sum = wave_reduce_sum(e) + 1.0e-20f;+ if (lane < ROUTER_TOP_K)+ {+ topk_indices[lane] = static_cast<int64_t>(selected_idx[lane]);+ topk_weights[lane] = __float2half_rn(e / sum);+ }+ }+}++bool is_gfx12_wave32(int device)+{+ hipDeviceProp_t prop;+ if (hipGetDeviceProperties(&prop, device) != hipSuccess) return false;+ const char* arch = prop.gcnArchName;+ // These kernels use only wave-width primitives (__shfl*, __syncwarp) and no+ // RDNA4-only instruction, so every wave32 gfx11.5 / gfx12 part is valid.+ // gfx1150/1151/1152 = RDNA3.5 (Strix Halo), gfx1200/1201 = RDNA4.+ auto is_arch = [arch](const char* name, size_t n) {+ return !std::strncmp(arch, name, n) && (arch[n] == '\0' || arch[n] == ':');+ };+ const bool wave32_arch =+ is_arch("gfx1200", 7) || is_arch("gfx1201", 7) ||+ is_arch("gfx1150", 7) || is_arch("gfx1151", 7) || is_arch("gfx1152", 7);+ return wave32_arch && prop.warpSize == WAVE_SIZE;+}++void check_tensor+(+ const at::Tensor& tensor,+ const at::Device& device,+ at::ScalarType dtype,+ at::IntArrayRef shape,+ const char* name,+ size_t alignment+)+{+ TORCH_CHECK(tensor.is_cuda(), "gm_routing_std_bsz1: ", name, " must be a device tensor");+ TORCH_CHECK(tensor.device() == device, "gm_routing_std_bsz1: ", name,+ " must be on the hidden-state device");+ TORCH_CHECK(tensor.dtype() == dtype, "gm_routing_std_bsz1: ", name,+ " has the wrong dtype");+ TORCH_CHECK(tensor.sizes() == shape, "gm_routing_std_bsz1: ", name,+ " has the wrong shape");+ TORCH_CHECK(tensor.is_contiguous(), "gm_routing_std_bsz1: ", name,+ " must be contiguous");+ TORCH_CHECK(reinterpret_cast<uintptr_t>(tensor.data_ptr()) % alignment == 0,+ "gm_routing_std_bsz1: ", name, " must be ", alignment, "-byte aligned");+}++} // namespace++void gm_routing_std_bsz1+(+ const at::Tensor& hidden,+ const at::Tensor& gate_t,+ at::Tensor& scores,+ at::Tensor& topk_indices,+ at::Tensor& topk_weights+)+{+ TORCH_CHECK(hidden.is_cuda(),+ "gm_routing_std_bsz1: hidden must be a device tensor");+ const at::cuda::OptionalCUDAGuard device_guard(hidden.device());+ const int device = hidden.get_device();+ TORCH_CHECK(is_gfx12_wave32(device),+ "gm_routing_std_bsz1 requires gfx1200/gfx1201 with wave32");++ TORCH_CHECK(hidden.dim() == 2,+ "gm_routing_std_bsz1: hidden must be a 2D tensor");+ const int64_t rows = hidden.size(0);+ TORCH_CHECK(rows > 0 && rows <= MAX_ROUTER_ROWS,+ "gm_routing_std_bsz1 supports 1 through ", MAX_ROUTER_ROWS, " rows");+ TORCH_CHECK(hidden.dim() == 2 && gate_t.dim() == 2 && topk_indices.dim() == 2,+ "gm_routing_std_bsz1: 2D tensors expected");+ const int64_t H = hidden.size(1), E = gate_t.size(0), K = topk_indices.size(1);+ check_tensor(hidden, hidden.device(), at::kHalf, {rows, H}, "hidden", 16);+ check_tensor(gate_t, hidden.device(), at::kHalf, {E, H}, "gate_t", 16);+ check_tensor(scores, hidden.device(), at::kHalf, {rows, E}, "scores", 16);+ check_tensor(topk_indices, hidden.device(), at::kLong, {rows, K}, "topk_indices", 16);+ check_tensor(topk_weights, hidden.device(), at::kHalf, {rows, K}, "topk_weights", 16);++ hipStream_t stream = at::cuda::getCurrentCUDAStream(device).stream();+ const half* h = reinterpret_cast<const half*>(hidden.data_ptr());+ const half* g = reinterpret_cast<const half*>(gate_t.data_ptr());+ half* sc = reinterpret_cast<half*>(scores.data_ptr());+ int64_t* ti = reinterpret_cast<int64_t*>(topk_indices.data_ptr());+ half* tw = reinterpret_cast<half*>(topk_weights.data_ptr());+ #define ROUTER_SHAPE(HH, EE, KK) \+ if (H == HH && E == EE && K == KK) \+ { \+ hipLaunchKernelGGL(( routing_gemv_gfx12_bsz1_kernel<HH, EE>), dim3(dim3(EE / GEMV_WAVES, rows)), dim3(GEMV_WAVES * WAVE_SIZE), 0, stream, h, g, sc); \+ hipLaunchKernelGGL(( routing_std_topk_gfx12_bsz1_kernel<EE, KK>), dim3(rows), dim3(EE), 0, stream, sc, ti, tw); \+ } else+ ROUTER_SHAPE(2560, 512, 10) // Qwen3.8-Flash-Next+ ROUTER_SHAPE(2048, 256, 8) // Qwen3.6-35B-A3B (GGUF and EXL3 packs)+ ROUTER_SHAPE(2048, 128, 8) // Qwen3-30B-A3B (qwen3moe)+ TORCH_CHECK(false, "gm_routing_std_bsz1: unsupported router shape ", H, " x ", E, " top-", K);+ #undef ROUTER_SHAPE+ TORCH_CHECK(hipPeekAtLastError() == hipSuccess, "gm_routing_std_bsz1: launch failed");+}++#endif // USE_ROCMdiff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex 042a205..4315db0 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -570,6 +570,7 @@ class Hy4Forward:lat = (k_.moe_prefill_i8 if PF_MOE_I8 else k_.moe_prefill)(z, sel, w, (rsp.bufs["gate"], rsp.bufs["up"], rsp.bufs["down"]), (k_.FROM_GROUPED[rsp.fu], k_.FROM_GROUPED[rsp.fd]), lim,rsp.nff, rsp.nout, (rsp.strides[0], rsp.strides[2]), rsp.ebytes, rsp.E, tm=tm)self.stats["prefill_moe_calls"] = self.stats.get("prefill_moe_calls", 0) + 1+ self.stats["moe_path_" + getattr(k_, "LAST_PATH", "?")] = self.stats.get("moe_path_" + getattr(k_, "LAST_PATH", "?"), 0) + 1sel_l = []rs = self.res.get(i) if (T <= MMVQ_MAXR and dev.type == "cuda") else Noneif rs is not None:diff --git a/exllamav3/loader/kq_moe_hip.py b/exllamav3/loader/kq_moe_hip.pynew file mode 100644index 0000000..44077ca--- /dev/null+++ b/exllamav3/loader/kq_moe_hip.py@@ -0,0 +1,114 @@+"""HIP / gfx1151 WMMA grouped MoE expert GEMM on the stored bytes of GGUF k-quants (Q4_K, Q3_K). Generic by quant type and shape.++gate_up(x, Wg, Wu, sp, be, P, topk, E, ebytes, lim, K, N, rowb, fmt, maxb) -> H fp16 [maxb*128, N] (SwiGLU applied)+down(H, Wd, wts, sp, be, P, E, ebytes, K, N, rowb, maxb) -> out fp32 [P, N] (rows scaled by wts[pair])+Block tables as in prefill_kernels.route_blocks with BM = 128. The code object is built by build_moe.sh (separate process, SDK toolchain);+it is loaded here through the HIP runtime torch already has in the process.+"""+import ctypes, os, re+import torch++MT = 128+_lib = None+_mod = {}+++def _hip():+ global _lib+ if _lib is None:+ path = None+ for line in open("/proc/self/maps"):+ m = re.search(r"(/\S*libamdhip64\.so[\d.]*)", line)+ if m:+ path = m.group(1)+ break+ _lib = ctypes.CDLL(path)+ return _lib+++def _fn(co, name):+ key = (co, name)+ if key not in _mod:+ lib = _hip()+ data = open(co, "rb").read()+ mod = ctypes.c_void_p()+ assert lib.hipModuleLoadData(ctypes.byref(mod), ctypes.c_char_p(data)) == 0, "hipModuleLoadData"+ fn = ctypes.c_void_p()+ assert lib.hipModuleGetFunction(ctypes.byref(fn), mod, name.encode()) == 0, "hipModuleGetFunction " + name+ _mod[key] = (mod, fn)+ return _mod[key][1]+++CO = os.environ.get("KQ_MOE_CO", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "exllamav3_ext", "hip_kq", "moe_hip.co"))+++def _launch(name, grid, args):+ lib = _hip()+ fn = _fn(CO, name)+ cargs = []+ for a in args:+ if isinstance(a, torch.Tensor):+ cargs.append(ctypes.c_void_p(a.data_ptr()))+ elif isinstance(a, float):+ cargs.append(ctypes.c_float(a))+ elif isinstance(a, tuple): # (value, ctypes type)+ cargs.append(a[1](a[0]))+ else:+ cargs.append(ctypes.c_int(a))+ ptrs = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.pointer(c), ctypes.c_void_p) for c in cargs])+ stream = torch.cuda.current_stream().cuda_stream+ rc = lib.hipModuleLaunchKernel(fn, grid[0], grid[1], 1, 256, 1, 1, 0, ctypes.c_void_p(stream), ptrs, None)+ assert rc == 0, f"hipModuleLaunchKernel {name} rc={rc}"+++def gate_up(x, Wg, Wu, sp, be, P, topk, E, ebytes, lim, K, N, rowb, fmt, maxb):+ """fmt: 0 = Q4_K, 1 = Q3_K (FMT ids of prefill_kernels)"""+ assert K % 64 == 0 and N % 128 == 0+ H = torch.empty(maxb * MT, N, dtype=torch.float16, device=x.device)+ _launch("gu_q4" if fmt == 0 else "gu_q3", (N // 128, maxb),+ [x, Wg, Wu, H, sp, be, P, topk, E, (ebytes, ctypes.c_long), float(lim), K, N, rowb])+ return H+++def down(H, Wd, wts, sp, be, P, E, ebytes, K, N, rowb, maxb, fmt=0):+ assert fmt == 0 and K % 64 == 0 and N % 256 == 0+ out = torch.empty(P, N, dtype=torch.float32, device=H.device)+ _launch("down_q4", (N // 256, maxb), [H, Wd, out, wts, sp, be, P, E, (ebytes, ctypes.c_long), K, N, rowb])+ return out+++# ---- the shared generic GGUF kernel (gguf-moe gm_ext / gm_pfmoe.cu: same kernels, per-expert pointer tables, Q3_K gate/up via fmt 3) ----+_gm = None+_ptrs = {}+++def shared_module():+ global _gm+ if _gm is None:+ import importlib.util+ so = os.environ.get("HY4_GM_EXT", os.path.expanduser("~/.cache/exl3_gm_ext/exl3_gm_ext.so"))+ spec = importlib.util.spec_from_file_location("exl3_gm_ext", so)+ _gm = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(_gm)+ return _gm+++def _table(buf, ebytes, E):+ key = (buf.data_ptr(), ebytes, E)+ if key not in _ptrs:+ _ptrs[key] = (buf.data_ptr() + torch.arange(E, dtype=torch.int64, device=buf.device) * ebytes)+ return _ptrs[key]+++def gate_up_shared(x, Wg, Wu, sp, be, P, topk, E, ebytes, lim, K, N, rowb, fmt, maxb):+ m = shared_module()+ H = torch.empty(maxb * MT, N, dtype=torch.float16, device=x.device)+ m.gm_pf_gate_up(x, _table(Wg, ebytes, E), _table(Wu, ebytes, E), H, sp, be, P, topk, E, float(lim), K, N, rowb, maxb, 0 if fmt == 0 else 3)+ return H+++def down_shared(H, Wd, wts, sp, be, P, E, ebytes, K, N, rowb, maxb):+ m = shared_module()+ out = torch.empty(P, N, dtype=torch.float32, device=H.device)+ m.gm_pf_down(H, _table(Wd, ebytes, E), wts, sp, be, out, P, E, K, N, rowb, 0, maxb)+ return outdiff --git a/exllamav3/loader/prefill_kernels.py b/exllamav3/loader/prefill_kernels.pyindex c2f397f..315a42c 100644--- a/exllamav3/loader/prefill_kernels.py+++ b/exllamav3/loader/prefill_kernels.py@@ -434,6 +434,8 @@ def to_f16(x):MOE_NF = None # tests: force the grid order (None = env HY4_MOE_NFIRST)+LAST_PATH = "" # path the last moe_prefill call ran (triton / hip_wmma / gm_pfmoe_shared); gmmq is not called from this module+MOE_HIP = None # tests: force (None = env HY4_MOE_HIP=1); HIP / WMMA expert kernels (moe_hip.cu, 128-row blocks, Q4_K / Q3_K); off = TritonMOE_CFG = None # None = chosen from the rows per expert (see moe_cfg)DENSE_CFG = {"BM": 128, "BN": 128, "warps": 8, "stages": 1}@@ -483,6 +485,19 @@ def moe_prefill(z, sel, w, bufs, fmts, lim, nff, nout, rowb, ebytes, E, cfg=Nonewith t("f moe: route + sort"):sp, be, maxb = route_blocks(sel.to(torch.int64), E, BM)x = to_f16(z).contiguous()+ use_hip = BM == 128 and nf and (MOE_HIP if MOE_HIP is not None else os.environ.get("HY4_MOE_HIP", "0") in ("1", "2")) and K % 64 == 0 and nff % 128 == 0 and nout % 128 == 0 and fmts[0] in (FMT_Q4K, FMT_Q3K) and fmts[1] == FMT_Q4K+ global LAST_PATH+ LAST_PATH = "triton"+ if use_hip:+ from . import kq_moe_hip as KH+ sh = os.environ.get("HY4_MOE_HIP", "0") == "2"+ LAST_PATH = "gm_pfmoe_shared" if sh else "hip_wmma" # 2 = the shared gguf-moe gm_ext kernel (same source family), 1 = the local code object+ with t("f moe: gate+up kernel"):+ H = (KH.gate_up_shared if sh else KH.gate_up)(x, bufs[0], bufs[1], sp, be, P, S, E, ebytes[0], float(lim), K, nff, rowb[0], 0 if fmts[0] == FMT_Q4K else 1, maxb)+ with t("f moe: down kernel"):+ out = (KH.down_shared if sh else KH.down)(H, bufs[2], w.reshape(-1).float().contiguous(), sp, be, P, E, ebytes[1], nff, nout, rowb[1], maxb)+ with t("f moe: sum over topk"):+ return out.view(T, S, nout).sum(1)H = torch.empty(maxb * BM, nff, dtype=torch.float16, device=z.device)with t("f moe: gate+up kernel"):_gu_kernel[((nff // BN, maxb) if nf else (maxb, nff // BN))](x, bufs[0], bufs[1], H, sp, be, P, S, E, ebytes[0], float(lim), K=K, N=nff, ROWB=rowb[0], FMT=fmts[0], BM=BM, BN=BN,diff --git a/tools/gguf_moe/r8_moe.py b/tools/gguf_moe/r8_moe.pynew file mode 100644index 0000000..28aa5ad--- /dev/null+++ b/tools/gguf_moe/r8_moe.py@@ -0,0 +1,36 @@+# r8_moe.py MODEL_DIR: gm_moe_kq_decode on R = 4 rows vs 4 one-row calls, same explicit routing, on a Q4_K-down and a Q6_K-down layer.+import os, sys, torch+sys.path.insert(0, os.environ.get("EXL3_ROOT", os.getcwd()))+torch.set_grad_enabled(False)+from exllamav3 import Config, Model+from exllamav3.modules.block_sparse_mlp import BlockSparseMLP+from exllamav3 import gm_ext+config = Config.from_directory(sys.argv[1]); model = Model.from_config(config); model.load(device="cuda:0", progressbar=False)+dev = "cuda:0"; m_ext = gm_ext.get()+def walk(ms):+ for m in ms:+ if isinstance(m, BlockSparseMLP): yield m+ else: yield from walk(getattr(m, "modules", []) or [])+mods = list(walk(model.modules)); K, I, E, S = 2048, 768, 128, 8+seen = set()+for m in mods:+ f = m._fq_grouped_kq_ok(torch.zeros(4, K, dtype=torch.half, device=dev))+ if f in seen: continue+ seen.add(f)+ mk = lambda ms: torch.tensor([x.packed.data_ptr() for x in ms], dtype=torch.int64, device=dev)+ g, u, d = mk(m.gates), mk(m.ups), mk(m.downs)+ fd = 0 if f[1] == "q4_k" else 2+ gs = (K // 256) * 144; ds = (I // 256) * (144 if fd == 0 else 210)+ torch.manual_seed(5)+ h = (torch.randn(4, K, device=dev) * 0.5).half()+ sel = torch.stack([torch.randperm(E, device=dev)[:S] for _ in range(4)]).long()+ w = torch.softmax(torch.randn(4, S, device=dev), -1).half()+ def run(hh, ss, ww):+ R = hh.shape[0]+ act = torch.empty(8 * S, I, dtype=torch.half, device=dev); qb = torch.empty(8 * K // 32 * 36, dtype=torch.uint8, device=dev)+ part = torch.empty(8 * S, K, dtype=torch.float, device=dev); out = torch.empty(R, K, dtype=torch.float, device=dev)+ m_ext.gm_moe_kq_decode(hh.contiguous(), ss.reshape(-1).contiguous(), ww.reshape(-1).contiguous(), g, u, d, gs, gs, ds, fd, act, qb, part, out, torch.empty(0, dtype=torch.float, device=dev))+ return out+ o4 = run(h, sel, w)+ o1 = torch.cat([run(h[i:i + 1], sel[i:i + 1], w[i:i + 1]) for i in range(4)])+ print("gm_moe_kq_decode R=4 vs 4 x R=1 bit-exact:", torch.equal(o4, o1), f, "max diff", (o4 - o1).abs().max().item(), flush=True)diff --git a/tools/gguf_moe/r8_test.py b/tools/gguf_moe/r8_test.pynew file mode 100644index 0000000..4ab6e36--- /dev/null+++ b/tools/gguf_moe/r8_test.py@@ -0,0 +1,56 @@+# r8_test.py MODEL_DIR: (1) bit-exactness of the R-row gm_ext decode ops against R one-row calls (qkv, MoE layer), (2) T-row decode forward: ms per forward+# and teacher-forced PPL on 1024 wiki tokens for T = 1, 2, 3, 4, 6, 8 rows per forward (verify rows). Arm = env (EXL3_GM=0 stock rows).+import os, sys, time, math, json+import torch+sys.path.insert(0, os.environ.get("EXL3_ROOT", os.getcwd()))+torch.set_grad_enabled(False)+from exllamav3 import Config, Model, Cache+from exllamav3.modules.attn import Attention+from exllamav3.modules.block_sparse_mlp import BlockSparseMLP+d, ids_json = sys.argv[1], sys.argv[2]+config = Config.from_directory(d); model = Model.from_config(config)+cache = Cache(model, max_num_tokens=2048 + 256); model.load(device="cuda:0", progressbar=False)+dev = "cuda:0"+def walk(ms, cls):+ for m in ms:+ if isinstance(m, cls): yield m+ else: yield from walk(getattr(m, "modules", []) or [], cls)+if os.environ.get("EXL3_GM", "1") != "0":+ torch.manual_seed(3)+ for a in list(walk(model.modules, Attention))[:4]:+ K = a.q_proj.in_features; x = (torch.randn(4, 1, K, device=dev) * 0.5).half()+ r4 = a._qkv_gm3(x, {}, 4, 1)+ if r4 is None: print("qkv gm3 declined", a.key); continue+ ok = True+ for i in range(4):+ r1 = a._qkv_gm3(x[i:i + 1], {}, 1, 1)+ ok &= all(torch.equal(u[i:i + 1], w) for u, w in zip(r4, r1))+ print("qkv R=4 bit-exact vs 4 x R=1:", ok, a.key, flush=True)+ seen = set()+ for m in walk(model.modules, BlockSparseMLP):+ f = m._fq_grouped_kq_ok(torch.zeros(4, 2048, dtype=torch.half, device=dev))+ if f in seen: continue+ seen.add(f); K = 2048+ y = (torch.randn(4, 1, K, device=dev) * 0.5).half()+ r4 = m.forward(y, {}).clone()+ ok = all(torch.equal(r4[i:i + 1], m.forward(y[i:i + 1], {})) for i in range(4))+ print("moe R=4 bit-exact vs 4 x R=1:", ok, f, m.key, flush=True)+ids = torch.tensor([json.load(open(ids_json))[:1024]], dtype=torch.long)+pages = cache.max_num_tokens // 256+bt = torch.arange(pages, dtype=torch.int32, device=dev).view(1, pages)+res = {}+for T in (1, 2, 3, 4, 6, 8):+ sl = torch.zeros(1, dtype=torch.int32, device=dev); nll = 0.0; cnt = 0; tms = []+ for i in range(0, 1024 - T, T):+ x = ids[:, i:i + T].to(dev)+ torch.cuda.synchronize(); t0 = time.time()+ lg = model.forward(x, {"attn_mode": "flash_attn", "block_table": bt, "cache": cache, "cache_seqlens": sl})+ torch.cuda.synchronize(); tms.append(time.time() - t0)+ sl += T+ if i >= 32:+ lp = torch.log_softmax(lg[0].float(), dim=-1)+ tg = ids[0, i + 1:i + T + 1].to(dev)+ nll += -lp[torch.arange(len(tg)), tg].sum().item() if len(tg) == T else 0.0; cnt += len(tg) if len(tg) == T else 0+ ms = sorted(tms[16:])[len(tms[16:]) // 2] * 1000+ res[T] = (round(ms, 2), round(math.exp(nll / cnt), 4)); print(f"T={T} median {ms:.2f} ms/forward ppl {math.exp(nll / cnt):.4f}", flush=True)+print("RESULT", json.dumps(res), flush=True)