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
ROCm: HIP tensor-core kernel for quantized-KV decode attention (qdec.hip), opt-in EXL3_QDEC_HIP=1
YanissAmzde2c63e66bb5
diff --git a/exllamav3/modules/attention_fn/qdec.hip b/exllamav3/modules/attention_fn/qdec.hipnew file mode 100644index 0000000..dffa95a--- /dev/null+++ b/exllamav3/modules/attention_fn/qdec.hip@@ -0,0 +1,486 @@+// Quantized-KV flash-decoding split kernel for gfx11.5 (wave32, WMMA f16): QK^T / PV straight from the packed bit-plane words.+// HIP port of cu/qdec.cu with the same cache format and the same math (dequant = (raw - (2^(B-1) - 0.5)) * scale * 2^-(B-1) in fp16,+// fp32 accumulation, log2-domain online softmax), but its own split/combine contract (qdec_split writes partials, qdec_combine+// reduces them, rotates the result back with h32 and writes fp16).+//+// A CTA has NSW slab streams x DW waves. A stream works on 16-token slabs of one (batch, kv head) pair (streams interleave the slabs of+// the CTA's token range and are merged through LDS at the end); the DW waves of a stream split the head dim: wave dw owns d in+// [dw*HD/DW, (dw+1)*HD/DW) for K (partial S over its k-steps, summed through LDS) and for V/O. DW = 1 keeps everything in one wave.+// Operands come straight from global memory into registers (no LDS staging):+// S (16 tokens x 16 q rows) = Kdeq (A: lane = token, 16 d per k-step) x q^T (B: lane = q row, from LDS) -> C: lane = q row, 8 tokens/lane+// O (16 q rows x 16 d) += P (A: lane = q row, 16 tokens) x V (B: lane = d column, 16 tokens)+// The d columns of the PV product are permuted: column n of d-tile dt is d = d0 + DTW*n + dt, so lane n dequantizes a run of DTW+// consecutive values of every token (a few aligned words) and no transpose through LDS is needed. The permutation is undone when+// the partials are stored.+// Fragment layout (gfx1151): A: lane l, elem r -> A[l & 15][r]; B: lane l, elem r -> B[r][l & 15]; C: lane l, reg r -> C[2r + (l >> 4)][l & 15]+// MEMORY SAFETY: every global read is for a token clamped into [n_start, n_end) (n_end = cache_seqlens + QLEN, block table index below+// num_pages_per_seq), every store is guarded by the row < ROWS test; qdec_hip.py checks the shapes, test_qdec_hip.py runs with guard pages.+#include <hip/hip_runtime.h>+#include <stdint.h>++typedef _Float16 half_t;+typedef _Float16 v16h __attribute__((ext_vector_type(16)));+typedef _Float16 v2h __attribute__((ext_vector_type(2)));+typedef float v8f __attribute__((ext_vector_type(8)));+typedef uint32_t u32;+typedef uint16_t u16;+typedef u32 v4u __attribute__((ext_vector_type(4)));+typedef u32 v8u __attribute__((ext_vector_type(8)));++#define G (HD / 32)+#define GROUP (NQH / NKV)+#define ROWS (QLEN * GROUP)+#define NT ((ROWS + 15) / 16)+#define RP (NT * 16)+#define GPT (NKV * HD / 32)+#define KCHW (G * KB)+#define VCHW (G * VB)+#define DT (HD / 16)+#define NSW (NW / DW)+#define KSW (DT / DW) // k-steps per wave+#define GWV (G / DW) // K groups per wave+#define KWW (GWV * KB) // K words per token row for this wave+#define DTW (DT / DW) // d-tiles per wave+#define HDW (HD / DW) // d columns per wave+#define NTHREADS (NW * 32)+#define QSTR (HD + 8)+#define LOG2E 1.4426950408889634f+#define NEG_INF (-__builtin_huge_valf())+#ifndef HAS_SINKS+#define HAS_SINKS 0+#endif++__device__ __forceinline__ u32 hsub2(u32 a, u32 b) { return __builtin_bit_cast(u32, __builtin_bit_cast(v2h, a) - __builtin_bit_cast(v2h, b)); }+__device__ __forceinline__ u32 hmul2(u32 a, u32 b) { return __builtin_bit_cast(u32, __builtin_bit_cast(v2h, a) * __builtin_bit_cast(v2h, b)); }+__device__ __forceinline__ u32 hfma2(u32 a, u32 b, u32 c)+{+ return __builtin_bit_cast(u32, __builtin_elementwise_fma(__builtin_bit_cast(v2h, a), __builtin_bit_cast(v2h, b), __builtin_bit_cast(v2h, c)));+}+__device__ __forceinline__ v8f wmma(v16h a, v16h b, v8f c) { return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); }+__device__ __forceinline__ u32 pack_h2(float lo, float hi)+{+ return __builtin_bit_cast(u32, __builtin_amdgcn_cvt_pkrtz(lo, hi));+}+__device__ __forceinline__ u32 perm(u32 hi, u32 lo, u32 sel) { return __builtin_amdgcn_perm(hi, lo, sel); }+__device__ __forceinline__ float h2f(u16 h) { return (float) __builtin_bit_cast(half_t, h); }++// grid step 2^-(B-1) as fp16 bits, duplicated in both halves+template<int B> __device__ __forceinline__ u32 inv2() { return (u32)((15 - (B - 1)) << 10) * 0x10001u; }+template<int B> __device__ __forceinline__ u32 c2() { return (u32)(0x6400 | (1 << (B - 1))) * 0x10001u; }+// half2(scale, scale) -> half2 of grid-step scales+template<int B> __device__ __forceinline__ u32 scale2(u16 a) { return hmul2((u32)a * 0x10001u, inv2<B>()); }++#define MAGIC 0x64006400u // fp16 1024.0 in both halves: OR-ing a raw value below 1024 gives 1024 + raw++// Two adjacent raw values (positions p, p+1, p even; compile-time) of a packed plane array, as the fp16 pair (1024 + raw) in the two+// 16-bit halves. base[o8..] = 8-bit plane words, base[o4..] = 4-bit plane, base[o2..] / base[o1..] = 2-bit / 1-bit plane (present planes+// of B only); position p of a plane with W bits per value is in word p / (32 / W), bits (p % (32 / W)) * W. A K group has+// o8 = 0, o4 = 8 (if the 8-bit plane exists), ...; a V run has its own layout (load_run).+template<int B> __device__ __forceinline__ u32 raw_pair_m(const u32* base, int p, int o8, int o4, int o2, int o1)+{+ if (B == 8) { // one v_perm: [b0, 0x64, b1, 0x64]+ u32 w = base[o8 + (p >> 2)];+ return (p & 2) ? perm(0x64646464u, w, 0x04030402u) : perm(0x64646464u, w, 0x04010400u);+ }+ u32 raw = 0; bool first = true;+ if (B & 8) { u32 v = (base[o8 + (p >> 2)] >> ((p & 3) << 3)) & 0xFFFFu; raw = (v & 0xFFu) | ((v & 0xFF00u) << 8); first = false; }+ if (B & 4) { u32 v = (base[o4 + (p >> 3)] >> ((p & 7) << 2)) & 0xFFu; u32 x = (v & 0xFu) | ((v & 0xF0u) << 12); raw = first ? x : ((raw << 4) | x); first = false; }+ if (B & 2) { u32 v = (base[o2 + (p >> 4)] >> ((p & 15) << 1)) & 0xFu; u32 x = (v & 3u) | ((v & 12u) << 14); raw = first ? x : ((raw << 2) | x); first = false; }+ if (B & 1) { u32 v = (base[o1 + (p >> 5)] >> (p & 31)) & 3u; u32 x = (v & 1u) | ((v & 2u) << 15); raw = first ? x : ((raw << 1) | x); }+ return raw | MAGIC;+}+// fp16 pair (1024 + raw) + half2 grid-step scale -> half2 values (raw - (2^(B-1) - 0.5)) * scale, one rounding (s2h = s2 * 0.5)+template<int B> __device__ __forceinline__ u32 dequant2(u32 raw_m, u32 s2, u32 s2h)+{+ return hfma2(hsub2(raw_m, c2<B>()), s2, s2h);+}++// K group plane offsets (words)+#define KO4 ((KB & 8) ? 8 : 0)+#define KO2 (KO4 + ((KB & 4) ? 4 : 0))+#define KO1 (KO2 + ((KB & 2) ? 2 : 0))++// ---- V runs: lane n owns the DTW consecutive values p0 .. p0 + DTW - 1 of a group (p0 = (d0 + DTW * n) mod 32; DTW in 4, 8, 16)+// run layout (present planes only): [8-bit: ceil(DTW/4) words][4-bit: ceil(DTW/8) words, run shifted to bit 0][2-bit: 1 word, run in the+// low DTW*2 bits][1-bit: 1 word, run in the low DTW bits]+#define RUN_W8 ((VB & 8) ? (DTW + 3) / 4 : 0)+#define RUN_W4 ((VB & 4) ? (DTW + 7) / 8 : 0)+#define RUN_W2 ((VB & 2) ? 1 : 0)+#define RUN_W1 ((VB & 1) ? 1 : 0)+#define NRW (RUN_W8 + RUN_W4 + RUN_W2 + RUN_W1)++__device__ __forceinline__ void load_run(u32* run, const u32* gw, int p0)+{+ int pb = 0, o = 0;+ if (VB & 8) {+ #pragma unroll+ for (int k = 0; k < RUN_W8; k++) run[o + k] = gw[pb + (p0 >> 2) + k];+ pb += 8; o += RUN_W8;+ }+ if (VB & 4) {+ #pragma unroll+ for (int k = 0; k < RUN_W4; k++) run[o + k] = gw[pb + (p0 >> 3) + k] >> (DTW < 8 ? ((p0 & 7) << 2) : 0);+ pb += 4; o += RUN_W4;+ }+ if (VB & 2) { run[o] = gw[pb + (p0 >> 4)] >> ((p0 & 15) << 1); pb += 2; o += 1; }+ if (VB & 1) { run[o] = gw[pb] >> p0; }+}++extern "C" __global__ void __launch_bounds__(NTHREADS)+qdec_split(+ const u16* __restrict__ q, const u32* __restrict__ k_cache, const u32* __restrict__ v_cache,+ const int* __restrict__ block_table, const int* __restrict__ cache_seqlens,+ float* __restrict__ partial_o, float* __restrict__ partial_ml,+ const u16* __restrict__ k_scales, const u16* __restrict__ v_scales, const u16* __restrict__ h32,+ int split_len, int num_pages_per_seq, int num_splits)+{+ extern __shared__ __align__(16) unsigned char smem[];+ u16* Qs = (u16*) smem;+ unsigned char* scratch = smem + ((RP * QSTR * 2 + 15) / 16) * 16;++ const int tid = threadIdx.x, lane = tid & 31;+ const int wid = __builtin_amdgcn_readfirstlane(tid >> 5);+ const int dw = wid % DW, sw = wid / DW;+ const int n = lane & 15, half = lane >> 4;+ const int pid = blockIdx.x, split = blockIdx.y;+ if (split >= num_splits) return;+ const int batch = pid / NKV, kvh = pid % NKV;++ const int total_k = cache_seqlens[batch] + QLEN; // the cache already holds the new tokens+ const int n_start = split * split_len;+ const int n_end = min(n_start + split_len, total_k);+ if (n_end <= n_start) { // empty range (split grid sized from the block-table bound): m = -inf, l = 0+ for (int i = tid; i < RP; i += NTHREADS) {+ partial_ml[((size_t)(pid * num_splits + split) * RP + i) * 2] = NEG_INF;+ partial_ml[((size_t)(pid * num_splits + split) * RP + i) * 2 + 1] = 0.f;+ }+ return;+ }++ // ---- q rows -> rotated (h32) fp16 in smem; rows >= ROWS are zero+ {+ float* hs = (float*) scratch; // 32x32 fp32, the scratch buffer is idle until the loop+ for (int i = tid; i < 1024; i += NTHREADS) hs[i] = h2f(h32[i]);+ __syncthreads();+ for (int idx = tid; idx < RP * HD; idx += NTHREADS) {+ int r = idx / HD, d = idx % HD, gi = d >> 5, c = d & 31;+ float acc = 0.f;+ if (r < ROWS) {+ int row_q = r / GROUP, hl = r % GROUP;+ const u16* qp = q + ((size_t)((batch * QLEN + row_q) * NQH + kvh * GROUP + hl)) * HD + gi * 32;+ #pragma unroll+ for (int k = 0; k < 32; k++) acc += h2f(qp[k]) * hs[k * 32 + c];+ }+ Qs[r * QSTR + d] = __builtin_bit_cast(u16, (half_t) acc);+ }+ __syncthreads();+ }++ float m[NT], lsum[NT], qabs[NT];+ bool rvalid[NT];+ #pragma unroll+ for (int j = 0; j < NT; j++) {+ int r = 16 * j + n;+ m[j] = NEG_INF; lsum[j] = 0.f;+ rvalid[j] = r < ROWS;+ qabs[j] = (float)(total_k - QLEN + r / GROUP);+ }+ v8f O[NT][DTW];+ #pragma unroll+ for (int j = 0; j < NT; j++)+ #pragma unroll+ for (int dt = 0; dt < DTW; dt++) O[j][dt] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};++ const int nslabs = (n_end - n_start + 15) / 16;+ const int iters = (nslabs + NSW - 1) / NSW; // uniform over the CTA (the DW waves of a stream exchange S every iteration)+ const float sl = SCALE * LOG2E;+ const float qmin = (float)(total_k - QLEN);++ float* Ssm = (float*) scratch; // DW > 1: [2][NSW*DW][NT][8][32] partial S, double buffered+ u32 kw[KWW]; // this lane's token row of K (kvh slice of this wave's groups)+ u16 ksc[GWV]; // its scales+ int row0 = 0, lim = 0;++ auto slab_rows = [&](int it) {+ int n0 = n_start + (sw + it * NSW) * 16;+ int page = n0 / PAGE;+ int phys = block_table[batch * num_pages_per_seq + page];+ row0 = phys * PAGE + (n0 - page * PAGE);+ lim = n_end - 1 - n0; // last valid token of the slab (>= 0)+ };+ auto load_k = [&]() {+ size_t row = (size_t) row0 + min(n, lim);+ const u32* kp = k_cache + row * (GPT * KB) + kvh * KCHW + dw * KWW;+ if (KWW % 4 == 0 && KCHW % 4 == 0) {+ #pragma unroll+ for (int c = 0; c < KWW / 4; c++) {+ v4u v = ((const v4u*) kp)[c];+ kw[4 * c] = v.x; kw[4 * c + 1] = v.y; kw[4 * c + 2] = v.z; kw[4 * c + 3] = v.w;+ }+ } else {+ #pragma unroll+ for (int c = 0; c < KWW; c++) kw[c] = kp[c];+ }+ const u16* sp = k_scales + row * GPT + kvh * G + dw * GWV;+ #pragma unroll+ for (int c = 0; c < GWV; c++) ksc[c] = sp[c];+ };++ if (nslabs > sw) { slab_rows(0); load_k(); }++ for (int it = 0; it < iters; it++) {+ const bool active = (sw + it * NSW) < nslabs;+ const int n0 = n_start + (sw + it * NSW) * 16;+ v8f S[NT];+ #pragma unroll+ for (int j = 0; j < NT; j++) S[j] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};++ if (active) {+ // ---- S (partial over this wave's k-steps) = Kdeq x q^T+ #pragma unroll+ for (int gl = 0; gl < GWV; gl++) {+ u32 sc = scale2<KB>(ksc[gl]);+ u32 sch = hmul2(sc, 0x38003800u); // 0x3800 = 0.5+ #pragma unroll+ for (int h = 0; h < 2; h++) {+ const int ks = dw * KSW + gl * 2 + h;+ v8u a;+ #pragma unroll+ for (int i = 0; i < 8; i++)+ a[i] = dequant2<KB>(raw_pair_m<KB>(kw + gl * KB, 16 * h + 2 * i, 0, KO4, KO2, KO1), sc, sch);+ v16h af = __builtin_bit_cast(v16h, a);+ #pragma unroll+ for (int j = 0; j < NT; j++) {+ const v4u* qp = (const v4u*)(Qs + (16 * j + n) * QSTR + 16 * ks);+ v8u b; v4u b0 = qp[0], b1 = qp[1];+ b[0] = b0.x; b[1] = b0.y; b[2] = b0.z; b[3] = b0.w; b[4] = b1.x; b[5] = b1.y; b[6] = b1.z; b[7] = b1.w;+ S[j] = wmma(af, __builtin_bit_cast(v16h, b), S[j]);+ }+ }+ }+ }+ if (DW > 1) {+ // sum the partial S of the DW waves of this stream in a fixed order (every wave gets the same bits)+ float* sb = Ssm + (size_t)(it & 1) * NSW * DW * NT * 8 * 32;+ if (active) {+ #pragma unroll+ for (int j = 0; j < NT; j++)+ #pragma unroll+ for (int r = 0; r < 8; r++) sb[((((size_t) sw * DW + dw) * NT + j) * 8 + r) * 32 + lane] = S[j][r];+ }+ __syncthreads();+ if (active) {+ #pragma unroll+ for (int j = 0; j < NT; j++)+ #pragma unroll+ for (int r = 0; r < 8; r++) {+ float t = sb[((((size_t) sw * DW) * NT + j) * 8 + r) * 32 + lane];+ #pragma unroll+ for (int w = 1; w < DW; w++) t += sb[((((size_t) sw * DW + w) * NT + j) * 8 + r) * 32 + lane];+ S[j][r] = t;+ }+ }+ }+ if (!active) continue;++ // ---- online softmax (log2 domain); lane owns q row n of every tile and tokens 2r + half, r = 0..7+ const bool full = (n0 + 15 < n_end) && (!CAUSAL || (float)(n0 + 15) <= qmin);+ u32 pa[NT][8];+ #pragma unroll+ for (int j = 0; j < NT; j++) {+ float s[8], p[8];+ float mx = NEG_INF;+ #pragma unroll+ for (int r = 0; r < 8; r++) s[r] = S[j][r] * sl;+ if (!full) {+ #pragma unroll+ for (int r = 0; r < 8; r++) {+ int tk = n0 + 2 * r + half;+ bool ok = rvalid[j] && tk < n_end && (!CAUSAL || (float) tk <= qabs[j]);+ if (!ok) s[r] = NEG_INF;+ }+ }+ #pragma unroll+ for (int r = 0; r < 8; r++) mx = fmaxf(mx, s[r]);+ mx = fmaxf(mx, __shfl_xor(mx, 16));+ float mn = fmaxf(m[j], mx);+ float me = (mn == NEG_INF) ? 0.f : mn;+ float alpha = (m[j] == NEG_INF) ? 0.f : __builtin_amdgcn_exp2f(m[j] - me);+ float ps = 0.f;+ #pragma unroll+ for (int r = 0; r < 8; r++) { p[r] = __builtin_amdgcn_exp2f(s[r] - me); ps += p[r]; }+ lsum[j] = lsum[j] * alpha + ps;+ m[j] = mn;+ if (__builtin_amdgcn_ballot_w32(alpha != 1.f)) { // skip the O rescale when no row's max moved+ #pragma unroll+ for (int r = 0; r < 8; r++) {+ float ar = __shfl(alpha, 2 * r + half); // O row 2r + half+ #pragma unroll+ for (int dt = 0; dt < DTW; dt++) O[j][dt][r] *= ar;+ }+ }+ // P as the A operand: element e = token e; lane half 0 owns even tokens, half 1 odd ones+ u32 own[4], oth[4];+ #pragma unroll+ for (int k = 0; k < 4; k++) own[k] = pack_h2(p[2 * k], p[2 * k + 1]);+ #pragma unroll+ for (int k = 0; k < 4; k++) oth[k] = __shfl_xor(own[k], 16);+ #pragma unroll+ for (int k = 0; k < 4; k++) {+ u32 lo = half ? oth[k] : own[k]; // half-0 values (regs 2k, 2k+1)+ u32 hi = half ? own[k] : oth[k]; // half-1 values+ pa[j][2 * k] = perm(hi, lo, 0x05040100u); // tokens 4k, 4k+1+ pa[j][2 * k + 1] = perm(hi, lo, 0x07060302u); // tokens 4k+2, 4k+3+ }+ }++ // ---- O += P x V ; lane n owns the d run d0 + DTW*n .. + DTW - 1 of each token+ const int cur_row0 = row0, cur_lim = lim;+ const int dcol = dw * HDW + DTW * n;+ const int gi_v = dcol >> 5, p0 = dcol & 31;+ u32 vr[16][NRW > 0 ? NRW : 1];+ u32 vsc[16];+ #pragma unroll+ for (int e = 0; e < 16; e++) {+ size_t row = (size_t) cur_row0 + min(e, cur_lim);+ load_run(vr[e], v_cache + row * (GPT * VB) + kvh * VCHW + gi_v * VB, p0);+ vsc[e] = scale2<VB>(v_scales[row * GPT + kvh * G + gi_v]);+ }+ // next slab's K (kw is dead now)+ if (it + 1 < iters && (sw + (it + 1) * NSW) < nslabs) { slab_rows(it + 1); load_k(); }+ #pragma unroll+ for (int u = 0; u < DTW / 2; u++) {+ u32 dq[16];+ #pragma unroll+ for (int e = 0; e < 16; e++) {+ u32 sh = hmul2(vsc[e], 0x38003800u);+ dq[e] = dequant2<VB>(raw_pair_m<VB>(vr[e], 2 * u, 0, RUN_W8, RUN_W8 + RUN_W4, RUN_W8 + RUN_W4 + RUN_W2), vsc[e], sh);+ }+ v8u b0, b1;+ #pragma unroll+ for (int i = 0; i < 8; i++) {+ b0[i] = perm(dq[2 * i + 1], dq[2 * i], 0x05040100u); // tokens 2i, 2i+1 at d column 2u+ b1[i] = perm(dq[2 * i + 1], dq[2 * i], 0x07060302u); // ... at d column 2u + 1+ }+ #pragma unroll+ for (int j = 0; j < NT; j++) {+ v8u pv;+ #pragma unroll+ for (int i = 0; i < 8; i++) pv[i] = pa[j][i];+ v16h af = __builtin_bit_cast(v16h, pv);+ O[j][2 * u] = wmma(af, __builtin_bit_cast(v16h, b0), O[j][2 * u]);+ O[j][2 * u + 1] = wmma(af, __builtin_bit_cast(v16h, b1), O[j][2 * u + 1]);+ }+ }+ }++ // ---- row sums across the two token halves+ #pragma unroll+ for (int j = 0; j < NT; j++) lsum[j] += __shfl_xor(lsum[j], 16);++ // ---- merge the NSW streams through LDS: streams 1.. publish (m, l, O), stream 0 combines and stores+ constexpr int NO = NT * DTW * 8;+ float* Osm = (float*) scratch; // [NSW-1][DW][NO][32]+ float* Msm = Osm + (size_t)(NSW - 1) * DW * NO * 32; // [NSW-1][NT][32]+ float* Lsm = Msm + (NSW - 1) * NT * 32;+ __syncthreads();+ if (sw > 0) {+ float* ob = Osm + ((size_t)(sw - 1) * DW + dw) * NO * 32;+ #pragma unroll+ for (int j = 0; j < NT; j++) {+ #pragma unroll+ for (int dt = 0; dt < DTW; dt++)+ #pragma unroll+ for (int r = 0; r < 8; r++) ob[((j * DTW + dt) * 8 + r) * 32 + lane] = O[j][dt][r];+ if (dw == 0) {+ Msm[((sw - 1) * NT + j) * 32 + lane] = m[j];+ Lsm[((sw - 1) * NT + j) * 32 + lane] = lsum[j];+ }+ }+ }+ __syncthreads();+ if (sw > 0) return;++ const size_t pbase = (size_t)(pid * num_splits + split);+ float* po = partial_o + pbase * RP * HD;+ float* pml = partial_ml + pbase * RP * 2;+ #pragma unroll+ for (int j = 0; j < NT; j++) {+ float M = m[j];+ #pragma unroll+ for (int w = 0; w < NSW - 1; w++) M = fmaxf(M, Msm[(w * NT + j) * 32 + lane]);+ float Ms = (M == NEG_INF) ? 0.f : M;+ float f0 = (m[j] == NEG_INF) ? 0.f : __builtin_amdgcn_exp2f(m[j] - Ms);+ float L = lsum[j] * f0;+ float fo[8];+ #pragma unroll+ for (int r = 0; r < 8; r++) fo[r] = __shfl(f0, 2 * r + half);+ #pragma unroll+ for (int dt = 0; dt < DTW; dt++)+ #pragma unroll+ for (int r = 0; r < 8; r++) O[j][dt][r] *= fo[r];+ #pragma unroll+ for (int w = 0; w < NSW - 1; w++) {+ float mw = Msm[(w * NT + j) * 32 + lane];+ float fw = (mw == NEG_INF) ? 0.f : __builtin_amdgcn_exp2f(mw - Ms);+ L += Lsm[(w * NT + j) * 32 + lane] * fw;+ #pragma unroll+ for (int r = 0; r < 8; r++) {+ float fr = __shfl(fw, 2 * r + half);+ #pragma unroll+ for (int dt = 0; dt < DTW; dt++)+ O[j][dt][r] += Osm[(((size_t) w * DW + dw) * NO + (j * DTW + dt) * 8 + r) * 32 + lane] * fr;+ }+ }+ if (dw == 0 && half == 0 && 16 * j + n < ROWS) {+ pml[(16 * j + n) * 2] = M; // log2 domain, see qdec_combine+ pml[(16 * j + n) * 2 + 1] = L;+ }+ #pragma unroll+ for (int r = 0; r < 8; r++) {+ int row = 16 * j + 2 * r + half;+ if (row < ROWS) {+ float* dst = po + (size_t) row * HD + dw * HDW + DTW * n;+ #pragma unroll+ for (int dt = 0; dt < DTW; dt++) dst[dt] = O[j][dt][r];+ }+ }+ }+}++// grid (batch * NKV, ROWS), HD threads: reduce the splits of one q row, normalize, rotate back with h32, write fp16 [batch, QLEN, NQH, HD]+extern "C" __global__ void __launch_bounds__(HD)+qdec_combine(+ const float* __restrict__ partial_o, const float* __restrict__ partial_ml, u16* __restrict__ out,+ const u16* __restrict__ h32, const float* __restrict__ sinks, int num_splits)+{+ __shared__ float hs[32 * 32];+ __shared__ float xs[HD];+ const int pid = blockIdx.x, r = blockIdx.y, d = threadIdx.x;+ const int batch = pid / NKV, kvh = pid % NKV;+ const int row_q = r / GROUP, hl = r % GROUP;+ for (int i = d; i < 1024; i += HD) hs[i] = h2f(h32[i]);++ float M = NEG_INF;+ for (int s = 0; s < num_splits; s++) M = fmaxf(M, partial_ml[(((size_t) pid * num_splits + s) * RP + r) * 2]);+ float sink = 0.f;+ if (HAS_SINKS) { sink = sinks[kvh * GROUP + hl] * LOG2E; M = fmaxf(M, sink); }+ float Ms = (M == NEG_INF) ? 0.f : M;+ float acc = 0.f, L = 0.f;+ for (int s = 0; s < num_splits; s++) {+ size_t pb = ((size_t) pid * num_splits + s) * RP + r;+ float ms = partial_ml[pb * 2];+ if (ms == NEG_INF) continue; // empty split: its partial_o was never written+ float w = __builtin_amdgcn_exp2f(ms - Ms);+ acc += partial_o[pb * HD + d] * w;+ L += partial_ml[pb * 2 + 1] * w;+ }+ if (HAS_SINKS) L += __builtin_amdgcn_exp2f(sink - Ms);+ xs[d] = (float)(half_t)(acc / (L == 0.f ? 1.f : L));+ __syncthreads();+ const int g = d >> 5, c = d & 31;+ float y = 0.f;+ #pragma unroll+ for (int k = 0; k < 32; k++) y += xs[g * 32 + k] * hs[k * 32 + c];+ out[((size_t)((batch * QLEN + row_q) * NQH + kvh * GROUP + hl)) * HD + d] = __builtin_bit_cast(u16, (half_t) y);+}diff --git a/exllamav3/modules/attention_fn/qdec_hip.py b/exllamav3/modules/attention_fn/qdec_hip.pynew file mode 100644index 0000000..b6e2a4b--- /dev/null+++ b/exllamav3/modules/attention_fn/qdec_hip.py@@ -0,0 +1,173 @@+"""+HIP (gfx11.5, wave32 WMMA) split kernel for quantized-KV decode attention (qdec.hip), the ROCm counterpart of qdec_cuda.py. Compiled+at first use with hipcc to an hsaco cached on disk, launched through the HIP module API. qdec_split writes per-split partials,+qdec_combine reduces them, rotates the result back with h32 and writes the fp16 output, so one call replaces the Triton split ++combine pair of triton_paged._paged_attn_decode_split_kernel for QCK > 0 and QCV > 0 with full (non-windowed) attention and no softcap.+make_cfg returns None for call shapes outside what the kernel covers; the caller then keeps the Triton kernels.+Switch: EXL3_QDEC_HIP=0/1 (see ENABLED).+"""+import ctypes+import hashlib+import os+import subprocess++import torch++_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qdec.hip")+_CACHE = os.path.expanduser(os.environ.get("EXL3_QDEC_CACHE", "~/.cache/exllamav3"))+ENABLED = bool(torch.version.hip) and os.environ.get("EXL3_QDEC_HIP", "0") != "0"+_kernels = {}+_bufs = {}+_lib = None+_cus = {}+++def _hip():+ global _lib+ if _lib is None:+ from exllamav3.util.hip_lib import load_hip_runtime+ _lib = load_hip_runtime()+ _lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3+ return _lib+++def pick_dw(hd, nt, nw):+ """waves per stream splitting the head dim: the smallest count that keeps the O accumulators (NT * HD/16 * 8 / DW floats) in budget"""+ if os.environ.get("EXL3_QDEC_HIP_DW"):+ dw = int(os.environ["EXL3_QDEC_HIP_DW"])+ return dw if dw in (1, 2, 4) and nw % dw == 0 and hd // 16 // dw >= 4 else None+ for dw in (1, 2, 4):+ if nw % dw == 0 and hd // 16 // dw >= 4 and nt * (hd // 16) * 8 // dw <= int(os.environ.get("EXL3_QDEC_HIP_MAXO", "96")):+ return dw+ return None+++def geometry(hd, nqh, nkv, qlen, nw, dw):+ """(NT, RP, shared bytes): q tile + max(32x32 fp32 q-rotation matrix, S exchange, cross-stream merge buffer), mirrors qdec.hip"""+ rows = qlen * (nqh // nkv)+ nt = (rows + 15) // 16+ rp = nt * 16+ qs = (rp * (hd + 8) * 2 + 15) // 16 * 16+ nsw = nw // dw+ no = nt * (hd // 16 // dw) * 8+ merge = ((nsw - 1) * dw * no * 32 + 2 * (nsw - 1) * nt * 32) * 4+ sx = 2 * nw * nt * 8 * 32 * 4 if dw > 1 else 0+ return nt, rp, qs + max(4096, merge, sx)+++def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size, causal, sm_scale,+ window_left, window_right, softcap, kv_append_len, has_sinks):+ """Kernel config for a call, or None when the Triton kernels must run it"""+ if (not ENABLED or window_left >= 0 or window_right >= 0 or softcap or kv_append_len != q_len+ or not (2 <= k_bits <= 8) or not (2 <= v_bits <= 8)):+ return None+ if head_dim not in (128, 256) or n_q_heads % n_kv_heads != 0 or page_size % 16 != 0:+ return None+ nw = int(os.environ.get("EXL3_QDEC_HIP_NW", "0")) or 4+ nt = (q_len * (n_q_heads // n_kv_heads) + 15) // 16+ dw = pick_dw(head_dim, nt, nw)+ if dw is None:+ return None+ _, _, shared = geometry(head_dim, n_q_heads, n_kv_heads, q_len, nw, dw)+ if shared > 64 * 1024:+ return None+ return dict(hd=head_dim, kb=k_bits, vb=v_bits, nkv=n_kv_heads, nqh=n_q_heads, qlen=q_len, page=page_size, nw=nw, dw=dw,+ causal=bool(causal), scale=float(sm_scale), sinks=bool(has_sinks))+++def _compile(cfg, arch):+ from exllamav3.util import hip_compiler+ defs = dict(HD=cfg["hd"], KB=cfg["kb"], VB=cfg["vb"], NKV=cfg["nkv"], NQH=cfg["nqh"], QLEN=cfg["qlen"], PAGE=cfg["page"],+ NW=cfg["nw"], DW=cfg["dw"], CAUSAL=int(cfg["causal"]), HAS_SINKS=int(cfg["sinks"]), SCALE=repr(float(cfg["scale"])) + "f")+ extra = [f"-D{k}={v}" for k, v in defs.items()] + os.environ.get("EXL3_QDEC_HIP_FLAGS", "").split()+ flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off", "--no-gpu-bundle-output"] + extra+ gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")+ if os.path.isdir(gcc):+ flags.append(f"--gcc-install-dir={gcc}")+ src = open(_SRC, "rb").read()+ tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]+ path = os.path.join(_CACHE, f"qdec_hip_{arch}_{tag}.hsaco")+ if not os.path.isfile(path):+ os.makedirs(_CACHE, exist_ok=True)+ tmp = path + f".{os.getpid()}.tmp"+ r = subprocess.run([hip_compiler.hipcc(), *flags, "-o", tmp, _SRC], capture_output=True, text=True)+ if r.returncode:+ raise RuntimeError("qdec_hip: hipcc failed:\n" + r.stderr[-3000:])+ os.replace(tmp, path)+ return path+++class _Kernel:+ def __init__(self, cfg, device):+ lib = _hip()+ torch.cuda.init()+ arch = torch.cuda.get_device_properties(device).gcnArchName.split(":")[0]+ self.cfg = cfg+ self.path = _compile(cfg, arch)+ _, self.rp, self.shared = geometry(cfg["hd"], cfg["nqh"], cfg["nkv"], cfg["qlen"], cfg["nw"], cfg["dw"])+ self.mod = ctypes.c_void_p()+ if lib.hipModuleLoad(ctypes.byref(self.mod), self.path.encode()) != 0:+ raise RuntimeError("qdec_hip: hipModuleLoad failed")+ self.split = ctypes.c_void_p()+ self.combine = ctypes.c_void_p()+ if lib.hipModuleGetFunction(ctypes.byref(self.split), self.mod, b"qdec_split") != 0 or \+ lib.hipModuleGetFunction(ctypes.byref(self.combine), self.mod, b"qdec_combine") != 0:+ raise RuntimeError("qdec_hip: kernel symbols missing")++ def _launch(self, fn, grid, block, shared, args):+ cargs = args # ctypes values: c_void_p for pointers, c_int for ints+ params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])+ r = _hip().hipModuleLaunchKernel(fn, grid[0], grid[1], 1, block, 1, 1, shared, torch.cuda.current_stream().cuda_stream, params, None)+ if r != 0:+ raise RuntimeError(f"qdec_hip: launch failed ({r})")+++def get_kernel(cfg, device):+ key = (device.index, tuple(sorted(cfg.items())))+ k = _kernels.get(key)+ if k is None:+ k = _kernels[key] = _Kernel(cfg, device)+ return k+++def _buf(device, name, n):+ key = (device.index, name)+ b = _bufs.get(key)+ if b is None or b.numel() < n:+ b = _bufs[key] = torch.empty(n, dtype=torch.float32, device=device)+ return b+++def cu_count(device):+ idx = device.index if device.index is not None else torch.cuda.current_device()+ if idx not in _cus:+ _cus[idx] = torch.cuda.get_device_properties(idx).multi_processor_count+ return _cus[idx]+++def num_splits(cfg, device, programs, max_k_len):+ if os.environ.get("EXL3_QDEC_HIP_SPL"):+ return int(os.environ["EXL3_QDEC_HIP_SPL"])+ waves = int(os.environ.get("EXL3_QDEC_HIP_WAVES", "0")) or cu_count(device) * 12+ return max(1, min(-(-waves // (programs * cfg["nw"])), -(-max_k_len // 16 // cfg["nw"]), 128))+++def decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, h32, sinks, out, max_k_len):+ """q [bsz, q_len, n_q_heads, hd] fp16 -> out (same shape, fp16); caches are the packed int32 words"""+ bsz = q.shape[0]+ kern = get_kernel(cfg, q.device)+ programs = bsz * cfg["nkv"]+ splits = num_splits(cfg, q.device, programs, max_k_len)+ split_len = -(-(-(-max_k_len // splits)) // 16) * 16+ rows = cfg["qlen"] * (cfg["nqh"] // cfg["nkv"])+ po = _buf(q.device, "po", programs * splits * kern.rp * cfg["hd"])+ pml = _buf(q.device, "pml", programs * splits * kern.rp * 2)+ P, I = ctypes.c_void_p, ctypes.c_int+ kern._launch(kern.split, (programs, splits), 32 * cfg["nw"], kern.shared,+ [P(q.data_ptr()), P(k_cache.data_ptr()), P(v_cache.data_ptr()), P(block_table.data_ptr()), P(cache_seqlens.data_ptr()),+ P(po.data_ptr()), P(pml.data_ptr()), P(k_scales.data_ptr()), P(v_scales.data_ptr()), P(h32.data_ptr()),+ I(split_len), I(block_table.shape[1]), I(splits)])+ kern._launch(kern.combine, (programs, rows), cfg["hd"], 0,+ [P(po.data_ptr()), P(pml.data_ptr()), P(out.data_ptr()), P(h32.data_ptr()),+ P(sinks.data_ptr() if cfg["sinks"] else None), I(splits)])+ return outdiff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.pyindex 7c213d2..4690a7d 100644--- a/exllamav3/modules/attention_fn/triton_paged.py+++ b/exllamav3/modules/attention_fn/triton_paged.py@@ -1089,6 +1089,39 @@ def _paged_attn_decode_combine_kernel(_decode_sm_count = {}+# ROCm: HIP tensor-core split kernel for quantized-KV decode (qdec.hip), EXL3_QDEC_HIP=0 keeps the Triton kernels+from . import qdec_hip as _qh+_QDEC_HIP = _qh.ENABLED+++def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size, softcap, sinks, out,+ num_splits, max_kv_len, qc, kv_append_len, n_kv_heads):+ """The qdec.hip path of paged_attn_triton_decode, or None when the call is outside its shapes (the Triton kernels then run it)"""+ k_scales, v_scales, qck, qcv = qc+ if (q.dtype != torch.float16 or q.ndim != 4 or not q.is_contiguous() or num_splits is not None+ or not all(t.is_contiguous() for t in (k_cache, v_cache, k_scales, v_scales, block_table, cache_seqlens))+ or block_table.dtype != torch.int32 or cache_seqlens.dtype != torch.int32 or k_cache.dtype != torch.int32+ or v_cache.dtype != torch.int32 or k_scales.dtype != torch.float16 or v_scales.dtype != torch.float16):+ return None+ bsz, q_len, n_q_heads, head_dim = q.shape+ if softmax_scale is None:+ softmax_scale = 1.0 / math.sqrt(head_dim)+ window_left, window_right = _normalize_window(window_size)+ sinks, has_sinks = _prep_sinks(sinks, n_q_heads, q)+ if has_sinks and (sinks.dtype != torch.float32 or not sinks.is_contiguous()):+ return None+ cfg = _qh.make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, qck, qcv, k_cache.shape[1], causal, softmax_scale,+ window_left, window_right, softcap, kv_append_len, has_sinks)+ if cfg is None:+ return None+ max_k_len = block_table.shape[1] * k_cache.shape[1] + kv_append_len+ if max_kv_len is not None:+ max_k_len = min(max_k_len, max_kv_len + kv_append_len)+ if out is None:+ out = torch.empty_like(q)+ with torch.cuda.device(q.device):+ return _qh.decode(cfg, q, k_cache, v_cache, block_table, cache_seqlens, k_scales, v_scales, _get_h32(q.device), sinks, out, max_k_len)+# A/B switch, read once at import: CUDA decode runs the upstream exllamav3 1.6.0 (MIT) kernels in triton_paged_cu.py;# EXL3_ATTN16=0 keeps the kernels in this file. ROCm always keeps themATTN16 = (not torch.version.hip) and os.environ.get("EXL3_ATTN16", "1") != "0"@@ -1136,6 +1169,11 @@ def paged_attn_triton_decode(_k = (tuple(q.shape), tuple(k_cache.shape), str(window_size), qc is not None, split_batch)if _k not in _ATTN16_SEEN:_ATTN16_SEEN.add(_k); print(" -- attn16 eager decode", _k, "new" if ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0) else "old", flush = True)+ if qc is not None and _QDEC_HIP and k is None:+ out_hip = _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size, softcap,+ sinks, out, num_splits, max_kv_len, qc, pre_appended_len, n_kv_heads_override)+ if out_hip is not None:+ return out_hipif ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0):from .triton_paged_cu import paged_attn_triton_decode_cu, NoFittingConfigtry:diff --git a/tests/gate_cmp.py b/tests/gate_cmp.pynew file mode 100644index 0000000..d59ba7c--- /dev/null+++ b/tests/gate_cmp.py@@ -0,0 +1,16 @@+"""gate_cmp.py REF.pt NEW.pt : REF = qdec.hip off, NEW = qdec.hip on run with --force REF.pt. Prints per prompt: greedy ids identical / first+divergence (+ REF top1-top2 gap there), teacher-forced top-1 agreement and KL(REF||NEW) over the window."""+import sys, torch+R, N = torch.load(sys.argv[1]), torch.load(sys.argv[2])+for i, (r, n) in enumerate(zip(R["res"], N["res"])):+ g, h = r["gen"], n["gen"]+ L = min(len(g), len(h)); div = next((k for k in range(L) if g[k] != h[k]), None)+ msg = f"prompt {i}: {'IDENTICAL' if div is None and len(g) == len(h) else 'DIVERGES at ' + str(div)}"+ if div is not None:+ top2 = r["lp"][div].float().topk(2); msg += f" (ref top1-top2 logprob gap {float(top2.values[0] - top2.values[1]):.3f}; ref tok {g[div]} new tok {h[div]})"+ p, q = r["lp"].float(), n["lp_forced"].float()+ m = min(len(p), len(q)); p, q = p[:m], q[:m]+ kl = (p.exp() * (p - q)).sum(-1)+ agree = (p.argmax(-1) == q.argmax(-1)).float().mean().item()+ msg += f" | TF top1 agree {agree * 100:.1f}% KL mean {kl.mean().item():.2e} max {kl.max().item():.2e} steps {m}"+ print(msg)diff --git a/tests/gate_kv.py b/tests/gate_kv.pynew file mode 100644index 0000000..1560078--- /dev/null+++ b/tests/gate_kv.py@@ -0,0 +1,72 @@+"""gate_kv.py PACK OUT.pt [--kv 16|K,V] [--depth 4096] [--n 128] [--force REF.pt]+Greedy decode of 3 prompts (real text of ~depth tokens + a question) x n tokens through the production cached decode path, recording the+log-prob distribution at every generated step (fp16). With --force REF.pt the same cache path is then re-run teacher-forced on REF's+generated tokens, so two builds (qdec.hip on/off) can be compared step by step: ids, top-1 agreement, KL (gate_cmp.py).+Env EXL3_QDEC_HIP selects the kernel (the pack's attention reads it at import)."""+import argparse, os, sys, time+ROOT = os.environ.get("ENG") or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+sys.path.insert(0, ROOT)+import torch+from exllamav3 import Config, Model, Cache, Tokenizer, Generator, Job+from exllamav3.cache import CacheLayer_quant+from exllamav3.generator.sampler import Sampler++ap = argparse.ArgumentParser(); ap.add_argument("pack"); ap.add_argument("out"); ap.add_argument("--kv", default="16")+ap.add_argument("--depth", type=int, default=4096); ap.add_argument("--n", type=int, default=128); ap.add_argument("--force")+ap.add_argument("--np", type=int, default=3)+a = ap.parse_args()+++class RecSampler(Sampler):+ """argmax (or the forced token), recording the log-softmax of every step"""+ def __init__(self, forced=None):+ super().__init__(); self.forced = forced; self.i = 0; self.lps = []+ def forward(self, logits, sequence_ids=None, rand_u32=None, tokenizer=None, logit_mask=None, return_state=False):+ lg = logits.float()+ if tokenizer is not None and tokenizer.actual_vocab_size < lg.shape[-1]:+ lg[..., tokenizer.actual_vocab_size:] = -float("inf")+ self.lps.append(torch.log_softmax(lg.reshape(-1, lg.shape[-1])[-1], -1).half().cpu())+ t = self.forced[self.i] if self.forced is not None else int(lg.reshape(-1, lg.shape[-1])[-1].argmax())+ self.i += 1+ return torch.full(logits.shape[:-1], t, dtype=torch.long, device=logits.device)++cfg = Config.from_directory(a.pack); model = Model.from_config(cfg); tok = Tokenizer.from_config(cfg)+ctx = ((a.depth + a.n + 512 + 255) // 256) * 256+if a.kv == "16": cache = Cache(model, max_num_tokens=ctx)+else:+ kb, vb = (int(x) for x in a.kv.split(",")); cache = Cache(model, max_num_tokens=ctx, layer_type=CacheLayer_quant, k_bits=kb, v_bits=vb)+t0 = time.time(); model.load(progressbar=False); print(f"loaded {time.time() - t0:.0f}s", flush=True)+gen = Generator(model=model, cache=cache, tokenizer=tok)+D = os.path.join(ROOT, "exllamav3/conversion/standard_cal_data")+srcs = ["wiki.utf8", "c4.utf8", "code.utf8"]+ref = torch.load(a.force) if a.force else None++def prompt_ids(i):+ if ref: return torch.tensor(ref["res"][i]["prompt"]).view(1, -1)+ s = open(f"{D}/{srcs[i % 3]}", encoding="utf8").read()+ off = 3000 * (i + 1)+ ids = tok.encode(s[off:off + max(a.depth * 8, 20000)], add_bos=False).flatten()[:max(a.depth - 40, 8)]+ q = tok.encode("\n\n---\nQuestion: summarize the text above in two sentences, in French.\nAnswer:", add_bos=False).flatten()+ return torch.cat([ids, q]).view(1, -1)++def run(ids, sampler):+ job = Job(input_ids=ids, max_new_tokens=a.n, sampler=sampler, stop_conditions=[])+ gen.enqueue(job); out = []+ while gen.num_remaining_jobs():+ for r in gen.iterate():+ if r.get("error"): print("JOB ERROR", r["error"])+ if r.get("token_ids") is not None and r["token_ids"].numel(): out += r["token_ids"].flatten().tolist()+ return out++res = []+for i in range(a.np):+ ids = prompt_ids(i)+ s = RecSampler(); t0 = time.time(); out = run(ids, s)+ r = {"prompt": ids.flatten().tolist(), "gen": out, "lp": torch.stack(s.lps)}+ if ref:+ s2 = RecSampler(forced=ref["res"][i]["gen"]); run(ids, s2)+ r["lp_forced"] = torch.stack(s2.lps); r["forced_gen"] = ref["res"][i]["gen"]+ res.append(r)+ print(f"prompt {i}: plen {ids.shape[-1]} gen {len(out)} steps-rec {len(s.lps)} {time.time() - t0:.0f}s", flush=True)+torch.save({"res": res, "kv": a.kv, "depth": a.depth, "hip": os.environ.get("EXL3_QDEC_HIP", "0")}, a.out)+print("saved", a.out)diff --git a/tests/test_qdec_hip.py b/tests/test_qdec_hip.pynew file mode 100644index 0000000..811aee4--- /dev/null+++ b/tests/test_qdec_hip.py@@ -0,0 +1,49 @@+"""qdec.hip vs the Triton decode kernels on random packed caches (any bit pattern is a valid packed state), plus a microbench.+python tests/test_qdec_hip.py [--hd 128 --kb 8 --vb 8 --nqh 32 --nkv 4 --qlen 1 --ctx 4096 --bsz 1 --bench]"""+import argparse, math, os, sys, time+os.environ.setdefault("EXL3_QDEC_HIP", "1")+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))+import torch+from exllamav3.modules.attention_fn import triton_paged as tp++ap = argparse.ArgumentParser()+ap.add_argument("--hd", type=int, default=128); ap.add_argument("--kb", type=int, default=8); ap.add_argument("--vb", type=int, default=8)+ap.add_argument("--nqh", type=int, default=32); ap.add_argument("--nkv", type=int, default=4); ap.add_argument("--qlen", type=int, default=1)+ap.add_argument("--ctx", type=int, default=4096); ap.add_argument("--bsz", type=int, default=1); ap.add_argument("--bench", action="store_true")+ap.add_argument("--noncausal", action="store_true"); ap.add_argument("--sinks", action="store_true"); ap.add_argument("--seed", type=int, default=0)+a = ap.parse_args()+dev = torch.device("cuda")+torch.manual_seed(a.seed)+PAGE = 256+gpt = a.nkv * a.hd // 32+npg = -(-(a.ctx + 64) // PAGE)+tot = a.bsz * npg + 3+def words(b): return torch.randint(-2**31, 2**31 - 1, (tot, PAGE, gpt * b), dtype=torch.int32, device=dev)+kc, vc = words(a.kb), words(a.vb)+ks = (torch.rand(tot, PAGE, gpt, device=dev) * 2 + 0.05).to(torch.float16) * torch.exp(torch.randn(tot, PAGE, gpt, device=dev) * 0.3).to(torch.float16)+vs = (torch.rand(tot, PAGE, gpt, device=dev) * 2 + 0.05).to(torch.float16)+perm = torch.randperm(tot, device=dev)[: a.bsz * npg].to(torch.int32).view(a.bsz, npg).contiguous()+seqs = torch.tensor([a.ctx - 7 * i for i in range(a.bsz)], dtype=torch.int32, device=dev) # tokens already in the cache before this step's q_len+q = (torch.randn(a.bsz, a.qlen, a.nqh, a.hd, device=dev) * 1.0).to(torch.float16)+sinks = torch.randn(a.nqh, device=dev) if a.sinks else None+causal = not a.noncausal+qc = (ks, vs, a.kb, a.vb)+# the cache holds the q_len new tokens already: counted as pre_appended_len+def run(hip):+ tp._QDEC_HIP = hip+ return tp.paged_attn_triton_decode(q, None, None, kc, vc, perm, seqs, causal=causal, softmax_scale=1 / math.sqrt(a.hd), sinks=sinks,+ qc=qc, pre_appended_len=a.qlen, n_kv_heads_override=a.nkv, max_kv_len=a.ctx)+ref = run(False); out = run(True)+torch.cuda.synchronize()+d = (ref.float() - out.float()).abs()+rel = d.max().item() / max(ref.float().abs().max().item(), 1e-9)+print(f"hd{a.hd} k{a.kb}v{a.vb} {a.nqh}/{a.nkv} qlen{a.qlen} ctx{a.ctx} bsz{a.bsz}: max|d| {d.max().item():.3e} mean|d| {d.mean().item():.3e} ref max {ref.float().abs().max().item():.3e} "+ f"rel {rel:.3e} nan {int(torch.isnan(out).any())} identical-sum-check {int(not torch.equal(ref, out))}")+if a.bench:+ nbytes = a.bsz * a.nkv * (a.ctx) * ((a.kb + a.vb) * a.hd // 8 + 2 * (a.hd // 32) * 2)+ for name, hip in (("triton", False), ("hip", True)):+ for _ in range(3): run(hip)+ torch.cuda.synchronize(); t0 = time.perf_counter(); n = 50+ for _ in range(n): run(hip)+ torch.cuda.synchronize(); dt = (time.perf_counter() - t0) / n+ print(f" {name}: {dt * 1e6:8.1f} us/call {nbytes / dt / 1e9:6.1f} GB/s (cache bytes touched {nbytes / 1e6:.1f} MB)")