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
Layer split: gfx12 KDA fused-H kernel port. This works towards removing the split front's dependence on the deterministic-but-slower fla chain, hopefully giving deterministic output with better performance.
Resynth12ab491b8555
diff --git a/exllamav3/util/hip_compiler.py b/exllamav3/util/hip_compiler.pyindex caa1e0c..23d9b97 100644--- a/exllamav3/util/hip_compiler.py+++ b/exllamav3/util/hip_compiler.py@@ -129,6 +129,23 @@ def gcc_flags():return [f"--gcc-install-dir={d}"] if d else []+def compile_tail(lines, n=12):+ """Last n lines of a hipcc log, plus any error lines clang printed before them (its warning+ preamble would otherwise fill the window). Shared by the JIT loaders' failure messages."""+ if len(lines) <= n:+ return lines+ start = len(lines) - n+ hits = [i for i, l in enumerate(lines[:start]) if "error:" in l or "fatal error" in l][-n:]+ keep = sorted(set(hits) | set(range(start, len(lines))))+ out, prev = [], None+ for i in keep:+ if prev is not None and i > prev + 1:+ out.append("...")+ out.append(lines[i])+ prev = i+ return out++def describe():i = resolve()if not i["path"]:diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.pyindex d1fefc9..6483878 100644--- a/exllamav3/vendor/fla/__init__.py+++ b/exllamav3/vendor/fla/__init__.py@@ -29,7 +29,7 @@ from .kda_fused_h import chunk_kda_fwd_h_fused_HIP_FAIL = [] # first failure disables the HIP path for the process-def _hip_ok(q, k, v, beta, Akk, Aqk, h0):+def _hip_ok(q, k, v, beta, Akk=None, Aqk=None, h0=None):if _HIP_FAIL:return Falsetry:@@ -39,7 +39,7 @@ def _hip_ok(q, k, v, beta, Akk, Aqk, h0):except Exception: # noqa: BLE001return Falsebf = torch.bfloat16- ts = (q, k, v, beta, Akk, Aqk)+ ts = (q, k, v, beta) if Akk is None else (q, k, v, beta, Akk, Aqk)return (all(t.dtype == bf and t.is_contiguous() for t in ts)and (h0 is None or h0.is_contiguous()))@@ -204,14 +204,14 @@ def chunk_kda(# or if hipcc/module load fails; default 3, step 12). Chunks under 512 tokens# 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 and os.environ.get("KYOJIN_SPLIT_ACTIVE", "0") != "0" and not _fused_output_stable(q.device):- # A layer split can run KDA on a gfx12 front and a different main device in one- # process. The fused output path is not run-to-run deterministic on gfx12, and- # its gfx11.5 HIP kernel cannot be JIT-built there (kda_fused_h_hip.supported()- # declines, so _hip_ok already fell back to the Triton fuse path). Force the- # deterministic fla chain on that arch only; keep it here, split-side, until the- # gfx12 fused kernel lands.- fuse = 0+ # The fused Triton output path is nondeterministic on gfx12, so an unavailable HIP kernel+ # must fall through to the deterministic fla chain there, not to fuse_o=True. gfx11.5 keeps+ # the Triton fused fallback. Explicit EXL3_KDA_FUSE=0/2 remain manual controls.+ det_fallback = fuse == 3 and not _fused_output_stable(q.device)+ # Whether the HIP fused kernel can run. Checked before the intra pass so a det_fallback arch+ # with no HIP kernel (gfx12) goes straight to the chain instead of computing Aqk/Akk twice.+ hip_may_run = (fuse == 3 and K == 128 and v.shape[-1] == 128+ and _hip_ok(q, k, v, beta, h0 = initial_state))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@@ -223,40 +223,46 @@ def chunk_kda(return o.to(q.dtype), final_stateexcept 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)- intra = int(os.environ.get("EXL3_KDA_INTRA", "2"))- if intra == 2:- Aqk, Akk = chunk_kda_fwd_intra_pinned(q = q, k = k, gk = g, beta = beta, scale = scale, chunk_size = chunk_size)- elif intra == 1:- Aqk, Akk = chunk_kda_fwd_intra_fused(q = q, k = k, gk = g, beta = beta, scale = scale, chunk_size = chunk_size)- else:- _, _, _, _, Aqk, Akk = chunk_kda_fwd_intra(- q = q, k = k, v = v, gk = g, beta = beta, scale = scale, chunk_size = chunk_size, skip_wu = True,- )- o = None- if fuse == 3 and K == 128 and v.shape[-1] == 128 and _hip_ok(q, k, v, beta, Akk, Aqk, initial_state):- try:- from .hip.kda_fused_h_hip import chunk_kda_fwd_h_fused_hip- h, v_new, o, final_state = chunk_kda_fwd_h_fused_hip(+ # When the HIP kernel cannot run on a det_fallback arch (gfx12), skip the pinned intra pass+ # and its Aqk/Akk buffers: the chain below computes its own.+ if not det_fallback or hip_may_run:+ # 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)+ intra = int(os.environ.get("EXL3_KDA_INTRA", "2"))+ if intra == 2:+ Aqk, Akk = chunk_kda_fwd_intra_pinned(q = q, k = k, gk = g, beta = beta, scale = scale, chunk_size = chunk_size)+ elif intra == 1:+ Aqk, Akk = chunk_kda_fwd_intra_fused(q = q, k = k, gk = g, beta = beta, scale = scale, chunk_size = chunk_size)+ else:+ _, _, _, _, Aqk, Akk = chunk_kda_fwd_intra(+ q = q, k = k, v = v, gk = g, beta = beta, scale = scale, chunk_size = chunk_size, skip_wu = True,+ )+ o = None+ if hip_may_run and _hip_ok(q, k, v, beta, Akk, Aqk, initial_state):+ try:+ from .hip.kda_fused_h_hip import chunk_kda_fwd_h_fused_hip+ h, v_new, o, final_state = chunk_kda_fwd_h_fused_hip(+ q = q, k = k, v = v, gk = g, beta = beta, Akk = Akk, Aqk = Aqk, scale = scale,+ initial_state = initial_state, output_final_state = output_final_state, chunk_size = chunk_size,+ ckpt = ckpt, # mid-chunk state side-write (HIP path only; sets ckpt["ok"])+ )+ except Exception as e: # hipcc missing, compile or module-load failure+ _HIP_FAIL.append(repr(e))+ print(f"chunk_kda: HIP fused_h disabled: {e!r}", file = sys.stderr)+ o = None+ if o is not None:+ return o.to(q.dtype), final_state+ if not det_fallback:+ h, v_new, o, final_state = chunk_kda_fwd_h_fused(q = q, k = k, v = v, gk = g, beta = beta, Akk = Akk, Aqk = Aqk, scale = scale,- initial_state = initial_state, output_final_state = output_final_state, chunk_size = chunk_size,- ckpt = ckpt, # mid-chunk state side-write (HIP path only; sets ckpt["ok"])+ initial_state = initial_state, output_final_state = output_final_state,+ chunk_size = chunk_size, fuse_o = fuse >= 2,)- except Exception as e: # hipcc missing, compile or module-load failure: fall back to Triton- _HIP_FAIL.append(repr(e))- print(f"chunk_kda: HIP fused_h disabled, Triton fallback: {e!r}", file = sys.stderr)- o = None- if o is None:- h, v_new, o, final_state = chunk_kda_fwd_h_fused(- q = q, k = k, v = v, gk = g, beta = beta, Akk = Akk, Aqk = Aqk, scale = scale,- initial_state = initial_state, output_final_state = output_final_state,- chunk_size = chunk_size, fuse_o = fuse >= 2,- )- if o is None:- o = chunk_gla_fwd_o_gk(q = q, v = v_new, g = g, A = Aqk, h = h, scale = scale, chunk_size = chunk_size)- return o.to(q.dtype), final_state+ if o is None:+ o = chunk_gla_fwd_o_gk(q = q, v = v_new, g = g, A = Aqk, h = h, scale = scale, chunk_size = chunk_size)+ return o.to(q.dtype), final_state+ # gfx12 and the HIP kernel is unavailable: deterministic fla chain below.w, u, _, kg, Aqk, _ = chunk_kda_fwd_intra(q = q, k = k, v = v, gk = g, beta = beta, scale = scale, chunk_size = chunk_size,)diff --git a/exllamav3/vendor/fla/hip/gdn_hf_hip.py b/exllamav3/vendor/fla/hip/gdn_hf_hip.pyindex 12527d0..d67f316 100644--- a/exllamav3/vendor/fla/hip/gdn_hf_hip.py+++ b/exllamav3/vendor/fla/hip/gdn_hf_hip.py@@ -28,23 +28,6 @@ def _gcc_flag():return hip_compiler.gcc_flags()-def _compile_tail(lines, n=12):- """Last n lines, plus any error lines clang printed before them (its warning preamble would- otherwise fill the window)."""- if len(lines) <= n:- return lines- start = len(lines) - n- hits = [i for i, l in enumerate(lines[:start]) if "error:" in l or "fatal error" in l][-n:]- keep = sorted(set(hits) | set(range(start, len(lines))))- out, prev = [], None- for i in keep:- if prev is not None and i > prev + 1:- out.append("...")- out.append(lines[i])- prev = i- return out--def _load(device=None):dev = select_device(device)key = (dev, "")@@ -65,7 +48,7 @@ def _load(device=None):except OSError:passerr = (r.stderr or r.stdout or b"").decode(errors="replace").strip().splitlines()- raise RuntimeError(f"gdn_hf_hip: hipcc failed for {arch}:\n" + "\n".join(_compile_tail(err)))+ raise RuntimeError(f"gdn_hf_hip: hipcc failed for {arch}:\n" + "\n".join(hip_compiler.compile_tail(err)))os.replace(tmp, cache)lib = load_hip_runtime()torch.cuda.init()diff --git a/exllamav3/vendor/fla/hip/kda_fused_h.hip b/exllamav3/vendor/fla/hip/kda_fused_h.hipindex aca4924..ae2ca3b 100644--- a/exllamav3/vendor/fla/hip/kda_fused_h.hip+++ b/exllamav3/vendor/fla/hip/kda_fused_h.hip@@ -1,21 +1,43 @@-// KDA fused chunk recurrence (o fused), hand-written for gfx11.5 WMMA (Strix Halo, wave32).+// KDA fused chunk recurrence (o fused), hand-written for gfx11.5 / gfx12 WMMA (wave32).// Same math and the same rounding points as chunk_kda_fwd_kernel_h_fused (FUSE_O) in kda_fused_h.py,-// so o and the final state match it bitwise: bf16 x bf16 products truncated, casts RNE, raw v_exp_f32,+// so o and the final state match it bitwise on gfx11.5: bf16 x bf16 products truncated, casts RNE, raw v_exp_f32,// fp32 WMMA accumulation chained in the same k order, no fma contraction (build with -ffp-contract=off).+// The gfx12 path uses the same math but is not bitwise (the gfx12 bf16 WMMA fp32 accumulation order differs+// from Triton's lowering: ~4e-3 relL2 on o and the final state); it stays runtime-gated off.//// One workgroup (8 waves) per (batch, value head); K = V = 128, BT = 64. Wave i owns the state columns// h[:, 16i:16i+16] in registers (8 WMMA C tiles) and computes w[:, 16i:16i+16] and u[:, 16i:16i+16].// Per chunk: inputs -> LDS (kb^T, vb^T, Akk) -> w, u -> LDS (w, qg, kg^T, Aqk) -> o, v_new, state update.// All global loads of a chunk issue in one batch (Aqk overlaps the w / u products); 4 barriers per chunk.-// Fragment layout (gfx1151, oracle-verified in exllamav3_ext/hip/hip_mma.cuh):-// 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]+// Fragment layout (oracle-verified in exllamav3_ext/hip/hip_mma.cuh):+// gfx11.5: A/B carry all 16 k per lane; C: lane l, reg r -> C[2r + (l >> 4)][l & 15].+// gfx12: A/B carry 8 k per lane (k split across the half-waves);+// A[l & 15][8(l >> 4) + r], B[8(l >> 4) + r][l & 15], C[8(l >> 4) + r][l & 15].#include <hip/hip_runtime.h>+#include <hip/hip_bfloat16.h>#include <stdint.h>typedef short v16s __attribute__((ext_vector_type(16)));typedef float v8f __attribute__((ext_vector_type(8)));typedef uint32_t v8u __attribute__((ext_vector_type(8)));+typedef uint32_t v4u __attribute__((ext_vector_type(4)));++#if defined(__gfx1200__) || defined(__gfx1201__)+#define KDA_GFX12 1+typedef __bf16 v8b __attribute__((ext_vector_type(8)));+typedef v8b frag_ab_t;+#define KDA_WMMA(a, b, c) __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12((a), (b), (c))+// C fragment row of register r, and the tril-mask key column within a diagonal tile.+#define KDA_CROW(r) (8 * half + (r))+#define KDA_TRIL_COL(m) (8 * half + 2 * (m))+#else+#define KDA_GFX12 0+typedef v8u frag_ab_t;+#define KDA_WMMA(a, b, c) __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(__builtin_bit_cast(v16s, (a)), __builtin_bit_cast(v16s, (b)), (c))+#define KDA_CROW(r) (2 * (r) + half)+#define KDA_TRIL_COL(m) (2 * (m))+#endif#ifndef ABL#define ABL 0 // timing-only ablation bits (wrong results): 1 phase-1 loads, 2 w/u, 4 o/vn chain, 8 tril o + store, 16 state update@@ -98,18 +120,24 @@ __device__ __forceinline__ float rbf(float f) { return bf2f(f2bf(f)); }__device__ __forceinline__ uint32_t f2bf_rtz(float f) { return __float_as_uint(f) >> 16; }__device__ __forceinline__ float ex2(float x) { return __builtin_amdgcn_exp2f(x); }-__device__ __forceinline__ v8f wmma(v8u a, v8u b, v8f c)+__device__ __forceinline__ v8f wmma(frag_ab_t a, frag_ab_t b, v8f c){- return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(__builtin_bit_cast(v16s, a), __builtin_bit_cast(v16s, b), c);+ return KDA_WMMA(a, b, c);}-// 16 contiguous bf16 at base[row * ld + col] (32 B, 16 B aligned)-__device__ __forceinline__ v8u ld16(const uint16_t* base, int row, int ld, int col)+// WMMA A/B fragment at base[row * ld + col]: 16 bf16 (32 B) on gfx11.5, 8 bf16 (16 B) at+// +8 * half on gfx12 (k split across the half-waves). 16 B aligned on both.+__device__ __forceinline__ frag_ab_t ld16(const uint16_t* base, int row, int ld, int col){+#if KDA_GFX12+ const uint4 x = *(const uint4*) (base + row * ld + col + 8 * ((threadIdx.x >> 4) & 1));+ return __builtin_bit_cast(frag_ab_t, x);+#elseconst uint4* p = (const uint4*) (base + row * ld + col);uint4 x = p[0], y = p[1];v8u r = {x.x, x.y, x.z, x.w, y.x, y.y, y.z, y.w};return r;+#endif}// p must be a valid address (clamped row); zeroed after the load when !ok@@ -121,9 +149,19 @@ __device__ __forceinline__ v8u ld16g(const uint16_t* p, bool ok)return r;}-// C tile (fp32, rows 2r + half) -> B fragment of the same bf16-rounded matrix (k = row), via permlanex16.-__device__ __forceinline__ v8u c_to_b(const v8f& c, int half)+// C tile (fp32) -> B fragment of the same bf16-rounded matrix (k = row).+// gfx12: C and B share the lane<->element map, so this is a direct pack; gfx11.5 needs+// the half-wave exchange (C rows 2r + half vs B k 0..15).+__device__ __forceinline__ frag_ab_t c_to_b(const v8f& c, int half){+#if KDA_GFX12+ (void) half;+ v4u p;+ #pragma unroll+ for (int m = 0; m < 4; ++m)+ p[m] = f2bf(c[2 * m]) | (f2bf(c[2 * m + 1]) << 16);+ return __builtin_bit_cast(frag_ab_t, p);+#elseuint32_t own[4], oth[4];#pragma unrollfor (int m = 0; m < 4; ++m)@@ -140,6 +178,30 @@ __device__ __forceinline__ v8u c_to_b(const v8f& c, int half)b[d] = half ? (t | (o << 16)) : (o | (t << 16));}return b;+#endif+}++// Zero the strict upper triangle of a diagonal A tile: word m holds bf16 columns+// KDA_TRIL_COL(m) (low) and KDA_TRIL_COL(m) + 1 (high); on gfx11.5 a word is 8 words of+// 16 k, on gfx12 it is 4 words of 8 k (k split across the half-waves).+__device__ __forceinline__ void tril_mask(frag_ab_t& A, int ll, int half)+{+#if KDA_GFX12+ v4u& a = reinterpret_cast<v4u&>(A);+ #pragma unroll+ for (int m = 0; m < 4; ++m)+ {+ if (KDA_TRIL_COL(m) > ll) a[m] &= 0xffff0000u;+ if (KDA_TRIL_COL(m) + 1 > ll) a[m] &= 0x0000ffffu;+ }+#else+ #pragma unroll+ for (int m = 0; m < 8; ++m)+ {+ if (KDA_TRIL_COL(m) > ll) A[m] &= 0xffff0000u;+ if (KDA_TRIL_COL(m) + 1 > ll) A[m] &= 0x0000ffffu;+ }+#endif}#ifndef PROF@@ -163,6 +225,15 @@ __device__ uint32_t kda_prof[4096 * 9];#define CK8 0 // 1: eight side-write slots (dense prompt-tail checkpoints); implies the CK4 slots#endif+// The gfx11 store/scheduling experiments encode the gfx11 C row / o-store layout and are not+// ported; gfx12 uses the default build (CK4 / CK8 checkpoints are layout-independent and ported).+#if KDA_GFX12 && (BRL || UNI || ADR || PF || PFW)+#error "kda_fused_h.hip: BRL/UNI/ADR/PF/PFW are gfx11-only"+#endif+#if defined(STG) && KDA_GFX12+#error "kda_fused_h.hip: STG is gfx11-only"+#endif+extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(const uint16_t* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v,const float* __restrict__ gk, const uint16_t* __restrict__ beta, const uint16_t* __restrict__ Akk,@@ -241,7 +312,7 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(for (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- h[kt][r] = h0 ? h0[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] : 0.0f;+ h[kt][r] = h0 ? h0[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] : 0.0f;#if PH1constexpr int NG = 16 / PH1;@@ -416,7 +487,7 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(for (int a = 0; a < 4; ++a){const int l_ = PIN(4, ll), c_ = PIN(4, col);- v8u A[4];+ frag_ab_t A[4];#pragma unrollfor (int j = 0; j < 4; ++j)A[j] = ld16(sA, 16 * a + l_, LDT, 16 * j);@@ -429,7 +500,7 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(}#pragma unrollfor (int r = 0; r < 8; ++r)- sW[(16 * a + 2 * r + half) * LDR + col] = (uint16_t) f2bf(w[r]);+ sW[(16 * a + KDA_CROW(r)) * LDR + col] = (uint16_t) f2bf(w[r]);#pragma unrollfor (int m = 0; m < 4; ++m)up[a][m] = f2bf(u[2 * m]) | (f2bf(u[2 * m + 1]) << 16);@@ -465,7 +536,7 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(#pragma unrollfor (int kt = 0; kt < 8; ++kt){- const v8u hb = c_to_b(h[kt], half);+ const frag_ab_t hb = c_to_b(h[kt], half);const int l_ = PIN(1, ll);#pragma unrollfor (int a = 0; a < 4; ++a)@@ -481,7 +552,7 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(PT(6);// ---- v_new = u - w h; o = scale o + tril(Aqk) v_new- v8u vs[4];+ frag_ab_t vs[4];#pragma unrollfor (int a = 0; a < 4; ++a){@@ -500,19 +571,11 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(#pragma unrollfor (int j = 0; j < 4; ++j){- v8u A = {0, 0, 0, 0, 0, 0, 0, 0};+ frag_ab_t A = {0, 0, 0, 0, 0, 0, 0, 0};if (j <= a){A = ld16(sA, 16 * a + l_, LDT, 16 * j);- if (j == a)- {- #pragma unroll- for (int m = 0; m < 8; ++m)- {- if (2 * m > ll) A[m] &= 0xffff0000u;- if (2 * m + 1 > ll) A[m] &= 0x0000ffffu;- }- }+ if (j == a) tril_mask(A, ll, half);}if (!(ABL & 8)) oa[a] = wmma(A, vs[j], oa[a]);}@@ -554,7 +617,7 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(#pragma unrollfor (int r = 0; r < 8; ++r){- const int t = t0 + 16 * a + 2 * r + half;+ const int t = t0 + 16 * a + KDA_CROW(r);if (t < T) o[((bos + t) * HV + i_hv) * VD + col] = (uint16_t) f2bf(oa[a][r]);}SBAR(8);@@ -572,7 +635,7 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(const int l_ = PIN(2, ll);#pragma unrollfor (int r = 0; r < 8; ++r)- h[kt][r] *= sEgn[16 * kt + 2 * r + half];+ h[kt][r] *= sEgn[16 * kt + KDA_CROW(r)];#pragma unrollfor (int j = 0; j < 4; ++j)if (!(ABL & 16)) h[kt] = wmma(ld16(sY, 16 * kt + l_, LDT, 16 * j), vs[j], h[kt]);@@ -586,14 +649,14 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(for (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- hc[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];+ hc[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] = h[kt][r];// second checkpoint (EXL3_PF_NO_TAIL: the prompt's last full page, stashed inside the chunk)if (hc2 && i_t + 1 == ckpt_chunk2)#pragma unrollfor (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- hc2[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];+ hc2[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] = h[kt][r];#if CK4 || CK8// third and fourth checkpoints (EXL3_NC2_CKPT4: 8192-row chunks), same store as aboveif (hc3 && i_t + 1 == ckpt_chunk3)@@ -601,13 +664,13 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(for (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- hc3[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];+ hc3[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] = h[kt][r];if (hc4 && i_t + 1 == ckpt_chunk4)#pragma unrollfor (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- hc4[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];+ hc4[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] = h[kt][r];#endif#if CK8// slots five to eight (dense prompt-tail checkpoints), same store@@ -616,25 +679,25 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(for (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- hc5[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];+ hc5[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] = h[kt][r];if (hc6 && i_t + 1 == ckpt_chunk6)#pragma unrollfor (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- hc6[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];+ hc6[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] = h[kt][r];if (hc7 && i_t + 1 == ckpt_chunk7)#pragma unrollfor (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- hc7[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];+ hc7[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] = h[kt][r];if (hc8 && i_t + 1 == ckpt_chunk8)#pragma unrollfor (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- hc8[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];+ hc8[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] = h[kt][r];#endif}@@ -647,5 +710,5 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(for (int kt = 0; kt < 8; ++kt)#pragma unrollfor (int r = 0; r < 8; ++r)- ht[(int64_t) i_nh * KD * VD + (16 * kt + 2 * r + half) * VD + col] = h[kt][r];+ ht[(int64_t) i_nh * KD * VD + (16 * kt + KDA_CROW(r)) * VD + col] = h[kt][r];}diff --git a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py b/exllamav3/vendor/fla/hip/kda_fused_h_hip.pyindex 6777930..7724aee 100644--- a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py+++ b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py@@ -10,13 +10,19 @@ from exllamav3.util.hip_lib import load_hip_runtime_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kda_fused_h.hip")_state = {}+# The kernel source has a gfx12 (RDNA4) fragment path that hipcc compiles for gfx1200/gfx1201,+# but its output is not bitwise equal to the Triton fused path on gfx1201 (plan gate G2:+# o relL2 ~4.4e-3, final state relL2 ~4.0e-3 on a T=64 synthetic chunk, from the gfx12 bf16+# WMMA accumulation order). Keep the runtime gate gfx11.5-only until that is resolved; the+# gfx12 path is reachable with _compile() for compile-only checks.+_ARCHS = GFX115_ARCHSdef supported(device=None):- """kda_fused_h.hip is a gfx11.5 WMMA kernel; refuse other archs before any hipcc attempt."""+ """kda_fused_h.hip is gfx11.5-only at the gate; the gfx12 source path is not bitwise yet."""if not torch.version.hip:return False- return device_supported(device, GFX115_ARCHS)+ return device_supported(device, _ARCHS)def _hipcc():@@ -33,7 +39,14 @@ def _compile(defs, arch):if not os.path.isfile(cache):os.makedirs(os.path.dirname(cache), exist_ok=True)tmp = cache + f".{os.getpid()}.{threading.get_ident()}.tmp"- subprocess.run([_hipcc(), *flags, "-o", tmp, _SRC], check=True, capture_output=True)+ r = subprocess.run([_hipcc(), *flags, "-o", tmp, _SRC], capture_output=True)+ if r.returncode != 0:+ try:+ os.remove(tmp)+ except OSError:+ pass+ err = (r.stderr or r.stdout or b"").decode(errors="replace").strip().splitlines()+ raise RuntimeError(f"kda_fused_h_hip: hipcc failed for {arch}:\n" + "\n".join(hip_compiler.compile_tail(err)))os.replace(tmp, cache)return cache@@ -99,7 +112,9 @@ def chunk_kda_fwd_h_fused_hip(q, k, v, gk, beta, Akk, Aqk, scale, initial_state=assert q.dtype == k.dtype == v.dtype == beta.dtype == Akk.dtype == Aqk.dtype == torch.bfloat16 and gk.dtype == torch.float32for t in (q, k, v, gk, beta, Akk, Aqk):assert t.is_contiguous()- pf = os.environ.get("EXL3_KDA_PF_SPLIT", "0") if not defs else ""+ # The EXL3_KDA_PF_SPLIT fast builds encode the gfx11 C row / o-store layout; gfx12 uses the+ # default defs="" build (bitwise equal, but the port does not carry those experiments).+ pf = os.environ.get("EXL3_KDA_PF_SPLIT", "0") if not defs and device_supported(q.device, GFX115_ARCHS) else ""if pf == "2":# spill-free build (0 VGPR spills vs 462): sched barriers (SB), opaque lane# indices (OPQ), pinned WMMA accumulators (OPV), uniform o-store base (ADR), no LSR,diff --git a/tests/test_gdn_hf_cpu.py b/tests/test_gdn_hf_cpu.pyindex a6cc8a0..1196395 100644--- a/tests/test_gdn_hf_cpu.py+++ b/tests/test_gdn_hf_cpu.py@@ -1,4 +1,4 @@-"""CPU tests of the gdn_hf_hip device gate and the hipcc error tail.+"""CPU tests of the gdn_hf_hip device gate and the shared hipcc error tail.No GPU, no ROCm, no built extension (the package __init__ files are bypassed with empty namespacestubs while the module is imported, then removed)."""import importlib, sys, types@@ -18,6 +18,7 @@ for _n in _PKGS:try:gdn_hf = importlib.import_module("exllamav3.vendor.fla.hip.gdn_hf_hip")arch_list = importlib.import_module("exllamav3.util.arch_list")+ hip_compiler = importlib.import_module("exllamav3.util.hip_compiler")finally:for _n in _added:sys.modules.pop(_n, None)@@ -78,12 +79,12 @@ def test_supported_probe_failure_is_false(monkeypatch):def test_compile_tail_short_output_is_unchanged():lines = [f"line {i}" for i in range(5)]- assert gdn_hf._compile_tail(lines) == lines+ assert hip_compiler.compile_tail(lines) == linesdef test_compile_tail_keeps_an_error_before_the_tail():lines = ["warning: noise"] * 30 + ["fatal error: 'cstdlib' file not found"] + ["note: context"] * 20- tail = gdn_hf._compile_tail(lines)+ tail = hip_compiler.compile_tail(lines)assert "fatal error: 'cstdlib' file not found" in tailassert tail[-1] == lines[-1]assert "..." in taildiff --git a/tests/test_hip_compiler_cpu.py b/tests/test_hip_compiler_cpu.pyindex e425a09..3b7dc86 100644--- a/tests/test_hip_compiler_cpu.py+++ b/tests/test_hip_compiler_cpu.py@@ -177,6 +177,7 @@ def test_warning_text(env, monkeypatch):("exllamav3.modules.gr_fn.gr_mix_hip", lambda m: m.compile_hsaco()),("exllamav3.vendor.fla.hip.gdn_fused_h_hip", lambda m: m._compile("", "gfx1151")),("exllamav3.vendor.fla.hip.kda_fused_h_hip", lambda m: m._compile("", "gfx1151")),+ ("exllamav3.vendor.fla.hip.kda_fused_h_hip", lambda m: m._compile("", "gfx1201")), # compile-only gfx12 path("exllamav3.modules.ple_fn.ple_hip", lambda m: m.compile_hsaco()),])def test_cache_key_includes_compiler(env, monkeypatch, modname, call):diff --git a/tests/test_kda_fused_h_gfx12.py b/tests/test_kda_fused_h_gfx12.pynew file mode 100644index 0000000..565d5d9--- /dev/null+++ b/tests/test_kda_fused_h_gfx12.py@@ -0,0 +1,144 @@+"""gfx12 (RDNA4) parity, determinism and checkpoint tests for the fused KDA HIP state kernel.++The HIP kernel port of kda_fused_h.hip must reproduce the Triton fused path+(chunk_kda_fwd_h_fused, fuse_o=True) bitwise on gfx1200/gfx1201, including the final+state and the CK4/CK8 checkpoint side-writes. Skipped on every other device.++STATUS: the gfx12 path compiles, loads and runs, but plan gate G2 is not met. On a+T=64 synthetic chunk (H=HV=64, K=V=128, l2-normalized q/k, h0 + ht) the HIP path+differs from Triton by o relL2 4.4e-3 (max 4.9e-4) and final-state relL2 4.0e-3+(max 6.3e-3); the deltas look like a last-bit fp32 accumulation-order difference in+the gfx12 bf16 WMMA chain, not a fragment-layout error (a 16x16x16 gfx12 bf16+oracle matches D == A*B + C exactly). The runtime gate therefore stays gfx11.5-only+(kda_fused_h_hip._ARCHS); the bitwise test below is xfail until the order is matched+or the user accepts a KLD/quality bar.+"""+import pytest+import torch++pytestmark = pytest.mark.skipif(not torch.version.hip, reason="requires ROCm")++T_ALL = (513, 777, 1500, 3001, 4095)+++def _gfx12_device():+ from exllamav3.util.arch_list import device_arch+ if not torch.cuda.is_available():+ return None+ for i in range(torch.cuda.device_count()):+ try:+ if device_arch(i) in ("gfx1200", "gfx1201"):+ return i+ except Exception: # noqa: BLE001+ pass+ return None+++def dev():+ i = _gfx12_device()+ if i is None:+ pytest.skip("requires a gfx1200/gfx1201 device")+ torch.cuda.set_device(i)+ return torch.device("cuda", i)++[email protected](scope="module")+def kda():+ from exllamav3.vendor.fla import RCP_LN2+ from exllamav3.vendor.fla.cumsum import chunk_local_cumsum+ from exllamav3.vendor.fla.kda_intra_fused import chunk_kda_fwd_intra_pinned+ from exllamav3.vendor.fla import kda_fused_h as KH+ from exllamav3.vendor.fla.hip import kda_fused_h_hip as HH+ return RCP_LN2, chunk_local_cumsum, chunk_kda_fwd_intra_pinned, KH, HH+++def test_runtime_gate_stays_closed(dev, kda):+ assert kda[4].supported(dev) is False+++def _synth(dev, B, T, seed=0):+ H = HV = 64+ K = V = 128+ g = torch.Generator(device = dev).manual_seed(seed)+ r = lambda *s: torch.randn(*s, device = dev, generator = g)+ q = torch.nn.functional.normalize(r(B, T, H, K), dim = -1).bfloat16()+ k = torch.nn.functional.normalize(r(B, T, H, K), dim = -1).bfloat16()+ v = r(B, T, HV, V).bfloat16()+ g_raw = (-5.0 * torch.sigmoid(r(B, T, HV, K) - 2.0)).float()+ beta = torch.sigmoid(r(B, T, HV)).bfloat16()+ h0 = 0.1 * r(B, HV, K, V).float()+ return q, k, v, g_raw, beta, h0+++def _inputs(kda, q, k, v, g_raw, beta):+ RCP_LN2, chunk_local_cumsum, chunk_kda_fwd_intra_pinned = kda[:3]+ g = chunk_local_cumsum(g_raw, chunk_size = 64, scale = RCP_LN2)+ scale = k.shape[-1] ** -0.5+ Aqk, Akk = chunk_kda_fwd_intra_pinned(q = q, k = k, gk = g, beta = beta, scale = scale, chunk_size = 64)+ return g, scale, Aqk, Akk+++def _run_hip(kda, q, k, v, g, beta, scale, Aqk, Akk, h0, ht):+ HH = kda[4]+ o = torch.empty_like(v)+ s = k.new_empty(q.shape[0], v.shape[2], q.shape[-1], v.shape[-1], dtype = torch.float32) if ht else None+ HH.chunk_kda_fwd_h_fused_hip(q, k, v, g, beta, Akk, Aqk, scale, initial_state = h0,+ output_final_state = ht, chunk_size = 64, o = o, final_state = s)+ return o, s++[email protected](strict = False, reason = "G2: gfx12 bf16 WMMA accumulation order differs from Triton")[email protected]("T", T_ALL)[email protected]("B", (1, 2))[email protected]("use_h0", (True, False))[email protected]("store_ht", (True, False))+def test_bitwise_vs_triton(dev, kda, T, B, use_h0, store_ht):+ KH = kda[3]+ q, k, v, g_raw, beta, h0 = _synth(dev, B, T, seed = T + B)+ h0 = h0 if use_h0 else None+ g, scale, Aqk, Akk = _inputs(kda, q, k, v, g_raw, beta)++ _, _, ref_o, ref_s = KH.chunk_kda_fwd_h_fused(+ q, k, v, g, beta, Akk, Aqk, scale, initial_state = h0,+ output_final_state = store_ht, chunk_size = 64, fuse_o = True)++ o, s = _run_hip(kda, q, k, v, g, beta, scale, Aqk, Akk, h0, store_ht)+ assert torch.isfinite(o).all()+ assert torch.equal(o, ref_o)+ if store_ht:+ assert s is not None and torch.equal(s, ref_s)+ else:+ assert s is None++ o2, s2 = _run_hip(kda, q, k, v, g, beta, scale, Aqk, Akk, h0, store_ht)+ assert torch.equal(o, o2)+ if store_ht:+ assert torch.equal(s, s2)++[email protected]("chunks", [(2, 5, 8, 11), tuple(range(1, 9))], ids = ("CK4", "CK8"))+def test_checkpoint_states(dev, kda, chunks):+ HH, KH = kda[4], kda[3]+ T = 777+ q, k, v, g_raw, beta, h0 = _synth(dev, 1, T, seed = 17)+ g, scale, Aqk, Akk = _inputs(kda, q, k, v, g_raw, beta)+ # Independent oracle: the Triton fused loop's per-chunk entry state. h[:, n] (0-indexed+ # chunk n) is the state entering chunk n, exactly the state after n chunks that CK chunk n+ # side-writes. h is bf16 here, so compare with a tolerance; a wrong state-row or checkpoint+ # mapping is still O(1) off.+ href, _, _, _ = KH.chunk_kda_fwd_h_fused(+ q, k, v, g, beta, Akk, Aqk, scale, initial_state = h0,+ output_final_state = False, chunk_size = 64, fuse_o = False)+ cks = [{"s": torch.zeros(1, v.shape[2], q.shape[-1], v.shape[-1], dtype = torch.float32, device = dev),+ "chunk": n} for n in chunks]+ o = torch.empty_like(v)+ final = k.new_empty(1, v.shape[2], q.shape[-1], v.shape[-1], dtype = torch.float32)+ HH.chunk_kda_fwd_h_fused_hip(q, k, v, g, beta, Akk, Aqk, scale, initial_state = h0,+ output_final_state = True, chunk_size = 64, o = o, final_state = final, ckpt = cks)+ assert torch.isfinite(o).all() and torch.isfinite(final).all()+ for c in cks:+ assert c.get("ok") is True+ ref = href[:, c["chunk"]].float()+ torch.testing.assert_close(c["s"], ref, rtol = 5e-2, atol = 1e-2,+ msg = f"checkpoint chunk {c['chunk']} vs Triton entry state")diff --git a/tests/test_multi_device_jit.py b/tests/test_multi_device_jit.pyindex 46869b5..6b917c6 100644--- a/tests/test_multi_device_jit.py+++ b/tests/test_multi_device_jit.py@@ -4,8 +4,9 @@ The engine can run the same kernel on two GPUs from one process. A loader that adevice 0's arch or keeps one handle per defines string runs the wrong code object on theother card. The CDC tests below fake the compiler and the HIP runtime, so the state-keyand arch-selection invariant is checked without a GPU; the hardware tests load every-loader on both devices. gdn_hf, gdn_fused, kda_fused and kda_hf are gfx11.5-only: on-gfx1201 their supported() gate must refuse before any hipcc attempt.+loader on both devices. gdn_hf, gdn_fused, kda_fused and kda_hf are gfx11.5-only at the+gate: on gfx1201 their supported() gate must refuse before any hipcc attempt. (The+kda_fused source has a gfx12 path, but it is not bitwise yet and stays gated off.)"""import ctypesimport importlib