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
HIP sparse prefill attention: WMMA 4-row union kernel (gfx1151, live switch) (#224)
Yaniss Amazouz21c1e1f3eff5
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 937e735..b2b6ba3 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -12,6 +12,12 @@ commit 07e1191, src/models/qwen38_flash_next/kernels/rocm/kernels.hip.cpp: RouteRoutedScatterKernel and their device helpers, and MoeEpilogueVec4Kernel for fq_routed_f16_combine and fq_routed_f16_combine_shared (its shared-expert term and gate), MIT License, Copyright (c) 2026 gufo contributors). The file keeps its licence header and listsits changes.+exllamav3/modules/attention_fn/qsa_prefill_wmma.hip (4-row union WMMA sparse prefill attention for HIP) follows the structure of Gufo's+WmmaCausalAttentionKernel (https://github.com/gufo-org/gufo, path src/models/qwen38_flash_next/kernels/rocm/kernels.hip.cpp, MIT License,+Copyright (c) 2026 Gufo contributors): several query rows per block, 16-key tiles gathered once from the union of the rows' selections,+K / V tile prefetch in registers, V staged transposed in LDS. The code itself is written for Kyojin's index-list selection (LDS bitonic+union, per-row visibility masks); no Gufo source is copied.+Parts of exllamav3/exllamav3_ext/foreign_quant/ggml_mmvq/ and foreign_quant/fq_mmvq.cu are derived fromllama.cpp (https://github.com/ggml-org/llama.cpp, commit 7182ef7):diff --git a/exllamav3/modules/attention_fn/qsa_prefill_hip.py b/exllamav3/modules/attention_fn/qsa_prefill_hip.pyindex 2506617..210a67d 100644--- a/exllamav3/modules/attention_fn/qsa_prefill_hip.py+++ b/exllamav3/modules/attention_fn/qsa_prefill_hip.py@@ -83,3 +83,68 @@ def qsa_prefill_hip(q, k, v, indices, sm_scale, block_table, page_size, out = Nor = _state["lib"].hipModuleLaunchKernel(fn, R * 2, 1, 1, 32, 1, 1, 0, torch.cuda.current_stream(device).cuda_stream, params, None)if r != 0: raise RuntimeError(f"qsa_prefill_hip: launch failed ({r})")return out+++# ---- 4-row union WMMA variant (qsa_prefill_wmma.hip), EXL3_HIP_ATTN_WMMA ----+_WMMA_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qsa_prefill_wmma.hip")++_WMMA_ARCH = {}+++def wmma_enabled(device = None) -> bool:+ # Live switch (read on every call, no reload): EXL3_HIP_ATTN_WMMA=0 / 1 forces it; unset = on for gfx1151 (the arch the+ # kernel is compiled and measured for), off elsewhere+ v = os.environ.get("EXL3_HIP_ATTN_WMMA", "")+ if v in ("0", "1"):+ return v == "1"+ key = str(device)+ if key not in _WMMA_ARCH:+ _WMMA_ARCH[key] = bool(torch.version.hip) and device_arch(device).split(":")[0] == "gfx1151"+ return _WMMA_ARCH[key]++def _load_wmma(device = None, defs = ""):+ dev = select_device(device)+ key = (dev, "wmma", defs)+ if key in _state: return _state[key]+ src = open(_WMMA_SRC, "rb").read()+ flags = ["--genco", f"--offload-arch={device_arch(dev)}", "-O3", "-ffp-contract=off", "--no-gpu-bundle-output"] + [x if x.startswith("-") else f"-D{x}" for x in defs.split()]+ flags += hip_compiler.gcc_flags()+ tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]+ cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"qsa_pfw_{device_arch(dev)}_{tag}.hsaco")+ if not os.path.isfile(cache):+ os.makedirs(os.path.dirname(cache), exist_ok = True)+ tmp = cache + f".{os.getpid()}.tmp"+ r = subprocess.run([_hipcc(), *flags, "-o", tmp, _WMMA_SRC], capture_output = True, text = True)+ if r.returncode: raise RuntimeError(r.stderr[-3000:])+ os.replace(tmp, cache)+ lib = load_hip_runtime()+ torch.cuda.init()+ mod = ctypes.c_void_p()+ if lib.hipModuleLoad(ctypes.byref(mod), cache.encode()) != 0: raise RuntimeError("qsa_prefill_wmma: hipModuleLoad failed")+ fn = ctypes.c_void_p()+ if lib.hipModuleGetFunction(ctypes.byref(fn), mod, b"qsa_pf_wmma") != 0: raise RuntimeError("qsa_prefill_wmma: no function")+ lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3+ _state["lib"] = lib; _state[key] = fn; _state["mod", key] = mod+ return fn++def qsa_prefill_wmma(q, k, v, indices, sm_scale, block_table, page_size, out = None, defs = ""):+ """Same contract as qsa_prefill_hip (1-D block table, fp16, Qwen shape) through the 4-row union kernel."""+ R, H, hd = q.shape+ assert (H, hd, k.shape[1], page_size, indices.shape[1]) == (24, 256, 2, 256, 2080), "qsa_prefill_wmma: Qwen shape only"+ assert q.dtype == k.dtype == v.dtype == torch.half and q.stride(2) == 1 and q.stride(1) == hd+ assert k.stride(1) == hd and k.stride(2) == 1 and k.stride() == v.stride() and indices.is_contiguous() and indices.dtype == torch.int32+ assert indices.shape[0] == R and R >= 1+ assert q.stride(0) % 8 == 0 and q.data_ptr() % 16 == 0 and k.data_ptr() % 16 == 0 and v.data_ptr() % 16 == 0 and k.stride(0) % 8 == 0+ assert indices.data_ptr() % 16 == 0 and block_table.dim() == 1 and block_table.is_contiguous() and block_table.dtype == torch.int32+ if out is None: out = torch.empty((R, H, hd), dtype = torch.half, device = q.device)+ assert out.stride(2) == 1 and out.stride(1) == hd and out.stride(0) % 8 == 0 and out.data_ptr() % 16 == 0+ ntok = k.shape[0]; assert v.shape[0] == ntok+ device = q.device+ fn = _load_wmma(device, defs)+ select_device(device)+ cargs = [ctypes.c_void_p(a.data_ptr()) for a in (q, k, v, block_table, indices, out)] + \+ [ctypes.c_int(x) for x in (q.stride(0), out.stride(0), k.stride(0), ntok, block_table.shape[-1], R)] + [ctypes.c_float(sm_scale)]+ params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])+ r = _state["lib"].hipModuleLaunchKernel(fn, ((R + 3) // 4) * 2, 1, 1, 256, 1, 1, 0, torch.cuda.current_stream(device).cuda_stream, params, None)+ if r != 0: raise RuntimeError(f"qsa_prefill_wmma: launch failed ({r})")+ return outdiff --git a/exllamav3/modules/attention_fn/qsa_prefill_wmma.hip b/exllamav3/modules/attention_fn/qsa_prefill_wmma.hipnew file mode 100644index 0000000..e5c7e14--- /dev/null+++ b/exllamav3/modules/attention_fn/qsa_prefill_wmma.hip@@ -0,0 +1,290 @@+// Qwen QSA sparse prefill attention, 4-row union variant for gfx11.5 WMMA f16 (wave32, 8 waves per block).+// Structure after Gufo's WmmaCausalAttentionKernel (https://github.com/gufo-org/gufo, MIT License, Copyright (c) 2026 Gufo contributors):+// one block serves several consecutive query rows of one kv head, walks the UNION of their selected key blocks in 16-key tiles (each K / V+// tile is gathered from global memory once for all rows), prefetches the next K tile / this V tile in registers behind the matrix work, and+// stages V transposed in LDS. Own code: the union is built in LDS (bitonic sort + dedupe) from the per-row index lists, rows keep their own+// selection through a per-(block, row) validity mask, softmax is online per (row, head) column in fp32.+// Block = 4 rows x 12 heads = 48 columns = 3 WMMA column tiles. Selection lists are 520 groups of 4 consecutive tokens (one 4-token block each).+// 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: global addresses are clamped (TOKC, PGC, row clamp); stores are guarded by the row bound.+#include <hip/hip_runtime.h>+#include <stdint.h>++typedef _Float16 half_t;+typedef _Float16 v16h __attribute__((ext_vector_type(16)));+typedef float v8f __attribute__((ext_vector_type(8)));+typedef uint32_t v4u __attribute__((ext_vector_type(4)));++#define HD 256+#define GRP 12+#define NKV 2+#define PAGE 256+#define KPAD 2080+#define NGRP (KPAD / 4) // 520 groups of 4 tokens per row+#define NR 4 // rows per block+#define NCOL 48+#define LDQ 264 // q / K / out pitch (halves)+#define LDT 24 // V^T and P pitch (halves): 16 keys + pad+#define SORTN 4096+#define MAXU 2096 // union entries (<= 2080) + pad++#define IX_Q(r_, h_, d_, p_) (((int64_t) (r_)) * (p_) + (h_) * HD + (d_))+#define IX_O(r_, h_, d_, p_) (((int64_t) (r_)) * (p_) + (h_) * HD + (d_))+#define IX_IDX(r_, n_) (((int64_t) (r_)) * KPAD + (n_))+#define PGC(pg_, NP_) min(max((pg_), 0), (NP_) - 1)+#define TOKC(t_, NT_) min(max((t_), 0), (NT_) - 1)+#define IX_KV(t_, g_, d_, p_) (((int64_t) (t_)) * (p_) + (g_) * HD + (d_))++__device__ __forceinline__ v8f wmma(v16h a, v16h b, v8f c) { return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); }+__device__ __forceinline__ v16h ld16h(const half_t* p) {+ v4u a = *(const v4u*) p, b = *(const v4u*) (p + 8);+ union { v4u u[2]; v16h h; } x; x.u[0] = a; x.u[1] = b; return x.h;+}+__device__ __forceinline__ __attribute__((convergent)) void sync_lds() { // LDS-only exchange: do not drain global loads+ asm volatile("s_waitcnt lgkmcnt(0)" ::: "memory");+ __builtin_amdgcn_s_barrier();+ asm volatile("" ::: "memory");+}++#ifndef NVGPR+#define NVGPR 192+#endif+#ifndef WPE+#define WPE 8 // 8 waves per SIMD = 2 blocks per CU (192 VGPRs)+#endif+extern "C" __global__ __launch_bounds__(256) __attribute__((amdgpu_waves_per_eu(WPE))) __attribute__((amdgpu_num_vgpr(NVGPR))) void qsa_pf_wmma(+ const half_t* __restrict__ q, const half_t* __restrict__ kc, const half_t* __restrict__ vc,+ const int* __restrict__ bt, const int* __restrict__ idx, half_t* __restrict__ o,+ int q_stride, int o_stride, int tok_stride, int ntok, int npages, int R, float scale)+{+ const int tid = threadIdx.x, w = tid >> 5, lane = tid & 31, n = lane & 15, hh = lane >> 4;+ const int g = blockIdx.x & 1, row0 = (blockIdx.x >> 1) * NR;++ __shared__ uint32_t sBlk[MAXU];+ __shared__ uint16_t sVm[MAXU]; // bit 4 * row + (token & 3): token visible to that row+ // one aliased region: sort buffer (start-up) | K tile / V^T | P | partial scores (loop) | output staging (end)+ __shared__ __attribute__((aligned(16))) char sBig[26112];+ half_t* const sKV = (half_t*) sBig; // K tile [16][LDQ] (8448 B)+ half_t* const sV = (half_t*) (sBig + 8448); // V^T [256][LDT] (12288 B)+ half_t* const sP = (half_t*) (sBig + 20736); // NCOL * LDT halves = 2304 B+ float* const sSp = (float*) (sBig + 23040); // 3 * 32 * 8 floats = 3072 B+ __shared__ float sAlpha[NCOL];+ __shared__ float sL[NCOL];+ __shared__ uint32_t sCnt[256];++ // ---- union of the 4 rows' selected blocks ----+ uint32_t* sSort = (uint32_t*) sBig;+ for (int e = tid; e < SORTN; e += 256) {+ uint32_t key = 0xFFFFFFFFu;+ if (e < NR * NGRP) {+ const int rho = e / NGRP, j = e - rho * NGRP;+ const int row = min(row0 + rho, R - 1);+ const int4 t = *(const int4*) (idx + IX_IDX(row, 4 * j));+ const uint32_t nib = (t.x >= 0 ? 1u : 0u) | (t.y >= 0 ? 2u : 0u) | (t.z >= 0 ? 4u : 0u) | (t.w >= 0 ? 8u : 0u);+ if (nib) {+ const int f = t.x >= 0 ? t.x : (t.y >= 0 ? t.y : (t.z >= 0 ? t.z : t.w));+ key = (((uint32_t) (f >> 2)) << 6) | ((uint32_t) rho << 4) | nib;+ }+ }+ sSort[e] = key;+ }+ sync_lds();+ for (int k = 2; k <= SORTN; k <<= 1)+ for (int j = k >> 1; j > 0; j >>= 1) {+ if (j >= 32) sync_lds(); // pairs of a step with j < 32 stay inside one wave: LDS order is enough+ else asm volatile("s_waitcnt lgkmcnt(0)" ::: "memory");+ for (int p = tid; p < SORTN / 2; p += 256) {+ const int i = ((p & ~(j - 1)) << 1) | (p & (j - 1)), i2 = i | j;+ const uint32_t a = sSort[i], b = sSort[i2];+ const bool up = (i & k) == 0;+ if ((a > b) == up) { sSort[i] = b; sSort[i2] = a; }+ }+ }+ sync_lds();+ {+ uint32_t cnt = 0;+ for (int e = tid * 16; e < tid * 16 + 16; ++e) {+ const uint32_t k = sSort[e];+ if (k != 0xFFFFFFFFu && (e == 0 || (sSort[e - 1] >> 6) != (k >> 6))) ++cnt;+ }+ sCnt[tid] = cnt;+ for (int off = 1; off < 256; off <<= 1) {+ sync_lds();+ const uint32_t v = tid >= off ? sCnt[tid - off] : 0u;+ sync_lds();+ sCnt[tid] += v;+ }+ sync_lds();+ uint32_t pos = sCnt[tid] - cnt;+ for (int e = tid * 16; e < tid * 16 + 16; ++e) {+ const uint32_t k = sSort[e];+ if (k != 0xFFFFFFFFu && (e == 0 || (sSort[e - 1] >> 6) != (k >> 6))) {+ uint32_t vm = 0;+ for (int u = e; u < e + 4 && u < SORTN && sSort[u] != 0xFFFFFFFFu && (sSort[u] >> 6) == (k >> 6); ++u)+ vm |= (sSort[u] & 15u) << (4 * ((sSort[u] >> 4) & 3));+ sBlk[pos] = k >> 6; sVm[pos] = vm; ++pos;+ }+ }+ }+ sync_lds();+ const int nU = (int) sCnt[255];+ if (tid < 8) { sBlk[nU + tid] = 0; sVm[nU + tid] = 0; }+ sync_lds();+#ifdef NOLOOP+ const int ntile = 0;+#else+ const int ntile = (nU + 3) >> 2;+#endif++ // ---- q B fragments of this wave (column tile ct, half dh of the head dim) straight from global ----+ v16h qf[8];+ {+ const int ctq = w % 3, dhq = w / 3, colq = 16 * ctq + n, rhoq = colq / GRP, hq = colq - rhoq * GRP;+ const int rowq = min(row0 + rhoq, R - 1);+#pragma unroll+ for (int ks = 0; ks < 8; ++ks) qf[ks] = (w < 6) ? ld16h(q + IX_Q(rowq, g * GRP + hq, 16 * (dhq * 8 + ks), q_stride)) : (v16h) {0};+ }+ sync_lds(); // sort buffer dead before the first K tile lands in the same LDS++ v8f acc[2][3];+#pragma unroll+ for (int a = 0; a < 2; ++a)+#pragma unroll+ for (int b = 0; b < 3; ++b) acc[a][b] = (v8f) {0, 0, 0, 0, 0, 0, 0, 0};+ float m = -__builtin_inff(), l = 0.0f;+ const float sl2 = scale * 1.44269504088896341f;+ const int kk = tid & 15, dch = tid >> 4;++#ifdef NOGLOB+#define GLD(p_) ((v4u) {1, 2, 3, 4})+#else+#define GLD(p_) (*(const v4u*) (p_))+#endif+ auto key_tok = [&](int i) -> int {+ const int blk = (int) sBlk[4 * i + (kk >> 2)];+ const int t0 = blk * 4;+ const int pg = bt[PGC(t0 / PAGE, npages)];+ return TOKC(pg * PAGE + (t0 % PAGE) + (kk & 3), ntok);+ };+ auto load_tile = [&](int i, v4u& k0, v4u& k1, v4u& v0, v4u& v1) {+ const int tk = key_tok(i);+ const uint32_t vm = sVm[4 * i + (kk >> 2)];+ const bool any = ((vm >> (kk & 3)) & 0x1111u) != 0u;+ k0 = GLD(kc + IX_KV(tk, g, dch * 16, tok_stride));+ k1 = GLD(kc + IX_KV(tk, g, dch * 16 + 8, tok_stride));+ v0 = (v4u) {0, 0, 0, 0}; v1 = (v4u) {0, 0, 0, 0};+ if (any) {+ v0 = GLD(vc + IX_KV(tk, g, dch * 16, tok_stride));+ v1 = GLD(vc + IX_KV(tk, g, dch * 16 + 8, tok_stride));+ }+ };+ v4u ka0 = {0, 0, 0, 0}, ka1 = {0, 0, 0, 0}, va0 = {0, 0, 0, 0}, va1 = {0, 0, 0, 0};+ v4u kb0 = {0, 0, 0, 0}, kb1 = {0, 0, 0, 0}, vb0 = {0, 0, 0, 0}, vb1 = {0, 0, 0, 0};+ if (ntile > 0) load_tile(0, ka0, ka1, va0, va1);+ half_t* sK = sKV;++ auto tile = [&](int i, v4u& kr0, v4u& kr1, v4u& vr0, v4u& vr1, v4u& kn0, v4u& kn1, v4u& vn0, v4u& vn1) {+ *(v4u*) (sK + kk * LDQ + dch * 16) = kr0;+ *(v4u*) (sK + kk * LDQ + dch * 16 + 8) = kr1;+ { // V^T into the same LDS (one key per lane group: conflict-free writes)+ const half_t* a0 = (const half_t*) &vr0;+ const half_t* a1 = (const half_t*) &vr1;+#pragma unroll+ for (int j = 0; j < 8; ++j) { sV[(dch * 16 + j) * LDT + kk] = a0[j]; sV[(dch * 16 + 8 + j) * LDT + kk] = a1[j]; }+ }+ if (i + 1 < ntile) load_tile(i + 1, kn0, kn1, vn0, vn1); // whole next tile in flight behind this tile's work+ sync_lds(); // K tile and V^T visible+ v8f S = (v8f) {0, 0, 0, 0, 0, 0, 0, 0};+ if (w < 6) { // scores: wave = (column tile, half of the head dim)+ const int ct = w % 3, dh = w / 3;+#pragma unroll+ for (int ks = 0; ks < 8; ++ks) {+ const int kq = dh * 8 + ks;+#ifndef NOS+ S = wmma(ld16h(sK + n * LDQ + 16 * kq), qf[ks], S);+#endif+ }+ if (dh) *(v8f*) (sSp + (ct * 32 + lane) * 8) = S;+ }+ sync_lds(); // partial scores of the second head-dim half+ if (w < 3) {+ S += *(const v8f*) (sSp + (w * 32 + lane) * 8);+ const int col = 16 * w + n, rho = col / GRP;+ float s[8], mx = -__builtin_inff();+ bool ok[8];+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const int kq = 2 * r + hh;+ const uint32_t vm = sVm[4 * i + (kq >> 2)];+ ok[r] = (vm >> (4 * rho + (kq & 3))) & 1u;+ s[r] = ok[r] ? S[r] * sl2 : -__builtin_inff();+ mx = fmaxf(mx, s[r]);+ }+ mx = fmaxf(mx, __shfl_xor(mx, 16));+ const float m_new = fmaxf(m, mx);+ const float m_exp = (m_new == -__builtin_inff()) ? 0.0f : m_new;+ const float alpha = (m == -__builtin_inff()) ? 0.0f : __builtin_amdgcn_exp2f(m - m_exp);+ float sum = 0.0f;+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const float p = ok[r] ? __builtin_amdgcn_exp2f(s[r] - m_exp) : 0.0f;+ sum += p;+ sP[col * LDT + 2 * r + hh] = (half_t) p;+ }+ sum += __shfl_xor(sum, 16);+ l = l * alpha + sum;+ m = m_new;+ if (hh == 0) sAlpha[col] = alpha;+ }+ sync_lds(); // P, alpha; K tile no longer read+ {+ float al[3];+ v16h Bp[3];+#pragma unroll+ for (int ct = 0; ct < 3; ++ct) { al[ct] = sAlpha[16 * ct + n]; Bp[ct] = ld16h(sP + (16 * ct + n) * LDT); }+#pragma unroll+ for (int dt = 0; dt < 2; ++dt) {+ const v16h A = ld16h(sV + (16 * (2 * w + dt) + n) * LDT);+#pragma unroll+ for (int ct = 0; ct < 3; ++ct) {+ v8f c = acc[dt][ct] * al[ct];+#ifndef NOPV+ acc[dt][ct] = wmma(A, Bp[ct], c);+#else+ acc[dt][ct] = c;+#endif+ }+ }+ }+ sync_lds(); // sKV / sP free+ };+ for (int i = 0; i < ntile; i += 2) {+ tile(i, ka0, ka1, va0, va1, kb0, kb1, vb0, vb1);+ if (i + 1 < ntile) tile(i + 1, kb0, kb1, vb0, vb1, ka0, ka1, va0, va1);+ }++ // ---- epilogue: acc / l, staged in LDS in two halves of 24 columns, coalesced stores ----+ if (w < 3 && hh == 0) sL[16 * w + n] = l;+ half_t* sO = (half_t*) sBig;+ for (int ph = 0; ph < 2; ++ph) {+ sync_lds();+#pragma unroll+ for (int dt = 0; dt < 2; ++dt)+#pragma unroll+ for (int ct = 0; ct < 3; ++ct) {+ const int col = 16 * ct + n;+ if (col / 24 == ph) {+ const float lv = sL[col];+#pragma unroll+ for (int r = 0; r < 8; ++r)+ sO[(col - 24 * ph) * LDQ + 16 * (2 * w + dt) + 2 * r + hh] = (half_t) (lv > 0.0f ? acc[dt][ct][r] / lv : 0.0f);+ }+ }+ sync_lds();+ for (int c = tid; c < 24 * 32; c += 256) {+ const int cl = c >> 5, ch = c & 31, col = cl + 24 * ph, rho = col / GRP, h = col - rho * GRP;+ const int row = row0 + rho;+ if (row < R) *(v4u*) (o + IX_O(row, g * GRP + h, ch * 8, o_stride)) = *(const v4u*) (sO + cl * LDQ + ch * 8);+ }+ }+}diff --git a/exllamav3/modules/qsa_indexer.py b/exllamav3/modules/qsa_indexer.pyindex eacd44f..0617e2a 100644--- a/exllamav3/modules/qsa_indexer.py+++ b/exllamav3/modules/qsa_indexer.py@@ -891,9 +891,13 @@ class QSAIndexer(Module):if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and qc is None and bsz == 1 and seq >= 64 and seq <= 4096 * 4and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)and q_rows.dtype == torch.half and k_arg.dtype == torch.half and _pf_hip_ready(q.device)):- # one wave per (row, kv head) HIP kernel, bit-identical to the Triton pair (fp16 cache, prefill chunks only)- from .attention_fn.qsa_prefill_hip import qsa_prefill_hip- o = qsa_prefill_hip(q_rows, k_arg, v_arg, indices, attn.sm_scale, block_table[0].int().contiguous(), page_size)+ # one wave per (row, kv head) HIP kernel, bit-identical to the Triton pair (fp16 cache, prefill chunks only); on gfx1151 the+ # 4-row union WMMA kernel by default (fp16 rounding-level difference, live switch EXL3_HIP_ATTN_WMMA)+ from .attention_fn.qsa_prefill_hip import qsa_prefill_hip, qsa_prefill_wmma, wmma_enabled+ if wmma_enabled(q.device):+ o = qsa_prefill_wmma(q_rows, k_arg, v_arg, indices, attn.sm_scale, block_table[0].int().contiguous(), page_size)+ else:+ o = qsa_prefill_hip(q_rows, k_arg, v_arg, indices, attn.sm_scale, block_table[0].int().contiguous(), page_size)return o.view(bsz, seq, attn.num_q_heads, attn.head_dim)if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and os.environ.get("EXL3_QSA_PF_DEQ", "1") == "1" and qc is not Noneand tq is None and qc[2] == 8 and qc[3] == 8 and bsz == 1 and seq >= 64 and seq <= 4096 * 4diff --git a/tests/check_qsa_wmma_bounds.py b/tests/check_qsa_wmma_bounds.pynew file mode 100644index 0000000..1779920--- /dev/null+++ b/tests/check_qsa_wmma_bounds.py@@ -0,0 +1,110 @@+"""CPU bounds check for qsa_prefill_wmma.hip (no GPU). usage: python tests/check_qsa_wmma_bounds.py [file.hip]+ 1. static: every global dereference of q / kc / vc / bt / idx / o goes through an IX_* macro, the o store is row-guarded,+ K/V token and page are clamped (TOKC / PGC), q and idx rows are clamped with min(.., R - 1).+ 2. replay: macros are taken from the source text; every global access of the kernel (idx int4 loads, q fragments, K/V gathers+ through the block table, o stores) is replayed over adversarial data (indices past the context up to 2^31-1, huge / negative+ block-table entries, R not a multiple of 4) and compared with the exact element range of its buffer.+ 3. LDS: static offsets of the aliased region are checked against its size."""+import os, re, sys+import numpy as np++path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "exllamav3", "modules", "attention_fn", "qsa_prefill_wmma.hip")+src = open(path).read()+def die(m): print("FAIL:", m); sys.exit(1)++macros = {m.group(1): (m.group(2).replace(" ", "").split(","), m.group(3).strip())+ for m in re.finditer(r"^#define (\w+)\(([^)]*)\)\s+(.*?)(?://.*)?$", src, re.M)}+consts = {m.group(1): int(m.group(2)) for m in re.finditer(r"^#define (\w+)\s+(\d+)\b", src, re.M)}+consts["NGRP"] = consts["KPAD"] // 4+def mk(name):+ args, body = macros[name]+ body = body.replace("(int64_t)", "")+ return eval("lambda " + ",".join(args) + ": " + body, dict(consts, min=min, max=max))+IX_Q, IX_O, IX_IDX, IX_KV, PGC, TOKC = [mk(n) for n in ("IX_Q", "IX_O", "IX_IDX", "IX_KV", "PGC", "TOKC")]+HD, GRP, PAGE, KPAD, NR, NGRP, MAXU = [consts[k] for k in ("HD", "GRP", "PAGE", "KPAD", "NR", "NGRP", "MAXU")]++# ---- part 1: static+body = src[src.index('extern "C" __global__'):]+for d in re.findall(r"[^;\n]*\b(?:q|kc|vc|bt|idx|o)\s*(?:\+|\[)[^;\n]*", body):+ if "IX_" not in d and "bt[PGC(" not in d: die("raw global access: " + d.strip())+for ln in body.splitlines():+ if re.search(r"\(o \+", ln) and "row < R" not in ln: die("unguarded store: " + ln.strip())+for pat in ("TOKC(pg", "PGC(t0", "min(row0 + rho, R - 1)", "min(row0 + rhoq, R - 1)"):+ if pat not in body: die("missing clamp: " + pat)+print("static ok")++# ---- part 3: LDS+BIG = int(re.search(r"sBig\[(\d+)\]", body).group(1))+LDQ, LDT, SORTN = consts["LDQ"], consts["LDT"], consts["SORTN"]+offs = {"sKV": 8448, "sV": 8448 + 0, "sP": 20736, "sSp": 23040}+assert int(re.search(r"sBig \+ (\d+)\)", body).group(1)) == 8448+lds = [("sort", 4 * SORTN), ("K tile", 2 * (15 * LDQ + 15 * 16 + 8 + 8)), ("V^T", 8448 + 2 * (255 * LDT + 15 + 1)),+ ("P", 20736 + 2 * (47 * LDT + 15 + 1)), ("partial scores", 23040 + 4 * ((2 * 32 + 31) * 8 + 8)),+ ("out staging", 2 * (23 * LDQ + 16 * 15 + 2 * 7 + 1 + 1)), ("out read", 2 * (23 * LDQ + 31 * 8 + 8))]+for n, e in lds:+ if e > BIG: die(f"LDS overflow {n}: {e} > {BIG}")+if consts["NGRP"] * NR > MAXU: die("union exceeds MAXU")+print("lds ok (aliased region %d B, max use %d B)" % (BIG, max(e for _, e in lds)))++# ---- part 2: replay+rng = np.random.default_rng(11)+viol = []+def chk(kind, lo, n_el, size, what):+ if lo < 0 or lo + n_el > size: viol.append((kind, what, lo, n_el, size))++def scenario(ctx, R, q_stride, o_stride, tok_stride, adversarial):+ npages = ctx // PAGE; ntok = ctx+ q_size = (R - 1) * q_stride + 24 * HD; o_size = (R - 1) * o_stride + 24 * HD+ kv_size = (ntok - 1) * tok_stride + 2 * HD; idx_size = R * KPAD+ if adversarial:+ bt = rng.integers(-2**31, 2**31 - 1, npages); bt[::3] = rng.integers(0, npages, len(bt[::3]))+ else:+ bt = rng.permutation(npages)+ blocks = sorted({0, R // 2, max(0, ((R - 1) // NR)) , (R - 1) // NR})+ for rb in blocks:+ row0 = rb * NR+ nU = 0; ublk = []+ for g in range(2):+ for rho in range(NR): # phase A: idx loads+ row = min(row0 + rho, R - 1)+ n = int(rng.integers(1, KPAD + 1))+ ids = np.sort(rng.integers(0, ctx if not adversarial else 2**31 - 1, n))+ if adversarial: ids[-1] = 2**31 - 1+ lst = np.full(KPAD, -1, np.int64); lst[:n] = ids+ for j in range(NGRP):+ chk("idx", IX_IDX(row, 4 * j), 4, idx_size, (row, j))+ f = int(lst[4 * j]) if lst[4 * j] >= 0 else -1+ if f >= 0:+ key = ((f >> 2) << 6) & 0xFFFFFFFF # uint32 wrap as in the kernel+ ublk.append(key >> 6)+ for w in range(6): # phase B: q fragments+ ctq, dhq = w % 3, w // 3+ for ln in (0, 15, 16, 31):+ colq = 16 * ctq + (ln & 15); rhoq = colq // GRP; hq = colq - rhoq * GRP+ rowq = min(row0 + rhoq, R - 1)+ for ks in range(8): chk("q", IX_Q(rowq, g * GRP + hq, 16 * (dhq * 8 + ks), q_stride), 16, q_size, (rowq, hq))+ ublk = sorted(set(ublk))[:MAXU - 8] or [0]+ ublk_p = ublk + [0] * 8 # padding entries written by the kernel+ ntile = (len(ublk) + 3) >> 2+ for i in range(ntile): # phase C: K / V gathers+ for kk in range(16):+ blk = ublk_p[4 * i + (kk >> 2)]; t0 = blk * 4+ pg = int(bt[PGC(t0 // PAGE, npages)])+ tk = TOKC(pg * PAGE + (t0 % PAGE) + (kk & 3), ntok)+ for dch in (0, 15):+ chk("kv", IX_KV(tk, g, dch * 16, tok_stride), 16, kv_size, (tk, g))+ for c in range(24 * 32 * 2): # phase D: stores+ ph = c // (24 * 32); cc = c % (24 * 32); cl = cc >> 5; ch = cc & 31+ col = cl + 24 * ph; rho = col // GRP; h = col - rho * GRP; row = row0 + rho+ if row < R: chk("o", IX_O(row, g * GRP + h, ch * 8, o_stride), 8, o_size, (row, h))+ if len(ublk) > MAXU - 8: viol.append(("union", "too many", len(ublk), 0, MAXU))++for ctx in (16384, 131072, 163840):+ for R in (1, 2, 3, 5, 2048, 8190, 8192):+ for adv in (False, True):+ scenario(ctx, R, 24 * HD, 24 * HD, 2 * HD, adv)+ scenario(ctx, 4097, 3 * 24 * HD, 24 * HD, 2 * HD + 64, True) # padded strides+if viol:+ print("FAIL: %d violations, first: %s" % (len(viol), viol[:3])); sys.exit(1)+print("replay ok")+print("OK")