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
gfx1201 (RDNA 4) native fdot2 GEMV + ROCm block-graph capture fix (#160)
resynth4b1a91238778
diff --git a/exllamav3/exllamav3_ext/build_config.py b/exllamav3/exllamav3_ext/build_config.pyindex d5997bf..fa108ce 100644--- a/exllamav3/exllamav3_ext/build_config.py+++ b/exllamav3/exllamav3_ext/build_config.py@@ -55,6 +55,10 @@ def get_sources(sources_dir, is_rocm, base_dir=None):continuerel_path = os.path.relpath(os.path.join(root, file), start=sources_dir)norm_rel = rel_path.replace('\\', '/')+ # rocm/ contains HIP-only translation units (for example the RDNA fdot2+ # GEMV); a CUDA build must not see them.+ if not is_rocm and norm_rel.startswith('rocm/'):+ continueif is_rocm and not norm_rel.startswith(ROCM_ALLOW_PREFIXES):parts = norm_rel.split('/')if any(d in parts for d in ROCM_EXCLUDE_DIRS):diff --git a/exllamav3/exllamav3_ext/quant/exl3_gemv.cu b/exllamav3/exllamav3_ext/quant/exl3_gemv.cuindex 6cddb65..3516d75 100644--- a/exllamav3/exllamav3_ext/quant/exl3_gemv.cu+++ b/exllamav3/exllamav3_ext/quant/exl3_gemv.cu@@ -8,6 +8,7 @@#include "hadamard.cuh"#if defined(USE_ROCM)#include "exl3_gemv_int8.cuh" // fused int8-activation GEMV (mul1 tensors, m <= 2), opt-in via EXL3_INT8_GEMV+#include "../rocm/quant/exl3_gemv_rdna.cuh" // fdot2 m == 1 dot core for gfx1200/gfx1201#endif#include <c10/cuda/CUDAGuard.h>@@ -1638,16 +1639,34 @@ void exl3_gemv(void*)& svh_ptr};- bool ok = exl3_gemv_try_launch- (- kernel_args, size_m, size_k, size_n, K, half_k, cb, c_fp32,- true, device, stream, nullptr, true- );+ bool ok = false;+ [[maybe_unused]] bool out_rotated = false;+#if defined(USE_ROCM)+ // gfx1200/gfx1201: the fdot2 dot core takes the dense multi-row GEMV+ // as well as m == 1. The input Hadamard above has already produced A_had.+ // For m == 1 the output Hadamard is fused into the dot kernel when the+ // width fits the per-device segment counters; rows > 1 store the raw+ // products and the had_r_128 below rotates the whole C as before.+ // Half-integer bitrates keep the WMMA kernel.+ if (!half_k && exl3_gemv_rdna_arch(device))+ ok = exl3_gemv_rdna_launch(A_ptr, B_ptr, C_ptr, svh_ptr, device,+ size_m, size_k, size_n, K, cb, c_fp32, stream,+ true, &out_rotated);+#endif+ if (!ok)+ ok = exl3_gemv_try_launch+ (+ kernel_args, size_m, size_k, size_n, K, half_k, cb, c_fp32,+ true, device, stream, nullptr, true+ );TORCH_CHECK(ok, "exl3_gemv: call is not eligible for the GEMV kernel");#if defined(USE_ROCM)- at::Tensor C_view = C.view({size_m, size_n});- had_r_128(C_view, C_view, c10::nullopt, svh, 1.0f);+ if (!out_rotated)+ {+ at::Tensor C_view = C.view({size_m, size_n});+ had_r_128(C_view, C_view, c10::nullopt, svh, 1.0f);+ }cuda_check(hipPeekAtLastError());#elsecuda_check(cudaPeekAtLastError());diff --git a/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_kernel_rdna.cuh b/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_kernel_rdna.cuhnew file mode 100644index 0000000..c0057b3--- /dev/null+++ b/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_kernel_rdna.cuh@@ -0,0 +1,754 @@+#pragma once++// =============================================================================+// RDNA 3.5 GEMV kernel -- fdot2 dot-product form+// =============================================================================+//+// This is NOT a port of quant/exl3_gemv_kernel.cuh. That kernel is built on+// m16n8k16 mma.sync (locally defined as mma_ab_h) plus cp_async and a+// cooperative grid.sync. It has no RDNA equivalent.+//+// Shape: one warp per 16-wide output tile, 16 active lanes each accumulating one+// output element in fp32. B is staged quantized through LDS, dequantized in+// registers, unswizzled to row-major in LDS, then consumed by V_DOT2_F32_F16.+//+// Handles bits 1-8, cb 0 (default) / 1 (mcg) / 2 (mul1), fp16 or fp32 C, and+// M == 1 plus the M == 2..8 split-K MR form below. Larger M falls through to+// the cooperative GEMM.+// =============================================================================++#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>++#include "../../quant/hadamard_inner.cuh"+#include "../../quant/exl3_dq.cuh"+#include "exl3_gemv_tiles_rdna.cuh"++// -----------------------------------------------------------------------------+// LDS geometry -- ONE definition, used by the kernel and by the host launch+// -----------------------------------------------------------------------------+// SH_STRIDE = 18: pads the 16-column tile to 18 halves (36 bytes = 9 dwords) per+// row so the write pattern spreads across all 32 LDS banks. At 17 the adjacent+// active-lane groups (0-3 vs 16-19, 8-11 vs 24-27) collide on banks 2,3,10,11+// etc. 9 is coprime with 32, so+// (row * 9 + col / 2) mod 32 covers every bank.+//+// The quantized staging area is sized for the widest bitwidth (8) rather than+// per-instantiation, so one host-side figure covers every kernel.+//+// Keep the host size and the kernel's indexing derived from these constants and+// nothing else. An LDS figure that drifts out of step presents as a kernel bug,+// not as a launch bug.+#define EXL3_GEMV_SH_STRIDE 18+#define EXL3_GEMV_SH_QUANT_U16 (16 * 8)++static inline size_t exl3_gemv_smem_bytes(int warps_per_block)+{+ return (size_t) warps_per_block *+ (16 * EXL3_GEMV_SH_STRIDE * sizeof(half) ++ EXL3_GEMV_SH_QUANT_U16 * sizeof(uint16_t));+}++// =============================================================================+// Dot-product tile loop -- shared between the single-matrix GEMV kernel below+// and the multi-row split-K form below+// =============================================================================+//+// Extracted verbatim from exl3_gemv_dot_kernel; the kernel wrappers own the+// grid/tile mapping and the output store, this owns everything per-warp. All 32+// lanes must enter (the unswizzle round trip uses the full warp); the return+// value is the accumulated dot product, meaningful for lanes 0-15 only.++template <int bits, int cb>+__device__ __forceinline__ float exl3_gemv_dot_tile+(+ const half* __restrict__ A, // rotated input, [size_k]+ const uint16_t* __restrict__ B, // quantized trellis for one matrix+ const int size_k,+ const int n_tiles, // size_n / 16 for THIS matrix+ const int tile_n, // this warp's N-tile+ const int lane,+ half* my_sh_b, // per-warp staging, 16 * EXL3_GEMV_SH_STRIDE halves+ uint16_t* my_sh_b_quant, // per-warp staging, EXL3_GEMV_SH_QUANT_U16 u16+ const int kb_begin, // k16-tile range for THIS warp; (0, size_k/16)+ const int kb_end // for the whole-K single-warp form+)+{+ constexpr int SH_STRIDE = EXL3_GEMV_SH_STRIDE;++ // Each lane 0-15 accumulates one output element+ float accum = 0.0f;++ const int tile_elements = 16 * bits;++ for (int k_tile = kb_begin; k_tile < kb_end; k_tile++)+ {+ const int k_offset = k_tile * 16;++ // =====================================================================+ // Step 1: Load quantized B tile+ // =====================================================================+ const uint16_t* gl_b = B + (k_tile * n_tiles + tile_n) * tile_elements;++ #pragma unroll+ for (int i = lane; i < tile_elements; i += 32)+ my_sh_b_quant[i] = gl_b[i];++ __syncwarp();++ // =====================================================================+ // Step 2: Dequantize+ // =====================================================================+ const uint32_t* b_quant = (const uint32_t*) my_sh_b_quant;++ FragB frag0, frag1;+ dq_dispatch<bits, cb>(b_quant, lane << 3, frag0, frag1);++ // Unswizzle (shuffle by 4 within warp + combine low/high halves)+ uint32_t v0 = *reinterpret_cast<uint32_t*>(&frag0[0]);+ uint32_t v1 = *reinterpret_cast<uint32_t*>(&frag0[1]);+ uint32_t v2 = *reinterpret_cast<uint32_t*>(&frag1[0]);+ uint32_t v3 = *reinterpret_cast<uint32_t*>(&frag1[1]);++ uint32_t s0 = __shfl_down(v0, 4, 32);+ uint32_t s1 = __shfl_down(v1, 4, 32);+ uint32_t s2 = __shfl_down(v2, 4, 32);+ uint32_t s3 = __shfl_down(v3, 4, 32);++ half2 n0 = *reinterpret_cast<half2*>(&s0);+ half2 n1 = *reinterpret_cast<half2*>(&s1);+ half2 n2 = *reinterpret_cast<half2*>(&s2);+ half2 n3 = *reinterpret_cast<half2*>(&s3);++ if (!(lane & 4))+ {+ // VGPR-pressure reduction: the previous implementation built 8+ // intermediate half2's (m0..m7) and then extracted their halves+ // to store. Each __halves2half2(X, Y) followed by __low/high2half+ // just gives back X and Y, so the m_i's were round-trip no-ops+ // consuming VGPRs. Storing the halves directly removes 8 VGPRs of+ // unnecessary live state per lane. Writes are also reordered so+ // each (frag, n) pair is fully consumed before the next, giving+ // the compiler a cleaner signal about which values can die early.+ const int r0 = (lane % 4) * 2;+ const int r1 = r0 + 1;+ const int r2 = r0 + 8;+ const int r3 = r0 + 9;+ const int c0 = (lane / 8) * 2;+ const int c1 = c0 + 8;++ #define B_IDX(row, col) ((row) * SH_STRIDE + (col))++ // Group 1: frag0[0] + n0 -> (r0, c0), (r1, c0) at cols c0, c0+1+ my_sh_b[B_IDX(r0, c0)] = __low2half (frag0[0]);+ my_sh_b[B_IDX(r0, c0 + 1)] = __low2half (n0);+ my_sh_b[B_IDX(r1, c0)] = __high2half(frag0[0]);+ my_sh_b[B_IDX(r1, c0 + 1)] = __high2half(n0);++ // Group 2: frag0[1] + n1 -> (r2, c0), (r3, c0)+ my_sh_b[B_IDX(r2, c0)] = __low2half (frag0[1]);+ my_sh_b[B_IDX(r2, c0 + 1)] = __low2half (n1);+ my_sh_b[B_IDX(r3, c0)] = __high2half(frag0[1]);+ my_sh_b[B_IDX(r3, c0 + 1)] = __high2half(n1);++ // Group 3: frag1[0] + n2 -> (r0, c1), (r1, c1)+ my_sh_b[B_IDX(r0, c1)] = __low2half (frag1[0]);+ my_sh_b[B_IDX(r0, c1 + 1)] = __low2half (n2);+ my_sh_b[B_IDX(r1, c1)] = __high2half(frag1[0]);+ my_sh_b[B_IDX(r1, c1 + 1)] = __high2half(n2);++ // Group 4: frag1[1] + n3 -> (r2, c1), (r3, c1)+ my_sh_b[B_IDX(r2, c1)] = __low2half (frag1[1]);+ my_sh_b[B_IDX(r2, c1 + 1)] = __low2half (n3);+ my_sh_b[B_IDX(r3, c1)] = __high2half(frag1[1]);+ my_sh_b[B_IDX(r3, c1 + 1)] = __high2half(n3);++ #undef B_IDX+ }++ __syncwarp();++ // =====================================================================+ // Step 3: Dot product -- lane L computes output column L+ //+ // Optimized with V_DOT2_F32_F16 (RDNA 3.5 ISA packed-math op,+ // VOP3P, full rate): __builtin_amdgcn_fdot2(a, b, c, clamp) computes+ // c + a.x * b.x + a.y * b.y (all fp16 inputs, fp32 accumulate)+ // This halves the instruction count of the inner loop: 8 dot2 ops+ // instead of 16 f16->f32 converts + 16 FMAs per lane per k-tile.+ //+ // A is contiguous in k -> single half2 aligned load per pair.+ // B is strided (rows 18 halves apart in LDS) -> pack two scalar LDS+ // reads into a half2 manually. All lanes read A[k_offset + k] for+ // the SAME k -- the compiler lifts that to a scalar broadcast load,+ // which is materially faster than a per-lane vector load. Splitting+ // K across lanes 0-15/16-31 breaks this broadcast and regresses+ // kernel time, so we stay with the 16-active-lane design.+ // =====================================================================+ if (lane < 16)+ {+ #pragma unroll+ for (int k = 0; k < 16; k += 2)+ {+ half2 a2 = *reinterpret_cast<const half2*>(&A[k_offset + k]);+ half2 b2 = __halves2half2(+ my_sh_b[k * SH_STRIDE + lane],+ my_sh_b[(k + 1) * SH_STRIDE + lane]+ );+ accum = exl3_fdot2(a2, b2, accum);+ }+ }++ __syncwarp();+ }++ return accum;+}++// =============================================================================+// Barrier-free dot-tile core -- accumulates in dq's native fragment layout+// =============================================================================+//+// The LDS core above spends most of each k-iteration on the unswizzle round+// trip: stage quantized -> dq -> __shfl_down -> LDS scatter -> __syncwarp ->+// LDS gather -> dot, with lanes 16-31 idle in the dot phase. This core deletes+// all of it by never leaving dq's output layout. Derivation, verified against+// the unswizzle above:+//+// dq_dispatch<bits,cb>(b_tile, L << 3, frag0, frag1) hands lane L the 16x16+// (K x N) tile elements+// frag0[0] = ( B[r0 ][cA], B[r0+1][cA] ) r0 = (L % 4) * 2+// frag0[1] = ( B[r0+8][cA], B[r0+9][cA] ) cA = (L / 8) * 2 + ((L >> 2) & 1)+// frag1[0] = ( B[r0 ][cB], B[r0+1][cB] ) cB = cA + 8+// frag1[1] = ( B[r0+8][cB], B[r0+9][cB] )+//+// (The unswizzle writes lane L's frag0[0] to column (L/8)*2 when L&4 == 0 and+// routes it through __shfl_down(,4) to column (L/8)*2+1 when L&4 == 4 --+// i.e. source lane S holds column (S/8)*2 + ((S>>2)&1). Rows follow (S%4)*2+// because S%4 == (S+4)%4.)+//+// So column cA is held by exactly the lane quad {4*cA .. 4*cA+3}, whose four+// lanes cover rows {0..7} x {+0,+8} between them, and every lane does useful+// work. Two fdot2 per fragment pair against A rows (r0, r0+1) and (r0+8,+// r0+9), a 2-hop __shfl_xor quad reduction ONCE at the end of the k-range+// (not per tile), and a broadcast remap so lanes 0-15 return columns 0-15 --+// the same contract as the LDS core, so every kernel wrapper takes either.+//+// B is read directly from global: a tile is 32*bits contiguous bytes, the warp+// collectively touches every byte exactly once, and L0 serves the overlapping+// lane reads. A is read per-lane (two half2 loads); quads repeat the same 32+// bytes and hit L0. No LDS, no barriers, no idle lanes.+//+// Selected at runtime by the kernels' trailing lds_core argument (see+// exl3_gemv_lds_core() -- EXL3_GEMV_LDS=1 pins the LDS core). All 32 lanes+// must enter (the reduction shuffles use the full warp).++template <int bits, int cb>+__device__ __forceinline__ float exl3_gemv_dot_tile_direct+(+ const half* __restrict__ A, // rotated input, [size_k]+ const uint16_t* __restrict__ B, // quantized trellis for one matrix+ const int n_tiles, // size_n / 16 for THIS matrix+ const int tile_n, // this warp's N-tile+ const int lane,+ const int kb_begin, // k16-tile range for THIS warp+ const int kb_end+)+{+ constexpr int tile_elements = 16 * bits;++ const int r0 = (lane & 3) * 2;++ float accA = 0.0f; // column cA+ float accB = 0.0f; // column cB = cA + 8++ for (int k_tile = kb_begin; k_tile < kb_end; k_tile++)+ {+ const uint32_t* b_ptr = (const uint32_t*)+ (B + (k_tile * n_tiles + tile_n) * tile_elements);++ FragB frag0, frag1;+ dq_dispatch<bits, cb>(b_ptr, lane << 3, frag0, frag1);++ const half2* a2 = (const half2*) (A + k_tile * 16);+ half2 a01 = a2[r0 >> 1]; // (A[r0], A[r0+1])+ half2 a89 = a2[(r0 >> 1) + 4]; // (A[r0+8], A[r0+9])++ accA = exl3_fdot2(a01, frag0[0], accA);+ accA = exl3_fdot2(a89, frag0[1], accA);+ accB = exl3_fdot2(a01, frag1[0], accB);+ accB = exl3_fdot2(a89, frag1[1], accB);+ }++ // Quad reduction: after two xor hops every lane of quad g holds the full+ // sum for columns g (accA) and g+8 (accB)+ accA += __shfl_xor(accA, 1, 32);+ accA += __shfl_xor(accA, 2, 32);+ accB += __shfl_xor(accB, 1, 32);+ accB += __shfl_xor(accB, 2, 32);++ // Remap to the LDS core's contract: lane l (0-15) returns column l.+ // Column c < 8 lives in quad 4c (accA); column c >= 8 in quad 4*(c-8)+ // (accB). Lanes 16-31 return a defined but meaningless value, as before.+ float vA = __shfl(accA, (lane & 7) * 4, 32);+ float vB = __shfl(accB, (lane & 7) * 4, 32);+ return (lane & 8) ? vB : vA;+}++// Defined in exl3_gemv_rdna.cu; EXL3_GEMV_LDS=1 pins the LDS core in every+// GEMV form (the A/B and kill switch for the barrier-free core). Re-read per+// call. Kernels take the result as their trailing lds_core argument -- runtime+// rather than a template split so the instantiation count stays put; the LDS+// high-water mark is unchanged (smem is passed identically in both modes) and+// LDS was never the occupancy limiter for these kernels.+bool exl3_gemv_lds_core();++// The dot core every GEMV kernel runs, as its trailing `core` argument:+// EXL3_GEMV_CORE_TILES (default; exl3_gemv_tiles_rdna.cuh), _DIRECT+// (EXL3_ROCM_GEMV_TILES=0) or _LDS (EXL3_GEMV_LDS=1). Defined in+// exl3_gemv_rdna.cu; re-read per call, baked into graphs at capture.+int exl3_gemv_core_mode();++// One tile's dot product for lanes 0-15 (the core contract), by core mode.+// SINGLE picks the single-warp U. A_LDS: A lives in LDS (fused prologues).+template <int bits, int cb, bool A_LDS, bool SINGLE>+__device__ __forceinline__ float exl3_gemv_dot_tile_sel+(+ const int core,+ const half* __restrict__ A,+ const uint16_t* __restrict__ B,+ const int size_k,+ const int n_tiles,+ const int tile_n,+ const int lane,+ half* my_sh_b,+ uint16_t* my_sh_b_quant,+ const int kb_begin,+ const int kb_end+)+{+ if (core == EXL3_GEMV_CORE_TILES)+ {+ constexpr int U = SINGLE ? exl3_tiles_u_single<bits>() : exl3_tiles_u_splitk<bits, 1, 1>();+ float o[1];+ exl3_gemv_dot_tile_tiles<bits, cb, 1, A_LDS, U, 1>(A, 0, B, n_tiles, tile_n, lane, kb_begin, kb_end, o);+ return o[0];+ }+ if (core == EXL3_GEMV_CORE_LDS)+ return exl3_gemv_dot_tile<bits, cb>(A, B, size_k, n_tiles, tile_n, lane, my_sh_b, my_sh_b_quant, kb_begin, kb_end);+ return exl3_gemv_dot_tile_direct<bits, cb>(A, B, n_tiles, tile_n, lane, kb_begin, kb_end);+}++// Split-K over T adjacent N-tiles (tile_n0 .. tile_n0 + tpb - 1, tpb <= T),+// M rows: the chunking and warp-order reduction of exl3_gemv_dot_tile_splitk+// per (tile, row), so each output is bit-identical to a tpb = 1 call. With+// the TILES core the tiles share A loads and one wide B read per k-tile; the+// other cores run `old(tile_n, kb0, kb1, out_M)` per tile. sh_red holds+// WARPS_PER_BLOCK * T * M * 16 floats. All threads enter; out[t * M + r] is+// meaningful for warp 0, lanes 0-15, t < tpb. rows_valid (<= M) is the number+// of rows A actually holds; the cores read nothing past them.+template <int bits, int cb, int WARPS_PER_BLOCK, int M, bool A_LDS, int T, typename OldCore>+__device__ __forceinline__ void exl3_gemv_dot_tile_splitk_t+(+ const int core,+ const int tpb,+ const half* __restrict__ A,+ const int lda,+ const uint16_t* __restrict__ B,+ const int size_k,+ const int n_tiles,+ const int tile_n0,+ const int warp_id,+ const int lane,+ float* sh_red,+ float* out,+ OldCore old,+ const int rows_valid = M+)+{+ const int num_k_tiles = size_k / 16;+ const int chunk = (num_k_tiles + WARPS_PER_BLOCK - 1) / WARPS_PER_BLOCK;+ const int kb0 = exl3_uni(warp_id) * chunk;+ const int kb1 = kb0 + chunk < num_k_tiles ? kb0 + chunk : num_k_tiles;++ float acc[T * M];+ #pragma unroll+ for (int i = 0; i < T * M; ++i) acc[i] = 0.0f;+ if (kb0 < kb1)+ {+ if (core == EXL3_GEMV_CORE_TILES)+ {+ if (T > 1 && tpb == T)+ exl3_gemv_dot_tile_tiles<bits, cb, M, A_LDS, exl3_tiles_u_splitk<bits, M, T>(), T>+ (A, lda, B, n_tiles, tile_n0, lane, kb0, kb1, acc, rows_valid);+ else+ exl3_gemv_dot_tile_tiles<bits, cb, M, A_LDS, exl3_tiles_u_splitk<bits, M, 1>(), 1>+ (A, lda, B, n_tiles, tile_n0, lane, kb0, kb1, acc, rows_valid);+ }+ else+ {+ for (int t = 0; t < tpb; ++t)+ old(tile_n0 + t, kb0, kb1, acc + t * M);+ }+ }++ if (lane < 16)+ {+ #pragma unroll+ for (int i = 0; i < T * M; ++i)+ if (i < tpb * M) sh_red[(warp_id * T * M + i) * 16 + lane] = acc[i];+ }+ __syncthreads();++ if (warp_id == 0 && lane < 16)+ {+ #pragma unroll+ for (int i = 0; i < T * M; ++i)+ {+ if (i >= tpb * M) break;+ float total = 0.0f;+ #pragma unroll+ for (int w = 0; w < WARPS_PER_BLOCK; ++w)+ total += sh_red[(w * T * M + i) * 16 + lane];+ out[i] = total;+ }+ }+}++// =============================================================================+// Dot-product GEMV kernel -- templated on WARPS_PER_BLOCK+// =============================================================================++template <int bits, bool c_fp32, int cb, int WARPS_PER_BLOCK>+__global__+__launch_bounds__(WARPS_PER_BLOCK * 32)+__attribute__((amdgpu_flat_work_group_size(WARPS_PER_BLOCK * 32, WARPS_PER_BLOCK * 32)))+void exl3_gemv_dot_kernel+(+ const half* __restrict__ A,+ const uint16_t* __restrict__ B,+ void* __restrict__ C,+ const int size_k,+ const int size_n,+ const int core+)+{+ const int warp_id = threadIdx.x / 32;+ const int lane = threadIdx.x % 32;++ // Each warp handles one N-tile (16 outputs)+ const int tile_n = blockIdx.x * WARPS_PER_BLOCK + warp_id;+ const int n_tiles = size_n / 16;++ if (tile_n >= n_tiles) return;++ // Dynamic shared memory -- layout mirrors exl3_gemv_smem_bytes() above+ extern __shared__ char shared_mem[];++ constexpr int SH_STRIDE = EXL3_GEMV_SH_STRIDE;++ half* sh_b_dq = (half*) shared_mem;+ uint16_t* sh_b_quant = (uint16_t*) (sh_b_dq + WARPS_PER_BLOCK * 16 * SH_STRIDE);++ half* my_sh_b = sh_b_dq + warp_id * 16 * SH_STRIDE;+ uint16_t* my_sh_b_quant = sh_b_quant + warp_id * EXL3_GEMV_SH_QUANT_U16;++ float accum = exl3_gemv_dot_tile_sel<bits, cb, false, true>+ (+ core, A, B, size_k, n_tiles, tile_n, lane, my_sh_b, my_sh_b_quant, 0, size_k / 16+ );++ // =========================================================================+ // Step 4: Write output+ // =========================================================================+ if (lane < 16)+ {+ const int out_idx = tile_n * 16 + lane;+ if constexpr (c_fp32)+ ((float*) C)[out_idx] = accum;+ else+ ((half*) C)[out_idx] = __float2half(accum);+ }+}++// =============================================================================+// In-block split-K form -- one block per N-tile, warps share the K range+// =============================================================================+//+// The single-warp form above gives a matmul only size_n/16 warps of+// parallelism, which starves narrow outputs: 3072->1024 is 64 warps in 8+// blocks on a part with 80 SIMDs. llama.cpp's mmvq solves the same problem on+// this hardware with one wave per output row and lanes splitting K; the EXL3+// trellis decodes in 16x16 tiles so one row per wave is off the table, but the+// K split transplants: all WARPS_PER_BLOCK warps of a block work the SAME+// N-tile on disjoint contiguous k16 ranges, then reduce through 16 floats of+// LDS per warp. Total waves multiply by WARPS_PER_BLOCK with zero extra+// global traffic (the ranges are disjoint), no atomics, no workspace, no+// cooperative launch. Wide outputs that already saturate the device keep the+// single-warp form -- see EXL3_GEMV_SPLITK_MAX_TILES at the launch sites.+//+// Per-warp staging (my_sh_b / my_sh_b_quant) is the same carve as the+// single-warp form; sh_red is WARPS_PER_BLOCK * 16 floats appended after it+// (exl3_gemv_smem_bytes_splitk). Every thread of the block must enter (the+// reduction has a __syncthreads); the return value is the full dot product,+// meaningful for warp 0 lanes 0-15 only.++static inline size_t exl3_gemv_smem_bytes_splitk(int warps_per_block)+{+ return exl3_gemv_smem_bytes(warps_per_block) ++ (size_t) warps_per_block * 16 * EXL3_GEMV_TILES_TMAX * sizeof(float);+}++static inline size_t exl3_gemv_smem_bytes_splitk_mr(int warps_per_block, int rows)+{+ return exl3_gemv_smem_bytes(warps_per_block) ++ (size_t) warps_per_block * rows * 16 * sizeof(float);+}++template <int bits, int cb, int WARPS_PER_BLOCK, bool A_LDS = false>+__device__ __forceinline__ float exl3_gemv_dot_tile_splitk+(+ const half* __restrict__ A,+ const uint16_t* __restrict__ B,+ const int size_k,+ const int n_tiles,+ const int tile_n,+ const int warp_id,+ const int lane,+ half* my_sh_b,+ uint16_t* my_sh_b_quant,+ float* sh_red, // WARPS_PER_BLOCK * 16 floats+ const int core+)+{+ float total[1] = {0.0f};+ exl3_gemv_dot_tile_splitk_t<bits, cb, WARPS_PER_BLOCK, 1, A_LDS, 1>+ (+ core, 1, A, 0, B, size_k, n_tiles, tile_n, warp_id, lane, sh_red, total,+ [&](int tn, int k0, int k1, float* o)+ {+ o[0] = core == EXL3_GEMV_CORE_LDS+ ? exl3_gemv_dot_tile<bits, cb>(A, B, size_k, n_tiles, tn, lane, my_sh_b, my_sh_b_quant, k0, k1)+ : exl3_gemv_dot_tile_direct<bits, cb>(A, B, n_tiles, tn, lane, k0, k1);+ }+ );+ return total[0];+}++// =============================================================================+// Multi-row (M = 2..8) split-K form+// =============================================================================+//+// Same split-K chunking and reduction as the M = 1 form above, but the decoded+// tile is applied to M A rows before it is discarded. A is the already-rotated+// input [rows, size_k] (row pitch size_k); rows_valid <= M rows are live and the+// rows past it re-read the last live row (their outputs are not stored). No+// output-Hadamard fusion here: the caller runs its usual had_r_128 over the+// whole C, exactly as the generic M-row path does.+template <int bits, int cb, int WARPS_PER_BLOCK, int M, bool A_LDS = false>+__device__ __forceinline__ void exl3_gemv_dot_tile_splitk_mr+(+ const half* __restrict__ A,+ const int lda,+ const uint16_t* __restrict__ B,+ const int size_k,+ const int n_tiles,+ const int tile_n,+ const int warp_id,+ const int lane,+ half* my_sh_b,+ uint16_t* my_sh_b_quant,+ float* sh_red, // WARPS_PER_BLOCK * M * 16 floats+ float* out, // M values, lanes 0-15 of warp 0+ const int core,+ const int rows_valid+)+{+ float total[M];+ #pragma unroll+ for (int i = 0; i < M; ++i) total[i] = 0.0f;+ exl3_gemv_dot_tile_splitk_t<bits, cb, WARPS_PER_BLOCK, M, A_LDS, 1>+ (+ core, 1, A, lda, B, size_k, n_tiles, tile_n, warp_id, lane, sh_red, total,+ [&](int tn, int k0, int k1, float* o)+ {+ #pragma unroll+ for (int r = 0; r < M; ++r)+ {+ const int rr = r < rows_valid ? r : rows_valid - 1;+ const half* Ar = A + (size_t) rr * lda;+ o[r] = core == EXL3_GEMV_CORE_LDS+ ? exl3_gemv_dot_tile<bits, cb>(Ar, B, size_k, n_tiles, tn, lane,+ my_sh_b, my_sh_b_quant, k0, k1)+ : exl3_gemv_dot_tile_direct<bits, cb>(Ar, B, n_tiles, tn, lane, k0, k1);+ }+ }, rows_valid+ );+ #pragma unroll+ for (int i = 0; i < M; ++i) out[i] = total[i];+}++// =============================================================================+// Output rotation fused into the dot kernels' store epilogue+// =============================================================================++// =============================================================================+// Entered by the warp holding one N-tile's 16 outputs in accum (lanes 0-15);+// all 32 lanes enter. Stores the tile, arrives at its segment's counter, and+// -- as the last of the segment's 8 tiles -- rotates the segment in place with+// the shared SUH/SVH Hadamard helper. The fences are wave-uniform (outside+// every lane predicate) so they cover all lanes' stores.++template <bool c_fp32>+__device__ __forceinline__ void exl3_gemv_fused_epilogue+(+ const float accum,+ void* Cb, // output base for this matrix+ const int64_t row_off, // j * size_n, or 0 for list outputs+ const int tile_n,+ const int lane,+ const half* __restrict__ svh,+ const float scale, // 1/sqrt(128) * routing weight+ int* seg_counter // this (slot, segment)'s arrival counter+)+{+ // 1. Store this tile, exactly as the unfused form does+ if (lane < 16)+ {+ const int64_t out_idx = row_off + tile_n * 16 + lane;+ if constexpr (c_fp32)+ ((float*) Cb)[out_idx] = accum;+ else+ ((half*) Cb)[out_idx] = __float2half(accum);+ }++ // 2. Arrive at the segment+ __threadfence();+ int old = 0;+ if (lane == 0) old = atomicAdd(seg_counter, 1);+ old = __shfl(old, 0, 32);+ if (old != 7) return;++ // 3. Last of the 8 tiles: acquire, reset, rotate in place. The shared+ // hadamard helper is the same arithmetic as the old local copy; the+ // scale pointer is already offset to this 128-wide segment.+ __threadfence();+ if (lane == 0) *seg_counter = 0;+ const int seg = tile_n / 8;+ const int64_t seg_off = row_off + (int64_t) seg * 128;+ if constexpr (c_fp32)+ had_ff_r_128_inner<false, true>(((float*) Cb) + seg_off, ((float*) Cb) + seg_off,+ svh + seg * 128, scale);+ else+ had_hf_r_128_inner<false, true>(((half*) Cb) + seg_off, ((half*) Cb) + seg_off,+ svh + seg * 128, scale);+}++// Above this many N-tiles the single-warp form is kept; below it, split-K+// multiplies the wave count by WARPS_PER_BLOCK. Split-K only reaches parity+// with the single-warp form at lm_head scale; 2048 flips every in-model+// projection to split-K and leaves lm_head-scale outputs on the single-warp+// form, which avoids 16k-block grids.+#define EXL3_GEMV_SPLITK_MAX_TILES 2048++// The split-K wave count is not a fixed constant: every split-K launch site+// calls exl3_gemv_splitk_warps() (exl3_gemv_rdna.cu), which picks 4, 8 or 16+// from (k_tiles, blocks = n_tiles x bszm), and EXL3_GEMV_SPLITK_WARPS (env)+// forces one count everywhere. The M == 2..8 MR kernel+// (exl3_gemv_dot_kernel_splitk_mr) gets its wave count from that same helper.++template <int bits, bool c_fp32, int cb, int WARPS_PER_BLOCK>+__global__+__launch_bounds__(WARPS_PER_BLOCK * 32)+__attribute__((amdgpu_flat_work_group_size(WARPS_PER_BLOCK * 32, WARPS_PER_BLOCK * 32)))+void exl3_gemv_dot_kernel_splitk+(+ const half* __restrict__ A,+ const uint16_t* __restrict__ B,+ void* __restrict__ C,+ const int size_k,+ const int size_n,+ const int core+)+{+ const int warp_id = threadIdx.x / 32;+ const int lane = threadIdx.x % 32;++ // One block per N-tile; the block's warps split K+ const int tile_n = blockIdx.x;+ const int n_tiles = size_n / 16;++ extern __shared__ char shared_mem[];+ constexpr int SH_STRIDE = EXL3_GEMV_SH_STRIDE;+ half* sh_b_dq = (half*) shared_mem;+ uint16_t* sh_b_quant = (uint16_t*) (sh_b_dq + WARPS_PER_BLOCK * 16 * SH_STRIDE);+ float* sh_red = (float*) (sh_b_quant + WARPS_PER_BLOCK * EXL3_GEMV_SH_QUANT_U16);+ half* my_sh_b = sh_b_dq + warp_id * 16 * SH_STRIDE;+ uint16_t* my_sh_b_quant = sh_b_quant + warp_id * EXL3_GEMV_SH_QUANT_U16;++ float accum = exl3_gemv_dot_tile_splitk<bits, cb, WARPS_PER_BLOCK>+ (+ A, B, size_k, n_tiles, tile_n, warp_id, lane, my_sh_b, my_sh_b_quant,+ sh_red, core+ );++ if (warp_id == 0 && lane < 16)+ {+ const int out_idx = tile_n * 16 + lane;+ if constexpr (c_fp32)+ ((float*) C)[out_idx] = accum;+ else+ ((half*) C)[out_idx] = __float2half(accum);+ }+}++// M = 2..8 rows, one block per N-tile, the block's warps split K.+template <int bits, bool c_fp32, int cb, int M, int WARPS_PER_BLOCK>+__global__+__launch_bounds__(WARPS_PER_BLOCK * 32)+__attribute__((amdgpu_flat_work_group_size(WARPS_PER_BLOCK * 32, WARPS_PER_BLOCK * 32)))+void exl3_gemv_dot_kernel_splitk_mr+(+ const half* __restrict__ A,+ const uint16_t* __restrict__ B,+ void* __restrict__ C,+ const int size_k,+ const int size_n,+ const int rows,+ const int core+)+{+ const int warp_id = threadIdx.x / 32;+ const int lane = threadIdx.x % 32;+ const int tile_n = blockIdx.x;+ const int n_tiles = size_n / 16;++ extern __shared__ char shared_mem[];+ constexpr int SH_STRIDE = EXL3_GEMV_SH_STRIDE;+ half* sh_b_dq = (half*) shared_mem;+ uint16_t* sh_b_quant = (uint16_t*) (sh_b_dq + WARPS_PER_BLOCK * 16 * SH_STRIDE);+ float* sh_red = (float*) (sh_b_quant + WARPS_PER_BLOCK * EXL3_GEMV_SH_QUANT_U16);+ half* my_sh_b = sh_b_dq + warp_id * 16 * SH_STRIDE;+ uint16_t* my_sh_b_quant = sh_b_quant + warp_id * EXL3_GEMV_SH_QUANT_U16;++ float out[M];+ exl3_gemv_dot_tile_splitk_mr<bits, cb, WARPS_PER_BLOCK, M>+ (+ A, size_k, B, size_k, n_tiles, tile_n, warp_id, lane, my_sh_b, my_sh_b_quant,+ sh_red, out, core, rows+ );++ if (warp_id == 0 && lane < 16)+ {+ #pragma unroll+ for (int r = 0; r < M; ++r)+ {+ if (r >= rows) break;+ const int64_t out_idx = (int64_t) r * size_n + tile_n * 16 + lane;+ if constexpr (c_fp32)+ ((float*) C)[out_idx] = out[r];+ else+ ((half*) C)[out_idx] = __float2half(out[r]);+ }+ }+}diff --git a/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_rdna.cu b/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_rdna.cunew file mode 100644index 0000000..7213beb--- /dev/null+++ b/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_rdna.cu@@ -0,0 +1,466 @@+// RDNA (gfx1200/gfx1201) GEMV launcher. See exl3_gemv_rdna.cuh.+//+// The kernel cores are adapted from exllamav3's RDNA GEMV (rocm/quant/+// exl3_gemv_kernel_rdna.cuh, MIT) and use the same dq chain as the rest of+// this tree. Two dense single-matrix forms are built here: M == 1 with the+// output Hadamard fused into the store epilogue, and M == 2..8 as a split-K+// multi-row kernel whose C the caller rotates. The multi-matrix and expert+// forms are not built here and stay on the generic WMMA path.+//+// Env switches (measurement / A-B only; all default to the measured choice):+// EXL3_GEMV=0 keep the generic WMMA GEMV+// EXL3_ROCM_GEMV_TILES=0 barrier-free direct core instead of the tiles core+// EXL3_GEMV_LDS=1 LDS unswizzle core+// EXL3_GEMV_SPLITK=0 pin the single-warp form+// EXL3_GEMV_SPLITK_WARPS=4|8|16+// EXL3_GEMV_WARPS=4|8|16 force the single-warp block size+// EXL3_GEMV_FUSE_OUT=0 keep the separate output Hadamard launcher+//+// EXL3_GEMV_SPLITK, EXL3_GEMV_SPLITK_WARPS and EXL3_GEMV_WARPS select the+// M == 1 form only; the M == 2..8 path always uses the split-K MR kernel and+// ignores them. EXL3_GEMV_FUSE_OUT likewise applies to M == 1 only.++#if defined(USE_ROCM)++#include <hip/hip_runtime.h>+#include <cstdlib>+#include <cstring>+#include <mutex>+#include <vector>++#include "../../util.h"+#include "../../util.cuh"+#include "exl3_gemv_rdna.cuh"+#include "exl3_gemv_kernel_rdna.cuh"++// One arrival counter per 128-wide output segment. Self-resetting: the warp+// that observes the final arrival zeroes it again (see+// exl3_gemv_fused_epilogue). Widths above the capacity keep the separate+// output-Hadamard launch.+#ifndef EXL3_GEMV_SEG_COUNTERS+#define EXL3_GEMV_SEG_COUNTERS 1024+#endif++// One preallocated counter slab per device; each stream owns one slice. The+// previous lazy table was capped at 64 entries, so keep that cap here.+static constexpr int MAX_SEG_COUNTER_STREAMS = 64;++static int env_int(const char* name, int def)+{+ const char* env = std::getenv(name);+ return env ? atoi(env) : def;+}++bool exl3_gemv_lds_core()+{+ return env_int("EXL3_GEMV_LDS", 0) != 0;+}++int exl3_gemv_core_mode()+{+ if (exl3_gemv_lds_core()) return EXL3_GEMV_CORE_LDS;+ return env_int("EXL3_ROCM_GEMV_TILES", 1) == 0+ ? EXL3_GEMV_CORE_DIRECT+ : EXL3_GEMV_CORE_TILES;+}++static bool splitk_enabled()+{+ return env_int("EXL3_GEMV_SPLITK", 1) != 0;+}++static int warps_for(int n_tiles, int k_blocks)+{+ const int forced = env_int("EXL3_GEMV_WARPS", 0);+ if (forced == 4 || forced == 8 || forced == 16) return forced;+ if (n_tiles <= 32) return 16;+ if (n_tiles <= 96 && k_blocks <= 256) return 8;+ return 4;+}++static int splitk_warps(int k_tiles, int n_tiles)+{+ int w = env_int("EXL3_GEMV_SPLITK_WARPS", 0);+ if (w == 4 || w == 8 || w == 16) return w;+ const int blocks = n_tiles;+ if (k_tiles <= 128) return 4;+ if (blocks >= 1024) return 4;+ if (blocks < 128 || k_tiles >= 1024) return 16;+ return 8;+}++// Per-(device, stream) output-Hadamard arrival counters. A single device-wide+// buffer would race when two streams overlap: both kernels index the same+// segment counters and one can rotate a segment the other is still writing.+// An entry is never freed (the process owns the device); if the table fills,+// the caller falls back to the separate output Hadamard.+//+// The counter slab is preallocated and zeroed on the first eager call, then+// handed out in per-stream slices. It must never be allocated inside a+// captured stream: hipMalloc/hipMemset are not permitted during capture, and+// the block graph captures on a dedicated stream that the eager warmups never+// touch. If the slab does not exist yet while capturing, decline and let the+// caller use the plain kernel plus the separate output Hadamard.+struct SegCounterSlot+{+ int device;+ hipStream_t stream;+ int* ptr;+};++struct SegCounterPool+{+ int device;+ int* base;+ int used;+};++static bool stream_is_capturing(hipStream_t stream)+{+ hipStreamCaptureStatus status = hipStreamCaptureStatusNone;+ if (hipStreamIsCapturing(stream, &status) != hipSuccess) return false;+ return status != hipStreamCaptureStatusNone;+}++static int* seg_counters(int device, hipStream_t stream)+{+ static std::mutex mtx;+ static std::vector<SegCounterSlot> slots;+ static std::vector<SegCounterPool> pools;+ if (device < 0 || device >= 64) return nullptr;+ std::lock_guard<std::mutex> lock(mtx);+ for (const auto& s : slots)+ if (s.device == device && s.stream == stream) return s.ptr;+ if (slots.size() >= (size_t) MAX_SEG_COUNTER_STREAMS) return nullptr;++ SegCounterPool* pool = nullptr;+ for (auto& p : pools)+ if (p.device == device) { pool = &p; break; }++ if (!pool)+ {+ if (stream_is_capturing(stream)) return nullptr;+ const size_t bytes = (size_t) MAX_SEG_COUNTER_STREAMS * EXL3_GEMV_SEG_COUNTERS * sizeof(int);+ void* base = nullptr;+ if (hipMalloc(&base, bytes) != hipSuccess)+ {+ (void) hipGetLastError();+ return nullptr;+ }+ if (hipMemset(base, 0, bytes) != hipSuccess)+ {+ (void) hipGetLastError();+ hipFree(base);+ return nullptr;+ }+ pools.push_back({device, (int*) base, 0});+ pool = &pools.back();+ }++ if (pool->used >= MAX_SEG_COUNTER_STREAMS) return nullptr;+ int* p = pool->base + (size_t) pool->used * EXL3_GEMV_SEG_COUNTERS;+ pool->used++;+ slots.push_back({device, stream, p});+ return p;+}++bool exl3_gemv_rdna_arch(int device)+{+ static int cache[64] = {};+ if (device < 0 || device >= 64) return false;+ if (cache[device] < 0) return false;+ if (cache[device] > 0) return true;++ hipDeviceProp_t prop;+ if (hipGetDeviceProperties(&prop, device) != hipSuccess)+ {+ cache[device] = -1;+ return false;+ }+ // This path is tuned for gfx1200/gfx1201. Keep the arch test explicit so+ // another RDNA family is opted in only after its own measurement and+ // tuning.+ const bool ok =+ strncmp(prop.gcnArchName, "gfx1200", 7) == 0 ||+ strncmp(prop.gcnArchName, "gfx1201", 7) == 0;+ cache[device] = ok ? 1 : -1;+ return ok;+}++// -----------------------------------------------------------------------------+// Dot kernel with the output Hadamard fused into the store (one launch fewer+// than the three-kernel form; the input Hadamard stays the caller's launch).+// Every output is identical to the separate rotation: the epilogue runs the+// same arithmetic once the last of the segment's eight tiles has arrived.+// -----------------------------------------------------------------------------++template <int bits, bool c_fp32, int cb, int WARPS_PER_BLOCK>+static __global__+__launch_bounds__(WARPS_PER_BLOCK * 32)+__attribute__((amdgpu_flat_work_group_size(WARPS_PER_BLOCK * 32, WARPS_PER_BLOCK * 32)))+void exl3_gemv_rdna_dot_fused+(+ const half* __restrict__ A,+ const uint16_t* __restrict__ B,+ void* __restrict__ C,+ const half* __restrict__ svh,+ int* __restrict__ seg,+ const int size_k,+ const int size_n,+ const int core+)+{+ const int warp_id = threadIdx.x / 32;+ const int lane = threadIdx.x % 32;+ const int tile_n = blockIdx.x * WARPS_PER_BLOCK + warp_id;+ const int n_tiles = size_n / 16;+ if (tile_n >= n_tiles) return;++ extern __shared__ char shared_mem[];+ constexpr int SH_STRIDE = EXL3_GEMV_SH_STRIDE;+ half* sh_b_dq = (half*) shared_mem;+ uint16_t* sh_b_quant = (uint16_t*) (sh_b_dq + WARPS_PER_BLOCK * 16 * SH_STRIDE);+ half* my_sh_b = sh_b_dq + warp_id * 16 * SH_STRIDE;+ uint16_t* my_sh_b_quant = sh_b_quant + warp_id * EXL3_GEMV_SH_QUANT_U16;++ const float accum = exl3_gemv_dot_tile_sel<bits, cb, false, true>+ (+ core, A, B, size_k, n_tiles, tile_n, lane, my_sh_b, my_sh_b_quant,+ 0, size_k / 16+ );++ exl3_gemv_fused_epilogue<c_fp32>+ (+ accum, C, 0, tile_n, lane, svh, 0.088388347648f,+ seg + tile_n / 8+ );+}++template <int bits, bool c_fp32, int cb, int WARPS_PER_BLOCK>+static __global__+__launch_bounds__(WARPS_PER_BLOCK * 32)+__attribute__((amdgpu_flat_work_group_size(WARPS_PER_BLOCK * 32, WARPS_PER_BLOCK * 32)))+void exl3_gemv_rdna_dot_fused_splitk+(+ const half* __restrict__ A,+ const uint16_t* __restrict__ B,+ void* __restrict__ C,+ const half* __restrict__ svh,+ int* __restrict__ seg,+ const int size_k,+ const int size_n,+ const int core+)+{+ const int warp_id = threadIdx.x / 32;+ const int lane = threadIdx.x % 32;+ const int tile_n = blockIdx.x;+ const int n_tiles = size_n / 16;++ extern __shared__ char shared_mem[];+ constexpr int SH_STRIDE = EXL3_GEMV_SH_STRIDE;+ half* sh_b_dq = (half*) shared_mem;+ uint16_t* sh_b_quant = (uint16_t*) (sh_b_dq + WARPS_PER_BLOCK * 16 * SH_STRIDE);+ float* sh_red = (float*) (sh_b_quant + WARPS_PER_BLOCK * EXL3_GEMV_SH_QUANT_U16);+ half* my_sh_b = sh_b_dq + warp_id * 16 * SH_STRIDE;+ uint16_t* my_sh_b_quant = sh_b_quant + warp_id * EXL3_GEMV_SH_QUANT_U16;++ const float accum = exl3_gemv_dot_tile_splitk<bits, cb, WARPS_PER_BLOCK>+ (+ A, B, size_k, n_tiles, tile_n, warp_id, lane,+ my_sh_b, my_sh_b_quant, sh_red, core+ );++ if (warp_id != 0) return;+ exl3_gemv_fused_epilogue<c_fp32>+ (+ accum, C, 0, tile_n, lane, svh, 0.088388347648f,+ seg + tile_n / 8+ );+}++bool exl3_gemv_rdna_launch+(+ const half* A,+ const uint16_t* B,+ void* C,+ const half* svh,+ int device,+ int size_m,+ int size_k,+ int size_n,+ int K,+ int cb,+ bool c_fp32,+ hipStream_t stream,+ bool fuse_out,+ bool* out_rotated+)+{+ if (out_rotated) *out_rotated = false;+ if (K < 1 || K > 8) return false;+ if (cb < 0 || cb > 2) return false;+ if (size_m < 1 || size_m > 8) return false;+ if (size_k % 128 || size_n % 128) return false;+ if (env_int("EXL3_GEMV", 1) == 0) return false;++ const int n_tiles = size_n / 16;+ const int k_blocks = size_k / 16;+ const int core = exl3_gemv_core_mode();++ // Rows 2..8: one block per N-tile, warps split K, the decoded tile is+ // applied to every row before it is discarded. No output-Hadamard fusion+ // (the caller's had_r_128 covers all rows), so C holds the raw products.+ if (size_m > 1)+ {+ if (K < 2 || K > 6 || (cb != 1 && cb != 2)) return false;+ const int M = size_m <= 2 ? 2 : (size_m == 3 ? 3 : (size_m == 4 ? 4 : 8));+ const int warps = splitk_warps(k_blocks, n_tiles);+ const size_t smem_mr = exl3_gemv_smem_bytes_splitk_mr(warps, M);+ if (smem_mr > 64 * 1024) return false;++ #define LAUNCH_MR(bits_val, codebook, m_val, w) \+ do { \+ if (c_fp32) hipLaunchKernelGGL((exl3_gemv_dot_kernel_splitk_mr<bits_val, true, codebook, m_val, w>), \+ dim3(n_tiles), dim3(w * 32), smem_mr, stream, A, B, C, size_k, size_n, size_m, core); \+ else hipLaunchKernelGGL((exl3_gemv_dot_kernel_splitk_mr<bits_val, false, codebook, m_val, w>), \+ dim3(n_tiles), dim3(w * 32), smem_mr, stream, A, B, C, size_k, size_n, size_m, core); \+ } while (0)++ #define LAUNCH_MR_W(bits_val, codebook, m_val) \+ do { \+ if (warps == 4) LAUNCH_MR(bits_val, codebook, m_val, 4); \+ else if (warps == 8) LAUNCH_MR(bits_val, codebook, m_val, 8); \+ else if (warps == 16) LAUNCH_MR(bits_val, codebook, m_val, 16); \+ else return false; \+ } while (0)++ #define LAUNCH_MR_CB(bits_val, m_val) \+ do { \+ if (cb == 1) LAUNCH_MR_W(bits_val, 1, m_val); \+ else if (cb == 2) LAUNCH_MR_W(bits_val, 2, m_val); \+ else return false; \+ } while (0)++ #define LAUNCH_MR_K(m_val) \+ do { \+ switch (K) { \+ case 2: LAUNCH_MR_CB(2, m_val); break; \+ case 3: LAUNCH_MR_CB(3, m_val); break; \+ case 4: LAUNCH_MR_CB(4, m_val); break; \+ case 5: LAUNCH_MR_CB(5, m_val); break; \+ case 6: LAUNCH_MR_CB(6, m_val); break; \+ default: return false; \+ } \+ } while (0)++ if (M == 2) LAUNCH_MR_K(2);+ else if (M == 3) LAUNCH_MR_K(3);+ else if (M == 4) LAUNCH_MR_K(4);+ else LAUNCH_MR_K(8);++ #undef LAUNCH_MR_K+ #undef LAUNCH_MR_CB+ #undef LAUNCH_MR_W+ #undef LAUNCH_MR+ return true;+ }++ bool splitk = splitk_enabled() && n_tiles <= EXL3_GEMV_SPLITK_MAX_TILES;+ int warps = warps_for(n_tiles, k_blocks);+ int blocks = (n_tiles + warps - 1) / warps;+ size_t smem = exl3_gemv_smem_bytes(warps);+ if (splitk)+ {+ warps = splitk_warps(k_blocks, n_tiles);+ blocks = n_tiles;+ smem = exl3_gemv_smem_bytes_splitk(warps);+ }+ if (smem > 64 * 1024) return false;++ int* seg = nullptr;+ if (fuse_out && env_int("EXL3_GEMV_FUSE_OUT", 1) != 0 &&+ size_n / 128 <= EXL3_GEMV_SEG_COUNTERS)+ seg = seg_counters(device, stream);+ const bool fused = seg != nullptr;++ #define LAUNCH_FUSED(bits_val, codebook, w, kern) \+ do { \+ if (c_fp32) hipLaunchKernelGGL((kern<bits_val, true, codebook, w>), \+ dim3(blocks), dim3(w * 32), smem, stream, A, B, C, svh, seg, \+ size_k, size_n, core); \+ else hipLaunchKernelGGL((kern<bits_val, false, codebook, w>), \+ dim3(blocks), dim3(w * 32), smem, stream, A, B, C, svh, seg, \+ size_k, size_n, core); \+ } while (0)++ #define LAUNCH_PLAIN_K(bits_val, codebook, w, kern) \+ do { \+ if (c_fp32) hipLaunchKernelGGL((kern<bits_val, true, codebook, w>), \+ dim3(blocks), dim3(w * 32), smem, stream, A, B, C, size_k, size_n, core); \+ else hipLaunchKernelGGL((kern<bits_val, false, codebook, w>), \+ dim3(blocks), dim3(w * 32), smem, stream, A, B, C, size_k, size_n, core); \+ } while (0)++ #define LAUNCH_FOR_W(bits_val, codebook, w, fused_kern, plain_kern) \+ do { \+ if (w != 4 && w != 8 && w != 16) return false; \+ if (fused) \+ { \+ if (w == 4) LAUNCH_FUSED(bits_val, codebook, 4, fused_kern); \+ if (w == 8) LAUNCH_FUSED(bits_val, codebook, 8, fused_kern); \+ if (w == 16) LAUNCH_FUSED(bits_val, codebook, 16, fused_kern); \+ } \+ else \+ { \+ if (w == 4) LAUNCH_PLAIN_K(bits_val, codebook, 4, plain_kern); \+ if (w == 8) LAUNCH_PLAIN_K(bits_val, codebook, 8, plain_kern); \+ if (w == 16) LAUNCH_PLAIN_K(bits_val, codebook, 16, plain_kern); \+ } \+ } while (0)++ #define LAUNCH_CB(bits_val, codebook) \+ do { \+ if (splitk) LAUNCH_FOR_W(bits_val, codebook, warps, \+ exl3_gemv_rdna_dot_fused_splitk, exl3_gemv_dot_kernel_splitk); \+ else LAUNCH_FOR_W(bits_val, codebook, warps, \+ exl3_gemv_rdna_dot_fused, exl3_gemv_dot_kernel); \+ } while (0)++ #define LAUNCH_BITS(bits_val) \+ do { \+ switch (cb) { \+ case 0: LAUNCH_CB(bits_val, 0); break; \+ case 1: LAUNCH_CB(bits_val, 1); break; \+ case 2: LAUNCH_CB(bits_val, 2); break; \+ default: return false; \+ } \+ } while (0)++ switch (K)+ {+ case 1: LAUNCH_BITS(1); break;+ case 2: LAUNCH_BITS(2); break;+ case 3: LAUNCH_BITS(3); break;+ case 4: LAUNCH_BITS(4); break;+ case 5: LAUNCH_BITS(5); break;+ case 6: LAUNCH_BITS(6); break;+ case 7: LAUNCH_BITS(7); break;+ case 8: LAUNCH_BITS(8); break;+ default: return false;+ }++ #undef LAUNCH_BITS+ #undef LAUNCH_CB+ #undef LAUNCH_FOR_W+ #undef LAUNCH_PLAIN_K+ #undef LAUNCH_FUSED++ // Publish only now: every LAUNCH_* path above can return false, and the+ // caller must fall back and still run its output Hadamard in that case.+ if (out_rotated) *out_rotated = fused;++ return true;+}++#endif // USE_ROCMdiff --git a/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_rdna.cuh b/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_rdna.cuhnew file mode 100644index 0000000..7accc88--- /dev/null+++ b/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_rdna.cuh@@ -0,0 +1,50 @@+#pragma once++// RDNA (gfx1200/gfx1201) fdot2 GEMV for the dense single-matrix forms:+// M == 1, and M == 2..8 split-K.+//+// The generic GEMV kernel (quant/exl3_gemv_kernel.cuh) is built on m16n8k16+// mma.sync and reaches 107-220 GB/s on the small dense shapes on gfx1201.+// The RDNA dot core here runs one warp per 16-wide output tile and consumes+// the decoded trellis through V_DOT2_F32_F16, which sustains 1.3x that on the+// same shapes (measured against upstream exllamav3 v1.6.6). For M == 1 the+// output Hadamard is fused into the store epilogue when the per-device+// segment counters fit the width; otherwise, and for every M == 2..8 call,+// the input and output Hadamards stay the caller's had_r_128 launches.++#if defined(USE_ROCM)++#include <cstdint>+#include <cuda_fp16.h>+#include <hip/hip_runtime.h>++// True on gfx1200/gfx1201 (the parts whose decode was measured with this core)+bool exl3_gemv_rdna_arch(int device);++// Launch the dot kernel for M == 1..8. A is the already-rotated input+// (A_had), B is the trellis. For M == 1, with fuse_out and room in the+// per-device segment counters, C receives the finished output (output+// Hadamard applied) and *out_rotated is set; otherwise C holds the+// pre-rotation values and the caller applies the output Hadamard. M > 1+// always returns *out_rotated = false, so the caller rotates the whole C.+// Returns false when the shape is outside the kernel's hard constraints,+// leaving nothing launched (and *out_rotated = false).+bool exl3_gemv_rdna_launch+(+ const half* A,+ const uint16_t* B,+ void* C,+ const half* svh,+ int device,+ int size_m,+ int size_k,+ int size_n,+ int K,+ int cb,+ bool c_fp32,+ hipStream_t stream,+ bool fuse_out,+ bool* out_rotated+);++#endif // USE_ROCMdiff --git a/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_tiles_rdna.cuh b/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_tiles_rdna.cuhnew file mode 100644index 0000000..00fac01--- /dev/null+++ b/exllamav3/exllamav3_ext/rocm/quant/exl3_gemv_tiles_rdna.cuh@@ -0,0 +1,623 @@+#pragma once++// =============================================================================+// EXL3 GEMV "tiles" core for RDNA: fewer VALU cycles per 16x16 weight tile+// =============================================================================+//+// Drop-in replacement for the barrier-free dot core (exl3_gemv_dot_tile_direct+// and its multi-row form exl3_gemv_dot_tile_direct_mr): same lane layout, same+// per-lane fdot2 chains in the same order, same quad reduction -- so every+// output is BIT-IDENTICAL to the core it replaces. Only the instruction+// sequence that produces the decoded weights and the addresses changes.+//+// Why: the decode GEMVs had the VALU as the binding unit, not DRAM. Per 16x16+// tile per lane the old K=2 loop spent:+// 8 x v_mul_lo_u32 (hash multiply) QUARTER rate+// 8 x v_dot4_u32_u8 (byte sum) HALF rate+// v_lshrrev_b64 (fshift)+// 64-bit per-lane address math + a divergent (exec-mask) loop+// bfe / and / lshl_or packing / pk_fma / dot2+// (add, bfe, perm, alignbit, sad_u8, sad_hi_u8, mad_u32_u16, pk_mul_lo_u16 and+// dot2_f32_f16 issue at full rate.)+//+// The rewrite, each step exact integer arithmetic:+//+// hash multiply P = x * C mod 2^32 for a 16-bit x (x < 2^16):+// P = x * C_lo16 + ((x * C_hi16) mod 2^16) << 16+// r = v_pk_mul_lo_u16 src, [0 | C_hi16] (op_sel picks x's+// half of src for the high lane; the low lane is x*0 = 0)+// P = v_mad_u32_u16 src, C_lo16, r (op_sel picks x)+// two full-rate ops for one quarter-rate op. x may sit in+// either 16-bit half of a register, so a window that starts+// at bit 0 or 16 of an aligned word needs no extraction op+// and the rest need one shift (no mask: the u16 operand+// ignores the upper bits). The cb 0 additive constant rides in+// the same two ops via v_pk_mad_u16.+// byte sum v_sad_u8 (P, 0, acc) is sum|P_i - 0| + acc, the dp4a-by-ones+// sum at full rate; v_sad_hi_u8 adds the second sum << 16, so+// a decoded PAIR comes out already packed as [0x6400 + s0 |+// 0x6400 + s1] -- no and / lshl_or packing (mul1, cb 2).+// fshift one v_alignbit_b32 (the shift is < 32 for the aligned+// layouts) instead of a 64-bit shift.+// addressing the tile base is wave-uniform (readfirstlane'd warp index,+// block indices, pointer from the parameter tables), so the+// loop runs on SGPR base pointers with a constant 32-bit+// per-lane offset: global_load vN, vOff, s[base:base+1]+// offset:imm, a scalar loop counter and s_cbranch_scc, zero+// VALU address math per tile.+//+// K = 1, 2, 4 take the hand-laid aligned decoders; K = 3, 5..8 run the generic+// dq8 / dq4 / dq2x2 bit arithmetic of quant/exl3_dq.cuh (unchanged) with the+// fast pair decoder and the uniform addressing.+//+// Selected at runtime (exl3_gemv_core_mode(), EXL3_ROCM_GEMV_TILES=0 selects+// the direct core; EXL3_GEMV_LDS=1 still pins the LDS core).+//+// Portability: v_pk_mul_lo_u16 / v_pk_mad_u16 (VOP3P), v_mad_u32_u16 with+// op_sel, v_sad_u8 / v_sad_hi_u8 exist on gfx10.3+, gfx11 and gfx12 with the+// same syntax.+// =============================================================================++#include <hip/hip_runtime.h>+#include <hip/hip_fp16.h>+#include "../../quant/hadamard_inner.cuh"+#include "../../quant/exl3_dq.cuh"+#include "../../port.cuh"++// Kyojin's portable helpers under the upstream names used by the ROCm GEMV+// core (exllamav3_ext/port.cuh, exllamav3_ext/quant/codebook.cuh)+#define exl3_fdot2(a, b, c) PORT_FDOT2_F32(a, b, c)+#define exl3_lop3_6a(a, b, c) lop3_0x6a(a, b, c)++#define EXL3_GEMV_CORE_DIRECT 0 // barrier-free direct core+#define EXL3_GEMV_CORE_LDS 1 // LDS unswizzle core (EXL3_GEMV_LDS=1)+#define EXL3_GEMV_CORE_TILES 2 // this file (default)++typedef __attribute__((address_space(1))) const uint32_t exl3_g_u32;+typedef __attribute__((address_space(3))) const uint32_t exl3_l_u32;++// -----------------------------------------------------------------------------+// Wave-uniform helpers+// -----------------------------------------------------------------------------++__device__ __forceinline__ int exl3_uni(int x)+{+ return __builtin_amdgcn_readfirstlane(x);+}++template <typename T>+__device__ __forceinline__ T* exl3_uni_ptr(T* p)+{+ uint64_t v = (uint64_t) p;+ uint32_t lo = __builtin_amdgcn_readfirstlane((uint32_t) v);+ uint32_t hi = __builtin_amdgcn_readfirstlane((uint32_t) (v >> 32));+ return (T*) (((uint64_t) hi << 32) | (uint64_t) lo);+}++// -----------------------------------------------------------------------------+// Hash multiply: x * C (+ D) mod 2^32 for the 16-bit x in the low (HI = false)+// or high (HI = true) half of src+// -----------------------------------------------------------------------------++template <uint32_t C, uint32_t D, bool HI>+__device__ __forceinline__ uint32_t exl3_hmul16(uint32_t src)+{+ constexpr uint32_t k_hi = C & 0xffff0000u; // [0 | C_hi16]+ constexpr uint32_t c_lo = C & 0xffffu;+ uint32_t r, p;+ if constexpr (D == 0)+ {+ // r = [src.x * 0 | src.x * C_hi16]+ if constexpr (HI)+ asm ("v_pk_mul_lo_u16 %0, %1, %2" : "=v"(r) : "v"(src), "s"(k_hi));+ else+ asm ("v_pk_mul_lo_u16 %0, %1, %2 op_sel_hi:[0,1]" : "=v"(r) : "v"(src), "s"(k_hi));+ }+ else+ {+ // r = [D_lo16 | src.x * C_hi16 + D_hi16]+ constexpr uint32_t d = D;+ if constexpr (HI)+ asm ("v_pk_mad_u16 %0, %1, %2, %3" : "=v"(r) : "v"(src), "s"(k_hi), "s"(d));+ else+ asm ("v_pk_mad_u16 %0, %1, %2, %3 op_sel_hi:[0,1,1]" : "=v"(r) : "v"(src), "s"(k_hi), "s"(d));+ }+ // p = src.x * C_lo16 + r (32-bit, carries included)+ if constexpr (HI)+ asm ("v_mad_u32_u16 %0, %1, %2, %3 op_sel:[1,0,0,0]" : "=v"(p) : "v"(src), "s"(c_lo), "v"(r));+ else+ asm ("v_mad_u32_u16 %0, %1, %2, %3" : "=v"(p) : "v"(src), "s"(c_lo), "v"(r));+ return p;+}++template <int cb, bool HI>+__device__ __forceinline__ uint32_t exl3_hash16(uint32_t src)+{+ if constexpr (cb == 0) return exl3_hmul16<89226354u, 64248484u, HI>(src);+ if constexpr (cb == 1) return exl3_hmul16<0xCBAC1FEDu, 0u, HI>(src);+ if constexpr (cb == 2) return exl3_hmul16<0x83DCD12Du, 0u, HI>(src);+ return 0;+}++// Two hashed words -> the decoded pair (lo = word 0, hi = word 1), bit for bit+// decode_3inst_2<cb> of the same two 16-bit indices.+template <int cb>+__device__ __forceinline__ half2 exl3_decode_pair(uint32_t p0, uint32_t p1)+{+ if constexpr (cb == 2)+ {+ uint32_t s = __builtin_amdgcn_sad_u8(p0, 0u, 0x64006400u);+ s = __builtin_amdgcn_sad_hi_u8(p1, 0u, s);+ half2_uint32 u(s);+ const half2 k_inv_h2 = __half2half2(__ushort_as_half(0x1eee));+ const half2 k_bias_h2 = __half2half2(__ushort_as_half(0xc931));+ return __hfma2(u.as_half2, k_inv_h2, k_bias_h2);+ }+ else+ {+ p0 = exl3_lop3_6a(p0, 0x8fff8fffu, 0x3b603b60u);+ p1 = exl3_lop3_6a(p1, 0x8fff8fffu, 0x3b603b60u);+ half2_uint32 xu0(p0);+ half2_uint32 xu1(p1);+ half2 d0 = __lows2half2(xu0.as_half2, xu1.as_half2);+ half2 d1 = __highs2half2(xu0.as_half2, xu1.as_half2);+ return __hadd2(d0, d1);+ }+}++// Pair decode from two sources, each 16-bit index in the low half (or high,+// per the flags) of its register+template <int cb, bool HI0, bool HI1>+__device__ __forceinline__ half2 exl3_dq_pair(uint32_t src0, uint32_t src1)+{+ return exl3_decode_pair<cb>(exl3_hash16<cb, HI0>(src0), exl3_hash16<cb, HI1>(src1));+}++// Generic form for the dq8/dq4/dq2x2 paths: indices in the low halves+template <int cb>+__device__ __forceinline__ half2 exl3_decode_3inst_2_fast(uint32_t w0, uint32_t w1)+{+ return exl3_dq_pair<cb, false, false>(w0, w1);+}+++template <int bits>+struct Exl3Width+{+ static constexpr int tile_bytes = 32 * bits; // bytes per 16x16 tile+ static constexpr int tile_u16 = tile_bytes / 2;+};++// -----------------------------------------------------------------------------+// Per-lane load plan: which dwords of a tile lane L reads, fixed for the loop+// -----------------------------------------------------------------------------+// A tile is 8 * bits dwords. Lane L (t_offset = 8 L) reads R dwords of it and+// decodes its 8 weights from those alone. The plan holds byte offsets from the+// tile base (constant over the loop, so the loads are SGPR base + one VGPR+// offset) and the funnel shifts. Load and decode are split so the loop can put+// several k-tiles' loads in flight before the first decode.+//+// bits 1, 2, 4 aligned decoders: 2 dwords, one shift (< 32)+// bits 3 dq8<3, cb, 4>: 2 dwords+// bits 5, 6, 8 dq4 x 2: 4 dwords+// bits 7 dq2x2 x 2: 8 dwords+// half K + 0.5 dq8_half: 4 dwords (two window groups of two), shifts < 32++template <int bits> struct Exl3RawCount { static constexpr int R = (bits <= 4) ? 2 : (bits == 7 ? 8 : 4); };++template <int bits>+struct Exl3LanePlan+{+ static constexpr int R = Exl3RawCount<bits>::R;+ uint32_t off[R]; // byte offsets within the tile; off[2i] = "a" (hi), off[2i+1] = "b" (lo)+ int sh[R / 2]; // funnel shift (aligned forms) or s2 (generic forms)+};++// Index helpers shared by plan and decode for the generic forms (the+// arithmetic of quant/exl3_dq.cuh's dq8 / dq4 / dq2x2)+template <int bits>+__device__ __forceinline__ void exl3_dq4_idx(int t_offset, int& i0, int& i2, int& s2)+{+ int b0 = (t_offset + 257) * bits - 16;+ int b1 = b0 + 3 * bits;+ int b2 = b1 + 16;+ i0 = (b0 / 32) % (bits * 256 / 32);+ s2 = ((b2 - 1) / 32 + 1) * 32 - b2;+ i2 = ((b2 - 1) / 32) % (bits * 256 / 32);+}++template <int bits>+__device__ __forceinline__ void exl3_dq2_idx(int t_offset, int& i0, int& i2, int& s2)+{+ int b0 = (t_offset + 257) * bits - 16;+ int b1 = b0 + 1 * bits;+ int b2 = b1 + 16;+ i0 = (b0 / 32) % (bits * 256 / 32);+ s2 = ((b2 - 1) / 32 + 1) * 32 - b2;+ i2 = ((b2 - 1) / 32) % (bits * 256 / 32);+}++template <int bits>+__device__ __forceinline__ void exl3_dq8_idx(int t_offset, int& i0, int& i2, int& s2)+{+ int b1 = (t_offset + 257) * bits;+ int b0 = b1 - 16;+ int b2 = b1 + bits * 7;+ i0 = (b0 / 32) % (bits * 256 / 32);+ s2 = ((b2 - 1) / 32 + 1) * 32 - b2;+ i2 = ((b2 - 1) / 32) % (bits * 256 / 32);+}++template <int bits>+__device__ __forceinline__ Exl3LanePlan<bits> exl3_lane_plan(int lane)+{+ Exl3LanePlan<bits> p;+ const int t_offset = lane << 3;+ if constexpr (bits == 1)+ {+ int i1 = t_offset >> 5;+ p.off[1] = i1 * 4;+ p.off[0] = ((i1 + 7) & 7) * 4;+ p.sh[0] = (~t_offset) & 24;+ }+ else if constexpr (bits == 2)+ {+ int i1 = t_offset >> 4;+ p.off[1] = i1 * 4;+ p.off[0] = ((i1 + 15) & 15) * 4;+ p.sh[0] = ((~t_offset) & 8) << 1;+ }+ else if constexpr (bits == 4)+ {+ int i1 = t_offset >> 3;+ p.off[1] = i1 * 4;+ p.off[0] = ((i1 + 31) & 31) * 4;+ p.sh[0] = 20;+ }+ else if constexpr (bits == 3)+ {+ int i0, i2, s2;+ exl3_dq8_idx<bits>(t_offset, i0, i2, s2);+ p.off[0] = i0 * 4; p.off[1] = i2 * 4; p.sh[0] = s2;+ }+ else if constexpr (bits == 7)+ {+ #pragma unroll+ for (int h = 0; h < 2; ++h)+ #pragma unroll+ for (int i = 0; i < 2; ++i)+ {+ int i0, i2, s2;+ exl3_dq2_idx<bits>(t_offset + 4 * h + 2 * i, i0, i2, s2);+ p.off[(h * 2 + i) * 2] = i0 * 4; p.off[(h * 2 + i) * 2 + 1] = i2 * 4; p.sh[h * 2 + i] = s2;+ }+ }+ else+ {+ #pragma unroll+ for (int h = 0; h < 2; ++h)+ {+ int i0, i2, s2;+ exl3_dq4_idx<bits>(t_offset + 4 * h, i0, i2, s2);+ p.off[h * 2] = i0 * 4; p.off[h * 2 + 1] = i2 * 4; p.sh[h] = s2;+ }+ }+ return p;+}++// Aligned decoders, from the two loaded dwords. Word k is decoded exactly as+// dq8_aligned_{1bit,2bits,4bits}: w7 at bit 0 of the funnel result, w(7-i) at+// bit i*bits; frag0 = (w0,w1),(w2,w3), frag1 = (w4,w5),(w6,w7).++template <int cb>+__device__ __forceinline__ void exl3_dq8_2bits_fast(uint32_t a, uint32_t b, int shift, FragB& frag0, FragB& frag1)+{+ b = __funnelshift_r(b, a, shift); // shift is 0 or 16: one v_alignbit+ frag0[0] = exl3_dq_pair<cb, false, false>(b >> 14, b >> 12);+ frag0[1] = exl3_dq_pair<cb, false, false>(b >> 10, b >> 8);+ frag1[0] = exl3_dq_pair<cb, false, false>(b >> 6, b >> 4);+ frag1[1] = exl3_dq_pair<cb, false, false>(b >> 2, b);+}++template <int cb>+__device__ __forceinline__ void exl3_dq8_1bit_fast(uint32_t a, uint32_t b, int shift, FragB& frag0, FragB& frag1)+{+ b = __funnelshift_r(b, a, shift); // shift in {0, 8, 16, 24}+ frag0[0] = exl3_dq_pair<cb, false, false>(b >> 7, b >> 6);+ frag0[1] = exl3_dq_pair<cb, false, false>(b >> 5, b >> 4);+ frag1[0] = exl3_dq_pair<cb, false, false>(b >> 3, b >> 2);+ frag1[1] = exl3_dq_pair<cb, false, false>(b >> 1, b);+}++template <int cb>+__device__ __forceinline__ void exl3_dq8_4bits_fast(uint32_t a, uint32_t b, FragB& frag0, FragB& frag1)+{+ uint32_t s = __funnelshift_r(b, a, 20);+ // w0..w2 from s (bits 8, 4, 0), w3..w7 from b (bits 16, 12, 8, 4, 0);+ // the bit-16 window is b's high half (no extraction op)+ frag0[0] = exl3_dq_pair<cb, false, false>(s >> 8, s >> 4);+ frag0[1] = exl3_dq_pair<cb, false, true >(s, b);+ frag1[0] = exl3_dq_pair<cb, false, false>(b >> 12, b >> 8);+ frag1[1] = exl3_dq_pair<cb, false, false>(b >> 4, b);+}++// Generic widths: dq8<3, cb, 4>, dq4, dq2 bit arithmetic verbatim (fshift is+// the 64-bit funnel there: s2 + bits * k can exceed 31), fast pair decoder.++template <int bits, int cb>+__device__ __forceinline__ void exl3_dq8_3bits_fast(uint32_t a, uint32_t b, int s2, FragB& frag0, FragB& frag1)+{+ uint32_t w0, w1, w2, w3, w4, w5, w6, w7;+ w7 = fshift(b, a, s2);+ w6 = w7 >> bits;+ w5 = w6 >> bits;+ w4 = w5 >> bits;+ w3 = fshift(b, a, s2 + bits * 4);+ w2 = w3 >> bits;+ w1 = w2 >> bits;+ w0 = w1 >> bits;+ frag0[0] = exl3_decode_3inst_2_fast<cb>(w0, w1);+ frag0[1] = exl3_decode_3inst_2_fast<cb>(w2, w3);+ frag1[0] = exl3_decode_3inst_2_fast<cb>(w4, w5);+ frag1[1] = exl3_decode_3inst_2_fast<cb>(w6, w7);+}++template <int bits, int cb>+__device__ __forceinline__ void exl3_dq4_fast(uint32_t a, uint32_t b, int s2, FragB& frag)+{+ uint32_t w3 = fshift(b, a, s2);+ uint32_t w2 = fshift(b, a, s2 + bits);+ uint32_t w1 = fshift(b, a, s2 + bits * 2);+ uint32_t w0 = fshift(b, a, s2 + bits * 3);+ frag[0] = exl3_decode_3inst_2_fast<cb>(w0, w1);+ frag[1] = exl3_decode_3inst_2_fast<cb>(w2, w3);+}++template <int bits, int cb>+__device__ __forceinline__ half2 exl3_dq2_fast(uint32_t a, uint32_t b, int s2)+{+ uint32_t w1 = fshift(b, a, s2);+ uint32_t w0 = fshift(b, a, s2 + bits);+ return exl3_decode_3inst_2_fast<cb>(w0, w1);+}++template <int bits, int cb>+__device__ __forceinline__ void exl3_dq_tile_decode+(+ const uint32_t* raw, // R dwords, plan order+ const Exl3LanePlan<bits>& lp,+ FragB& frag0,+ FragB& frag1+)+{+ if constexpr (bits == 1) exl3_dq8_1bit_fast<cb>(raw[0], raw[1], lp.sh[0], frag0, frag1);+ else if constexpr (bits == 2) exl3_dq8_2bits_fast<cb>(raw[0], raw[1], lp.sh[0], frag0, frag1);+ else if constexpr (bits == 4) exl3_dq8_4bits_fast<cb>(raw[0], raw[1], frag0, frag1);+ else if constexpr (bits == 3) exl3_dq8_3bits_fast<bits, cb>(raw[0], raw[1], lp.sh[0], frag0, frag1);+ else if constexpr (bits == 7)+ {+ frag0[0] = exl3_dq2_fast<bits, cb>(raw[0], raw[1], lp.sh[0]);+ frag0[1] = exl3_dq2_fast<bits, cb>(raw[2], raw[3], lp.sh[1]);+ frag1[0] = exl3_dq2_fast<bits, cb>(raw[4], raw[5], lp.sh[2]);+ frag1[1] = exl3_dq2_fast<bits, cb>(raw[6], raw[7], lp.sh[3]);+ }+ else+ {+ exl3_dq4_fast<bits, cb>(raw[0], raw[1], lp.sh[0], frag0);+ exl3_dq4_fast<bits, cb>(raw[2], raw[3], lp.sh[1], frag1);+ }+}++// Loads through a wave-uniform base + per-lane 32-bit byte offset+typedef __attribute__((address_space(1))) const char exl3_g_char;+typedef __attribute__((address_space(3))) const char exl3_l_char;++__device__ __forceinline__ uint32_t exl3_ld_g(exl3_g_char* base, uint32_t off)+{+ return *(exl3_g_u32*) (base + off);+}++__device__ __forceinline__ uint32_t exl3_ld_l(const char* base, uint32_t off)+{+ return *(exl3_l_u32*) ((exl3_l_char*) base + off);+}++// -----------------------------------------------------------------------------+// The core: M rows, one N-tile, k16-tiles [kb_begin, kb_end)+// -----------------------------------------------------------------------------+// A: this slab's rotated rows (lda halves apart), in global memory (A_LDS =+// false) or LDS (true). B: the matrix's trellis. All pointer and range+// arguments must be wave-uniform (the callers pass block indices, kernel+// arguments, and exl3_uni()'d warp indices). out[r]: row r's column-lane value+// (lanes 0-15), exactly exl3_gemv_dot_tile_direct_mr's contract.+//+// U k-tiles are loaded before the first is decoded (their loads in flight+// together), then decoded and accumulated in k order, so the fdot2 chains are+// the same instruction sequence as U = 1. The remainder runs at U = 1.++// Keeps a loop-invariant lane offset opaque inside the loop. Without it LICM+// hoists the zero-extension of the 32-bit offset out of the loop and+// instruction selection, seeing a bare 64-bit VGPR add, emits two VALU ops of+// address arithmetic per load instead of the global_load saddr form (SGPR+// base + 32-bit VGPR offset + immediate). The asm is empty; the register is+// carried through it unchanged, so it costs nothing.+__device__ __forceinline__ void exl3_opaque(uint32_t& v)+{+ asm volatile ("" : "+v"(v));+}++template <int bits, int cb, int M, bool A_LDS, int U, int T>+__device__ __forceinline__ void exl3_tiles_step+(+ const char* A_c, // byte pointer, this k-group's first slice (uniform)+ const uint32_t* a_row, // per-row byte offsets from A_c (M, uniform)+ exl3_g_char* b_c, // byte pointer, this k-group's first tile (uniform)+ const uint32_t b_stride, // bytes between consecutive k-tiles of this N-tile+ uint32_t* off, // lane plan byte offsets (R), loop-invariant+ uint32_t& a_off, // lane's A byte offset within a slice+ const Exl3LanePlan<bits>& lp,+ float* accA, // [T][M]+ float* accB+)+{+ constexpr int R = Exl3LanePlan<bits>::R;+ constexpr int tile_bytes = Exl3Width<bits>::tile_bytes;+ #pragma unroll+ for (int i = 0; i < R; ++i) exl3_opaque(off[i]);+ exl3_opaque(a_off);++ uint32_t raw[U][T][R];+ uint32_t w01[U][M], w89[U][M];+ #pragma unroll+ for (int u = 0; u < U; ++u)+ #pragma unroll+ for (int t = 0; t < T; ++t)+ #pragma unroll+ for (int i = 0; i < R; ++i)+ raw[u][t][i] = exl3_ld_g(b_c + (size_t) u * b_stride + t * tile_bytes, off[i]);+ #pragma unroll+ for (int u = 0; u < U; ++u)+ #pragma unroll+ for (int r = 0; r < M; ++r)+ {+ const char* a = A_c + a_row[r] + u * 32;+ if constexpr (A_LDS) { w01[u][r] = exl3_ld_l(a, a_off); w89[u][r] = exl3_ld_l(a + 16, a_off); }+ else { w01[u][r] = exl3_ld_g((exl3_g_char*) a, a_off); w89[u][r] = exl3_ld_g((exl3_g_char*) a + 16, a_off); }+ }+ #pragma unroll+ for (int u = 0; u < U; ++u)+ #pragma unroll+ for (int t = 0; t < T; ++t)+ {+ FragB frag0, frag1;+ exl3_dq_tile_decode<bits, cb>(raw[u][t], lp, frag0, frag1);+ #pragma unroll+ for (int r = 0; r < M; ++r)+ {+ half2_uint32 a01(w01[u][r]);+ half2_uint32 a89(w89[u][r]);+ float& aA = accA[t * M + r];+ float& aB = accB[t * M + r];+ aA = exl3_fdot2(a01.as_half2, frag0[0], aA);+ aA = exl3_fdot2(a89.as_half2, frag0[1], aA);+ aB = exl3_fdot2(a01.as_half2, frag1[0], aB);+ aB = exl3_fdot2(a89.as_half2, frag1[1], aB);+ }+ }+}++// T adjacent N-tiles [tile_n, tile_n + T) per wave, sharing the A loads and+// reading T * 32 * bits contiguous bytes per k-tile. out[t * M + r]. A holds+// rows_valid rows (<= M, the row tile): the rows past it re-read the last+// valid row, so the tile never touches memory beyond A's rows_valid rows+// (the caller discards their outputs).+template <int bits, int cb, int M, bool A_LDS, int U = 1, int T = 1>+__device__ __forceinline__ void exl3_gemv_dot_tile_tiles+(+ const half* __restrict__ A,+ const int lda,+ const uint16_t* __restrict__ B,+ const int n_tiles,+ const int tile_n,+ const int lane,+ const int kb_begin,+ const int kb_end,+ float* out,+ const int rows_valid = M+)+{+ // Every argument but lane is wave-uniform by contract; say so, so the+ // tile base and the loop live in SGPRs (the callers' warp index is a+ // VGPR value to the compiler).+ A = exl3_uni_ptr(A);+ B = exl3_uni_ptr(B);+ const int n_tiles_u = exl3_uni(n_tiles);+ const int tile_n_u = exl3_uni(tile_n);+ const int kb_begin_u = exl3_uni(kb_begin);+ const int kb_end_u = exl3_uni(kb_end);+ const int lda_u = exl3_uni(lda);++ constexpr int tile_bytes = Exl3Width<bits>::tile_bytes;+ const Exl3LanePlan<bits> lp = exl3_lane_plan<bits>(lane);+ constexpr int R = Exl3LanePlan<bits>::R;+ uint32_t off[R];+ #pragma unroll+ for (int i = 0; i < R; ++i) off[i] = lp.off[i];+ uint32_t a_off = (uint32_t) (lane & 3) * 4; // (A[r0], A[r0+1]) within a k16 slice++ float accA[T * M], accB[T * M];+ #pragma unroll+ for (int r = 0; r < T * M; ++r) { accA[r] = 0.0f; accB[r] = 0.0f; }++ const uint32_t b_stride = (uint32_t) n_tiles_u * tile_bytes;+ exl3_g_char* b_c = (exl3_g_char*) (const char*) B + ((size_t) kb_begin_u * n_tiles_u + tile_n_u) * tile_bytes;+ const char* a_c = (const char*) (A + kb_begin_u * 16);+ const int lda_b = lda_u * 2;+ const int row_last = exl3_uni(rows_valid) - 1;+ uint32_t a_row[M];+ #pragma unroll+ for (int r = 0; r < M; ++r) a_row[r] = (uint32_t) ((r < row_last ? r : row_last) * lda_b);++ int k = kb_begin_u;+ if constexpr (U > 1)+ {+ for (; k + U <= kb_end_u; k += U)+ {+ exl3_tiles_step<bits, cb, M, A_LDS, U, T>(a_c, a_row, b_c, b_stride, off, a_off, lp, accA, accB);+ b_c += (size_t) U * b_stride;+ a_c += U * 32;+ }+ }+ for (; k < kb_end_u; k++)+ {+ exl3_tiles_step<bits, cb, M, A_LDS, 1, T>(a_c, a_row, b_c, b_stride, off, a_off, lp, accA, accB);+ b_c += b_stride;+ a_c += 32;+ }++ #pragma unroll+ for (int r = 0; r < T * M; ++r)+ {+ accA[r] += __shfl_xor(accA[r], 1, 32);+ accA[r] += __shfl_xor(accA[r], 2, 32);+ accB[r] += __shfl_xor(accB[r], 1, 32);+ accB[r] += __shfl_xor(accB[r], 2, 32);+ float vA = __shfl(accA[r], (lane & 7) * 4, 32);+ float vB = __shfl(accB[r], (lane & 7) * 4, 32);+ out[r] = (lane & 8) ? vB : vA;+ }+}++// -----------------------------------------------------------------------------+// Per-architecture tile shape+// -----------------------------------------------------------------------------+// U: k-tiles whose loads are issued together (device, compile time); all+// instantiations here are T = 1 (one N-tile per wave):+//+// K=1-3 K=4 K=5-6 K=7-8+// split-K, T = 1 U4 U2 U2 U1+// single-warp (head) U4 U2 U4 U1+// rows M = 8: U1 (register budget)+//+// All RDNA3/4 parts take the same values -- they share the wave32 VMEM/VALU+// structure; only the DRAM latency/bandwidth ratio that sets the best U+// differs. The VGPR count stays <= 64 for every entry, so occupancy is not+// what the table trades.++#define EXL3_GEMV_TILES_TMAX 1++template <int bits, int M, int T>+__device__ __forceinline__ constexpr int exl3_tiles_u_splitk()+{+#if defined(__gfx1151__) || defined(__gfx1150__) || 1 /* all RDNA */+ if constexpr (M >= 8) return 1;+ if constexpr (T >= 2) return (bits <= 3) ? 2 : 1;+ return (bits <= 3) ? 4 : (bits <= 6 ? 2 : 1);+#endif+}++template <int bits>+__device__ __forceinline__ constexpr int exl3_tiles_u_single()+{+ return (bits <= 3) ? 4 : (bits == 4 ? 2 : (bits <= 6 ? 4 : 1));+}diff --git a/exllamav3/modules/attention_fn/qdec_hip.py b/exllamav3/modules/attention_fn/qdec_hip.pyindex 9bd8120..58cfbd5 100644--- a/exllamav3/modules/attention_fn/qdec_hip.py+++ b/exllamav3/modules/attention_fn/qdec_hip.py@@ -19,11 +19,11 @@ _SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qdec.hip")_CACHE = os.path.expanduser(os.environ.get("EXL3_QDEC_CACHE", "~/.cache/exllamav3"))-def _gfx115_family0() -> bool:- """qdec.hip uses gfx11.5-only (RDNA3.5) wave32 WMMA; enable it only when device 0 is that- family. On a mixed gfx1201+gfx1151 box (RX 9070 exposed as device 0) quantized-KV decode- keeps the Triton fallback (triton_paged.py) instead of trying to compile gfx11.5 WMMA for- gfx1201. An extension without the family probe keeps the historical behavior."""+def _gfx115_family(device=None) -> bool:+ """qdec.hip uses gfx11.5-only (RDNA3.5) wave32 WMMA; enable it only on that family.+ The check is per call, not per process: on a mixed gfx1201+gfx1151 box the model+ device may be index 1 while device 0 is the other part. An extension without the+ family probe keeps the historical behavior."""if not torch.version.hip:return Falsetry:@@ -33,18 +33,24 @@ def _gfx115_family0() -> bool:if not hasattr(ext, "exl3_gemv_wmma_family"):return Truetry:- return ext.exl3_gemv_wmma_family(0) == 2+ if device is None:+ idx = torch.cuda.current_device()+ elif isinstance(device, torch.device):+ idx = device.index if device.index is not None else torch.cuda.current_device()+ else:+ idx = int(device)+ return ext.exl3_gemv_wmma_family(idx) == 2except Exception: # noqa: BLE001return False-ENABLED = bool(torch.version.hip) and _gfx115_family0() and knob_on("EXL3_QDEC_HIP")+ENABLED = bool(torch.version.hip) and knob_on("EXL3_QDEC_HIP")@on_changedef _refresh_knobs():global ENABLED- ENABLED = bool(torch.version.hip) and _gfx115_family0() and knob_on("EXL3_QDEC_HIP")+ ENABLED = bool(torch.version.hip) and knob_on("EXL3_QDEC_HIP")_kernels = {}_bufs = {}@@ -91,10 +97,11 @@ def geometry(hd, nqh, nkv, qlen, nw, dw, smm = 0, sxmul = 0):def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size, causal, sm_scale,- window_left, window_right, softcap, kv_append_len, has_sinks, key_lo = 0, tq = False, bsz = 1):+ window_left, window_right, softcap, kv_append_len, has_sinks, key_lo = 0, tq = False, bsz = 1, device = None):"""Kernel config for a call, or None when the Triton kernels must run it. key_lo: KVWIN, positions below it are not attended- bsz: sequences in the call; it only feeds the EXL3_QDEC_HIP_SMM default (auto: on for one sequence, see below)"""- if (not ENABLED or window_left >= 0 or window_right >= 0 or softcap or kv_append_len != q_len+ bsz: sequences in the call; it only feeds the EXL3_QDEC_HIP_SMM default (auto: on for one sequence, see below)+ device: the tensor's device; the gfx11.5 gate is per device, not per process"""+ if (not ENABLED or not _gfx115_family(device) or window_left >= 0 or window_right >= 0 or softcap or kv_append_len != q_lenor not (2 <= k_bits <= 8) or not (2 <= v_bits <= 8)):return Noneif head_dim not in (128, 256) or n_q_heads % n_kv_heads != 0 or page_size % 16 != 0:diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.pyindex 4635076..ffe2513 100644--- a/exllamav3/modules/attention_fn/triton_paged.py+++ b/exllamav3/modules/attention_fn/triton_paged.py@@ -1264,13 +1264,13 @@ def _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, sosinks, has_sinks = _prep_sinks(sinks, n_q_heads, q)cfg = _qh.make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, qck, qcv, k_cache.shape[1], causal, softmax_scale,window_left, window_right, softcap, kv_append_len, has_sinks, ring.cfg.S if ring is not None else 0, tq is not None,- bsz = bsz)+ bsz = bsz, device = q.device)if cfg is None:# A verify step with more rows than one pass of the kernel holds (accumulator budget: 4 tokens at GQA 12, hd 256) runs as# row chunks, each one a smaller verify at the shifted position: the Triton split kernels cost 15-20x more at 128Kif q_len > 1 and kv_append_len == q_len:n = next((n for n in range(q_len - 1, 0, -1) if _qh.make_cfg(n, n_q_heads, n_kv_heads, head_dim, qck, qcv, k_cache.shape[1], causal, softmax_scale,- window_left, window_right, softcap, n, has_sinks, ring.cfg.S if ring is not None else 0, tq is not None) is not None), 0)+ window_left, window_right, softcap, n, has_sinks, ring.cfg.S if ring is not None else 0, tq is not None, device = q.device) is not None), 0)if n:if _QDEC_HIP_DEBUG: _qdec_hip_note(("hip-chunks", f"q_len {q_len} in {n}"))if out is None:@@ -1356,7 +1356,7 @@ def paged_attn_triton_decode(_k = (tuple(q.shape), tuple(k_cache.shape), str(window_size), qc is not None, split_batch)if _k not in _ATTN16_SEEN:_ATTN16_SEEN.add(_k); print(" -- attn16 eager decode", _k, "new" if ATTN16 and (qc is not None or _normalize_window(window_size)[0] >= 0) else "old", flush = True)- if qc is not None and _QDEC_HIP and k is None:+ if qc is not None and _QDEC_HIP and k is None and _qh._gfx115_family(q.device):out_hip = _qdec_hip_decode(q, k_cache, v_cache, block_table, cache_seqlens, causal, softmax_scale, window_size, softcap,sinks, out, num_splits, max_kv_len, qc, pre_appended_len, n_kv_heads_override, ring, tq)if out_hip is not None:diff --git a/exllamav3/modules/hyperconnections.py b/exllamav3/modules/hyperconnections.pyindex 4291568..ae55109 100644--- a/exllamav3/modules/hyperconnections.py+++ b/exllamav3/modules/hyperconnections.py@@ -500,19 +500,25 @@ def _gr_hip():return _gr_hip_mod[0]-def _wmma_family0() -> int:- """WMMA family of device 0: 0 none, 1 gfx12 (RDNA4), 2 gfx11.5 (RDNA3.5).+def _wmma_family(device=None) -> int:+ """WMMA family of the module device: 0 none, 1 gfx12 (RDNA4), 2 gfx11.5 (RDNA3.5).gr_mix.hip is a gfx11.5-only hand kernel (different builtin and fragment layout from- gfx12) and its JIT compiles for device 0, so it must not be selected when device 0 is a- gfx1201 part -- the PyTorch/reference gr path stays. Mirrors exl3_gemv_wmma_family, with an- arch-name fallback for builds that predate the probe."""+ gfx12) and its JIT compiles for the module's device, so it must not be selected on a+ gfx1201 part. Mirrors exl3_gemv_wmma_family, with an arch-name fallback for builds that+ predate the probe."""+ if device is None:+ idx = torch.cuda.current_device()+ elif isinstance(device, torch.device):+ idx = device.index if device.index is not None else torch.cuda.current_device()+ else:+ idx = int(device)try:- return ext.exl3_gemv_wmma_family(0)+ return ext.exl3_gemv_wmma_family(idx)except Exception: # noqa: BLE001passtry:- arch = torch.cuda.get_device_properties(0).gcnArchName.split(":")[0]+ arch = torch.cuda.get_device_properties(idx).gcnArchName.split(":")[0]if arch in ("gfx1200", "gfx1201"):return 1if arch in ("gfx1150", "gfx1151", "gfx1152"):@@ -752,7 +758,7 @@ class GatedResidual(Module):if self.use_combine else Nonefuse = _GR_PF_FUSE and dev.type == "cuda" and torch.version.hip is not Nonegr_hip_ok = (R > 32 and os.environ.get("EXL3_GR_HIP", "0") == "1" and fuse and self.use_combine and H == 4- and _wmma_family0() == 2+ and _wmma_family(dev) == 2and tuple(self.proj_h.shape) == (324, 10240) and tuple(self.up_h.shape) == (10240, 320)and self.proj_h.dtype == torch.half and self.up_h.dtype == torch.halfand self.proj_h.is_contiguous() and self.up_h.is_contiguous())