Skip to content

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.

Hy4 prefill: hand-written HIP/WMMA sparse MLA kernel (one workgroup per query, 16 waves, Q resident, gathered K tiles via LDS), host guard-page test, GPU exactness test and microbench

YanissAmz68ec00ab1746
diff --git a/hipsp/build.sh b/hipsp/build.sh
new file mode 100755
index 0000000..02572de
--- /dev/null
+++ b/hipsp/build.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# build.sh SRC.cu OUT.so [VENV] : HIP library for gfx1151 (SDK toolchain that matches torch). Prints resource usage.
+SRC=$1; OUT=$2; VENV=${3:-${VIRTUAL_ENV:-.venv}}
+SDK=$(PATH=$VENV/bin:$PATH rocm-sdk path --root)
+GCCD=$(dirname "$(gcc -print-libgcc-file-name)")
+BC=$SDK/lib/llvm/amdgcn/bitcode; [ -d $BC ] || BC=$SDK/amdgcn/bitcode
+export ROCM_PATH=$SDK HIP_PATH=$SDK
+$SDK/bin/hipcc -x hip --offload-arch=gfx1151 -O3 -std=c++17 -shared -fPIC --gcc-install-dir=$GCCD --rocm-device-lib-path=$BC --rocm-path=$SDK -I$(dirname $SRC) -Rpass-analysis=kernel-resource-usage "$SRC" -o "$OUT" 2>&1 | grep -E "error|VGPRs:|Spill|LDS Size|Occupancy|Function Name|warning: " | head -60
+ls -la "$OUT"
diff --git a/hipsp/host_guard_test.cpp b/hipsp/host_guard_test.cpp
new file mode 100644
index 0000000..3a0db63
--- /dev/null
+++ b/hipsp/host_guard_test.cpp
@@ -0,0 +1,56 @@
+// CPU-side bounds test of the gather address math (sp_idx.h) with mmap guard pages: every virtual key of every tile of every query is
+// resolved through sp_row and the whole latent row [0, 576) is read; gidx holds exactly ns entries followed by a PROT_NONE page.
+#include <sys/mman.h>
+#include <unistd.h>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <vector>
+#include <stdint.h>
+#include "sp_idx.h"
+static void* guarded(size_t bytes, void** base, size_t* tot)
+{
+ const size_t pg = sysconf(_SC_PAGESIZE), body = (bytes + pg - 1) / pg * pg, total = body + 2 * pg;
+ char* b = (char*)mmap(nullptr, total, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ mprotect(b, pg, PROT_NONE); mprotect(b + pg + body, pg, PROT_NONE);
+ *base = b; *tot = total;
+ return b + pg + body - bytes; // data ends exactly at the trailing guard page
+}
+template <int KP> static long run(int N, int T, int qstart, int ns_cap, int tail, unsigned seed)
+{
+ srand(seed);
+ void *b1, *b2; size_t t1, t2;
+ int16_t* kc = (int16_t*)guarded((size_t)N * 576 * 2, &b1, &t1);
+ long chk = 0;
+ for (int t = 0; t < T; t++) {
+ const int pos = qstart + t, lo_t = sp_lo_t(pos, KP, tail), ntail = pos - lo_t + 1;
+ const int P = (pos / KP) > 0 ? pos / KP : 1;
+ int ns = rand() % (ns_cap + 1); if (ns > P) ns = P;
+ int* gi = (int*)guarded((size_t)(ns ? ns : 1) * 4, &b2, &t2);
+ for (int i = 0; i < ns; i++) gi[i] = (int)((long)i * P / (ns ? ns : 1)); // ascending, < P (groups fully before pos)
+ const int nv = ns * KP + ntail, ntiles = (nv + 15) >> 4;
+ for (int tau = 0; tau < ntiles; tau++)
+ for (int k = 0; k < 16; k++) {
+ const int row = sp_row<KP>(tau * 16 + k, nv, ns, lo_t, gi, N);
+ if (row < 0 || row >= N) { printf("OOB row %d (N %d)\n", row, N); exit(1); }
+ chk += kc[(long)row * 576] + kc[(long)row * 576 + 575]; // touches first and last element of the row
+ }
+ munmap(b2, t2);
+ }
+ munmap(b1, t1);
+ return chk;
+}
+int main()
+{
+ int cases = 0;
+ const int Ns[] = {1, 3, 4, 5, 17, 40, 255, 2049, 3000, 33001};
+ for (int N : Ns)
+ for (int tail = 0; tail < 2; tail++) {
+ const int T = N < 64 ? N : 64;
+ for (int qs : {0, N - T}) {
+ run<4>(N, T, qs, 511, tail, N + qs); run<2>(N, T, qs, 511, tail, N + 1); run<8>(N, T, qs, 300, tail, N + 2); cases += 3;
+ }
+ }
+ printf("guard-page host test OK (%d cases)\n", cases);
+ return 0;
+}
diff --git a/hipsp/mb_hip.py b/hipsp/mb_hip.py
new file mode 100644
index 0000000..68bbaeb
--- /dev/null
+++ b/hipsp/mb_hip.py
@@ -0,0 +1,46 @@
+"""microbench: HIP sparse MLA vs Triton mla_sparse, 8192-row chunk, TF from the real key count. python mb_hip.py TREE [N,N,..]"""
+import os, sys, types, time, json
+import torch
+tree = sys.argv[1]
+for n, s in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ m = types.ModuleType(n); m.__path__ = [os.path.join(tree, "exllamav3", s)]; sys.modules[n] = m
+from exllamav3.loader import prefill_kernels as PK, prefill_attn as PA
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import sp_hip
+dev = "cuda"
+H, R, Pd, KP, NTOP = 64, 512, 64, 4, 511
+scale = 1 / 16.0
+Ns = [int(x) for x in sys.argv[2].split(",")] if len(sys.argv) > 2 else [8192, 33000, 131072]
+def tm(f, reps=3):
+ f(); torch.cuda.synchronize(); t = time.time()
+ for _ in range(reps): f()
+ torch.cuda.synchronize(); return (time.time() - t) / reps * 1000
+torch.manual_seed(0)
+qc8 = (torch.randn(H, 8192, R + Pd, device=dev) * 0.3).half()
+sinks = torch.randn(H, device=dev)
+# ceiling: fixed resident tile, 128 tiles (2048 keys) per query
+kc0 = (torch.randn(8192, R + Pd, device=dev) * 0.3).half()
+class S: pass
+s0 = S(); s0.gidx = torch.zeros(8192, 512, dtype=torch.int32, device=dev); s0.nsel = torch.zeros(8192, dtype=torch.int32, device=dev); s0.tail = True; s0.kpool = 4
+ms = tm(lambda: sp_hip.mla_sparse_hip(R, kc0, 0, scale, sinks, s0, qc8, fixed_tiles=128))
+fl = 8192 * 2048 * H * (R + Pd + R) * 2
+print(json.dumps({"CEIL_2048keys_ms": ms, "TF": fl / ms / 1e9}), flush=True)
+for N in Ns:
+ T = min(8192, N); qstart = N - T; P = N // KP
+ sc = torch.randn(T, P, device=dev)
+ pos = qstart + torch.arange(T, device=dev)
+ gend = torch.arange(P, device=dev) * KP + KP - 1
+ sc = sc.masked_fill(~(gend[None] < pos[:, None]), float("-inf"))
+ sp = PK.ix_select(sc, qstart, N, NTOP, KP, True, sparse=True)
+ nkeys = float((sp.nsel.double() * KP + (pos % KP + 1).double()).sum())
+ qc = qc8[:, :T].contiguous()
+ kc = (torch.randn(N, R + Pd, device=dev) * 0.3)
+ kc16 = kc.half().contiguous()
+ res = {"N": N, "T": T, "mean_keys": nkeys / T}
+ res["hip_ms"] = tm(lambda: sp_hip.mla_sparse_hip(R, kc16, qstart, scale, sinks, sp, qc))
+ res["hip_TF"] = nkeys * H * (R + Pd + R) * 2 / res["hip_ms"] / 1e9
+ if not os.environ.get("MB_NOTRITON"):
+ res["triton_ms"] = tm(lambda: PA.mla_sparse(R, kc, qstart, scale, sinks, sp, qc))
+ print(json.dumps(res), flush=True)
+ del sc, qc, kc, kc16, sp; torch.cuda.empty_cache()
+print("MBDONE")
diff --git a/hipsp/sp_hip.py b/hipsp/sp_hip.py
new file mode 100644
index 0000000..26e3cfb
--- /dev/null
+++ b/hipsp/sp_hip.py
@@ -0,0 +1,23 @@
+"""ctypes wrapper of sp_mla.cu: sparse MLA prefill (one workgroup per query x 64 heads)."""
+import ctypes, os, torch
+_lib = None
+def lib():
+ global _lib
+ if _lib is None:
+ so = os.environ.get("SP_SO", os.path.join(os.path.dirname(os.path.abspath(__file__)), "libspmla.so"))
+ _lib = ctypes.CDLL(so); f = _lib.sp_launch; f.restype = ctypes.c_int
+ f.argtypes = [ctypes.c_void_p] * 6 + [ctypes.c_int] * 5 + [ctypes.c_float] + [ctypes.c_int] * 3 + [ctypes.c_void_p]
+ return _lib
+
+def mla_sparse_hip(R, kc16, qstart, scale, sinks, sel, qcat, fixed_tiles=0, out=None):
+ """same contract as prefill_attn.mla_sparse but kc16 must already be fp16 contiguous [N, 576]: qcat fp16 [H, T, 576] -> o [H, T, R] fp16 (saturated)"""
+ H, T, D = qcat.shape
+ N = kc16.shape[0]
+ assert R == 512 and D == 576 and kc16.shape[1] == 576 and kc16.dtype == torch.float16 and kc16.is_contiguous() and qcat.is_contiguous() and qcat.dtype == torch.float16
+ assert N == qstart + T and sel.gidx.dtype == torch.int32 and sel.nsel.dtype == torch.int32 and sel.gidx.is_contiguous()
+ o = out if out is not None else torch.empty(H, T, R, dtype=torch.float16, device=qcat.device)
+ sk = sinks.float().contiguous() if sinks is not None else None
+ r = lib().sp_launch(qcat.data_ptr(), kc16.data_ptr(), sk.data_ptr() if sk is not None else None, sel.gidx.data_ptr(), sel.nsel.data_ptr(), o.data_ptr(),
+ T, qstart, H, sel.gidx.shape[1], N, float(scale), int(bool(sel.tail)), int(sel.kpool), int(fixed_tiles), torch.cuda.current_stream().cuda_stream)
+ assert r == 0, r
+ return o
diff --git a/hipsp/sp_idx.h b/hipsp/sp_idx.h
new file mode 100644
index 0000000..09b440e
--- /dev/null
+++ b/hipsp/sp_idx.h
@@ -0,0 +1,20 @@
+// Address math of the sparse MLA gather, shared by the HIP kernel and the host guard-page test.
+// Virtual key v of query t: groups 0..ns-1 are the selected groups (gidx), then the own open group (tail keys lo_t .. pos).
+// nv = ns*KP + ntail virtual keys are valid; v >= nv is clamped to nv-1 (the row is read, its probability is forced to 0).
+#pragma once
+#ifdef __HIPCC__
+#define SP_HD __host__ __device__
+#else
+#define SP_HD
+#endif
+template <int KP>
+SP_HD inline int sp_row(int v, int nv, int ns, int lo_t, const int* gi /* ns valid entries */, int N)
+{
+ v = v < nv ? v : nv - 1;
+ const int g = v / KP, e = v % KP;
+ int row = g < ns ? gi[g] * KP + e : lo_t + e;
+ row = row < 0 ? 0 : row;
+ row = row >= N ? N - 1 : row;
+ return row;
+}
+SP_HD inline int sp_lo_t(int pos, int KP, int tail) { return tail ? pos - pos % KP : pos - ((pos + 1) % KP) + 1; }
diff --git a/hipsp/sp_mla.cu b/hipsp/sp_mla.cu
new file mode 100644
index 0000000..1e55112
--- /dev/null
+++ b/hipsp/sp_mla.cu
@@ -0,0 +1,188 @@
+// Sparse MLA prefill kernel for gfx1151 (WMMA f16, wave32). One workgroup (16 waves) = one query x 64 heads.
+// Latent rows [N, 576] (512 content + 64 rope), Q [H, T, 576], O [H, T, 512] fp16 (saturated). Visible keys = selected groups + own open group.
+// Layout: wave w = (mt = w & 3: 16 heads, qq = w >> 2: quarter). QK: S^T = K Q^T over a 144-dim slice (Q B fragments resident, 72 VGPR), partial S through LDS,
+// every wave of a head tile sums the 4 partials and runs the same online softmax (lazy rescale); PV: O^T = V^T P^T for 128 dims (acc 64 VGPR).
+// K tile (16 keys) is staged in LDS row-major (QK) and transposed with a 16-key slot permutation [evens | odds] (PV), P^T is built with one permlanex16 per 4 regs.
+#include <hip/hip_runtime.h>
+#include <stdint.h>
+#include "sp_idx.h"
+typedef __attribute__((__vector_size__(16 * sizeof(__fp16)))) __fp16 h16;
+typedef __attribute__((__vector_size__(8 * sizeof(float)))) float f8;
+#define LOG2E 1.4426950408889634f
+#define D_ 576
+#define R_ 512
+#define KPITCH 1168 // bytes per K row in LDS (73 * 16: conflict free b128 rows)
+#define VPITCH 48 // bytes per V^T row (16 keys * 2 + 16 pad)
+#define LAZY 8.0f
+
+__device__ __forceinline__ uint32_t perm16(uint32_t x) { return __builtin_amdgcn_permlanex16(x, x, 0x76543210, 0xfedcba98, false, false); }
+__device__ __forceinline__ float permf(float x) { return __builtin_bit_cast(float, perm16(__builtin_bit_cast(uint32_t, x))); }
+__device__ __forceinline__ uint32_t pk2(float a, float b)
+{
+ return (uint32_t)__builtin_bit_cast(uint16_t, (_Float16)a) | ((uint32_t)__builtin_bit_cast(uint16_t, (_Float16)b) << 16);
+}
+__device__ __forceinline__ h16 mk16(uint4 a, uint4 b) { h16 f; ((uint4*)&f)[0] = a; ((uint4*)&f)[1] = b; return f; }
+__device__ __forceinline__ _Float16 satf(float x) { return (_Float16)fminf(fmaxf(x, -65504.f), 65504.f); }
+__device__ __forceinline__ uint32_t pk2s(float a, float b)
+{
+ return (uint32_t)__builtin_bit_cast(uint16_t, satf(a)) | ((uint32_t)__builtin_bit_cast(uint16_t, satf(b)) << 16);
+}
+
+template <int KP, bool SINK>
+__global__ __launch_bounds__(512, 1) void sp_mla(const _Float16* __restrict__ Q, const _Float16* __restrict__ KC, const float* __restrict__ sink, const int* __restrict__ gidx,
+ const int* __restrict__ nsel, _Float16* __restrict__ O, int T, int qstart, int H, int GS, int N, float scale, int tail, int fixed_tiles)
+{
+ __shared__ __attribute__((aligned(16))) char Kn[16 * KPITCH];
+ __shared__ __attribute__((aligned(16))) char Vt[512 * VPITCH];
+ __shared__ __attribute__((aligned(16))) float Sp[4 * 4 * 16 * 16];
+ __shared__ int gi[512];
+ const int tid = threadIdx.x, w = tid >> 5, l = tid & 31, n = l & 15, hh = l >> 4, mt = w & 3, qq = w >> 2;
+ const int t = blockIdx.x, hg = blockIdx.y * 64;
+ const int pos = qstart + t;
+ const int ns = fixed_tiles ? 0 : min(nsel[t], min(GS, 512));
+ const int lo_t = sp_lo_t(pos, KP, tail);
+ const int ntail = pos - lo_t + 1;
+ const int nv = fixed_tiles ? fixed_tiles * 16 : ns * KP + ntail;
+ const int ntiles = (nv + 15) >> 4;
+ if (tid < ns) gi[tid] = gidx[(long)t * GS + tid];
+ const int head = hg + mt * 16 + n;
+ const long qrow = ((long)head * T + t) * D_;
+ // resident Q B fragments (both lane halves hold the full 16 dims)
+ h16 qf[9];
+#pragma unroll
+ for (int s = 0; s < 9; s++) {
+ const uint4* p = (const uint4*)(Q + qrow + 144 * qq + 16 * s);
+ qf[s] = mk16(p[0], p[1]);
+ }
+ f8 acc[8];
+#pragma unroll
+ for (int i = 0; i < 8; i++) acc[i] = (f8){0, 0, 0, 0, 0, 0, 0, 0};
+ float m = SINK ? sink[head] * LOG2E : -1e30f;
+ float ls = SINK ? (hh == 0 ? 1.f : 0.f) : 0.f;
+ const float c = scale * LOG2E;
+ // gather task: V part (dim chunk cT, group g, parity e) = 2 keys x 8 dims; rope part for tid < 128
+ const int cT = tid >> 3, tg = (tid >> 1) & 3, te = tid & 1;
+ const int rk = tid >> 3, rc = tid & 7;
+ uint4 ga, gb, gr;
+ auto gload = [&](int tau) {
+ const int v0 = tau * 16 + 4 * tg + te;
+ int r0, r1;
+ if (fixed_tiles) { r0 = v0 & 15; r1 = (v0 + 2) & 15; }
+ else { r0 = sp_row<KP>(v0, nv, ns, lo_t, gi, N); r1 = sp_row<KP>(v0 + 2, nv, ns, lo_t, gi, N); }
+ ga = *(const uint4*)(KC + (long)r0 * D_ + 8 * cT);
+ gb = *(const uint4*)(KC + (long)r1 * D_ + 8 * cT);
+ if (tid < 128) {
+ const int rr = fixed_tiles ? ((tau * 16 + rk) & 15) : sp_row<KP>(tau * 16 + rk, nv, ns, lo_t, gi, N);
+ gr = *(const uint4*)(KC + (long)rr * D_ + R_ + 8 * rc);
+ }
+ };
+ auto wK = [&]() {
+ const int k0 = 4 * tg + te;
+ *(uint4*)(Kn + k0 * KPITCH + 16 * cT) = ga;
+ *(uint4*)(Kn + (k0 + 2) * KPITCH + 16 * cT) = gb;
+ if (tid < 128) *(uint4*)(Kn + rk * KPITCH + 2 * (R_ + 8 * rc)) = gr;
+ };
+ auto wV = [&]() {
+ const uint32_t av[4] = {ga.x, ga.y, ga.z, ga.w}, bv[4] = {gb.x, gb.y, gb.z, gb.w};
+#pragma unroll
+ for (int j = 0; j < 8; j++) {
+ const uint32_t a = av[j >> 1], b = bv[j >> 1];
+ const uint32_t pr = (j & 1) ? ((a >> 16) | (b & 0xffff0000u)) : ((a & 0xffffu) | (b << 16));
+ const int d = (8 * cT + j) ^ (cT & 3);
+ *(uint32_t*)(Vt + d * VPITCH + 16 * te + 4 * tg) = pr;
+ }
+ };
+ __syncthreads();
+ if (ntiles > 0) { gload(0); wK(); wV(); }
+ __syncthreads();
+ const char* kb = Kn + n * KPITCH + 2 * 144 * qq;
+ float* spw = Sp + ((mt * 4 + qq) * 16 + hh) * 16 + n;
+ for (int tau = 0; tau < ntiles; tau++) {
+ const bool more = tau + 1 < ntiles;
+ if (more) gload(tau + 1);
+ f8 s = (f8){0, 0, 0, 0, 0, 0, 0, 0};
+#pragma unroll
+ for (int k = 0; k < 9; k++) {
+ const uint4* kp = (const uint4*)(kb + 32 * k);
+ s = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(mk16(kp[0], kp[1]), qf[k], s);
+ }
+#pragma unroll
+ for (int i = 0; i < 8; i++) spw[2 * i * 16] = s[i];
+ __syncthreads();
+ if (more) wK();
+ float sv[8];
+#pragma unroll
+ for (int i = 0; i < 8; i++) {
+ float p[4];
+#pragma unroll
+ for (int q2 = 0; q2 < 4; q2++) p[q2] = (q2 == qq) ? s[i] : Sp[(((mt * 4 + q2) * 16 + 2 * i + hh) * 16) + n];
+ sv[i] = (((p[0] + p[1]) + p[2]) + p[3]) * c;
+ }
+ float mx = -INFINITY;
+#pragma unroll
+ for (int i = 0; i < 8; i++) {
+ const bool ok = tau * 16 + 2 * i + hh < nv;
+ sv[i] = ok ? sv[i] : -INFINITY;
+ mx = fmaxf(mx, sv[i]);
+ }
+ mx = fmaxf(mx, permf(mx));
+ const bool upd = mx > m + LAZY;
+ const float mn = upd ? mx : m;
+ const float alpha = upd ? __builtin_amdgcn_exp2f(m - mn) : 1.f;
+ m = mn;
+ float ps = 0.f;
+ uint32_t pw[4];
+#pragma unroll
+ for (int i = 0; i < 8; i += 2) {
+ const float p0 = __builtin_amdgcn_exp2f(sv[i] - mn), p1 = __builtin_amdgcn_exp2f(sv[i + 1] - mn);
+ ps += p0 + p1;
+ pw[i >> 1] = pk2(p0, p1);
+ }
+ ls = ls * alpha + ps;
+ if (__any(upd)) {
+#pragma unroll
+ for (int i = 0; i < 8; i++)
+#pragma unroll
+ for (int j = 0; j < 8; j++) acc[i][j] *= alpha;
+ }
+ const h16 pb = mk16(make_uint4(pw[0], pw[1], pw[2], pw[3]), make_uint4(perm16(pw[0]), perm16(pw[1]), perm16(pw[2]), perm16(pw[3])));
+#pragma unroll
+ for (int tt = 0; tt < 8; tt++) {
+ const int d = (16 * (8 * qq + tt) + n);
+ const int pd = d ^ ((d >> 3) & 3);
+ const char* vp = Vt + pd * VPITCH;
+ const uint4 a0 = *(const uint4*)(vp + 16 * hh), a1 = *(const uint4*)(vp + 16 * (hh ^ 1));
+ acc[tt] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(mk16(a0, a1), pb, acc[tt]);
+ }
+ __syncthreads();
+ if (more) wV();
+ __syncthreads();
+ }
+ ls += permf(ls);
+ const float inv = 1.f / fmaxf(ls, 1e-30f);
+ _Float16* op = O + ((long)head * T + t) * R_ + 128 * qq + 8 * hh;
+#pragma unroll
+ for (int tt = 0; tt < 8; tt++) {
+ float a[8], b[8];
+#pragma unroll
+ for (int i = 0; i < 8; i++) { a[i] = acc[tt][i] * inv; b[i] = permf(a[i]); }
+ uint4 o;
+ if (hh == 0) o = make_uint4(pk2s(a[0], b[0]), pk2s(a[1], b[1]), pk2s(a[2], b[2]), pk2s(a[3], b[3]));
+ else o = make_uint4(pk2s(b[4], a[4]), pk2s(b[5], a[5]), pk2s(b[6], a[6]), pk2s(b[7], a[7]));
+ *(uint4*)(op + 16 * tt) = o;
+ }
+}
+
+extern "C" int sp_launch(const void* Q, const void* KC, const void* sink, const void* gidx, const void* nsel, void* O, int T, int qstart, int H, int GS, int N, float scale, int tail,
+ int KP, int fixed_tiles, void* stream)
+{
+ hipStream_t st = (hipStream_t)stream;
+ if (GS > 512 || H % 64) return -2;
+ dim3 g(T, H / 64);
+#define L(KPV, SK) sp_mla<KPV, SK><<<g, 512, 0, st>>>((const _Float16*)Q, (const _Float16*)KC, (const float*)sink, (const int*)gidx, (const int*)nsel, (_Float16*)O, T, qstart, H, GS, N, scale, tail, fixed_tiles)
+ if (KP == 4) { if (sink) L(4, true); else L(4, false); }
+ else if (KP == 2) { if (sink) L(2, true); else L(2, false); }
+ else if (KP == 8) { if (sink) L(8, true); else L(8, false); }
+ else return -1;
+ return (int)hipGetLastError();
+}
diff --git a/hipsp/test_sp_hip.py b/hipsp/test_sp_hip.py
new file mode 100644
index 0000000..ac3fc54
--- /dev/null
+++ b/hipsp/test_sp_hip.py
@@ -0,0 +1,59 @@
+"""GPU correctness: HIP sparse MLA vs fp64 dense-mask reference and vs the Triton mla_sparse. python test_sp_hip.py TREE"""
+import os, sys, types, time
+import torch
+tree = sys.argv[1]
+for n, s in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ m = types.ModuleType(n); m.__path__ = [os.path.join(tree, "exllamav3", s)]; sys.modules[n] = m
+from exllamav3.loader import prefill_kernels as PK, prefill_attn as PA
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import sp_hip
+dev = "cuda"
+H, R, Pd, KP, NTOP = 64, 512, 64, 4, 511
+scale = 1 / 16.0
+def make(N, T, tail, ntop, seed, sc_scale=1.0, sink=True):
+ g = torch.Generator(device=dev); g.manual_seed(seed)
+ qstart = N - T; P = (N + KP - 1) // KP
+ sc = torch.randn(T, P, device=dev, generator=g) * sc_scale
+ pos = qstart + torch.arange(T, device=dev)
+ gend = torch.arange(P, device=dev) * KP + KP - 1
+ sc = sc.masked_fill(~(gend[None] < pos[:, None]), float("-inf"))
+ sp = PK.ix_select(sc, qstart, N, ntop, KP, tail, want_bias=False, sparse=True)
+ qc = (torch.randn(H, T, R + Pd, device=dev, generator=g) * 0.3).half()
+ kc = torch.randn(N, R + Pd, device=dev, generator=g) * 0.3
+ sinks = torch.randn(H, device=dev, generator=g) if sink else None
+ return qstart, sp, qc, kc, sinks
+def ref64(qstart, sp, qc, kc, sinks):
+ allow = sp.to_dense()
+ H_, T = qc.shape[:2]
+ o = torch.empty(H_, T, R, dtype=torch.float64, device=dev)
+ k64 = kc.half().double()
+ for h in range(H_):
+ s = (qc[h].double() @ k64.T) * scale
+ s = s.masked_fill(~allow, float("-inf"))
+ mx = s.max(1, keepdim=True).values
+ mx = torch.where(torch.isfinite(mx), mx, torch.zeros_like(mx))
+ if sinks is not None: mx = torch.maximum(mx, sinks[h].double().expand_as(mx))
+ p = torch.exp(s - mx)
+ den = p.sum(1, keepdim=True) + (torch.exp(sinks[h].double() - mx) if sinks is not None else 0)
+ o[h] = (p @ k64[:, :R]) / den.clamp_min(1e-300)
+ return o
+ok = True
+cases = [(3000, 256, True, 511), (3000, 256, False, 511), (2999, 129, True, 511), (2998, 64, False, 40), (41, 41, True, 511), (41, 41, False, 511), (7, 7, True, 511), (1, 1, False, 511), (130, 64, True, 3),
+ (33001, 48, True, 511), (33000, 48, False, 511), (4100, 32, True, 5)]
+for (N, T, tail, ntop) in cases:
+ for sink in (True, False):
+ qstart, sp, qc, kc, sinks = make(N, T, tail, ntop, N + T, sink=sink)
+ kc16 = kc.clamp(-65504.0, 65504.0).half().contiguous()
+ o = sp_hip.mla_sparse_hip(R, kc16, qstart, scale, sinks, sp, qc).double()
+ torch.cuda.synchronize()
+ ref = ref64(qstart, sp, qc, kc, sinks)
+ err = float((o - ref).norm() / ref.norm().clamp_min(1e-30))
+ mx = float((o - ref).abs().max())
+ try:
+ tr = PA.mla_sparse(R, kc, qstart, scale, sinks, sp, qc).double(); etr = float((o - tr).norm() / tr.norm().clamp_min(1e-30)); etr0 = float((tr - ref).norm() / ref.norm().clamp_min(1e-30))
+ except Exception as e:
+ etr = etr0 = -1
+ good = err < 1.5e-3 and bool(torch.isfinite(o).all())
+ ok &= good
+ print(f"N {N} T {T} tail {int(tail)} ntop {ntop} sink {int(sink)} nsel mean {float(sp.nsel.float().mean()):.0f}: err vs fp64 {err:.2e} (max {mx:.1e}) | triton vs fp64 {etr0:.2e} | hip vs triton {etr:.2e} {'OK' if good else 'FAIL'}", flush=True)
+print("ALL OK" if ok else "FAILURES")