From 4fe4ba532ed9fe1873af54c8638f46511f5f61bf Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Sun, 6 Dec 2026 03:47:12 +0100 Subject: [PATCH 1/4] hip: the dense int8 prefill GEMM runs on the 8-bit WMMA Qwen4-35B-A3B Q4_K_XL prefill +3.5% at pp4096 and Bonsai 2 9B Q2_0 +16.3% at pp4096 against the f16 GEMM, decode unchanged (leo A/B, noise under 1%). The dp4a body this branch started with measured slower than f16 on both and is gone. The int8 path is gated on wmma_gemm(), so only gfx11/gfx12 compile it. --- src/cuda/kernels.cu | 118 ++++++++++++++++++++++++++++++++++++++------ src/cuda/mod.rs | 11 ++--- src/hip/compat.h | 39 +++++++++++++++ src/hip/mod.rs | 71 +++++++++++++++++++++----- tests/kernels.rs | 39 +++++++++++++++ 5 files changed, 244 insertions(+), 34 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 64454c0e..510305ba 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -1714,14 +1714,30 @@ template __device__ __forceinline__ void cp_async_wait() { } #endif -// sm_80+ int8 tensor-core path, and TU116/TU117 (MMA_FMA) native __dp4a path. +// sm_80+ int8 tensor-core path, and TU116/TU117 (MMA_FMA) native __dp4a path, and RDNA3/4 (gfx11/gfx12) int8 WMMA. // SM: as in gemm_q (gemmis_*, the tiles of at most 32 positions, 16 x 16 outputs per warp). -#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 || MMA_FMA +// HIP has neither mma.sync nor CUDA's int8 tensor cores: it takes the __dp4a body or, where compat.h has the 8-bit +// WMMA intrinsic, the GEMMI_WMMA body. Both keep the selection inside this family: a global `#define MMA_FMA 1` would +// also flip the f16 prefill attention's CUDA-core branch, whose guards exclude STRATA_HIP but whose comment then lies +// about why. +#if STRATA_HIP +#define GEMMI_DP4A 1 +#else +#define GEMMI_DP4A MMA_FMA +#endif +// The 8-bit WMMA (compat.h): ~3 cycles a 16x16x16 tile against the f16 form's 16, but it accumulates int32, so a +// weight scale needs its own fold. It runs where the card has the intrinsic and STRATA_HIP_WMMA is on. +#if STRATA_HIP && STRATA_WMMA && GEMM_WMMA +#define GEMMI_WMMA 1 +#else +#define GEMMI_WMMA 0 +#endif +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 || GEMMI_DP4A template __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int nd, const u8* __restrict__ x, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { constexpr int P = 80, XM = SM ? 32 : BM; // smem pitch in bytes: 64 int8 + padding (conflict-free fragments, 16-byte aligned rows) -#if MMA_FMA +#if GEMMI_DP4A || GEMMI_WMMA constexpr int NB = 1; #else constexpr int NB = 2; @@ -1739,7 +1755,7 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int bool xok = xr_ < tl.cnt; const u8* xp = x + (size_t)(xok ? (xrow ? xrow[tl.m0 + xr_] : tl.m0 + xr_) : 0) * Q8_ROW(cols); auto ldx = [&](int kb) { -#if MMA_FMA +#if GEMMI_DP4A || GEMMI_WMMA int b = 0; #else int b = kb & 1; @@ -1756,6 +1772,13 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int const u8* wp = n0 + wr_ < rows ? tl.w + (size_t)(n0 + wr_) * ROWB(cols, SBB) : nullptr; const bool v16 = ((size_t)tl.w & 15) == 0 && ROWB(cols, SBB) % 16 == 0; // QI::get2's 16-byte loads float acc[2][4][4] = {}; +#if GEMMI_WMMA + // The WMMA path's own f32 accumulator, a float2 per slot as the 8-bit intrinsic's output: accw[t * NTW + nt][i] + // is position STRATA_WMMA_ROW(lane, i) of tile t, weight row wn + nt * 16 + (lane & 15) — the layout the tail of + // this function stores. It is separate from `acc` because a sum of int32 (the WMMA's D) is folded here with the + // activation and weight scales, while `acc` keeps the dp4a and tensor-core paths' per-lane shape untouched. + float accw[4][8] = {}; +#endif const int nk = n64; // W step kb is decoded into registers during step kb - 1's mma and stored after it. int lo0, hi0, lo1, hi1; float wd0, wm0; @@ -1780,19 +1803,21 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int ldw(0); stw(); for (int kb = 0; kb < nk; kb++) { -#if !MMA_FMA +#if !GEMMI_DP4A && !GEMMI_WMMA if (kb + 1 < nk) ldx(kb + 1); if (kb + 1 < nk) cp_async_wait<1>(); else cp_async_wait<0>(); #endif __syncthreads(); if (kb + 1 < nk) ldw(kb + 1); -#if MMA_FMA +#if GEMMI_DP4A || GEMMI_WMMA const int b = 0; #else const int b = kb & 1; #endif constexpr int KS = scale32() ? 32 : 16; // depth of one mma (one weight scale) constexpr int MT = SM ? 1 : 2, NT8 = SM ? 2 : 4; + // The three bodies below fold the same int32 sums into acc[mt][nt][i]; GEMMI_WMMA writes the 8-bit WMMA's + // slots directly (i2f_small) and leaves the per-i scale to the store, since a lane's 8 slots share one X row. // X scales and sums of the step for this thread's rows (g, g + 8 of each mt), one vector load each. float2 xdv[2][2]; float4 xsv[2][2]; #pragma unroll @@ -1803,7 +1828,7 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int xdv[mt][i] = *(const float2*)xd[b][r]; if (QI::MIN) xsv[mt][i] = *(const float4*)xsum[b][r]; } -#if MMA_FMA +#if GEMMI_DP4A && !GEMMI_WMMA #pragma unroll for (int h = 0; h < 64 / KS; h++) if (wm < tl.cnt) { float da[2][2], sa[2][2], dbv[4][2], mb[4][2]; @@ -1866,6 +1891,44 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int } __syncthreads(); if (kb + 1 < nk) { ldx(kb + 1); stw(); } +#elif GEMMI_WMMA + // One int8 WMMA per 16 columns, its int32 sum folded into the f32 accumulator with this position's activation + // scale and the 16-group's weight scale d (and min m). A lane's 8 slots are 8 positions of one weight row: + // accw[mt * NTW + nt][i] is position STRATA_WMMA_ROW(lane, i) of tile mt, weight row wn + nt * 16 + (lane & 15). + constexpr int NTW = SM ? 1 : 2; + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); + #pragma unroll + for (int h = 0; h < 64 / KS; h++) if (wm < tl.cnt) { + #pragma unroll + for (int s = 0; s < KS / 16; s++) { + const int kk = h * KS + s * 16, gi = kk / 16; + strata_hip::strata_i8 sum[2][NTW]; + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int nt = 0; nt < NTW; nt++) { + strata_hip::strata_ik a = strata_hip::strata_ld_wmma_i8(&xq[0][(wm + mt * 16 + l16) * P + kk + w0]); + strata_hip::strata_ik bw = strata_hip::strata_ld_wmma_i8(&wq[(wn + nt * 16 + l16) * P + kk + w0]); + sum[mt][nt] = strata_hip::strata_wmma_i8(a, bw, strata_hip::strata_i8_zero()); + } + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int nt = 0; nt < NTW; nt++) { + const float2 dm = *(const float2*)&wdm[gi][wn + nt * 16 + l16]; + #pragma unroll + for (int i = 0; i < 8; i++) { + const int r = wm + mt * 16 + STRATA_WMMA_ROW(lane, i); + const float2 xs = *(const float2*)&xd[0][r]; + float f = (float)sum[mt][nt][i] * ((kk / 32 ? xs.y : xs.x) * dm.x); + if (QI::MIN) f -= ((const float*)&xsum[0][r])[gi] * dm.y; + accw[mt * NTW + nt][i] += f; + } + } + } + } + __syncthreads(); + if (kb + 1 < nk) { ldx(kb + 1); stw(); } #else #pragma unroll for (int h = 0; h < 64 / KS; h++) if (wm < tl.cnt) { @@ -1912,6 +1975,30 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int if (kb + 1 < nk) stw(); #endif } +#if GEMMI_WMMA + // [mt][nt] slot i is weight row n0 + wn + nt * 16 + (lane & 15) of position wm + mt * 16 + + // STRATA_WMMA_ROW(lane, i); the two differently-shaped tiles (SM's 32 x 32, the big one's 64 x 64) fall out of + // (NTW, MT) alone. + { + constexpr int NTW = SM ? 1 : 2, MTT = SM ? 1 : 2; + const int l16 = lane & 15; + #pragma unroll + for (int mt = 0; mt < MTT; mt++) + #pragma unroll + for (int nt = 0; nt < NTW; nt++) { + int n = n0 + wn + nt * 16 + l16; + if (n >= rows) continue; + #pragma unroll + for (int i = 0; i < 8; i++) { + int r = wm + mt * 16 + STRATA_WMMA_ROW(lane, i); + if (r >= tl.cnt) continue; + float* yr = y + (size_t)(tl.m0 + r) * y_stride; + float v = (float)accw[mt * NTW + nt][i] * sc; + yr[n] = act == 0 ? v : act == 1 ? silu(yr[n]) * v : yr[n] + v; + } + } + } +#else #pragma unroll for (int mt = 0; mt < (SM ? 1 : 2); mt++) #pragma unroll @@ -1928,6 +2015,7 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int yr[n + e] = act == 0 ? v : act == 1 ? silu(yr[n + e]) * v : yr[n + e] + v; } } +#endif } // gemmi_q in steps of S (64-deep K steps per barrier), taken only by gemmis_q6_k on sm_80+. Its loop shape makes ptxas @@ -1939,7 +2027,7 @@ template __device__ __forceinline__ void gemmi_qs(const GemmTile* tiles, const u8* wd, int nd, const u8* __restrict__ x, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { constexpr int P = 64 * S + 16, XM = SM ? 32 : BM; // smem pitch in bytes: S * 64 int8 + padding (conflict-free fragments, 16-byte aligned rows) -#if MMA_FMA +#if GEMMI_DP4A constexpr int NB = 1; static_assert(S == 1, "the dp4a path steps 64 deep"); #else @@ -1960,7 +2048,7 @@ __device__ __forceinline__ void gemmi_qs(const GemmTile* tiles, const u8* wd, in bool xok = xr_ < tl.cnt; const u8* xp = x + (size_t)(xok ? (xrow ? xrow[tl.m0 + xr_] : tl.m0 + xr_) : 0) * Q8_ROW(cols); auto ldx = [&](int kb) { -#if MMA_FMA +#if GEMMI_DP4A int b = 0; #else int b = (kb / S) & 1; @@ -2010,13 +2098,13 @@ __device__ __forceinline__ void gemmi_qs(const GemmTile* tiles, const u8* wd, in ldw(0); stw(); for (int kb = 0; kb < nk; kb += S) { -#if !MMA_FMA +#if !GEMMI_DP4A if (kb + S < nk) ldx(kb + S); if (kb + S < nk) cp_async_wait<1>(); else cp_async_wait<0>(); #endif __syncthreads(); if (kb + S < nk) ldw(kb + S); -#if MMA_FMA +#if GEMMI_DP4A const int b = 0; #else const int b = (kb / S) & 1; @@ -2035,7 +2123,7 @@ __device__ __forceinline__ void gemmi_qs(const GemmTile* tiles, const u8* wd, in xdv[mt][i] = *(const float2*)&xd[b][r][2 * s]; if (QI::MIN) xsv[mt][i] = *(const float4*)&xsum[b][r][4 * s]; } -#if MMA_FMA +#if GEMMI_DP4A #pragma unroll for (int h = 0; h < 64 / KS; h++) if (wm < tl.cnt) { float da[2][2], sa[2][2], dbv[4][2], mb[4][2]; @@ -2142,7 +2230,7 @@ __device__ __forceinline__ void gemmi_qs(const GemmTile* tiles, const u8* wd, in #endif } __syncthreads(); -#if MMA_FMA +#if GEMMI_DP4A if (kb + 1 < nk) { ldx(kb + 1); stw(); } #else if (kb + S < nk) stw(); @@ -2166,8 +2254,10 @@ __device__ __forceinline__ void gemmi_qs(const GemmTile* tiles, const u8* wd, in } } -#if MMA_FMA +#if GEMMI_DP4A #define GEMMIS_S 0 +#elif GEMMI_WMMA +#define GEMMIS_S 0 // gemmi_qs has no int8 WMMA body yet #else #define GEMMIS_S 1 // gemmis_q6_k takes gemmi_qs (not measured on the dp4a path) #endif diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 989c3f11..65990a78 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -572,12 +572,9 @@ fn smem_log(family: &str, optin: usize, stat: usize, set: Option, carveou /// The kernel names to load from the cubin: the full list on sm_80+, without the int8 GEMM (`gemmi_*`, `gemmis_*` and /// `gemmd_*`, 23 non-float types x 3 fewer names) on a device where that code is not compiled in. Pure so a CPU test can pin -/// both lists (394 / 325 names). -pub(crate) fn kernel_names(sm80: bool) -> Vec { - kernel_names_with(sm80, false) -} - -fn kernel_names_with(sm80: bool, dp4a: bool) -> Vec { +/// both lists (394 / 325 names). `dp4a` adds the `gemmi_*`/`gemmis_*` names without `gemmd_*` (the TU11x and HIP +/// backends, which run the int8 GEMM on the integer dot rather than tensor cores). +pub(crate) fn kernel_names_with(sm80: bool, dp4a: bool) -> Vec { let int8_i = move |&&t: &&GgmlType| (sm80 || dp4a) && !t.float_x(); let int8_d = move |&&t: &&GgmlType| sm80 && !t.float_x(); KERNELS.iter().map(|s| s.to_string()) @@ -2414,7 +2411,7 @@ mod tests { /// them out. 469 names today (sm_80), 397 on sm_70. #[test] fn kernel_names() { - let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); + let (sm70, sm80) = (super::kernel_names_with(false, false), super::kernel_names_with(true, false)); assert_eq!(sm80.len(), 470); assert_eq!(sm70.len(), 398); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")), diff --git a/src/hip/compat.h b/src/hip/compat.h index 157fc9f7..2a6a5e66 100644 --- a/src/hip/compat.h +++ b/src/hip/compat.h @@ -156,6 +156,45 @@ __device__ __forceinline__ strata_hk strata_ld_wmma_t(const unsigned short* p, i for (int i = 0; i < STRATA_WMMA_K; i++) r[i] = *(const _Float16*)(p + i * stride); return r; } + +// ---- int8 matrix cores: D[16x16] += A[16x16] * B^T[16x16], int8 operands, int32 accumulator ---- +// The fragment map is the f16 one above, at a byte a value: a lane's operand is STRATA_WMMA_K int8 of its own row at +// its half-wave's k offset (gfx12: row lane & 15, k 8 * (lane >> 4); gfx11: the whole 16 bytes of row lane & 15, +// lanes 16-31 repeating 0-15). The B side takes a [n][k] tile (the prefill GEMM's weight staging), which is the same +// addressing. D: slot i is column lane & 15 and row STRATA_WMMA_ROW(lane, i), as for f16. The mapping is undocumented +// by AMD (ROCm issue #6025); the evidence is radiance's libr4d/r4d_fp8_wmma.h, which measured it on gfx1201, and +// llama.cpp's mma.cuh for gfx11. +typedef int strata_ik __attribute__((ext_vector_type(STRATA_WMMA_K / 4))); +typedef int strata_i8 __attribute__((ext_vector_type(8))); + +__device__ __forceinline__ strata_ik strata_ld_wmma_i8(const signed char* p) { + union { strata_ik v; int d[STRATA_WMMA_K / 4]; } c; +#if STRATA_WMMA_K == 8 + const uint2 u = *(const uint2*)p; + c.d[0] = (int)u.x; c.d[1] = (int)u.y; +#else + const uint4 u = *(const uint4*)p; + c.d[0] = (int)u.x; c.d[1] = (int)u.y; c.d[2] = (int)u.z; c.d[3] = (int)u.w; +#endif + return c.v; +} + +/// `neg_a`/`neg_b` are set so both operands are signed (the 8-bit WMMA has no sign in its encoding otherwise); the +/// int32 accumulator fits this GEMM's 64-deep K step (64 * 127 * 127 = 2^20) with no clamping. +__device__ __forceinline__ strata_i8 strata_wmma_i8(strata_ik a, strata_ik b, strata_i8 c) { +#if defined(__gfx1200__) || defined(__gfx1201__) + return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, true, b, c, false); +#else + return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, false); +#endif +} + +__device__ __forceinline__ strata_i8 strata_i8_zero() { + strata_i8 z; +#pragma unroll + for (int i = 0; i < 8; i++) z[i] = 0; + return z; +} #endif } // namespace strata_hip diff --git a/src/hip/mod.rs b/src/hip/mod.rs index cfa7119b..42f4d632 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -80,6 +80,9 @@ pub struct Gpu { /// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next /// region while the card reads the previous one (expert streaming in prefill). staging: Mutex, + /// q8 rows of the last integer GEMM's X (see quant_q8 in kernels.cu), grown on demand, and which x they hold + /// (x, x_stride, n_x, cols) for a `SAME_X` call; None when they hold nothing. + q8: Mutex<(Buf, Option<[u64; 4]>)>, } // The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` @@ -251,8 +254,10 @@ impl Gpu { let sms = hip.attribute(ffi::ATTR_MULTIPROCESSOR_COUNT, device as i32).unwrap_or(16).max(1) as usize; let wm = hip_wmma && wmma_arch(&arch); let (mla_wmma, idx_wmma) = (wm && std::env::var_os("STRATA_MLA_SIMT").is_none(), wm && std::env::var("STRATA_IDX_WMMA").is_ok_and(|v| v == "1")); + let q8 = alloc_raw(&hip, 1)?; Ok(Gpu { hip, device, stream, side, marks, next_mark: Default::default(), pinned: Default::default(), beside: Default::default(), beside_lag: Default::default(), fns, arch, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags: ink_flags(), pci, max_smem, sms, mla_wmma, idx_wmma, am: am_buf, - graphs: Mutex::new(HashMap::new()), graph_failed: Default::default(), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) + graphs: Mutex::new(HashMap::new()), graph_failed: Default::default(), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging), + q8: Mutex::new((q8, None)) }) } pub fn arch(&self) -> &str { &self.arch } @@ -376,6 +381,12 @@ impl Gpu { } /// Whether the stream is capturing a graph: no allocation and no synchronous copy may be issued inside one. + /// Whether `kernels.cu` compiles its int8 WMMA branch for this build: `GEMMI_WMMA` is `STRATA_HIP && STRATA_WMMA && + /// GEMM_WMMA`, i.e. a gfx11/gfx12 card with `STRATA_HIP_WMMA` (the same switch as the f16 WMMA GEMM). + fn wmma_gemm(&self) -> bool { + wmma_arch(&self.arch) && std::env::var("STRATA_HIP_WMMA").map(|v| v != "0").unwrap_or(true) + } + fn capturing(&self) -> bool { let mut status = 0; unsafe { (self.hip.stream_is_capturing)(self.stream, &mut status) }; @@ -439,28 +450,58 @@ impl Gpu { Ok(()) } - /// Prefill GEMM over a tile list (or one dense matrix when `tiles` is 0). Without int8 tensor cores the f16 - /// `gemm_*`/`gemms_*` kernels run; `gemm_tc` is compiled out of this build (`GEMM_TC 0`). + /// Prefill GEMM over a tile list (or one dense matrix when `tiles` is 0). A dense GEMM of an integer type with + /// `cols % 128 == 0` on an int8-WMMA target takes the int8 path (`quant_q8` + `gemmi_*`/`gemmis_*`); everything + /// else runs the f16 `gemm_*`/`gemms_*` kernels (`gemm_tc` is compiled out of this build, `GEMM_TC 0`). fn gemm_raw(&self, ty: GgmlType, rows: usize, cols: usize, tiles: u64, n_tiles: usize, wd: u64, nd: usize, - x: u64, x_stride: usize, _n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32, w_scale: f32) -> anyhow::Result<()> { + x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32, w_scale: f32) -> anyhow::Result<()> { if cols % 64 != 0 { bail!("{} matrix with {cols} columns: GEMM needs a multiple of 64", ty.name()); } if n_tiles == 0 { return Ok(()) } // Only the activation reaches the kernel: SAME_X and BATCHED (the same kernels here) are flags for the host. let (same, act) = (act & SAME_X != 0, act & 3); - let _ = same; let grid = (rows.div_ceil(64) as u32, n_tiles as u32); let sm = tiles == 0 && (grid.0 * grid.1 < 112 || nd <= 32); let grid = if sm { (grid.0, nd.div_ceil(32) as u32) } else { grid }; - launch!(self, &kname(if sm { "gemms" } else { "gemm" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), - tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); - // Tile lists: gemm_* skips the tiles of at most 32 positions, which gemms_* takes. - if tiles != 0 { - launch!(self, &kname("gemms", ty), cfg(grid, 2 * GEMM_BM as u32, 0), + // q8 rows are loaded 16 bytes at a time, aligned only for a multiple of 128 columns (Q8_ROW's stride). The + // scratch grows with hipMalloc, which a capture forbids: a graph that needs a bigger one keeps the f16 kernel. + let mut q8 = self.q8.lock().unwrap(); + let key = Some([x, x_stride as u64, n_x as u64, cols as u64]); + let reuse = same && q8.1 == key; + let grow = !reuse && q8.0.len() < n_x * (cols + cols / 8 + cols / 4); + let int8 = tiles == 0 && self.wmma_gemm() && crate::cuda::Gpu::mmq(ty) && cols.is_multiple_of(128) && !(grow && self.capturing()); + if !int8 { + if !same { q8.1 = None; } + launch!(self, &kname(if sm { "gemms" } else { "gemm" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); + // Tile lists: gemm_* skips the tiles of at most 32 positions, which gemms_* takes. + if tiles != 0 { + launch!(self, &kname("gemms", ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, x, x_stride as i32, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); + } + return Ok(()); } + // Only SAME_X promises that x still holds what was quantized: the same address can hold new rows. + if !same { q8.1 = None; } + let xq = self.q8_x(&mut q8, ty, cols, n_x, x, x_stride)?.expect("int8 GEMM without a quantized x"); + launch!(self, &kname(if sm { "gemmis" } else { "gemmi" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, xq, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); Ok(()) } + /// Quantize `x` for the int8 GEMM, unless the cache already holds the same rows; `None` when `ty` or `cols` + /// selects the f16 path. Mirrors CUDA's `Gpu::q8_x`. + fn q8_x(&self, q8: &mut (Buf, Option<[u64; 4]>), ty: GgmlType, cols: usize, n_x: usize, x: u64, x_stride: usize) -> anyhow::Result> { + if !crate::cuda::Gpu::mmq(ty) || !cols.is_multiple_of(128) { return Ok(None); } + let key = Some([x, x_stride as u64, n_x as u64, cols as u64]); + if q8.1 == key { return Ok(Some(self.ptr(&q8.0))); } + let need = n_x * (cols + cols / 8 + cols / 4); + if q8.0.len() < need { q8.0 = alloc_raw(&self.hip, need)?; } + let xq = self.ptr(&q8.0); + launch!(self, "quant_q8", cfg((n_x as u32, 1), 256, 0), x, x_stride as i32, xq, cols as i32); + q8.1 = key; + Ok(Some(xq)) + } + /// Decode attention: `attn_decode_gq` plus `attn_merge`, which also writes `out` quantized into xq. fn attn(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, part: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, gq_min: i32, nt: usize, xq: u64, sel: u64, sst: usize, sink: u64, win: usize, kvt: u64, ns1: usize) -> anyhow::Result<()> { @@ -626,10 +667,11 @@ fn drm_free(total: usize, bus: Option<&str>) -> Option { free_where(&at_bus).or_else(|| free_where(&|_, t: usize| t.abs_diff(total) <= 256 << 20)) } -/// The kernel names to load: `cuda::kernel_names(false)` has no int8-mma GEMM, which needs no separate list here, +/// The kernel names to load: `cuda::kernel_names_with(false, true)` has the int8 GEMM (`gemmi_*`/`gemmis_*`), which +/// this backend runs on the RDNA int8 dot (compat.h's `dp4a`) and load as the TU11x dp4a path does (no `gemmd_*`), /// plus the kernels `kernels.cu` compiles only under `STRATA_HIP`. fn kernel_names() -> Vec { - let mut v = crate::cuda::kernel_names(false); + let mut v = crate::cuda::kernel_names_with(false, true); v.extend(["mla_attn_wmma", "idx_score_wmma", "mla_qpack"].map(String::from)); v } @@ -833,7 +875,10 @@ impl Backend for Gpu { self.gemm_raw(w.ty, w.rows, w.cols, 0, n.div_ceil(GEMM_BM), w.ptr, n, x, x_stride, n, 0, y, y_stride, act, w.scale) } - fn int8_gemm(&self, _ty: GgmlType) -> bool { false } + /// Whether the dense int8 prefill GEMM (quant_q8 + gemmi_*/gemmis_*) runs for `ty`: the type policy, and only on a + /// target where `kernels.cu` compiles the int8 WMMA branch (`GEMMI_WMMA`: gfx11/gfx12 with `STRATA_HIP_WMMA` on). + /// The column gate (cols % 128) is per call, in `gemm_raw`. + fn int8_gemm(&self, ty: GgmlType) -> bool { self.wmma_gemm() && crate::cuda::Gpu::mmq(ty) } /// No int8 GEMM here (see `int8_gemm`), so the prefill GEMM is f16 and its inputs are f16. The trait default is /// CUDA's type policy alone, which would tell the tests to build their reference from int8 `x` (Q2_0 at 640 diff --git a/tests/kernels.rs b/tests/kernels.rs index 1245d25d..14ff1e80 100644 --- a/tests/kernels.rs +++ b/tests/kernels.rs @@ -1749,6 +1749,45 @@ fn gemv_partial_superblocks_and_q2_0() { } } +/// The dense int8 prefill GEMM (quant_q8 + gemmi_*/gemmis_*, `Backend::int8_gemm` with 128-column tiles) against +/// per-row dot products of `as_seen` x and the dequantized weights. HIP runs it on the RDNA int8 dot (compat.h's +/// `dp4a`), which sums a different integer order than the CUDA tensor-core mma: the reference is the same value +/// (`gemmi_q` scales the same per-16 sums), so this holds on both. +#[test] +fn int8_gemm_dense_matches_reference() { + for (bk, gpu) in common::backends_except(&[]) { + let gpu = &*gpu; + for ty in [GgmlType::Q4K, GgmlType::Q6K, GgmlType::Q8_0, GgmlType::Q2_0] { + if !gpu.int8_gemm(ty) { eprintln!("{bk} {}: f16 path, int8_gemm false", ty.name()); continue; } + for cols in [640, 2560] { + if cols % ty.block_elems() != 0 || cols % 128 != 0 { continue; } + // 42 rows take the sm-sized tile (gemmis_*), 3600 the dense one (gemmi_*: 57 x 2 blocks >= 112); + // 130 positions are a full 128-position tile and a partial one. + for (rows, m) in [(42, 130), (3600, 130)] { + let data = random_tensor(ty, rows, cols, cols as u32 + ty as u32 + 7); + let t = Tensor { ty, cols, rows, data: &data, scale: 1.0 }; + let b = gpu.alloc(t.data.len()).unwrap(); + gpu.htod(t.data, &b, 0).unwrap(); + let dt = GpuTensor::new(t.ty, t.rows, t.cols, b); + let xm = xs(m * cols); + let (dxm, dym) = (up(gpu, &xm), gpu.zeros::(m * rows).unwrap()); + gpu.gemm_dense(&dt, m, dxm.addr(), cols, dym.addr(), rows, 0).unwrap(); + let mut wr = vec![0f32; cols]; + let mut want = vec![0f32; m * rows]; + for r in 0..rows { + t.row(r, &mut wr); + for (i, xv) in xm.chunks(cols).enumerate() { + want[i * rows + r] = wr.iter().zip(as_seen(ty, xv)).map(|(a, b)| a * b).sum(); + } + } + let e = rel_l2(&down::(gpu, &dym), &want); + assert!(e <= 1e-4, "{bk} {} cols {cols} rows {rows}: int8 gemm rel err {e}", ty.name()); + } + } + } + } +} + /// Per-type Vulkan pass/fail matrix over all `GgmlType` variants: dequant, GEMV/GEMV-N/GEMV-Q, MoE GEMV, dense /// and tiled GEMM, plus each type's largest shared-memory request. Synthetic raw blocks bypass `Backend::upload`, so /// native kernels run even for F16, which the loader converts. Vulkan only: run it with From 98387e76f8a7d0cb5b69a5fed3548a5e3c88fc10 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Sun, 6 Dec 2026 06:17:40 +0100 Subject: [PATCH 2/4] hip: the int8 WMMA GEMM folds once per 32-column weight scale A scale32 type's two 16-column WMMA steps chain in int32 (exact, 32 * 127^2 < 2^22) and fold once, halving the per-slot fold, its cvt and its LDS reads. Bonsai 2 9B Q2_0 prefill +21.3% at pp512 and +26.7% at pp4096 over f16, Qwen4-35B-A3B +4.7% at pp4096 (leo A/B, same binary, STRATA_MMQ= for f16). gemmi_q4_k 209 VGPR / 7 waves -> 135 / 10. --- src/cuda/kernels.cu | 44 +++++++++++++++++++++++++++++++++++++------- tests/kernels.rs | 6 +++--- 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 510305ba..8d029700 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -1736,7 +1736,11 @@ template __device__ __forceinline__ void cp_async_wait() { template __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int nd, const u8* __restrict__ x, const int* xrow, float* y, int y_stride, int rows, int n64, int act, float sc) { - constexpr int P = 80, XM = SM ? 32 : BM; // smem pitch in bytes: 64 int8 + padding (conflict-free fragments, 16-byte aligned rows) + // smem pitch in bytes: 64 int8 + 16 of padding, which keeps rows 16-byte aligned for the vector copies. The + // pitch is not bank-conflict free (80 / 4 = 20 words, period 8, so rows r and r + 8 collide); a 72-byte pitch + // would separate all sixteen rows, but this body is fold-bound rather than fragment-read-bound, and the CUDA + // tensor-core branch shares the layout. + constexpr int P = 80, XM = SM ? 32 : BM; #if GEMMI_DP4A || GEMMI_WMMA constexpr int NB = 1; #else @@ -1899,29 +1903,55 @@ __device__ __forceinline__ void gemmi_q(const GemmTile* tiles, const u8* wd, int const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); #pragma unroll for (int h = 0; h < 64 / KS; h++) if (wm < tl.cnt) { + strata_hip::strata_i8 sum[2][NTW]; #pragma unroll for (int s = 0; s < KS / 16; s++) { - const int kk = h * KS + s * 16, gi = kk / 16; - strata_hip::strata_i8 sum[2][NTW]; + const int kk = h * KS + s * 16; #pragma unroll for (int mt = 0; mt < MT; mt++) #pragma unroll for (int nt = 0; nt < NTW; nt++) { strata_hip::strata_ik a = strata_hip::strata_ld_wmma_i8(&xq[0][(wm + mt * 16 + l16) * P + kk + w0]); strata_hip::strata_ik bw = strata_hip::strata_ld_wmma_i8(&wq[(wn + nt * 16 + l16) * P + kk + w0]); - sum[mt][nt] = strata_hip::strata_wmma_i8(a, bw, strata_hip::strata_i8_zero()); + // A 32-column weight scale chains its two 16-column steps in int32: exact (32 * 127^2 < 2^22) + // and one fold instead of two. A 16-column scale folds inside the s step instead. + sum[mt][nt] = strata_hip::strata_wmma_i8(a, bw, s == 0 ? strata_hip::strata_i8_zero() : sum[mt][nt]); } + if constexpr (KS == 16) { + #pragma unroll + for (int mt = 0; mt < MT; mt++) + #pragma unroll + for (int nt = 0; nt < NTW; nt++) { + const float2 dm = *(const float2*)&wdm[h][wn + nt * 16 + l16]; + #pragma unroll + for (int i = 0; i < 8; i++) { + const int r = wm + mt * 16 + STRATA_WMMA_ROW(lane, i); + const float2 xs = *(const float2*)&xd[0][r]; + float f = (float)sum[mt][nt][i] * ((kk % 64 >= 32 ? xs.y : xs.x) * dm.x); + if (QI::MIN) f -= ((const float*)&xsum[0][r])[h] * dm.y; + accw[mt * NTW + nt][i] += f; + } + } + } + } + if constexpr (KS == 32) { + // The group's scale is one pair (wdm[h] for both halves: QI::get indexes d/m by e / 32) and the + // min term needs the two per-16 X sums of the 32 columns, side by side. #pragma unroll for (int mt = 0; mt < MT; mt++) #pragma unroll for (int nt = 0; nt < NTW; nt++) { - const float2 dm = *(const float2*)&wdm[gi][wn + nt * 16 + l16]; + // wdm is indexed by 16 columns, the scale is one per 32: entry 2h holds both halves' d and m. + const float2 dm = *(const float2*)&wdm[2 * h][wn + nt * 16 + l16]; #pragma unroll for (int i = 0; i < 8; i++) { const int r = wm + mt * 16 + STRATA_WMMA_ROW(lane, i); const float2 xs = *(const float2*)&xd[0][r]; - float f = (float)sum[mt][nt][i] * ((kk / 32 ? xs.y : xs.x) * dm.x); - if (QI::MIN) f -= ((const float*)&xsum[0][r])[gi] * dm.y; + float f = (float)sum[mt][nt][i] * ((h & 1 ? xs.y : xs.x) * dm.x); + if (QI::MIN) { + const float* xsv = (const float*)&xsum[0][r]; + f -= (xsv[2 * h] + xsv[2 * h + 1]) * dm.y; + } accw[mt * NTW + nt][i] += f; } } diff --git a/tests/kernels.rs b/tests/kernels.rs index 14ff1e80..dda29c6e 100644 --- a/tests/kernels.rs +++ b/tests/kernels.rs @@ -1750,9 +1750,9 @@ fn gemv_partial_superblocks_and_q2_0() { } /// The dense int8 prefill GEMM (quant_q8 + gemmi_*/gemmis_*, `Backend::int8_gemm` with 128-column tiles) against -/// per-row dot products of `as_seen` x and the dequantized weights. HIP runs it on the RDNA int8 dot (compat.h's -/// `dp4a`), which sums a different integer order than the CUDA tensor-core mma: the reference is the same value -/// (`gemmi_q` scales the same per-16 sums), so this holds on both. +/// per-row dot products of `as_seen` x and the dequantized weights. CUDA sums on the int8 tensor-core mma and RDNA +/// on the 8-bit WMMA; both scale the same per-16 sums and a scale32 type chains its two 16-column steps exactly, so +/// the reference is the same value on both. #[test] fn int8_gemm_dense_matches_reference() { for (bk, gpu) in common::backends_except(&[]) { From 663055ee180f98c20925f73e5e3e8524b967ae74 Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Sun, 6 Dec 2026 06:51:38 +0100 Subject: [PATCH 3/4] hip: mmq follows int8_gemm, and tile lists take the int8 GEMM Main's #228 made mmq false while int8_gemm returns true on gfx11/12, so the tests built an f16 reference for a GEMM the launcher ran as int8. Tile lists also fell back to f16, which a test compared against int8 math (Q8_0 read 3.6e-3 off). gemmis_* now serves them as on CUDA: Q8_0 reads 8.2e-7. --- src/hip/mod.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 42f4d632..06259aaf 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -468,7 +468,7 @@ impl Gpu { let key = Some([x, x_stride as u64, n_x as u64, cols as u64]); let reuse = same && q8.1 == key; let grow = !reuse && q8.0.len() < n_x * (cols + cols / 8 + cols / 4); - let int8 = tiles == 0 && self.wmma_gemm() && crate::cuda::Gpu::mmq(ty) && cols.is_multiple_of(128) && !(grow && self.capturing()); + let int8 = self.wmma_gemm() && self.int8_gemm(ty) && cols.is_multiple_of(128) && !(grow && self.capturing()); if !int8 { if !same { q8.1 = None; } launch!(self, &kname(if sm { "gemms" } else { "gemm" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), @@ -485,6 +485,11 @@ impl Gpu { let xq = self.q8_x(&mut q8, ty, cols, n_x, x, x_stride)?.expect("int8 GEMM without a quantized x"); launch!(self, &kname(if sm { "gemmis" } else { "gemmi" }, ty), cfg(grid, 2 * GEMM_BM as u32, 0), tiles, wd, nd as i32, xq, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); + // Tile lists: gemmi_* skips the tiles of at most 32 positions, which gemmis_* takes. + if tiles != 0 { + launch!(self, &kname("gemmis", ty), cfg(grid, 2 * GEMM_BM as u32, 0), + tiles, wd, nd as i32, xq, xrow, y, y_stride as i32, rows as i32, (cols / 64) as i32, act, w_scale); + } Ok(()) } @@ -880,10 +885,10 @@ impl Backend for Gpu { /// The column gate (cols % 128) is per call, in `gemm_raw`. fn int8_gemm(&self, ty: GgmlType) -> bool { self.wmma_gemm() && crate::cuda::Gpu::mmq(ty) } - /// No int8 GEMM here (see `int8_gemm`), so the prefill GEMM is f16 and its inputs are f16. The trait default is - /// CUDA's type policy alone, which would tell the tests to build their reference from int8 `x` (Q2_0 at 640 - /// columns read 0.0043 off that way), and callers that want the type policy use `cuda::Gpu::mmq`. - fn mmq(&self, _ty: GgmlType) -> bool { false } + /// The same question as `int8_gemm`, and they must not disagree: the tests build their reference from this, and + /// a `true` here with `int8_gemm` false made them read a Q2_0 GEMM 0.0043 off the f16 result (#228). The trait + /// default is CUDA's type policy alone, with no device in it. + fn mmq(&self, ty: GgmlType) -> bool { self.int8_gemm(ty) } fn gemv(&self, w: &GpuTensor, x: u64, y: u64) -> anyhow::Result<()> { let (ncols, kn) = Self::gemv_cols("gemv", w.ty, w.cols)?; From 2bf928d8e5e93c5fe6aa9c374291d37e6a0dfcbe Mon Sep 17 00:00:00 2001 From: Hannes Klas Date: Sun, 6 Dec 2026 06:52:20 +0100 Subject: [PATCH 4/4] docs: HIP.md has the int8 WMMA prefill numbers Bonsai 2 9B Q2_0 3295 / 3196 tok/s at pp 512 / 4096 against 2589 / 2338 on the f16 GEMM; Qwen4-35B-A3B 1959 / 1873 at pp 4096 / 16384 against 1839 / 1767. STRATA_HIP_WMMA=0 and STRATA_MMQ are listed. --- docs/HIP.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/HIP.md b/docs/HIP.md index 79dca90a..35ac31e1 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -95,6 +95,21 @@ A 128k prompt costs more VRAM in the KV cache than a 16 GB card has left for exp host memory. A shorter `--ctx` or `--kv q8` gives expert slots back. Token-by-token prefill (`--chunk 0`) does not help. +Prefill GEMM on the int8 matrix cores: a dense integer-weight GEMM with a multiple of 128 columns quantizes the +activations to int8 (`quant_q8`) and runs the 8-bit WMMA, two 16-column steps per 32-column weight scale, folded once. +It beats the f16 GEMM on every card this is checked on. Ternary Bonsai 2 9B Q2_0, prefill 512 / 4096, `--mtp 0`: + +| | pp 512 | pp 4096 | +|---|---|---| +| int8 WMMA | 3295 tok/s | 3196 tok/s | +| f16 GEMM (`STRATA_MMQ=`) | 2589 tok/s | 2338 tok/s | + +Qwen4-35B-A3B UD-Q4_K_XL on the same card: 1959 / 1873 tok/s (pp 4096 / 16384) against 1839 / 1767. Decode is +unchanged (it runs the int8 GEMV-N, not this GEMM), and so are MTP and DFlash. + +`STRATA_MMQ=` (empty) forces the f16 GEMM for every type; `STRATA_MMQ=q4_k,q6_k` names the types that keep it. The +int8 path needs a gfx11/gfx12 card with `STRATA_HIP_WMMA` on, and a multiple of 128 columns. + ## Run GigaChat 4 on a 16 GB card ```bash @@ -243,7 +258,8 @@ Environment variables for tests and tuning. | Variable | What it does | |---|---| -| `STRATA_HIP_WMMA=0` | CUDA cores instead of matrix cores in prefill. Prefill at pp 1024: 737 tok/s, against 1684. | +| `STRATA_HIP_WMMA=0` | CUDA cores instead of matrix cores in prefill, and the f16 GEMM instead of the int8 WMMA. Prefill at pp 1024: 737 tok/s, against 1684. | +| `STRATA_MMQ=types` | The weight types the dense int8 prefill GEMM keeps for. Empty is the f16 GEMM for all. | | `STRATA_HIP_GRAPH=0` | Runs the forward every time. By default it is captured (+5% decode). | | `STRATA_NO_GRAPH=1` | Turns capture off for both GPU backends. | | `STRATA_HIP_SYNC=1` | Waits after every launch, so a hardware exception names its kernel. |