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.

GLM KDA prefill: 16-row WY chunk kernel (opt-in EXL3_KDA_HF)

YanissAmz07d5eb5dbfd4
diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.py
index 03eaf3d..9c1eaf6 100644
--- a/exllamav3/vendor/fla/__init__.py
+++ b/exllamav3/vendor/fla/__init__.py
@@ -174,6 +174,16 @@ def chunk_kda(
# keep the fla chain: the one-program-per-head fused loop is ~0.14 ms slower there (T=255 sweep).
fuse = int(os.environ.get("EXL3_KDA_FUSE", "3")) if K <= 128 and chunk_size == 64 and T >= 512 else 0
if fuse:
+ # EXL3_KDA_HF=1 (default off, read per call): 16-row-chunk WY kernel (hip/kda_hf.hip, derived from hipfire's GDN kernel,
+ # diagonal blocks computed in the kernel); replaces the intra kernels + kda_fused_h_o, incl. the prefix-cache
+ # checkpoint side-write. Not bitwise (f16 / bf16 WMMA operands)
+ from .hip.kda_hf_hip import kda_hf_ok, chunk_kda_hf
+ if kda_hf_ok(q, k, v, g, beta, initial_state, chunk_size):
+ try:
+ o, final_state = chunk_kda_hf(q, k, v, g, beta, scale, initial_state, output_final_state, ckpt = ckpt)
+ return o.to(q.dtype), final_state
+ except Exception as e:
+ print(f" -- EXL3_KDA_HF failed, Triton/HIP chain for the rest of the process: {e!r}", flush = True)
# EXL3_KDA_INTRA (read per call): 2 = fla's two intra kernels with pinned gfx1151 configs (bitwise
# equal to 0), 1 = one-kernel intra (diagonal blocks computed in the inter/solve program, no
# token_parallel pass, no Akkd round trip; ties 2 on gfx1151, not bitwise), 0 = fla autotune. Default 2 (step 11)
diff --git a/exllamav3/vendor/fla/hip/kda_hf.hip b/exllamav3/vendor/fla/hip/kda_hf.hip
new file mode 100644
index 0000000..fde9140
--- /dev/null
+++ b/exllamav3/vendor/fla/hip/kda_hf.hip
@@ -0,0 +1,290 @@
+// Derived from hipfire (https://github.com/warpfront/hipfire, v0.4.2.1-13-gbfb90b9, kernels/src/gated_delta_chunk_wmma.gfx1151.hip),
+// Copyright the hipfire authors, licensed under the Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0).
+// Changes for exllamav3 (EXL3_KDA_HF): Kimi Delta Attention (per-channel decay) instead of the scalar-gate GDN recurrence.
+// The 16x16 intra-chunk blocks are computed in the kernel (bf16 WMMA on q, k scaled by 2^{+-(g - g_m)} around the chunk's middle
+// row m; KHF_TP=1 instead reads them from fla's token_parallel kernel), the decay factors are per channel, raw o rows out.
+// SPDX-License-Identifier: Apache-2.0
+
+#include <hip/hip_runtime.h>
+#include <hip/hip_bfloat16.h>
+
+// KDA prefill recurrence on gfx11 WMMA, 16-row chunks. Per value head (block) and chunk, G the 16-row-local cumulative log2
+// decay (a vector per row, G = g - g[c0 - 1] from the caller's 64-row-local cumsum), GL = G of the chunk's last row:
+// L = -Akk (strictly lower, beta_i sum_c k_i k_j 2^{G_i - G_j}), T = (I - L)^-1 = (I + L)(I + L^2)(I + L^4)(I + L^8)
+// Vnew = T (v beta - ((k beta) * 2^G) S)
+// O = ((q scale) * 2^G) S + Aqk Vnew (Aqk = scale sum_c q_i k_j 2^{G_i - G_j}, j <= i)
+// S = diag(2^GL) S + (k * 2^{GL - G})^T Vnew
+// Every exponent is <= 0 (no overflow). Products are F16 WMMA with F32 accumulation (S, T, Vnew and the decayed operands round
+// to F16): not bitwise equal to the 64-row chain, quality-gated (KLD).
+// Wave w owns value columns 16w .. 16w + 15 of S as eight C-layout tiles in registers. Grid [value_heads], block 256, K = V = 128.
+// Inputs (B = 1, contiguous): q, k [rows, H, 128] bf16; v [rows, HV, 128] bf16; g [rows, HV, 128] fp32 (64-row-local log2 cumsum);
+// beta [rows, HV] bf16; akk [rows, HV, 16] fp32 (row i, column j - 16 (i / 16), valid for j < i); aqk [rows, HV, 64] bf16 (column
+// j % 64, valid for j <= i in the same 16-row block). state [HV, 128, 128] fp32 in/out. output [rows, HV, 128] bf16.
+
+typedef _Float16 __attribute__((ext_vector_type(16))) gc_h16;
+typedef float __attribute__((ext_vector_type(8))) gc_f8;
+typedef unsigned int __attribute__((ext_vector_type(8))) gc_u8;
+typedef _Float16 __attribute__((ext_vector_type(2))) gc_h2;
+// __syncthreads also waits for every outstanding global access (WGP-mode
+// workgroup fence), which would drain the prefetch.
+#define GC_BARRIER() asm volatile("s_waitcnt lgkmcnt(0)\n\ts_barrier" ::: "memory")
+// Wave-private LDS handoff: order this wave's stores before its loads.
+#define GC_WAVE_SYNC() do { __builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront"); __builtin_amdgcn_wave_barrier(); __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); } while (0)
+#define GC_WMMA(a, b, c) __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c)
+typedef short __attribute__((ext_vector_type(16))) gc_s16;
+#define GC_WMMA_BF(a, b, c) __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c)
+static __device__ __forceinline__ unsigned int gc_pack(float a, float b) {
+ return __builtin_bit_cast(unsigned int, gc_h2{(_Float16)a, (_Float16)b});
+}
+// C-layout tile (lane: column l16, rows 2r + hi) -> the B operand of that
+// matrix (lane: column l16, all 16 rows), by swapping half-waves.
+static __device__ __forceinline__ gc_h16 gc_c_to_b(const gc_f8 c, int hi) {
+ gc_u8 out;
+#pragma unroll
+ for (int p = 0; p < 4; ++p) {
+ const unsigned int own = gc_pack(c[2 * p], c[2 * p + 1]);
+ const unsigned int oth = __builtin_amdgcn_permlanex16(own, own, 0x76543210u, 0xfedcba98u, false, false);
+ const unsigned int a = hi ? oth : own, b = hi ? own : oth;
+ out[2 * p] = __builtin_amdgcn_perm(b, a, 0x05040100u);
+ out[2 * p + 1] = __builtin_amdgcn_perm(b, a, 0x07060302u);
+ }
+ return __builtin_bit_cast(gc_h16, out);
+}
+static __device__ __forceinline__ float bf_lo(unsigned int w) { return __uint_as_float(w << 16); }
+static __device__ __forceinline__ float bf_hi(unsigned int w) { return __uint_as_float(w & 0xFFFF0000u); }
+
+__launch_bounds__(256)
+extern "C" __global__ void kda_chunk16_wmma(
+ const unsigned short* __restrict__ q, const unsigned short* __restrict__ k, const unsigned short* __restrict__ v,
+ const float* __restrict__ g, const unsigned short* __restrict__ beta, const float* __restrict__ akk,
+ const unsigned short* __restrict__ aqk, float* __restrict__ state, unsigned short* __restrict__ output,
+ int rows, int key_heads, int value_heads, float query_scale,
+ float* __restrict__ ck0, int ck_row0, float* __restrict__ ck1, int ck_row1) { // state entering row ck_row* (multiple of 16), or -1
+ const int vh = blockIdx.x;
+ const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4;
+ const int kh = vh / (value_heads / key_heads);
+ const size_t state_base = (size_t)vh * 128 * 128;
+ __shared__ __align__(16) _Float16 q_s[16][136]; // q scale 2^G rows
+ __shared__ __align__(16) _Float16 kb_s[16][136]; // k beta 2^G rows
+ __shared__ __align__(16) _Float16 kdT[128][16]; // (k 2^{GL-G})^T
+ __shared__ float vb_s[16][132]; // v beta rows (F32)
+ __shared__ float l_s[16][16]; // Akk diagonal block (masked j < i)
+ __shared__ __align__(16) _Float16 t_s[16][16];
+ __shared__ __align__(16) _Float16 p_s[16][16]; // Aqk diagonal block (masked j <= i)
+ __shared__ float gl_s[128], egl_s[128]; // GL, 2^GL per key channel
+ __shared__ __align__(16) unsigned short out_s[16][136];
+#ifndef KHF_TP // diagonal blocks in-kernel: bf16 WMMA on operands scaled around the chunk's middle row m,
+ // |g_i - g_m| <= 8 steps x 7.22 (gate lower bound -5 nat) < 58 -> 2^{+-58} fits bf16 (and fp32); rows >= nn are zero
+ __shared__ __align__(16) unsigned short qg_s[16][136], kg_s[16][136], ki_s[16][136]; // q 2^{g-gm}, k 2^{g-gm}, k 2^{gm-g}
+ __shared__ float gm_s[128], bt_s[16];
+#endif
+ const int dv0 = wave * 16;
+ gc_f8 S[8];
+#pragma unroll
+ for (int t = 0; t < 8; ++t)
+#pragma unroll
+ for (int r = 0; r < 8; ++r)
+ S[t][r] = state[state_base + (size_t)(16 * t + 2 * r + hi) * 128 + dv0 + l16];
+ const int si = tid & 15, sd = (tid >> 4) * 8; // row / 8 channels of the per-row prep
+ const int ai = tid >> 4, aj = tid & 15; // element of the 16x16 blocks
+ // Raw prefetch registers, widened where used so the loads stay in flight.
+ uint4 pk, pq, pv; float4 pg0, pg1, pp0, pp1; unsigned short pb, paq; float pa;
+ auto fetch = [&](int c0) {
+ const int nn = min(16, rows - c0);
+ pk = make_uint4(0, 0, 0, 0); pq = pk; pv = pk;
+ pg0 = make_float4(0.f, 0.f, 0.f, 0.f); pg1 = pg0; pp0 = pg0; pp1 = pg0; pb = 0; paq = 0; pa = 0.f;
+ if (si < nn) {
+ const size_t bq = ((size_t)(c0 + si) * key_heads + kh) * 128 + sd;
+ const size_t bv = ((size_t)(c0 + si) * value_heads + vh) * 128 + sd;
+ pk = *(const uint4*)(k + bq);
+ pq = *(const uint4*)(q + bq);
+ pv = *(const uint4*)(v + bv);
+ pg0 = *(const float4*)(g + bv); pg1 = *(const float4*)(g + bv + 4);
+ if (c0 & 63) {
+ const size_t bp = ((size_t)(c0 - 1) * value_heads + vh) * 128 + sd;
+ pp0 = *(const float4*)(g + bp); pp1 = *(const float4*)(g + bp + 4);
+ }
+ pb = beta[(size_t)(c0 + si) * value_heads + vh];
+ }
+#ifdef KHF_TP
+ if (ai < nn) {
+ const size_t r = (size_t)(c0 + ai) * value_heads + vh;
+ if (aj < ai) pa = akk[r * 16 + aj];
+ if (aj <= ai) paq = aqk[r * 64 + (c0 & 63) + aj];
+ }
+#endif
+ };
+ fetch(0);
+ for (int t0 = 0; t0 < rows; t0 += 16) {
+ const int nn = min(16, rows - t0);
+ float kf[8], gf[8], qf[8], gr[8];
+ {
+ const unsigned int kw[4] = {pk.x, pk.y, pk.z, pk.w}, qw[4] = {pq.x, pq.y, pq.z, pq.w}, vw[4] = {pv.x, pv.y, pv.z, pv.w};
+ const float ga[8] = {pg0.x, pg0.y, pg0.z, pg0.w, pg1.x, pg1.y, pg1.z, pg1.w};
+ const float gp[8] = {pp0.x, pp0.y, pp0.z, pp0.w, pp1.x, pp1.y, pp1.z, pp1.w};
+ const float b = __uint_as_float((unsigned int)pb << 16);
+ float vf[8], eg[8];
+#pragma unroll
+ for (int h = 0; h < 4; ++h) {
+ kf[2 * h] = bf_lo(kw[h]); kf[2 * h + 1] = bf_hi(kw[h]);
+ qf[2 * h] = bf_lo(qw[h]); qf[2 * h + 1] = bf_hi(qw[h]);
+ vf[2 * h] = bf_lo(vw[h]); vf[2 * h + 1] = bf_hi(vw[h]);
+ }
+#pragma unroll
+ for (int h = 0; h < 8; ++h) {
+ gr[h] = ga[h];
+ gf[h] = ga[h] - gp[h];
+ eg[h] = exp2f(gf[h]);
+ vb_s[si][sd + h] = vf[h] * b;
+ }
+#pragma unroll
+ for (int h = 0; h < 4; ++h) {
+ *(unsigned int*)&q_s[si][sd + 2 * h] = gc_pack(qf[2 * h] * query_scale * eg[2 * h], qf[2 * h + 1] * query_scale * eg[2 * h + 1]);
+ *(unsigned int*)&kb_s[si][sd + 2 * h] = gc_pack(kf[2 * h] * b * eg[2 * h], kf[2 * h + 1] * b * eg[2 * h + 1]);
+ }
+ if (si == nn - 1)
+#pragma unroll
+ for (int h = 0; h < 8; ++h) gl_s[sd + h] = gf[h];
+#ifndef KHF_TP
+ if (si == min(7, nn - 1))
+#pragma unroll
+ for (int h = 0; h < 8; ++h) gm_s[sd + h] = gr[h];
+ if (sd == 0) bt_s[si] = b;
+#else
+ l_s[ai][aj] = pa;
+ p_s[ai][aj] = (_Float16)__uint_as_float((unsigned int)paq << 16);
+#endif
+ }
+ GC_BARRIER();
+ {
+#pragma unroll
+ for (int h = 0; h < 8; ++h) kdT[sd + h][si] = (_Float16)(kf[h] * exp2f(gl_s[sd + h] - gf[h]));
+ if (tid < 128) egl_s[tid] = exp2f(gl_s[tid]);
+#ifndef KHF_TP
+ unsigned int wq[4], wk[4], wi[4];
+#pragma unroll
+ for (int h = 0; h < 4; ++h) {
+ float a2[2], b2[2], c2[2];
+#pragma unroll
+ for (int u = 0; u < 2; ++u) {
+ // clamp: overflow guard only, never reached under GLM's gate bound (|e| < 58); a gate-less KDA model with
+ // per-step decay below ~-12 log2 would get inexact (not inf) diagonal terms
+ const float e = si < nn ? fminf(fmaxf(gr[2 * h + u] - gm_s[sd + 2 * h + u], -100.f), 100.f) : 0.f;
+ const float up = exp2f(e), dn = exp2f(-e);
+ a2[u] = qf[2 * h + u] * up; b2[u] = kf[2 * h + u] * up; c2[u] = kf[2 * h + u] * dn;
+ }
+ wq[h] = __builtin_bit_cast(unsigned short, (hip_bfloat16)a2[0]) | ((unsigned int)__builtin_bit_cast(unsigned short, (hip_bfloat16)a2[1]) << 16);
+ wk[h] = __builtin_bit_cast(unsigned short, (hip_bfloat16)b2[0]) | ((unsigned int)__builtin_bit_cast(unsigned short, (hip_bfloat16)b2[1]) << 16);
+ wi[h] = __builtin_bit_cast(unsigned short, (hip_bfloat16)c2[0]) | ((unsigned int)__builtin_bit_cast(unsigned short, (hip_bfloat16)c2[1]) << 16);
+ }
+ *(uint4*)&qg_s[si][sd] = make_uint4(wq[0], wq[1], wq[2], wq[3]);
+ *(uint4*)&kg_s[si][sd] = make_uint4(wk[0], wk[1], wk[2], wk[3]);
+ *(uint4*)&ki_s[si][sd] = make_uint4(wi[0], wi[1], wi[2], wi[3]);
+#endif
+ }
+ if (t0 + 16 < rows) fetch(t0 + 16);
+ GC_BARRIER();
+ if (wave == 0) {
+ // L strictly lower; T = (I - L)^-1 = (I + L)(I + L^2)(I + L^4)(I + L^8).
+ gc_f8 T, P;
+#ifndef KHF_TP
+ gc_f8 c = {0, 0, 0, 0, 0, 0, 0, 0};
+#pragma unroll
+ for (int s = 0; s < 8; ++s)
+ c = GC_WMMA_BF(*(const gc_s16*)&kg_s[l16][16 * s], *(const gc_s16*)&ki_s[l16][16 * s], c);
+#endif
+#pragma unroll
+ for (int r = 0; r < 8; ++r) {
+ const int i = 2 * r + hi, j = l16;
+#ifndef KHF_TP
+ P[r] = j < i ? -bt_s[i] * c[r] : 0.f;
+#else
+ P[r] = -l_s[i][j];
+#endif
+ T[r] = P[r] + (i == j ? 1.f : 0.f);
+ }
+#pragma unroll
+ for (int s = 0; s < 3; ++s) {
+ // P as A: rows via LDS (t_s scratch), as B: half-wave swap.
+#pragma unroll
+ for (int r = 0; r < 8; ++r) t_s[2 * r + hi][l16] = (_Float16)P[r];
+ GC_WAVE_SYNC();
+ const gc_h16 pa_ = *(const gc_h16*)&t_s[l16][0];
+ const gc_h16 pbv = gc_c_to_b(P, hi);
+ GC_WAVE_SYNC();
+#pragma unroll
+ for (int r = 0; r < 8; ++r) t_s[2 * r + hi][l16] = (_Float16)T[r];
+ GC_WAVE_SYNC();
+ const gc_h16 ta = *(const gc_h16*)&t_s[l16][0];
+ gc_f8 P2 = {0, 0, 0, 0, 0, 0, 0, 0};
+ P2 = GC_WMMA(pa_, pbv, P2);
+ T = GC_WMMA(ta, gc_c_to_b(P2, hi), T);
+ P = P2;
+ GC_WAVE_SYNC();
+ }
+#pragma unroll
+ for (int r = 0; r < 8; ++r) t_s[2 * r + hi][l16] = (_Float16)T[r];
+ }
+#ifndef KHF_TP
+ else if (wave == 1) {
+ gc_f8 c = {0, 0, 0, 0, 0, 0, 0, 0};
+#pragma unroll
+ for (int s = 0; s < 8; ++s)
+ c = GC_WMMA_BF(*(const gc_s16*)&qg_s[l16][16 * s], *(const gc_s16*)&ki_s[l16][16 * s], c);
+#pragma unroll
+ for (int r = 0; r < 8; ++r) {
+ const int i = 2 * r + hi, j = l16;
+ p_s[i][j] = (_Float16)(j <= i ? query_scale * c[r] : 0.f);
+ }
+ }
+#endif
+ // K' = (k beta 2^G) S and O_inter = (q scale 2^G) S on this wave's slice (S as B from registers).
+ gc_f8 Ks = {0, 0, 0, 0, 0, 0, 0, 0}, Oi = {0, 0, 0, 0, 0, 0, 0, 0};
+#pragma unroll
+ for (int t = 0; t < 8; ++t) {
+ const gc_h16 sb = gc_c_to_b(S[t], hi);
+ Ks = GC_WMMA(*(const gc_h16*)&kb_s[l16][16 * t], sb, Ks);
+ Oi = GC_WMMA(*(const gc_h16*)&q_s[l16][16 * t], sb, Oi);
+ }
+ gc_f8 Dm;
+#pragma unroll
+ for (int r = 0; r < 8; ++r) Dm[r] = vb_s[2 * r + hi][dv0 + l16] - Ks[r];
+ GC_BARRIER(); // T ready
+ gc_f8 Vn = {0, 0, 0, 0, 0, 0, 0, 0};
+ Vn = GC_WMMA(*(const gc_h16*)&t_s[l16][0], gc_c_to_b(Dm, hi), Vn);
+ const gc_h16 vb = gc_c_to_b(Vn, hi);
+ gc_f8 O = Oi;
+ O = GC_WMMA(*(const gc_h16*)&p_s[l16][0], vb, O);
+#pragma unroll
+ for (int r = 0; r < 8; ++r)
+ out_s[2 * r + hi][dv0 + l16] = __builtin_bit_cast(unsigned short, (hip_bfloat16)O[r]);
+#pragma unroll
+ for (int t = 0; t < 8; ++t) {
+#pragma unroll
+ for (int r = 0; r < 8; ++r) S[t][r] *= egl_s[16 * t + 2 * r + hi];
+ S[t] = GC_WMMA(*(const gc_h16*)&kdT[16 * t + l16][0], vb, S[t]);
+ }
+ GC_BARRIER(); // chunk inputs consumed; out_s complete
+ if (t0 + 16 == ck_row0 || t0 + 16 == ck_row1) { // prefix-cache checkpoint: S after this chunk = state entering row t0 + 16
+ float* ck = t0 + 16 == ck_row0 ? ck0 : ck1;
+#pragma unroll
+ for (int t = 0; t < 8; ++t)
+#pragma unroll
+ for (int r = 0; r < 8; ++r)
+ ck[state_base + (size_t)(16 * t + 2 * r + hi) * 128 + dv0 + l16] = S[t][r];
+ }
+ { // o rows (BF16 bits) -> output [rows, value_heads * 128]
+#pragma unroll
+ for (int i = 0; i < 8; ++i) {
+ const int e = tid + 256 * i, r = e >> 7, c = e & 127;
+ if (r < nn) output[((size_t)(t0 + r) * value_heads + vh) * 128 + c] = out_s[r][c];
+ }
+ GC_BARRIER(); // out_s is rewritten by the next chunk
+ }
+ }
+#pragma unroll
+ for (int t = 0; t < 8; ++t)
+#pragma unroll
+ for (int r = 0; r < 8; ++r)
+ state[state_base + (size_t)(16 * t + 2 * r + hi) * 128 + dv0 + l16] = S[t][r];
+}
diff --git a/exllamav3/vendor/fla/hip/kda_hf_hip.py b/exllamav3/vendor/fla/hip/kda_hf_hip.py
new file mode 100644
index 0000000..1e59cdf
--- /dev/null
+++ b/exllamav3/vendor/fla/hip/kda_hf_hip.py
@@ -0,0 +1,104 @@
+# EXL3_KDA_HF (default off): GLM KDA prefill recurrence with 16-row WY chunks (kda_hf.hip, derived from hipfire's GDN kernel,
+# Apache-2.0). One kernel per layer (diagonal 16x16 blocks in-kernel) replaces token_parallel + kda_inter_off + inter_merge +
+# kda_fused_h_o. F16 WMMA operands with fp32 accumulation: NOT bitwise equal to the 64-row
+# chain; quality-gated (KLD). Compiled with the ROCm SDK hipcc on first use (cached by source hash), launched on torch's stream.
+import ctypes, hashlib, os, subprocess
+import torch
+import triton
+from exllamav3.util import hip_compiler
+from exllamav3.util.hip_lib import load_hip_runtime
+
+_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kda_hf.hip")
+_state = {}
+
+
+def _load(defs=""):
+ # defs: extra -D defines (experiments only, e.g. "KHF_TP=1"); one module per defines string
+ if ("fn", defs) in _state:
+ return _state["fn", defs]
+ arch = torch.cuda.get_device_properties(0).gcnArchName.split(":")[0]
+ src = open(_SRC, "rb").read()
+ flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off"] + [f"-D{x}" for x in defs.split()]
+ 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}")
+ 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"kda_hf_{arch}_{tag}.hsaco")
+ if not os.path.isfile(cache):
+ os.makedirs(os.path.dirname(cache), exist_ok=True)
+ tmp = cache + f".{os.getpid()}.tmp"
+ subprocess.run([hip_compiler.hipcc(), *flags, "-o", tmp, _SRC], check=True, capture_output=True)
+ os.replace(tmp, cache)
+ lib = load_hip_runtime()
+ torch.cuda.init()
+ mod, fn = ctypes.c_void_p(), ctypes.c_void_p()
+ if lib.hipModuleLoad(ctypes.byref(mod), cache.encode()) != 0:
+ raise RuntimeError("kda_hf_hip: hipModuleLoad failed")
+ if lib.hipModuleGetFunction(ctypes.byref(fn), mod, b"kda_chunk16_wmma") != 0:
+ raise RuntimeError("kda_hf_hip: hipModuleGetFunction failed")
+ lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
+ _state["lib"] = lib
+ _state["fn", defs] = fn
+ _state["mod", defs] = mod
+ return fn
+
+
+def kda_hf_ok(q, k, v, g, beta, initial_state, chunk_size):
+ """q, k [1, T, H, 128] bf16 (l2-normalized), v [1, T, HV, 128] bf16, g [1, T, HV, 128] fp32 = 64-row-local log2 cumsum,
+ beta [1, T, HV] bf16, all contiguous."""
+ if os.environ.get("EXL3_KDA_HF", "0") != "1" or _state.get("fail"):
+ return False
+ B, T, H, K = q.shape
+ HV, V = v.shape[2], v.shape[3]
+ bf = torch.bfloat16
+ return (B == 1 and K == 128 and V == 128 and chunk_size == 64 and HV % H == 0 and k.shape == q.shape
+ and q.dtype == k.dtype == v.dtype == beta.dtype == bf and g.dtype == torch.float32 and g.shape == (1, T, HV, K)
+ and beta.shape == (1, T, HV) and all(t.is_contiguous() for t in (q, k, v, g, beta))
+ and (initial_state is None or (initial_state.dtype == torch.float32 and initial_state.shape == (1, HV, K, V))))
+
+
+def chunk_kda_hf(q, k, v, g, beta, scale, initial_state, output_final_state, ckpt=None, defs=""):
+ """Returns (o [1, T, HV, 128] bf16, final_state or None). ckpt: None, a dict or a list of <= 2 dicts {"s": fp32 [1, HV, K, V]
+ contiguous, "chunk": n} (kda_fused_h_hip contract): the state after row 64 n is written to ck["s"] and ck["ok"] set."""
+ try:
+ fn = _load(defs)
+ except Exception:
+ _state["fail"] = True # no hipcc / no module: the Triton/HIP chain for the rest of the process
+ raise
+ from ..kda_chunk_intra_token_parallel import chunk_kda_fwd_kernel_intra_token_parallel as _tp
+ _, T, H, K = q.shape
+ HV = v.shape[2]
+ # diagonal 16x16 blocks, launched as chunk_kda_fwd_intra_pinned does (BH 16, 16 warps): Aqk [T, HV, 64] (columns j % 64),
+ # Akkd [T, HV, 16] fp32; only j <= i (Aqk) / j < i (Akkd) entries are written and read
+ Aqk = Akkd = None
+ if "KHF_TP" in defs:
+ Aqk = torch.empty(1, T, HV, 64, device=q.device, dtype=q.dtype)
+ Akkd = torch.empty(1, T, HV, 16, device=q.device, dtype=torch.float32)
+ if "KHF_TP" in defs: # timing/accuracy variant: diagonal blocks from token_parallel (default: computed in the kernel)
+ _tp.fn.fn[(T, triton.cdiv(HV, 16))](q, k, g, beta, Aqk, Akkd, scale, None, 1, T, H=H, HV=HV, K=K, BT=64,
+ BC=16, BH=16, IS_VARLEN=False, num_warps=16, num_stages=1)
+ state = (torch.zeros(1, HV, K, K, device=q.device, dtype=torch.float32) if initial_state is None
+ else initial_state.contiguous().clone()) # the kernel reads the entry state and writes the final one in place
+ o = torch.empty(1, T, HV, 128, device=q.device, dtype=torch.bfloat16)
+ P = ctypes.c_void_p
+ args = [P(q.data_ptr()), P(k.data_ptr()), P(v.data_ptr()), P(g.data_ptr()), P(beta.data_ptr()), P(0 if Akkd is None else Akkd.data_ptr()),
+ P(0 if Aqk is None else Aqk.data_ptr()), P(state.data_ptr()), P(o.data_ptr()), ctypes.c_int(T), ctypes.c_int(H), ctypes.c_int(HV),
+ ctypes.c_float(scale)]
+ cks = [] if ckpt is None else (list(ckpt) if isinstance(ckpt, (list, tuple)) else [ckpt])
+ cks = [c for c in cks if 0 < 64 * c["chunk"] <= T]
+ assert len(cks) <= 2
+ for c in cks:
+ assert c["s"].dtype == torch.float32 and c["s"].is_contiguous() and c["s"].shape == (1, HV, K, K)
+ for i in range(2):
+ c = cks[i] if i < len(cks) else None
+ args += [P(0 if c is None else c["s"].data_ptr()), ctypes.c_int(-1 if c is None else 64 * c["chunk"])]
+ params = (ctypes.c_void_p * len(args))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in args])
+ stream = torch.cuda.current_stream().cuda_stream
+ r = _state["lib"].hipModuleLaunchKernel(fn, HV, 1, 1, 256, 1, 1, 0, stream, params, None)
+ if r != 0:
+ _state["fail"] = True
+ raise RuntimeError(f"kda_hf_hip: launch failed ({r})")
+ for c in cks:
+ c["ok"] = True
+ _state["calls"] = _state.get("calls", 0) + 1
+ return o, (state if output_final_state else None)