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
gfx12: enable the fused KDA state kernel (bitwise, deterministic). Bonus gfx1151 improvements. (#225)
resyntheee77f7ab16e
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 8d99c74..2f7234a 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()))@@ -222,14 +222,17 @@ 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.+ # Off HIP (CUDA, unknown arch) the default keeps the previous rule: the deterministic chain only+ # under a layer split (KYOJIN_SPLIT_ACTIVE), the Triton fused path otherwise.+ det_fallback = (fuse == 3 and not _fused_output_stable(q.device)+ and (bool(torch.version.hip) or os.environ.get("KYOJIN_SPLIT_ACTIVE", "0") != "0"))+ # 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@@ -241,40 +244,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 7e80c13..be8250e 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, blocked=False):dev = select_device(device)key = (dev, "blocked" if blocked else "")@@ -65,7 +48,7 @@ def _load(device=None, blocked=False):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..cbfe220 100644--- a/exllamav3/vendor/fla/hip/kda_fused_h.hip+++ b/exllamav3/vendor/fla/hip/kda_fused_h.hip@@ -1,21 +1,42 @@-// 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,-// fp32 WMMA accumulation chained in the same k order, no fma contraction (build with -ffp-contract=off).+// so o and the final state match it bitwise on gfx11.5 and gfx12: bf16 products round RNE, 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 fragment path uses 8 bf16 per lane and direct C->B packing.//// 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@@ -93,23 +114,36 @@ __device__ __forceinline__ uint32_t f2bf(float f)}__device__ __forceinline__ float bf2f(uint32_t b) { return __uint_as_float(b << 16); }__device__ __forceinline__ float rbf(float f) { return bf2f(f2bf(f)); }-// Triton rounds explicit .to(bf16) casts to nearest even but truncates the result of bf16 x bf16 arithmetic-// (k * beta, v * beta); oracle-checked against the Triton kernel on a captured GLM chunk.+// Triton rounds explicit .to(bf16) casts to nearest even. Its bf16 x bf16 arithmetic (k * beta, v * beta) is+// truncated (RTZ) on gfx11.5 and nearest even on gfx12 (oracle-checked on the box), so the multiply site is arch-specific.__device__ __forceinline__ uint32_t f2bf_rtz(float f) { return __float_as_uint(f) >> 16; }+__device__ __forceinline__ uint32_t f2bf_mul(float f) {+#if KDA_GFX12+ return f2bf(f);+#else+ return f2bf_rtz(f);+#endif+}__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 +155,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 +184,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 +231,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 +318,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;@@ -307,10 +384,10 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(const float fb = bf2f(bb), eg0 = ex2(g.x), eg1 = ex2(g.y);const float k0 = bf2f(kk & 0xffff), k1 = bf2f(kk >> 16);const float q0 = bf2f(qq & 0xffff), q1 = bf2f(qq >> 16);- kb[0][e] = f2bf(bf2f(f2bf_rtz(k0 * fb)) * eg0);- kb[1][e] = f2bf(bf2f(f2bf_rtz(k1 * fb)) * eg1);- vb[0][e] = f2bf_rtz(bf2f(vv & 0xffff) * fb);- vb[1][e] = f2bf_rtz(bf2f(vv >> 16) * fb);+ kb[0][e] = f2bf(bf2f(f2bf_mul(k0 * fb)) * eg0);+ kb[1][e] = f2bf(bf2f(f2bf_mul(k1 * fb)) * eg1);+ vb[0][e] = f2bf_mul(bf2f(vv & 0xffff) * fb);+ vb[1][e] = f2bf_mul(bf2f(vv >> 16) * fb);kg[0][e] = f2bf(k0 * (ok ? ex2(gn.x - g.x) : 0.0f));kg[1][e] = f2bf(k1 * (ok ? ex2(gn.y - g.y) : 0.0f));qgp[s] = f2bf(q0 * eg0) | (f2bf(q1 * eg1) << 16);@@ -371,10 +448,10 @@ extern "C" __global__ __launch_bounds__(PFW ? 288 : 256) void kda_fused_h_o(const float fb = bf2f(bb), eg0 = ex2(g.x), eg1 = ex2(g.y);const float k0 = bf2f(kk & 0xffff), k1 = bf2f(kk >> 16);const float q0 = bf2f(qq & 0xffff), q1 = bf2f(qq >> 16);- kb[0][e] = f2bf(bf2f(f2bf_rtz(k0 * fb)) * eg0);- kb[1][e] = f2bf(bf2f(f2bf_rtz(k1 * fb)) * eg1);- vb[0][e] = f2bf_rtz(bf2f(vv & 0xffff) * fb);- vb[1][e] = f2bf_rtz(bf2f(vv >> 16) * fb);+ kb[0][e] = f2bf(bf2f(f2bf_mul(k0 * fb)) * eg0);+ kb[1][e] = f2bf(bf2f(f2bf_mul(k1 * fb)) * eg1);+ vb[0][e] = f2bf_mul(bf2f(vv & 0xffff) * fb);+ vb[1][e] = f2bf_mul(bf2f(vv >> 16) * fb);kg[0][e] = f2bf(k0 * (ok ? ex2(gn.x - g.x) : 0.0f));kg[1][e] = f2bf(k1 * (ok ? ex2(gn.y - g.y) : 0.0f));qgp[2 * s2 + e] = f2bf(q0 * eg0) | (f2bf(q1 * eg1) << 16);@@ -416,7 +493,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 +506,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 +542,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 +558,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 +577,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 +623,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 +641,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 +655,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 +670,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 +685,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 +716,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..f09e3ff 100644--- a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py+++ b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py@@ -10,13 +10,17 @@ 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. Its bf16 x bf16 products round to+# nearest even on gfx11.5 and gfx12 (f2bf_mul), which makes o and the final state bitwise equal+# to the Triton fused path on gfx1201 under Triton 3.9; both arches are enabled at the gate.+_ARCHS = GFX115_ARCHS | frozenset(("gfx1200", "gfx1201"))def supported(device=None):- """kda_fused_h.hip is a gfx11.5 WMMA kernel; refuse other archs before any hipcc attempt."""+ """True for the gfx11.5 and gfx12 WMMA fragment paths of kda_fused_h.hip; refuse others before hipcc."""if not torch.version.hip:return False- return device_supported(device, GFX115_ARCHS)+ return device_supported(device, _ARCHS)def _hipcc():@@ -33,7 +37,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 +110,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_dispatch_cpu.py b/tests/test_kda_dispatch_cpu.pynew file mode 100644index 0000000..bcf6e58--- /dev/null+++ b/tests/test_kda_dispatch_cpu.py@@ -0,0 +1,70 @@+"""CPU test of the chunk_kda default dispatch (EXL3_KDA_FUSE unset = 3) on an arch whose fused Triton output is not+known-stable: {HIP, non-HIP} x {single device, layer split}. Kernels are stubbed; the test records which path runs.++Non-HIP keeps the previous rule (deterministic fla chain only under KYOJIN_SPLIT_ACTIVE, the Triton fused path otherwise).+HIP with no runnable HIP kernel takes the deterministic chain in both modes. A known-stable arch keeps the fused path."""+import sys, types+import pytest+import torch++import exllamav3.vendor.fla as F+++def stubs(monkeypatch):+ calls = []+ monkeypatch.delenv("EXL3_KDA_FUSE", raising = False)+ monkeypatch.delenv("EXL3_KDA_INTRA", raising = False)+ hf = types.ModuleType("exllamav3.vendor.fla.hip.kda_hf_hip")+ hf.kda_hf_ok = lambda *a, **k: False+ hf.chunk_kda_hf = None+ monkeypatch.setitem(sys.modules, "exllamav3.vendor.fla.hip.kda_hf_hip", hf)+ monkeypatch.setattr(F, "_hip_ok", lambda *a, **k: False)++ def intra_pinned(q, k, gk, beta, scale, chunk_size):+ B, T, H, K = q.shape+ return torch.zeros(B, T, H, 64), torch.zeros(B, T, H, 64)++ def fused(q, k, v, gk, beta, Akk, Aqk, scale, initial_state, output_final_state, chunk_size, fuse_o):+ calls.append("triton_fused")+ return None, None, torch.zeros_like(v), None++ def chain_intra(q, k, v, gk, beta, scale, chunk_size, **kw):+ calls.append("chain")+ z = torch.zeros(1)+ return z, z, z, z, z, z++ monkeypatch.setattr(F, "chunk_kda_fwd_intra_pinned", intra_pinned)+ monkeypatch.setattr(F, "chunk_kda_fwd_h_fused", fused)+ monkeypatch.setattr(F, "chunk_kda_fwd_intra", chain_intra)+ monkeypatch.setattr(F, "chunk_gated_delta_rule_fwd_h", lambda **kw: (None, None, None))+ monkeypatch.setattr(F, "chunk_gla_fwd_o_gk", lambda **kw: torch.zeros(1))+ return calls+++def _run():+ B, T, H, K = 1, 512, 2, 128+ q = torch.zeros(B, T, H, K, dtype = torch.bfloat16)+ v = torch.zeros(B, T, H, K, dtype = torch.bfloat16)+ g = torch.zeros(B, T, H, K)+ beta = torch.zeros(B, T, H, dtype = torch.bfloat16)+ F.chunk_kda(q, q.clone(), v, g, beta, g_cumsum = True)++[email protected]("hip, split, stable, expected", [+ (False, False, False, "triton_fused"), # CUDA / unknown arch, one device: as before this change+ (False, True, False, "chain"), # CUDA / unknown arch under a split: as before+ (True, False, False, "chain"), # gfx12, no runnable HIP kernel: deterministic chain+ (True, True, False, "chain"),+ (False, False, True, "triton_fused"), # known-stable arch keeps the fused path+ (True, True, True, "triton_fused"),+])+def test_default_dispatch(stubs, monkeypatch, hip, split, stable, expected):+ monkeypatch.setattr(torch.version, "hip", "7.0" if hip else None)+ if split:+ monkeypatch.setenv("KYOJIN_SPLIT_ACTIVE", "1")+ else:+ monkeypatch.delenv("KYOJIN_SPLIT_ACTIVE", raising = False)+ monkeypatch.setattr(F, "_fused_output_stable", lambda device = None: stable)+ _run()+ assert stubs == [expected]diff --git a/tests/test_kda_fused_h_gfx12.py b/tests/test_kda_fused_h_gfx12.pynew file mode 100644index 0000000..33b6729--- /dev/null+++ b/tests/test_kda_fused_h_gfx12.py@@ -0,0 +1,140 @@+"""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, runs and is bitwise equal to the Triton fused+path on gfx1201 for the shape/ragged/h0/ht matrix and CK4/CK8 checkpoints. The missing+piece was the bf16 x bf16 product rounding: under Triton 3.9 it rounds to nearest even+on both gfx11.5 and gfx12. `kda_fused_h.hip` does the same in `f2bf_mul`, and the runtime+gate now includes gfx1200/gfx1201.+"""+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_accepts(dev, kda):+ assert kda[4].supported(dev) is True+++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]("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..24da6e1 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 and kda_hf are gfx11.5-only at the gate: on+gfx1201 their supported() gate must refuse before any hipcc attempt. kda_fused now has+a bitwise gfx12 path and accepts gfx1200/gfx1201 as well."""import ctypesimport importlib@@ -53,6 +54,8 @@ finally:sys.modules.pop(_n, None)GFX115 = arch_list.GFX115_ARCHS+GFX12 = frozenset(("gfx1200", "gfx1201"))+KDA_FUSED_GATE = GFX115 | GFX12# name -> (module, load(device), arch gate)CASES = {@@ -66,10 +69,11 @@ CASES = {"dsv41_moe": (dsv41_moe, lambda m, d: m._load(d), None),"gdn_hf": (gdn_hf, lambda m, d: m._load(d), GFX115),"gdn_fused_h_hip": (gdn_fused, lambda m, d: m._load("", d), GFX115),- "kda_fused_h_hip": (kda_fused, lambda m, d: m._load("", d), GFX115),+ "kda_fused_h_hip": (kda_fused, lambda m, d: m._load("", d), KDA_FUSED_GATE),"kda_hf_hip": (kda_hf, lambda m, d: m._load("", d), GFX115),}-SUPPORTED = {"gr_mix_hip", "ple_hip", "gdn_hf", "gdn_fused_h_hip", "kda_fused_h_hip", "kda_hf_hip"}+# gfx11.5-only loaders whose gfx1201 supported() gate must refuse before compiling.+SUPPORTED = {"gr_mix_hip", "ple_hip", "gdn_hf", "gdn_fused_h_hip", "kda_hf_hip"}class FakeCuda:@@ -216,6 +220,11 @@ def test_gfx12_gate_refuses_before_compiling(fake_jit, name):assert not any(isinstance(k, tuple) and k[0] == 1 for k in module._state)+def test_kda_fused_gfx12_gate_accepts(fake_jit):+ assert kda_fused.supported(0) is True+ assert kda_fused.supported(1) is True++@pytest.mark.skipif(not (torch.version.hip and torch.cuda.device_count() >= 2),reason = "requires two ROCm GPUs")def test_each_loader_loads_on_both_devices():