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 experts v2 (HY4_MOE_V2, default off): HIP code object for the grouped MoE stages, Q3_K gate/up one thread per 256-block, Q4_K unrolled loads with LDS activations; bit-equal to the shipped kernels; opbench experts_v2 A/B and paired ABBA driver
YanissAmz0f81106e977a
diff --git a/exllamav3/exllamav3_ext/hip_kq/build_moe.sh b/exllamav3/exllamav3_ext/hip_kq/build_moe.shindex a130ec6..4ce41e2 100644--- a/exllamav3/exllamav3_ext/hip_kq/build_moe.sh+++ b/exllamav3/exllamav3_ext/hip_kq/build_moe.sh@@ -6,5 +6,5 @@ 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/bitcodeexport 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+$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 -400ls -la "$OUT"diff --git a/exllamav3/exllamav3_ext/hip_kq/moe_dec.cu b/exllamav3/exllamav3_ext/hip_kq/moe_dec.cunew file mode 100644index 0000000..50905b4--- /dev/null+++ b/exllamav3/exllamav3_ext/hip_kq/moe_dec.cu@@ -0,0 +1,569 @@+// Decode MoE (grouped, q8_1 activations) kernels for GGUF k-quants, gfx1151 device-only code object (build: hip_kq/build_moe.sh).+// Same arithmetic and accumulation order as fq_moe_kq.cu (fq_moe_kq_upgate_kernel<8> / fq_moe_kq_upgate_v2_kernel / fq_moe_kq_down_v2_kernel<0>):+// outputs are bit-equal. Kernels with the suffix _ref are verbatim copies kept for the A/B; _v3 are the rewrites:+// * K / I are template parameters (NB = K / 256): every weight load of a thread is issued before its first dot (full unroll),+// * the q8_1 activation row of the slot is staged once in LDS (the reference re-reads it from global per item),+// * Q3_K (110-byte blocks, 2-byte aligned): one thread per 256-block, whole block loaded as 28 dwords (alignbyte shift for odd blocks),+// the 16 scale values are decoded once per block, gate and up share the activation reads.+// Assignment s = row * topk + j reads activation row s / topk; perm (optional) is the expert-major slot order of the sort kernel.+#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>+#include <stdint.h>++#define Q8_1_BYTES 36+#define Q4_K_BYTES 144+#define Q3_K_BYTES 110+#define OUT_PER_BLOCK 8+#define LANES 32+#define ROWS 32+#define PS 33++__device__ __forceinline__ int dp4a_(int a, int b, int c) { return __builtin_amdgcn_sudot4(true, a, true, b, c, false); }+__device__ __forceinline__ float h2f_lo(uint32_t w) { uint16_t lo = (uint16_t)(w & 0xFFFFu); __half h; __builtin_memcpy(&h, &lo, 2); return __half2float(h); }+__device__ __forceinline__ uint32_t 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;+}++__device__ __forceinline__ void slot_tile(int b, int ntiles, int S, const int32_t* __restrict__ perm, int nslots, int& s, int& t)+{+ if (perm != nullptr) { const int p = b % nslots; t = b / nslots; s = (p < S) ? (int)perm[p] : p; }+ else { s = b / ntiles; t = b % ntiles; }+}++extern "C" {++// ---- sort: perm[rank of assignment i by (expert id, i)] = i (verbatim)+__global__ void moe_sort(const int64_t* __restrict__ sel, int32_t* __restrict__ perm, int S, int E)+{+ const int i = threadIdx.x;+ if (i < S)+ {+ int64_t k = sel[i]; k = (k < 0 || k >= E) ? 0 : k;+ int rank = 0;+ for (int j = 0; j < S; j++) { int64_t kj = sel[j]; kj = (kj < 0 || kj >= E) ? 0 : kj; rank += (kj < k) || (kj == k && j < i); }+ perm[rank] = i;+ }+}++// ---- q8_1 quantisation of fp16 rows (verbatim fq_quant_q8_1_kernel<__half>): grid M * K/32, 32 threads+__global__ void moe_quant_q8_1(const __half* __restrict__ x, uint8_t* __restrict__ qb, int M, int K)+{+ const int blk = blockIdx.x, nb32 = K / 32, m = blk / nb32, b = blk % nb32, tid = threadIdx.x;+ if (m >= M) return;+ const __half* xr = x + (int64_t)m * K + (int64_t)b * 32;+ float amax = 0.0f;+ #pragma unroll+ for (int i = 0; i < 32; i++) amax = fmaxf(amax, fabsf(__half2float(xr[i])));+ float d = amax / 127.0f;+ float v = __half2float(xr[tid]);+ int q = (amax == 0.0f) ? 0 : (int)roundf(v / d);+ q = q < -127 ? -127 : (q > 127 ? 127 : q);+ uint8_t* qbblk = qb + ((int64_t)m * nb32 + b) * Q8_1_BYTES;+ qbblk[4 + tid] = (uint8_t)(int8_t)q;+ if (tid == 0)+ {+ float sum = 0.0f;+ #pragma unroll+ for (int i = 0; i < 32; i++) sum += __half2float(xr[i]);+ __half dh = __float2half_rn(d), sh = __float2half_rn(sum);+ uint16_t dhb, shb;+ __builtin_memcpy(&dhb, &dh, 2); __builtin_memcpy(&shb, &sh, 2);+ *reinterpret_cast<uint16_t*>(qbblk) = dhb;+ *reinterpret_cast<uint16_t*>(qbblk + 2) = shb;+ }+}++// ---- combine (verbatim, no shared expert): out[r] = sum_s partial[r*S+s] * wts[r*S+s]+__global__ void moe_combine(const float* __restrict__ partial, const __half* __restrict__ wts, float* __restrict__ out, int S, int K)+{+ partial += (int64_t)blockIdx.y * S * K; wts += (int64_t)blockIdx.y * S; out += (int64_t)blockIdx.y * K;+ for (int k = blockIdx.x * blockDim.x + threadIdx.x; k < K; k += gridDim.x * blockDim.x)+ {+ float acc = 0.0f;+ #pragma unroll+ for (int s = 0; s < 32; s++) if (s < S) acc = __fadd_rn(acc, __fmul_rn(partial[(int64_t)s * K + k], __half2float(wts[s])));+ out[k] = acc;+ }+}++} // extern "C"++// ================================================================== Q3_K v1 dot (verbatim fq_dot_q3_k_q8) and reference gate/up+__device__ float dot_q3_k_ref(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aqb, int K, int tid, int nthreads)+{+ int nsub = K / 16; float acc = 0.0f;+ for (int c = tid; c < nsub; c += nthreads)+ {+ int b = c >> 4, iqs = c & 15;+ const uint8_t* blk = wr + (size_t)b * Q3_K_BYTES;+ int bq8_offset = 4 * (iqs / 8), scale_offset = iqs - iqs % 8 + (iqs % 8) / 4;+ int32_t vl, vm;+ __builtin_memcpy(&vl, blk + 32 + 4 * iqs, 4); __builtin_memcpy(&vm, blk + 4 * (iqs % 8), 4);+ int32_t vh = ~vm >> bq8_offset;+ const uint8_t* scales = blk + 96;+ __half dh; __builtin_memcpy(&dh, blk + 108, 2);+ float d = __half2float(dh), sumf = 0.0f;+ #pragma unroll+ for (int i = 0; i < 4; i++)+ {+ int isc = scale_offset + 2 * i;+ int sc_low = (scales[isc % 8] >> (4 * (isc / 8))) & 0xF;+ int sc_high = ((scales[8 + isc % 4] >> (2 * (isc / 4))) & 3) << 4;+ int sc = (sc_low | sc_high) - 32;+ uint32_t vil = ((uint32_t)vl >> (2 * i)) & 0x03030303u;+ uint32_t vih = (uint32_t)((vh >> i) << 2) & 0x04040404u;+ uint32_t vi = vsub4_(vil, vih);+ const uint8_t* aqb_blk = aqb + (size_t)(b * 8 + bq8_offset + i) * Q8_1_BYTES;+ __half dah; __builtin_memcpy(&dah, aqb_blk, 2);+ float d8 = __half2float(dah);+ int32_t u; __builtin_memcpy(&u, aqb_blk + 4 + 4 * (iqs % 8), 4);+ sumf = __fadd_rn(sumf, __fmul_rn(d8, (float)(dp4a_((int32_t)vi, u, 0) * sc)));+ }+ acc = __fadd_rn(acc, __fmul_rn(d, sumf));+ }+ return acc;+}++extern "C" {++// reference: fq_moe_kq_upgate_kernel<8> (256 threads, 8 rows per block, 32 lanes per row), dynamic LDS 256 * 2 * 4 bytes+__global__ void ug_q3_ref(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, int64_t qb_stride,+ __half* __restrict__ act, int S, int I, int K, int E, int ntiles_u, int topk, float lim,+ const int32_t* __restrict__ perm, int nslots)+{+ int s, t; slot_tile(blockIdx.x, ntiles_u, S, perm, nslots, s, t);+ int grp = threadIdx.x / LANES, lane = threadIdx.x % LANES;+ int64_t e = sel[s]; e = (e < 0 || e >= E) ? 0 : e;+ int n = t * OUT_PER_BLOCK + grp;+ const uint8_t* aq = aqb + (int64_t)(s / topk) * qb_stride;+ extern __shared__ float red[];+ float g = 0.0f, u = 0.0f;+ if (n < I)+ {+ g = dot_q3_k_ref(gate_bases[e] + (int64_t)n * gate_stride, aq, K, lane, LANES);+ u = dot_q3_k_ref(up_bases[e] + (int64_t)n * up_stride, aq, K, lane, LANES);+ }+ red[2 * threadIdx.x] = g; red[2 * threadIdx.x + 1] = u;+ __syncthreads();+ if (n < I && lane == 0)+ {+ float sg = 0.0f, su = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++) { sg = __fadd_rn(sg, red[(grp * 32 + l) * 2]); su = __fadd_rn(su, red[(grp * 32 + l) * 2 + 1]); }+ float gh = __half2float(__float2half_rn(sg)), uh = __half2float(__float2half_rn(su));+ if (lim > 0.0f) { gh = fminf(gh, lim); uh = fminf(fmaxf(uh, -lim), lim); }+ float sig = 1.0f / (1.0f + expf(-gh));+ act[(int64_t)s * I + n] = __float2half_rn(sig * gh * uh);+ }+}++} // extern "C"++// ================================================================== Q4_K items+struct Q4It { uint32_t hd, s0, s1, s2; uint4 va, vb; };++__device__ __forceinline__ void q4_load(const uint8_t* __restrict__ wr, int it, Q4It& r)+{+ const int b = it >> 2, g = it & 3;+ const uint8_t* blk = wr + (size_t)b * Q4_K_BYTES;+ r.hd = *reinterpret_cast<const uint32_t*>(blk);+ const uint32_t* sp = reinterpret_cast<const uint32_t*>(blk + 4);+ r.s0 = sp[0]; r.s1 = sp[1]; r.s2 = sp[2];+ r.va = *reinterpret_cast<const uint4*>(blk + 16 + 32 * g);+ r.vb = *reinterpret_cast<const uint4*>(blk + 16 + 32 * g + 16);+}++// verbatim fq_kq_item_q4_k arithmetic; the q8_1 row comes from LDS words aql (9 words per 32-block)+__device__ __forceinline__ void q4_comp(const Q4It& r, int it, const uint32_t* __restrict__ aql, float* __restrict__ dst)+{+ const int b = it >> 2, g = it & 3;+ const uint32_t* a0 = aql + (b * 8 + 2 * g) * 9;+ const uint32_t* a1 = a0 + 9;+ const float dm0 = h2f_lo(r.hd), dm1 = h2f_lo(r.hd >> 16);+ const float d8[2] = {h2f_lo(a0[0]), h2f_lo(a1[0])};+ const int sh = 16 * (g & 1);+ const uint32_t s0 = (r.s0 >> sh) & 0xFFFFu, s2 = (r.s1 >> sh) & 0xFFFFu, s4 = (r.s2 >> 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] = {r.va.x, r.va.y, r.va.z, r.va.w};+ const uint32_t w1[4] = {r.vb.x, r.vb.y, r.vb.z, r.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 uint32_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 = (int32_t)a[1 + qo], u1 = (int32_t)a[5 + qo];+ int dot1 = dp4a_((int32_t)v0i, u0, 0);+ dot1 = dp4a_((int32_t)v1i, u1, dot1);+ int dot2 = dp4a_(0x01010101, u0, 0);+ dot2 = 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));+ }+}++template <int NB>+__device__ __forceinline__ void stage_act(uint32_t* __restrict__ aql, const uint8_t* __restrict__ aq)+{+ const uint32_t* src = reinterpret_cast<const uint32_t*>(aq);+ for (int i = threadIdx.x; i < NB * 8 * 9; i += blockDim.x) aql[i] = src[i];+ __syncthreads();+}++// Q4_K gate+up, v3: 32 rows per block, 8 threads per row, items j, j + 8, ... all loaded before the first dot. grid Sg * (I / 32) x 256+template <int NB>+__device__ __forceinline__ void ug_q4_v3_body(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,+ int64_t qb_stride, __half* __restrict__ act, int S, int I, int E, int ntiles_u, int topk, float lim,+ const int32_t* __restrict__ perm, int nslots)+{+ constexpr int NIT = NB * 4, PER = (NIT + 7) / 8;+ __shared__ float pg[ROWS * PS];+ __shared__ float pu[ROWS * PS];+ __shared__ uint32_t aql[NB * 8 * 9];+ int s, t; slot_tile(blockIdx.x, ntiles_u, S, perm, nslots, s, t);+ const int r = threadIdx.x >> 3, j = threadIdx.x & 7;+ int64_t e = sel[s]; e = (e < 0 || e >= E) ? 0 : e;+ const int n = t * ROWS + r;+ const uint8_t* gr = gate_bases[e] + (int64_t)n * gate_stride;+ const uint8_t* ur = up_bases[e] + (int64_t)n * up_stride;+ Q4It G[PER], U[PER];+ #pragma unroll+ for (int p = 0; p < PER; p++) if (NIT % 8 == 0 || j + 8 * p < NIT) { q4_load(gr, j + 8 * p, G[p]); q4_load(ur, j + 8 * p, U[p]); }+ stage_act<NB>(aql, aqb + (int64_t)(s / topk) * qb_stride);+ float ag[4] = {0.0f, 0.0f, 0.0f, 0.0f}, au[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ #pragma unroll+ for (int p = 0; p < PER; p++)+ if (NIT % 8 == 0 || j + 8 * p < NIT)+ {+ float tg[4], tu[4];+ q4_comp(G[p], j + 8 * p, aql, tg);+ q4_comp(U[p], j + 8 * p, aql, 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 * PS + 4 * j + q] = ag[q]; pu[r * PS + 4 * j + q] = au[q]; }+ __syncthreads();+ if (j == 0)+ {+ float sg = 0.0f, su = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++) { sg = __fadd_rn(sg, pg[r * PS + l]); su = __fadd_rn(su, pu[r * PS + l]); }+ float gh = __half2float(__float2half_rn(sg)), uh = __half2float(__float2half_rn(su));+ if (lim > 0.0f) { gh = fminf(gh, lim); uh = fminf(fmaxf(uh, -lim), lim); }+ float sig = 1.0f / (1.0f + expf(-gh));+ act[(int64_t)s * I + n] = __float2half_rn(sig * gh * uh);+ }+}++extern "C" {+#define UG_Q4(NBV) \+__global__ void __launch_bounds__(256) ug_q4_v3_##NBV(const uint8_t* __restrict__ aqb, const int64_t* __restrict__ sel, \+ const uint8_t* const* __restrict__ gb, const uint8_t* const* __restrict__ ub, int64_t gs, int64_t us, int64_t qs, \+ __half* __restrict__ act, int S, int I, int E, int ntiles, int topk, float lim, const int32_t* __restrict__ perm, int nslots) \+{ ug_q4_v3_body<NBV>(aqb, sel, gb, ub, gs, us, qs, act, S, I, E, ntiles, topk, lim, perm, nslots); }+UG_Q4(6)+UG_Q4(8)+UG_Q4(16)++} // extern "C"++// Q4_K down, v3 (act row of slot s from the q8_1 act scratch): partial[s, n] = sum over the 32 lane partials in order. grid S * (K / 32) x 256+template <int NB>+__device__ __forceinline__ void dn_q4_v3_body(const uint8_t* __restrict__ aqb, int64_t qb_stride, const int64_t* __restrict__ sel,+ const uint8_t* const* __restrict__ down_bases, int64_t down_stride, float* __restrict__ partial, int S, int K, int E, int ntiles_d,+ const int32_t* __restrict__ perm, int nslots)+{+ constexpr int NIT = NB * 4, PER = (NIT + 7) / 8;+ __shared__ float pp[ROWS * PS];+ __shared__ uint32_t aql[NB * 8 * 9];+ int s, t; slot_tile(blockIdx.x, ntiles_d, S, perm, nslots, s, t);+ const int r = threadIdx.x >> 3, j = threadIdx.x & 7;+ int64_t e = sel[s]; e = (e < 0 || e >= E) ? 0 : e;+ const int n = t * ROWS + r;+ const uint8_t* dr = down_bases[e] + (int64_t)n * down_stride;+ Q4It D[PER];+ #pragma unroll+ for (int p = 0; p < PER; p++) if (NIT % 8 == 0 || j + 8 * p < NIT) q4_load(dr, j + 8 * p, D[p]);+ stage_act<NB>(aql, aqb + (int64_t)s * qb_stride);+ float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ #pragma unroll+ for (int p = 0; p < PER; p++)+ if (NIT % 8 == 0 || j + 8 * p < NIT)+ {+ float tv[4];+ q4_comp(D[p], j + 8 * p, aql, 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 * PS + 4 * j + q] = acc[q];+ __syncthreads();+ if (j == 0)+ {+ float sp = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++) sp = __fadd_rn(sp, pp[r * PS + l]);+ partial[(int64_t)s * K + n] = sp;+ }+}++extern "C" {+#define DN_Q4(NBV) \+__global__ void __launch_bounds__(256) dn_q4_v3_##NBV(const uint8_t* __restrict__ aqb, int64_t qs, const int64_t* __restrict__ sel, \+ const uint8_t* const* __restrict__ db, int64_t ds, float* __restrict__ partial, int S, int K, int E, int ntiles, \+ const int32_t* __restrict__ perm, int nslots) \+{ dn_q4_v3_body<NBV>(aqb, qs, sel, db, ds, partial, S, K, E, ntiles, perm, nslots); }+DN_Q4(6)+DN_Q4(8)+DN_Q4(16)++} // extern "C"++// ================================================================== Q3_K gate+up v3: one thread per (row, 256-block), NB blocks per row+struct Q3B { uint32_t w[28]; };++__device__ __forceinline__ void q3_load(const uint8_t* __restrict__ blk, Q3B& r)+{+ const uintptr_t a = (uintptr_t)blk;+ const uint32_t* p = reinterpret_cast<const uint32_t*>(a & ~(uintptr_t)3);+ uint32_t t[28];+ #pragma unroll+ for (int k = 0; k < 28; k++) t[k] = p[k];+ const bool odd = (a & 2) != 0;+ #pragma unroll+ for (int k = 0; k < 27; k++) r.w[k] = odd ? __builtin_amdgcn_alignbyte(t[k + 1], t[k], 2) : t[k];+ r.w[27] = odd ? (t[27] >> 16) : t[27];+}++__device__ __forceinline__ void q3_scales(const Q3B& B, int* __restrict__ sc)+{+ #pragma unroll+ for (int k = 0; k < 16; k++)+ {+ const int i0 = k % 8, i1 = 8 + k % 4;+ const int s0 = (B.w[24 + (i0 >> 2)] >> (8 * (i0 & 3))) & 0xFF;+ const int s1 = (B.w[24 + (i1 >> 2)] >> (8 * (i1 & 3))) & 0xFF;+ sc[k] = (((s0 >> (4 * (k / 8))) & 0xF) | (((s1 >> (2 * (k / 4))) & 3) << 4)) - 32;+ }+}++template <int NB>+__device__ __forceinline__ void ug_q3_v3_body(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,+ int64_t qb_stride, __half* __restrict__ act, int S, int I, int E, int ntiles_u, int topk, float lim,+ const int32_t* __restrict__ perm, int nslots)+{+ constexpr int RS = NB * 16 + 1;+ extern __shared__ float lds[]; // pg[ROWS * RS], pu[ROWS * RS], aql[NB * 72]+ float* pg = lds; float* pu = lds + ROWS * RS;+ float* dgs = lds + 2 * ROWS * RS; float* dus = dgs + ROWS * NB; // block scales d (the lane accumulation is fma(d, sumf, acc), as the compiler fuses it in the reference)+ uint32_t* aql = reinterpret_cast<uint32_t*>(lds + 2 * ROWS * RS + 2 * ROWS * NB);+ int s, t; slot_tile(blockIdx.x, ntiles_u, S, perm, nslots, s, t);+ const int r = threadIdx.x / NB, b = threadIdx.x % NB;+ int64_t e = sel[s]; e = (e < 0 || e >= E) ? 0 : e;+ const int n = t * ROWS + r;+ Q3B G, U;+ q3_load(gate_bases[e] + (int64_t)n * gate_stride + (size_t)b * Q3_K_BYTES, G);+ q3_load(up_bases[e] + (int64_t)n * up_stride + (size_t)b * Q3_K_BYTES, U);+ {+ const uint32_t* src = reinterpret_cast<const uint32_t*>(aqb + (int64_t)(s / topk) * qb_stride);+ for (int i = threadIdx.x; i < NB * 72; i += blockDim.x) aql[i] = src[i];+ __syncthreads();+ }+ int scg[16], scu[16];+ q3_scales(G, scg); q3_scales(U, scu);+ const float dg = h2f_lo(G.w[27]), du = h2f_lo(U.w[27]);+ float d8[8];+ #pragma unroll+ for (int k = 0; k < 8; k++) d8[k] = h2f_lo(aql[(b * 8 + k) * 9]);+ dgs[r * NB + b] = dg; dus[r * NB + b] = du;+ #pragma unroll+ for (int iqs = 0; iqs < 16; iqs++)+ {+ const int bq8 = 4 * (iqs / 8), so = (iqs & 8) + ((iqs & 7) >> 2);+ const int32_t vlg = (int32_t)G.w[8 + iqs], vmg = (int32_t)G.w[iqs & 7];+ const int32_t vlu = (int32_t)U.w[8 + iqs], vmu = (int32_t)U.w[iqs & 7];+ const int32_t vhg = ~vmg >> bq8, vhu = ~vmu >> bq8;+ float sg = 0.0f, su = 0.0f;+ #pragma unroll+ for (int i = 0; i < 4; i++)+ {+ const int32_t u = (int32_t)aql[(b * 8 + bq8 + i) * 9 + 1 + (iqs & 7)];+ const float d8i = d8[bq8 + i];+ const uint32_t vilg = ((uint32_t)vlg >> (2 * i)) & 0x03030303u, vihg = (uint32_t)((vhg >> i) << 2) & 0x04040404u;+ const uint32_t vilu = ((uint32_t)vlu >> (2 * i)) & 0x03030303u, vihu = (uint32_t)((vhu >> i) << 2) & 0x04040404u;+ // bytes of vil are 0..3 and of vih 0 / 4: a per-byte wrapping subtraction without borrow+ const uint32_t vig = ((vilg | 0x80808080u) - vihg) ^ 0x80808080u;+ const uint32_t viu = ((vilu | 0x80808080u) - vihu) ^ 0x80808080u;+ sg = __fadd_rn(sg, __fmul_rn(d8i, (float)(dp4a_((int32_t)vig, u, 0) * scg[so + 2 * i])));+ su = __fadd_rn(su, __fmul_rn(d8i, (float)(dp4a_((int32_t)viu, u, 0) * scu[so + 2 * i])));+ }+ pg[r * RS + b * 16 + iqs] = sg;+ pu[r * RS + b * 16 + iqs] = su;+ }+ __syncthreads();+ if (b == 0)+ {+ float sg = 0.0f, su = 0.0f;+ #pragma unroll+ for (int l = 0; l < 32; l++)+ {+ const int h = l >> 4, iq = l & 15;+ float ag = 0.0f, au = 0.0f;+ #pragma unroll+ for (int k = 0; 2 * k + h < NB; k++) { ag = fmaf(dgs[r * NB + 2 * k + h], pg[r * RS + (2 * k + h) * 16 + iq], ag); au = fmaf(dus[r * NB + 2 * k + h], pu[r * RS + (2 * k + h) * 16 + iq], au); }+ sg = __fadd_rn(sg, ag); su = __fadd_rn(su, au);+ }+ float gh = __half2float(__float2half_rn(sg)), uh = __half2float(__float2half_rn(su));+ if (lim > 0.0f) { gh = fminf(gh, lim); uh = fminf(fmaxf(uh, -lim), lim); }+ float sig = 1.0f / (1.0f + expf(-gh));+ act[(int64_t)s * I + n] = __float2half_rn(sig * gh * uh);+ }+}++extern "C" {+#define UG_Q3(NBV) \+__global__ void __launch_bounds__(ROWS * NBV) ug_q3_v3_##NBV(const uint8_t* __restrict__ aqb, const int64_t* __restrict__ sel, \+ const uint8_t* const* __restrict__ gb, const uint8_t* const* __restrict__ ub, int64_t gs, int64_t us, int64_t qs, \+ __half* __restrict__ act, int S, int I, int E, int ntiles, int topk, float lim, const int32_t* __restrict__ perm, int nslots) \+{ ug_q3_v3_body<NBV>(aqb, sel, gb, ub, gs, us, qs, act, S, I, E, ntiles, topk, lim, perm, nslots); }+UG_Q3(6)+UG_Q3(8)+} // extern "C"++// ================================================================== references copied from fq_moe_kq.cu (v2 Q4_K gate/up and down, 8 threads per row)+__device__ __forceinline__ void q4_item_ref(const uint8_t* __restrict__ wr, const uint8_t* __restrict__ aq, int it, float* __restrict__ dst)+{+ Q4It r; q4_load(wr, it, r);+ const int b = it >> 2, g = it & 3;+ const uint32_t* a0 = reinterpret_cast<const uint32_t*>(aq + (size_t)(b * 8 + 2 * g) * Q8_1_BYTES);+ // same arithmetic as q4_comp, reading the row from global+ const uint32_t* a1 = a0 + 9;+ const float dm0 = h2f_lo(r.hd), dm1 = h2f_lo(r.hd >> 16);+ const float d8[2] = {h2f_lo(a0[0]), h2f_lo(a1[0])};+ const int sh = 16 * (g & 1);+ const uint32_t s0 = (r.s0 >> sh) & 0xFFFFu, s2 = (r.s1 >> sh) & 0xFFFFu, s4 = (r.s2 >> 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] = {r.va.x, r.va.y, r.va.z, r.va.w};+ const uint32_t w1[4] = {r.vb.x, r.vb.y, r.vb.z, r.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 uint32_t* a = i ? a1 : a0;+ const uint32_t v0i = (w0[qo] >> (4 * i)) & 0x0F0F0F0Fu, v1i = (w1[qo] >> (4 * i)) & 0x0F0F0F0Fu;+ const int32_t u0 = (int32_t)a[1 + qo], u1 = (int32_t)a[5 + qo];+ int dot1 = dp4a_((int32_t)v0i, u0, 0);+ dot1 = dp4a_((int32_t)v1i, u1, dot1);+ int dot2 = dp4a_(0x01010101, u0, 0);+ dot2 = 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));+ }+}++extern "C" {++__global__ void __launch_bounds__(256) ug_q4_ref(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,+ int64_t qb_stride, __half* __restrict__ act, int S, int I, int K, int E, int ntiles_u, int topk, float lim,+ const int32_t* __restrict__ perm, int nslots)+{+ __shared__ float pg[ROWS * PS];+ __shared__ float pu[ROWS * PS];+ int s, t; slot_tile(blockIdx.x, ntiles_u, S, perm, nslots, s, t);+ const int r = threadIdx.x >> 3, j = threadIdx.x & 7;+ int64_t e = sel[s]; e = (e < 0 || e >= E) ? 0 : e;+ const int n = t * ROWS + r;+ const uint8_t* aq = aqb + (int64_t)(s / topk) * qb_stride;+ 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];+ q4_item_ref(gr, aq, it, tg); q4_item_ref(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 * PS + 4 * j + q] = ag[q]; pu[r * 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 * PS + l]); su = __fadd_rn(su, pu[r * PS + l]); }+ float gh = __half2float(__float2half_rn(sg)), uh = __half2float(__float2half_rn(su));+ if (lim > 0.0f) { gh = fminf(gh, lim); uh = fminf(fmaxf(uh, -lim), lim); }+ float sig = 1.0f / (1.0f + expf(-gh));+ act[(int64_t)s * I + n] = __float2half_rn(sig * gh * uh);+ }+}++__global__ void __launch_bounds__(256) dn_q4_ref(const uint8_t* __restrict__ aqb, int64_t qb_stride, const int64_t* __restrict__ sel,+ const uint8_t* const* __restrict__ down_bases, int64_t down_stride, float* __restrict__ partial, int S, int I, int K, int E, int ntiles_d,+ const int32_t* __restrict__ perm, int nslots)+{+ __shared__ float pp[ROWS * PS];+ int s, t; slot_tile(blockIdx.x, ntiles_d, S, perm, nslots, s, t);+ const int r = threadIdx.x >> 3, j = threadIdx.x & 7;+ int64_t e = sel[s]; e = (e < 0 || e >= E) ? 0 : e;+ const int n = t * ROWS + r;+ float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};+ if (n < K)+ {+ const uint8_t* dr = down_bases[e] + (int64_t)n * down_stride;+ const uint8_t* aq = aqb + (int64_t)s * qb_stride;+ const int nitems = (I / 256) * 4;+ for (int it = j; it < nitems; it += 8)+ {+ float tv[4];+ q4_item_ref(dr, aq, 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 * PS + 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 * PS + l]);+ partial[(int64_t)s * K + n] = sp;+ }+}++} // extern "C"diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex a69b23d..9c3e475 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -201,6 +201,32 @@ def _ext():return _EXT[0]+MOE_V2 = os.environ.get("HY4_MOE_V2", "0") == "1" # routed experts through loader/moe_dec_hip.py (HIP code object, bit-equal to the shipped grouped kernels, fewer waits per row); default off+_MD = []+++def _moe_v2(rs, T, K):+ """the MoeDec scratch holder for this layer shape, or None (flag off / code object missing / shape or alignment outside the kernels' contract)"""+ if not MOE_V2 or T > MMVQ_MAXR:+ return None+ if not _MD:+ try:+ from . import moe_dec_hip as md+ _MD.append(md if os.path.exists(md.CO) else None)+ _MD.append({})+ except Exception as ex: # noqa: BLE001+ print("hy4_forward: HY4_MOE_V2 unavailable:", repr(ex)[:160], flush=True)+ _MD.extend([None, {}])+ md, cache = _MD[0], _MD[1]+ fmt = {0: "q4_k", 8: "q3_k"}.get(rs.fu)+ if md is None or fmt is None or rs.fd != 0 or rs.nout != K or K % 256 or rs.nff % 256 or K != 1536 or rs.nff != 1536 or any(st % 16 for st in rs.strides) or (rs.bufs["gate"].data_ptr() % 16):+ return None+ key = (T, fmt, K, rs.nff)+ if key not in cache:+ cache[key] = md.MoeDec(rs.bufs["gate"].device, T, 16, K, rs.nff, fmt, rs.E)+ return cache[key] if cache[key].topk == 16 else None++def mmvq_fn(ty, K):"""kernel for stored ggml type `ty` with row length K, or None (-> torch dequant path)"""f = GG_MMVQ.get(int(ty))@@ -746,10 +772,15 @@ class Hy4Forward:if getattr(self, "_gpart", None) is None or self._gpart.shape[1] != N:self._gpart = torch.empty(MMVQ_MAXR * S, N, dtype=torch.float32, device=dev)self._gout = torch.empty(MMVQ_MAXR, N, dtype=torch.float32, device=dev)- ext.fq_moe_kq_set_swiglu_limit(lim)- ext.fq_moe_kq_grouped_mixed_q8(z.half().contiguous(), sel.contiguous(), w.half().contiguous(), *rs.ptrs, *rs.strides, rs.fu, rs.fd,- self._gpart[:T * S], self._gout[:T])- lat = self._gout[:T] if (self.hook is None and not NO_ALIAS_LAT) else self._gout[:T].clone() # rup reads it before the next layer's grouped call overwrites _gout (one stream); hooks keep a copy+ mv2 = _moe_v2(rs, T, z.shape[1]) if S == 16 else None+ if mv2 is not None:+ out2 = mv2.run(z.half().contiguous(), sel.reshape(-1).contiguous(), w.half().reshape(-1).contiguous(), rs.ptrs, rs.strides, lim, "v3", "v3")+ lat = out2 if (self.hook is None and not NO_ALIAS_LAT) else out2.clone()+ else:+ ext.fq_moe_kq_set_swiglu_limit(lim)+ ext.fq_moe_kq_grouped_mixed_q8(z.half().contiguous(), sel.contiguous(), w.half().contiguous(), *rs.ptrs, *rs.strides, rs.fu, rs.fd,+ self._gpart[:T * S], self._gout[:T])+ lat = self._gout[:T] if (self.hook is None and not NO_ALIAS_LAT) else self._gout[:T].clone() # rup reads it before the next layer's grouped call overwrites _gout (one stream); hooks keep a copyself.stats["grouped_calls"] = self.stats.get("grouped_calls", 0) + 1sel_l = [] # the per-expert pread loop below runs zero timesif lat is None:diff --git a/exllamav3/loader/moe_dec_hip.py b/exllamav3/loader/moe_dec_hip.pynew file mode 100644index 0000000..31d96e7--- /dev/null+++ b/exllamav3/loader/moe_dec_hip.py@@ -0,0 +1,102 @@+"""Decode MoE stages (q8_1 activations) for GGUF k-quants on gfx1151: HIP code object moe_dec.co (built by hip_kq/build_moe.sh from moe_dec.cu).+Same arithmetic and accumulation order as fq_moe_kq.cu, so every arm is bit-equal to the shipped extension kernels. Arms (per stage):+ ug ('ref' = copy of the shipped kernel, 'v3' = unrolled loads + LDS activations / Q3_K one thread per 256-block), dn ('ref', 'v3').+Used by tools/hy4/step/opbench.py `experts_v2` and (flag HY4_MOE_V2, default off) by hy4_forward's routed-expert call."""+import ctypes, os+import torch+from . import kq_moe_hip as _K++CO = os.environ.get("MOE_DEC_CO", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "exllamav3_ext", "hip_kq", "moe_dec.co"))+++def _launch(name, grid, block, args, shmem=0):+ lib = _K._hip()+ fn = _K._fn(CO, name)+ cargs = []+ for a in args:+ if a is None:+ cargs.append(ctypes.c_void_p(0))+ elif 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):+ 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])+ rc = lib.hipModuleLaunchKernel(fn, grid, 1, 1, block, 1, 1, shmem, ctypes.c_void_p(torch.cuda.current_stream().cuda_stream), ptrs, None)+ assert rc == 0, f"hipModuleLaunchKernel {name} rc={rc}"+++def _i64(v):+ return (int(v), ctypes.c_long)+++class MoeDec:+ """scratch + launches for one layer shape: R rows, topk, K (hidden, = down rows), I (ff), gate/up fmt 'q4_k' | 'q3_k', down Q4_K"""++ def __init__(self, dev, R, topk, K, I, fmt_ug, E, sort=True):+ assert K % 256 == 0 and I % 256 == 0 and K % 32 == 0 and I % 32 == 0 and fmt_ug in ("q4_k", "q3_k")+ self.R, self.topk, self.K, self.I, self.fmt, self.E = R, topk, K, I, fmt_ug, E+ self.S = R * topk+ self.sort = sort and R > 1 and self.S <= 128+ self.qbh = torch.empty(R, K // 32 * 36, dtype=torch.uint8, device=dev)+ self.act = torch.empty(self.S, I, dtype=torch.float16, device=dev)+ self.qba = torch.empty(self.S, I // 32 * 36, dtype=torch.uint8, device=dev)+ self.partial = torch.empty(self.S, K, dtype=torch.float32, device=dev)+ self.perm = torch.empty(self.S, dtype=torch.int32, device=dev) if self.sort else None+ self.out = torch.empty(R, K, dtype=torch.float32, device=dev)++ def prep(self, h, sel):+ if self.sort:+ _launch("moe_sort", 1, 128, [sel, self.perm, self.S, self.E])+ _launch("moe_quant_q8_1", self.R * (self.K // 32), 32, [h, self.qbh, self.R, self.K])++ def ug(self, arm, sel, ptrs, strides, lim):+ S, I, K, E, topk = self.S, self.I, self.K, self.E, self.topk+ gp, up_ = ptrs[0], ptrs[1]+ qs = self.qbh.shape[1]+ if arm == "ref":+ if self.fmt == "q4_k":+ nt = I // 32+ _launch("ug_q4_ref", S * nt, 256, [self.qbh, sel, gp, up_, _i64(strides[0]), _i64(strides[1]), _i64(qs), self.act, S, I, K, E, nt, topk, float(lim), self.perm, S])+ else:+ nt = I // 8+ _launch("ug_q3_ref", S * nt, 256, [self.qbh, sel, gp, up_, _i64(strides[0]), _i64(strides[1]), _i64(qs), self.act, S, I, K, E, nt, topk, float(lim), self.perm, S], 2048)+ else:+ nb, nt = K // 256, I // 32+ if self.fmt == "q4_k":+ _launch(f"ug_q4_v3_{nb}", S * nt, 256, [self.qbh, sel, gp, up_, _i64(strides[0]), _i64(strides[1]), _i64(qs), self.act, S, I, E, nt, topk, float(lim), self.perm, S])+ else:+ shm = (2 * 32 * (nb * 16 + 1) + 2 * 32 * nb + nb * 72) * 4+ _launch(f"ug_q3_v3_{nb}", S * nt, 32 * nb, [self.qbh, sel, gp, up_, _i64(strides[0]), _i64(strides[1]), _i64(qs), self.act, S, I, E, nt, topk, float(lim), self.perm, S], shm)++ def qact(self):+ _launch("moe_quant_q8_1", self.S * (self.I // 32), 32, [self.act, self.qba, self.S, self.I])++ def dn(self, arm, sel, ptrs, strides):+ S, I, K, E = self.S, self.I, self.K, self.E+ nt = K // 32+ qs = self.qba.shape[1]+ if arm == "ref":+ _launch("dn_q4_ref", S * nt, 256, [self.qba, _i64(qs), sel, ptrs[2], _i64(strides[2]), self.partial, S, I, K, E, nt, self.perm, S])+ else:+ _launch(f"dn_q4_v3_{I // 256}", S * nt, 256, [self.qba, _i64(qs), sel, ptrs[2], _i64(strides[2]), self.partial, S, K, E, nt, self.perm, S])++ def combine(self, wts):+ nb = (self.K + 255) // 256+ lib = _K._hip()+ fn = _K._fn(CO, "moe_combine")+ cargs = [ctypes.c_void_p(self.partial.data_ptr()), ctypes.c_void_p(wts.data_ptr()), ctypes.c_void_p(self.out.data_ptr()), ctypes.c_int(self.topk), ctypes.c_int(self.K)]+ pp = (ctypes.c_void_p * 5)(*[ctypes.cast(ctypes.pointer(c), ctypes.c_void_p) for c in cargs])+ rc = lib.hipModuleLaunchKernel(fn, nb, self.R, 1, 256, 1, 1, 0, ctypes.c_void_p(torch.cuda.current_stream().cuda_stream), pp, None)+ assert rc == 0++ def run(self, h, sel, wts, ptrs, strides, lim, ug="v3", dn="v3"):+ self.prep(h, sel)+ self.ug(ug, sel, ptrs, strides, lim)+ self.qact()+ self.dn(dn, sel, ptrs, strides)+ self.combine(wts)+ return self.outdiff --git a/tools/hy4/step/ab_exp.py b/tools/hy4/step/ab_exp.pynew file mode 100644index 0000000..cf7d8cf--- /dev/null+++ b/tools/hy4/step/ab_exp.py@@ -0,0 +1,58 @@+"""ab_exp.py: ONE load (HY4_MOE_V2=1 in the environment, code object exllamav3_ext/hip_kq/moe_dec.co built by hip_kq/build_moe.sh); cwd = tree.+Paired ABBA graph-replay step wall, T = 1..6, ctx 1000 / 4000 (PCTXS, PTS): arm A = shipped grouped kernel (fq_moe_kq_grouped_mixed_q8), arm B = HY4_MOE_V2 stages.+Prints head_ab.log style lines (ARM ... done, AB ctx T: A [...] B [...] ms delta, KL_mean top1_agree: the arms are bit-equal where the code object is bit-equal, so KL 0 is expected;+a nonzero KL is a kernel bug, not noise). cwd = tree."""+import json, os, statistics, sys, time+tree = os.getcwd()+sys.path.insert(0, os.path.join(tree, "tools", "hy4"))+import serve+serve.apply_env(16384)+import torch+from engine import Hy4Engine+GGUF = os.environ.get("GGUF", "/home/kamel/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf")+e = Hy4Engine(tree, GGUF, ctx=16384, k=3)+e.load(print)+GR, M = e.GR, e.M+fwm = sys.modules[type(M).__module__]+assert fwm.MOE_V2, "run with HY4_MOE_V2=1"+wiki = json.load(open(os.environ.get("WIKI", "/home/kamel/scratch_w5/wiki_ids.json")))+pc, sync = time.perf_counter, torch.cuda.synchronize+++def kl_top1(la, lb):+ la, lb = la.float().log_softmax(-1), lb.float().log_softmax(-1)+ return (la.exp() * (la - lb)).sum(-1), (la.argmax(-1) == lb.argmax(-1)).float()+++def arm(b):+ fwm.MOE_V2 = b+ fwm._MD.clear() if not b else None # arm B rebuilds its scratch lazily+ GR.clear()+++ctxs = [int(x) for x in os.environ.get("PCTXS", "1000,4000").split(",")]+Ts = [int(x) for x in os.environ.get("PTS", "1,2,3,4,5,6").split(",")]+res, logit = {}, {}+for ctxn in ctxs:+ e._t0 = pc(); e.reset(); e.prefill(wiki[:ctxn]); e.phase("decode")+ for a_ in ("A", "B", "B", "A"):+ arm(a_ == "B")+ for T in Ts:+ toks = wiki[ctxn:ctxn + T]+ for _ in range(3):+ GR.step_rows(toks); sync(); GR.rewind(ctxn)+ ts = []+ for _ in range(20):+ t = pc(); out = GR.step_rows(toks); sync(); ts.append((pc() - t) * 1000); GR.rewind(ctxn)+ res.setdefault((ctxn, T, a_), []).append(statistics.median(ts))+ if (ctxn, T, a_) not in logit:+ logit[(ctxn, T, a_)] = out[0].float().reshape(T, -1).clone()+ print(f"ARM {a_} ctx {ctxn} done (MOE_V2 {fwm.MOE_V2}, v2 layers {fwm._MD[1].keys() if len(fwm._MD) > 1 else None})", flush=True)+arm(False)+for ctxn in ctxs:+ for T in Ts:+ a, b = res[(ctxn, T, "A")], res[(ctxn, T, "B")]+ k_, s_ = kl_top1(logit[(ctxn, T, "A")], logit[(ctxn, T, "B")])+ print(f"AB ctx {ctxn} T {T}: A {[round(x, 2) for x in a]} B {[round(x, 2) for x in b]} ms delta {statistics.mean(b) - statistics.mean(a):+.2f} ms "+ f"KL_mean {k_.mean().item():.2e} top1_agree {s_.mean().item():.2f}", flush=True)+print("ABEXP_DONE", flush=True)diff --git a/tools/hy4/step/opbench.py b/tools/hy4/step/opbench.pyindex 19c1c76..f73b174 100644--- a/tools/hy4/step/opbench.py+++ b/tools/hy4/step/opbench.py@@ -416,6 +416,81 @@ def op_experts(c):torch.cuda.empty_cache()+# ---------------------------------------------------------------------------------------------------------------- experts_v2+def op_experts_v2(c):+ """A/B of the HIP stage kernels (loader/moe_dec_hip.py): copies of the shipped kernels (ref) vs the rewrites (v3), bit-equality checked"""+ from exllamav3.loader import moe_dec_hip as MD+ g = c.gguf()+ ext = HF._ext()+ m, p = g.meta, c.p+ clamp = list(m[p + "swiglu_clamp_exp"])+ w_scale = float(m[p + "expert_weights_scale"])+ S = c.topk+ first, types = {}, {}+ for i in moe_layers(c):+ ty = int(g.infos[f"blk.{i}.ffn_gate_exps.weight"][0])+ types[ty] = types.get(ty, 0) + 1+ first.setdefault(ty, i)+ E0 = g.infos[f"blk.{c.n_dense}.ffn_gate_exps.weight"][1][2]+ pk = calib_overlap(S, E0)+ rng = np.random.default_rng(1)+ for ty, i in first.items():+ rs = load_experts(c, i)+ assert rs.fd == 0, "down is not Q4_K"+ per_exp = 2 * rs.ebytes[0] + rs.ebytes[1]+ lim = float(clamp[i])+ for T in tlist(c.a):+ sels = [sample_sel(T, S, rs.E, pk, rng) for _ in range(c.a.variants)]+ dis = [len(set(s.flatten().tolist())) for s in sels]+ md = sum(dis) / len(dis)+ z = (torch.randn(T, rs.K, device=dev) * 0.5).half()+ ws = [(torch.rand(T, S, device=dev) + 0.1) for _ in sels]+ ws = [(w / w.sum(-1, keepdim=True) * w_scale).half().reshape(-1).contiguous() for w in ws]+ seltt = [torch.from_numpy(s).to(dev).reshape(-1).contiguous() for s in sels]+ M = MD.MoeDec(dev, T, S, rs.K, rs.nff, rs.fmt, rs.E)+ perms = []+ for s_ in seltt:+ pm = torch.empty(T * S, dtype=torch.int32, device=dev)+ if M.sort:+ MD._launch("moe_sort", 1, 128, [s_, pm, T * S, rs.E])+ perms.append(pm if M.sort else None)+ gpart = torch.empty(HF.MMVQ_MAXR * S, rs.nout, dtype=torch.float32, device=dev)+ gout = torch.empty(HF.MMVQ_MAXR, rs.nout, dtype=torch.float32, device=dev)+ ext.fq_moe_kq_set_swiglu_limit(lim)+ ext.fq_moe_kq_grouped_mixed_q8(z, seltt[0], ws[0], *rs.ptrs, *rs.strides, rs.fu, rs.fd, gpart[:T * S], gout[:T])+ ref = gout[:T].clone()+ o_ref = M.run(z, seltt[0], ws[0], rs.ptrs, rs.strides, lim, "ref", "ref").clone()+ a_ref = M.act.clone()+ o_v3 = M.run(z, seltt[0], ws[0], rs.ptrs, rs.strides, lim, "v3", "v3").clone()+ a_v3 = M.act.clone()+ torch.cuda.synchronize()+ eq = dict(ext_vs_ref=float((ref - o_ref).abs().max()), ref_vs_v3=float((o_ref - o_v3).abs().max()), act_ref_vs_v3=float((a_ref.float() - a_v3.float()).abs().max()))+ print(f"experts_v2 {rs.fmt} T {T}: max abs diff {eq}", flush=True)+ def mk(arm_ug, arm_dn, stage):+ def f(s, w, pm=None):+ M.perm = pm if stage != "full" else M.perm+ if stage == "full":+ M.run(z, s, w, rs.ptrs, rs.strides, lim, arm_ug, arm_dn)+ elif stage == "ug":+ M.ug(arm_ug, s, rs.ptrs, rs.strides, lim)+ else:+ M.dn(arm_dn, s, rs.ptrs, rs.strides)+ return [(lambda s=s, w=w, pm=pm: f(s, w, pm)) for s, w, pm in zip(seltt, ws, perms)]+ def prime(s, w):+ M.prep(z, s); M.ug("ref", s, rs.ptrs, rs.strides, lim); M.qact()+ prime(seltt[0], ws[0])+ for arm, stage, bytes_ in (("ext", "ext", per_exp), ("ref", "full", per_exp), ("v3", "full", per_exp), ("ref", "ug", 2 * rs.ebytes[0]), ("v3", "ug", 2 * rs.ebytes[0]),+ ("ref", "dn", rs.ebytes[1]), ("v3", "dn", rs.ebytes[1])):+ if stage == "ext":+ fns = [(lambda s=s, w=w: ext.fq_moe_kq_grouped_mixed_q8(z, s, w, *rs.ptrs, *rs.strides, rs.fu, rs.fd, gpart[:T * S], gout[:T])) for s, w in zip(seltt, ws)]+ else:+ fns = mk(arm, arm, stage)+ # stage arms reuse the activations of variant 0 (timing only depends on the expert bytes)+ point(c, "experts_v2", T, 0, f"{rs.fmt}_layer{i}_{stage}_{arm}", fns, md * bytes_, rs.fmt, types[ty], None, dict(distinct_mean=md, bit=eq))+ del rs+ torch.cuda.empty_cache()++# ---------------------------------------------------------------------------------------------------------------- routerdef op_router(c):g = c.gguf()@@ -563,7 +638,7 @@ def op_info(c):print("n_dense", c.n_dense, "n_trunk", c.n_trunk, "topk", c.topk, "ext", HF._ext() is not None, "sha", SHA, "flags", FLAGHASH)-OPS = dict(roofs=op_roofs, dense_q8=op_dense_q8, experts=op_experts, router=op_router, absorb=op_absorb, mla_rows=op_mla_rows, head=op_head, draft_head=op_draft_head, info=op_info)+OPS = dict(roofs=op_roofs, dense_q8=op_dense_q8, experts=op_experts, experts_v2=op_experts_v2, router=op_router, absorb=op_absorb, mla_rows=op_mla_rows, head=op_head, draft_head=op_draft_head, info=op_info)ALL = ["roofs", "experts", "mla_rows", "dense_q8", "absorb", "router", "head", "draft_head"]